Bug 3244 - SFC Improvements for distributed classifier, robustness
[groupbasedpolicy.git] / renderers / ofoverlay / src / main / java / org / opendaylight / groupbasedpolicy / renderer / ofoverlay / node / SwitchManager.java
1 /*
2  * Copyright (c) 2014 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
9 package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.node;
10
11 import static com.google.common.base.Preconditions.checkNotNull;
12
13 import java.util.Collection;
14 import java.util.Collections;
15 import java.util.HashMap;
16 import java.util.HashSet;
17 import java.util.List;
18 import java.util.Map;
19 import java.util.Map.Entry;
20 import java.util.Set;
21 import java.util.concurrent.CopyOnWriteArrayList;
22
23 import javax.annotation.Nullable;
24
25 import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.node.SwitchListener;
26 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
27 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.ofoverlay.rev140528.OfOverlayConfig.EncapsulationFormat;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.ofoverlay.rev140528.OfOverlayNodeConfig;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.ofoverlay.rev140528.nodes.node.ExternalInterfaces;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.ofoverlay.rev140528.nodes.node.Tunnel;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.ofoverlay.rev140528.nodes.node.TunnelBuilder;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.overlay.rev150105.TunnelTypeBase;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.overlay.rev150105.TunnelTypeVxlan;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.overlay.rev150105.TunnelTypeVxlanGpe;
44 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 import com.google.common.base.Function;
49 import com.google.common.base.Objects;
50 import com.google.common.base.Predicate;
51 import com.google.common.collect.Collections2;
52 import com.google.common.collect.FluentIterable;
53 import com.google.common.collect.ImmutableList;
54 import com.google.common.collect.ImmutableSet;
55 import com.google.common.collect.Maps;
56
57 /**
58  * Manage connected switches and ensure their configuration is set up
59  * correctly
60  */
61 public class SwitchManager implements AutoCloseable {
62
63     private static final Logger LOG = LoggerFactory.getLogger(SwitchManager.class);
64
65     protected static Map<NodeId, SwitchState> switches = new HashMap<>();
66     protected List<SwitchListener> listeners = new CopyOnWriteArrayList<>();
67
68     private final FlowCapableNodeListener nodeListener;
69     private final OfOverlayNodeListener ofOverlayNodeListener;
70     private final FlowCapableNodeConnectorListener nodeConnectorListener;
71
72     public SwitchManager(DataBroker dataProvider) {
73         if (dataProvider == null) {
74             LOG.warn("No data provider for {}. Listeners {}, {}, {} are not registered.",
75                     SwitchManager.class.getSimpleName(), FlowCapableNodeListener.class.getSimpleName(),
76                     OfOverlayNodeListener.class.getSimpleName(), FlowCapableNodeConnectorListener.class.getSimpleName());
77             nodeListener = null;
78             ofOverlayNodeListener = null;
79             nodeConnectorListener = null;
80         } else {
81             nodeListener = new FlowCapableNodeListener(dataProvider, this);
82             ofOverlayNodeListener = new OfOverlayNodeListener(dataProvider, this);
83             nodeConnectorListener = new FlowCapableNodeConnectorListener(dataProvider, this);
84         }
85         LOG.debug("Initialized OFOverlay switch manager");
86     }
87
88     // When first endpoint is attached to switch, it can be ready
89     public static void activatingSwitch(NodeId nodeId) {
90         SwitchState state = switches.get(nodeId);
91         if (state == null) {
92             state = new SwitchState(nodeId);
93             switches.put(nodeId, state);
94         }
95         state.setHasEndpoints(true);
96         state.updateStatus();
97     }
98
99     // When last endpoint is removed from switch, it is no longer ready
100     public static void deactivatingSwitch(NodeId nodeId) {
101         SwitchState state = switches.get(nodeId);
102         if (state == null) {
103             LOG.error("No SwitchState for {} in deactivatingSwitch. This should not happen.",nodeId);
104             return;
105         }
106         state.setHasEndpoints(false);;
107         state.updateStatus();
108     }
109
110     /**
111      * Get the collection of switches that are in the "ready" state. Note
112      * that the collection is immutable.
113      *
114      * @return A {@link Collection} containing the switches that are ready.
115      */
116     public synchronized Collection<NodeId> getReadySwitches() {
117         ImmutableList<NodeId> readySwitches = FluentIterable.from(switches.values())
118             .filter(new Predicate<SwitchState>() {
119
120                 @Override
121                 public boolean apply(SwitchState input) {
122                     return input.status == SwitchStatus.READY;
123                 }
124             })
125             .transform(new Function<SwitchState, NodeId>() {
126
127                 @Override
128                 public NodeId apply(SwitchState input) {
129                     return input.nodeId;
130                 }
131             })
132             .toList();
133         LOG.trace("Get ready switches: {}", readySwitches);
134         return readySwitches;
135     }
136
137     public synchronized Set<NodeConnectorId> getExternalPorts(NodeId nodeId) {
138         SwitchState state = switches.get(nodeId);
139         if (state == null)
140             return Collections.emptySet();
141         return ImmutableSet.copyOf(state.externalPorts);
142     }
143
144     public synchronized Collection<NodeConnectorId> getTunnelPorts(NodeId nodeId) {
145         Collection<NodeConnectorId> ncIds = new HashSet<>();
146         SwitchState state = switches.get(nodeId);
147         if (state == null ) {
148             return Collections.emptySet();
149         }
150         ncIds = Collections2.transform(state.tunnelBuilderByType.values(),new Function<TunnelBuilder, NodeConnectorId>() {
151
152             @Override
153             public NodeConnectorId apply(TunnelBuilder input) {
154                 return input.getNodeConnectorId();
155             }
156         });
157
158         return ncIds;
159     }
160     public synchronized NodeConnectorId getTunnelPort(NodeId nodeId, Class<? extends TunnelTypeBase> tunnelType) {
161         SwitchState state = switches.get(nodeId);
162         if (state == null) {
163             return null;
164         }
165         TunnelBuilder tunnel = state.tunnelBuilderByType.get(tunnelType);
166         if (tunnel == null) {
167             return null;
168         }
169         return tunnel.getNodeConnectorId();
170     }
171
172     public synchronized IpAddress getTunnelIP(NodeId nodeId, Class<? extends TunnelTypeBase> tunnelType) {
173         SwitchState state = switches.get(nodeId);
174         if (state == null) {
175             return null;
176         }
177         TunnelBuilder tunnel = state.tunnelBuilderByType.get(tunnelType);
178         if (tunnel == null) {
179             return null;
180         }
181         return tunnel.getIp();
182     }
183
184     /**
185      * Add a {@link SwitchListener} to get notifications of switch events
186      *
187      * @param listener the {@link SwitchListener} to add
188      */
189     public void registerListener(SwitchListener listener) {
190         listeners.add(listener);
191     }
192
193     /**
194      * Set the encapsulation format the specified value
195      *
196      * @param format The new format
197      */
198     public void setEncapsulationFormat(EncapsulationFormat format) {
199         // No-op for now
200     }
201
202     synchronized void updateSwitch(NodeId nodeId, @Nullable FlowCapableNode fcNode) {
203         SwitchState state = getSwitchState(checkNotNull(nodeId));
204         SwitchStatus oldStatus = state.status;
205         state.setFlowCapableNode(fcNode);
206         handleSwitchState(state, oldStatus);
207     }
208
209     synchronized void updateSwitchNodeConnectorConfig(InstanceIdentifier<NodeConnector> ncIid,
210             @Nullable FlowCapableNodeConnector fcnc) {
211         NodeId nodeId = ncIid.firstKeyOf(Node.class, NodeKey.class).getId();
212         SwitchState state = getSwitchState(nodeId);
213         SwitchStatus oldStatus = state.status;
214         state.setNodeConnectorConfig(ncIid, fcnc);
215         handleSwitchState(state, oldStatus);
216     }
217
218     synchronized void updateSwitchConfig(NodeId nodeId, @Nullable OfOverlayNodeConfig config) {
219         SwitchState state = getSwitchState(checkNotNull(nodeId));
220         SwitchStatus oldStatus = state.status;
221         state.setConfig(config);
222         handleSwitchState(state, oldStatus);
223     }
224
225     private SwitchState getSwitchState(NodeId id) {
226         SwitchState state = switches.get(id);
227         if (state == null) {
228             state = new SwitchState(id);
229             switches.put(id, state);
230             LOG.trace("Switch {} added to switches {}", state.nodeId.getValue(), switches.keySet());
231         }
232         return state;
233     }
234
235     private void handleSwitchState(SwitchState state, SwitchStatus oldStatus) {
236         if (oldStatus == SwitchStatus.READY && state.status != SwitchStatus.READY) {
237             LOG.info("Switch {} removed", state.nodeId.getValue());
238             notifySwitchRemoved(state.nodeId);
239         } else if (oldStatus != SwitchStatus.READY && state.status == SwitchStatus.READY) {
240             LOG.info("Switch {} ready", state.nodeId.getValue());
241             notifySwitchReady(state.nodeId);
242         } else if (oldStatus == SwitchStatus.READY && state.status == SwitchStatus.READY) {
243             // TODO Be msunal we could improve this by ignoring of updates where uninteresting fields are changed
244             LOG.debug("Switch {} updated", state.nodeId.getValue());
245             notifySwitchUpdated(state.nodeId);
246         }
247         if (state.status == SwitchStatus.DISCONNECTED && state.isConfigurationEmpty()) {
248             switches.remove(state.nodeId);
249             LOG.trace("Switch {} removed from switches {}", state.nodeId, switches.keySet());
250         }
251     }
252
253     private void notifySwitchRemoved(NodeId nodeId) {
254         for (SwitchListener listener : listeners) {
255             listener.switchRemoved(nodeId);
256         }
257     }
258
259     private void notifySwitchReady(NodeId nodeId) {
260         for (SwitchListener listener : listeners) {
261             listener.switchReady(nodeId);
262         }
263     }
264
265     private void notifySwitchUpdated(NodeId nodeId) {
266         for (SwitchListener listener : listeners) {
267             listener.switchUpdated(nodeId);
268         }
269     }
270
271     @Override
272     public void close() throws Exception {
273         nodeListener.close();
274         ofOverlayNodeListener.close();
275         nodeConnectorListener.close();
276     }
277
278     /**
279      * Internal representation of the state of a connected switch
280      */
281     protected static final class SwitchState {
282
283         private NodeId nodeId;
284         private FlowCapableNode fcNode;
285         private OfOverlayNodeConfig nodeConfig;
286         private Map<InstanceIdentifier<NodeConnector>, FlowCapableNodeConnector> fcncByNcIid = Maps.newHashMap();
287         private boolean hasEndpoints=false;
288
289
290         public boolean isHasEndpoints() {
291             return hasEndpoints;
292         }
293
294
295         public void setHasEndpoints(boolean hasEndpoints) {
296             this.hasEndpoints = hasEndpoints;
297         }
298
299         Map<Class<? extends TunnelTypeBase>, TunnelBuilder> tunnelBuilderByType = new HashMap<>();
300         Set<NodeConnectorId> externalPorts = new HashSet<>();
301
302         SwitchStatus status;
303
304         public SwitchState(NodeId switchNode) {
305             super();
306             nodeId = switchNode;
307         }
308
309         /**
310          * Constructor used for tests
311          */
312         public SwitchState(NodeId node, NodeConnectorId tunnelPort, Set<NodeConnectorId> externalPorts,
313                 OfOverlayNodeConfig nodeConfig) {
314             this.nodeId = node;
315             this.nodeConfig = nodeConfig;
316             update();
317             this.externalPorts = externalPorts;
318         }
319
320         private void update() {
321             tunnelBuilderByType = new HashMap<>();
322             externalPorts = new HashSet<>();
323             if (nodeConfig != null && nodeConfig.getExternalInterfaces() != null) {
324                 for (ExternalInterfaces nc : nodeConfig.getExternalInterfaces()) {
325                     externalPorts.add(nc.getNodeConnectorId());
326                 }
327             }
328             if (nodeConfig != null && nodeConfig.getTunnel() != null) {
329                 for (Tunnel tunnel : nodeConfig.getTunnel()) {
330                     TunnelBuilder tunnelBuilder = tunnelBuilderByType.get(tunnel.getTunnelType());
331                     if (tunnelBuilder == null) {
332                         tunnelBuilder = new TunnelBuilder();
333                         tunnelBuilderByType.put(tunnel.getTunnelType(), tunnelBuilder);
334                     }
335                     if (tunnel.getIp() != null) {
336                         tunnelBuilder.setIp(tunnel.getIp());
337                     }
338                     if (tunnel.getNodeConnectorId() != null) {
339                         tunnelBuilder.setNodeConnectorId(tunnel.getNodeConnectorId());
340                     }
341                     if (tunnel.getPort() != null) {
342                         tunnelBuilder.setPort(tunnel.getPort());
343                     }
344                 }
345             }
346             for (Entry<InstanceIdentifier<NodeConnector>, FlowCapableNodeConnector> fcncByNcIidEntry : fcncByNcIid.entrySet()) {
347                 FlowCapableNodeConnector fcnc = fcncByNcIidEntry.getValue();
348                 if (fcnc.getName() == null) {
349                     continue;
350                 }
351                 InstanceIdentifier<NodeConnector> ncIid = fcncByNcIidEntry.getKey();
352                 NodeConnectorId ncId = ncIid.firstKeyOf(NodeConnector.class, NodeConnectorKey.class).getId();
353                 if (fcnc.getName().matches(".*(vxlan-).*")) {
354                     TunnelBuilder tunnelBuilder = tunnelBuilderByType.get(TunnelTypeVxlan.class);
355                     if (tunnelBuilder == null) {
356                         tunnelBuilder = new TunnelBuilder().setTunnelType(TunnelTypeVxlan.class);
357                         tunnelBuilderByType.put(TunnelTypeVxlan.class, tunnelBuilder);
358                     }
359                     tunnelBuilder.setNodeConnectorId(ncId);
360                 } else if (fcnc.getName().matches(".*(vxlangpe-).*")) {
361                     TunnelBuilder tunnelBuilder = tunnelBuilderByType.get(TunnelTypeVxlanGpe.class);
362                     if (tunnelBuilder == null) {
363                         tunnelBuilder = new TunnelBuilder().setTunnelType(TunnelTypeVxlanGpe.class);
364                         tunnelBuilderByType.put(TunnelTypeVxlanGpe.class, tunnelBuilder);
365                     }
366                     tunnelBuilder.setNodeConnectorId(ncId);
367                 }
368             }
369         }
370
371         private void updateStatus() {
372             boolean tunnelWithIpAndNcExists = tunnelWithIpAndNcExists();
373             if (fcNode != null) {
374                 if (tunnelWithIpAndNcExists && isHasEndpoints()) {
375                     setStatus(SwitchStatus.READY);
376                 } else {
377                     setStatus(SwitchStatus.PREPARING);
378                 }
379             } else {
380                 setStatus(SwitchStatus.DISCONNECTED);
381             }
382         }
383
384         private void setStatus(SwitchStatus newStatus) {
385             if (Objects.equal(status, newStatus)) {
386                 return;
387             }
388             LOG.debug("Switch {} is changing status from {} to {}", nodeId.getValue(), this.status, newStatus);
389             this.status = newStatus;
390         }
391
392         private boolean tunnelWithIpAndNcExists() {
393             if (tunnelBuilderByType.isEmpty()) {
394                 LOG.trace("No tunnel on switch {}", nodeId.getValue());
395                 return false;
396             }
397             LOG.trace("Iterating over tunnel till tunnel with IP and node-connector is not found.");
398             for (TunnelBuilder tb : tunnelBuilderByType.values()) {
399                 if (tb.getIp() != null && tb.getNodeConnectorId() != null) {
400                     LOG.trace("Tunnel {} found.",tb.toString());
401                     return true;
402                 } else {
403                     LOG.trace("Tunnel is not complete for node: {}", nodeId.getValue());
404                 }
405             }
406             return false;
407         }
408
409         public boolean isConfigurationEmpty() {
410             if (fcNode != null)
411                 return false;
412             if (nodeConfig != null)
413                 return false;
414             if (!fcncByNcIid.isEmpty())
415                 return false;
416             return true;
417         }
418
419         public void setFlowCapableNode(FlowCapableNode fcNode) {
420             this.fcNode = fcNode;
421             LOG.trace("Switch {} set {}", nodeId.getValue(), fcNode);
422             updateStatus();
423         }
424
425         public void setConfig(OfOverlayNodeConfig config) {
426             this.nodeConfig = config;
427             LOG.trace("Switch {} set {}", nodeId.getValue(), config);
428             update();
429             updateStatus();
430         }
431
432         public void setNodeConnectorConfig(InstanceIdentifier<NodeConnector> ncIid, FlowCapableNodeConnector fcnc) {
433             if (fcnc == null) {
434                 fcncByNcIid.remove(ncIid);
435             } else {
436                 fcncByNcIid.put(ncIid, fcnc);
437             }
438             LOG.trace("Switch {} node connector {} set {}", nodeId.getValue(),
439                     ncIid.firstKeyOf(NodeConnector.class, NodeConnectorKey.class).getId().getValue(), fcnc);
440             update();
441             updateStatus();
442         }
443
444     }
445
446     protected enum SwitchStatus {
447         /**
448          * The switch is not currently connected
449          */
450         DISCONNECTED,
451         /**
452          * The switch is connected but not yet configured
453          */
454         PREPARING,
455         /**
456          * The switch is ready to for policy rules to be installed
457          */
458         READY
459     }
460
461
462
463 }