5a94eb972b8fa639938278590861e02f9a92700a
[ovsdb.git] / openstack / net-virt-providers / src / main / java / org / opendaylight / ovsdb / openstack / netvirt / providers / openflow13 / AbstractServiceInstance.java
1 /*
2  * Copyright (c) 2014, 2015 Red Hat, Inc. and others. All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13;
10
11 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
12 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
13 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
14 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
15 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
16 import org.opendaylight.ovsdb.openstack.netvirt.api.Southbound;
17 import org.opendaylight.ovsdb.openstack.netvirt.api.Constants;
18 import org.opendaylight.ovsdb.openstack.netvirt.providers.NetvirtProvidersProvider;
19 import org.opendaylight.ovsdb.utils.mdsal.openflow.InstructionUtils;
20 import org.opendaylight.ovsdb.utils.servicehelper.ServiceHelper;
21 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
22 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
23 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
24 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.InstructionsBuilder;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionBuilder;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionKey;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
37 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
38 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
39
40 import com.google.common.base.Optional;
41 import com.google.common.collect.Lists;
42 import com.google.common.util.concurrent.CheckedFuture;
43
44 import java.util.List;
45 import java.util.concurrent.ExecutionException;
46
47 import org.osgi.framework.ServiceReference;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 /**
52  * Any ServiceInstance class that extends AbstractServiceInstance to be a part of the pipeline
53  * have 2 basic requirements : <br>
54  * 1. Program a default pipeline flow to take any unmatched traffic to the next table in the pipeline. <br>
55  * 2. Get Pipeline Instructions from AbstractServiceInstance (using getMutablePipelineInstructionBuilder) and
56  *    use it in any matching flows that needs to be further processed by next service in the pipeline.
57  *
58  */
59 public abstract class AbstractServiceInstance {
60     public static final String SERVICE_PROPERTY ="serviceProperty";
61     private static final Logger LOG = LoggerFactory.getLogger(AbstractServiceInstance.class);
62     public static final String OPENFLOW = "openflow:";
63     private DataBroker dataBroker = null;
64     // OSGi Services that we are dependent on.
65     private volatile PipelineOrchestrator orchestrator;
66     private volatile Southbound southbound;
67
68     // Concrete Service that this AbstractServiceInstance represents
69     private Service service;
70
71     public AbstractServiceInstance (Service service) {
72         this.service = service;
73         this.dataBroker = NetvirtProvidersProvider.getDataBroker();
74     }
75
76     protected void setDependencies(final ServiceReference ref, AbstractServiceInstance serviceInstance) {
77         this.orchestrator =
78                 (PipelineOrchestrator) ServiceHelper.getGlobalInstance(PipelineOrchestrator.class, serviceInstance);
79         orchestrator.registerService(ref, serviceInstance);
80         this.southbound =
81                 (Southbound) ServiceHelper.getGlobalInstance(Southbound.class, serviceInstance);
82     }
83
84     public boolean isBridgeInPipeline (Node node){
85         String bridgeName = southbound.getBridgeName(node);
86         return bridgeName != null && Constants.INTEGRATION_BRIDGE.equals(bridgeName);
87     }
88
89     public short getTable() {
90         return service.getTable();
91     }
92
93     public Service getService() {
94         return service;
95     }
96
97     public void setService(Service service) {
98         this.service = service;
99     }
100
101     public NodeBuilder createNodeBuilder(String nodeId) {
102         NodeBuilder builder = new NodeBuilder();
103         builder.setId(new NodeId(nodeId));
104         builder.setKey(new NodeKey(builder.getId()));
105         return builder;
106     }
107
108     private static InstanceIdentifier<Flow> createFlowPath(FlowBuilder flowBuilder, NodeBuilder nodeBuilder) {
109         return InstanceIdentifier.builder(Nodes.class)
110                 .child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node.class,
111                         nodeBuilder.getKey())
112                 .augmentation(FlowCapableNode.class)
113                 .child(Table.class, new TableKey(flowBuilder.getTableId()))
114                 .child(Flow.class, flowBuilder.getKey()).build();
115     }
116
117     private static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node>
118     createNodePath(NodeBuilder nodeBuilder) {
119         return InstanceIdentifier.builder(Nodes.class)
120                 .child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node.class,
121                         nodeBuilder.getKey()).build();
122     }
123
124     /**
125      * This method returns the required Pipeline Instructions to by used by any matching flows that need
126      * to be further processed by next service in the pipeline.
127      *
128      * Important to note that this is a convenience method which returns a mutable instructionBuilder which
129      * needs to be further adjusted by the concrete ServiceInstance class such as setting the Instruction Order, etc.
130      * @return Newly created InstructionBuilder to be used along with other instructions on the main flow
131      */
132     protected final InstructionBuilder getMutablePipelineInstructionBuilder() {
133         Service nextService = orchestrator.getNextServiceInPipeline(service);
134         if (nextService != null) {
135             return InstructionUtils.createGotoTableInstructions(new InstructionBuilder(), nextService.getTable());
136         } else {
137             return InstructionUtils.createDropInstructions(new InstructionBuilder());
138         }
139     }
140
141     protected void writeFlow(FlowBuilder flowBuilder, NodeBuilder nodeBuilder) {
142         LOG.debug("writeFlow 3: flowBuilder: {}, nodeBuilder: {}",
143                 flowBuilder.build(), nodeBuilder.build());
144         WriteTransaction modification = dataBroker.newWriteOnlyTransaction();
145         LOG.debug("writeFlow: about to put nodePath for Flow {}, nodePath: {}",
146                 flowBuilder.getFlowName(), createNodePath(nodeBuilder));
147         modification.put(LogicalDatastoreType.CONFIGURATION, createNodePath(nodeBuilder),
148                 nodeBuilder.build(), true /*createMissingParents*/);
149         LOG.debug("writeFlow: about to put Flow {}", flowBuilder.getFlowName());
150         modification.put(LogicalDatastoreType.CONFIGURATION, createFlowPath(flowBuilder, nodeBuilder),
151                 flowBuilder.build(), true /*createMissingParents*/);
152         LOG.debug("writeFlow: about to submit Flow {}", flowBuilder.getFlowName());
153         CheckedFuture<Void, TransactionCommitFailedException> commitFuture = modification.submit();
154         LOG.debug("writeFlow: checking status of Flow {}", flowBuilder.getFlowName());
155         try {
156             commitFuture.checkedGet();  // TODO: Make it async (See bug 1362)
157             LOG.debug("Transaction success for write of Flow {}", flowBuilder.getFlowName());
158         } catch (Exception e) {
159             LOG.error(e.getMessage(), e);
160             modification.cancel();
161         }
162     }
163
164     protected void removeFlow(FlowBuilder flowBuilder, NodeBuilder nodeBuilder) {
165         WriteTransaction modification = dataBroker.newWriteOnlyTransaction();
166         modification.delete(LogicalDatastoreType.CONFIGURATION, createFlowPath(flowBuilder, nodeBuilder));
167
168         CheckedFuture<Void, TransactionCommitFailedException> commitFuture = modification.submit();
169         try {
170             commitFuture.get();  // TODO: Make it async (See bug 1362)
171             LOG.debug("Transaction success for deletion of Flow {}", flowBuilder.getFlowName());
172         } catch (Exception e) {
173             LOG.error(e.getMessage(), e);
174             modification.cancel();
175         }
176     }
177
178     public Flow getFlow(FlowBuilder flowBuilder, NodeBuilder nodeBuilder) {
179         ReadOnlyTransaction readTx = dataBroker.newReadOnlyTransaction();
180         try {
181             Optional<Flow> data =
182                     readTx.read(LogicalDatastoreType.CONFIGURATION, createFlowPath(flowBuilder, nodeBuilder)).get();
183             if (data.isPresent()) {
184                 return data.get();
185             }
186         } catch (InterruptedException|ExecutionException e) {
187             LOG.error(e.getMessage(), e);
188         }
189
190         LOG.debug("Cannot find data for Flow {}", flowBuilder.getFlowName());
191         return null;
192     }
193
194     public org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node
195     getOpenFlowNode(String nodeId) {
196
197         ReadOnlyTransaction readTx = dataBroker.newReadOnlyTransaction();
198         try {
199             Optional<org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node> data =
200                     readTx.read(LogicalDatastoreType.OPERATIONAL, createNodePath(createNodeBuilder(nodeId))).get();
201             if (data.isPresent()) {
202                 return data.get();
203             }
204         } catch (InterruptedException|ExecutionException e) {
205             LOG.error(e.getMessage(), e);
206         }
207
208         LOG.debug("Cannot find data for Node {}", nodeId);
209         return null;
210     }
211
212     private long getDpid(Node node) {
213         long dpid = southbound.getDataPathId(node);
214         if (dpid == 0) {
215             LOG.warn("getDpid: dpid not found: {}", node);
216         }
217         return dpid;
218     }
219
220     /**
221      * Program Default Pipeline Flow.
222      *
223      * @param node on which the default pipeline flow is programmed.
224      */
225     protected void programDefaultPipelineRule(Node node) {
226         if (!isBridgeInPipeline(node)) {
227             //LOG.trace("Bridge is not in pipeline {} ", node);
228             return;
229         }
230         MatchBuilder matchBuilder = new MatchBuilder();
231         FlowBuilder flowBuilder = new FlowBuilder();
232         long dpid = getDpid(node);
233         if (dpid == 0L) {
234             LOG.info("could not find dpid: {}", node.getNodeId());
235             return;
236         }
237         String nodeName = OPENFLOW + getDpid(node);
238         NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
239
240         // Create the OF Actions and Instructions
241         InstructionsBuilder isb = new InstructionsBuilder();
242
243         // Instructions List Stores Individual Instructions
244         List<Instruction> instructions = Lists.newArrayList();
245
246         // Call the InstructionBuilder Methods Containing Actions
247         InstructionBuilder ib = this.getMutablePipelineInstructionBuilder();
248         ib.setOrder(0);
249         ib.setKey(new InstructionKey(0));
250         instructions.add(ib.build());
251
252         // Add InstructionBuilder to the Instruction(s)Builder List
253         isb.setInstruction(instructions);
254
255         // Add InstructionsBuilder to FlowBuilder
256         flowBuilder.setInstructions(isb.build());
257
258         String flowId = "DEFAULT_PIPELINE_FLOW_"+service.getTable();
259         flowBuilder.setId(new FlowId(flowId));
260         FlowKey key = new FlowKey(new FlowId(flowId));
261         flowBuilder.setMatch(matchBuilder.build());
262         flowBuilder.setPriority(0);
263         flowBuilder.setBarrier(false);
264         flowBuilder.setTableId(service.getTable());
265         flowBuilder.setKey(key);
266         flowBuilder.setFlowName(flowId);
267         flowBuilder.setHardTimeout(0);
268         flowBuilder.setIdleTimeout(0);
269         writeFlow(flowBuilder, nodeBuilder);
270     }
271 }