2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.bgpcep.programming.impl;
10 import static java.util.Objects.requireNonNull;
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;
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;
78 final class DefaultInstructionScheduler implements ClusterSingletonService, InstructionScheduler {
79 private static final Logger LOG = LoggerFactory.getLogger(DefaultInstructionScheduler.class);
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;
92 private Registration reg;
94 private final class InstructionPusher implements QueueInstruction {
95 private final InstructionBuilder builder = new InstructionBuilder();
97 InstructionPusher(final InstructionId id, final Nanotime deadline) {
98 builder.setDeadline(deadline);
100 builder.withKey(new InstructionKey(id));
101 builder.setStatus(InstructionStatus.Queued);
105 public void instructionUpdated(final InstructionStatus status, final Details details) {
106 if (!status.equals(builder.getStatus())) {
107 builder.setStatus(status);
109 final WriteTransaction wt = dataProvider.newWriteOnlyTransaction();
110 wt.put(LogicalDatastoreType.OPERATIONAL,
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>() {
117 public void onSuccess(final CommitInfo result) {
118 LOG.debug("Instruction Queue {} updated", qid);
122 public void onFailure(final Throwable trw) {
123 LOG.error("Failed to update Instruction Queue {}", qid, trw);
125 }, MoreExecutors.directExecutor());
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);
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>() {
145 public void onSuccess(final CommitInfo result) {
146 LOG.debug("Instruction Queue {} removed", qid);
150 public void onFailure(final Throwable trw) {
151 LOG.error("Failed to remove Instruction Queue {}", qid, trw);
153 }, MoreExecutors.directExecutor());
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);
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);
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>() {
185 public void onSuccess(final CommitInfo result) {
186 LOG.debug("Instruction Queue {} added", qid);
190 public void onFailure(final Throwable trw) {
191 LOG.error("Failed to add Instruction Queue {}", qid, trw);
193 }, MoreExecutors.directExecutor());
197 public ServiceGroupIdentifier getIdentifier() {
202 ListenableFuture<RpcResult<CancelInstructionOutput>> cancelInstruction(final CancelInstructionInput input) {
203 return Futures.submit(() -> realCancelInstruction(input), executor);
207 ListenableFuture<RpcResult<CleanInstructionsOutput>> cleanInstructions(final CleanInstructionsInput input) {
208 return Futures.submit(() -> realCleanInstructions(input), executor);
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());
216 final CancelInstructionOutput out = new CancelInstructionOutputBuilder()
217 .setFailure(UnknownInstruction.VALUE).build();
218 return SuccessfulRpcResult.create(out);
221 return SuccessfulRpcResult.create(new CancelInstructionOutputBuilder()
222 .setFailure(instruction.tryCancel(null)).build());
225 private synchronized RpcResult<CleanInstructionsOutput> realCleanInstructions(final CleanInstructionsInput input) {
226 final Set<InstructionId> failed = new HashSet<>();
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());
238 switch (instruction.getStatus()) {
247 LOG.debug("Instruction {} cannot be cleaned because of it's in state {}",
248 id, instruction.getStatus());
255 // The instruction is in a terminal state, we need to just unlink
256 // it from its dependencies and dependents
260 LOG.debug("Instruction {} cleaned successfully", id);
263 final CleanInstructionsOutputBuilder ob = new CleanInstructionsOutputBuilder();
264 ob.setUnflushed(failed);
266 return SuccessfulRpcResult.create(ob.build());
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);
274 * Some dependencies have failed, declare the request dead-on-arrival
275 * and fail the operation.
277 if (!unmet.isEmpty()) {
278 throw new SchedulerException("Instruction's dependencies are already unsuccessful", new FailureBuilder()
279 .setType(DeadOnArrival.VALUE).setFailedPreconditions(unmet).build());
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());
293 dependencies.add(instruction);
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()) {
305 unmet.add(d.getId());
320 public synchronized ListenableFuture<Instruction> scheduleInstruction(final SubmitInstructionInput input) throws
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());
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());
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());
339 // Resolve dependencies
340 final List<InstructionImpl> dependencies = checkDependencies(input);
343 * All pre-flight checks done are at this point, the following
344 * steps can only fail in catastrophic scenarios (OOM and the
348 // Schedule a timeout for the instruction
349 final Timeout t = timer.newTimeout(timeout -> timeoutInstruction(input.getId()), left.longValue(),
350 TimeUnit.NANOSECONDS);
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,
356 insns.put(id, instruction);
358 // Attach it into its dependencies
359 for (final InstructionImpl d : dependencies) {
360 d.addDependant(instruction);
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.
369 executor.execute(() -> tryScheduleInstruction(instruction));
375 public String getInstructionID() {
376 return instructionId;
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);
386 instruction.timeout();
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());
397 private synchronized void tryScheduleInstruction(final InstructionImpl instruction) {
398 final ListenableFuture<ExecutionResult<Details>> f = instruction.ready();
400 Futures.addCallback(f, new FutureCallback<>() {
402 public void onSuccess(final ExecutionResult<Details> result) {
403 tryScheduleDependants(instruction);
407 public void onFailure(final Throwable trw) {
408 LOG.error("Instruction {} failed to execute", instruction.getId(), trw);
410 }, MoreExecutors.directExecutor());
415 public synchronized FluentFuture<? extends CommitInfo> closeServiceInstance() {
416 LOG.info("Closing Instruction Queue service {}", sgi.value());
422 for (final InstructionImpl instruction : insns.values()) {
423 instruction.tryCancel(null);
425 // Workaround for BUG-2283
426 final WriteTransaction wt = dataProvider.newWriteOnlyTransaction();
427 wt.delete(LogicalDatastoreType.OPERATIONAL, qid);
429 final FluentFuture<? extends CommitInfo> future = wt.commit();
430 future.addCallback(new FutureCallback<CommitInfo>() {
432 public void onSuccess(final CommitInfo result) {
433 LOG.debug("Instruction Queue {} removed", qid);
437 public void onFailure(final Throwable trw) {
438 LOG.error("Failed to shutdown Instruction Queue {}", qid, trw);
440 }, MoreExecutors.directExecutor());
446 public synchronized void close() {