Integrate LoopRemover module with config subsystem.
[l2switch.git] / loopremover / implementation / src / main / java / org / opendaylight / l2switch / loopremover / flow / InitialFlowWriter.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.l2switch.loopremover.flow;
9
10 import com.google.common.collect.ImmutableList;
11 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Uri;
12 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.OutputActionCaseBuilder;
13 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.output.action._case.OutputActionBuilder;
14 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
15 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.ActionBuilder;
16 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.ActionKey;
17 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
18 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
19 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
20 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
21 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
22 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
23 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
24 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInputBuilder;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowOutput;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.FlowTableRef;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.SalFlowService;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowCookie;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowModFlags;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowRef;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.OutputPortValues;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.InstructionsBuilder;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.Match;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.ApplyActionsCaseBuilder;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.apply.actions._case.ApplyActions;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.apply.actions._case.ApplyActionsBuilder;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionBuilder;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRemoved;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorUpdated;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRemoved;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeUpdated;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.OpendaylightInventoryListener;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.EtherType;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ethernet.match.fields.EthernetTypeBuilder;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.EthernetMatchBuilder;
50 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
51 import org.opendaylight.yangtools.yang.common.RpcResult;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 import java.math.BigInteger;
56 import java.util.concurrent.ExecutorService;
57 import java.util.concurrent.Executors;
58 import java.util.concurrent.Future;
59 import java.util.concurrent.atomic.AtomicLong;
60
61 /**
62  * Adds default flows on all switches. Registers as ODL Inventory listener so that
63  * it can add flows once a new node i.e. switch is added
64  */
65 public class InitialFlowWriter implements OpendaylightInventoryListener {
66   private final Logger _logger = LoggerFactory.getLogger(InitialFlowWriter.class);
67
68   private final ExecutorService initialFlowExecutor = Executors.newCachedThreadPool();
69   private final SalFlowService salFlowService;
70   private final int LLDP_ETHER_TYPE = 35020;
71   private short flowTableId;
72   private int flowPriority;
73   private int flowIdleTimeout;
74   private int flowHardTimeout;
75
76   private AtomicLong flowIdInc = new AtomicLong();
77   private AtomicLong flowCookieInc = new AtomicLong(0x2b00000000000000L);
78
79
80   public InitialFlowWriter(SalFlowService salFlowService) {
81     this.salFlowService = salFlowService;
82   }
83
84   public void setFlowTableId(short flowTableId) {
85     this.flowTableId = flowTableId;
86   }
87
88   public void setFlowPriority(int flowPriority) {
89     this.flowPriority = flowPriority;
90   }
91
92   public void setFlowIdleTimeout(int flowIdleTimeout) {
93     this.flowIdleTimeout = flowIdleTimeout;
94   }
95
96   public void setFlowHardTimeout(int flowHardTimeout) {
97     this.flowHardTimeout = flowHardTimeout;
98   }
99
100   @Override
101   public void onNodeConnectorRemoved(NodeConnectorRemoved nodeConnectorRemoved) {
102     //do nothing
103   }
104
105   @Override
106   public void onNodeConnectorUpdated(NodeConnectorUpdated nodeConnectorUpdated) {
107     //do nothing
108   }
109
110   @Override
111   public void onNodeRemoved(NodeRemoved nodeRemoved) {
112     //do nothing
113   }
114
115   @Override
116   public void onNodeUpdated(NodeUpdated nodeUpdated) {
117     initialFlowExecutor.submit(new InitialFlowWriterProcessor(nodeUpdated));
118   }
119
120   /**
121    * A private class to process the node updated event in separate thread. Allows to release the
122    * thread that invoked the data node updated event. Avoids any thread lock it may cause.
123    */
124   private class InitialFlowWriterProcessor implements Runnable {
125     private NodeUpdated nodeUpdated;
126
127     public InitialFlowWriterProcessor(NodeUpdated nodeUpdated) {
128       this.nodeUpdated = nodeUpdated;
129     }
130
131     @Override
132     public void run() {
133
134       if(nodeUpdated == null) {
135         return;
136       }
137
138       addInitialFlows((InstanceIdentifier<Node>) nodeUpdated.getNodeRef().getValue());
139
140     }
141
142     public void addInitialFlows(InstanceIdentifier<Node> nodeId) {
143       _logger.debug("adding initial flows for node {} ", nodeId);
144
145       InstanceIdentifier<Table> tableId = getTableInstanceId(nodeId);
146       InstanceIdentifier<Flow> flowId = getFlowInstanceId(tableId);
147
148       //add lldpToController flow
149       writeFlowToController(nodeId, tableId, flowId, createLldpToControllerFlow(flowTableId, flowPriority));
150
151       _logger.debug("Added initial flows for node {} ", nodeId);
152     }
153
154     private InstanceIdentifier<Table> getTableInstanceId(InstanceIdentifier<Node> nodeId) {
155       // get flow table key
156       TableKey flowTableKey = new TableKey(flowTableId);
157
158       return nodeId.builder()
159           .augmentation(FlowCapableNode.class)
160           .child(Table.class, flowTableKey)
161           .build();
162     }
163
164     private InstanceIdentifier<Flow> getFlowInstanceId(InstanceIdentifier<Table> tableId) {
165       // generate unique flow key
166       FlowId flowId = new FlowId(String.valueOf(flowIdInc.getAndIncrement()));
167       FlowKey flowKey = new FlowKey(flowId);
168       return tableId.child(Flow.class, flowKey);
169     }
170
171     private Flow createLldpToControllerFlow(Short tableId, int priority) {
172
173       // start building flow
174       FlowBuilder lldpFlow = new FlowBuilder() //
175           .setTableId(tableId) //
176           .setFlowName("lldptocntrl");
177
178       // use its own hash code for id.
179       lldpFlow.setId(new FlowId(Long.toString(lldpFlow.hashCode())));
180       EthernetMatchBuilder ethernetMatchBuilder = new EthernetMatchBuilder()
181           .setEthernetType(new EthernetTypeBuilder()
182               .setType(new EtherType(Long.valueOf(LLDP_ETHER_TYPE))).build());
183
184       Match match = new MatchBuilder()
185           .setEthernetMatch(ethernetMatchBuilder.build())
186           .build();
187
188       // Create an Apply Action
189       ApplyActions applyActions = new ApplyActionsBuilder().setAction(ImmutableList.of(getSendToControllerAction()))
190           .build();
191
192       // Wrap our Apply Action in an Instruction
193       Instruction applyActionsInstruction = new InstructionBuilder() //
194           .setOrder(0)
195           .setInstruction(new ApplyActionsCaseBuilder()//
196               .setApplyActions(applyActions) //
197               .build()) //
198           .build();
199
200       // Put our Instruction in a list of Instructions
201       lldpFlow
202           .setMatch(match) //
203           .setInstructions(new InstructionsBuilder() //
204               .setInstruction(ImmutableList.of(applyActionsInstruction)) //
205               .build()) //
206           .setPriority(priority) //
207           .setBufferId(0L) //
208           .setHardTimeout(flowHardTimeout) //
209           .setIdleTimeout(flowIdleTimeout) //
210           .setCookie(new FlowCookie(BigInteger.valueOf(flowCookieInc.getAndIncrement())))
211           .setFlags(new FlowModFlags(false, false, false, false, false));
212
213       return lldpFlow.build();
214     }
215
216     private Action getSendToControllerAction() {
217       Action sendToController = new ActionBuilder()
218           .setOrder(0)
219           .setKey(new ActionKey(0))
220           .setAction(new OutputActionCaseBuilder()
221               .setOutputAction(new OutputActionBuilder()
222                   .setMaxLength(new Integer(0xffff))
223                   .setOutputNodeConnector(new Uri(OutputPortValues.CONTROLLER.toString()))
224                   .build())
225               .build())
226           .build();
227
228       return sendToController;
229     }
230
231     private Future<RpcResult<AddFlowOutput>> writeFlowToController(InstanceIdentifier<Node> nodeInstanceId,
232                                                                    InstanceIdentifier<Table> tableInstanceId,
233                                                                    InstanceIdentifier<Flow> flowPath,
234                                                                    Flow flow) {
235       final AddFlowInputBuilder builder = new AddFlowInputBuilder(flow);
236       builder.setNode(new NodeRef(nodeInstanceId));
237       builder.setFlowRef(new FlowRef(flowPath));
238       builder.setFlowTable(new FlowTableRef(tableInstanceId));
239       builder.setTransactionUri(new Uri(flow.getId().getValue()));
240       return salFlowService.addFlow(builder.build());
241     }
242   }
243 }