InMemoryDOMDataStore$DOMStoreTransactionChainImpl isnt happy if there are mulitple...
[ovsdb.git] / openstack / net-virt-providers / src / main / java / org / opendaylight / ovsdb / openstack / netvirt / providers / openflow13 / AbstractServiceInstance.java
1 /*
2  * Copyright (C) 2014 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
9  */
10 package org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13;
11
12 import java.util.List;
13 import java.util.concurrent.BlockingQueue;
14 import java.util.concurrent.ExecutionException;
15 import java.util.concurrent.LinkedBlockingDeque;
16
17 import org.opendaylight.controller.md.sal.binding.api.BindingTransactionChain;
18 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
19 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
20 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
21 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
22 import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
23 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
24 import org.opendaylight.controller.md.sal.common.api.data.TransactionChain;
25 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
26 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
27 import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
28 import org.opendaylight.ovsdb.utils.mdsal.openflow.InstructionUtils;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
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.MatchBuilder;
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.flow.types.rev131026.instruction.list.InstructionKey;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRemoved;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorUpdated;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRemoved;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeUpdated;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.OpendaylightInventoryListener;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
52 import org.opendaylight.yangtools.yang.binding.DataObject;
53 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
54 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57
58 import com.google.common.base.Optional;
59 import com.google.common.base.Preconditions;
60 import com.google.common.collect.Lists;
61 import com.google.common.util.concurrent.CheckedFuture;
62 import com.google.common.util.concurrent.FutureCallback;
63 import com.google.common.util.concurrent.Futures;
64
65 /**
66  * Any ServiceInstance class that extends AbstractServiceInstance to be a part of the pipeline
67  * have 2 basic requirements : <br>
68  * 1. Program a default pipeline flow to take any unmatched traffic to the next table in the pipeline. <br>
69  * 2. Get Pipeline Instructions from AbstractServiceInstance (using getMutablePipelineInstructionBuilder) and
70  *    use it in any matching flows that needs to be further processed by next service in the pipeline.
71  *
72  */
73 public abstract class AbstractServiceInstance implements OpendaylightInventoryListener, Runnable, TransactionChainListener {
74     public static final String SERVICE_PROPERTY ="serviceProperty";
75     private static final Logger logger = LoggerFactory.getLogger(AbstractServiceInstance.class);
76     public static final String OPENFLOW = "openflow:";
77     // OSGi Services that we are dependent on.
78     private volatile MdsalConsumer mdsalConsumer;
79     private volatile PipelineOrchestrator orchestrator;
80
81     // Concrete Service that this AbstractServiceInstance represent
82     private Service service;
83
84     // Process Notification in its own thread
85     Thread thread = null;
86     private final BlockingQueue<String> queue = new LinkedBlockingDeque<>();
87
88     public AbstractServiceInstance (Service service) {
89         this.service = service;
90     }
91
92     // Let the Concrete service instance class decide if a Bride is part of the pipeline or not.
93     public abstract boolean isBridgeInPipeline (String nodeId);
94
95     public short getTable() {
96         return service.getTable();
97     }
98
99     public Service getService() {
100         return service;
101     }
102
103     public void setService(Service service) {
104         this.service = service;
105     }
106
107     public void start() {
108         // Register for OpenFlow bridge/node Creation notification.
109         NotificationProviderService notificationService = mdsalConsumer.getNotificationService();
110         if (notificationService != null) {
111             notificationService.registerNotificationListener(this);
112         }
113
114         // Never block a Notification thread. Process the notification in its own Thread.
115         thread = new Thread(this);
116         thread.setDaemon(true);
117         thread.setName("AbstractServiceInstance-"+service.toString());
118         thread.start();
119     }
120
121     public NodeBuilder createNodeBuilder(String nodeId) {
122         NodeBuilder builder = new NodeBuilder();
123         builder.setId(new NodeId(nodeId));
124         builder.setKey(new NodeKey(builder.getId()));
125         return builder;
126     }
127
128     /**
129      * This method returns the required Pipeline Instructions to by used by any matching flows that needs
130      * to be further processed by next service in the pipeline.
131      *
132      * Important to note that this is a convenience method which returns a mutable instructionBuilder which
133      * needs to be further adjusted by the concrete ServiceInstance class such as setting the Instruction Order, etc.
134      * @return Newly created InstructionBuilder to be used along with other instructions on the main flow
135      */
136     protected final InstructionBuilder getMutablePipelineInstructionBuilder() {
137         Service nextService = orchestrator.getNextServiceInPipeline(service);
138         if (nextService != null) {
139             return InstructionUtils.createGotoTableInstructions(new InstructionBuilder(), nextService.getTable());
140         } else {
141             return InstructionUtils.createDropInstructions(new InstructionBuilder());
142         }
143     }
144
145     protected void writeFlow(FlowBuilder flowBuilder, NodeBuilder nodeBuilder) {
146         Preconditions.checkNotNull(mdsalConsumer);
147         if (mdsalConsumer == null) {
148             logger.error("ERROR finding MDSAL Service. Its possible that writeFlow is called too soon ?");
149             return;
150         }
151
152         DataBroker dataBroker = mdsalConsumer.getDataBroker();
153         if (dataBroker == null) {
154             logger.error("ERROR finding reference for DataBroker. Please check MD-SAL support on the Controller.");
155             return;
156         }
157
158         ReadWriteTransaction modification = dataBroker.newReadWriteTransaction();
159         InstanceIdentifier<Flow> path1 = InstanceIdentifier.builder(Nodes.class).child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory
160                 .rev130819.nodes.Node.class, nodeBuilder.getKey()).augmentation(FlowCapableNode.class).child(Table.class,
161                 new TableKey(flowBuilder.getTableId())).child(Flow.class, flowBuilder.getKey()).build();
162
163         //modification.put(LogicalDatastoreType.OPERATIONAL, path1, flowBuilder.build());
164         modification.put(LogicalDatastoreType.CONFIGURATION, path1, flowBuilder.build(), true /*createMissingParents*/);
165
166
167         CheckedFuture<Void, TransactionCommitFailedException> commitFuture = modification.submit();
168         try {
169             commitFuture.get();  // TODO: Make it async (See bug 1362)
170             logger.debug("Transaction success for write of Flow "+flowBuilder.getFlowName());
171         } catch (InterruptedException|ExecutionException e) {
172             logger.error(e.getMessage(), e);
173
174         }
175     }
176
177     protected void removeFlow(FlowBuilder flowBuilder, NodeBuilder nodeBuilder) {
178         Preconditions.checkNotNull(mdsalConsumer);
179         if (mdsalConsumer == null) {
180             logger.error("ERROR finding MDSAL Service.");
181             return;
182         }
183
184         DataBroker dataBroker = mdsalConsumer.getDataBroker();
185         if (dataBroker == null) {
186             logger.error("ERROR finding reference for DataBroker. Please check MD-SAL support on the Controller.");
187             return;
188         }
189
190         WriteTransaction modification = dataBroker.newWriteOnlyTransaction();
191         InstanceIdentifier<Flow> path1 = InstanceIdentifier.builder(Nodes.class)
192                 .child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory
193                                .rev130819.nodes.Node.class, nodeBuilder.getKey())
194                 .augmentation(FlowCapableNode.class).child(Table.class,
195                                                            new TableKey(flowBuilder.getTableId())).child(Flow.class, flowBuilder.getKey()).build();
196         //modification.delete(LogicalDatastoreType.OPERATIONAL, nodeBuilderToInstanceId(nodeBuilder));
197         //modification.delete(LogicalDatastoreType.OPERATIONAL, path1);
198         //modification.delete(LogicalDatastoreType.CONFIGURATION, nodeBuilderToInstanceId(nodeBuilder));
199         modification.delete(LogicalDatastoreType.CONFIGURATION, path1);
200
201         CheckedFuture<Void, TransactionCommitFailedException> commitFuture = modification.submit();
202         try {
203             commitFuture.get();  // TODO: Make it async (See bug 1362)
204             logger.debug("Transaction success for deletion of Flow "+flowBuilder.getFlowName());
205         } catch (InterruptedException|ExecutionException e) {
206             logger.error(e.getMessage(), e);
207         }
208     }
209
210     public Flow getFlow(FlowBuilder flowBuilder, NodeBuilder nodeBuilder) {
211         Preconditions.checkNotNull(mdsalConsumer);
212         if (mdsalConsumer == null) {
213             logger.error("ERROR finding MDSAL Service. Its possible that writeFlow is called too soon ?");
214             return null;
215         }
216
217         DataBroker dataBroker = mdsalConsumer.getDataBroker();
218         if (dataBroker == null) {
219             logger.error("ERROR finding reference for DataBroker. Please check MD-SAL support on the Controller.");
220             return null;
221         }
222
223         InstanceIdentifier<Flow> path1 = InstanceIdentifier.builder(Nodes.class).child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory
224                 .rev130819.nodes.Node.class, nodeBuilder.getKey()).augmentation(FlowCapableNode.class).child(Table.class,
225                 new TableKey(flowBuilder.getTableId())).child(Flow.class, flowBuilder.getKey()).build();
226
227         ReadOnlyTransaction readTx = dataBroker.newReadOnlyTransaction();
228         try {
229             Optional<Flow> data = readTx.read(LogicalDatastoreType.CONFIGURATION, path1).get();
230             if (data.isPresent()) {
231                 return data.get();
232             }
233         } catch (InterruptedException|ExecutionException e) {
234             logger.error(e.getMessage(), e);
235         }
236
237         logger.debug("Cannot find data for Flow " + flowBuilder.getFlowName());
238         return null;
239     }
240
241     /**
242      * Program Default Pipeline Flow.
243      *
244      * @param nodeId Node on which the default pipeline flow is programmed.
245      */
246     protected void programDefaultPipelineRule(String nodeId) {
247         MatchBuilder matchBuilder = new MatchBuilder();
248         FlowBuilder flowBuilder = new FlowBuilder();
249         NodeBuilder nodeBuilder = createNodeBuilder(nodeId);
250
251         // Create the OF Actions and Instructions
252         InstructionsBuilder isb = new InstructionsBuilder();
253
254         // Instructions List Stores Individual Instructions
255         List<Instruction> instructions = Lists.newArrayList();
256
257         // Call the InstructionBuilder Methods Containing Actions
258         InstructionBuilder ib = this.getMutablePipelineInstructionBuilder();
259         ib.setOrder(0);
260         ib.setKey(new InstructionKey(0));
261         instructions.add(ib.build());
262
263         // Add InstructionBuilder to the Instruction(s)Builder List
264         isb.setInstruction(instructions);
265
266         // Add InstructionsBuilder to FlowBuilder
267         flowBuilder.setInstructions(isb.build());
268
269         String flowId = "DEFAULT_PIPELINE_FLOW";
270         flowBuilder.setId(new FlowId(flowId));
271         FlowKey key = new FlowKey(new FlowId(flowId));
272         flowBuilder.setMatch(matchBuilder.build());
273         flowBuilder.setPriority(0);
274         flowBuilder.setBarrier(true);
275         flowBuilder.setTableId(service.getTable());
276         flowBuilder.setKey(key);
277         flowBuilder.setFlowName(flowId);
278         flowBuilder.setHardTimeout(0);
279         flowBuilder.setIdleTimeout(0);
280         writeFlow(flowBuilder, nodeBuilder);
281     }
282
283     @Override
284     public void onNodeConnectorRemoved(NodeConnectorRemoved nodeConector) {
285     }
286
287     @Override
288     public void onNodeConnectorUpdated(NodeConnectorUpdated nodeConnector) {
289     }
290
291     @Override
292     public void onNodeRemoved(NodeRemoved node) {
293     }
294
295
296     @Override
297     public void run() {
298         try {
299             for (; ; ) {
300                 String nodeId = queue.take();
301                 this.programDefaultPipelineRule(nodeId);
302             }
303         } catch (InterruptedException e) {
304             logger.warn("Processing interrupted, terminating", e);
305         }
306
307         while (!queue.isEmpty()) {
308             queue.poll();
309         }
310
311     }
312
313     void enqueue(final String nodeId) {
314         try {
315             queue.put(nodeId);
316         } catch (InterruptedException e) {
317             logger.warn("Failed to enqueue operation {}", nodeId, e);
318         }
319     }
320
321     /**
322      * Process the Node update notification. Check for Openflow node and make sure if the bridge is part of the Pipeline before
323      * programming the Pipeline specific flows.
324      */
325     @Override
326     public void onNodeUpdated(NodeUpdated nodeUpdated) {
327         NodeRef ref = nodeUpdated.getNodeRef();
328         InstanceIdentifier<Node> identifier = (InstanceIdentifier<Node>) ref.getValue();
329         logger.info("GOT NOTIFICATION FOR "+identifier.toString());
330         final NodeKey key = identifier.firstKeyOf(Node.class, NodeKey.class);
331         final String nodeId = key.getId().getValue();
332         if (!this.isBridgeInPipeline(nodeId)) {
333             logger.debug("Bridge {} is not in pipeline", nodeId);
334             return;
335         }
336         if (key != null && key.getId().getValue().contains("openflow")) {
337             InstanceIdentifierBuilder<Node> builder = ((InstanceIdentifier<Node>) ref.getValue()).builder();
338             InstanceIdentifierBuilder<FlowCapableNode> augmentation = builder.augmentation(FlowCapableNode.class);
339             final InstanceIdentifier<FlowCapableNode> path = augmentation.build();
340             BindingTransactionChain txChain = mdsalConsumer.getDataBroker().createTransactionChain(this);
341             CheckedFuture readFuture = txChain.newReadWriteTransaction().read(LogicalDatastoreType.OPERATIONAL, path);
342             Futures.addCallback(readFuture, new FutureCallback<Optional<? extends DataObject>>() {
343                 @Override
344                 public void onSuccess(Optional<? extends DataObject> optional) {
345                     if (!optional.isPresent()) {
346                         enqueue(nodeId);
347                     }
348                 }
349
350                 @Override
351                 public void onFailure(Throwable throwable) {
352                     logger.debug(String.format("Can't retrieve node data for node %s. Writing node data with table0.", nodeId));
353                     enqueue(nodeId);
354                 }
355             });
356         }
357     }
358
359     @Override
360     public void onTransactionChainFailed(final TransactionChain<?, ?> chain, final AsyncTransaction<?, ?> transaction,
361             final Throwable cause) {
362         logger.error("Failed to export Flow Capable Inventory, Transaction {} failed.",transaction.getIdentifier(),cause);
363     }
364
365     @Override
366     public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
367     }
368 }