Merge "Bug-2226: RFC5886 - Messages parsers/serializers"
[bgpcep.git] / programming / impl / src / main / java / org / opendaylight / bgpcep / programming / impl / ProgrammingServiceImpl.java
1 /*
2  * Copyright (c) 2013 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.bgpcep.programming.impl;
9
10 import com.google.common.base.Preconditions;
11 import com.google.common.util.concurrent.FutureCallback;
12 import com.google.common.util.concurrent.Futures;
13 import com.google.common.util.concurrent.ListenableFuture;
14 import com.google.common.util.concurrent.ListeningExecutorService;
15 import com.google.common.util.concurrent.SettableFuture;
16 import io.netty.util.Timeout;
17 import io.netty.util.Timer;
18 import io.netty.util.TimerTask;
19 import java.math.BigInteger;
20 import java.util.ArrayList;
21 import java.util.Collections;
22 import java.util.HashMap;
23 import java.util.Iterator;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.concurrent.Callable;
27 import java.util.concurrent.ExecutionException;
28 import java.util.concurrent.TimeUnit;
29 import org.opendaylight.bgpcep.programming.NanotimeUtil;
30 import org.opendaylight.bgpcep.programming.spi.ExecutionResult;
31 import org.opendaylight.bgpcep.programming.spi.Instruction;
32 import org.opendaylight.bgpcep.programming.spi.InstructionScheduler;
33 import org.opendaylight.bgpcep.programming.spi.SchedulerException;
34 import org.opendaylight.bgpcep.programming.spi.SuccessfulRpcResult;
35 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
36 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
37 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
38 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
39 import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev130930.CancelInstructionInput;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev130930.CancelInstructionOutput;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev130930.CancelInstructionOutputBuilder;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev130930.CleanInstructionsInput;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev130930.CleanInstructionsOutput;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev130930.CleanInstructionsOutputBuilder;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev130930.DeadOnArrival;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev130930.DuplicateInstructionId;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev130930.InstructionId;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev130930.InstructionStatus;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev130930.InstructionStatusChangedBuilder;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev130930.InstructionsQueue;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev130930.InstructionsQueueBuilder;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev130930.Nanotime;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev130930.ProgrammingService;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev130930.SubmitInstructionInput;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev130930.UnknownInstruction;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev130930.UnknownPreconditionId;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev130930.instruction.queue.InstructionBuilder;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev130930.instruction.queue.InstructionKey;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev130930.instruction.status.changed.Details;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev130930.submit.instruction.output.result.failure._case.FailureBuilder;
62 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
63 import org.opendaylight.yangtools.yang.common.RpcResult;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
66
67 public final class ProgrammingServiceImpl implements AutoCloseable, InstructionScheduler, ProgrammingService {
68     private static final Logger LOG = LoggerFactory.getLogger(ProgrammingServiceImpl.class);
69
70     private final Map<InstructionId, InstructionImpl> insns = new HashMap<>();
71     private final InstanceIdentifier<InstructionsQueue> qid;
72     private final NotificationProviderService notifs;
73     private final ListeningExecutorService executor;
74     private final DataBroker dataProvider;
75     private final Timer timer;
76
77     private final class InstructionPusher implements QueueInstruction {
78         private final InstructionBuilder builder = new InstructionBuilder();
79
80         InstructionPusher(final InstructionId id, final Nanotime deadline) {
81             this.builder.setDeadline(deadline);
82             this.builder.setId(id);
83             this.builder.setKey(new InstructionKey(id));
84             this.builder.setStatus(InstructionStatus.Queued);
85         }
86
87         @Override
88         public void instructionUpdated(final InstructionStatus status, final Details details) {
89             if (!status.equals(this.builder.getStatus())) {
90                 this.builder.setStatus(status);
91
92                 final WriteTransaction t = ProgrammingServiceImpl.this.dataProvider.newWriteOnlyTransaction();
93                 t.put(LogicalDatastoreType.OPERATIONAL,
94                         ProgrammingServiceImpl.this.qid.child(
95                                 org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev130930.instruction.queue.Instruction.class,
96                                 new InstructionKey(this.builder.getId())), this.builder.build());
97                 t.submit();
98             }
99
100             ProgrammingServiceImpl.this.notifs.publish(new InstructionStatusChangedBuilder().setId(this.builder.getId()).setStatus(status).setDetails(details).build());
101         }
102
103         @Override
104         public void instructionRemoved() {
105             final WriteTransaction t = ProgrammingServiceImpl.this.dataProvider.newWriteOnlyTransaction();
106             t.delete(LogicalDatastoreType.OPERATIONAL, ProgrammingServiceImpl.this.qid.child(
107                     org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev130930.instruction.queue.Instruction.class,
108                     new InstructionKey(this.builder.getId())));
109             t.submit();
110         }
111     }
112
113     public ProgrammingServiceImpl(final DataBroker dataProvider, final NotificationProviderService notifs,
114             final ListeningExecutorService executor, final Timer timer) {
115         this.dataProvider = Preconditions.checkNotNull(dataProvider);
116         this.notifs = Preconditions.checkNotNull(notifs);
117         this.executor = Preconditions.checkNotNull(executor);
118         this.timer = Preconditions.checkNotNull(timer);
119         this.qid = InstanceIdentifier.builder(InstructionsQueue.class).build();
120
121         final ReadWriteTransaction t = dataProvider.newReadWriteTransaction();
122         try {
123             Preconditions.checkState(!t.read(LogicalDatastoreType.OPERATIONAL, this.qid).get().isPresent(), "Conflicting instruction queue found");
124         } catch (InterruptedException | ExecutionException e) {
125             throw new IllegalStateException("Failed to acquire instruction queue", e);
126         }
127
128         t.put(LogicalDatastoreType.OPERATIONAL, this.qid,
129                 new InstructionsQueueBuilder().setInstruction(
130                         Collections.<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev130930.instruction.queue.Instruction> emptyList()).build());
131         t.submit();
132     }
133
134     @Override
135     public ListenableFuture<RpcResult<CancelInstructionOutput>> cancelInstruction(final CancelInstructionInput input) {
136         return this.executor.submit(new Callable<RpcResult<CancelInstructionOutput>>() {
137             @Override
138             public RpcResult<CancelInstructionOutput> call() {
139                 return realCancelInstruction(input);
140             }
141         });
142     }
143
144     @Override
145     public ListenableFuture<RpcResult<CleanInstructionsOutput>> cleanInstructions(final CleanInstructionsInput input) {
146         return this.executor.submit(new Callable<RpcResult<CleanInstructionsOutput>>() {
147             @Override
148             public RpcResult<CleanInstructionsOutput> call() {
149                 return realCleanInstructions(input);
150             }
151         });
152     }
153
154     private synchronized RpcResult<CancelInstructionOutput> realCancelInstruction(final CancelInstructionInput input) {
155         final InstructionImpl i = this.insns.get(input.getId());
156         if (i == null) {
157             LOG.debug("Instruction {} not present in the graph", input.getId());
158
159             final CancelInstructionOutput out = new CancelInstructionOutputBuilder().setFailure(UnknownInstruction.class).build();
160             return SuccessfulRpcResult.create(out);
161         }
162
163         return SuccessfulRpcResult.create(new CancelInstructionOutputBuilder().setFailure(i.tryCancel(null)).build());
164     }
165
166     private synchronized RpcResult<CleanInstructionsOutput> realCleanInstructions(final CleanInstructionsInput input) {
167         final List<InstructionId> failed = new ArrayList<>();
168
169         for (final InstructionId id : input.getId()) {
170             // Find the instruction
171             final InstructionImpl i = this.insns.get(id);
172             if (i == null) {
173                 LOG.debug("Instruction {} not present in the graph", input.getId());
174                 failed.add(id);
175                 continue;
176             }
177
178             // Check its status
179             switch (i.getStatus()) {
180             case Cancelled:
181             case Failed:
182             case Successful:
183                 break;
184             case Executing:
185             case Queued:
186             case Scheduled:
187             case Unknown:
188                 LOG.debug("Instruction {} cannot be cleaned because of it's in state {}", id, i.getStatus());
189                 failed.add(id);
190                 continue;
191             default:
192                 break;
193             }
194
195             // The instruction is in a terminal state, we need to just unlink
196             // it from its dependencies and dependents
197             i.clean();
198
199             this.insns.remove(id);
200             LOG.debug("Instruction {} cleaned successfully", id);
201         }
202
203         final CleanInstructionsOutputBuilder ob = new CleanInstructionsOutputBuilder();
204         ob.setUnflushed(failed);
205
206         return SuccessfulRpcResult.create(ob.build());
207     }
208
209     private List<InstructionImpl> checkDependencies(final SubmitInstructionInput input) throws SchedulerException {
210         final List<InstructionImpl> dependencies = new ArrayList<>();
211         for (final InstructionId pid : input.getPreconditions()) {
212             final InstructionImpl i = this.insns.get(pid);
213             if (i == null) {
214                 LOG.info("Instruction {} depends on {}, which is not a known instruction", input.getId(), pid);
215                 throw new SchedulerException("Unknown dependency ID specified", new FailureBuilder().setType(UnknownPreconditionId.class).build());
216             }
217             dependencies.add(i);
218         }
219         // Check if all dependencies are non-failed
220         final List<InstructionId> unmet = new ArrayList<>();
221         for (final InstructionImpl d : dependencies) {
222             switch (d.getStatus()) {
223             case Cancelled:
224             case Failed:
225             case Unknown:
226                 unmet.add(d.getId());
227                 break;
228             case Executing:
229             case Queued:
230             case Scheduled:
231             case Successful:
232                 break;
233             default:
234                 break;
235             }
236         }
237         /*
238          *  Some dependencies have failed, declare the request dead-on-arrival
239          *  and fail the operation.
240          */
241         if (!unmet.isEmpty()) {
242             throw new SchedulerException("Instruction's dependencies are already unsuccessful", new FailureBuilder().setType(
243                     DeadOnArrival.class).setFailedPreconditions(unmet).build());
244         }
245         return dependencies;
246     }
247
248     @Override
249     public synchronized ListenableFuture<Instruction> scheduleInstruction(final SubmitInstructionInput input) throws SchedulerException {
250         final InstructionId id = input.getId();
251         if (this.insns.get(id) != null) {
252             LOG.info("Instruction ID {} already present", id);
253             throw new SchedulerException("Instruction ID currently in use", new FailureBuilder().setType(DuplicateInstructionId.class).build());
254         }
255
256         // First things first: check the deadline
257         final Nanotime now = NanotimeUtil.currentTime();
258         final BigInteger left = input.getDeadline().getValue().subtract(now.getValue());
259
260         if (left.compareTo(BigInteger.ZERO) <= 0) {
261             LOG.debug("Instruction {} deadline has already passed by {}ns", id, left);
262             throw new SchedulerException("Instruction arrived after specified deadline", new FailureBuilder().setType(DeadOnArrival.class).build());
263         }
264
265         // Resolve dependencies
266         final List<InstructionImpl> dependencies = checkDependencies(input);
267
268         /*
269          * All pre-flight checks done are at this point, the following
270          * steps can only fail in catastrophic scenarios (OOM and the
271          * like).
272          */
273
274         // Schedule a timeout for the instruction
275         final Timeout t = this.timer.newTimeout(new TimerTask() {
276             @Override
277             public void run(final Timeout timeout) {
278                 timeoutInstruction(input.getId());
279             }
280         }, left.longValue(), TimeUnit.NANOSECONDS);
281
282         // Put it into the instruction list
283         final SettableFuture<Instruction> ret = SettableFuture.create();
284         final InstructionImpl i = new InstructionImpl(new InstructionPusher(id, input.getDeadline()), ret, id, dependencies, t);
285         this.insns.put(id, i);
286
287         // Attach it into its dependencies
288         for (final InstructionImpl d : dependencies) {
289             d.addDependant(i);
290         }
291
292         /*
293          * All done. The next part is checking whether the instruction can
294          * run, which we can figure out after sending out the acknowledgement.
295          * This task should be ingress-weighed, so we reinsert it into the
296          * same execution service.
297          */
298         this.executor.submit(new Runnable() {
299             @Override
300             public void run() {
301                 tryScheduleInstruction(i);
302             }
303         });
304
305         return ret;
306     }
307
308     private synchronized void timeoutInstruction(final InstructionId id) {
309         final InstructionImpl i = this.insns.get(id);
310         if (i == null) {
311             LOG.warn("Instruction {} timed out, but not found in the queue", id);
312             return;
313         }
314
315         i.timeout();
316     }
317
318     private synchronized void tryScheduleDependants(final InstructionImpl i) {
319         // Walk all dependants and try to schedule them
320         final Iterator<InstructionImpl> it = i.getDependants();
321         while (it.hasNext()) {
322             tryScheduleInstruction(it.next());
323         }
324     }
325
326     private synchronized void tryScheduleInstruction(final InstructionImpl i) {
327         final ListenableFuture<ExecutionResult<Details>> f = i.ready();
328         if (f != null) {
329             Futures.addCallback(f, new FutureCallback<ExecutionResult<Details>>() {
330                 @Override
331                 public void onSuccess(final ExecutionResult<Details> result) {
332                     tryScheduleDependants(i);
333                 }
334
335                 @Override
336                 public void onFailure(final Throwable t) {
337                     LOG.error("Instruction {} failed to execute", i.getId(), t);
338                 }
339             });
340         }
341
342     }
343
344     @Override
345     public synchronized void close() {
346         try {
347             for (final InstructionImpl i : this.insns.values()) {
348                 i.tryCancel(null);
349             }
350             // Workaround for BUG-2283
351             final WriteTransaction t = this.dataProvider.newWriteOnlyTransaction();
352             t.delete(LogicalDatastoreType.OPERATIONAL, this.qid);
353             t.submit().checkedGet();
354         } catch (final Exception e) {
355             LOG.error("Failed to shutdown Instruction Queue", e);
356         }
357     }
358 }