Fix sonar complains
[bgpcep.git] / bgp / topology-provider / src / main / java / org / opendaylight / bgpcep / bgp / topology / provider / LinkstateTopologyBuilder.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.bgpcep.bgp.topology.provider;
9
10 import com.google.common.base.Preconditions;
11 import com.google.common.collect.Collections2;
12 import com.google.common.collect.Lists;
13 import com.google.common.io.BaseEncoding;
14 import java.math.BigDecimal;
15 import java.nio.ByteBuffer;
16 import java.util.ArrayList;
17 import java.util.HashMap;
18 import java.util.HashSet;
19 import java.util.List;
20 import java.util.Map;
21 import java.util.Set;
22 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
23 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
24 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
25 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
26 import org.opendaylight.protocol.bgp.rib.RibReference;
27 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.DomainName;
28 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
29 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpPrefix;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.Ipv4InterfaceIdentifier;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.Ipv6InterfaceIdentifier;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.IsisAreaIdentifier;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.LinkstateAddressFamily;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.LinkstateSubsequentAddressFamily;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.NodeFlagBits;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.NodeIdentifier;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.TopologyIdentifier;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.ObjectType;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.object.type.LinkCase;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.object.type.NodeCase;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.object.type.PrefixCase;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.object.type.link._case.LinkDescriptors;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.path.attribute.LinkStateAttribute;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.path.attribute.link.state.attribute.LinkAttributesCase;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.path.attribute.link.state.attribute.NodeAttributesCase;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.path.attribute.link.state.attribute.PrefixAttributesCase;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.path.attribute.link.state.attribute.link.attributes._case.LinkAttributes;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.path.attribute.link.state.attribute.node.attributes._case.NodeAttributes;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.path.attribute.link.state.attribute.prefix.attributes._case.PrefixAttributes;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.routes.LinkstateRoutes;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.routes.linkstate.routes.LinkstateRoute;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.routes.linkstate.routes.linkstate.route.Attributes1;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.node.identifier.CRouterIdentifier;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.node.identifier.c.router.identifier.IsisNodeCase;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.node.identifier.c.router.identifier.IsisPseudonodeCase;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.node.identifier.c.router.identifier.OspfNodeCase;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.node.identifier.c.router.identifier.OspfPseudonodeCase;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.node.identifier.c.router.identifier.isis.node._case.IsisNode;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.node.identifier.c.router.identifier.isis.pseudonode._case.IsisPseudonode;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.node.identifier.c.router.identifier.ospf.pseudonode._case.OspfPseudonode;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.Attributes;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.Tables;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.network.concepts.rev131125.Bandwidth;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.odl.bgp.topology.types.rev160524.TopologyTypes1;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.odl.bgp.topology.types.rev160524.TopologyTypes1Builder;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.odl.bgp.topology.types.rev160524.bgp.linkstate.topology.type.BgpLinkstateTopologyBuilder;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev150820.SrlgId;
68 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.isis.topology.rev131021.IsoNetId;
69 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.isis.topology.rev131021.IsoPseudonodeId;
70 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.isis.topology.rev131021.IsoSystemId;
71 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.isis.topology.rev131021.isis.link.attributes.IsisLinkAttributesBuilder;
72 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.isis.topology.rev131021.isis.node.attributes.IsisNodeAttributesBuilder;
73 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.isis.topology.rev131021.isis.node.attributes.isis.node.attributes.IsoBuilder;
74 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.ted.rev131021.srlg.attributes.SrlgValues;
75 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.ted.rev131021.srlg.attributes.SrlgValuesBuilder;
76 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.ted.rev131021.ted.link.attributes.SrlgBuilder;
77 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.ted.rev131021.ted.link.attributes.UnreservedBandwidth;
78 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.ted.rev131021.ted.link.attributes.UnreservedBandwidthBuilder;
79 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.ted.rev131021.ted.link.attributes.UnreservedBandwidthKey;
80 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.LinkId;
81 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
82 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId;
83 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TpId;
84 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.link.attributes.DestinationBuilder;
85 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.link.attributes.SourceBuilder;
86 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Link;
87 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.LinkBuilder;
88 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.LinkKey;
89 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
90 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
91 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
92 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.TopologyTypes;
93 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.TopologyTypesBuilder;
94 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPoint;
95 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPointBuilder;
96 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPointKey;
97 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.Link1;
98 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.Link1Builder;
99 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.Node1;
100 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.Node1Builder;
101 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.TerminationPoint1;
102 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.TerminationPoint1Builder;
103 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.igp.link.attributes.IgpLinkAttributesBuilder;
104 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.igp.node.attributes.IgpNodeAttributes;
105 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.igp.node.attributes.IgpNodeAttributesBuilder;
106 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.igp.node.attributes.igp.node.attributes.Prefix;
107 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.igp.node.attributes.igp.node.attributes.PrefixBuilder;
108 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.igp.node.attributes.igp.node.attributes.PrefixKey;
109 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.igp.termination.point.attributes.IgpTerminationPointAttributesBuilder;
110 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.igp.termination.point.attributes.igp.termination.point.attributes.TerminationPointType;
111 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.igp.termination.point.attributes.igp.termination.point.attributes.termination.point.type.IpBuilder;
112 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.igp.termination.point.attributes.igp.termination.point.attributes.termination.point.type.UnnumberedBuilder;
113 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.Prefix1;
114 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.Prefix1Builder;
115 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.ospf.link.attributes.OspfLinkAttributesBuilder;
116 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.ospf.node.attributes.OspfNodeAttributesBuilder;
117 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.ospf.node.attributes.ospf.node.attributes.router.type.AbrBuilder;
118 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.ospf.node.attributes.ospf.node.attributes.router.type.InternalBuilder;
119 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.ospf.node.attributes.ospf.node.attributes.router.type.PseudonodeBuilder;
120 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.ospf.prefix.attributes.OspfPrefixAttributesBuilder;
121 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
122 import org.slf4j.Logger;
123 import org.slf4j.LoggerFactory;
124
125 public class LinkstateTopologyBuilder extends AbstractTopologyBuilder<LinkstateRoute> {
126     public static final TopologyTypes LINKSTATE_TOPOLOGY_TYPE = new TopologyTypesBuilder()
127     .addAugmentation(TopologyTypes1.class,
128             new TopologyTypes1Builder()
129     .setBgpLinkstateTopology(new BgpLinkstateTopologyBuilder().build()).build())
130     .build();
131
132     private static final String UNHANDLED_OBJECT_CLASS = "Unhandled object class {}";
133
134     private static final class TpHolder {
135         private final Set<LinkId> local = new HashSet<>();
136         private final Set<LinkId> remote = new HashSet<>();
137
138         private final TerminationPoint tp;
139
140         private TpHolder(final TerminationPoint tp) {
141             this.tp = Preconditions.checkNotNull(tp);
142         }
143
144         private synchronized void addLink(final LinkId id, final boolean isRemote) {
145             if (isRemote) {
146                 this.remote.add(id);
147             } else {
148                 this.local.add(id);
149             }
150         }
151
152         private synchronized boolean removeLink(final LinkId id, final boolean isRemote) {
153             final boolean removed;
154             if (isRemote) {
155                 removed = this.remote.remove(id);
156             } else {
157                 removed = this.local.remove(id);
158             }
159             if (!removed) {
160                 LOG.warn("Removed non-reference link {} from TP {} isRemote {}", this.tp.getTpId(), id, isRemote);
161             }
162
163             return this.local.isEmpty() && this.remote.isEmpty();
164         }
165
166         private TerminationPoint getTp() {
167             return this.tp;
168         }
169     }
170
171     private final class NodeHolder {
172         private final Map<PrefixKey, Prefix> prefixes = new HashMap<>();
173         private final Map<TpId, TpHolder> tps = new HashMap<>();
174         private boolean advertized = false;
175         private IgpNodeAttributesBuilder inab;
176         private NodeBuilder nb;
177
178         private NodeHolder(final NodeId id) {
179             this.inab = new IgpNodeAttributesBuilder();
180             this.nb = new NodeBuilder().setKey(new NodeKey(id)).setNodeId(id);
181         }
182
183         /**
184          * Synchronized in-core state of a node into the backing store using the transaction
185          *
186          * @param trans data modification transaction which to use
187          * @return True if the node has been purged, false otherwise.
188          */
189         private boolean syncState(final WriteTransaction trans) {
190             final InstanceIdentifier<Node> nid = getNodeInstanceIdentifier(this.nb.getKey());
191
192             /*
193              * Transaction's putOperationalData() does a merge. Force it onto a replace
194              * by removing the data. If we decide to remove the node -- we just skip the put.
195              */
196             trans.delete(LogicalDatastoreType.OPERATIONAL, nid);
197
198             if (!this.advertized) {
199                 if (this.tps.isEmpty() && this.prefixes.isEmpty()) {
200                     LOG.debug("Removing unadvertized unused node {}", this.nb.getNodeId());
201                     return true;
202                 }
203
204                 LOG.debug("Node {} is still implied by {} TPs and {} prefixes", this.nb.getNodeId(), this.tps.size(), this.prefixes.size());
205             }
206
207             // Re-generate termination points
208             this.nb.setTerminationPoint(Lists.newArrayList(Collections2.transform(this.tps.values(), TpHolder::getTp)));
209
210             // Re-generate prefixes
211             this.inab.setPrefix(Lists.newArrayList(this.prefixes.values()));
212
213             // Write the node out
214             final Node n = this.nb.addAugmentation(Node1.class, new Node1Builder().setIgpNodeAttributes(this.inab.build()).build()).build();
215             trans.put(LogicalDatastoreType.OPERATIONAL, nid, n);
216             LOG.debug("Created node {} at {}", n, nid);
217             return false;
218         }
219
220         private boolean checkForRemoval(final WriteTransaction trans) {
221             final InstanceIdentifier<Node> nid = getNodeInstanceIdentifier(this.nb.getKey());
222
223                 if (!this.advertized) {
224                     if (this.tps.isEmpty() && this.prefixes.isEmpty()) {
225                         trans.delete(LogicalDatastoreType.OPERATIONAL, nid);
226                         LOG.debug("Removing unadvertized unused node {}", this.nb.getNodeId());
227                         return true;
228                     }
229
230                     LOG.debug("Node {} is still implied by {} TPs and {} prefixes", this.nb.getNodeId(), this.tps.size(), this.prefixes.size());
231                 }
232                 return false;
233         }
234
235         private synchronized void removeTp(final TpId tp, final LinkId link, final boolean isRemote) {
236             final TpHolder h = this.tps.get(tp);
237             if (h != null) {
238                 if (h.removeLink(link, isRemote)) {
239                     this.tps.remove(tp);
240                     LOG.debug("Removed TP {}", tp);
241                 }
242             } else {
243                 LOG.warn("Removed non-present TP {} by link {}", tp, link);
244             }
245         }
246
247         private void addTp(final TerminationPoint tp, final LinkId link, final boolean isRemote) {
248             final TpHolder h = this.tps.computeIfAbsent(tp.getTpId(), k -> new TpHolder(tp));
249             h.addLink(link, isRemote);
250         }
251
252         private void addPrefix(final Prefix pfx) {
253             this.prefixes.put(pfx.getKey(), pfx);
254         }
255
256         private void removePrefix(final PrefixCase p) {
257             this.prefixes.remove(new PrefixKey(p.getPrefixDescriptors().getIpReachabilityInformation()));
258         }
259
260         private void unadvertized() {
261             this.inab = new IgpNodeAttributesBuilder();
262             this.nb = new NodeBuilder().setKey(this.nb.getKey()).setNodeId(this.nb.getNodeId());
263             this.advertized = false;
264             LOG.debug("Node {} is unadvertized", this.nb.getNodeId());
265         }
266
267         private void advertized(final NodeBuilder nb, final IgpNodeAttributesBuilder inab) {
268             this.nb = Preconditions.checkNotNull(nb);
269             this.inab = Preconditions.checkNotNull(inab);
270             this.advertized = true;
271             LOG.debug("Node {} is advertized", nb.getNodeId());
272         }
273
274         private NodeId getNodeId() {
275             return this.nb.getNodeId();
276         }
277     }
278
279     private static final Logger LOG = LoggerFactory.getLogger(LinkstateTopologyBuilder.class);
280     private final Map<NodeId, NodeHolder> nodes = new HashMap<>();
281
282     public LinkstateTopologyBuilder(final DataBroker dataProvider, final RibReference locRibReference, final TopologyId topologyId) {
283         super(dataProvider, locRibReference, topologyId, LINKSTATE_TOPOLOGY_TYPE, LinkstateAddressFamily.class, LinkstateSubsequentAddressFamily.class);
284     }
285
286     public LinkstateTopologyBuilder(final DataBroker dataProvider, final RibReference locRibReference,
287             final TopologyId topologyId, final long listenerResetLimitInMillsec, final int listenerResetEnforceCounter) {
288         super(dataProvider, locRibReference, topologyId, LINKSTATE_TOPOLOGY_TYPE, LinkstateAddressFamily.class, LinkstateSubsequentAddressFamily.class,
289             listenerResetLimitInMillsec, listenerResetEnforceCounter);
290     }
291
292     private static LinkId buildLinkId(final UriBuilder base, final LinkCase link) {
293         return new LinkId(new UriBuilder(base, "link").add(link).toString());
294     }
295
296     private static NodeId buildNodeId(final UriBuilder base,
297             final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.NodeIdentifier node) {
298         return new NodeId(new UriBuilder(base, "node").add("", node).toString());
299     }
300
301     private static TpId buildTpId(final UriBuilder base, final TopologyIdentifier topologyIdentifier,
302             final Ipv4InterfaceIdentifier ipv4InterfaceIdentifier, final Ipv6InterfaceIdentifier ipv6InterfaceIdentifier, final Long id) {
303         final UriBuilder b = new UriBuilder(base, "tp");
304         if (topologyIdentifier != null) {
305             b.add("mt", topologyIdentifier.getValue());
306         }
307         if (ipv4InterfaceIdentifier != null) {
308             b.add("ipv4", ipv4InterfaceIdentifier.getValue());
309         }
310         if (ipv6InterfaceIdentifier != null) {
311             b.add("ipv6", ipv6InterfaceIdentifier.getValue());
312         }
313
314         return new TpId(b.add("id", id).toString());
315     }
316
317     private static TpId buildLocalTpId(final UriBuilder base, final LinkDescriptors linkDescriptors) {
318         return buildTpId(base, linkDescriptors.getMultiTopologyId(), linkDescriptors.getIpv4InterfaceAddress(),
319                 linkDescriptors.getIpv6InterfaceAddress(), linkDescriptors.getLinkLocalIdentifier());
320     }
321
322     private static TerminationPoint buildTp(final TpId id, final TerminationPointType type) {
323         final TerminationPointBuilder stpb = new TerminationPointBuilder();
324         stpb.setKey(new TerminationPointKey(id));
325         stpb.setTpId(id);
326
327         if (type != null) {
328             stpb.addAugmentation(TerminationPoint1.class, new TerminationPoint1Builder().setIgpTerminationPointAttributes(
329                     new IgpTerminationPointAttributesBuilder().setTerminationPointType(type).build()).build());
330         }
331
332         return stpb.build();
333     }
334
335     private static TerminationPointType getTpType(final Ipv4InterfaceIdentifier ipv4InterfaceIdentifier,
336             final Ipv6InterfaceIdentifier ipv6InterfaceIdentifier, final Long id) {
337         // Order of preference: Unnumbered first, then IP
338         if (id != null) {
339             LOG.debug("Unnumbered termination point type: {}", id);
340             return new UnnumberedBuilder().setUnnumberedId(id).build();
341         }
342
343         final IpAddress ip;
344         if (ipv6InterfaceIdentifier != null) {
345             ip = new IpAddress(ipv6InterfaceIdentifier);
346         } else if (ipv4InterfaceIdentifier != null) {
347             ip = new IpAddress(ipv4InterfaceIdentifier);
348         } else {
349             ip = null;
350         }
351
352         if (ip != null) {
353             LOG.debug("IP termination point type: {}", ip);
354             return new IpBuilder().setIpAddress(Lists.newArrayList(ip)).build();
355         }
356
357         return null;
358     }
359
360     private static TerminationPoint buildLocalTp(final UriBuilder base, final LinkDescriptors linkDescriptors) {
361         final TpId id = buildLocalTpId(base, linkDescriptors);
362         final TerminationPointType t = getTpType(linkDescriptors.getIpv4InterfaceAddress(), linkDescriptors.getIpv6InterfaceAddress(),
363                 linkDescriptors.getLinkLocalIdentifier());
364
365         return buildTp(id, t);
366     }
367
368     private static TpId buildRemoteTpId(final UriBuilder base, final LinkDescriptors linkDescriptors) {
369         return buildTpId(base, linkDescriptors.getMultiTopologyId(), linkDescriptors.getIpv4NeighborAddress(),
370                 linkDescriptors.getIpv6NeighborAddress(), linkDescriptors.getLinkRemoteIdentifier());
371     }
372
373     private static TerminationPoint buildRemoteTp(final UriBuilder base, final LinkDescriptors linkDescriptors) {
374         final TpId id = buildRemoteTpId(base, linkDescriptors);
375         final TerminationPointType t = getTpType(linkDescriptors.getIpv4NeighborAddress(), linkDescriptors.getIpv6NeighborAddress(),
376                 linkDescriptors.getLinkRemoteIdentifier());
377
378         return buildTp(id, t);
379     }
380
381     private InstanceIdentifier<Link> buildLinkIdentifier(final LinkId id) {
382         return getInstanceIdentifier().child(
383                 org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Link.class,
384                 new LinkKey(id));
385     }
386
387     private static Float bandwidthToFloat(final Bandwidth bandwidth) {
388         return ByteBuffer.wrap(bandwidth.getValue()).getFloat();
389     }
390
391     private static BigDecimal bandwidthToBigDecimal(final Bandwidth bandwidth) {
392         return BigDecimal.valueOf(bandwidthToFloat(bandwidth));
393     }
394
395     private static List<UnreservedBandwidth> unreservedBandwidthList(
396             final List<? extends org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.UnreservedBandwidth> input) {
397         final List<UnreservedBandwidth> ret = new ArrayList<>(input.size());
398
399         for (final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.UnreservedBandwidth i : input) {
400             ret.add(new UnreservedBandwidthBuilder().setBandwidth(bandwidthToBigDecimal(i.getBandwidth())).setKey(
401                     new UnreservedBandwidthKey(i.getPriority())).build());
402         }
403
404         return ret;
405     }
406
407     private static org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.isis.topology.rev131021.IgpLinkAttributes1 isisLinkAttributes(
408             final TopologyIdentifier topologyIdentifier, final LinkAttributes la) {
409         final org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.isis.topology.rev131021.isis.link.attributes.isis.link.attributes.TedBuilder tb = new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.isis.topology.rev131021.isis.link.attributes.isis.link.attributes.TedBuilder();
410
411         if (la != null) {
412             if (la.getAdminGroup() != null) {
413                 tb.setColor(la.getAdminGroup().getValue());
414             }
415             if (la.getTeMetric() != null) {
416                 tb.setTeDefaultMetric(la.getTeMetric().getValue());
417             }
418             if (la.getUnreservedBandwidth() != null) {
419                 tb.setUnreservedBandwidth(unreservedBandwidthList(la.getUnreservedBandwidth()));
420             }
421             if (la.getMaxLinkBandwidth() != null) {
422                 tb.setMaxLinkBandwidth(bandwidthToBigDecimal(la.getMaxLinkBandwidth()));
423             }
424             if (la.getMaxReservableBandwidth() != null) {
425                 tb.setMaxResvLinkBandwidth(bandwidthToBigDecimal(la.getMaxReservableBandwidth()));
426             }
427             if (la.getSharedRiskLinkGroups() != null) {
428                 final List<SrlgValues> srlgs = new ArrayList<>();
429                 for (final SrlgId id : la.getSharedRiskLinkGroups()) {
430                     srlgs.add(new SrlgValuesBuilder().setSrlgValue(id.getValue()).build());
431                 }
432                 tb.setSrlg(new SrlgBuilder().setSrlgValues(srlgs).build());
433             }
434         }
435
436         final IsisLinkAttributesBuilder ilab = new IsisLinkAttributesBuilder();
437         ilab.setTed(tb.build());
438         if (topologyIdentifier != null) {
439             ilab.setMultiTopologyId(topologyIdentifier.getValue().shortValue());
440         }
441
442         return new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.isis.topology.rev131021.IgpLinkAttributes1Builder().setIsisLinkAttributes(
443                 ilab.build()).build();
444     }
445
446     private static org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.IgpLinkAttributes1 ospfLinkAttributes(
447             final TopologyIdentifier topologyIdentifier, final LinkAttributes la) {
448         final org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.ospf.link.attributes.ospf.link.attributes.TedBuilder tb = new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.ospf.link.attributes.ospf.link.attributes.TedBuilder();
449
450         if (la != null) {
451             if (la.getAdminGroup() != null) {
452                 tb.setColor(la.getAdminGroup().getValue());
453             }
454             if (la.getTeMetric() != null) {
455                 tb.setTeDefaultMetric(la.getTeMetric().getValue());
456             }
457             if (la.getUnreservedBandwidth() != null) {
458                 tb.setUnreservedBandwidth(unreservedBandwidthList(la.getUnreservedBandwidth()));
459             }
460             if (la.getMaxLinkBandwidth() != null) {
461                 tb.setMaxLinkBandwidth(bandwidthToBigDecimal(la.getMaxLinkBandwidth()));
462             }
463             if (la.getMaxReservableBandwidth() != null) {
464                 tb.setMaxResvLinkBandwidth(bandwidthToBigDecimal(la.getMaxReservableBandwidth()));
465             }
466             if (la.getSharedRiskLinkGroups() != null) {
467                 final List<SrlgValues> srlgs = new ArrayList<>();
468                 for (final SrlgId id : la.getSharedRiskLinkGroups()) {
469                     srlgs.add(new SrlgValuesBuilder().setSrlgValue(id.getValue()).build());
470                 }
471                 tb.setSrlg(new SrlgBuilder().setSrlgValues(srlgs).build());
472             }
473         }
474
475         final OspfLinkAttributesBuilder ilab = new OspfLinkAttributesBuilder();
476         ilab.setTed(tb.build());
477         if (topologyIdentifier != null) {
478             ilab.setMultiTopologyId(topologyIdentifier.getValue().shortValue());
479         }
480
481         return new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.IgpLinkAttributes1Builder().setOspfLinkAttributes(
482                 ilab.build()).build();
483     }
484
485     private NodeHolder getNode(final NodeId id) {
486         if (this.nodes.containsKey(id)) {
487             LOG.debug("Node {} is already present", id);
488             return this.nodes.get(id);
489         }
490
491         final NodeHolder ret = new NodeHolder(id);
492         this.nodes.put(id, ret);
493         return ret;
494     }
495
496     private void putNode(final WriteTransaction trans, final NodeHolder holder) {
497         if (holder.syncState(trans)) {
498             this.nodes.remove(holder.getNodeId());
499         }
500     }
501
502     private void checkNodeForRemoval(final WriteTransaction trans, final NodeHolder holder) {
503         if (holder.checkForRemoval(trans)) {
504             this.nodes.remove(holder.getNodeId());
505         }
506     }
507
508     private static void augmentProtocolId(final LinkstateRoute value, final IgpLinkAttributesBuilder ilab,
509             final LinkAttributes la, final LinkDescriptors ld) {
510         switch (value.getProtocolId()) {
511         case Direct:
512         case Static:
513         case IsisLevel1:
514         case IsisLevel2:
515             ilab.addAugmentation(
516                     org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.isis.topology.rev131021.IgpLinkAttributes1.class,
517                     isisLinkAttributes(ld.getMultiTopologyId(), la));
518             break;
519         case OspfV3:
520         case Ospf:
521             ilab.addAugmentation(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.IgpLinkAttributes1.class,
522                     ospfLinkAttributes(ld.getMultiTopologyId(), la));
523             break;
524         default:
525             break;
526         }
527     }
528
529     private void createLink(final WriteTransaction trans, final UriBuilder base,
530             final LinkstateRoute value, final LinkCase l, final Attributes attributes) {
531         // defensive lookup
532         final LinkAttributes la;
533         final Attributes1 attr = attributes.getAugmentation(Attributes1.class);
534         if (attr != null) {
535             final LinkStateAttribute attrType = attr.getLinkStateAttribute();
536             if (attrType != null) {
537                 la = ((LinkAttributesCase)attrType).getLinkAttributes();
538             } else {
539                 LOG.debug("Missing attribute type in link {} route {}, skipping it", l, value);
540                 la = null;
541             }
542         } else {
543             LOG.debug("Missing attributes in link {} route {}, skipping it", l, value);
544             la = null;
545         }
546
547         final IgpLinkAttributesBuilder ilab = new IgpLinkAttributesBuilder();
548         if (la != null) {
549             if (la.getMetric() != null) {
550                 ilab.setMetric(la.getMetric().getValue());
551             }
552             ilab.setName(la.getLinkName());
553         }
554         augmentProtocolId(value, ilab, la, l.getLinkDescriptors());
555
556         final LinkBuilder lb = new LinkBuilder();
557         lb.setLinkId(buildLinkId(base, l));
558         lb.addAugmentation(Link1.class, new Link1Builder().setIgpLinkAttributes(ilab.build()).build());
559
560         final NodeId srcNode = buildNodeId(base, l.getLocalNodeDescriptors());
561         LOG.debug("Link {} implies source node {}", l, srcNode);
562
563         final NodeId dstNode = buildNodeId(base, l.getRemoteNodeDescriptors());
564         LOG.debug("Link {} implies destination node {}", l, dstNode);
565
566         final TerminationPoint srcTp = buildLocalTp(base, l.getLinkDescriptors());
567         LOG.debug("Link {} implies source TP {}", l, srcTp);
568
569         final TerminationPoint dstTp = buildRemoteTp(base, l.getLinkDescriptors());
570         LOG.debug("Link {} implies destination TP {}", l, dstTp);
571
572         lb.setSource(new SourceBuilder().setSourceNode(srcNode).setSourceTp(srcTp.getTpId()).build());
573         lb.setDestination(new DestinationBuilder().setDestNode(dstNode).setDestTp(dstTp.getTpId()).build());
574
575         LOG.debug("Created TP {} as link source", srcTp);
576         NodeHolder snh = this.nodes.get(srcNode);
577         if (snh == null) {
578             snh = getNode(srcNode);
579             snh.addTp(srcTp, lb.getLinkId(), false);
580             putNode(trans, snh);
581         } else {
582             snh.addTp(srcTp, lb.getLinkId(), false);
583             final InstanceIdentifier<Node> nid = getNodeInstanceIdentifier(new NodeKey((NodeId) snh.getNodeId()));
584             trans.put(LogicalDatastoreType.OPERATIONAL, nid.child(TerminationPoint.class, srcTp.getKey()), srcTp);
585         }
586
587         LOG.debug("Created TP {} as link destination", dstTp);
588         NodeHolder dnh = this.nodes.get(dstNode);
589         if (dnh == null) {
590             dnh = getNode(dstNode);
591             dnh.addTp(dstTp, lb.getLinkId(), true);
592             putNode(trans, dnh);
593         } else {
594             dnh.addTp(dstTp, lb.getLinkId(), true);
595             final InstanceIdentifier<Node> nid = getInstanceIdentifier().child(
596                     org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node.class,
597                     new NodeKey((NodeId) dnh.getNodeId()));
598             trans.put(LogicalDatastoreType.OPERATIONAL, nid.child(TerminationPoint.class, dstTp.getKey()), dstTp);
599         }
600
601         final InstanceIdentifier<Link> lid = buildLinkIdentifier(lb.getLinkId());
602         final Link link = lb.build();
603
604         trans.put(LogicalDatastoreType.OPERATIONAL, lid, link);
605         LOG.debug("Created link {} at {} for {}", link, lid, l);
606     }
607
608     private void removeTp(final WriteTransaction trans, final NodeId node, final TpId tp,
609             final LinkId link, final boolean isRemote) {
610         final NodeHolder nh = this.nodes.get(node);
611         if (nh != null) {
612             final InstanceIdentifier<Node> nid = getNodeInstanceIdentifier(new NodeKey((NodeId) nh.getNodeId()));
613             trans.delete(LogicalDatastoreType.OPERATIONAL, nid.child(TerminationPoint.class, new TerminationPointKey(tp)));
614             nh.removeTp(tp, link, isRemote);
615             checkNodeForRemoval(trans, nh);
616         } else {
617             LOG.warn("Removed non-existent node {}", node);
618         }
619     }
620
621     private void removeLink(final WriteTransaction trans, final UriBuilder base, final LinkCase l) {
622         final LinkId id = buildLinkId(base, l);
623         final InstanceIdentifier<?> lid = buildLinkIdentifier(id);
624         trans.delete(LogicalDatastoreType.OPERATIONAL, lid);
625         LOG.debug("Removed link {}", lid);
626
627         removeTp(trans, buildNodeId(base, l.getLocalNodeDescriptors()), buildLocalTpId(base, l.getLinkDescriptors()), id, false);
628         removeTp(trans, buildNodeId(base, l.getRemoteNodeDescriptors()), buildRemoteTpId(base, l.getLinkDescriptors()), id, true);
629     }
630
631     private static List<Short> nodeMultiTopology(final List<TopologyIdentifier> list) {
632         final List<Short> ret = new ArrayList<>(list.size());
633         for (final TopologyIdentifier id : list) {
634             ret.add(id.getValue().shortValue());
635         }
636         return ret;
637     }
638
639     private static org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.isis.topology.rev131021.IgpNodeAttributes1 isisNodeAttributes(
640             final NodeIdentifier node, final NodeAttributes na) {
641         final org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.isis.topology.rev131021.isis.node.attributes.isis.node.attributes.TedBuilder tb = new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.isis.topology.rev131021.isis.node.attributes.isis.node.attributes.TedBuilder();
642         final IsisNodeAttributesBuilder ab = new IsisNodeAttributesBuilder();
643
644         if (na != null) {
645             if (na.getIpv4RouterId() != null) {
646                 tb.setTeRouterIdIpv4(na.getIpv4RouterId());
647             }
648             if (na.getIpv6RouterId() != null) {
649                 tb.setTeRouterIdIpv6(na.getIpv6RouterId());
650             }
651             if (na.getTopologyIdentifier() != null) {
652                 ab.setMultiTopologyId(nodeMultiTopology(na.getTopologyIdentifier()));
653             }
654         }
655
656         final CRouterIdentifier ri = node.getCRouterIdentifier();
657         if (ri instanceof IsisPseudonodeCase) {
658             final IsisPseudonode pn = ((IsisPseudonodeCase) ri).getIsisPseudonode();
659             final IsoBuilder b = new IsoBuilder();
660             final String systemId = UriBuilder.isoId(pn.getIsIsRouterIdentifier().getIsoSystemId());
661             b.setIsoSystemId(new IsoSystemId(systemId));
662             b.setIsoPseudonodeId(new IsoPseudonodeId(BaseEncoding.base16().encode(new byte[] {pn.getPsn().byteValue()})));
663             ab.setIso(b.build());
664             if (na != null) {
665                 ab.setNet(toIsoNetIds(na.getIsisAreaId(), systemId));
666             }
667         } else if (ri instanceof IsisNodeCase) {
668             final IsisNode in = ((IsisNodeCase) ri).getIsisNode();
669             final String systemId = UriBuilder.isoId(in.getIsoSystemId());
670             ab.setIso(new IsoBuilder().setIsoSystemId(new IsoSystemId(systemId)).build());
671             if (na != null) {
672                 ab.setNet(toIsoNetIds(na.getIsisAreaId(), systemId));
673             }
674         }
675
676         ab.setTed(tb.build());
677
678         return new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.isis.topology.rev131021.IgpNodeAttributes1Builder().setIsisNodeAttributes(
679                 ab.build()).build();
680     }
681
682     private static List<IsoNetId> toIsoNetIds(final List<IsisAreaIdentifier> areaIds, final String systemId) {
683         return Lists.transform(areaIds, input -> new IsoNetId(UriBuilder.toIsoNetId(input, systemId)));
684     }
685
686     private static org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.IgpNodeAttributes1 ospfNodeAttributes(
687             final NodeIdentifier node, final NodeAttributes na) {
688         final org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.ospf.node.attributes.ospf.node.attributes.TedBuilder tb = new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.ospf.node.attributes.ospf.node.attributes.TedBuilder();
689         final OspfNodeAttributesBuilder ab = new OspfNodeAttributesBuilder();
690         if (na != null) {
691             if (na.getIpv4RouterId() != null) {
692                 tb.setTeRouterIdIpv4(na.getIpv4RouterId());
693             }
694             if (na.getIpv6RouterId() != null) {
695                 tb.setTeRouterIdIpv6(na.getIpv6RouterId());
696             }
697             if (na.getTopologyIdentifier() != null) {
698                 ab.setMultiTopologyId(nodeMultiTopology(na.getTopologyIdentifier()));
699             }
700             final CRouterIdentifier ri = node.getCRouterIdentifier();
701             if (ri instanceof OspfPseudonodeCase) {
702                 final OspfPseudonode pn = ((OspfPseudonodeCase) ri).getOspfPseudonode();
703
704                 ab.setRouterType(new PseudonodeBuilder().setPseudonode(Boolean.TRUE).build());
705                 ab.setDrInterfaceId(pn.getLanInterface().getValue());
706             } else if (ri instanceof OspfNodeCase && na.getNodeFlags() != null) {
707                 // TODO: what should we do with in.getOspfRouterId()?
708
709                 final NodeFlagBits nf = na.getNodeFlags();
710                 if (nf.isAbr() != null) {
711                     ab.setRouterType(new AbrBuilder().setAbr(nf.isAbr()).build());
712                 } else if (nf.isExternal() != null) {
713                     ab.setRouterType(new InternalBuilder().setInternal(!nf.isExternal()).build());
714                 }
715             }
716         }
717         ab.setTed(tb.build());
718         return new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.IgpNodeAttributes1Builder().setOspfNodeAttributes(
719                 ab.build()).build();
720     }
721
722     private static void augmentProtocolId(final LinkstateRoute value, final IgpNodeAttributesBuilder inab,
723             final NodeAttributes na, final NodeIdentifier nd) {
724         switch (value.getProtocolId()) {
725         case Direct:
726         case Static:
727         case IsisLevel1:
728         case IsisLevel2:
729             inab.addAugmentation(
730                     org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.isis.topology.rev131021.IgpNodeAttributes1.class,
731                     isisNodeAttributes(nd, na));
732             break;
733         case Ospf:
734             inab.addAugmentation(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.ospf.topology.rev131021.IgpNodeAttributes1.class,
735                     ospfNodeAttributes(nd, na));
736             break;
737         default:
738             break;
739         }
740     }
741
742     private void createNode(final WriteTransaction trans, final UriBuilder base,
743             final LinkstateRoute value, final NodeCase n, final Attributes attributes) {
744         final NodeAttributes na;
745         //defensive lookup
746         final Attributes1 attr = attributes.getAugmentation(Attributes1.class);
747         if (attr != null) {
748             final LinkStateAttribute attrType = attr.getLinkStateAttribute();
749             if (attrType != null) {
750                 na = ((NodeAttributesCase)attrType).getNodeAttributes();
751             } else {
752                 LOG.debug("Missing attribute type in node {} route {}, skipping it", n, value);
753                 na = null;
754             }
755         } else {
756             LOG.debug("Missing attributes in node {} route {}, skipping it", n, value);
757             na = null;
758         }
759         final IgpNodeAttributesBuilder inab = new IgpNodeAttributesBuilder();
760         final List<IpAddress> ids = new ArrayList<>();
761         if (na != null) {
762             if (na.getIpv4RouterId() != null) {
763                 ids.add(new IpAddress(na.getIpv4RouterId()));
764             }
765             if (na.getIpv6RouterId() != null) {
766                 ids.add(new IpAddress(na.getIpv6RouterId()));
767             }
768             if (na.getDynamicHostname() != null) {
769                 inab.setName(new DomainName(na.getDynamicHostname()));
770             }
771         }
772         if (!ids.isEmpty()) {
773             inab.setRouterId(ids);
774         }
775         augmentProtocolId(value, inab, na, n.getNodeDescriptors());
776
777         final NodeId nid = buildNodeId(base, n.getNodeDescriptors());
778         final NodeHolder nh = getNode(nid);
779         /*
780          *  Eventhough the the holder creates a dummy structure, we need to duplicate it here,
781          *  as that is the API requirement. The reason for it is the possible presence of supporting
782          *  node -- something which the holder does not track.
783          */
784         final NodeBuilder nb = new NodeBuilder();
785         nb.setNodeId(nid);
786         nb.setKey(new NodeKey(nb.getNodeId()));
787
788         nh.advertized(nb, inab);
789         putNode(trans, nh);
790     }
791
792     private void removeNode(final WriteTransaction trans, final UriBuilder base, final NodeCase n) {
793         final NodeId id = buildNodeId(base, n.getNodeDescriptors());
794         final NodeHolder nh = this.nodes.get(id);
795         if (nh != null) {
796             nh.unadvertized();
797             putNode(trans, nh);
798         } else {
799             LOG.warn("Node {} does not have a holder", id);
800         }
801     }
802
803     private static void augmentProtocolId(final LinkstateRoute value, final PrefixAttributes pa, final PrefixBuilder pb) {
804         switch (value.getProtocolId()) {
805         case Direct:
806         case IsisLevel1:
807         case IsisLevel2:
808         case Static:
809         case Ospf:
810             if (pa != null && pa.getOspfForwardingAddress() != null) {
811                 pb.addAugmentation(
812                         Prefix1.class,
813                         new Prefix1Builder().setOspfPrefixAttributes(
814                                 new OspfPrefixAttributesBuilder().setForwardingAddress(pa.getOspfForwardingAddress().getIpv4Address()).build()).build());
815             }
816             break;
817         default:
818             break;
819         }
820     }
821
822     private void createPrefix(final WriteTransaction trans, final UriBuilder base,
823             final LinkstateRoute value, final PrefixCase p, final Attributes attributes) {
824         final IpPrefix ippfx = p.getPrefixDescriptors().getIpReachabilityInformation();
825         if (ippfx == null) {
826             LOG.warn("IP reachability not present in prefix {} route {}, skipping it", p, value);
827             return;
828         }
829         final PrefixBuilder pb = new PrefixBuilder();
830         final PrefixKey pk = new PrefixKey(ippfx);
831         pb.setKey(pk);
832         pb.setPrefix(ippfx);
833
834         final PrefixAttributes pa;
835         // Very defensive lookup
836         final Attributes1 attr = attributes.getAugmentation(Attributes1.class);
837         if (attr != null) {
838             final LinkStateAttribute attrType = attr.getLinkStateAttribute();
839             if (attrType != null) {
840                 pa = ((PrefixAttributesCase)attrType).getPrefixAttributes();
841             } else {
842                 LOG.debug("Missing attribute type in IP {} prefix {} route {}, skipping it", ippfx, p, value);
843                 pa = null;
844             }
845         } else {
846             LOG.debug("Missing attributes in IP {} prefix {} route {}, skipping it", ippfx, p, value);
847             pa = null;
848         }
849         if (pa != null) {
850             pb.setMetric(pa.getPrefixMetric().getValue());
851         }
852         augmentProtocolId(value, pa, pb);
853
854         final Prefix pfx = pb.build();
855         LOG.debug("Created prefix {} for {}", pfx, p);
856
857         /*
858          * All set, but... the hosting node may not exist, we may need to fake it.
859          */
860         final NodeId node = buildNodeId(base, p.getAdvertisingNodeDescriptors());
861         NodeHolder nh = this.nodes.get(node);
862         if (nh == null) {
863             nh = getNode(node);
864             nh.addPrefix(pfx);
865             putNode(trans, nh);
866         } else {
867             nh.addPrefix(pfx);
868             final InstanceIdentifier<Node> nid = getNodeInstanceIdentifier(new NodeKey((NodeId) nh.getNodeId()));
869             final InstanceIdentifier<IgpNodeAttributes> inaId = nid.builder().augmentation(Node1.class).child(IgpNodeAttributes.class).build();
870             trans.put(LogicalDatastoreType.OPERATIONAL, inaId.child(Prefix.class, pk), pfx);
871         }
872     }
873
874     private void removePrefix(final WriteTransaction trans, final UriBuilder base, final PrefixCase p) {
875         final NodeId node = buildNodeId(base, p.getAdvertisingNodeDescriptors());
876         final NodeHolder nh = this.nodes.get(node);
877         if (nh != null) {
878             LOG.debug("Removed prefix {}", p);
879             final InstanceIdentifier<Node> nid = getNodeInstanceIdentifier(new NodeKey((NodeId) nh.getNodeId()));
880             final InstanceIdentifier<IgpNodeAttributes> inaId = nid.builder().augmentation(Node1.class).child(IgpNodeAttributes.class).build();
881             final IpPrefix ippfx = p.getPrefixDescriptors().getIpReachabilityInformation();
882             if (ippfx == null) {
883                 LOG.warn("IP reachability not present in prefix {}, skipping it", p);
884                 return;
885             }
886             final PrefixKey pk = new PrefixKey(ippfx);
887             trans.delete(LogicalDatastoreType.OPERATIONAL, inaId.child(Prefix.class, pk));
888             nh.removePrefix(p);
889             checkNodeForRemoval(trans, nh);
890         } else {
891             LOG.warn("Removing prefix from non-existing node {}", node);
892         }
893     }
894
895     private InstanceIdentifier<Node> getNodeInstanceIdentifier(final NodeKey nodeKey) {
896         return getInstanceIdentifier().child(
897                 org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node.class,
898                 nodeKey);
899     }
900
901     @Override
902     protected void createObject(final ReadWriteTransaction trans,
903             final InstanceIdentifier<LinkstateRoute> id, final LinkstateRoute value) {
904         final UriBuilder base = new UriBuilder(value);
905
906         final ObjectType t = value.getObjectType();
907         Preconditions.checkArgument(t != null, "Route %s value %s has null object type", id, value);
908
909         if (t instanceof LinkCase) {
910             createLink(trans, base, value, (LinkCase) t, value.getAttributes());
911         } else if (t instanceof NodeCase) {
912             createNode(trans, base, value, (NodeCase) t, value.getAttributes());
913         } else if (t instanceof PrefixCase) {
914             createPrefix(trans, base, value, (PrefixCase) t, value.getAttributes());
915         } else {
916             LOG.debug(UNHANDLED_OBJECT_CLASS, t.getImplementedInterface());
917         }
918     }
919
920     @Override
921     protected void removeObject(final ReadWriteTransaction trans,
922             final InstanceIdentifier<LinkstateRoute> id, final LinkstateRoute value) {
923         if (value == null) {
924             LOG.error("Empty before-data received in delete data change notification for instance id {}", id);
925             return;
926         }
927
928         final UriBuilder base = new UriBuilder(value);
929
930         final ObjectType t = value.getObjectType();
931         if (t instanceof LinkCase) {
932             removeLink(trans, base, (LinkCase) t);
933         } else if (t instanceof NodeCase) {
934             removeNode(trans, base, (NodeCase) t);
935         } else if (t instanceof PrefixCase) {
936             removePrefix(trans, base, (PrefixCase) t);
937         } else {
938             LOG.debug(UNHANDLED_OBJECT_CLASS, t.getImplementedInterface());
939         }
940     }
941
942     @SuppressWarnings({ "rawtypes", "unchecked" })
943     @Override
944     protected InstanceIdentifier<LinkstateRoute> getRouteWildcard(final InstanceIdentifier<Tables> tablesId) {
945         return tablesId.child((Class)LinkstateRoutes.class).child(LinkstateRoute.class);
946     }
947
948     @Override
949     protected void clearTopology() {
950         this.nodes.clear();
951     }
952 }