Merge "Bug 2013 - Vlan flows needs merging from traditional rules to a single L2Fwdin...
[netvirt.git] / openstack / net-virt-providers / src / main / java / org / opendaylight / ovsdb / openstack / netvirt / providers / openflow13 / OF13Provider.java
1 /**
2  * Copyright (C) 2013 Red Hat, Inc.
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  * Authors : Madhu Venugopal, Brent Salisbury, Dave Tucker
9  */
10 package org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13;
11
12 import java.net.InetAddress;
13 import java.util.List;
14 import java.util.Map;
15 import java.util.Set;
16 import java.util.concurrent.ExecutionException;
17
18 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
19 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
20 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
21 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
22 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
23 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
24 import org.opendaylight.controller.networkconfig.neutron.NeutronNetwork;
25 import org.opendaylight.controller.networkconfig.neutron.NeutronSecurityGroup;
26 import org.opendaylight.controller.sal.core.Node;
27 import org.opendaylight.controller.sal.utils.HexEncode;
28 import org.opendaylight.controller.sal.utils.Status;
29 import org.opendaylight.controller.sal.utils.StatusCode;
30 import org.opendaylight.ovsdb.lib.notation.Row;
31 import org.opendaylight.ovsdb.lib.notation.UUID;
32 import org.opendaylight.ovsdb.openstack.netvirt.NetworkHandler;
33 import org.opendaylight.ovsdb.openstack.netvirt.api.BridgeConfigurationManager;
34 import org.opendaylight.ovsdb.openstack.netvirt.api.ClassifierProvider;
35 import org.opendaylight.ovsdb.openstack.netvirt.api.Constants;
36 import org.opendaylight.ovsdb.openstack.netvirt.api.EgressAclProvider;
37 import org.opendaylight.ovsdb.openstack.netvirt.api.IngressAclProvider;
38 import org.opendaylight.ovsdb.openstack.netvirt.api.L2ForwardingProvider;
39 import org.opendaylight.ovsdb.openstack.netvirt.api.NetworkingProvider;
40 import org.opendaylight.ovsdb.openstack.netvirt.api.SecurityServicesManager;
41 import org.opendaylight.ovsdb.openstack.netvirt.api.TenantNetworkManager;
42 import org.opendaylight.ovsdb.plugin.api.OvsdbConfigurationService;
43 import org.opendaylight.ovsdb.plugin.api.OvsdbConnectionService;
44 import org.opendaylight.ovsdb.plugin.api.StatusWithUuid;
45 import org.opendaylight.ovsdb.schema.openvswitch.Bridge;
46 import org.opendaylight.ovsdb.schema.openvswitch.Interface;
47 import org.opendaylight.ovsdb.schema.openvswitch.Port;
48 import org.opendaylight.ovsdb.utils.mdsal.openflow.InstructionUtils;
49 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Uri;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.GroupActionCase;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.GroupActionCaseBuilder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.OutputActionCase;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.OutputActionCaseBuilder;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.group.action._case.GroupActionBuilder;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.output.action._case.OutputActionBuilder;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.ActionBuilder;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.ActionKey;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.InstructionsBuilder;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.ApplyActionsCase;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.ApplyActionsCaseBuilder;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.apply.actions._case.ApplyActionsBuilder;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionBuilder;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionKey;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.BucketId;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupId;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupTypes;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.Buckets;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.BucketsBuilder;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.buckets.Bucket;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.buckets.BucketBuilder;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.buckets.BucketKey;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupBuilder;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupKey;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
90 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
91 import org.slf4j.Logger;
92 import org.slf4j.LoggerFactory;
93
94 import com.google.common.base.Optional;
95 import com.google.common.base.Preconditions;
96 import com.google.common.collect.Lists;
97 import com.google.common.collect.Maps;
98 import com.google.common.util.concurrent.CheckedFuture;
99
100 /**
101  * Open vSwitch OpenFlow 1.3 Networking Provider for OpenStack Neutron
102  */
103 public class OF13Provider implements NetworkingProvider {
104     private static final Logger logger = LoggerFactory.getLogger(OF13Provider.class);
105     private DataBroker dataBroker;
106     private static final short TABLE_0_DEFAULT_INGRESS = 0;
107     private static final short TABLE_1_ISOLATE_TENANT = 10;
108     private static final short TABLE_2_LOCAL_FORWARD = 20;
109     private static final String OPENFLOW = "openflow:";
110     private static Long groupId = 1L;
111
112     private volatile org.opendaylight.ovsdb.openstack.netvirt.api.ConfigurationService configurationService;
113     private volatile BridgeConfigurationManager bridgeConfigurationManager;
114     private volatile TenantNetworkManager tenantNetworkManager;
115     private volatile OvsdbConfigurationService ovsdbConfigurationService;
116     private volatile OvsdbConnectionService connectionService;
117     private volatile MdsalConsumer mdsalConsumer;
118     private volatile SecurityServicesManager securityServicesManager;
119     private volatile IngressAclProvider ingressAclProvider;
120     private volatile EgressAclProvider egressAclProvider;
121     private volatile ClassifierProvider classifierProvider;
122     private volatile L2ForwardingProvider l2ForwardingProvider;
123
124     public static final String NAME = "OF13Provider";
125
126     public OF13Provider(){
127
128     }
129
130     @Override
131     public String getName() {
132         return NAME;
133     }
134
135     @Override
136     public boolean supportsServices() {
137         return true;
138     }
139
140     @Override
141     public boolean hasPerTenantTunneling() {
142         return false;
143     }
144
145     private Status getTunnelReadinessStatus (Node node, String tunnelKey) {
146         InetAddress srcTunnelEndPoint = configurationService.getTunnelEndPoint(node);
147         if (srcTunnelEndPoint == null) {
148             logger.error("Tunnel Endpoint not configured for Node {}", node);
149             return new Status(StatusCode.NOTFOUND, "Tunnel Endpoint not configured for "+ node);
150         }
151
152         if (!bridgeConfigurationManager.isNodeNeutronReady(node)) {
153             logger.error(node+" is not Overlay ready");
154             return new Status(StatusCode.NOTACCEPTABLE, node+" is not Overlay ready");
155         }
156
157         if (!tenantNetworkManager.isTenantNetworkPresentInNode(node, tunnelKey)) {
158             logger.debug(node+" has no VM corresponding to segment "+ tunnelKey);
159             return new Status(StatusCode.NOTACCEPTABLE, node+" has no VM corresponding to segment "+ tunnelKey);
160         }
161         return new Status(StatusCode.SUCCESS);
162     }
163
164     private String getTunnelName(String tunnelType, InetAddress dst) {
165         return tunnelType+"-"+dst.getHostAddress();
166     }
167
168     private boolean isTunnelPresent(Node node, String tunnelName, String bridgeUUID) throws Exception {
169         Preconditions.checkNotNull(ovsdbConfigurationService);
170         Row bridgeRow = ovsdbConfigurationService
171                 .getRow(node, ovsdbConfigurationService.getTableName(node, Bridge.class), bridgeUUID);
172         Bridge bridge = ovsdbConfigurationService.getTypedRow(node, Bridge.class, bridgeRow);
173         if (bridge != null) {
174             Set<UUID> ports = bridge.getPortsColumn().getData();
175             for (UUID portUUID : ports) {
176                 Row portRow = ovsdbConfigurationService
177                         .getRow(node, ovsdbConfigurationService.getTableName(node, Port.class), portUUID.toString());
178                 Port port = ovsdbConfigurationService.getTypedRow(node, Port.class, portRow);
179                 if (port != null && tunnelName.equalsIgnoreCase(port.getName())) return true;
180             }
181         }
182         return false;
183     }
184
185     private String getPortUuid(Node node, String name, String bridgeUUID) throws Exception {
186         Preconditions.checkNotNull(ovsdbConfigurationService);
187         Row bridgeRow = ovsdbConfigurationService
188                 .getRow(node, ovsdbConfigurationService.getTableName(node, Bridge.class), bridgeUUID);
189         Bridge bridge = ovsdbConfigurationService.getTypedRow(node, Bridge.class, bridgeRow);
190         if (bridge != null) {
191             Set<UUID> ports = bridge.getPortsColumn().getData();
192             for (UUID portUUID : ports) {
193                 Row portRow = ovsdbConfigurationService
194                         .getRow(node, ovsdbConfigurationService.getTableName(node, Port.class), portUUID.toString());
195                 Port port = ovsdbConfigurationService.getTypedRow(node, Port.class, portRow);
196                 if (port != null && name.equalsIgnoreCase(port.getName())) return portUUID.toString();
197             }
198         }
199         return null;
200     }
201
202     private Status addTunnelPort (Node node, String tunnelType, InetAddress src, InetAddress dst) {
203         Preconditions.checkNotNull(ovsdbConfigurationService);
204         try {
205             String bridgeUUID = null;
206             String tunnelBridgeName = configurationService.getIntegrationBridgeName();
207             Map<String, Row> bridgeTable = ovsdbConfigurationService.getRows(node, ovsdbConfigurationService.getTableName(node, Bridge.class));
208             if (bridgeTable != null) {
209                 for (String uuid : bridgeTable.keySet()) {
210                     Bridge bridge = ovsdbConfigurationService.getTypedRow(node,Bridge.class, bridgeTable.get(uuid));
211                     if (bridge.getName().equals(tunnelBridgeName)) {
212                         bridgeUUID = uuid;
213                         break;
214                     }
215                 }
216             }
217             if (bridgeUUID == null) {
218                 logger.error("Could not find Bridge {} in {}", tunnelBridgeName, node);
219                 return new Status(StatusCode.NOTFOUND, "Could not find "+tunnelBridgeName+" in "+node);
220             }
221             String portName = getTunnelName(tunnelType, dst);
222
223             if (this.isTunnelPresent(node, portName, bridgeUUID)) {
224                 logger.trace("Tunnel {} is present in {} of {}", portName, tunnelBridgeName, node);
225                 return new Status(StatusCode.SUCCESS);
226             }
227
228             Port tunnelPort = ovsdbConfigurationService.createTypedRow(node, Port.class);
229             tunnelPort.setName(portName);
230             StatusWithUuid statusWithUuid = ovsdbConfigurationService
231                     .insertRow(node, ovsdbConfigurationService.getTableName(node, Port.class), bridgeUUID, tunnelPort.getRow());
232             if (!statusWithUuid.isSuccess()) {
233                 logger.error("Failed to insert Tunnel port {} in {}", portName, bridgeUUID);
234                 return statusWithUuid;
235             }
236
237             String tunnelPortUUID = statusWithUuid.getUuid().toString();
238             String interfaceUUID = null;
239             int timeout = 6;
240             while ((interfaceUUID == null) && (timeout > 0)) {
241                 Row portRow = ovsdbConfigurationService
242                         .getRow(node, ovsdbConfigurationService.getTableName(node, Port.class), tunnelPortUUID);
243                 tunnelPort = ovsdbConfigurationService.getTypedRow(node, Port.class, portRow);
244                 Set<UUID> interfaces = tunnelPort.getInterfacesColumn().getData();
245                 if (interfaces == null || interfaces.size() == 0) {
246                     // Wait for the OVSDB update to sync up the Local cache.
247                     Thread.sleep(500);
248                     timeout--;
249                     continue;
250                 }
251                 interfaceUUID = interfaces.toArray()[0].toString();
252                 Row intfRow = ovsdbConfigurationService
253                         .getRow(node, ovsdbConfigurationService.getTableName(node, Interface.class), interfaceUUID);
254                 Interface intf = ovsdbConfigurationService.getTypedRow(node, Interface.class, intfRow);
255                 if (intf == null) interfaceUUID = null;
256             }
257
258             if (interfaceUUID == null) {
259                 logger.error("Cannot identify Tunnel Interface for port {}/{}", portName, tunnelPortUUID);
260                 return new Status(StatusCode.INTERNALERROR);
261             }
262
263             Interface tunInterface = ovsdbConfigurationService.createTypedRow(node, Interface.class);
264             tunInterface.setType(tunnelType);
265             Map<String, String> options = Maps.newHashMap();
266             options.put("key", "flow");
267             options.put("local_ip", src.getHostAddress());
268             options.put("remote_ip", dst.getHostAddress());
269             tunInterface.setOptions(options);
270             Status status = ovsdbConfigurationService
271                     .updateRow(node, ovsdbConfigurationService.getTableName(node, Interface.class), tunnelPortUUID, interfaceUUID, tunInterface.getRow());
272             logger.debug("Tunnel {} add status : {}", tunInterface, status);
273             return status;
274         } catch (Exception e) {
275             logger.error("Exception in addTunnelPort", e);
276             return new Status(StatusCode.INTERNALERROR);
277         }
278     }
279
280     /* delete port from ovsdb port table */
281     private Status deletePort(Node node, String bridgeName, String portName) {
282         Preconditions.checkNotNull(ovsdbConfigurationService);
283         try {
284             String bridgeUUID = null;
285             Map<String, Row> bridgeTable = ovsdbConfigurationService.getRows(node, ovsdbConfigurationService.getTableName(node, Bridge.class));
286             if (bridgeTable != null) {
287                 for (String uuid : bridgeTable.keySet()) {
288                     Bridge bridge = ovsdbConfigurationService.getTypedRow(node, Bridge.class, bridgeTable.get(uuid));
289                     if (bridge.getName().equals(bridgeName)) {
290                         bridgeUUID = uuid;
291                         break;
292                     }
293                 }
294             }
295             if (bridgeUUID == null) {
296                 logger.debug("Could not find Bridge {} in {}", bridgeName, node);
297                 return new Status(StatusCode.SUCCESS);
298             }
299
300             String portUUID = this.getPortUuid(node, portName, bridgeUUID);
301             Status status = new Status(StatusCode.SUCCESS);
302             if (portUUID != null) {
303                 status = ovsdbConfigurationService
304                         .deleteRow(node, ovsdbConfigurationService.getTableName(node, Port.class), portUUID);
305                 if (!status.isSuccess()) {
306                     logger.error("Failed to delete port {} in {} status : {}", portName, bridgeUUID,
307                             status);
308                     return status;
309                 }
310                 logger.debug("Port {} delete status : {}", portName, status);
311             }
312             return status;
313         } catch (Exception e) {
314             logger.error("Exception in deletePort", e);
315             return new Status(StatusCode.INTERNALERROR);
316         }
317     }
318
319     private Status deleteTunnelPort(Node node, String tunnelType, InetAddress src, InetAddress dst) {
320         String tunnelBridgeName = configurationService.getIntegrationBridgeName();
321         String portName = getTunnelName(tunnelType, dst);
322         return deletePort(node, tunnelBridgeName, portName);
323     }
324
325     private Status deletePhysicalPort(Node node, String phyIntfName) {
326         String intBridgeName = configurationService.getIntegrationBridgeName();
327         return deletePort(node, intBridgeName, phyIntfName);
328     }
329
330     private void programLocalBridgeRules(Node node, Long dpid, String segmentationId, String attachedMac, long localPort) {
331         /*
332          * Table(0) Rule #3
333          * ----------------
334          * Match: VM sMac and Local Ingress Port
335          * Action:Action: Set Tunnel ID and GOTO Local Table (5)
336          */
337
338         handleLocalInPort(dpid, TABLE_0_DEFAULT_INGRESS, TABLE_1_ISOLATE_TENANT, segmentationId, localPort, attachedMac, true);
339
340         /*
341          * Table(0) Rule #4
342          * ----------------
343          * Match: Drop any remaining Ingress Local VM Packets
344          * Action: Drop w/ a low priority
345          */
346
347         handleDropSrcIface(dpid, localPort, true);
348
349         /*
350          * Table(2) Rule #1
351          * ----------------
352          * Match: Match TunID and Destination DL/dMAC Addr
353          * Action: Output Port
354          * table=2,tun_id=0x5,dl_dst=00:00:00:00:00:01 actions=output:2
355          */
356
357         handleLocalUcastOut(dpid, TABLE_2_LOCAL_FORWARD, segmentationId, localPort, attachedMac, true);
358
359         /*
360          * Table(2) Rule #2
361          * ----------------
362          * Match: Tunnel ID and dMAC (::::FF:FF)
363          * table=2,priority=16384,tun_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
364          * actions=output:2,3,4,5
365          */
366
367         handleLocalBcastOut(dpid, TABLE_2_LOCAL_FORWARD, segmentationId, localPort, true);
368         handleTunnelFloodOut(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD, segmentationId, localPort, true);
369
370         /*
371          * TODO : Optimize the following 2 writes to be restricted only for the very first port known in a segment.
372          */
373         /*
374          * Table(1) Rule #3
375          * ----------------
376          * Match:  Any remaining Ingress Local VM Packets
377          * Action: Drop w/ a low priority
378          * -------------------------------------------
379          * table=1,priority=8192,tun_id=0x5 actions=goto_table:2
380          */
381
382         handleTunnelMiss(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD, segmentationId, true);
383
384         /*
385          * Table(2) Rule #3
386          * ----------------
387          * Match: Any Remaining Flows w/a TunID
388          * Action: Drop w/ a low priority
389          * table=2,priority=8192,tun_id=0x5 actions=drop
390          */
391
392         handleLocalTableMiss(dpid, TABLE_2_LOCAL_FORWARD, segmentationId, true);
393     }
394
395     private void removeLocalBridgeRules(Node node, Long dpid, String segmentationId, String attachedMac, long localPort) {
396         /*
397          * Table(0) Rule #3
398          * ----------------
399          * Match: VM sMac and Local Ingress Port
400          * Action:Action: Set Tunnel ID and GOTO Local Table (5)
401          */
402
403         handleLocalInPort(dpid, TABLE_0_DEFAULT_INGRESS, TABLE_1_ISOLATE_TENANT, segmentationId, localPort, attachedMac, false);
404
405         /*
406          * Table(0) Rule #4
407          * ----------------
408          * Match: Drop any remaining Ingress Local VM Packets
409          * Action: Drop w/ a low priority
410          */
411
412         handleDropSrcIface(dpid, localPort, false);
413
414         /*
415          * Table(2) Rule #1
416          * ----------------
417          * Match: Match TunID and Destination DL/dMAC Addr
418          * Action: Output Port
419          * table=2,tun_id=0x5,dl_dst=00:00:00:00:00:01 actions=output:2
420          */
421
422         handleLocalUcastOut(dpid, TABLE_2_LOCAL_FORWARD, segmentationId, localPort, attachedMac, false);
423
424         /*
425          * Table(2) Rule #2
426          * ----------------
427          * Match: Tunnel ID and dMAC (::::FF:FF)
428          * table=2,priority=16384,tun_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
429          * actions=output:2,3,4,5
430          */
431
432         handleLocalBcastOut(dpid, TABLE_2_LOCAL_FORWARD, segmentationId, localPort, false);
433         handleTunnelFloodOut(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD, segmentationId, localPort, false);
434     }
435
436     private void programLocalIngressTunnelBridgeRules(Node node, Long dpid, String segmentationId, String attachedMac, long tunnelOFPort, long localPort) {
437         /*
438          * Table(0) Rule #2
439          * ----------------
440          * Match: Ingress Port, Tunnel ID
441          * Action: GOTO Local Table (20)
442          */
443
444         handleTunnelIn(dpid, TABLE_0_DEFAULT_INGRESS, TABLE_2_LOCAL_FORWARD, segmentationId, tunnelOFPort, true);
445
446         /*
447          * Table(1) Rule #2
448          * ----------------
449          * Match: Match Tunnel ID and L2 ::::FF:FF Flooding
450          * Action: Flood to selected destination TEPs
451          * -------------------------------------------
452          * table=1,priority=16384,tun_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
453          * actions=output:10,output:11,goto_table:2
454          */
455
456         handleTunnelFloodOut(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD, segmentationId, tunnelOFPort, true);
457
458     }
459
460     private void programRemoteEgressTunnelBridgeRules(Node node, Long dpid, String segmentationId, String attachedMac, long tunnelOFPort, long localPort) {
461         /*
462          * Table(1) Rule #1
463          * ----------------
464          * Match: Drop any remaining Ingress Local VM Packets
465          * Action: Drop w/ a low priority
466          * -------------------------------------------
467          * table=1,tun_id=0x5,dl_dst=00:00:00:00:00:08 \
468          * actions=output:11,goto_table:2
469          */
470
471         handleTunnelOut(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD, segmentationId, tunnelOFPort, attachedMac, true);
472     }
473
474     private void removeRemoteEgressTunnelBridgeRules(Node node, Long dpid, String segmentationId, String attachedMac, long tunnelOFPort, long localPort) {
475         /*
476          * Table(1) Rule #1
477          * ----------------
478          * Match: Drop any remaining Ingress Local VM Packets
479          * Action: Drop w/ a low priority
480          * -------------------------------------------
481          * table=1,tun_id=0x5,dl_dst=00:00:00:00:00:08 \
482          * actions=output:11,goto_table:2
483          */
484
485         handleTunnelOut(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD, segmentationId, tunnelOFPort, attachedMac, false);
486     }
487
488     /* Remove tunnel rules if last node in this tenant network */
489     private void removePerTunnelRules(Node node, Long dpid, String segmentationId, long tunnelOFPort) {
490         /*
491          * TODO : Optimize the following 2 writes to be restricted only for the very first port known in a segment.
492          */
493         /*
494          * Table(1) Rule #3
495          * ----------------
496          * Match:  Any remaining Ingress Local VM Packets
497          * Action: Drop w/ a low priority
498          * -------------------------------------------
499          * table=1,priority=8192,tun_id=0x5 actions=goto_table:2
500          */
501
502         handleTunnelMiss(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD, segmentationId, false);
503
504         /*
505          * Table(2) Rule #3
506          * ----------------
507          * Match: Any Remaining Flows w/a TunID
508          * Action: Drop w/ a low priority
509          * table=2,priority=8192,tun_id=0x5 actions=drop
510          */
511
512         handleLocalTableMiss(dpid, TABLE_2_LOCAL_FORWARD, segmentationId, false);
513
514         /*
515          * Table(0) Rule #2
516          * ----------------
517          * Match: Ingress Port, Tunnel ID
518          * Action: GOTO Local Table (10)
519          */
520
521         handleTunnelIn(dpid, TABLE_0_DEFAULT_INGRESS, TABLE_2_LOCAL_FORWARD, segmentationId, tunnelOFPort, false);
522
523         /*
524          * Table(1) Rule #2
525          * ----------------
526          * Match: Match Tunnel ID and L2 ::::FF:FF Flooding
527          * Action: Flood to selected destination TEPs
528          * -------------------------------------------
529          * table=1,priority=16384,tun_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
530          * actions=output:10,output:11,goto_table:2
531          */
532
533         handleTunnelFloodOut(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD, segmentationId, tunnelOFPort, false);
534     }
535
536     private void programLocalVlanRules(Node node, Long dpid, String segmentationId, String attachedMac, long localPort) {
537         /*
538          * Table(0) Rule #1
539          * ----------------
540          * Tag traffic coming from the local port and vm srcmac
541          * Match: VM sMac and Local Ingress Port
542          * Action: Set VLAN ID and GOTO Local Table 1
543          */
544
545         handleLocalInPortSetVlan(dpid, TABLE_0_DEFAULT_INGRESS,
546                 TABLE_1_ISOLATE_TENANT, segmentationId, localPort,
547                 attachedMac, true);
548
549         /*
550          * Table(0) Rule #3
551          * ----------------
552          * Drop all other traffic coming from the local port
553          * Match: Drop any remaining Ingress Local VM Packets
554          * Action: Drop w/ a low priority
555          */
556
557         handleDropSrcIface(dpid, localPort, true);
558
559         /*
560          * Table(2) Rule #1
561          * ----------------
562          * Forward unicast traffic destined to the local port after stripping tag
563          * Match: Match VLAN ID and Destination DL/dMAC Addr
564          * Action: strip vlan, output to local port
565          * Example: table=2,vlan_id=0x5,dl_dst=00:00:00:00:00:01 actions= strip vlan, output:2
566          */
567
568         handleLocalVlanUcastOut(dpid, TABLE_2_LOCAL_FORWARD, segmentationId,
569                 localPort, attachedMac, true);
570
571         /*
572          * Table(2) Rule #2
573          * ----------------
574          * Match: VLAN ID and dMAC (::::FF:FF)
575          * Action: strip vlan, output to all local ports in this vlan
576          * Example: table=2,priority=16384,vlan_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
577          * actions= strip_vlan, output:2,3,4,5
578          */
579
580         //handleLocalVlanBcastOut(dpid, TABLE_2_LOCAL_FORWARD, segmentationId,
581         //        localPort, ethPort, true);
582         //handleVlanFloodOut(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD,
583         //        segmentationId, localPort, ethport, true);
584
585         /*
586          * Table(2) Rule #3
587          * ----------------
588          * Match: Any Remaining Flows w/a VLAN ID
589          * Action: Drop w/ a low priority
590          * Example: table=2,priority=8192,vlan_id=0x5 actions=drop
591          */
592
593         //handleLocalVlanTableMiss(dpid, TABLE_2_LOCAL_FORWARD, segmentationId,
594         //        true);
595     }
596
597     private void removeLocalVlanRules(Node node, Long dpid,
598                                       String segmentationId, String attachedMac, long localPort) {
599         /*
600          * Table(0) Rule #1
601          * ----------------
602          * Match: VM sMac and Local Ingress Port
603          * Action: Set VLAN ID and GOTO Local Table 1
604          */
605
606         handleLocalInPortSetVlan(dpid, TABLE_0_DEFAULT_INGRESS,
607                 TABLE_1_ISOLATE_TENANT, segmentationId, localPort,
608                 attachedMac, false);
609
610         /*
611          * Table(0) Rule #3
612          * ----------------
613          * Match: Drop any remaining Ingress Local VM Packets
614          * Action: Drop w/ a low priority
615          */
616
617         handleDropSrcIface(dpid, localPort, false);
618
619         /*
620          * Table(2) Rule #1
621          * ----------------
622          * Match: Match VLAN ID and Destination DL/dMAC Addr
623          * Action: strip vlan, output to local port
624          * Example: table=2,vlan_id=0x5,dl_dst=00:00:00:00:00:01 actions= strip vlan, output:2
625          */
626
627         handleLocalVlanUcastOut(dpid, TABLE_2_LOCAL_FORWARD, segmentationId,
628                 localPort, attachedMac, false);
629
630         /*
631          * Table(2) Rule #2
632          * ----------------
633          * Match: VLAN ID and dMAC (::::FF:FF)
634          * Action: strip vlan, output to all local ports in this vlan
635          * Example: table=2,priority=16384,vlan_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
636          * actions= strip_vlan, output:2,3,4,5
637          */
638
639         //handleLocalVlanBcastOut(dpid, TABLE_2_LOCAL_FORWARD, segmentationId,
640         //        localPort, ethPort, false);
641         //handleVlanFloodOut(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD,
642         //        segmentationId, localPort, false);
643
644     }
645
646     private void programLocalIngressVlanRules(Node node, Long dpid, String segmentationId, String attachedMac,
647                                               long localPort, long ethPort) {
648         /*
649          * Table(0) Rule #2
650          * ----------------
651          * Match: Ingress port = physical interface, Vlan ID
652          * Action: GOTO Local Table 2
653          */
654
655         handleVlanIn(dpid, TABLE_0_DEFAULT_INGRESS, TABLE_2_LOCAL_FORWARD,
656                 segmentationId, ethPort, true);
657
658         /*
659          * Table(1) Rule #2
660          * ----------------
661          * Match: Match VLAN ID and L2 ::::FF:FF Flooding
662          * Action: Flood to local and remote VLAN members
663          * -------------------------------------------
664          * Example: table=1,priority=16384,vlan_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
665          * actions=output:10 (eth port),goto_table:2
666          * table=110, priority=16384,dl_vlan=2001,dl_dst=01:00:00:00:00:00/01:00:00:00:00:00 actions=output:2,pop_vlan,output:1,output:3,output:4
667          */
668
669         handleLocalVlanBcastOut(dpid, TABLE_2_LOCAL_FORWARD, segmentationId, localPort, ethPort, true);
670
671         /*
672          * Table(1) Rule #2
673          * ----------------
674          * Match: Match VLAN ID and L2 ::::FF:FF Flooding
675          * Action: Flood to local and remote VLAN members
676          * -------------------------------------------
677          * Example: table=1,priority=16384,vlan_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
678          * actions=output:10 (eth port),goto_table:2
679          */
680
681         //handleVlanFloodOut(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD,
682         //        segmentationId, ethPort, true);
683     }
684
685     private void programRemoteEgressVlanRules(Node node, Long dpid, String segmentationId,
686                                               String attachedMac, long ethPort) {
687         /*
688          * Table(1) Rule #1
689          * ----------------
690          * Match: Destination MAC is local VM MAC and vlan id
691          * Action: go to table 2
692          * -------------------------------------------
693          * Example: table=1,vlan_id=0x5,dl_dst=00:00:00:00:00:08 \
694          * actions=goto_table:2
695          */
696
697         //handleVlanOut(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD,
698         //        segmentationId, ethPort, attachedMac, true);
699
700         /*
701          * Table(1) Rule #3
702          * ----------------
703          * Match:  VLAN ID
704          * Action: Go to table 2
705          * -------------------------------------------
706          * Example: table=1,priority=8192,vlan_id=0x5 actions=output:1,goto_table:2
707          */
708
709         handleVlanMiss(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD,
710                 segmentationId, ethPort, true);
711     }
712
713     private void removeRemoteEgressVlanRules(Node node, Long dpid, String segmentationId,
714                                              String attachedMac, long ethPort) {
715         /*
716          * Table(1) Rule #1
717          * ----------------
718          * Match: Destination MAC is local VM MAC and vlan id
719          * Action: go to table 2
720          * -------------------------------------------
721          * Example: table=1,vlan_id=0x5,dl_dst=00:00:00:00:00:08 \
722          * actions=goto_table:2
723          */
724
725         //handleVlanOut(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD,
726         //        segmentationId, ethPort, attachedMac, false);
727     }
728
729     private void removePerVlanRules(Node node, Long dpid, String segmentationId, long localPort, long ethPort) {
730         /*
731          * Table(2) Rule #3
732          * ----------------
733          * Match: Any Remaining Flows w/a VLAN ID
734          * Action: Drop w/ a low priority
735          * Example: table=2,priority=8192,vlan_id=0x5 actions=drop
736          */
737
738         handleLocalVlanTableMiss(dpid, TABLE_2_LOCAL_FORWARD, segmentationId,
739                 false);
740
741         /*
742          * Table(0) Rule #2
743          * ----------------
744          * Match: Ingress port = physical interface, Vlan ID
745          * Action: GOTO Local Table 2
746          */
747
748         handleVlanIn(dpid, TABLE_0_DEFAULT_INGRESS, TABLE_2_LOCAL_FORWARD,
749                 segmentationId, ethPort, false);
750
751         /*
752          * Table(1) Rule #2
753          * ----------------
754          * Match: Match VLAN ID and L2 ::::FF:FF Flooding
755          * Action: Flood to local and remote VLAN members
756          * -------------------------------------------
757          * Example: table=1,priority=16384,vlan_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
758          * actions=output:10 (eth port),goto_table:2
759          * table=110, priority=16384,dl_vlan=2001,dl_dst=01:00:00:00:00:00/01:00:00:00:00:00 actions=output:2,pop_vlan,output:1,output:3,output:4
760          */
761
762         handleLocalVlanBcastOut(dpid, TABLE_2_LOCAL_FORWARD, segmentationId, localPort, ethPort, false);
763
764         /*
765          * Table(1) Rule #2
766          * ----------------
767          * Match: Match VLAN ID and L2 ::::FF:FF Flooding
768          * Action: Flood to local and remote VLAN members
769          * -------------------------------------------
770          * Example: table=1,priority=16384,vlan_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
771          * actions=output:10 (eth port),goto_table:2
772          */
773
774         //handleVlanFloodOut(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD,
775         //        segmentationId, ethPort, false);
776
777         /*
778          * Table(1) Rule #3
779          * ----------------
780          * Match:  VLAN ID
781          * Action: Go to table 2
782          * -------------------------------------------
783          * Example: table=1,priority=8192,vlan_id=0x5 actions=output:1,goto_table:2
784          */
785
786         handleVlanMiss(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD, segmentationId, ethPort, false);
787     }
788
789     private Long getDpid (Node node, String bridgeUuid) {
790         Preconditions.checkNotNull(ovsdbConfigurationService);
791         try {
792             Row bridgeRow =  ovsdbConfigurationService
793                     .getRow(node, ovsdbConfigurationService.getTableName(node, Bridge.class), bridgeUuid);
794             Bridge bridge = ovsdbConfigurationService.getTypedRow(node, Bridge.class, bridgeRow);
795             Set<String> dpids = bridge.getDatapathIdColumn().getData();
796             if (dpids == null || dpids.size() == 0) return 0L;
797             return HexEncode.stringToLong((String) dpids.toArray()[0]);
798         } catch (Exception e) {
799             logger.error("Error finding Bridge's OF DPID", e);
800             return 0L;
801         }
802     }
803
804     private Long getIntegrationBridgeOFDPID (Node node) {
805         try {
806             String bridgeName = configurationService.getIntegrationBridgeName();
807             String brIntId = this.getInternalBridgeUUID(node, bridgeName);
808             if (brIntId == null) {
809                 logger.error("Unable to spot Bridge Identifier for {} in {}", bridgeName, node);
810                 return 0L;
811             }
812
813             return getDpid(node, brIntId);
814         } catch (Exception e) {
815             logger.error("Error finding Integration Bridge's OF DPID", e);
816             return 0L;
817         }
818     }
819
820     private Long getExternalBridgeDpid (Node node) {
821         try {
822             String bridgeName = configurationService.getExternalBridgeName();
823             String brUuid = this.getInternalBridgeUUID(node, bridgeName);
824             if (brUuid == null) {
825                 logger.error("Unable to spot Bridge Identifier for {} in {}", bridgeName, node);
826                 return 0L;
827             }
828
829             return getDpid(node, brUuid);
830         } catch (Exception e) {
831             logger.error("Error finding External Bridge's OF DPID", e);
832             return 0L;
833         }
834     }
835
836     private void programLocalRules (String networkType, String segmentationId, Node node, Interface intf) {
837         try {
838             Long dpid = this.getIntegrationBridgeOFDPID(node);
839             if (dpid == 0L) {
840                 logger.debug("Openflow Datapath-ID not set for the integration bridge in {}", node);
841                 return;
842             }
843
844             Set<Long> of_ports = intf.getOpenFlowPortColumn().getData();
845             if (of_ports == null || of_ports.size() <= 0) {
846                 logger.debug("Could NOT Identify OF value for port {} on {}", intf.getName(), node);
847                 return;
848             }
849             long localPort = (Long)of_ports.toArray()[0];
850
851             Map<String, String> externalIds = intf.getExternalIdsColumn().getData();
852             if (externalIds == null) {
853                 logger.error("No external_ids seen in {}", intf);
854                 return;
855             }
856
857             String attachedMac = externalIds.get(Constants.EXTERNAL_ID_VM_MAC);
858             if (attachedMac == null) {
859                 logger.error("No AttachedMac seen in {}", intf);
860                 return;
861             }
862
863             /* Program local rules based on network type */
864             if (networkType.equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VLAN)) {
865                 logger.debug("Program local vlan rules for interface {}", intf.getName());
866                 programLocalVlanRules(node, dpid, segmentationId, attachedMac, localPort);
867             }
868             /* If the network type is tunnel based (VXLAN/GRRE/etc) with Neutron Port Security ACLs */
869             if ((networkType.equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_GRE) || networkType.equalsIgnoreCase
870                     (NetworkHandler.NETWORK_TYPE_VXLAN)) && securityServicesManager.isPortSecurityReady(intf)) {
871                 logger.debug("Neutron port has a Port Security Group");
872                 /* Retrieve the security group UUID from the Neutron Port */
873                 NeutronSecurityGroup securityGroupInPort = securityServicesManager.getSecurityGroupInPort(intf);
874                 logger.debug("Program Local rules for networkType: {} does contain a Port Security Group: {} " +
875                         "to be installed on DPID: {}", networkType, securityGroupInPort, dpid);
876                 ingressAclProvider.programPortSecurityACL(node, dpid, segmentationId, attachedMac, localPort,
877                         securityGroupInPort);
878                 egressAclProvider.programPortSecurityACL(node, dpid, segmentationId, attachedMac, localPort,
879                         securityGroupInPort);
880             }
881             if (networkType.equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_GRE) ||
882                     networkType.equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VXLAN)) {
883                 logger.debug("Program local bridge rules for interface {}", intf.getName());
884                 programLocalBridgeRules(node, dpid, segmentationId, attachedMac, localPort);
885             }
886         } catch (Exception e) {
887             logger.error("Exception in programming Local Rules for "+intf+" on "+node, e);
888         }
889     }
890
891     private void removeLocalRules (String networkType, String segmentationId, Node node, Interface intf) {
892         try {
893             Long dpid = this.getIntegrationBridgeOFDPID(node);
894             if (dpid == 0L) {
895                 logger.debug("Openflow Datapath-ID not set for the integration bridge in {}", node);
896                 return;
897             }
898
899             Set<Long> of_ports = intf.getOpenFlowPortColumn().getData();
900             if (of_ports == null || of_ports.size() <= 0) {
901                 logger.debug("Could NOT Identify OF value for port {} on {}", intf.getName(), node);
902                 return;
903             }
904             long localPort = (Long)of_ports.toArray()[0];
905
906             Map<String, String> externalIds = intf.getExternalIdsColumn().getData();
907             if (externalIds == null) {
908                 logger.error("No external_ids seen in {}", intf);
909                 return;
910             }
911
912             String attachedMac = externalIds.get(Constants.EXTERNAL_ID_VM_MAC);
913             if (attachedMac == null) {
914                 logger.error("No AttachedMac seen in {}", intf);
915                 return;
916             }
917
918             /* Program local rules based on network type */
919             if (networkType.equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VLAN)) {
920                 logger.debug("Remove local vlan rules for interface {}", intf.getName());
921                 removeLocalVlanRules(node, dpid, segmentationId, attachedMac, localPort);
922             } else if (networkType.equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_GRE) ||
923                     networkType.equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VXLAN)) {
924                 logger.debug("Remove local bridge rules for interface {}", intf.getName());
925                 removeLocalBridgeRules(node, dpid, segmentationId, attachedMac, localPort);
926             }
927         } catch (Exception e) {
928             logger.error("Exception in removing Local Rules for "+intf+" on "+node, e);
929         }
930     }
931
932     private void programTunnelRules (String tunnelType, String segmentationId, InetAddress dst, Node node,
933             Interface intf, boolean local) {
934
935         Preconditions.checkNotNull(ovsdbConfigurationService);
936
937         try {
938
939             Long dpid = this.getIntegrationBridgeOFDPID(node);
940             if (dpid == 0L) {
941                 logger.debug("Openflow Datapath-ID not set for the integration bridge in {}", node);
942                 return;
943             }
944
945             Set<Long> of_ports = intf.getOpenFlowPortColumn().getData();
946             if (of_ports == null || of_ports.size() <= 0) {
947                 logger.debug("Could NOT Identify OF value for port {} on {}", intf.getName(), node);
948                 return;
949             }
950             long localPort = (Long)of_ports.toArray()[0];
951
952             Map<String, String> externalIds = intf.getExternalIdsColumn().getData();
953             if (externalIds == null) {
954                 logger.error("No external_ids seen in {}", intf);
955                 return;
956             }
957
958             String attachedMac = externalIds.get(Constants.EXTERNAL_ID_VM_MAC);
959             if (attachedMac == null) {
960                 logger.error("No AttachedMac seen in {}", intf);
961                 return;
962             }
963
964             Map<String, Row> intfs = ovsdbConfigurationService.getRows(node, ovsdbConfigurationService.getTableName(node, Interface.class));
965             if (intfs != null) {
966                 for (Row row : intfs.values()) {
967                     Interface tunIntf = ovsdbConfigurationService.getTypedRow(node, Interface.class, row);
968                     if (tunIntf.getName().equals(this.getTunnelName(tunnelType, dst))) {
969                         of_ports = tunIntf.getOpenFlowPortColumn().getData();
970                         if (of_ports == null || of_ports.size() <= 0) {
971                             logger.debug("Could NOT Identify Tunnel port {} on {}", tunIntf.getName(), node);
972                             continue;
973                         }
974                         long tunnelOFPort = (Long)of_ports.toArray()[0];
975
976                         if (tunnelOFPort == -1) {
977                             logger.error("Could NOT Identify Tunnel port {} -> OF ({}) on {}", tunIntf.getName(), tunnelOFPort, node);
978                             return;
979                         }
980                         logger.debug("Identified Tunnel port {} -> OF ({}) on {}", tunIntf.getName(), tunnelOFPort, node);
981
982                         if (!local) {
983                             programRemoteEgressTunnelBridgeRules(node, dpid, segmentationId, attachedMac, tunnelOFPort, localPort);
984                         }
985                         logger.trace("program local ingress tunnel rules: node" + node.getNodeIDString() + " intf " + intf.getName());
986                         if (local) {
987                             programLocalIngressTunnelBridgeRules(node, dpid, segmentationId, attachedMac, tunnelOFPort, localPort);
988                         }
989                         return;
990                     }
991                 }
992             }
993         } catch (Exception e) {
994             logger.error("", e);
995         }
996     }
997
998     private void removeTunnelRules (String tunnelType, String segmentationId, InetAddress dst, Node node,
999             Interface intf, boolean local, boolean isLastInstanceOnNode) {
1000
1001         Preconditions.checkNotNull(ovsdbConfigurationService);
1002         try {
1003
1004             Long dpid = this.getIntegrationBridgeOFDPID(node);
1005             if (dpid == 0L) {
1006                 logger.debug("Openflow Datapath-ID not set for the integration bridge in {}", node);
1007                 return;
1008             }
1009
1010             Set<Long> of_ports = intf.getOpenFlowPortColumn().getData();
1011             if (of_ports == null || of_ports.size() <= 0) {
1012                 logger.error("Could NOT Identify OF value for port {} on {}", intf.getName(), node);
1013                 return;
1014             }
1015             long localPort = (Long)of_ports.toArray()[0];
1016
1017             Map<String, String> externalIds = intf.getExternalIdsColumn().getData();
1018             if (externalIds == null) {
1019                 logger.error("No external_ids seen in {}", intf);
1020                 return;
1021             }
1022
1023             String attachedMac = externalIds.get(Constants.EXTERNAL_ID_VM_MAC);
1024             if (attachedMac == null) {
1025                 logger.error("No AttachedMac seen in {}", intf);
1026                 return;
1027             }
1028
1029             Map<String, Row> intfs = ovsdbConfigurationService.getRows(node, ovsdbConfigurationService.getTableName(node, Interface.class));
1030             if (intfs != null) {
1031                 for (Row row : intfs.values()) {
1032                     Interface tunIntf = ovsdbConfigurationService.getTypedRow(node, Interface.class, row);
1033                     if (tunIntf.getName().equals(this.getTunnelName(tunnelType, dst))) {
1034                         of_ports = tunIntf.getOpenFlowPortColumn().getData();
1035                         if (of_ports == null || of_ports.size() <= 0) {
1036                             logger.error("Could NOT Identify Tunnel port {} on {}", tunIntf.getName(), node);
1037                             continue;
1038                         }
1039                         long tunnelOFPort = (Long)of_ports.toArray()[0];
1040
1041                         if (tunnelOFPort == -1) {
1042                             logger.error("Could NOT Identify Tunnel port {} -> OF ({}) on {}", tunIntf.getName(), tunnelOFPort, node);
1043                             return;
1044                         }
1045                         logger.debug("Identified Tunnel port {} -> OF ({}) on {}", tunIntf.getName(), tunnelOFPort, node);
1046
1047                         if (!local) {
1048                             removeRemoteEgressTunnelBridgeRules(node, dpid, segmentationId, attachedMac, tunnelOFPort, localPort);
1049                         }
1050                         if (local && isLastInstanceOnNode) {
1051                             removePerTunnelRules(node, dpid, segmentationId, tunnelOFPort);
1052                         }
1053                         return;
1054                     }
1055                 }
1056             }
1057         } catch (Exception e) {
1058             logger.error("", e);
1059         }
1060     }
1061
1062     private void programVlanRules (NeutronNetwork network, Node node, Interface intf) {
1063         Preconditions.checkNotNull(ovsdbConfigurationService);
1064         logger.debug("Program vlan rules for interface {}", intf.getName());
1065         try {
1066
1067             Long dpid = this.getIntegrationBridgeOFDPID(node);
1068             if (dpid == 0L) {
1069                 logger.debug("Openflow Datapath-ID not set for the integration bridge in {}", node);
1070                 return;
1071             }
1072
1073             Set<Long> of_ports = intf.getOpenFlowPortColumn().getData();
1074             int timeout = 6;
1075             while ((of_ports == null) && (timeout > 0)) {
1076                 of_ports = intf.getOpenFlowPortColumn().getData();
1077                 if (of_ports == null || of_ports.size() <= 0) {
1078                     // Wait for the OVSDB update to sync up the Local cache.
1079                     Thread.sleep(500);
1080                     timeout--;
1081                 }
1082             }
1083             if (of_ports == null || of_ports.size() <= 0) {
1084                 logger.error("Could NOT Identify OF value for port {} on {}", intf.getName(), node);
1085                 return;
1086             }
1087             long localPort = (Long)of_ports.toArray()[0];
1088
1089             Map<String, String> externalIds = intf.getExternalIdsColumn().getData();
1090             if (externalIds == null) {
1091                 logger.error("No external_ids seen in {}", intf);
1092                 return;
1093             }
1094
1095             String attachedMac = externalIds.get(Constants.EXTERNAL_ID_VM_MAC);
1096             if (attachedMac == null) {
1097                 logger.error("No AttachedMac seen in {}", intf);
1098                 return;
1099             }
1100
1101             Map<String, Row> intfs = ovsdbConfigurationService.getRows(node, ovsdbConfigurationService.getTableName(node, Interface.class));
1102             if (intfs != null) {
1103                 for (Row row : intfs.values()) {
1104                     Interface ethIntf = ovsdbConfigurationService.getTypedRow(node, Interface.class, row);
1105                     if (ethIntf.getName().equalsIgnoreCase(bridgeConfigurationManager.getPhysicalInterfaceName(node, network.getProviderPhysicalNetwork()))) {
1106                         of_ports = ethIntf.getOpenFlowPortColumn().getData();
1107                         timeout = 6;
1108                         while ((of_ports == null) && (timeout > 0)) {
1109                             of_ports = ethIntf.getOpenFlowPortColumn().getData();
1110                             if (of_ports == null || of_ports.size() <= 0) {
1111                                 // Wait for the OVSDB update to sync up the Local cache.
1112                                 Thread.sleep(500);
1113                                         timeout--;
1114                             }
1115                         }
1116
1117                         if (of_ports == null || of_ports.size() <= 0) {
1118                             logger.error("Could NOT Identify eth port {} on {}", ethIntf.getName(), node);
1119                             continue;
1120                         }
1121                         long ethOFPort = (Long)of_ports.toArray()[0];
1122
1123                         if (ethOFPort == -1) {
1124                             logger.error("Could NOT Identify eth port {} -> OF ({}) on {}", ethIntf.getName(), ethOFPort, node);
1125                             throw new Exception("port number < 0");
1126                         }
1127                         logger.debug("Identified eth port {} -> OF ({}) on {}", ethIntf.getName(), ethOFPort, node);
1128                         // TODO: add logic to only add rule on remote nodes
1129                         programRemoteEgressVlanRules(node, dpid, network.getProviderSegmentationID(), attachedMac, ethOFPort);
1130                         programLocalIngressVlanRules(node, dpid, network.getProviderSegmentationID(), attachedMac, localPort, ethOFPort);
1131                         return;
1132                     }
1133                 }
1134             }
1135         } catch (Exception e) {
1136             logger.error("", e);
1137         }
1138     }
1139
1140     private void removeVlanRules (NeutronNetwork network, Node node,
1141             Interface intf, boolean isLastInstanceOnNode) {
1142         Preconditions.checkNotNull(ovsdbConfigurationService);
1143         logger.debug("Remove vlan rules for interface {}", intf.getName());
1144
1145         try {
1146
1147             Long dpid = this.getIntegrationBridgeOFDPID(node);
1148             if (dpid == 0L) {
1149                 logger.debug("Openflow Datapath-ID not set for the integration bridge in {}", node);
1150                 return;
1151             }
1152
1153             Set<Long> of_ports = intf.getOpenFlowPortColumn().getData();
1154             if (of_ports == null || of_ports.size() <= 0) {
1155                 logger.error("Could NOT Identify OF value for port {} on {}", intf.getName(), node);
1156                 return;
1157             }
1158             long localPort = (Long)of_ports.toArray()[0];
1159
1160             Map<String, String> externalIds = intf.getExternalIdsColumn().getData();
1161             if (externalIds == null) {
1162                 logger.error("No external_ids seen in {}", intf);
1163                 return;
1164             }
1165
1166             String attachedMac = externalIds.get(Constants.EXTERNAL_ID_VM_MAC);
1167             if (attachedMac == null) {
1168                 logger.error("No AttachedMac seen in {}", intf);
1169                 return;
1170             }
1171
1172             Map<String, Row> intfs = ovsdbConfigurationService.getRows(node, ovsdbConfigurationService.getTableName(node, Interface.class));
1173             if (intfs != null) {
1174                 for (Row row : intfs.values()) {
1175                     Interface ethIntf = ovsdbConfigurationService.getTypedRow(node, Interface.class, row);
1176                     if (ethIntf.getName().equalsIgnoreCase(bridgeConfigurationManager.getPhysicalInterfaceName(node,
1177                             network.getProviderPhysicalNetwork()))) {
1178                         of_ports = ethIntf.getOpenFlowPortColumn().getData();
1179                         if (of_ports == null || of_ports.size() <= 0) {
1180                             logger.error("Could NOT Identify eth port {} on {}", ethIntf.getName(), node);
1181                             continue;
1182                         }
1183                         long ethOFPort = (Long)of_ports.toArray()[0];
1184
1185                         if (ethOFPort == -1) {
1186                             logger.error("Could NOT Identify eth port {} -> OF ({}) on {}", ethIntf.getName(), ethOFPort, node);
1187                             throw new Exception("port number < 0");
1188                         }
1189                         logger.debug("Identified eth port {} -> OF ({}) on {}", ethIntf.getName(), ethOFPort, node);
1190
1191                         removeRemoteEgressVlanRules(node, dpid, network.getProviderSegmentationID(), attachedMac, ethOFPort);
1192                         if (isLastInstanceOnNode) {
1193                             removePerVlanRules(node, dpid, network.getProviderSegmentationID(), localPort, ethOFPort);
1194                         }
1195                         return;
1196                     }
1197                 }
1198             }
1199         } catch (Exception e) {
1200             logger.error("", e);
1201         }
1202     }
1203
1204     @Override
1205     public Status handleInterfaceUpdate(NeutronNetwork network, Node srcNode, Interface intf) {
1206         Preconditions.checkNotNull(connectionService);
1207         List<Node> nodes = connectionService.getNodes();
1208         nodes.remove(srcNode);
1209         this.programLocalRules(network.getProviderNetworkType(), network.getProviderSegmentationID(), srcNode, intf);
1210
1211         if (network.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VLAN)) {
1212             this.programVlanRules(network, srcNode, intf);
1213         } else if (network.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_GRE)
1214                 || network.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VXLAN)){
1215             for (Node dstNode : nodes) {
1216                 InetAddress src = configurationService.getTunnelEndPoint(srcNode);
1217                 InetAddress dst = configurationService.getTunnelEndPoint(dstNode);
1218                 Status status = addTunnelPort(srcNode, network.getProviderNetworkType(), src, dst);
1219                 if (status.isSuccess()) {
1220                     this.programTunnelRules(network.getProviderNetworkType(), network.getProviderSegmentationID(), dst, srcNode, intf, true);
1221                 }
1222                 addTunnelPort(dstNode, network.getProviderNetworkType(), dst, src);
1223                 if (status.isSuccess()) {
1224                     this.programTunnelRules(network.getProviderNetworkType(), network.getProviderSegmentationID(), src, dstNode, intf, false);
1225                 }
1226             }
1227         }
1228
1229         return new Status(StatusCode.SUCCESS);
1230     }
1231
1232     private Status triggerInterfaceUpdates(Node node) {
1233         Preconditions.checkNotNull(ovsdbConfigurationService);
1234         try {
1235             Map<String, Row> intfs = ovsdbConfigurationService.getRows(node, ovsdbConfigurationService.getTableName(node, Interface.class));
1236             if (intfs != null) {
1237                 for (Row row : intfs.values()) {
1238                     Interface intf = ovsdbConfigurationService.getTypedRow(node, Interface.class, row);
1239                     NeutronNetwork network = tenantNetworkManager.getTenantNetwork(intf);
1240                     logger.debug("Trigger Interface update for {}", intf);
1241                     if (network != null) {
1242                         this.handleInterfaceUpdate(network, node, intf);
1243                     }
1244                 }
1245             }
1246         } catch (Exception e) {
1247             logger.error("Error Triggering the lost interface updates for "+ node, e);
1248             return new Status(StatusCode.INTERNALERROR, e.getLocalizedMessage());
1249         }
1250         return new Status(StatusCode.SUCCESS);
1251     }
1252     @Override
1253     public Status handleInterfaceUpdate(String tunnelType, String tunnelKey) {
1254         // TODO Auto-generated method stub
1255         return null;
1256     }
1257
1258     @Override
1259     public Status handleInterfaceDelete(String tunnelType, NeutronNetwork network, Node srcNode, Interface intf,
1260             boolean isLastInstanceOnNode) {
1261         Preconditions.checkNotNull(connectionService);
1262         Status status = new Status(StatusCode.SUCCESS);
1263         List<Node> nodes = connectionService.getNodes();
1264         nodes.remove(srcNode);
1265
1266         logger.info("Delete intf " + intf.getName() + " isLastInstanceOnNode " + isLastInstanceOnNode);
1267         List<String> phyIfName = bridgeConfigurationManager.getAllPhysicalInterfaceNames(srcNode);
1268         if (intf.getTypeColumn().getData().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VXLAN)
1269                 || intf.getTypeColumn().getData().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_GRE)) {
1270             /* Delete tunnel port */
1271             try {
1272                 Map<String, String> options = intf.getOptionsColumn().getData();
1273                 InetAddress src = InetAddress.getByName(options.get("local_ip"));
1274                 InetAddress dst = InetAddress.getByName(options.get("remote_ip"));
1275                 status = deleteTunnelPort(srcNode, intf.getTypeColumn().getData(), src, dst);
1276             } catch (Exception e) {
1277                 logger.error(e.getMessage(), e);
1278             }
1279         } else if (phyIfName.contains(intf.getName())) {
1280             deletePhysicalPort(srcNode, intf.getName());
1281         } else {
1282             /* delete all other interfaces */
1283             this.removeLocalRules(network.getProviderNetworkType(), network.getProviderSegmentationID(),
1284                     srcNode, intf);
1285
1286             if (network.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VLAN)) {
1287                 this.removeVlanRules(network, srcNode,
1288                         intf, isLastInstanceOnNode);
1289             } else if (network.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_GRE)
1290                     || network.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VXLAN)) {
1291
1292                 for (Node dstNode : nodes) {
1293                     InetAddress src = configurationService.getTunnelEndPoint(srcNode);
1294                     InetAddress dst = configurationService.getTunnelEndPoint(dstNode);
1295                     logger.info("Remove tunnel rules for interface " + intf.getName() + " on srcNode " + srcNode.getNodeIDString());
1296                     this.removeTunnelRules(tunnelType, network.getProviderSegmentationID(),
1297                             dst, srcNode, intf, true, isLastInstanceOnNode);
1298                     logger.info("Remove tunnel rules for interface " + intf.getName() + " on dstNode " + dstNode.getNodeIDString());
1299                     this.removeTunnelRules(tunnelType, network.getProviderSegmentationID(),
1300                             src, dstNode, intf, false, isLastInstanceOnNode);
1301                 }
1302             }
1303         }
1304         return status;
1305     }
1306
1307     @Override
1308     public void initializeFlowRules(Node node) {
1309         this.initializeFlowRules(node, configurationService.getIntegrationBridgeName());
1310         this.initializeFlowRules(node, configurationService.getExternalBridgeName());
1311         this.triggerInterfaceUpdates(node);
1312     }
1313
1314     private void initializeFlowRules(Node node, String bridgeName) {
1315         String bridgeUuid = this.getInternalBridgeUUID(node, bridgeName);
1316         if (bridgeUuid == null) {
1317             return;
1318         }
1319
1320         Long dpid = getDpid(node, bridgeUuid);
1321
1322         if (dpid == 0L) {
1323             logger.debug("Openflow Datapath-ID not set for the integration bridge in {}", node);
1324             return;
1325         }
1326
1327         /*
1328          * Table(0) Rule #1
1329          * ----------------
1330          * Match: LLDP (0x88CCL)
1331          * Action: Packet_In to Controller Reserved Port
1332          */
1333
1334         writeLLDPRule(dpid);
1335         if (bridgeName.equals(configurationService.getExternalBridgeName())) {
1336             writeNormalRule(dpid);
1337         }
1338     }
1339
1340     /*
1341      * Create an LLDP Flow Rule to encapsulate into
1342      * a packet_in that is sent to the controller
1343      * for topology handling.
1344      * Match: Ethertype 0x88CCL
1345      * Action: Punt to Controller in a Packet_In msg
1346      */
1347
1348     private void writeLLDPRule(Long dpidLong) {
1349         classifierProvider.programLLDPPuntRule(dpidLong);
1350     }
1351
1352     /*
1353      * Create a NORMAL Table Miss Flow Rule
1354      * Match: any
1355      * Action: forward to NORMAL pipeline
1356      */
1357
1358     private void writeNormalRule(Long dpidLong) {
1359
1360         String nodeName = OPENFLOW + dpidLong;
1361
1362         MatchBuilder matchBuilder = new MatchBuilder();
1363         NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
1364         FlowBuilder flowBuilder = new FlowBuilder();
1365
1366         // Create the OF Actions and Instructions
1367         InstructionBuilder ib = new InstructionBuilder();
1368         InstructionsBuilder isb = new InstructionsBuilder();
1369
1370         // Instructions List Stores Individual Instructions
1371         List<Instruction> instructions = Lists.newArrayList();
1372
1373         // Call the InstructionBuilder Methods Containing Actions
1374         InstructionUtils.createNormalInstructions(ib);
1375         ib.setOrder(0);
1376         ib.setKey(new InstructionKey(0));
1377         instructions.add(ib.build());
1378
1379         // Add InstructionBuilder to the Instruction(s)Builder List
1380         isb.setInstruction(instructions);
1381
1382         // Add InstructionsBuilder to FlowBuilder
1383         flowBuilder.setInstructions(isb.build());
1384
1385         String flowId = "NORMAL";
1386         flowBuilder.setId(new FlowId(flowId));
1387         FlowKey key = new FlowKey(new FlowId(flowId));
1388         flowBuilder.setMatch(matchBuilder.build());
1389         flowBuilder.setPriority(0);
1390         flowBuilder.setBarrier(true);
1391         flowBuilder.setTableId((short) 0);
1392         flowBuilder.setKey(key);
1393         flowBuilder.setFlowName(flowId);
1394         flowBuilder.setHardTimeout(0);
1395         flowBuilder.setIdleTimeout(0);
1396         writeFlow(flowBuilder, nodeBuilder);
1397     }
1398
1399     /*
1400      * (Table:0) Ingress Tunnel Traffic
1401      * Match: OpenFlow InPort and Tunnel ID
1402      * Action: GOTO Local Table (10)
1403      * table=0,tun_id=0x5,in_port=10, actions=goto_table:2
1404      */
1405
1406     private void handleTunnelIn(Long dpidLong, Short writeTable,
1407             Short goToTableId, String segmentationId,
1408             Long ofPort, boolean write) {
1409         classifierProvider.programTunnelIn(dpidLong, segmentationId, ofPort, write);
1410     }
1411
1412     /*
1413      * (Table:0) Ingress VLAN Traffic
1414      * Match: OpenFlow InPort and vlan ID
1415      * Action: GOTO Local Table (20)
1416      * table=0,vlan_id=0x5,in_port=10, actions=goto_table:2
1417      */
1418
1419     private void handleVlanIn(Long dpidLong, Short writeTable, Short goToTableId,
1420             String segmentationId,  Long ethPort, boolean write) {
1421         classifierProvider.programVlanIn(dpidLong, segmentationId, ethPort, write);
1422     }
1423
1424     /*
1425      * (Table:0) Egress VM Traffic Towards TEP
1426      * Match: Destination Ethernet Addr and OpenFlow InPort
1427      * Instruction: Set TunnelID and GOTO Table Tunnel Table (n)
1428      * table=0,in_port=2,dl_src=00:00:00:00:00:01 \
1429      * actions=set_field:5->tun_id,goto_table=1"
1430      */
1431
1432     private void handleLocalInPort(Long dpidLong, Short writeTable, Short goToTableId,
1433             String segmentationId, Long inPort, String attachedMac,
1434             boolean write) {
1435         classifierProvider.programLocalInPort(dpidLong, segmentationId, inPort, attachedMac, write);
1436     }
1437
1438     /*
1439      * (Table:0) Egress VM Traffic Towards TEP
1440      * Match: Source Ethernet Addr and OpenFlow InPort
1441      * Instruction: Set VLANID and GOTO Table Egress (n)
1442      * table=0,in_port=2,dl_src=00:00:00:00:00:01 \
1443      * actions=push_vlan, set_field:5->vlan_id,goto_table=1"
1444      */
1445
1446     private void handleLocalInPortSetVlan(Long dpidLong, Short writeTable,
1447             Short goToTableId, String segmentationId,
1448             Long inPort, String attachedMac,
1449             boolean write) {
1450         classifierProvider.programLocalInPortSetVlan(dpidLong, segmentationId, inPort, attachedMac, write);
1451     }
1452
1453     /*
1454      * (Table:0) Drop frames source from a VM that do not
1455      * match the associated MAC address of the local VM.
1456      * Match: Low priority anything not matching the VM SMAC
1457      * Instruction: Drop
1458      * table=0,priority=16384,in_port=1 actions=drop"
1459      */
1460
1461     private void handleDropSrcIface(Long dpidLong, Long inPort, boolean write) {
1462         classifierProvider.programDropSrcIface(dpidLong, inPort, write);
1463     }
1464
1465     /*
1466      * (Table:1) Egress Tunnel Traffic
1467      * Match: Destination Ethernet Addr and Local InPort
1468      * Instruction: Set TunnelID and GOTO Table Tunnel Table (n)
1469      * table=1,tun_id=0x5,dl_dst=00:00:00:00:00:08 \
1470      * actions=output:10,goto_table:2"
1471      */
1472     private void handleTunnelOut(Long dpidLong, Short writeTable,
1473             Short goToTableId, String segmentationId,
1474             Long OFPortOut, String attachedMac,
1475             boolean write) {
1476         l2ForwardingProvider.programTunnelOut(dpidLong, segmentationId, OFPortOut, attachedMac, write);
1477     }
1478
1479     /*
1480      * (Table:1) Egress VLAN Traffic
1481      * Match: Destination Ethernet Addr and VLAN id
1482      * Instruction: GOTO Table Table 2
1483      * table=1,vlan_id=0x5,dl_dst=00:00:00:00:00:08 \
1484      * actions= goto_table:2"
1485      */
1486
1487     private void handleVlanOut(Long dpidLong, Short writeTable,
1488             Short goToTableId, String segmentationId,
1489             Long ethPort, String attachedMac, boolean write) {
1490         l2ForwardingProvider.programVlanOut(dpidLong, segmentationId, ethPort, attachedMac, write);
1491     }
1492
1493     /*
1494      * (Table:1) Egress Tunnel Traffic
1495      * Match: Destination Ethernet Addr and Local InPort
1496      * Instruction: Set TunnelID and GOTO Table Tunnel Table (n)
1497      * table=1,priority=16384,tun_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
1498      * actions=output:10,output:11,goto_table:2
1499      */
1500
1501     private void handleTunnelFloodOut(Long dpidLong, Short writeTable,
1502             Short localTable, String segmentationId,
1503             Long OFPortOut, boolean write) {
1504         l2ForwardingProvider.programTunnelFloodOut(dpidLong, segmentationId, OFPortOut, write);
1505     }
1506
1507     /*
1508      * (Table:1) Egress VLAN Traffic
1509      * Match: Destination Ethernet Addr and VLAN id
1510      * Instruction: GOTO table 2 and Output port eth interface
1511      * Example: table=1,priority=16384,vlan_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
1512      * actions=output:eth1,goto_table:2
1513      */
1514
1515     private void handleVlanFloodOut(Long dpidLong, Short writeTable,
1516             Short localTable, String segmentationId,
1517             Long localPort, Long ethPort, boolean write) {
1518         //l2ForwardingProvider.programVlanFloodOut(dpidLong, segmentationId, localPort, ethPort, write);
1519     }
1520
1521     /*
1522      * (Table:1) Table Drain w/ Catch All
1523      * Match: Tunnel ID
1524      * Action: GOTO Local Table (10)
1525      * table=2,priority=8192,tun_id=0x5 actions=drop
1526      */
1527
1528     private void handleTunnelMiss(Long dpidLong, Short writeTable,
1529             Short goToTableId, String segmentationId,
1530             boolean write) {
1531         l2ForwardingProvider.programTunnelMiss(dpidLong, segmentationId, write);
1532     }
1533
1534
1535     /*
1536      * (Table:1) Table Drain w/ Catch All
1537      * Match: Vlan ID
1538      * Action: Output port eth interface
1539      * table=1,priority=8192,vlan_id=0x5 actions= output port:eth1
1540      */
1541
1542     private void handleVlanMiss(Long dpidLong, Short writeTable,
1543             Short goToTableId, String segmentationId,
1544             Long ethPort, boolean write) {
1545         l2ForwardingProvider.programVlanMiss(dpidLong, segmentationId, ethPort, write);
1546     }
1547
1548     /*
1549      * (Table:1) Local Broadcast Flood
1550      * Match: Tunnel ID and dMAC
1551      * Action: Output Port
1552      * table=2,tun_id=0x5,dl_dst=00:00:00:00:00:01 actions=output:2
1553      */
1554
1555     private void handleLocalUcastOut(Long dpidLong, Short writeTable,
1556             String segmentationId, Long localPort,
1557             String attachedMac, boolean write) {
1558         l2ForwardingProvider.programLocalUcastOut(dpidLong, segmentationId, localPort, attachedMac, write);
1559     }
1560
1561     /*
1562      * (Table:2) Local VLAN unicast
1563      * Match: VLAN ID and dMAC
1564      * Action: Output Port
1565      * table=2,vlan_id=0x5,dl_dst=00:00:00:00:00:01 actions=output:2
1566      */
1567
1568     private void handleLocalVlanUcastOut(Long dpidLong, Short writeTable,
1569             String segmentationId, Long localPort,
1570             String attachedMac, boolean write) {
1571         l2ForwardingProvider.programLocalVlanUcastOut(dpidLong, segmentationId, localPort, attachedMac, write);
1572     }
1573
1574     /*
1575      * (Table:2) Local Broadcast Flood
1576      * Match: Tunnel ID and dMAC (::::FF:FF)
1577      * table=2,priority=16384,tun_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
1578      * actions=output:2,3,4,5
1579      */
1580
1581     private void handleLocalBcastOut(Long dpidLong, Short writeTable,
1582             String segmentationId, Long localPort,
1583             boolean write) {
1584         l2ForwardingProvider.programLocalBcastOut(dpidLong, segmentationId, localPort, write);
1585     }
1586
1587     /*
1588      * (Table:2) Local VLAN Broadcast Flood
1589      * Match: vlan ID and dMAC (::::FF:FF)
1590      * table=2,priority=16384,vlan_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
1591      * actions=strip_vlan, output:2,3,4,5
1592      */
1593
1594     private void handleLocalVlanBcastOut(Long dpidLong, Short writeTable,
1595             String segmentationId, Long localPort, Long ethPort,
1596             boolean write) {
1597         l2ForwardingProvider.programLocalVlanBcastOut(dpidLong, segmentationId, localPort, ethPort, write);
1598     }
1599
1600     /*
1601      * (Table:1) Local Table Miss
1602      * Match: Any Remaining Flows w/a TunID
1603      * Action: Drop w/ a low priority
1604      * table=2,priority=8192,tun_id=0x5 actions=drop
1605      */
1606
1607     private void handleLocalTableMiss(Long dpidLong, Short writeTable,
1608             String segmentationId, boolean write) {
1609         l2ForwardingProvider.programLocalTableMiss(dpidLong, segmentationId, write);
1610     }
1611
1612     /*
1613      * (Table:1) Local Table Miss
1614      * Match: Any Remaining Flows w/a VLAN ID
1615      * Action: Drop w/ a low priority
1616      * table=2,priority=8192,vlan_id=0x5 actions=drop
1617      */
1618
1619     private void handleLocalVlanTableMiss(Long dpidLong, Short writeTable,
1620             String segmentationId, boolean write) {
1621         l2ForwardingProvider.programLocalVlanTableMiss(dpidLong, segmentationId, write);
1622     }
1623
1624     private Group getGroup(GroupBuilder groupBuilder, NodeBuilder nodeBuilder) {
1625         Preconditions.checkNotNull(mdsalConsumer);
1626         if (mdsalConsumer == null) {
1627             logger.error("ERROR finding MDSAL Service. Its possible that writeFlow is called too soon ?");
1628             return null;
1629         }
1630
1631         dataBroker = mdsalConsumer.getDataBroker();
1632         if (dataBroker == null) {
1633             logger.error("ERROR finding reference for DataBroker. Please check MD-SAL support on the Controller.");
1634             return null;
1635         }
1636
1637         InstanceIdentifier<Group> path1 = InstanceIdentifier.builder(Nodes.class).child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory
1638                 .rev130819.nodes.Node.class, nodeBuilder.getKey()).augmentation(FlowCapableNode.class).child(Group.class,
1639                         new GroupKey(groupBuilder.getGroupId())).build();
1640         ReadOnlyTransaction readTx = dataBroker.newReadOnlyTransaction();
1641         try {
1642             Optional<Group> data = readTx.read(LogicalDatastoreType.CONFIGURATION, path1).get();
1643             if (data.isPresent()) {
1644                 return data.get();
1645             }
1646         } catch (InterruptedException|ExecutionException e) {
1647             logger.error(e.getMessage(), e);
1648         }
1649
1650         logger.debug("Cannot find data for Group " + groupBuilder.getGroupName());
1651         return null;
1652     }
1653
1654     private void writeGroup(GroupBuilder groupBuilder, NodeBuilder nodeBuilder) {
1655         Preconditions.checkNotNull(mdsalConsumer);
1656         if (mdsalConsumer == null) {
1657             logger.error("ERROR finding MDSAL Service. Its possible that writeFlow is called too soon ?");
1658             return;
1659         }
1660
1661         dataBroker = mdsalConsumer.getDataBroker();
1662         if (dataBroker == null) {
1663             logger.error("ERROR finding reference for DataBroker. Please check MD-SAL support on the Controller.");
1664             return;
1665         }
1666
1667         ReadWriteTransaction modification = dataBroker.newReadWriteTransaction();
1668         InstanceIdentifier<Group> path1 = InstanceIdentifier.builder(Nodes.class).child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory
1669                 .rev130819.nodes.Node.class, nodeBuilder.getKey()).augmentation(FlowCapableNode.class).child(Group.class,
1670                         new GroupKey(groupBuilder.getGroupId())).build();
1671         modification.put(LogicalDatastoreType.CONFIGURATION, path1, groupBuilder.build(), true /*createMissingParents*/);
1672
1673         CheckedFuture<Void, TransactionCommitFailedException> commitFuture = modification.submit();
1674         try {
1675             commitFuture.get();  // TODO: Make it async (See bug 1362)
1676             logger.debug("Transaction success for write of Group "+groupBuilder.getGroupName());
1677         } catch (InterruptedException|ExecutionException e) {
1678             logger.error(e.getMessage(), e);
1679         }
1680     }
1681
1682     private void removeGroup(GroupBuilder groupBuilder, NodeBuilder nodeBuilder) {
1683         Preconditions.checkNotNull(mdsalConsumer);
1684         if (mdsalConsumer == null) {
1685             logger.error("ERROR finding MDSAL Service. Its possible that writeFlow is called too soon ?");
1686             return;
1687         }
1688
1689         dataBroker = mdsalConsumer.getDataBroker();
1690         if (dataBroker == null) {
1691             logger.error("ERROR finding reference for DataBroker. Please check MD-SAL support on the Controller.");
1692             return;
1693         }
1694
1695         WriteTransaction modification = dataBroker.newWriteOnlyTransaction();
1696         InstanceIdentifier<Group> path1 = InstanceIdentifier.builder(Nodes.class).child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory
1697                 .rev130819.nodes.Node.class, nodeBuilder.getKey()).augmentation(FlowCapableNode.class).child(Group.class,
1698                         new GroupKey(groupBuilder.getGroupId())).build();
1699         modification.delete(LogicalDatastoreType.CONFIGURATION, path1);
1700         CheckedFuture<Void, TransactionCommitFailedException> commitFuture = modification.submit();
1701
1702         try {
1703             commitFuture.get();  // TODO: Make it async (See bug 1362)
1704             logger.debug("Transaction success for deletion of Group "+groupBuilder.getGroupName());
1705         } catch (InterruptedException|ExecutionException e) {
1706             logger.error(e.getMessage(), e);
1707         }
1708     }
1709     private Flow getFlow(FlowBuilder flowBuilder, NodeBuilder nodeBuilder) {
1710         Preconditions.checkNotNull(mdsalConsumer);
1711         if (mdsalConsumer == null) {
1712             logger.error("ERROR finding MDSAL Service. Its possible that writeFlow is called too soon ?");
1713             return null;
1714         }
1715
1716         dataBroker = mdsalConsumer.getDataBroker();
1717         if (dataBroker == null) {
1718             logger.error("ERROR finding reference for DataBroker. Please check MD-SAL support on the Controller.");
1719             return null;
1720         }
1721
1722         InstanceIdentifier<Flow> path1 = InstanceIdentifier.builder(Nodes.class).child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory
1723                 .rev130819.nodes.Node.class, nodeBuilder.getKey()).augmentation(FlowCapableNode.class).child(Table.class,
1724                         new TableKey(flowBuilder.getTableId())).child(Flow.class, flowBuilder.getKey()).build();
1725
1726         ReadOnlyTransaction readTx = dataBroker.newReadOnlyTransaction();
1727         try {
1728             Optional<Flow> data = readTx.read(LogicalDatastoreType.CONFIGURATION, path1).get();
1729             if (data.isPresent()) {
1730                 return data.get();
1731             }
1732         } catch (InterruptedException|ExecutionException e) {
1733             logger.error(e.getMessage(), e);
1734         }
1735
1736         logger.debug("Cannot find data for Flow " + flowBuilder.getFlowName());
1737         return null;
1738     }
1739
1740     private void writeFlow(FlowBuilder flowBuilder, NodeBuilder nodeBuilder) {
1741         Preconditions.checkNotNull(mdsalConsumer);
1742         if (mdsalConsumer == null) {
1743             logger.error("ERROR finding MDSAL Service. Its possible that writeFlow is called too soon ?");
1744             return;
1745         }
1746
1747         dataBroker = mdsalConsumer.getDataBroker();
1748         if (dataBroker == null) {
1749             logger.error("ERROR finding reference for DataBroker. Please check MD-SAL support on the Controller.");
1750             return;
1751         }
1752
1753         ReadWriteTransaction modification = dataBroker.newReadWriteTransaction();
1754         InstanceIdentifier<Flow> path1 = InstanceIdentifier.builder(Nodes.class).child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory
1755                 .rev130819.nodes.Node.class, nodeBuilder.getKey()).augmentation(FlowCapableNode.class).child(Table.class,
1756                         new TableKey(flowBuilder.getTableId())).child(Flow.class, flowBuilder.getKey()).build();
1757
1758         //modification.put(LogicalDatastoreType.OPERATIONAL, path1, flowBuilder.build());
1759         modification.put(LogicalDatastoreType.CONFIGURATION, path1, flowBuilder.build(), true /*createMissingParents*/);
1760
1761
1762         CheckedFuture<Void, TransactionCommitFailedException> commitFuture = modification.submit();
1763         try {
1764             commitFuture.get();  // TODO: Make it async (See bug 1362)
1765             logger.debug("Transaction success for write of Flow "+flowBuilder.getFlowName());
1766         } catch (InterruptedException|ExecutionException e) {
1767             logger.error(e.getMessage(), e);
1768         }
1769     }
1770
1771     private void removeFlow(FlowBuilder flowBuilder, NodeBuilder nodeBuilder) {
1772         Preconditions.checkNotNull(mdsalConsumer);
1773         if (mdsalConsumer == null) {
1774             logger.error("ERROR finding MDSAL Service.");
1775             return;
1776         }
1777
1778         dataBroker = mdsalConsumer.getDataBroker();
1779         if (dataBroker == null) {
1780             logger.error("ERROR finding reference for DataBroker. Please check MD-SAL support on the Controller.");
1781             return;
1782         }
1783
1784         WriteTransaction modification = dataBroker.newWriteOnlyTransaction();
1785         InstanceIdentifier<Flow> path1 = InstanceIdentifier.builder(Nodes.class)
1786                 .child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory
1787                         .rev130819.nodes.Node.class, nodeBuilder.getKey())
1788                         .augmentation(FlowCapableNode.class).child(Table.class,
1789                                 new TableKey(flowBuilder.getTableId())).child(Flow.class, flowBuilder.getKey()).build();
1790         //modification.delete(LogicalDatastoreType.OPERATIONAL, nodeBuilderToInstanceId(nodeBuilder));
1791         //modification.delete(LogicalDatastoreType.OPERATIONAL, path1);
1792         //modification.delete(LogicalDatastoreType.CONFIGURATION, nodeBuilderToInstanceId(nodeBuilder));
1793         modification.delete(LogicalDatastoreType.CONFIGURATION, path1);
1794
1795         CheckedFuture<Void, TransactionCommitFailedException> commitFuture = modification.submit();
1796         try {
1797             commitFuture.get();  // TODO: Make it async (See bug 1362)
1798             logger.debug("Transaction success for deletion of Flow "+flowBuilder.getFlowName());
1799         } catch (InterruptedException|ExecutionException e) {
1800             logger.error(e.getMessage(), e);
1801         }
1802     }
1803
1804     /**
1805      * Create Output Port Group Instruction
1806      *
1807      * @param ib       Map InstructionBuilder without any instructions
1808      * @param dpidLong Long the datapath ID of a switch/node
1809      * @param port     Long representing a port on a switch/node
1810      * @return ib InstructionBuilder Map with instructions
1811      */
1812     protected InstructionBuilder createOutputGroupInstructions(NodeBuilder nodeBuilder,
1813             InstructionBuilder ib,
1814             Long dpidLong, Long port ,
1815             List<Instruction> instructions) {
1816         NodeConnectorId ncid = new NodeConnectorId(OPENFLOW + dpidLong + ":" + port);
1817         logger.debug("createOutputGroupInstructions() Node Connector ID is - Type=openflow: DPID={} port={} existingInstructions={}", dpidLong, port, instructions);
1818
1819         List<Action> actionList = Lists.newArrayList();
1820         ActionBuilder ab = new ActionBuilder();
1821
1822         List<Action> existingActions;
1823         if (instructions != null) {
1824             for (Instruction in : instructions) {
1825                 if (in.getInstruction() instanceof ApplyActionsCase) {
1826                     existingActions = (((ApplyActionsCase) in.getInstruction()).getApplyActions().getAction());
1827                     actionList.addAll(existingActions);
1828                 }
1829             }
1830         }
1831
1832         GroupBuilder groupBuilder = new GroupBuilder();
1833         Group group = null;
1834
1835         /* Create output action for this port*/
1836         OutputActionBuilder oab = new OutputActionBuilder();
1837         oab.setOutputNodeConnector(ncid);
1838         ab.setAction(new OutputActionCaseBuilder().setOutputAction(oab.build()).build());
1839         logger.debug("createOutputGroupInstructions(): output action {}", ab.build());
1840         boolean addNew = true;
1841         boolean groupActionAdded = false;
1842
1843         /* Find the group action and get the group */
1844         for (Action action : actionList) {
1845             if (action.getAction() instanceof GroupActionCase) {
1846                 groupActionAdded = true;
1847                 GroupActionCase groupAction = (GroupActionCase) action.getAction();
1848                 Long id = groupAction.getGroupAction().getGroupId();
1849                 String groupName = groupAction.getGroupAction().getGroup();
1850                 GroupKey key = new GroupKey(new GroupId(id));
1851
1852                 groupBuilder.setGroupId(new GroupId(id));
1853                 groupBuilder.setGroupName(groupName);
1854                 groupBuilder.setGroupType(GroupTypes.GroupAll);
1855                 groupBuilder.setKey(key);
1856                 group = getGroup(groupBuilder, nodeBuilder);
1857                 logger.debug("createOutputGroupInstructions: group {}", group);
1858                 break;
1859             }
1860         }
1861
1862         logger.debug("createOutputGroupInstructions: groupActionAdded {}", groupActionAdded);
1863         if (groupActionAdded) {
1864             /* modify the action bucket in group */
1865             groupBuilder = new GroupBuilder(group);
1866             Buckets buckets = groupBuilder.getBuckets();
1867             for (Bucket bucket : buckets.getBucket()) {
1868                 List<Action> bucketActions = bucket.getAction();
1869                 logger.debug("createOutputGroupInstructions: bucketActions {}", bucketActions);
1870                 for (Action action : bucketActions) {
1871                     if (action.getAction() instanceof OutputActionCase) {
1872                         OutputActionCase opAction = (OutputActionCase)action.getAction();
1873                         /* If output port action already in the action list of one of the buckets, skip */
1874                         if (opAction.getOutputAction().getOutputNodeConnector().equals(new Uri(ncid))) {
1875                             addNew = false;
1876                             break;
1877                         }
1878                     }
1879                 }
1880             }
1881             logger.debug("createOutputGroupInstructions: addNew {}", addNew);
1882             if (addNew) {
1883                 /* the new output action is not in the bucket, add to bucket */
1884                 if (!buckets.getBucket().isEmpty()) {
1885                     Bucket bucket = buckets.getBucket().get(0);
1886                     List<Action> bucketActionList = Lists.newArrayList();
1887                     bucketActionList.addAll(bucket.getAction());
1888                     /* set order for new action and add to action list */
1889                     ab.setOrder(bucketActionList.size());
1890                     ab.setKey(new ActionKey(bucketActionList.size()));
1891                     bucketActionList.add(ab.build());
1892
1893                     /* set bucket and buckets list. Reset groupBuilder with new buckets.*/
1894                     BucketsBuilder bucketsBuilder = new BucketsBuilder();
1895                     List<Bucket> bucketList = Lists.newArrayList();
1896                     BucketBuilder bucketBuilder = new BucketBuilder();
1897                     bucketBuilder.setBucketId(new BucketId((long) 1));
1898                     bucketBuilder.setKey(new BucketKey(new BucketId((long) 1)));
1899                     bucketBuilder.setAction(bucketActionList);
1900                     bucketList.add(bucketBuilder.build());
1901                     bucketsBuilder.setBucket(bucketList);
1902                     groupBuilder.setBuckets(bucketsBuilder.build());
1903                     logger.debug("createOutputGroupInstructions: bucketList {}", bucketList);
1904                 }
1905             }
1906         } else {
1907             /* create group */
1908             groupBuilder = new GroupBuilder();
1909             groupBuilder.setGroupType(GroupTypes.GroupAll);
1910             groupBuilder.setGroupId(new GroupId(groupId));
1911             groupBuilder.setKey(new GroupKey(new GroupId(groupId)));
1912             groupBuilder.setGroupName("Output port group " + groupId);
1913             groupBuilder.setBarrier(false);
1914
1915             BucketsBuilder bucketBuilder = new BucketsBuilder();
1916             List<Bucket> bucketList = Lists.newArrayList();
1917             BucketBuilder bucket = new BucketBuilder();
1918             bucket.setBucketId(new BucketId((long) 1));
1919             bucket.setKey(new BucketKey(new BucketId((long) 1)));
1920
1921             /* put output action to the bucket */
1922             List<Action> bucketActionList = Lists.newArrayList();
1923             /* set order for new action and add to action list */
1924             ab.setOrder(bucketActionList.size());
1925             ab.setKey(new ActionKey(bucketActionList.size()));
1926             bucketActionList.add(ab.build());
1927
1928             bucket.setAction(bucketActionList);
1929             bucketList.add(bucket.build());
1930             bucketBuilder.setBucket(bucketList);
1931             groupBuilder.setBuckets(bucketBuilder.build());
1932
1933             /* Add new group action */
1934             GroupActionBuilder groupActionB = new GroupActionBuilder();
1935             groupActionB.setGroupId(groupId);
1936             groupActionB.setGroup("Output port group " + groupId);
1937             ab = new ActionBuilder();
1938             ab.setAction(new GroupActionCaseBuilder().setGroupAction(groupActionB.build()).build());
1939             ab.setOrder(actionList.size());
1940             ab.setKey(new ActionKey(actionList.size()));
1941             actionList.add(ab.build());
1942
1943             groupId++;
1944         }
1945         logger.debug("createOutputGroupInstructions: group {}", groupBuilder.build());
1946         logger.debug("createOutputGroupInstructions: actionList {}", actionList);
1947
1948         if (addNew) {
1949             /* rewrite the group to group table */
1950             writeGroup(groupBuilder, nodeBuilder);
1951         }
1952
1953         // Create an Apply Action
1954         ApplyActionsBuilder aab = new ApplyActionsBuilder();
1955         aab.setAction(actionList);
1956         ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
1957
1958         return ib;
1959     }
1960
1961     /**
1962      * Remove Output Port from action list in group bucket
1963      *
1964      * @param ib       Map InstructionBuilder without any instructions
1965      * @param dpidLong Long the datapath ID of a switch/node
1966      * @param port     Long representing a port on a switch/node
1967      * @return ib InstructionBuilder Map with instructions
1968      */
1969     protected boolean removeOutputPortFromGroup(NodeBuilder nodeBuilder, InstructionBuilder ib,
1970             Long dpidLong, Long port , List<Instruction> instructions) {
1971
1972         NodeConnectorId ncid = new NodeConnectorId(OPENFLOW + dpidLong + ":" + port);
1973         logger.debug("removeOutputPortFromGroup() Node Connector ID is - Type=openflow: DPID={} port={} existingInstructions={}", dpidLong, port, instructions);
1974
1975         List<Action> actionList = Lists.newArrayList();
1976         ActionBuilder ab;
1977
1978         List<Action> existingActions;
1979         if (instructions != null) {
1980             for (Instruction in : instructions) {
1981                 if (in.getInstruction() instanceof ApplyActionsCase) {
1982                     existingActions = (((ApplyActionsCase) in.getInstruction()).getApplyActions().getAction());
1983                     actionList.addAll(existingActions);
1984                     break;
1985                 }
1986             }
1987         }
1988
1989         GroupBuilder groupBuilder = new GroupBuilder();
1990         Group group = null;
1991         boolean groupActionAdded = false;
1992         /* Find the group action and get the group */
1993         for (Action action : actionList) {
1994             if (action.getAction() instanceof GroupActionCase) {
1995                 groupActionAdded = true;
1996                 GroupActionCase groupAction = (GroupActionCase) action.getAction();
1997                 Long id = groupAction.getGroupAction().getGroupId();
1998                 String groupName = groupAction.getGroupAction().getGroup();
1999                 GroupKey key = new GroupKey(new GroupId(id));
2000
2001                 groupBuilder.setGroupId(new GroupId(id));
2002                 groupBuilder.setGroupName(groupName);
2003                 groupBuilder.setGroupType(GroupTypes.GroupAll);
2004                 groupBuilder.setKey(key);
2005                 group = getGroup(groupBuilder, nodeBuilder);
2006                 break;
2007             }
2008         }
2009
2010         if (groupActionAdded) {
2011             /* modify the action bucket in group */
2012             groupBuilder = new GroupBuilder(group);
2013             Buckets buckets = groupBuilder.getBuckets();
2014             List<Action> bucketActions = Lists.newArrayList();
2015             for (Bucket bucket : buckets.getBucket()) {
2016                 int index = 0;
2017                 boolean isPortDeleted = false;
2018                 bucketActions = bucket.getAction();
2019                 for (Action action : bucketActions) {
2020                     if (action.getAction() instanceof OutputActionCase) {
2021                         OutputActionCase opAction = (OutputActionCase)action.getAction();
2022                         if (opAction.getOutputAction().getOutputNodeConnector().equals(new Uri(ncid))) {
2023                             /* Find the output port in action list and remove */
2024                             index = bucketActions.indexOf(action);
2025                             bucketActions.remove(action);
2026                             isPortDeleted = true;
2027                             break;
2028                         }
2029                     }
2030                 }
2031                 if (isPortDeleted && !bucketActions.isEmpty()) {
2032                     for (int i = index; i< bucketActions.size(); i++) {
2033                         Action action = bucketActions.get(i);
2034                         if (action.getOrder() != i) {
2035                             /* Shift the action order */
2036                             ab = new ActionBuilder();
2037                             ab.setAction(action.getAction());
2038                             ab.setOrder(i);
2039                             ab.setKey(new ActionKey(i));
2040                             Action actionNewOrder = ab.build();
2041                             bucketActions.remove(action);
2042                             bucketActions.add(i, actionNewOrder);
2043                         }
2044                     }
2045
2046                 } else if (bucketActions.isEmpty()) {
2047                     /* remove bucket with empty action list */
2048                     buckets.getBucket().remove(bucket);
2049                     break;
2050                 }
2051             }
2052             if (!buckets.getBucket().isEmpty()) {
2053                 /* rewrite the group to group table */
2054                 /* set bucket and buckets list. Reset groupBuilder with new buckets.*/
2055                 BucketsBuilder bucketsBuilder = new BucketsBuilder();
2056                 List<Bucket> bucketList = Lists.newArrayList();
2057                 BucketBuilder bucketBuilder = new BucketBuilder();
2058                 bucketBuilder.setBucketId(new BucketId((long) 1));
2059                 bucketBuilder.setKey(new BucketKey(new BucketId((long) 1)));
2060                 bucketBuilder.setAction(bucketActions);
2061                 bucketList.add(bucketBuilder.build());
2062                 bucketsBuilder.setBucket(bucketList);
2063                 groupBuilder.setBuckets(bucketsBuilder.build());
2064                 logger.debug("removeOutputPortFromGroup: bucketList {}", bucketList);
2065
2066                 writeGroup(groupBuilder, nodeBuilder);
2067                 ApplyActionsBuilder aab = new ApplyActionsBuilder();
2068                 aab.setAction(actionList);
2069                 ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
2070                 return false;
2071             } else {
2072                 /* remove group with empty bucket. return true to delete flow */
2073                 removeGroup(groupBuilder, nodeBuilder);
2074                 return true;
2075             }
2076         } else {
2077             /* no group for port list. flow can be removed */
2078             return true;
2079         }
2080     }
2081
2082     @Override
2083     public void initializeOFFlowRules(Node openflowNode) {
2084         Preconditions.checkNotNull(connectionService);
2085         List<Node> ovsNodes = connectionService.getNodes();
2086         if (ovsNodes == null) return;
2087         for (Node ovsNode : ovsNodes) {
2088             Long brIntDpid = this.getIntegrationBridgeOFDPID(ovsNode);
2089             Long brExDpid = this.getExternalBridgeDpid(ovsNode);
2090             logger.debug("Compare openflowNode to OVS node {} vs {} and {}", openflowNode.getID(), brIntDpid, brExDpid);
2091             String openflowID = openflowNode.getID().toString();
2092             if (openflowID.contains(brExDpid.toString())) {
2093                 this.initializeFlowRules(ovsNode, configurationService.getExternalBridgeName());
2094                 this.triggerInterfaceUpdates(ovsNode);
2095             }
2096             if (openflowID.contains(brIntDpid.toString())) {
2097                 this.initializeFlowRules(ovsNode, configurationService.getIntegrationBridgeName());
2098                 this.triggerInterfaceUpdates(ovsNode);
2099             }
2100         }
2101     }
2102
2103     public static NodeBuilder createNodeBuilder(String nodeId) {
2104         NodeBuilder builder = new NodeBuilder();
2105         builder.setId(new NodeId(nodeId));
2106         builder.setKey(new NodeKey(builder.getId()));
2107         return builder;
2108     }
2109
2110     private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node> nodeBuilderToInstanceId(NodeBuilder
2111             node) {
2112         return InstanceIdentifier.builder(Nodes.class).child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node.class,
2113                 node.getKey()).toInstance();
2114     }
2115
2116     private String getInternalBridgeUUID (Node node, String bridgeName) {
2117         Preconditions.checkNotNull(ovsdbConfigurationService);
2118         try {
2119             Map<String, Row> bridgeTable = ovsdbConfigurationService.getRows(node, ovsdbConfigurationService.getTableName(node, Bridge.class));
2120             if (bridgeTable == null) return null;
2121             for (String key : bridgeTable.keySet()) {
2122                 Bridge bridge = ovsdbConfigurationService.getTypedRow(node, Bridge.class, bridgeTable.get(key));
2123                 if (bridge.getName().equals(bridgeName)) return key;
2124             }
2125         } catch (Exception e) {
2126             logger.error("Error getting Bridge Identifier for {} / {}", node, bridgeName, e);
2127         }
2128         return null;
2129     }
2130 }