5176095f1b7febe1ac04c7043b1c3d3a4453aeb5
[ovsdb.git] / neutron / src / main / java / org / opendaylight / ovsdb / neutron / provider / OF13ProviderManager.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
9  */
10 package org.opendaylight.ovsdb.neutron.provider;
11
12 import java.math.BigInteger;
13 import java.net.InetAddress;
14 import java.util.ArrayList;
15 import java.util.List;
16 import java.util.Map;
17 import java.util.Set;
18 import java.util.concurrent.ExecutionException;
19 import java.util.concurrent.Future;
20
21 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
22 import org.opendaylight.controller.md.sal.common.api.data.DataModification;
23 import org.opendaylight.controller.sal.binding.api.data.DataBrokerService;
24 import org.opendaylight.controller.sal.core.Node;
25 import org.opendaylight.controller.sal.utils.HexEncode;
26 import org.opendaylight.controller.sal.utils.ServiceHelper;
27 import org.opendaylight.controller.sal.utils.Status;
28 import org.opendaylight.controller.sal.utils.StatusCode;
29 import org.opendaylight.ovsdb.lib.notation.OvsDBMap;
30 import org.opendaylight.ovsdb.lib.notation.OvsDBSet;
31 import org.opendaylight.ovsdb.lib.notation.UUID;
32 import org.opendaylight.ovsdb.lib.table.Bridge;
33 import org.opendaylight.ovsdb.lib.table.Interface;
34 import org.opendaylight.ovsdb.lib.table.Port;
35 import org.opendaylight.ovsdb.neutron.AdminConfigManager;
36 import org.opendaylight.ovsdb.neutron.IMDSALConsumer;
37 import org.opendaylight.ovsdb.neutron.InternalNetworkManager;
38 import org.opendaylight.ovsdb.neutron.TenantNetworkManager;
39 import org.opendaylight.ovsdb.plugin.IConnectionServiceInternal;
40 import org.opendaylight.ovsdb.plugin.OVSDBConfigService;
41 import org.opendaylight.ovsdb.plugin.StatusWithUuid;
42 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Prefix;
43 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.PortNumber;
44 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Uri;
45 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.DecNwTtlCaseBuilder;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.DropActionCaseBuilder;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.OutputActionCaseBuilder;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.SetFieldCaseBuilder;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.SetNwDstActionCaseBuilder;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.SetNwSrcActionCaseBuilder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.SetVlanIdActionCaseBuilder;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.StripVlanActionCaseBuilder;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.dec.nw.ttl._case.DecNwTtl;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.dec.nw.ttl._case.DecNwTtlBuilder;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.drop.action._case.DropAction;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.drop.action._case.DropActionBuilder;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.output.action._case.OutputActionBuilder;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.set.field._case.SetFieldBuilder;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.set.nw.dst.action._case.SetNwDstActionBuilder;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.set.nw.src.action._case.SetNwSrcActionBuilder;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.set.vlan.id.action._case.SetVlanIdActionBuilder;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.strip.vlan.action._case.StripVlanAction;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.strip.vlan.action._case.StripVlanActionBuilder;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.ActionBuilder;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.ActionKey;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.address.address.Ipv4Builder;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.InstructionsBuilder;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.ApplyActionsCaseBuilder;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.GoToTableCaseBuilder;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.apply.actions._case.ApplyActionsBuilder;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.go.to.table._case.GoToTableBuilder;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionBuilder;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionKey;
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.yang.gen.v1.urn.opendaylight.l2.types.rev130827.EtherType;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.VlanId;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.arp.match.fields.ArpSourceHardwareAddressBuilder;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.arp.match.fields.ArpTargetHardwareAddressBuilder;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ethernet.match.fields.EthernetDestinationBuilder;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ethernet.match.fields.EthernetSourceBuilder;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ethernet.match.fields.EthernetTypeBuilder;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.EthernetMatchBuilder;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.Icmpv4MatchBuilder;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.IpMatchBuilder;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.TunnelBuilder;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.VlanMatchBuilder;
102 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.ArpMatchBuilder;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.Ipv4MatchBuilder;
104 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._4.match.TcpMatchBuilder;
105 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._4.match.UdpMatchBuilder;
106 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.vlan.match.fields.VlanIdBuilder;
107 import org.opendaylight.yangtools.yang.binding.DataObject;
108 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
109 import org.opendaylight.yangtools.yang.common.RpcResult;
110 import org.slf4j.Logger;
111 import org.slf4j.LoggerFactory;
112
113
114 /**
115  *
116  */
117 class OF13ProviderManager extends ProviderNetworkManager {
118     private static final Logger logger = LoggerFactory.getLogger(OF13ProviderManager.class);
119     private DataBrokerService dataBrokerService;
120     private static final short TABLE_0_DEFAULT_INGRESS = 0;
121     private static final short TABLE_1_ISOLATE_TENANT = 10;
122     private static final short TABLE_2_LOCAL_FORWARD = 20;
123
124     @Override
125     public boolean hasPerTenantTunneling() {
126         return false;
127     }
128
129     private Status getTunnelReadinessStatus (Node node, String tunnelKey) {
130         InetAddress srcTunnelEndPoint = AdminConfigManager.getManager().getTunnelEndPoint(node);
131         if (srcTunnelEndPoint == null) {
132             logger.error("Tunnel Endpoint not configured for Node {}", node);
133             return new Status(StatusCode.NOTFOUND, "Tunnel Endpoint not configured for "+ node);
134         }
135
136         if (!InternalNetworkManager.getManager().isInternalNetworkNeutronReady(node)) {
137             logger.error(node+" is not Overlay ready");
138             return new Status(StatusCode.NOTACCEPTABLE, node+" is not Overlay ready");
139         }
140
141         if (!TenantNetworkManager.getManager().isTenantNetworkPresentInNode(node, tunnelKey)) {
142             logger.debug(node+" has no VM corresponding to segment "+ tunnelKey);
143             return new Status(StatusCode.NOTACCEPTABLE, node+" has no VM corresponding to segment "+ tunnelKey);
144         }
145         return new Status(StatusCode.SUCCESS);
146     }
147
148     private String getTunnelName(String tunnelType, InetAddress dst) {
149         return tunnelType+"-"+dst.getHostAddress();
150     }
151
152     private boolean isTunnelPresent(Node node, String tunnelName, String bridgeUUID) throws Exception {
153         OVSDBConfigService ovsdbTable = (OVSDBConfigService)ServiceHelper.getGlobalInstance(OVSDBConfigService.class, this);
154         Bridge bridge = (Bridge)ovsdbTable.getRow(node, Bridge.NAME.getName(), bridgeUUID);
155         if (bridge != null) {
156             Set<UUID> ports = bridge.getPorts();
157             for (UUID portUUID : ports) {
158                 Port port = (Port)ovsdbTable.getRow(node, Port.NAME.getName(), portUUID.toString());
159                 if (port != null && port.getName().equalsIgnoreCase(tunnelName)) return true;
160             }
161         }
162         return false;
163     }
164
165     private Status addTunnelPort (Node node, String tunnelType, InetAddress src, InetAddress dst) {
166         try {
167             String bridgeUUID = null;
168             String tunnelBridgeName = AdminConfigManager.getManager().getIntegrationBridgeName();
169             OVSDBConfigService ovsdbTable = (OVSDBConfigService)ServiceHelper.getGlobalInstance(OVSDBConfigService.class, this);
170             Map<String, org.opendaylight.ovsdb.lib.table.internal.Table<?>> bridgeTable = ovsdbTable.getRows(node, Bridge.NAME.getName());
171             if (bridgeTable != null) {
172                 for (String uuid : bridgeTable.keySet()) {
173                     Bridge bridge = (Bridge)bridgeTable.get(uuid);
174                     if (bridge.getName().equals(tunnelBridgeName)) {
175                         bridgeUUID = uuid;
176                         break;
177                     }
178                 }
179             }
180             if (bridgeUUID == null) {
181                 logger.error("Could not find Bridge {} in {}", tunnelBridgeName, node);
182                 return new Status(StatusCode.NOTFOUND, "Could not find "+tunnelBridgeName+" in "+node);
183             }
184             String portName = getTunnelName(tunnelType, dst);
185
186             if (this.isTunnelPresent(node, portName, bridgeUUID)) {
187                 logger.trace("Tunnel {} is present in {} of {}", portName, tunnelBridgeName, node);
188                 return new Status(StatusCode.SUCCESS);
189             }
190
191             Port tunnelPort = new Port();
192             tunnelPort.setName(portName);
193             StatusWithUuid statusWithUuid = ovsdbTable.insertRow(node, Port.NAME.getName(), bridgeUUID, tunnelPort);
194             if (!statusWithUuid.isSuccess()) {
195                 logger.error("Failed to insert Tunnel port {} in {}", portName, bridgeUUID);
196                 return statusWithUuid;
197             }
198
199             String tunnelPortUUID = statusWithUuid.getUuid().toString();
200             String interfaceUUID = null;
201             int timeout = 6;
202             while ((interfaceUUID == null) && (timeout > 0)) {
203                 tunnelPort = (Port)ovsdbTable.getRow(node, Port.NAME.getName(), tunnelPortUUID);
204                 OvsDBSet<UUID> interfaces = tunnelPort.getInterfaces();
205                 if (interfaces == null || interfaces.size() == 0) {
206                     // Wait for the OVSDB update to sync up the Local cache.
207                     Thread.sleep(500);
208                     timeout--;
209                     continue;
210                 }
211                 interfaceUUID = interfaces.toArray()[0].toString();
212                 Interface intf = (Interface)ovsdbTable.getRow(node, Interface.NAME.getName(), interfaceUUID);
213                 if (intf == null) interfaceUUID = null;
214             }
215
216             if (interfaceUUID == null) {
217                 logger.error("Cannot identify Tunnel Interface for port {}/{}", portName, tunnelPortUUID);
218                 return new Status(StatusCode.INTERNALERROR);
219             }
220
221             Interface tunInterface = new Interface();
222             tunInterface.setType(tunnelType);
223             OvsDBMap<String, String> options = new OvsDBMap<String, String>();
224             options.put("key", "flow");
225             options.put("local_ip", src.getHostAddress());
226             options.put("remote_ip", dst.getHostAddress());
227             tunInterface.setOptions(options);
228             Status status = ovsdbTable.updateRow(node, Interface.NAME.getName(), tunnelPortUUID, interfaceUUID, tunInterface);
229             logger.debug("Tunnel {} add status : {}", tunInterface, status);
230             return status;
231         } catch (Exception e) {
232             logger.error("Exception in addTunnelPort", e);
233             return new Status(StatusCode.INTERNALERROR);
234         }
235     }
236
237     private void programLocalIngressTunnelBridgeRules(Node node, Long dpid, String segmentationId, String attachedMac, long tunnelOFPort, long localPort) {
238         /*
239          * Table(0) Rule #2
240          * ----------------
241          * Match: Ingress Port, Tunnel ID
242          * Action: GOTO Local Table (10)
243          */
244
245          writeTunnelIn(dpid, TABLE_0_DEFAULT_INGRESS, TABLE_2_LOCAL_FORWARD, segmentationId, tunnelOFPort);
246
247          /*
248          * Table(0) Rule #3
249          * ----------------
250          * Match: VM sMac and Local Ingress Port
251          * Action:Action: Set Tunnel ID and GOTO Local Table (5)
252          */
253
254          writeLocalInPort(dpid, TABLE_0_DEFAULT_INGRESS, TABLE_1_ISOLATE_TENANT, segmentationId, localPort, attachedMac);
255
256         /*
257          * Table(0) Rule #4
258          * ----------------
259          * Match: Drop any remaining Ingress Local VM Packets
260          * Action: Drop w/ a low priority
261          */
262
263          writeDropSrcIface(dpid, localPort);
264     }
265
266     private void programRemoteEgressTunnelBridgeRules(Node node, Long dpid, String segmentationId, String attachedMac, long tunnelOFPort, long localPort) {
267         /*
268          * Table(1) Rule #1
269          * ----------------
270          * Match: Drop any remaining Ingress Local VM Packets
271          * Action: Drop w/ a low priority
272          * -------------------------------------------
273          * table=1,tun_id=0x5,dl_dst=00:00:00:00:00:08 \
274          * actions=output:11,goto_table:2
275          */
276
277         writeTunnelOut(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD, segmentationId, tunnelOFPort, attachedMac);
278
279         /*
280          * Table(1) Rule #2
281          * ----------------
282          * Match: Match Tunnel ID and L2 ::::FF:FF Flooding
283          * Action: Flood to selected destination TEPs
284          * -------------------------------------------
285          * table=1,priority=16384,tun_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
286          * actions=output:10,output:11,goto_table:2
287          */
288
289         writeTunnelFloodOut(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD, segmentationId, tunnelOFPort);
290
291         /*
292          * Table(2) Rule #1
293          * ----------------
294          * Match: Match TunID and Destination DL/dMAC Addr
295          * Action: Output Port
296          * table=2,tun_id=0x5,dl_dst=00:00:00:00:00:01 actions=output:2
297          */
298
299          writeLocalUcastOut(dpid, TABLE_2_LOCAL_FORWARD, segmentationId, localPort, attachedMac);
300
301         /*
302          * Table(2) Rule #2
303          * ----------------
304          * Match: Tunnel ID and dMAC (::::FF:FF)
305          * table=2,priority=16384,tun_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
306          * actions=output:2,3,4,5
307          */
308
309          writeLocalBcastOut(dpid, TABLE_2_LOCAL_FORWARD, segmentationId, localPort);
310     }
311
312     private void programFloodEgressTunnelBridgeRules(Long dpid, String segmentationId) {
313         /*
314          * Table(1) Rule #3
315          * ----------------
316          * Match:  Any remaining Ingress Local VM Packets
317          * Action: Drop w/ a low priority
318          * -------------------------------------------
319          * table=1,priority=8192,tun_id=0x5 actions=goto_table:2
320          */
321
322          writeTunnelMiss(dpid, TABLE_1_ISOLATE_TENANT, TABLE_2_LOCAL_FORWARD, segmentationId);
323
324         /*
325          * Table(2) Rule #3
326          * ----------------
327          * Match: Any Remaining Flows w/a TunID
328          * Action: Drop w/ a low priority
329          * table=2,priority=8192,tun_id=0x5 actions=drop
330          */
331
332          writeLocalTableMiss(dpid, TABLE_2_LOCAL_FORWARD, segmentationId);
333     }
334
335     private void programTunnelRules (String tunnelType, String segmentationId, InetAddress dst, Node node,
336             Interface intf, boolean local) {
337         try {
338
339             String bridgeName = AdminConfigManager.getManager().getIntegrationBridgeName();
340             String brIntId = this.getInternalBridgeUUID(node, bridgeName);
341             if (brIntId == null) {
342                 logger.error("Unable to spot Bridge Identifier for {} in {}", bridgeName, node);
343                 return;
344             }
345
346             OVSDBConfigService ovsdbTable = (OVSDBConfigService) ServiceHelper.getGlobalInstance(OVSDBConfigService.class, this);
347             Bridge bridge = (Bridge) ovsdbTable.getRow(node, Bridge.NAME.getName(), brIntId);
348             Set<String> dpids = bridge.getDatapath_id();
349             if (dpids == null || dpids.size() == 0) return;
350             Long dpid = Long.valueOf(HexEncode.stringToLong((String) dpids.toArray()[0]));
351
352             Set<BigInteger> of_ports = intf.getOfport();
353             if (of_ports == null || of_ports.size() <= 0) {
354                 logger.error("Could NOT Identify OF value for port {} on {}", intf.getName(), node);
355                 return;
356             }
357             long localPort = ((BigInteger)of_ports.toArray()[0]).longValue();
358
359             Map<String, String> externalIds = intf.getExternal_ids();
360             if (externalIds == null) {
361                 logger.error("No external_ids seen in {}", intf);
362                 return;
363             }
364
365             String attachedMac = externalIds.get(TenantNetworkManager.EXTERNAL_ID_VM_MAC);
366             if (attachedMac == null) {
367                 logger.error("No AttachedMac seen in {}", intf);
368                 return;
369             }
370
371             Map<String, org.opendaylight.ovsdb.lib.table.internal.Table<?>> intfs = ovsdbTable.getRows(node, Interface.NAME.getName());
372             if (intfs != null) {
373                 for (org.opendaylight.ovsdb.lib.table.internal.Table<?> row : intfs.values()) {
374                     Interface tunIntf = (Interface)row;
375                     if (tunIntf.getName().equals(this.getTunnelName(tunnelType, dst))) {
376                         of_ports = tunIntf.getOfport();
377                         if (of_ports == null || of_ports.size() <= 0) {
378                             logger.error("Could NOT Identify Tunnel port {} on {}", tunIntf.getName(), node);
379                             continue;
380                         }
381                         long tunnelOFPort = ((BigInteger)of_ports.toArray()[0]).longValue();
382
383                         if (tunnelOFPort == -1) {
384                             logger.error("Could NOT Identify Tunnel port {} -> OF ({}) on {}", tunIntf.getName(), tunnelOFPort, node);
385                             return;
386                         }
387                         logger.debug("Identified Tunnel port {} -> OF ({}) on {}", tunIntf.getName(), tunnelOFPort, node);
388
389                         if (!local) {
390                             programRemoteEgressTunnelBridgeRules(node, dpid, segmentationId, attachedMac, tunnelOFPort, localPort);
391                         }
392                         programLocalIngressTunnelBridgeRules(node, dpid, segmentationId, attachedMac, tunnelOFPort, localPort);
393                         programFloodEgressTunnelBridgeRules(dpid, segmentationId);
394                         return;
395                     }
396                 }
397             }
398         } catch (Exception e) {
399             logger.error("", e);
400         }
401     }
402
403     @Override
404     public Status handleInterfaceUpdate(String tunnelType, String tunnelKey, Node srcNode, Interface intf) {
405         Status status = getTunnelReadinessStatus(srcNode, tunnelKey);
406         if (!status.isSuccess()) return status;
407
408         IConnectionServiceInternal connectionService = (IConnectionServiceInternal)ServiceHelper.getGlobalInstance(IConnectionServiceInternal.class, this);
409         List<Node> nodes = connectionService.getNodes();
410         nodes.remove(srcNode);
411         for (Node dstNode : nodes) {
412             status = getTunnelReadinessStatus(dstNode, tunnelKey);
413             if (!status.isSuccess()) continue;
414             InetAddress src = AdminConfigManager.getManager().getTunnelEndPoint(srcNode);
415             InetAddress dst = AdminConfigManager.getManager().getTunnelEndPoint(dstNode);
416             status = addTunnelPort(srcNode, tunnelType, src, dst);
417             if (status.isSuccess()) {
418                 this.programTunnelRules(tunnelType, tunnelKey, dst, srcNode, intf, true);
419             }
420             addTunnelPort(dstNode, tunnelType, dst, src);
421             if (status.isSuccess()) {
422                 this.programTunnelRules(tunnelType, tunnelKey, src, dstNode, intf, false);
423             }
424         }
425         return new Status(StatusCode.SUCCESS);
426     }
427
428     @Override
429     public Status handleInterfaceUpdate(String tunnelType, String tunnelKey) {
430         // TODO Auto-generated method stub
431         return null;
432     }
433
434     @Override
435     public void initializeFlowRules(Node node) {
436         this.initializeFlowRules(node, AdminConfigManager.getManager().getIntegrationBridgeName());
437     }
438
439     /**
440      * @param node
441      * @param bridgeName
442      */
443     private void initializeFlowRules(Node node, String bridgeName) {
444
445         // TODO : 3 second sleep hack is to make sure the OF connection is established.
446         // Correct fix is to check the MD-SAL inventory before proceeding and listen
447         // to Inventory update for processing.
448         try {
449             Thread.sleep(3000);
450         } catch (InterruptedException e1) {
451             logger.error("Sleep Thread interrupted ",e1);
452         }
453
454         String brIntId = this.getInternalBridgeUUID(node, bridgeName);
455         if (brIntId == null) {
456             logger.error("Failed to initialize Flow Rules for {}", node);
457             return;
458         }
459
460         try {
461             OVSDBConfigService ovsdbTable = (OVSDBConfigService) ServiceHelper.getGlobalInstance(OVSDBConfigService.class, this);
462             Bridge bridge = (Bridge) ovsdbTable.getRow(node, Bridge.NAME.getName(), brIntId);
463             Set<String> dpids = bridge.getDatapath_id();
464             if (dpids == null || dpids.size() == 0) return;
465             Long dpid = Long.valueOf(HexEncode.stringToLong((String) dpids.toArray()[0]));
466
467             /*
468              * Table(0) Rule #1
469              * ----------------
470              * Match: LLDP (0x88CCL)
471              * Action: Packet_In to Controller Reserved Port
472              */
473
474              writeLLDPRule(dpid);
475         } catch (Exception e) {
476             logger.error("Failed to initialize Flow Rules for " + node.toString()+ " Bridge "+bridgeName, e);
477         }
478     }
479
480     /*
481     * Create an LLDP Flow Rule to encapsulate into
482     * a packet_in that is sent to the controller
483     * for topology handling.
484     * Match: Ethertype 0x88CCL
485     * Action: Punt to Controller in a Packet_In msg
486     */
487
488     private void writeLLDPRule(Long dpidLong) {
489
490         String nodeName = "openflow:" + dpidLong;
491         EtherType etherType = new EtherType(0x88CCL);
492
493         MatchBuilder matchBuilder = new MatchBuilder();
494         NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
495         FlowBuilder flowBuilder = new FlowBuilder();
496
497         // Create Match(es) and Set them in the FlowBuilder Object
498         flowBuilder.setMatch(createEtherTypeMatch(matchBuilder, etherType).build());
499
500         // Create the OF Actions and Instructions
501         InstructionBuilder ib = new InstructionBuilder();
502         InstructionsBuilder isb = new InstructionsBuilder();
503
504         // Instructions List Stores Individual Instructions
505         List<Instruction> instructions = new ArrayList<Instruction>();
506
507         // Call the InstructionBuilder Methods Containing Actions
508         createSendToControllerInstructions(ib);
509         instructions.add(ib.build());
510
511         // Add InstructionBuilder to the Instruction(s)Builder List
512         isb.setInstruction(instructions);
513
514         // Add InstructionsBuilder to FlowBuilder
515         flowBuilder.setInstructions(isb.build());
516
517         flowBuilder.setId(new FlowId("10"));
518         FlowKey key = new FlowKey(new FlowId(String.valueOf((long) 110)));
519         flowBuilder.setBarrier(true);
520         flowBuilder.setTableId((short) 0);
521         flowBuilder.setKey(key);
522         flowBuilder.setFlowName("LLDP_" + nodeName);
523         flowBuilder.setHardTimeout(0);
524         flowBuilder.setIdleTimeout(0);
525         writeFlow(flowBuilder, nodeBuilder);
526     }
527
528     /*
529      * (Table:0) Ingress Tunnel Traffic
530      * Match: OpenFlow InPort and Tunnel ID
531      * Action: GOTO Local Table (10)
532      * table=0,tun_id=0x5,in_port=10, actions=goto_table:2
533      */
534
535     private void writeTunnelIn(Long dpidLong, Short writeTable, Short goToTableId, String segmentationId,  Long ofPort) {
536
537         String nodeName = "openflow:" + dpidLong;
538
539         BigInteger tunnelId = new BigInteger(segmentationId);
540         MatchBuilder matchBuilder = new MatchBuilder();
541         NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
542         FlowBuilder flowBuilder = new FlowBuilder();
543
544         // Create Match(es) and Set them in the FlowBuilder Object
545         flowBuilder.setMatch(createTunnelIDMatch(matchBuilder, tunnelId).build());
546         flowBuilder.setMatch(createInPortMatch(matchBuilder, dpidLong, ofPort).build());
547
548         // Create the OF Actions and Instructions
549         InstructionBuilder ib = new InstructionBuilder();
550         InstructionsBuilder isb = new InstructionsBuilder();
551
552         // Instructions List Stores Individual Instructions
553         List<Instruction> instructions = new ArrayList<Instruction>();
554
555         // Call the InstructionBuilder Methods Containing Actions
556         createGotoTableInstructions(ib, goToTableId);
557         instructions.add(ib.build());
558
559         // Add InstructionBuilder to the Instruction(s)Builder List
560         isb.setInstruction(instructions);
561
562         // Add InstructionsBuilder to FlowBuilder
563         flowBuilder.setInstructions(isb.build());
564
565         // Add Flow Attributes
566         flowBuilder.setId(new FlowId("20"));
567         FlowKey key = new FlowKey(new FlowId(String.valueOf((long) 120)));
568         flowBuilder.setBarrier(false);
569         flowBuilder.setTableId(writeTable);
570         flowBuilder.setKey(key);
571         flowBuilder.setFlowName("TUNIN_" + nodeName);
572         flowBuilder.setHardTimeout(0);
573         flowBuilder.setIdleTimeout(0);
574         writeFlow(flowBuilder, nodeBuilder);
575     }
576
577    /*
578     * (Table:0) Egress VM Traffic Towards TEP
579     * Match: Destination Ethernet Addr and OpenFlow InPort
580     * Instruction: Set TunnelID and GOTO Table Tunnel Table (n)
581     * table=0,in_port=2,dl_src=00:00:00:00:00:01 \
582     * actions=set_field:5->tun_id,goto_table=1"
583     */
584
585     private void writeLocalInPort(Long dpidLong, Short writeTable, Short goToTableId, String segmentationId, Long inPort, String attachedMac) {
586
587         String nodeName = "openflow:" + dpidLong;
588
589         MatchBuilder matchBuilder = new MatchBuilder();
590         NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
591         FlowBuilder flowBuilder = new FlowBuilder();
592
593         // Create the OF Match using MatchBuilder
594         flowBuilder.setMatch(createEthSrcMatch(matchBuilder, new MacAddress(attachedMac)).build());
595         // TODO Broken In_Port Match
596         flowBuilder.setMatch(createInPortMatch(matchBuilder, dpidLong, inPort).build());
597
598         // Instantiate the Builders for the OF Actions and Instructions
599         InstructionBuilder ib = new InstructionBuilder();
600         InstructionsBuilder isb = new InstructionsBuilder();
601
602         // Instructions List Stores Individual Instructions
603         List<Instruction> instructions = new ArrayList<Instruction>();
604
605         // GOTO Instuctions Need to be added first to the List
606         createGotoTableInstructions(ib, goToTableId);
607         instructions.add(ib.build());
608         // TODO Broken SetTunID
609         createSetTunnelIdInstructions(ib, new BigInteger(segmentationId));
610         instructions.add(ib.build());
611
612         // Add InstructionBuilder to the Instruction(s)Builder List
613         isb.setInstruction(instructions);
614
615         // Add InstructionsBuilder to FlowBuilder
616         flowBuilder.setInstructions(isb.build());
617
618         // Add Flow Attributes
619         flowBuilder.setId(new FlowId("30"));
620         FlowKey key = new FlowKey(new FlowId(String.valueOf((long) 130)));
621         flowBuilder.setBarrier(false);
622         flowBuilder.setTableId(writeTable);
623         flowBuilder.setKey(key);
624         flowBuilder.setFlowName("LOCALSMAC_" + nodeName);
625         flowBuilder.setHardTimeout(0);
626         flowBuilder.setIdleTimeout(0);
627         writeFlow(flowBuilder, nodeBuilder);
628     }
629
630     /*
631      * (Table:0) Drop frames sourced from a VM that do not
632      * match the associated MAC address of the local VM.
633      * Match: Low priority anything not matching the VM SMAC
634      * Instruction: Drop
635      * table=0,priority=16384,in_port=1 actions=drop"
636      */
637
638     private void writeDropSrcIface(Long dpidLong, Long inPort) {
639
640         String nodeName = "openflow:" + dpidLong;
641
642         MatchBuilder matchBuilder = new MatchBuilder();
643         NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
644         FlowBuilder flowBuilder = new FlowBuilder();
645
646         // Create the OF Match using MatchBuilder
647         flowBuilder.setMatch(createInPortMatch(matchBuilder, dpidLong, inPort).build());
648
649         // Instantiate the Builders for the OF Actions and Instructions
650         InstructionBuilder ib = new InstructionBuilder();
651         InstructionsBuilder isb = new InstructionsBuilder();
652
653         // Instructions List Stores Individual Instructions
654         List<Instruction> instructions = new ArrayList<Instruction>();
655
656         // Call the InstructionBuilder Methods Containing Actions
657         createDropInstructions(ib);
658         instructions.add(ib.build());
659
660         // Add InstructionBuilder to the Instruction(s)Builder List
661         isb.setInstruction(instructions);
662
663         // Add InstructionsBuilder to FlowBuilder
664         flowBuilder.setInstructions(isb.build());
665
666         // Add Flow Attributes
667         flowBuilder.setId(new FlowId("40"));
668         FlowKey key = new FlowKey(new FlowId(String.valueOf((long) 140)));
669         flowBuilder.setBarrier(false);
670         flowBuilder.setTableId((short) 0);
671         flowBuilder.setKey(key);
672         flowBuilder.setFlowName("LOCALDROP_" + nodeName);
673         flowBuilder.setPriority(8192);
674         flowBuilder.setHardTimeout(0);
675         flowBuilder.setIdleTimeout(0);
676         writeFlow(flowBuilder, nodeBuilder);
677     }
678
679    /*
680     * (Table:1) Egress Tunnel Traffic
681     * Match: Destination Ethernet Addr and Local InPort
682     * Instruction: Set TunnelID and GOTO Table Tunnel Table (n)
683     * table=1,tun_id=0x5,dl_dst=00:00:00:00:00:08 \
684     * actions=output:10,goto_table:2"
685     */
686
687     private void writeTunnelOut(Long dpidLong, Short writeTable, Short goToTableId, String segmentationId , Long OFPortOut, String attachedMac) {
688
689         String nodeName = "openflow:" + dpidLong;
690
691         MatchBuilder matchBuilder = new MatchBuilder();
692         NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
693         FlowBuilder flowBuilder = new FlowBuilder();
694
695         // Create the OF Match using MatchBuilder
696         flowBuilder.setMatch(createTunnelIDMatch(matchBuilder, new BigInteger(segmentationId)).build());
697         flowBuilder.setMatch(createDestEthMatch(matchBuilder, new MacAddress(attachedMac), null).build());
698
699         // Instantiate the Builders for the OF Actions and Instructions
700         InstructionBuilder ib = new InstructionBuilder();
701         InstructionsBuilder isb = new InstructionsBuilder();
702
703         // Instructions List Stores Individual Instructions
704         List<Instruction> instructions = new ArrayList<Instruction>();
705
706         // GOTO Instuctions
707         createGotoTableInstructions(ib, goToTableId);
708         instructions.add(ib.build());
709         // Set the Output Port/Iface
710         createOutputPortInstructions(ib, dpidLong, OFPortOut);
711         instructions.add(ib.build());
712
713         // Add InstructionBuilder to the Instruction(s)Builder List
714         isb.setInstruction(instructions);
715
716         // Add InstructionsBuilder to FlowBuilder
717         flowBuilder.setInstructions(isb.build());
718
719         // Add Flow Attributes
720         flowBuilder.setId(new FlowId("50"));
721         FlowKey key = new FlowKey(new FlowId(String.valueOf((long) 150)));
722         flowBuilder.setBarrier(false);
723         flowBuilder.setTableId(writeTable);
724         flowBuilder.setKey(key);
725         flowBuilder.setFlowName("TUNOUT_" + nodeName);
726         flowBuilder.setHardTimeout(0);
727         flowBuilder.setIdleTimeout(0);
728         writeFlow(flowBuilder, nodeBuilder);
729     }
730
731        /*
732     * (Table:1) Egress Tunnel Traffic
733     * Match: Destination Ethernet Addr and Local InPort
734     * Instruction: Set TunnelID and GOTO Table Tunnel Table (n)
735     * table=1,priority=16384,tun_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
736     * actions=output:10,output:11,goto_table:2
737     */
738
739     private void writeTunnelFloodOut(Long dpidLong, Short writeTable, Short localTable, String segmentationId,  Long OFPortOut) {
740
741         String nodeName = "openflow:" + dpidLong;
742
743         MatchBuilder matchBuilder = new MatchBuilder();
744         NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
745         FlowBuilder flowBuilder = new FlowBuilder();
746
747         // Create the OF Match using MatchBuilder
748         // Match TunnelID
749         flowBuilder.setMatch(createTunnelIDMatch(matchBuilder, new BigInteger(segmentationId)).build());
750         // Match DMAC
751         byte[] mask = new byte[] { (byte) 1, 0, 0, 0, 0, 0 };
752         flowBuilder.setMatch(createDestEthMatch(matchBuilder, new MacAddress("01:00:00:00:00:00"), mask).build());
753
754         // Instantiate the Builders for the OF Actions and Instructions
755         InstructionBuilder ib = new InstructionBuilder();
756         InstructionsBuilder isb = new InstructionsBuilder();
757
758         // Instructions List Stores Individual Instructions
759         List<Instruction> instructions = new ArrayList<Instruction>();
760
761         // GOTO Instuction
762         createGotoTableInstructions(ib, localTable);
763         instructions.add(ib.build());
764         // Set the Output Port/Iface
765         createOutputPortInstructions(ib, dpidLong, OFPortOut);
766         instructions.add(ib.build());
767
768         // Add InstructionBuilder to the Instruction(s)Builder List
769         isb.setInstruction(instructions);
770
771         // Add InstructionsBuilder to FlowBuilder
772         flowBuilder.setInstructions(isb.build());
773
774         // Add Flow Attributes
775         flowBuilder.setId(new FlowId("60"));
776         FlowKey key = new FlowKey(new FlowId(String.valueOf((long) 160)));
777         flowBuilder.setBarrier(true);
778         flowBuilder.setTableId(writeTable);
779         flowBuilder.setKey(key);
780         flowBuilder.setPriority(16384);
781         flowBuilder.setFlowName("TUNFLOODOUT_" + nodeName);
782         flowBuilder.setHardTimeout(0);
783         flowBuilder.setIdleTimeout(0);
784         writeFlow(flowBuilder, nodeBuilder);
785     }
786
787    /*
788     * (Table:1) Table Drain w/ Catch All
789     * Match: Tunnel ID
790     * Action: GOTO Local Table (10)
791     * table=2,priority=8192,tun_id=0x5 actions=drop
792     */
793
794     private void writeTunnelMiss(Long dpidLong, Short writeTable, Short goToTableId, String segmentationId) {
795
796         String nodeName = "openflow:" + dpidLong;
797
798         MatchBuilder matchBuilder = new MatchBuilder();
799         NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
800         FlowBuilder flowBuilder = new FlowBuilder();
801
802         // Create Match(es) and Set them in the FlowBuilder Object
803         flowBuilder.setMatch(createTunnelIDMatch(matchBuilder, new BigInteger(segmentationId)).build());
804
805         // Create the OF Actions and Instructions
806         InstructionBuilder ib = new InstructionBuilder();
807         InstructionsBuilder isb = new InstructionsBuilder();
808
809         // Instructions List Stores Individual Instructions
810         List<Instruction> instructions = new ArrayList<Instruction>();
811
812         // Call the InstructionBuilder Methods Containing Actions
813         createGotoTableInstructions(ib, goToTableId);
814         instructions.add(ib.build());
815
816         // Add InstructionBuilder to the Instruction(s)Builder List
817         isb.setInstruction(instructions);
818
819         // Add InstructionsBuilder to FlowBuilder
820         flowBuilder.setInstructions(isb.build());
821
822         // Add Flow Attributes
823         flowBuilder.setId(new FlowId("70"));
824         FlowKey key = new FlowKey(new FlowId(String.valueOf((long) 170)));
825         flowBuilder.setBarrier(false);
826         flowBuilder.setTableId(writeTable);
827         flowBuilder.setKey(key);
828         flowBuilder.setPriority(8192);
829         flowBuilder.setFlowName("TUNMISS_" + nodeName);
830         flowBuilder.setHardTimeout(0);
831         flowBuilder.setIdleTimeout(0);
832         writeFlow(flowBuilder, nodeBuilder);
833     }
834
835     /*
836      * (Table:1) Local Broadcast Flood
837      * Match: Tunnel ID and dMAC
838      * Action: Output Port
839      * table=2,tun_id=0x5,dl_dst=00:00:00:00:00:01 actions=output:2
840      */
841
842     private void writeLocalUcastOut(Long dpidLong, Short writeTable, String segmentationId, Long localPort, String attachedMac) {
843
844         String nodeName = "openflow:" + dpidLong;
845
846         MatchBuilder matchBuilder = new MatchBuilder();
847         NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
848         FlowBuilder flowBuilder = new FlowBuilder();
849
850         // Create the OF Match using MatchBuilder
851         flowBuilder.setMatch(createTunnelIDMatch(matchBuilder, new BigInteger(segmentationId)).build());
852         flowBuilder.setMatch(createDestEthMatch(matchBuilder, new MacAddress(attachedMac), null).build());
853
854         // Instantiate the Builders for the OF Actions and Instructions
855         InstructionBuilder ib = new InstructionBuilder();
856         InstructionsBuilder isb = new InstructionsBuilder();
857
858         // Instructions List Stores Individual Instructions
859         List<Instruction> instructions = new ArrayList<Instruction>();
860
861         // Set the Output Port/Iface
862         createOutputPortInstructions(ib, dpidLong, localPort);
863         instructions.add(ib.build());
864
865         // Add InstructionBuilder to the Instruction(s)Builder List
866         isb.setInstruction(instructions);
867
868         // Add InstructionsBuilder to FlowBuilder
869         flowBuilder.setInstructions(isb.build());
870
871         // Add Flow Attributes
872         flowBuilder.setId(new FlowId("80"));
873         FlowKey key = new FlowKey(new FlowId(String.valueOf((long) 180)));
874         flowBuilder.setBarrier(false);
875         flowBuilder.setTableId(writeTable);
876         flowBuilder.setKey(key);
877         flowBuilder.setFlowName("LOCALHOSTUCAST_" + nodeName);
878         flowBuilder.setHardTimeout(0);
879         flowBuilder.setIdleTimeout(0);
880         writeFlow(flowBuilder, nodeBuilder);
881     }
882
883     /*
884      * (Table:1) Local Broadcast Flood
885      * Match: Tunnel ID and dMAC (::::FF:FF)
886      * table=2,priority=16384,tun_id=0x5,dl_dst=ff:ff:ff:ff:ff:ff \
887      * actions=output:2,3,4,5
888      */
889
890     private void writeLocalBcastOut(Long dpidLong, Short writeTable, String segmentationId, Long localPort) {
891
892         String nodeName = "openflow:" + dpidLong;
893
894         MatchBuilder matchBuilder = new MatchBuilder();
895         NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
896         FlowBuilder flowBuilder = new FlowBuilder();
897
898         // Create the OF Match using MatchBuilder
899         flowBuilder.setMatch(createTunnelIDMatch(matchBuilder, new BigInteger(segmentationId)).build());
900         byte[] mask = new byte[] { (byte) 1, 0, 0, 0, 0, 0 };
901         flowBuilder.setMatch(createDestEthMatch(matchBuilder, new MacAddress("01:00:00:00:00:00"), mask).build());
902
903         // Instantiate the Builders for the OF Actions and Instructions
904         InstructionBuilder ib = new InstructionBuilder();
905         InstructionsBuilder isb = new InstructionsBuilder();
906
907         // Instructions List Stores Individual Instructions
908         List<Instruction> instructions = new ArrayList<Instruction>();
909
910         // Broken OutPort TODO: localPort needs to be a list of Ports)
911         createOutputPortInstructions(ib, dpidLong, localPort);
912         instructions.add(ib.build());
913
914         // Add InstructionBuilder to the Instruction(s)Builder List
915         isb.setInstruction(instructions);
916
917         // Add InstructionsBuilder to FlowBuilder
918         flowBuilder.setInstructions(isb.build());
919
920         // Add Flow Attributes
921         flowBuilder.setId(new FlowId("90"));
922         FlowKey key = new FlowKey(new FlowId(String.valueOf((long) 190)));
923         flowBuilder.setBarrier(false);
924         flowBuilder.setTableId(writeTable);
925         flowBuilder.setKey(key);
926         flowBuilder.setPriority(16384);
927         flowBuilder.setFlowName("LOCALHOSTBCAST_" + nodeName);
928         flowBuilder.setHardTimeout(0);
929         flowBuilder.setIdleTimeout(0);
930         writeFlow(flowBuilder, nodeBuilder);
931     }
932
933     /*
934      * (Table:1) Local Table Miss
935      * Match: Any Remaining Flows w/a TunID
936      * Action: Drop w/ a low priority
937      * table=2,priority=8192,tun_id=0x5 actions=drop
938      */
939
940     private void writeLocalTableMiss(Long dpidLong, Short writeTable, String segmentationId) {
941
942         String nodeName = "openflow:" + dpidLong;
943
944         MatchBuilder matchBuilder = new MatchBuilder();
945         NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
946         FlowBuilder flowBuilder = new FlowBuilder();
947
948         // Create Match(es) and Set them in the FlowBuilder Object
949         flowBuilder.setMatch(createTunnelIDMatch(matchBuilder, new BigInteger(segmentationId)).build());
950
951         // Create the OF Actions and Instructions
952         InstructionBuilder ib = new InstructionBuilder();
953         InstructionsBuilder isb = new InstructionsBuilder();
954
955         // Instructions List Stores Individual Instructions
956         List<Instruction> instructions = new ArrayList<Instruction>();
957
958         // Call the InstructionBuilder Methods Containing Actions
959         createDropInstructions(ib);
960         instructions.add(ib.build());
961
962         // Add InstructionBuilder to the Instruction(s)Builder List
963         isb.setInstruction(instructions);
964
965         // Add InstructionsBuilder to FlowBuilder
966         flowBuilder.setInstructions(isb.build());
967
968         // Add Flow Attributes
969         flowBuilder.setId(new FlowId("100"));
970         FlowKey key = new FlowKey(new FlowId(String.valueOf((long) 200)));
971         flowBuilder.setBarrier(false);
972         flowBuilder.setTableId(writeTable);
973         flowBuilder.setKey(key);
974         flowBuilder.setPriority(8192);
975         flowBuilder.setFlowName("TUNMISS_" + nodeName);
976         flowBuilder.setHardTimeout(0);
977         flowBuilder.setIdleTimeout(0);
978         writeFlow(flowBuilder, nodeBuilder);
979     }
980
981     private void writeFlow(FlowBuilder flowBuilder, NodeBuilder nodeBuilder) {
982         IMDSALConsumer mdsalConsumer = (IMDSALConsumer) ServiceHelper.getInstance(IMDSALConsumer.class, "default", this);
983         if (mdsalConsumer == null) {
984             logger.error("ERROR finding MDSAL Service. Its possible that writeFlow is called too soon ?");
985             return;
986         }
987
988         dataBrokerService = mdsalConsumer.getDataBrokerService();
989
990         if (dataBrokerService == null) {
991             logger.error("ERROR finding reference for DataBrokerService. Please check out the MD-SAL support on the Controller.");
992             return;
993         }
994         DataModification<InstanceIdentifier<?>, DataObject> modification = dataBrokerService.beginTransaction();
995         InstanceIdentifier<Flow> path1 = InstanceIdentifier.builder(Nodes.class).child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory
996                 .rev130819.nodes.Node.class, nodeBuilder.getKey()).augmentation(FlowCapableNode.class).child(Table.class,
997                 new TableKey(flowBuilder.getTableId())).child(Flow.class, flowBuilder.getKey()).build();
998         modification.putOperationalData(nodeBuilderToInstanceId(nodeBuilder), nodeBuilder.build());
999         modification.putOperationalData(path1, flowBuilder.build());
1000         modification.putConfigurationData(nodeBuilderToInstanceId(nodeBuilder), nodeBuilder.build());
1001         modification.putConfigurationData(path1, flowBuilder.build());
1002         Future<RpcResult<TransactionStatus>> commitFuture = modification.commit();
1003         try {
1004             RpcResult<TransactionStatus> result = commitFuture.get();
1005             TransactionStatus status = result.getResult();
1006         } catch (InterruptedException e) {
1007             logger.error(e.getMessage(), e);
1008         } catch (ExecutionException e) {
1009             logger.error(e.getMessage(), e);
1010         }
1011     }
1012
1013     /**
1014      * Create Ingress Port Match dpidLong, inPort
1015      *
1016      * @param matchBuilder  Map matchBuilder MatchBuilder Object without a match
1017      * @param dpidLong      Long the datapath ID of a switch/node
1018      * @param inPort        Long ingress port on a switch
1019      * @return matchBuilder Map MatchBuilder Object with a match
1020      */
1021     protected static MatchBuilder createInPortMatch(MatchBuilder matchBuilder, Long dpidLong, Long inPort) {
1022
1023         NodeConnectorId ncid = new NodeConnectorId("openflow:" + dpidLong + ":" + inPort);
1024         logger.debug("createInPortMatch() Node Connector ID is - Type=openflow: DPID={} inPort={} ", dpidLong, inPort);
1025         matchBuilder.setInPort(NodeConnectorId.getDefaultInstance(ncid.getValue()));
1026         matchBuilder.setInPort(ncid);
1027
1028         return matchBuilder;
1029     }
1030
1031     /**
1032      * Create EtherType Match
1033      *
1034      * @param matchBuilder  Map matchBuilder MatchBuilder Object without a match
1035      * @param etherType     Long EtherType
1036      * @return matchBuilder Map MatchBuilder Object with a match
1037      */
1038     protected static MatchBuilder createEtherTypeMatch(MatchBuilder matchBuilder, EtherType etherType) {
1039
1040         EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder();
1041         EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder();
1042         ethTypeBuilder.setType(new EtherType(etherType));
1043         ethernetMatch.setEthernetType(ethTypeBuilder.build());
1044         matchBuilder.setEthernetMatch(ethernetMatch.build());
1045
1046         return matchBuilder;
1047     }
1048
1049     /**
1050      * Create Ethernet Source Match
1051      *
1052      * @param matchBuilder  MatchBuilder Object without a match yet
1053      * @param sMacAddr      String representing a source MAC
1054      * @return matchBuilder Map MatchBuilder Object with a match
1055      */
1056     protected static MatchBuilder createEthSrcMatch(MatchBuilder matchBuilder, MacAddress sMacAddr) {
1057
1058         EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder();
1059         EthernetSourceBuilder ethSourceBuilder = new EthernetSourceBuilder();
1060         ethSourceBuilder.setAddress(new MacAddress(sMacAddr));
1061         ethernetMatch.setEthernetSource(ethSourceBuilder.build());
1062         matchBuilder.setEthernetMatch(ethernetMatch.build());
1063
1064         return matchBuilder;
1065     }
1066
1067     /**
1068      * Create Ethernet Destination Match
1069      *
1070      * @param matchBuilder MatchBuilder Object without a match yet
1071      * @param vlanId       Integer representing a VLAN ID Integer representing a VLAN ID
1072      * @return matchBuilder Map MatchBuilder Object with a match
1073      */
1074
1075     protected static MatchBuilder createVlanIdMatch(MatchBuilder matchBuilder, VlanId vlanId) {
1076
1077         VlanMatchBuilder vlanMatchBuilder = new VlanMatchBuilder();
1078         VlanIdBuilder vlanIdBuilder = new VlanIdBuilder();
1079         vlanIdBuilder.setVlanId(new VlanId(vlanId));
1080         vlanMatchBuilder.setVlanId(vlanIdBuilder.build());
1081         matchBuilder.setVlanMatch(vlanMatchBuilder.build());
1082
1083         return matchBuilder;
1084     }
1085
1086     /**
1087      * Create Ethernet Destination Match
1088      *
1089      * @param matchBuilder  MatchBuilder Object without a match yet
1090      * @param dMacAddr      String representing a destination MAC
1091      * @return matchBuilder Map MatchBuilder Object with a match
1092      */
1093
1094     protected static MatchBuilder createDestEthMatch(MatchBuilder matchBuilder, MacAddress dMacAddr, byte[] mask) {
1095
1096         EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder();
1097         EthernetDestinationBuilder ethDestinationBuilder = new EthernetDestinationBuilder();
1098         ethDestinationBuilder.setAddress(new MacAddress(dMacAddr));
1099         if (mask != null) {
1100             ethDestinationBuilder.setMask(mask);
1101         }
1102         ethernetMatch.setEthernetDestination(ethDestinationBuilder.build());
1103         matchBuilder.setEthernetMatch(ethernetMatch.build());
1104
1105         return matchBuilder;
1106     }
1107
1108     /**
1109      * Tunnel ID Match Builder
1110      *
1111      * @param matchBuilder  MatchBuilder Object without a match yet
1112      * @param tunnelId      BigInteger representing a tunnel ID
1113      * @return matchBuilder Map MatchBuilder Object with a match
1114      */
1115     protected static MatchBuilder createTunnelIDMatch(MatchBuilder matchBuilder, BigInteger tunnelId) {
1116
1117         TunnelBuilder tunnelBuilder = new TunnelBuilder();
1118         tunnelBuilder.setTunnelId(tunnelId);
1119         matchBuilder.setTunnel(tunnelBuilder.build());
1120
1121         return matchBuilder;
1122     }
1123
1124     /**
1125      * Match ICMP code and type
1126      *
1127      * @param matchBuilder  MatchBuilder Object without a match yet
1128      * @param type          short representing an ICMP type
1129      * @param code          short representing an ICMP code
1130      * @return matchBuilder Map MatchBuilder Object with a match
1131      */
1132     protected static MatchBuilder createICMPv4Match(MatchBuilder matchBuilder, short type, short code) {
1133
1134         EthernetMatchBuilder eth = new EthernetMatchBuilder();
1135         EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder();
1136         ethTypeBuilder.setType(new EtherType(0x0800L));
1137         eth.setEthernetType(ethTypeBuilder.build());
1138         matchBuilder.setEthernetMatch(eth.build());
1139
1140         // Build the IPv4 Match requied per OVS Syntax
1141         IpMatchBuilder ipmatch = new IpMatchBuilder();
1142         ipmatch.setIpProtocol((short) 1);
1143         matchBuilder.setIpMatch(ipmatch.build());
1144
1145         // Build the ICMPv4 Match
1146         Icmpv4MatchBuilder icmpv4match = new Icmpv4MatchBuilder();
1147         icmpv4match.setIcmpv4Type(type);
1148         icmpv4match.setIcmpv4Code(code);
1149         matchBuilder.setIcmpv4Match(icmpv4match.build());
1150
1151         return matchBuilder;
1152     }
1153
1154     /**
1155      * @param matchBuilder MatchBuilder Object without a match yet
1156      * @param dstip        String containing an IPv4 prefix
1157      * @return matchBuilder Map Object with a match
1158      */
1159     private static MatchBuilder createDstL3IPv4Match(MatchBuilder matchBuilder, Ipv4Prefix dstip) {
1160
1161         EthernetMatchBuilder eth = new EthernetMatchBuilder();
1162         EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder();
1163         ethTypeBuilder.setType(new EtherType(0x0800L));
1164         eth.setEthernetType(ethTypeBuilder.build());
1165         matchBuilder.setEthernetMatch(eth.build());
1166
1167         Ipv4MatchBuilder ipv4match = new Ipv4MatchBuilder();
1168         ipv4match.setIpv4Destination(dstip);
1169
1170         matchBuilder.setLayer3Match(ipv4match.build());
1171
1172         return matchBuilder;
1173
1174     }
1175
1176     /**
1177      * @param matchBuilder MatchBuilder Object without a match yet
1178      * @param srcip        String containing an IPv4 prefix
1179      * @return             matchBuilder Map Object with a match
1180      */
1181     private static MatchBuilder createSrcL3IPv4Match(MatchBuilder matchBuilder, Ipv4Prefix srcip) {
1182
1183         EthernetMatchBuilder eth = new EthernetMatchBuilder();
1184         EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder();
1185         ethTypeBuilder.setType(new EtherType(0x0800L));
1186         eth.setEthernetType(ethTypeBuilder.build());
1187         matchBuilder.setEthernetMatch(eth.build());
1188
1189         Ipv4MatchBuilder ipv4Match = new Ipv4MatchBuilder();
1190         Ipv4MatchBuilder ipv4match = new Ipv4MatchBuilder();
1191         ipv4match.setIpv4Source(srcip);
1192         matchBuilder.setLayer3Match(ipv4match.build());
1193
1194         return matchBuilder;
1195
1196     }
1197
1198     /**
1199      * Create Source TCP Port Match
1200      *
1201      * @param matchBuilder @param matchbuilder MatchBuilder Object without a match yet
1202      * @param tcpport      Integer representing a source TCP port
1203      * @return             matchBuilder Map MatchBuilder Object with a match
1204      */
1205     protected static MatchBuilder createSetSrcTcpMatch(MatchBuilder matchBuilder, PortNumber tcpport) {
1206
1207         EthernetMatchBuilder ethType = new EthernetMatchBuilder();
1208         EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder();
1209         ethTypeBuilder.setType(new EtherType(0x0800L));
1210         ethType.setEthernetType(ethTypeBuilder.build());
1211         matchBuilder.setEthernetMatch(ethType.build());
1212
1213         IpMatchBuilder ipmatch = new IpMatchBuilder();
1214         ipmatch.setIpProtocol((short) 6);
1215         matchBuilder.setIpMatch(ipmatch.build());
1216
1217         TcpMatchBuilder tcpmatch = new TcpMatchBuilder();
1218         tcpmatch.setTcpSourcePort(tcpport);
1219         matchBuilder.setLayer4Match(tcpmatch.build());
1220
1221         return matchBuilder;
1222
1223     }
1224
1225     /**
1226      * Create Destination TCP Port Match
1227      *
1228      * @param matchBuilder MatchBuilder Object without a match yet
1229      * @param tcpport      Integer representing a destination TCP port
1230      * @return             matchBuilder Map MatchBuilder Object with a match
1231      */
1232     protected static MatchBuilder createSetDstTcpMatch(MatchBuilder matchBuilder, PortNumber tcpport) {
1233
1234         EthernetMatchBuilder ethType = new EthernetMatchBuilder();
1235         EthernetTypeBuilder ethTypeBuilder = new EthernetTypeBuilder();
1236         ethTypeBuilder.setType(new EtherType(0x0800L));
1237         ethType.setEthernetType(ethTypeBuilder.build());
1238         matchBuilder.setEthernetMatch(ethType.build());
1239
1240         IpMatchBuilder ipmatch = new IpMatchBuilder();
1241         ipmatch.setIpProtocol((short) 6);
1242         matchBuilder.setIpMatch(ipmatch.build());
1243
1244         PortNumber dstport = new PortNumber(tcpport);
1245         TcpMatchBuilder tcpmatch = new TcpMatchBuilder();
1246
1247         tcpmatch.setTcpDestinationPort(tcpport);
1248         matchBuilder.setLayer4Match(tcpmatch.build());
1249
1250         return matchBuilder;
1251     }
1252
1253     /**
1254      * Create Send to Controller Reserved Port Instruction (packet_in)
1255      *
1256      * @param ib Map InstructionBuilder without any instructions
1257      * @return ib Map InstructionBuilder with instructions
1258      */
1259
1260     protected static InstructionBuilder createSendToControllerInstructions(InstructionBuilder ib) {
1261
1262         List<Action> actionList = new ArrayList<Action>();
1263         ActionBuilder ab = new ActionBuilder();
1264
1265         OutputActionBuilder output = new OutputActionBuilder();
1266         output.setMaxLength(56);
1267         Uri value = new Uri("CONTROLLER");
1268         output.setOutputNodeConnector(value);
1269         ab.setAction(new OutputActionCaseBuilder().setOutputAction(output.build()).build());
1270         ab.setOrder(0);
1271         ab.setKey(new ActionKey(0));
1272         actionList.add(ab.build());
1273
1274         // Create an Apply Action
1275         ApplyActionsBuilder aab = new ApplyActionsBuilder();
1276         aab.setAction(actionList);
1277
1278         // Wrap our Apply Action in an Instruction
1279         ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
1280         ib.setOrder(0);
1281         ib.setKey(new InstructionKey(0));
1282
1283         return ib;
1284     }
1285
1286     /**
1287      * Create Output Port Instruction
1288      *
1289      * @param ib       Map InstructionBuilder without any instructions
1290      * @param dpidLong Long the datapath ID of a switch/node
1291      * @param port     Long representing a port on a switch/node
1292      * @return ib InstructionBuilder Map with instructions
1293      */
1294     protected static InstructionBuilder createOutputPortInstructions(InstructionBuilder ib, Long dpidLong, Long port) {
1295
1296         NodeConnectorId ncid = new NodeConnectorId("openflow:" + dpidLong + ":" + port);
1297         logger.debug("createOutputPortInstructions() Node Connector ID is - Type=openflow: DPID={} inPort={} ", dpidLong, port);
1298
1299         List<Action> actionList = new ArrayList<Action>();
1300         ActionBuilder ab = new ActionBuilder();
1301         OutputActionBuilder oab = new OutputActionBuilder();
1302         oab.setOutputNodeConnector(ncid);
1303
1304         ab.setAction(new OutputActionCaseBuilder().setOutputAction(oab.build()).build());
1305         ab.setOrder(5);
1306         ab.setKey(new ActionKey(5));
1307         actionList.add(ab.build());
1308
1309         // Create an Apply Action
1310         ApplyActionsBuilder aab = new ApplyActionsBuilder();
1311         aab.setAction(actionList);
1312         ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
1313
1314         return ib;
1315     }
1316
1317     /**
1318      * Create Set Vlan ID Instruction
1319      *
1320      * @param ib     Map InstructionBuilder without any instructions
1321      * @param vlanId Integer representing a VLAN ID Integer representing a VLAN ID
1322      * @return ib Map InstructionBuilder with instructions
1323      */
1324     protected static InstructionBuilder createSetVlanInstructions(InstructionBuilder ib, VlanId vlanId) {
1325
1326         List<Action> actionList = new ArrayList<Action>();
1327         ActionBuilder ab = new ActionBuilder();
1328
1329         SetVlanIdActionBuilder vl = new SetVlanIdActionBuilder();
1330         vl.setVlanId(vlanId);
1331         ab.setAction(new SetVlanIdActionCaseBuilder().setSetVlanIdAction(vl.build()).build());
1332         actionList.add(ab.build());
1333         // Create an Apply Action
1334         ApplyActionsBuilder aab = new ApplyActionsBuilder();
1335         aab.setAction(actionList);
1336
1337         // Wrap our Apply Action in an Instruction
1338         ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
1339
1340         return ib;
1341     }
1342
1343     /**
1344      * Create Set IPv4 Destination Instruction
1345      *
1346      * @param ib Map InstructionBuilder without any instructions
1347      * @return ib Map InstructionBuilder with instructions
1348      */
1349     protected static InstructionBuilder createStripVlanInstructions(InstructionBuilder ib) {
1350
1351         StripVlanActionBuilder stripVlanActionBuilder = new StripVlanActionBuilder();
1352         StripVlanAction vlanAction = stripVlanActionBuilder.build();
1353         ActionBuilder ab = new ActionBuilder();
1354         ab.setAction(new StripVlanActionCaseBuilder().setStripVlanAction(vlanAction).build());
1355
1356         // Add our drop action to a list
1357         List<Action> actionList = new ArrayList<Action>();
1358         actionList.add(ab.build());
1359
1360         // Create an Apply Action
1361         ApplyActionsBuilder aab = new ApplyActionsBuilder();
1362         aab.setAction(actionList);
1363
1364         // Wrap our Apply Action in an Instruction
1365         ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
1366         ib.setOrder(0);
1367         ib.setKey(new InstructionKey(0));
1368
1369         return ib;
1370     }
1371
1372     /**
1373      * Create Set IPv4 Source Instruction
1374      *
1375      * @param ib        Map InstructionBuilder without any instructions
1376      * @param prefixsrc String containing an IPv4 prefix
1377      * @return ib Map InstructionBuilder with instructions
1378      */
1379     protected static InstructionBuilder createNwSrcInstructions(InstructionBuilder ib, Ipv4Prefix prefixsrc) {
1380
1381         List<Action> actionList = new ArrayList<Action>();
1382         ActionBuilder ab = new ActionBuilder();
1383
1384         SetNwSrcActionBuilder setNwsrcActionBuilder = new SetNwSrcActionBuilder();
1385         Ipv4Builder ipsrc = new Ipv4Builder();
1386         ipsrc.setIpv4Address(prefixsrc);
1387         setNwsrcActionBuilder.setAddress(ipsrc.build());
1388         ab.setAction(new SetNwSrcActionCaseBuilder().setSetNwSrcAction(setNwsrcActionBuilder.build()).build());
1389         actionList.add(ab.build());
1390
1391         // Create an Apply Action
1392         ApplyActionsBuilder aab = new ApplyActionsBuilder();
1393         aab.setAction(actionList);
1394
1395         // Wrap our Apply Action in an Instruction
1396         ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
1397
1398         return ib;
1399     }
1400
1401     /**
1402      * Create Set IPv4 Destination Instruction
1403      *
1404      * @param ib           Map InstructionBuilder without any instructions
1405      * @param prefixdst    String containing an IPv4 prefix
1406      * @return ib Map InstructionBuilder with instructions
1407      */
1408     protected static InstructionBuilder createNwDstInstructions(InstructionBuilder ib, Ipv4Prefix prefixdst) {
1409
1410         List<Action> actionList = new ArrayList<Action>();
1411         ActionBuilder ab = new ActionBuilder();
1412
1413         SetNwDstActionBuilder setNwDstActionBuilder = new SetNwDstActionBuilder();
1414         Ipv4Builder ipdst = new Ipv4Builder();
1415         ipdst.setIpv4Address(prefixdst);
1416         setNwDstActionBuilder.setAddress(ipdst.build());
1417         ab.setAction(new SetNwDstActionCaseBuilder().setSetNwDstAction(setNwDstActionBuilder.build()).build());
1418         actionList.add(ab.build());
1419
1420         // Create an Apply Action
1421         ApplyActionsBuilder aab = new ApplyActionsBuilder();
1422         aab.setAction(actionList);
1423
1424         // Wrap our Apply Action in an Instruction
1425         ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
1426
1427         return ib;
1428     }
1429
1430     /**
1431      * Create Drop Instruction
1432      *
1433      * @param ib Map InstructionBuilder without any instructions
1434      * @return ib Map InstructionBuilder with instructions
1435      */
1436     protected static InstructionBuilder createDropInstructions(InstructionBuilder ib) {
1437
1438         DropActionBuilder dab = new DropActionBuilder();
1439         DropAction dropAction = dab.build();
1440         ActionBuilder ab = new ActionBuilder();
1441         ab.setAction(new DropActionCaseBuilder().setDropAction(dropAction).build());
1442
1443         // Add our drop action to a list
1444         List<Action> actionList = new ArrayList<Action>();
1445         actionList.add(ab.build());
1446
1447         // Create an Apply Action
1448         ApplyActionsBuilder aab = new ApplyActionsBuilder();
1449         aab.setAction(actionList);
1450
1451         // Wrap our Apply Action in an Instruction
1452         ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
1453         ib.setOrder(0);
1454         ib.setKey(new InstructionKey(0));
1455
1456         return ib;
1457     }
1458
1459     /**
1460      * Create GOTO Table Instruction Builder
1461      *
1462      * @param ib      Map InstructionBuilder without any instructions
1463      * @param tableId short representing a flow table ID short representing a flow table ID
1464      * @return ib Map InstructionBuilder with instructions
1465      */
1466     protected static InstructionBuilder createGotoTableInstructions(InstructionBuilder ib, short tableId) {
1467
1468         GoToTableBuilder gttb = new GoToTableBuilder();
1469         gttb.setTableId(tableId);
1470
1471         // Wrap our Apply Action in an InstructionBuilder
1472         ib.setInstruction(new GoToTableCaseBuilder().setGoToTable(gttb.build()).build());
1473         ib.setOrder(0);
1474         ib.setKey(new InstructionKey(0));
1475
1476         return ib;
1477     }
1478
1479     /**
1480      * Create Set Tunnel ID Instruction Builder
1481      *
1482      * @param ib       Map InstructionBuilder without any instructions
1483      * @param tunnelId BigInteger representing a tunnel ID
1484      * @return ib Map InstructionBuilder with instructions
1485      */
1486     protected static InstructionBuilder createSetTunnelIdInstructions(InstructionBuilder ib, BigInteger tunnelId) {
1487
1488         List<Action> actionList = new ArrayList<Action>();
1489         ActionBuilder ab = new ActionBuilder();
1490         SetFieldBuilder setFieldBuilder = new SetFieldBuilder();
1491
1492         // Build the Set Tunnel Field Action
1493         TunnelBuilder tunnel = new TunnelBuilder();
1494         tunnel.setTunnelId(tunnelId);
1495         setFieldBuilder.setTunnel(tunnel.build());
1496         ab.setAction(new SetFieldCaseBuilder().setSetField(setFieldBuilder.build()).build());
1497         actionList.add(ab.build());
1498
1499         ApplyActionsBuilder aab = new ApplyActionsBuilder();
1500         aab.setAction(actionList);
1501
1502         // Wrap the Apply Action in an InstructionBuilder and return
1503         ib.setOrder(0);
1504         ib.setKey(new InstructionKey(0));
1505         ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
1506
1507         return ib;
1508     }
1509
1510     /**
1511      * Create Set Source TCP Port Instruction
1512      *
1513      * @param ib      Map InstructionBuilder without any instructions
1514      * @param tcpport Integer representing a source TCP port
1515      * @return ib Map InstructionBuilder with instructions
1516      */
1517     protected static InstructionBuilder createSetSrcTCPPort(InstructionBuilder ib, PortNumber tcpport) {
1518
1519         List<Action> actionList = new ArrayList<Action>();
1520         ActionBuilder ab = new ActionBuilder();
1521         SetFieldBuilder setFieldBuilder = new SetFieldBuilder();
1522
1523         // Build the Destination TCP Port
1524         PortNumber tcpsrcport = new PortNumber(tcpport);
1525         TcpMatchBuilder tcpmatch = new TcpMatchBuilder();
1526         tcpmatch.setTcpSourcePort(tcpsrcport);
1527
1528         setFieldBuilder.setLayer4Match(tcpmatch.build());
1529         ab.setAction(new SetFieldCaseBuilder().setSetField(setFieldBuilder.build()).build());
1530         ab.setKey(new ActionKey(1));
1531         actionList.add(ab.build());
1532
1533         ApplyActionsBuilder aab = new ApplyActionsBuilder();
1534         aab.setAction(actionList);
1535         ib.setKey(new InstructionKey(1));
1536         ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
1537
1538         return ib;
1539     }
1540
1541     /**
1542      * Create Set Destination TCP Port Instruction
1543      *
1544      * @param ib      Map InstructionBuilder without any instructions
1545      * @param tcpport Integer representing a source TCP port
1546      * @return ib Map InstructionBuilder with instructions
1547      */
1548     protected static InstructionBuilder createSetDstTCPPort(InstructionBuilder ib, PortNumber tcpport) {
1549
1550         List<Action> actionList = new ArrayList<Action>();
1551         ActionBuilder ab = new ActionBuilder();
1552         SetFieldBuilder setFieldBuilder = new SetFieldBuilder();
1553
1554         // Build the Destination TCP Port
1555         PortNumber tcpdstport = new PortNumber(tcpport);
1556         TcpMatchBuilder tcpmatch = new TcpMatchBuilder();
1557         tcpmatch.setTcpDestinationPort(tcpdstport);
1558
1559         setFieldBuilder.setLayer4Match(tcpmatch.build());
1560         ab.setAction(new SetFieldCaseBuilder().setSetField(setFieldBuilder.build()).build());
1561         ab.setKey(new ActionKey(1));
1562         actionList.add(ab.build());
1563
1564         ApplyActionsBuilder aab = new ApplyActionsBuilder();
1565         aab.setAction(actionList);
1566         ib.setKey(new InstructionKey(1));
1567         ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
1568
1569         return ib;
1570     }
1571
1572     /**
1573      * Create Set Source UDP Port Instruction
1574      *
1575      * @param ib      Map InstructionBuilder without any instructions
1576      * @param udpport Integer representing a source UDP port
1577      * @return ib Map InstructionBuilder with instructions
1578      */
1579     protected static InstructionBuilder createSetSrcUDPPort(InstructionBuilder ib, PortNumber udpport) {
1580
1581         List<Action> actionList = new ArrayList<Action>();
1582         ActionBuilder ab = new ActionBuilder();
1583         SetFieldBuilder setFieldBuilder = new SetFieldBuilder();
1584
1585         // Build the Destination TCP Port
1586         PortNumber udpsrcport = new PortNumber(udpport);
1587         UdpMatchBuilder udpmatch = new UdpMatchBuilder();
1588         udpmatch.setUdpSourcePort(udpsrcport);
1589
1590         setFieldBuilder.setLayer4Match(udpmatch.build());
1591         ab.setAction(new SetFieldCaseBuilder().setSetField(setFieldBuilder.build()).build());
1592         ab.setKey(new ActionKey(1));
1593         actionList.add(ab.build());
1594
1595         ApplyActionsBuilder aab = new ApplyActionsBuilder();
1596         aab.setAction(actionList);
1597         ib.setKey(new InstructionKey(1));
1598         ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
1599
1600         return ib;
1601     }
1602
1603     /**
1604      * Create Set Destination UDP Port Instruction
1605      *
1606      * @param ib      Map InstructionBuilder without any instructions
1607      * @param udpport Integer representing a destination UDP port
1608      * @return ib Map InstructionBuilder with instructions
1609      */
1610     protected static InstructionBuilder createSetDstUDPPort(InstructionBuilder ib, PortNumber udpport) {
1611
1612         List<Action> actionList = new ArrayList<Action>();
1613         ActionBuilder ab = new ActionBuilder();
1614         SetFieldBuilder setFieldBuilder = new SetFieldBuilder();
1615
1616         // Build the Destination TCP Port
1617         PortNumber udpdstport = new PortNumber(udpport);
1618         UdpMatchBuilder udpmatch = new UdpMatchBuilder();
1619         udpmatch.setUdpDestinationPort(udpdstport);
1620
1621         setFieldBuilder.setLayer4Match(udpmatch.build());
1622         ab.setAction(new SetFieldCaseBuilder().setSetField(setFieldBuilder.build()).build());
1623         ab.setKey(new ActionKey(1));
1624         actionList.add(ab.build());
1625
1626         ApplyActionsBuilder aab = new ApplyActionsBuilder();
1627         aab.setAction(actionList);
1628         ib.setKey(new InstructionKey(1));
1629         ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
1630
1631         return ib;
1632     }
1633
1634     /**
1635      * Create Set ICMP Code Instruction
1636      *
1637      * @param ib   Map InstructionBuilder without any instructions
1638      * @param code short repesenting an ICMP code
1639      * @return ib Map InstructionBuilder with instructions
1640      */
1641
1642     private static InstructionBuilder createSetIcmpCodeInstruction(InstructionBuilder ib, short code) {
1643
1644         List<Action> actionList = new ArrayList<Action>();
1645         ActionBuilder ab = new ActionBuilder();
1646         SetFieldBuilder setFieldBuilder = new SetFieldBuilder();
1647         Icmpv4MatchBuilder icmpv4match = new Icmpv4MatchBuilder();
1648
1649         // Build the ICMPv4 Code Match
1650         icmpv4match.setIcmpv4Code(code);
1651         setFieldBuilder.setIcmpv4Match(icmpv4match.build());
1652
1653         ab.setAction(new SetFieldCaseBuilder().setSetField(setFieldBuilder.build()).build());
1654         ab.setKey(new ActionKey(0));
1655         actionList.add(ab.build());
1656         ApplyActionsBuilder aab = new ApplyActionsBuilder();
1657         aab.setAction(actionList);
1658
1659         // Wrap our Apply Action in an Instruction
1660         ib.setKey(new InstructionKey(0));
1661         ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
1662
1663         return ib;
1664     }
1665
1666     /**
1667      * Create Set ICMP Code Instruction
1668      *
1669      * @param ib Map InstructionBuilder without any instructions
1670      * @return ib Map InstructionBuilder with instructions
1671      */
1672     private static InstructionBuilder createSetIcmpTypeInstruction(InstructionBuilder ib, short type) {
1673
1674         List<Action> actionList = new ArrayList<Action>();
1675         ActionBuilder ab = new ActionBuilder();
1676         SetFieldBuilder setFieldBuilder = new SetFieldBuilder();
1677         Icmpv4MatchBuilder icmpv4match = new Icmpv4MatchBuilder();
1678
1679         // Build the ICMPv4 Code Match
1680         icmpv4match.setIcmpv4Code(type);
1681         setFieldBuilder.setIcmpv4Match(icmpv4match.build());
1682
1683         ab.setAction(new SetFieldCaseBuilder().setSetField(setFieldBuilder.build()).build());
1684         ab.setKey(new ActionKey(1));
1685         actionList.add(ab.build());
1686         ApplyActionsBuilder aab = new ApplyActionsBuilder();
1687         aab.setAction(actionList);
1688
1689         // Wrap our Apply Action in an Instruction
1690         ib.setKey(new InstructionKey(1));
1691         ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
1692
1693         return ib;
1694     }
1695
1696     /**
1697      * Create Decrement TTL Instruction
1698      *
1699      * @param ib Map InstructionBuilder without any instructions
1700      * @return ib Map InstructionBuilder with instructions
1701      */
1702     private static InstructionBuilder createDecNwTtlInstructions(InstructionBuilder ib) {
1703         DecNwTtlBuilder decNwTtlBuilder = new DecNwTtlBuilder();
1704         DecNwTtl decNwTtl = decNwTtlBuilder.build();
1705         ActionBuilder ab = new ActionBuilder();
1706         ab.setAction(new DecNwTtlCaseBuilder().setDecNwTtl(decNwTtl).build());
1707
1708         // Add our drop action to a list
1709         List<Action> actionList = new ArrayList<Action>();
1710         actionList.add(ab.build());
1711
1712         // Create an Apply Action
1713         ApplyActionsBuilder aab = new ApplyActionsBuilder();
1714         aab.setAction(actionList);
1715
1716         // Wrap our Apply Action in an Instruction
1717         ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
1718         ib.setKey(new InstructionKey(0));
1719         ib.setOrder(0);
1720
1721         return ib;
1722     }
1723
1724     /**
1725      * Set Src Arp MAC
1726      */
1727     private static InstructionBuilder createSrcArpMacInstructions(InstructionBuilder ib, MacAddress macsrc) {
1728
1729         List<Action> actionList = new ArrayList<Action>();
1730         ActionBuilder ab = new ActionBuilder();
1731
1732         SetFieldBuilder setFieldBuilder = new SetFieldBuilder();
1733         ArpMatchBuilder arpmatch = new ArpMatchBuilder();
1734         ArpSourceHardwareAddressBuilder arpsrc = new ArpSourceHardwareAddressBuilder();
1735         arpsrc.setAddress(macsrc);
1736         arpmatch.setArpSourceHardwareAddress(arpsrc.build());
1737         setFieldBuilder.setLayer3Match(arpmatch.build());
1738         ab.setAction(new SetFieldCaseBuilder().setSetField(setFieldBuilder.build()).build());
1739         ab.setKey(new ActionKey(0));
1740         actionList.add(ab.build());
1741
1742         ApplyActionsBuilder aab = new ApplyActionsBuilder();
1743         aab.setAction(actionList);
1744
1745         return ib;
1746     }
1747
1748     /**
1749      * Set Dst Arp MAC
1750      */
1751     private static InstructionBuilder createDstArpMacInstructions(InstructionBuilder ib, MacAddress macdst) {
1752
1753         List<Action> actionList = new ArrayList<Action>();
1754         ActionBuilder ab = new ActionBuilder();
1755         SetFieldBuilder setFieldBuilder = new SetFieldBuilder();
1756
1757         ArpMatchBuilder arpmatch = new ArpMatchBuilder();
1758         ArpTargetHardwareAddressBuilder arpdst = new ArpTargetHardwareAddressBuilder();
1759         arpdst.setAddress(macdst);
1760         setFieldBuilder.setLayer3Match(arpmatch.build());
1761         ab.setAction(new SetFieldCaseBuilder().setSetField(setFieldBuilder.build()).build());
1762         ab.setKey(new ActionKey(0));
1763         actionList.add(ab.build());
1764
1765         ApplyActionsBuilder aab = new ApplyActionsBuilder();
1766         aab.setAction(actionList);
1767
1768         return ib;
1769     }
1770
1771     /**
1772      * Set Dst Arp IP
1773      */
1774     private static InstructionBuilder createDstArpIpInstructions(InstructionBuilder ib, Ipv4Prefix dstiparp) {
1775
1776         List<Action> actionList = new ArrayList<Action>();
1777         ActionBuilder ab = new ActionBuilder();
1778         SetFieldBuilder setFieldBuilder = new SetFieldBuilder();
1779
1780         ArpMatchBuilder arpmatch = new ArpMatchBuilder();
1781         arpmatch.setArpTargetTransportAddress(dstiparp);
1782         setFieldBuilder.setLayer3Match(arpmatch.build());
1783         ab.setAction(new SetFieldCaseBuilder().setSetField(setFieldBuilder.build()).build());
1784         ab.setKey(new ActionKey(0));
1785         actionList.add(ab.build());
1786
1787         ApplyActionsBuilder aab = new ApplyActionsBuilder();
1788         aab.setAction(actionList);
1789
1790         return ib;
1791     }
1792
1793     /**
1794      * Set Src Arp IP
1795      */
1796     private static InstructionBuilder createSrcArpIpInstructions(InstructionBuilder ib, Ipv4Prefix srciparp) {
1797
1798         List<Action> actionList = new ArrayList<Action>();
1799         ActionBuilder ab = new ActionBuilder();
1800         SetFieldBuilder setFieldBuilder = new SetFieldBuilder();
1801
1802         ArpMatchBuilder arpmatch = new ArpMatchBuilder();
1803         arpmatch.setArpSourceTransportAddress(srciparp);
1804         setFieldBuilder.setLayer3Match(arpmatch.build());
1805         ab.setAction(new SetFieldCaseBuilder().setSetField(setFieldBuilder.build()).build());
1806         ab.setKey(new ActionKey(0));
1807         actionList.add(ab.build());
1808
1809         ApplyActionsBuilder aab = new ApplyActionsBuilder();
1810         aab.setAction(actionList);
1811
1812         return ib;
1813     }
1814
1815     @Override
1816     public void initializeOFFlowRules(Node openflowNode) {
1817     }
1818
1819     private NodeBuilder createNodeBuilder(String nodeId) {
1820         NodeBuilder builder = new NodeBuilder();
1821         builder.setId(new NodeId(nodeId));
1822         builder.setKey(new NodeKey(builder.getId()));
1823         return builder;
1824     }
1825
1826     private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node> nodeBuilderToInstanceId(NodeBuilder
1827                                                                                                                                              node) {
1828         return InstanceIdentifier.builder(Nodes.class).child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node.class,
1829                 node.getKey()).toInstance();
1830     }
1831 }