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