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.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;
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;
75 public final class ProgrammingServiceImpl implements AutoCloseable, ClusterSingletonService, InstructionScheduler,
77 private static final Logger LOG = LoggerFactory.getLogger(ProgrammingServiceImpl.class);
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;
93 private final class InstructionPusher implements QueueInstruction {
94 private final InstructionBuilder builder = new InstructionBuilder();
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);
104 public void instructionUpdated(final InstructionStatus status, final Details details) {
105 if (!status.equals(this.builder.getStatus())) {
106 this.builder.setStatus(status);
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>() {
116 public void onSuccess(final Void result) {
117 LOG.debug("Instruction Queue {} updated", ProgrammingServiceImpl.this.qid);
121 public void onFailure(final Throwable t) {
122 LOG.error("Failed to update Instruction Queue {}", ProgrammingServiceImpl.this.qid, t);
124 }, MoreExecutors.directExecutor());
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);
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>() {
144 public void onSuccess(final Void result) {
145 LOG.debug("Instruction Queue {} removed", ProgrammingServiceImpl.this.qid);
149 public void onFailure(final Throwable t) {
150 LOG.error("Failed to remove Instruction Queue {}", ProgrammingServiceImpl.this.qid, t);
152 }, MoreExecutors.directExecutor());
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);
174 public void instantiateServiceInstance() {
175 LOG.info("Instruction Queue service {} instantiated", this.sgi.getValue());
177 if (this.writeConfiguration != null) {
178 this.writeConfiguration.create();
180 this.reg = this.rpcProviderRegistry.addRpcImplementation(ProgrammingService.class, this);
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>() {
187 public void onSuccess(final Void result) {
188 LOG.debug("Instruction Queue {} added", ProgrammingServiceImpl.this.qid);
192 public void onFailure(final Throwable t) {
193 LOG.error("Failed to add Instruction Queue {}", ProgrammingServiceImpl.this.qid, t);
195 }, MoreExecutors.directExecutor());
199 public ServiceGroupIdentifier getIdentifier() {
204 public ListenableFuture<RpcResult<CancelInstructionOutput>> cancelInstruction(final CancelInstructionInput input) {
205 return this.executor.submit(() -> realCancelInstruction(input));
209 public ListenableFuture<RpcResult<CleanInstructionsOutput>> cleanInstructions(final CleanInstructionsInput input) {
210 return this.executor.submit(() -> realCleanInstructions(input));
213 private synchronized RpcResult<CancelInstructionOutput> realCancelInstruction(final CancelInstructionInput input) {
214 final InstructionImpl i = this.insns.get(input.getId());
216 LOG.debug("Instruction {} not present in the graph", input.getId());
218 final CancelInstructionOutput out = new CancelInstructionOutputBuilder()
219 .setFailure(UnknownInstruction.class).build();
220 return SuccessfulRpcResult.create(out);
223 return SuccessfulRpcResult.create(new CancelInstructionOutputBuilder().setFailure(i.tryCancel(null)).build());
226 private synchronized RpcResult<CleanInstructionsOutput> realCleanInstructions(final CleanInstructionsInput input) {
227 final List<InstructionId> failed = new ArrayList<>();
229 for (final InstructionId id : input.getId()) {
230 // Find the instruction
231 final InstructionImpl i = this.insns.get(id);
233 LOG.debug("Instruction {} not present in the graph", input.getId());
239 switch (i.getStatus()) {
248 LOG.debug("Instruction {} cannot be cleaned because of it's in state {}", id, i.getStatus());
255 // The instruction is in a terminal state, we need to just unlink
256 // it from its dependencies and dependents
259 this.insns.remove(id);
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 List<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.class).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 i = this.insns.get(pid);
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());
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()) {
305 unmet.add(d.getId());
320 public synchronized ListenableFuture<Instruction> scheduleInstruction(final SubmitInstructionInput input) throws
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());
329 // First things first: check the deadline
330 final Nanotime now = NanotimeUtil.currentTime();
331 final BigInteger left = input.getDeadline().getValue().subtract(now.getValue());
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());
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 = this.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 i = new InstructionImpl(new InstructionPusher(id, input.getDeadline()), ret, id,
356 this.insns.put(id, i);
358 // Attach it into its dependencies
359 for (final InstructionImpl d : dependencies) {
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 this.executor.submit(() -> tryScheduleInstruction(i));
375 public String getInstructionID() {
376 return this.instructionId;
379 private synchronized void timeoutInstruction(final InstructionId id) {
380 final InstructionImpl i = this.insns.get(id);
382 LOG.warn("Instruction {} timed out, but not found in the queue", id);
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());
397 private synchronized void tryScheduleInstruction(final InstructionImpl i) {
398 final ListenableFuture<ExecutionResult<Details>> f = i.ready();
400 Futures.addCallback(f, new FutureCallback<ExecutionResult<Details>>() {
402 public void onSuccess(final ExecutionResult<Details> result) {
403 tryScheduleDependants(i);
407 public void onFailure(final Throwable t) {
408 LOG.error("Instruction {} failed to execute", i.getId(), t);
410 }, MoreExecutors.directExecutor());
416 public synchronized ListenableFuture<Void> closeServiceInstance() {
417 LOG.info("Closing Instruction Queue service {}", this.sgi.getValue());
419 ListenableFuture<Void> writeConfigurationFuture = null;
420 if (this.writeConfiguration != null) {
421 writeConfigurationFuture = this.writeConfiguration.remove();
424 for (final InstructionImpl i : this.insns.values()) {
427 // Workaround for BUG-2283
428 final WriteTransaction t = this.dataProvider.newWriteOnlyTransaction();
429 t.delete(LogicalDatastoreType.OPERATIONAL, this.qid);
431 final SettableFuture<Void> future = SettableFuture.create();
433 if (writeConfigurationFuture != null) {
434 writeConfigurationFuture.addListener(() -> submitRemoval(t, future), executor);
436 submitRemoval(t, future);
442 private void submitRemoval(WriteTransaction t, SettableFuture<Void> futureSetable) {
443 final ListenableFuture<Void> future = t.submit();
444 Futures.addCallback(future, new FutureCallback<Void>() {
446 public void onSuccess(final Void result) {
447 LOG.debug("Instruction Queue {} removed", ProgrammingServiceImpl.this.qid);
448 futureSetable.set(null);
452 public void onFailure(final Throwable t) {
453 LOG.error("Failed to shutdown Instruction Queue {}", ProgrammingServiceImpl.this.qid, t);
454 futureSetable.setException(t);
456 }, MoreExecutors.directExecutor());
460 public synchronized void close() {
461 if (this.csspReg != null) {
463 this.csspReg.close();
464 } catch (final Exception e) {
465 LOG.debug("Failed to close Instruction Scheduler service", e);
468 if (this.serviceRegistration != null) {
469 this.serviceRegistration.unregister();
470 this.serviceRegistration = null;
474 void setServiceRegistration(final ServiceRegistration<?> serviceRegistration) {
475 this.serviceRegistration = serviceRegistration;