Merge "Pre-populate links/nodes with empty lists"
[bgpcep.git] / bgp / topology-provider / src / main / java / org / opendaylight / bgpcep / bgp / topology / provider / AbstractTopologyBuilder.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.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.util.concurrent.FutureCallback;
13 import com.google.common.util.concurrent.Futures;
14
15 import java.util.Collections;
16 import java.util.HashSet;
17 import java.util.Map;
18 import java.util.Set;
19 import java.util.concurrent.ExecutionException;
20
21 import org.opendaylight.bgpcep.topology.TopologyReference;
22 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
23 import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
24 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
25 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
26 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
27 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
28 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
29 import org.opendaylight.protocol.bgp.rib.RibReference;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.Route;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.LocRib;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.Tables;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.AddressFamily;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.SubsequentAddressFamily;
36 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
37 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId;
38 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
39 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyBuilder;
40 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
41 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Link;
42 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
43 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.TopologyTypes;
44 import org.opendaylight.yangtools.yang.binding.DataObject;
45 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 public abstract class AbstractTopologyBuilder<T extends Route> implements AutoCloseable, DataChangeListener, LocRIBListener, TopologyReference {
50     private static final Logger LOG = LoggerFactory.getLogger(AbstractTopologyBuilder.class);
51     private final RibReference locRibReference;
52     private final InstanceIdentifier<Topology> topology;
53     private final DataBroker dataProvider;
54     private final Class<T> idClass;
55
56     protected AbstractTopologyBuilder(final DataBroker dataProvider, final RibReference locRibReference,
57             final TopologyId topologyId, final TopologyTypes types, final Class<T> idClass) {
58         this.dataProvider = Preconditions.checkNotNull(dataProvider);
59         this.locRibReference = Preconditions.checkNotNull(locRibReference);
60         this.idClass = Preconditions.checkNotNull(idClass);
61
62         final TopologyKey tk = new TopologyKey(Preconditions.checkNotNull(topologyId));
63         this.topology = InstanceIdentifier.builder(NetworkTopology.class).child(Topology.class, tk).toInstance();
64
65         LOG.debug("Initiating topology builder from {} at {}", locRibReference, this.topology);
66
67         final ReadWriteTransaction t = dataProvider.newReadWriteTransaction();
68         final Optional<Topology> o;
69         try {
70             o = t.read(LogicalDatastoreType.OPERATIONAL, this.topology).get();
71         } catch (InterruptedException | ExecutionException e) {
72             throw new IllegalStateException("Failed to read topology " + topology, e);
73         }
74         Preconditions.checkState(!o.isPresent(), "Data provider conflict detected on object {}", this.topology);
75
76         t.put(LogicalDatastoreType.OPERATIONAL, this.topology,
77                 new TopologyBuilder().setKey(tk).setServerProvided(Boolean.TRUE).setTopologyTypes(types)
78                     .setLink(Collections.<Link>emptyList()).setNode(Collections.<Node>emptyList()).build());
79         Futures.addCallback(t.submit(), new FutureCallback<Void>() {
80             @Override
81             public void onSuccess(final Void result) {
82                 LOG.trace("Transaction {} committed successfully", t.getIdentifier());
83             }
84
85             @Override
86             public void onFailure(final Throwable t) {
87                 LOG.error("Failed to initiate topology {} by listener {}", AbstractTopologyBuilder.this.topology,
88                         AbstractTopologyBuilder.this, t);
89             }
90         });
91     }
92
93     public final InstanceIdentifier<Tables> tableInstanceIdentifier(final Class<? extends AddressFamily> afi,
94             final Class<? extends SubsequentAddressFamily> safi) {
95         return this.locRibReference.getInstanceIdentifier().builder().child(LocRib.class).child(Tables.class, new TablesKey(afi, safi)).toInstance();
96     }
97
98     protected abstract void createObject(ReadWriteTransaction trans, InstanceIdentifier<T> id, T value);
99
100     protected abstract void removeObject(ReadWriteTransaction trans, InstanceIdentifier<T> id, T value);
101
102     public final DataBroker getDataProvider() {
103         return this.dataProvider;
104     }
105
106     @Override
107     public final InstanceIdentifier<Topology> getInstanceIdentifier() {
108         return this.topology;
109     }
110
111     private void addIdentifier(final InstanceIdentifier<?> i, final String set, final Set<InstanceIdentifier<T>> out) {
112         final InstanceIdentifier<T> id = i.firstIdentifierOf(this.idClass);
113         if (id != null) {
114             out.add(id);
115         } else {
116             LOG.debug("Identifier {} in {} set does not contain listening class {}, ignoring it", i, set, this.idClass);
117         }
118     }
119
120     @Override
121     public final void onLocRIBChange(final ReadWriteTransaction trans,
122             final AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> event) {
123         LOG.debug("Received data change {} event with transaction {}", event, trans.getIdentifier());
124
125         // FIXME: speed this up
126         final Set<InstanceIdentifier<T>> ids = new HashSet<>();
127         for (final InstanceIdentifier<?> i : event.getRemovedPaths()) {
128             addIdentifier(i, "remove", ids);
129         }
130         for (final InstanceIdentifier<?> i : event.getUpdatedData().keySet()) {
131             addIdentifier(i, "update", ids);
132         }
133         for (final InstanceIdentifier<?> i : event.getCreatedData().keySet()) {
134             addIdentifier(i, "create", ids);
135         }
136
137         final Map<InstanceIdentifier<?>, ? extends DataObject> o = event.getOriginalData();
138         final Map<InstanceIdentifier<?>, DataObject> u = event.getUpdatedData();
139         final Map<InstanceIdentifier<?>, DataObject> c = event.getCreatedData();
140         for (final InstanceIdentifier<T> i : ids) {
141             final T oldValue = this.idClass.cast(o.get(i));
142             T newValue = this.idClass.cast(u.get(i));
143             if (newValue == null) {
144                 newValue = this.idClass.cast(c.get(i));
145             }
146
147             LOG.debug("Updating object {} value {} -> {}", i, oldValue, newValue);
148             if (oldValue != null) {
149                 removeObject(trans, i, oldValue);
150             }
151             if (newValue != null) {
152                 createObject(trans, i, newValue);
153             }
154         }
155
156         Futures.addCallback(trans.submit(), new FutureCallback<Void>() {
157             @Override
158             public void onSuccess(final Void result) {
159                 LOG.trace("Transaction {} committed successfully", trans.getIdentifier());
160             }
161
162             @Override
163             public void onFailure(final Throwable t) {
164                 LOG.error("Failed to propagate change by listener {}", AbstractTopologyBuilder.this);
165             }
166         });
167     }
168
169     @Override
170     public final void close() throws TransactionCommitFailedException {
171         LOG.info("Shutting down builder for {}", getInstanceIdentifier());
172         final WriteTransaction trans = this.dataProvider.newWriteOnlyTransaction();
173         trans.delete(LogicalDatastoreType.OPERATIONAL, getInstanceIdentifier());
174         trans.submit().checkedGet();
175     }
176
177     @Override
178     public final void onDataChanged(final AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> change) {
179         final ReadWriteTransaction trans = this.dataProvider.newReadWriteTransaction();
180
181         try {
182             onLocRIBChange(trans, change);
183         } catch (final RuntimeException e) {
184             LOG.warn("Data change {} was not completely propagated to listener {}", change, this, e);
185             return;
186         }
187     }
188 }