Modernize RPC registration
[bgpcep.git] / programming / impl / src / main / java / org / opendaylight / bgpcep / programming / impl / DefaultInstructionScheduler.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 static java.util.Objects.requireNonNull;
11
12 import com.google.common.annotations.VisibleForTesting;
13 import com.google.common.util.concurrent.FluentFuture;
14 import com.google.common.util.concurrent.FutureCallback;
15 import com.google.common.util.concurrent.Futures;
16 import com.google.common.util.concurrent.ListenableFuture;
17 import com.google.common.util.concurrent.MoreExecutors;
18 import com.google.common.util.concurrent.SettableFuture;
19 import io.netty.util.Timeout;
20 import io.netty.util.Timer;
21 import java.math.BigInteger;
22 import java.util.ArrayList;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.Iterator;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Set;
29 import java.util.concurrent.Executor;
30 import java.util.concurrent.TimeUnit;
31 import org.checkerframework.checker.lock.qual.GuardedBy;
32 import org.opendaylight.bgpcep.programming.NanotimeUtil;
33 import org.opendaylight.bgpcep.programming.spi.ExecutionResult;
34 import org.opendaylight.bgpcep.programming.spi.Instruction;
35 import org.opendaylight.bgpcep.programming.spi.InstructionScheduler;
36 import org.opendaylight.bgpcep.programming.spi.SchedulerException;
37 import org.opendaylight.bgpcep.programming.spi.SuccessfulRpcResult;
38 import org.opendaylight.mdsal.binding.api.DataBroker;
39 import org.opendaylight.mdsal.binding.api.NotificationPublishService;
40 import org.opendaylight.mdsal.binding.api.RpcProviderService;
41 import org.opendaylight.mdsal.binding.api.WriteTransaction;
42 import org.opendaylight.mdsal.common.api.CommitInfo;
43 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
44 import org.opendaylight.mdsal.singleton.api.ClusterSingletonService;
45 import org.opendaylight.mdsal.singleton.api.ClusterSingletonServiceProvider;
46 import org.opendaylight.mdsal.singleton.api.ServiceGroupIdentifier;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.CancelInstruction;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.CancelInstructionInput;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.CancelInstructionOutput;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.CancelInstructionOutputBuilder;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.CleanInstructions;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.CleanInstructionsInput;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.CleanInstructionsOutput;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.CleanInstructionsOutputBuilder;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.DeadOnArrival;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.DuplicateInstructionId;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.InstructionId;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.InstructionStatus;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.InstructionStatusChangedBuilder;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.InstructionsQueue;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.InstructionsQueueBuilder;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.InstructionsQueueKey;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.Nanotime;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.SubmitInstructionInput;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.UnknownInstruction;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.UnknownPreconditionId;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.instruction.queue.InstructionBuilder;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.instruction.queue.InstructionKey;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.instruction.status.changed.Details;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.submit.instruction.output.result.failure._case.FailureBuilder;
71 import org.opendaylight.yangtools.concepts.Registration;
72 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
73 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
74 import org.opendaylight.yangtools.yang.common.RpcResult;
75 import org.slf4j.Logger;
76 import org.slf4j.LoggerFactory;
77
78 final class DefaultInstructionScheduler implements ClusterSingletonService, InstructionScheduler {
79     private static final Logger LOG = LoggerFactory.getLogger(DefaultInstructionScheduler.class);
80
81     private final Map<InstructionId, InstructionImpl> insns = new HashMap<>();
82     private final InstanceIdentifier<InstructionsQueue> qid;
83     private final NotificationPublishService notifs;
84     private final Executor executor;
85     private final DataBroker dataProvider;
86     private final Timer timer;
87     private final String instructionId;
88     private final ServiceGroupIdentifier sgi;
89     private final Registration csspReg;
90     private final RpcProviderService rpcProviderRegistry;
91     @GuardedBy("this")
92     private Registration reg;
93
94     private final class InstructionPusher implements QueueInstruction {
95         private final InstructionBuilder builder = new InstructionBuilder();
96
97         InstructionPusher(final InstructionId id, final Nanotime deadline) {
98             builder.setDeadline(deadline);
99             builder.setId(id);
100             builder.withKey(new InstructionKey(id));
101             builder.setStatus(InstructionStatus.Queued);
102         }
103
104         @Override
105         public void instructionUpdated(final InstructionStatus status, final Details details) {
106             if (!status.equals(builder.getStatus())) {
107                 builder.setStatus(status);
108
109                 final WriteTransaction wt = dataProvider.newWriteOnlyTransaction();
110                 wt.put(LogicalDatastoreType.OPERATIONAL,
111                         qid.child(
112                                 org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming
113                                         .rev150720.instruction.queue.Instruction.class,
114                                 new InstructionKey(builder.getId())), builder.build());
115                 wt.commit().addCallback(new FutureCallback<CommitInfo>() {
116                     @Override
117                     public void onSuccess(final CommitInfo result) {
118                         LOG.debug("Instruction Queue {} updated", qid);
119                     }
120
121                     @Override
122                     public void onFailure(final Throwable trw) {
123                         LOG.error("Failed to update Instruction Queue {}", qid, trw);
124                     }
125                 }, MoreExecutors.directExecutor());
126             }
127
128             try {
129                 notifs.putNotification(new InstructionStatusChangedBuilder()
130                         .setId(builder.getId()).setStatus(status).setDetails(details).build());
131             } catch (final InterruptedException e) {
132                 LOG.debug("Failed to publish notification", e);
133             }
134         }
135
136         @Override
137         public void instructionRemoved() {
138             final WriteTransaction wt = dataProvider.newWriteOnlyTransaction();
139             wt.delete(LogicalDatastoreType.OPERATIONAL, qid.child(
140                     org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.instruction
141                             .queue.Instruction.class,
142                     new InstructionKey(builder.getId())));
143             wt.commit().addCallback(new FutureCallback<CommitInfo>() {
144                 @Override
145                 public void onSuccess(final CommitInfo result) {
146                     LOG.debug("Instruction Queue {} removed", qid);
147                 }
148
149                 @Override
150                 public void onFailure(final Throwable trw) {
151                     LOG.error("Failed to remove Instruction Queue {}", qid, trw);
152                 }
153             }, MoreExecutors.directExecutor());
154         }
155     }
156
157     DefaultInstructionScheduler(final DataBroker dataProvider, final NotificationPublishService notifs,
158             final Executor executor, final RpcProviderService rpcProviderRegistry,
159             final ClusterSingletonServiceProvider cssp, final Timer timer, final String instructionId) {
160         this.dataProvider = requireNonNull(dataProvider);
161         this.instructionId = requireNonNull(instructionId);
162         this.notifs = requireNonNull(notifs);
163         this.executor = requireNonNull(executor);
164         this.rpcProviderRegistry = requireNonNull(rpcProviderRegistry);
165         this.timer = requireNonNull(timer);
166         qid = KeyedInstanceIdentifier.builder(InstructionsQueue.class,
167                 new InstructionsQueueKey(this.instructionId)).build();
168         sgi = new ServiceGroupIdentifier(this.instructionId + "-service-group");
169         LOG.info("Creating Programming Service {}.", sgi.value());
170         csspReg = cssp.registerClusterSingletonService(this);
171     }
172
173     @Override
174     public synchronized void instantiateServiceInstance() {
175         LOG.info("Instruction Queue service {} instantiated", sgi.value());
176         reg = rpcProviderRegistry.registerRpcImplementations(
177             (CancelInstruction) this::cancelInstruction,
178             (CleanInstructions) this::cleanInstructions);
179
180         final WriteTransaction wt = dataProvider.newWriteOnlyTransaction();
181         wt.put(LogicalDatastoreType.OPERATIONAL, qid, new InstructionsQueueBuilder()
182                 .withKey(new InstructionsQueueKey(instructionId)).setInstruction(Map.of()).build());
183         wt.commit().addCallback(new FutureCallback<CommitInfo>() {
184             @Override
185             public void onSuccess(final CommitInfo result) {
186                 LOG.debug("Instruction Queue {} added", qid);
187             }
188
189             @Override
190             public void onFailure(final Throwable trw) {
191                 LOG.error("Failed to add Instruction Queue {}", qid, trw);
192             }
193         }, MoreExecutors.directExecutor());
194     }
195
196     @Override
197     public ServiceGroupIdentifier getIdentifier() {
198         return sgi;
199     }
200
201     @VisibleForTesting
202     ListenableFuture<RpcResult<CancelInstructionOutput>> cancelInstruction(final CancelInstructionInput input) {
203         return Futures.submit(() -> realCancelInstruction(input), executor);
204     }
205
206     @VisibleForTesting
207     ListenableFuture<RpcResult<CleanInstructionsOutput>> cleanInstructions(final CleanInstructionsInput input) {
208         return Futures.submit(() -> realCleanInstructions(input), executor);
209     }
210
211     private synchronized RpcResult<CancelInstructionOutput> realCancelInstruction(final CancelInstructionInput input) {
212         final InstructionImpl instruction = insns.get(input.getId());
213         if (instruction == null) {
214             LOG.debug("Instruction {} not present in the graph", input.getId());
215
216             final CancelInstructionOutput out = new CancelInstructionOutputBuilder()
217                     .setFailure(UnknownInstruction.VALUE).build();
218             return SuccessfulRpcResult.create(out);
219         }
220
221         return SuccessfulRpcResult.create(new CancelInstructionOutputBuilder()
222                 .setFailure(instruction.tryCancel(null)).build());
223     }
224
225     private synchronized RpcResult<CleanInstructionsOutput> realCleanInstructions(final CleanInstructionsInput input) {
226         final Set<InstructionId> failed = new HashSet<>();
227
228         for (final InstructionId id : input.getId()) {
229             // Find the instruction
230             final InstructionImpl instruction = insns.get(id);
231             if (instruction == null) {
232                 LOG.debug("Instruction {} not present in the graph", input.getId());
233                 failed.add(id);
234                 continue;
235             }
236
237             // Check its status
238             switch (instruction.getStatus()) {
239                 case Cancelled:
240                 case Failed:
241                 case Successful:
242                     break;
243                 case Executing:
244                 case Queued:
245                 case Scheduled:
246                 case Unknown:
247                     LOG.debug("Instruction {} cannot be cleaned because of it's in state {}",
248                             id, instruction.getStatus());
249                     failed.add(id);
250                     continue;
251                 default:
252                     break;
253             }
254
255             // The instruction is in a terminal state, we need to just unlink
256             // it from its dependencies and dependents
257             instruction.clean();
258
259             insns.remove(id);
260             LOG.debug("Instruction {} cleaned successfully", id);
261         }
262
263         final CleanInstructionsOutputBuilder ob = new CleanInstructionsOutputBuilder();
264         ob.setUnflushed(failed);
265
266         return SuccessfulRpcResult.create(ob.build());
267     }
268
269     private List<InstructionImpl> checkDependencies(final SubmitInstructionInput input) throws SchedulerException {
270         final List<InstructionImpl> dependencies = collectDependencies(input);
271         // Check if all dependencies are non-failed
272         final Set<InstructionId> unmet = checkIfUnfailed(dependencies);
273         /*
274          *  Some dependencies have failed, declare the request dead-on-arrival
275          *  and fail the operation.
276          */
277         if (!unmet.isEmpty()) {
278             throw new SchedulerException("Instruction's dependencies are already unsuccessful", new FailureBuilder()
279                     .setType(DeadOnArrival.VALUE).setFailedPreconditions(unmet).build());
280         }
281         return dependencies;
282     }
283
284     private List<InstructionImpl> collectDependencies(final SubmitInstructionInput input) throws SchedulerException {
285         final List<InstructionImpl> dependencies = new ArrayList<>();
286         for (final InstructionId pid : input.getPreconditions()) {
287             final InstructionImpl instruction = insns.get(pid);
288             if (instruction == null) {
289                 LOG.info("Instruction {} depends on {}, which is not a known instruction", input.getId(), pid);
290                 throw new SchedulerException("Unknown dependency ID specified",
291                         new FailureBuilder().setType(UnknownPreconditionId.VALUE).build());
292             }
293             dependencies.add(instruction);
294         }
295         return dependencies;
296     }
297
298     private static Set<InstructionId> checkIfUnfailed(final List<InstructionImpl> dependencies) {
299         final Set<InstructionId> unmet = new HashSet<>();
300         for (final InstructionImpl d : dependencies) {
301             switch (d.getStatus()) {
302                 case Cancelled:
303                 case Failed:
304                 case Unknown:
305                     unmet.add(d.getId());
306                     break;
307                 case Executing:
308                 case Queued:
309                 case Scheduled:
310                 case Successful:
311                     break;
312                 default:
313                     break;
314             }
315         }
316         return unmet;
317     }
318
319     @Override
320     public synchronized ListenableFuture<Instruction> scheduleInstruction(final SubmitInstructionInput input) throws
321             SchedulerException {
322         final InstructionId id = input.getId();
323         if (insns.get(id) != null) {
324             LOG.info("Instruction ID {} already present", id);
325             throw new SchedulerException("Instruction ID currently in use",
326                     new FailureBuilder().setType(DuplicateInstructionId.VALUE).build());
327         }
328
329         // First things first: check the deadline
330         final Nanotime now = NanotimeUtil.currentTime();
331         final BigInteger left = input.getDeadline().getValue().toJava().subtract(now.getValue().toJava());
332
333         if (left.compareTo(BigInteger.ZERO) <= 0) {
334             LOG.debug("Instruction {} deadline has already passed by {}ns", id, left);
335             throw new SchedulerException("Instruction arrived after specified deadline",
336                     new FailureBuilder().setType(DeadOnArrival.VALUE).build());
337         }
338
339         // Resolve dependencies
340         final List<InstructionImpl> dependencies = checkDependencies(input);
341
342         /*
343          * All pre-flight checks done are at this point, the following
344          * steps can only fail in catastrophic scenarios (OOM and the
345          * like).
346          */
347
348         // Schedule a timeout for the instruction
349         final Timeout t = timer.newTimeout(timeout -> timeoutInstruction(input.getId()), left.longValue(),
350                 TimeUnit.NANOSECONDS);
351
352         // Put it into the instruction list
353         final SettableFuture<Instruction> ret = SettableFuture.create();
354         final InstructionImpl instruction = new InstructionImpl(new InstructionPusher(id, input.getDeadline()), ret, id,
355                 dependencies, t);
356         insns.put(id, instruction);
357
358         // Attach it into its dependencies
359         for (final InstructionImpl d : dependencies) {
360             d.addDependant(instruction);
361         }
362
363         /*
364          * All done. The next part is checking whether the instruction can
365          * run, which we can figure out after sending out the acknowledgement.
366          * This task should be ingress-weighed, so we reinsert it into the
367          * same execution service.
368          */
369         executor.execute(() -> tryScheduleInstruction(instruction));
370
371         return ret;
372     }
373
374     @Override
375     public String getInstructionID() {
376         return instructionId;
377     }
378
379     private synchronized void timeoutInstruction(final InstructionId id) {
380         final InstructionImpl instruction = insns.get(id);
381         if (instruction == null) {
382             LOG.warn("Instruction {} timed out, but not found in the queue", id);
383             return;
384         }
385
386         instruction.timeout();
387     }
388
389     private synchronized void tryScheduleDependants(final InstructionImpl instruction) {
390         // Walk all dependants and try to schedule them
391         final Iterator<InstructionImpl> it = instruction.getDependants();
392         while (it.hasNext()) {
393             tryScheduleInstruction(it.next());
394         }
395     }
396
397     private synchronized void tryScheduleInstruction(final InstructionImpl instruction) {
398         final ListenableFuture<ExecutionResult<Details>> f = instruction.ready();
399         if (f != null) {
400             Futures.addCallback(f, new FutureCallback<>() {
401                 @Override
402                 public void onSuccess(final ExecutionResult<Details> result) {
403                     tryScheduleDependants(instruction);
404                 }
405
406                 @Override
407                 public void onFailure(final Throwable trw) {
408                     LOG.error("Instruction {} failed to execute", instruction.getId(), trw);
409                 }
410             }, MoreExecutors.directExecutor());
411         }
412     }
413
414     @Override
415     public synchronized FluentFuture<? extends CommitInfo> closeServiceInstance() {
416         LOG.info("Closing Instruction Queue service {}", sgi.value());
417
418         if (reg != null) {
419             reg.close();
420             reg = null;
421         }
422         for (final InstructionImpl instruction : insns.values()) {
423             instruction.tryCancel(null);
424         }
425         // Workaround for BUG-2283
426         final WriteTransaction wt = dataProvider.newWriteOnlyTransaction();
427         wt.delete(LogicalDatastoreType.OPERATIONAL, qid);
428
429         final FluentFuture<? extends CommitInfo> future = wt.commit();
430         future.addCallback(new FutureCallback<CommitInfo>() {
431             @Override
432             public void onSuccess(final CommitInfo result) {
433                 LOG.debug("Instruction Queue {} removed", qid);
434             }
435
436             @Override
437             public void onFailure(final Throwable trw) {
438                 LOG.error("Failed to shutdown Instruction Queue {}", qid, trw);
439             }
440         }, MoreExecutors.directExecutor());
441
442         return future;
443     }
444
445     @Override
446     public synchronized void close() {
447         csspReg.close();
448     }
449 }