Update to work on Sodium SR1
[l2switch.git] / l2switch-main / src / main / java / org / opendaylight / l2switch / flow / FlowWriterServiceImpl.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.flow;
9
10 import com.google.common.base.Preconditions;
11 import com.google.common.collect.ImmutableList;
12 import java.math.BigInteger;
13 import java.util.concurrent.Future;
14 import java.util.concurrent.atomic.AtomicLong;
15 import org.opendaylight.l2switch.util.InstanceIdentifierUtils;
16 import org.opendaylight.openflowplugin.api.OFConstants;
17 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
18 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
19 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.OutputActionCaseBuilder;
20 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.output.action._case.OutputActionBuilder;
21 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
22 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.ActionBuilder;
23 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
24 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInputBuilder;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowOutput;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.FlowTableRef;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.SalFlowService;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowCookie;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowModFlags;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowRef;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.InstructionsBuilder;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.Match;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.ApplyActionsCaseBuilder;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.apply.actions._case.ApplyActions;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.apply.actions._case.ApplyActionsBuilder;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionBuilder;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ethernet.match.fields.EthernetDestinationBuilder;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ethernet.match.fields.EthernetSourceBuilder;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.EthernetMatch;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.EthernetMatchBuilder;
52 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
53 import org.opendaylight.yangtools.yang.common.RpcResult;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56
57 /**
58  * Implementation of
59  * FlowWriterService{@link org.opendaylight.l2switch.flow.FlowWriterService},
60  * that builds required flow and writes to configuration data store using
61  * provided {@link org.opendaylight.controller.md.sal.binding.api.DataBroker}.
62  */
63 public class FlowWriterServiceImpl implements FlowWriterService {
64     private static final Logger LOG = LoggerFactory.getLogger(FlowWriterServiceImpl.class);
65     private static final String FLOW_ID_PREFIX = "L2switch-";
66
67     private final SalFlowService salFlowService;
68     private short flowTableId;
69     private int flowPriority;
70     private int flowIdleTimeout;
71     private int flowHardTimeout;
72
73     private final AtomicLong flowIdInc = new AtomicLong();
74     private final AtomicLong flowCookieInc = new AtomicLong(0x2a00000000000000L);
75
76     public FlowWriterServiceImpl(SalFlowService salFlowService) {
77         Preconditions.checkNotNull(salFlowService, "salFlowService should not be null.");
78         this.salFlowService = salFlowService;
79     }
80
81     public void setFlowTableId(short flowTableId) {
82         this.flowTableId = flowTableId;
83     }
84
85     public void setFlowPriority(int flowPriority) {
86         this.flowPriority = flowPriority;
87     }
88
89     public void setFlowIdleTimeout(int flowIdleTimeout) {
90         this.flowIdleTimeout = flowIdleTimeout;
91     }
92
93     public void setFlowHardTimeout(int flowHardTimeout) {
94         this.flowHardTimeout = flowHardTimeout;
95     }
96
97     @Override
98     public void addMacToMacFlow(MacAddress sourceMac, MacAddress destMac, NodeConnectorRef destNodeConnectorRef) {
99
100         Preconditions.checkNotNull(destMac, "Destination mac address should not be null.");
101         Preconditions.checkNotNull(destNodeConnectorRef, "Destination port should not be null.");
102
103         // do not add flow if both macs are same.
104         if (sourceMac != null && destMac.equals(sourceMac)) {
105             LOG.info("In addMacToMacFlow: No flows added. Source and Destination mac are same.");
106             return;
107         }
108
109         // get flow table key
110         TableKey flowTableKey = new TableKey(flowTableId);
111
112         // build a flow path based on node connector to program flow
113         InstanceIdentifier<Flow> flowPath = buildFlowPath(destNodeConnectorRef, flowTableKey);
114
115         // build a flow that target given mac id
116         Flow flowBody = createMacToMacFlow(flowTableKey.getId(), flowPriority, sourceMac, destMac,
117                 destNodeConnectorRef);
118
119         // commit the flow in config data
120         writeFlowToConfigData(flowPath, flowBody);
121     }
122
123     @Override
124     public void addBidirectionalMacToMacFlows(MacAddress sourceMac, NodeConnectorRef sourceNodeConnectorRef,
125             MacAddress destMac, NodeConnectorRef destNodeConnectorRef) {
126         Preconditions.checkNotNull(sourceMac, "Source mac address should not be null.");
127         Preconditions.checkNotNull(sourceNodeConnectorRef, "Source port should not be null.");
128         Preconditions.checkNotNull(destMac, "Destination mac address should not be null.");
129         Preconditions.checkNotNull(destNodeConnectorRef, "Destination port should not be null.");
130
131         if (sourceNodeConnectorRef.equals(destNodeConnectorRef)) {
132             LOG.info(
133                     "In addMacToMacFlowsUsingShortestPath: No flows added. Source and Destination ports are same.");
134             return;
135
136         }
137
138         // add destMac-To-sourceMac flow on source port
139         addMacToMacFlow(destMac, sourceMac, sourceNodeConnectorRef);
140
141         // add sourceMac-To-destMac flow on destination port
142         addMacToMacFlow(sourceMac, destMac, destNodeConnectorRef);
143     }
144
145     private InstanceIdentifier<Flow> buildFlowPath(NodeConnectorRef nodeConnectorRef, TableKey flowTableKey) {
146
147         // generate unique flow key
148         FlowId flowId = new FlowId(FLOW_ID_PREFIX + String.valueOf(flowIdInc.getAndIncrement()));
149         FlowKey flowKey = new FlowKey(flowId);
150
151         return InstanceIdentifierUtils.generateFlowInstanceIdentifier(nodeConnectorRef, flowTableKey, flowKey);
152     }
153
154     /**
155      * Builds a flow that forwards all packets with destMac to given port.
156      *
157      * @param tableId the table id
158      * @param priority the flow priority
159      * @param sourceMac the source MAC of the flow
160      * @param destMac the destination MAC of the flow
161      * @param destPort the destination port
162      * @return the Flow
163      */
164     private Flow createMacToMacFlow(Short tableId, int priority, MacAddress sourceMac, MacAddress destMac,
165             NodeConnectorRef destPort) {
166
167         // start building flow
168         FlowBuilder macToMacFlow = new FlowBuilder() //
169                 .setTableId(tableId) //
170                 .setFlowName("mac2mac");
171
172         // use its own hash code for id.
173         macToMacFlow.setId(new FlowId(Long.toString(macToMacFlow.hashCode())));
174
175         // create a match that has mac to mac ethernet match
176         EthernetMatchBuilder ethernetMatchBuilder = new EthernetMatchBuilder() //
177                 .setEthernetDestination(new EthernetDestinationBuilder() //
178                         .setAddress(destMac) //
179                         .build());
180         // set source in the match only if present
181         if (sourceMac != null) {
182             ethernetMatchBuilder.setEthernetSource(new EthernetSourceBuilder().setAddress(sourceMac).build());
183         }
184         EthernetMatch ethernetMatch = ethernetMatchBuilder.build();
185         Match match = new MatchBuilder().setEthernetMatch(ethernetMatch).build();
186
187         Uri destPortUri = destPort.getValue().firstKeyOf(NodeConnector.class).getId();
188
189         Action outputToControllerAction = new ActionBuilder() //
190                 .setOrder(0)
191                 .setAction(new OutputActionCaseBuilder() //
192                         .setOutputAction(new OutputActionBuilder() //
193                                 .setMaxLength(0xffff) //
194                                 .setOutputNodeConnector(destPortUri) //
195                                 .build()) //
196                         .build()) //
197                 .build();
198
199         // Create an Apply Action
200         ApplyActions applyActions = new ApplyActionsBuilder().setAction(ImmutableList.of(outputToControllerAction))
201                 .build();
202
203         // Wrap our Apply Action in an Instruction
204         Instruction applyActionsInstruction = new InstructionBuilder() //
205                 .setOrder(0)
206                 .setInstruction(new ApplyActionsCaseBuilder()//
207                         .setApplyActions(applyActions) //
208                         .build()) //
209                 .build();
210
211         // Put our Instruction in a list of Instructions
212         macToMacFlow.setMatch(match) //
213                 .setInstructions(new InstructionsBuilder() //
214                         .setInstruction(ImmutableList.of(applyActionsInstruction)) //
215                         .build()) //
216                 .setPriority(priority) //
217                 .setBufferId(OFConstants.OFP_NO_BUFFER) //
218                 .setHardTimeout(flowHardTimeout) //
219                 .setIdleTimeout(flowIdleTimeout) //
220                 .setCookie(new FlowCookie(BigInteger.valueOf(flowCookieInc.getAndIncrement())))
221                 .setFlags(new FlowModFlags(false, false, false, false, false));
222
223         return macToMacFlow.build();
224     }
225
226     /**
227      * Starts and commits data change transaction which modifies provided flow
228      * path with supplied body.
229      *
230      * @param flowPath the Flow path
231      * @param flow the Flow
232      * @return transaction commit
233      */
234     private Future<RpcResult<AddFlowOutput>> writeFlowToConfigData(InstanceIdentifier<Flow> flowPath, Flow flow) {
235         final InstanceIdentifier<Table> tableInstanceId = flowPath.<Table>firstIdentifierOf(Table.class);
236         final InstanceIdentifier<Node> nodeInstanceId = flowPath.<Node>firstIdentifierOf(Node.class);
237         final AddFlowInputBuilder builder = new AddFlowInputBuilder(flow);
238         builder.setNode(new NodeRef(nodeInstanceId));
239         builder.setFlowRef(new FlowRef(flowPath));
240         builder.setFlowTable(new FlowTableRef(tableInstanceId));
241         builder.setTransactionUri(new Uri(flow.getId().getValue()));
242         return salFlowService.addFlow(builder.build());
243     }
244 }