Replace Preconditions.CheckNotNull per RequireNonNull
[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 static java.util.Objects.requireNonNull;
11
12 import com.google.common.util.concurrent.FutureCallback;
13 import com.google.common.util.concurrent.Futures;
14 import com.google.common.util.concurrent.ListenableFuture;
15 import com.google.common.util.concurrent.ListeningExecutorService;
16 import com.google.common.util.concurrent.MoreExecutors;
17 import com.google.common.util.concurrent.SettableFuture;
18 import io.netty.util.Timeout;
19 import io.netty.util.Timer;
20 import java.math.BigInteger;
21 import java.util.ArrayList;
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.Iterator;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.concurrent.TimeUnit;
28 import org.opendaylight.bgpcep.programming.NanotimeUtil;
29 import org.opendaylight.bgpcep.programming.impl.InstructionDeployerImpl.WriteConfiguration;
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.NotificationPublishService;
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.BindingAwareBroker.RpcRegistration;
40 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
41 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonService;
42 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
43 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration;
44 import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.CancelInstructionInput;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.CancelInstructionOutput;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.CancelInstructionOutputBuilder;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.CleanInstructionsInput;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.CleanInstructionsOutput;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.CleanInstructionsOutputBuilder;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.DeadOnArrival;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.DuplicateInstructionId;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.InstructionId;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.InstructionStatus;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.InstructionStatusChangedBuilder;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.InstructionsQueue;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.InstructionsQueueBuilder;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.InstructionsQueueKey;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.Nanotime;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.ProgrammingService;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.SubmitInstructionInput;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.UnknownInstruction;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.UnknownPreconditionId;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.instruction.queue.InstructionBuilder;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.instruction.queue.InstructionKey;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.instruction.status.changed.Details;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.submit.instruction.output.result.failure._case.FailureBuilder;
68 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
69 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
70 import org.opendaylight.yangtools.yang.common.RpcResult;
71 import org.osgi.framework.ServiceRegistration;
72 import org.slf4j.Logger;
73 import org.slf4j.LoggerFactory;
74
75 public final class ProgrammingServiceImpl implements AutoCloseable, ClusterSingletonService, InstructionScheduler,
76     ProgrammingService {
77     private static final Logger LOG = LoggerFactory.getLogger(ProgrammingServiceImpl.class);
78
79     private final Map<InstructionId, InstructionImpl> insns = new HashMap<>();
80     private final InstanceIdentifier<InstructionsQueue> qid;
81     private final NotificationPublishService notifs;
82     private final ListeningExecutorService executor;
83     private final DataBroker dataProvider;
84     private final Timer timer;
85     private final String instructionId;
86     private final ServiceGroupIdentifier sgi;
87     private final ClusterSingletonServiceRegistration csspReg;
88     private final RpcProviderRegistry rpcProviderRegistry;
89     private final WriteConfiguration writeConfiguration;
90     private RpcRegistration<ProgrammingService> reg;
91     private ServiceRegistration<?> serviceRegistration;
92
93     private final class InstructionPusher implements QueueInstruction {
94         private final InstructionBuilder builder = new InstructionBuilder();
95
96         InstructionPusher(final InstructionId id, final Nanotime deadline) {
97             this.builder.setDeadline(deadline);
98             this.builder.setId(id);
99             this.builder.setKey(new InstructionKey(id));
100             this.builder.setStatus(InstructionStatus.Queued);
101         }
102
103         @Override
104         public void instructionUpdated(final InstructionStatus status, final Details details) {
105             if (!status.equals(this.builder.getStatus())) {
106                 this.builder.setStatus(status);
107
108                 final WriteTransaction t = ProgrammingServiceImpl.this.dataProvider.newWriteOnlyTransaction();
109                 t.put(LogicalDatastoreType.OPERATIONAL,
110                     ProgrammingServiceImpl.this.qid.child(
111                         org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming
112                             .rev150720.instruction.queue.Instruction.class,
113                         new InstructionKey(this.builder.getId())), this.builder.build());
114                 Futures.addCallback(t.submit(), new FutureCallback<Void>() {
115                     @Override
116                     public void onSuccess(final Void result) {
117                         LOG.debug("Instruction Queue {} updated", ProgrammingServiceImpl.this.qid);
118                     }
119
120                     @Override
121                     public void onFailure(final Throwable t) {
122                         LOG.error("Failed to update Instruction Queue {}", ProgrammingServiceImpl.this.qid, t);
123                     }
124                 }, MoreExecutors.directExecutor());
125             }
126
127             try {
128                 ProgrammingServiceImpl.this.notifs.putNotification(new InstructionStatusChangedBuilder()
129                     .setId(this.builder.getId()).setStatus(status).setDetails(details).build());
130             } catch (final InterruptedException e) {
131                 LOG.debug("Failed to publish notification", e);
132             }
133         }
134
135         @Override
136         public void instructionRemoved() {
137             final WriteTransaction t = ProgrammingServiceImpl.this.dataProvider.newWriteOnlyTransaction();
138             t.delete(LogicalDatastoreType.OPERATIONAL, ProgrammingServiceImpl.this.qid.child(
139                 org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.instruction
140                     .queue.Instruction.class,
141                 new InstructionKey(this.builder.getId())));
142             Futures.addCallback(t.submit(), new FutureCallback<Void>() {
143                 @Override
144                 public void onSuccess(final Void result) {
145                     LOG.debug("Instruction Queue {} removed", ProgrammingServiceImpl.this.qid);
146                 }
147
148                 @Override
149                 public void onFailure(final Throwable t) {
150                     LOG.error("Failed to remove Instruction Queue {}", ProgrammingServiceImpl.this.qid, t);
151                 }
152             }, MoreExecutors.directExecutor());
153         }
154     }
155
156     ProgrammingServiceImpl(final DataBroker dataProvider, final NotificationPublishService notifs,
157         final ListeningExecutorService executor, final RpcProviderRegistry rpcProviderRegistry,
158         final ClusterSingletonServiceProvider cssp, final Timer timer, final String instructionId,
159         final WriteConfiguration writeConfiguration) {
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         this.qid = KeyedInstanceIdentifier.builder(InstructionsQueue.class,
167             new InstructionsQueueKey(this.instructionId)).build();
168         this.writeConfiguration = writeConfiguration;
169         this.sgi = ServiceGroupIdentifier.create("programming-" + this.instructionId + "-service-group");
170         this.csspReg = cssp.registerClusterSingletonService(this);
171     }
172
173     @Override
174     public void instantiateServiceInstance() {
175         LOG.info("Instruction Queue service {} instantiated", this.sgi.getValue());
176
177         if (this.writeConfiguration != null) {
178             this.writeConfiguration.create();
179         }
180         this.reg = this.rpcProviderRegistry.addRpcImplementation(ProgrammingService.class, this);
181
182         final WriteTransaction t = this.dataProvider.newWriteOnlyTransaction();
183         t.put(LogicalDatastoreType.OPERATIONAL, this.qid, new InstructionsQueueBuilder()
184             .setKey(new InstructionsQueueKey(this.instructionId)).setInstruction(Collections.emptyList()).build());
185         Futures.addCallback(t.submit(), new FutureCallback<Void>() {
186             @Override
187             public void onSuccess(final Void result) {
188                 LOG.debug("Instruction Queue {} added", ProgrammingServiceImpl.this.qid);
189             }
190
191             @Override
192             public void onFailure(final Throwable t) {
193                 LOG.error("Failed to add Instruction Queue {}", ProgrammingServiceImpl.this.qid, t);
194             }
195         }, MoreExecutors.directExecutor());
196     }
197
198     @Override
199     public ServiceGroupIdentifier getIdentifier() {
200         return this.sgi;
201     }
202
203     @Override
204     public ListenableFuture<RpcResult<CancelInstructionOutput>> cancelInstruction(final CancelInstructionInput input) {
205         return this.executor.submit(() -> realCancelInstruction(input));
206     }
207
208     @Override
209     public ListenableFuture<RpcResult<CleanInstructionsOutput>> cleanInstructions(final CleanInstructionsInput input) {
210         return this.executor.submit(() -> realCleanInstructions(input));
211     }
212
213     private synchronized RpcResult<CancelInstructionOutput> realCancelInstruction(final CancelInstructionInput input) {
214         final InstructionImpl i = this.insns.get(input.getId());
215         if (i == null) {
216             LOG.debug("Instruction {} not present in the graph", input.getId());
217
218             final CancelInstructionOutput out = new CancelInstructionOutputBuilder()
219                 .setFailure(UnknownInstruction.class).build();
220             return SuccessfulRpcResult.create(out);
221         }
222
223         return SuccessfulRpcResult.create(new CancelInstructionOutputBuilder().setFailure(i.tryCancel(null)).build());
224     }
225
226     private synchronized RpcResult<CleanInstructionsOutput> realCleanInstructions(final CleanInstructionsInput input) {
227         final List<InstructionId> failed = new ArrayList<>();
228
229         for (final InstructionId id : input.getId()) {
230             // Find the instruction
231             final InstructionImpl i = this.insns.get(id);
232             if (i == null) {
233                 LOG.debug("Instruction {} not present in the graph", input.getId());
234                 failed.add(id);
235                 continue;
236             }
237
238             // Check its status
239             switch (i.getStatus()) {
240                 case Cancelled:
241                 case Failed:
242                 case Successful:
243                     break;
244                 case Executing:
245                 case Queued:
246                 case Scheduled:
247                 case Unknown:
248                     LOG.debug("Instruction {} cannot be cleaned because of it's in state {}", id, i.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             i.clean();
258
259             this.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 List<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.class).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 i = this.insns.get(pid);
288             if (i == 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.class).build());
292             }
293             dependencies.add(i);
294         }
295         return dependencies;
296     }
297
298     private static List<InstructionId> checkIfUnfailed(final List<InstructionImpl> dependencies) {
299         final List<InstructionId> unmet = new ArrayList<>();
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 (this.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.class).build());
327         }
328
329         // First things first: check the deadline
330         final Nanotime now = NanotimeUtil.currentTime();
331         final BigInteger left = input.getDeadline().getValue().subtract(now.getValue());
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.class).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 = this.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 i = new InstructionImpl(new InstructionPusher(id, input.getDeadline()), ret, id,
355             dependencies, t);
356         this.insns.put(id, i);
357
358         // Attach it into its dependencies
359         for (final InstructionImpl d : dependencies) {
360             d.addDependant(i);
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         this.executor.submit(() -> tryScheduleInstruction(i));
370
371         return ret;
372     }
373
374     @Override
375     public String getInstructionID() {
376         return this.instructionId;
377     }
378
379     private synchronized void timeoutInstruction(final InstructionId id) {
380         final InstructionImpl i = this.insns.get(id);
381         if (i == null) {
382             LOG.warn("Instruction {} timed out, but not found in the queue", id);
383             return;
384         }
385
386         i.timeout();
387     }
388
389     private synchronized void tryScheduleDependants(final InstructionImpl i) {
390         // Walk all dependants and try to schedule them
391         final Iterator<InstructionImpl> it = i.getDependants();
392         while (it.hasNext()) {
393             tryScheduleInstruction(it.next());
394         }
395     }
396
397     private synchronized void tryScheduleInstruction(final InstructionImpl i) {
398         final ListenableFuture<ExecutionResult<Details>> f = i.ready();
399         if (f != null) {
400             Futures.addCallback(f, new FutureCallback<ExecutionResult<Details>>() {
401                 @Override
402                 public void onSuccess(final ExecutionResult<Details> result) {
403                     tryScheduleDependants(i);
404                 }
405
406                 @Override
407                 public void onFailure(final Throwable t) {
408                     LOG.error("Instruction {} failed to execute", i.getId(), t);
409                 }
410             }, MoreExecutors.directExecutor());
411         }
412
413     }
414
415     @Override
416     public synchronized ListenableFuture<Void> closeServiceInstance() {
417         LOG.info("Closing Instruction Queue service {}", this.sgi.getValue());
418
419         ListenableFuture<Void> writeConfigurationFuture = null;
420         if (this.writeConfiguration != null) {
421             writeConfigurationFuture = this.writeConfiguration.remove();
422         }
423         this.reg.close();
424         for (final InstructionImpl i : this.insns.values()) {
425             i.tryCancel(null);
426         }
427         // Workaround for BUG-2283
428         final WriteTransaction t = this.dataProvider.newWriteOnlyTransaction();
429         t.delete(LogicalDatastoreType.OPERATIONAL, this.qid);
430
431         final SettableFuture<Void> future = SettableFuture.create();
432
433         if (writeConfigurationFuture != null) {
434             writeConfigurationFuture.addListener(() -> submitRemoval(t, future), executor);
435         } else {
436             submitRemoval(t, future);
437         }
438
439         return future;
440     }
441
442     private void submitRemoval(WriteTransaction t, SettableFuture<Void> futureSetable) {
443         final ListenableFuture<Void> future = t.submit();
444         Futures.addCallback(future, new FutureCallback<Void>() {
445             @Override
446             public void onSuccess(final Void result) {
447                 LOG.debug("Instruction Queue {} removed", ProgrammingServiceImpl.this.qid);
448                 futureSetable.set(null);
449             }
450
451             @Override
452             public void onFailure(final Throwable t) {
453                 LOG.error("Failed to shutdown Instruction Queue {}", ProgrammingServiceImpl.this.qid, t);
454                 futureSetable.setException(t);
455             }
456         }, MoreExecutors.directExecutor());
457     }
458
459     @Override
460     public synchronized void close() {
461         if (this.csspReg != null) {
462             try {
463                 this.csspReg.close();
464             } catch (final Exception e) {
465                 LOG.debug("Failed to close Instruction Scheduler service", e);
466             }
467         }
468         if (this.serviceRegistration != null) {
469             this.serviceRegistration.unregister();
470             this.serviceRegistration = null;
471         }
472     }
473
474     void setServiceRegistration(final ServiceRegistration<?> serviceRegistration) {
475         this.serviceRegistration = serviceRegistration;
476     }
477 }