2 * Copyright (c) 2014 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.controller.sample.toaster.provider;
10 import static java.util.Objects.requireNonNull;
11 import static org.opendaylight.mdsal.common.api.LogicalDatastoreType.CONFIGURATION;
12 import static org.opendaylight.mdsal.common.api.LogicalDatastoreType.OPERATIONAL;
13 import static org.opendaylight.yangtools.yang.common.ErrorType.APPLICATION;
15 import com.google.common.util.concurrent.FluentFuture;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import com.google.common.util.concurrent.MoreExecutors;
20 import com.google.common.util.concurrent.SettableFuture;
21 import java.util.List;
22 import java.util.Optional;
23 import java.util.concurrent.Callable;
24 import java.util.concurrent.ExecutionException;
25 import java.util.concurrent.ExecutorService;
26 import java.util.concurrent.Executors;
27 import java.util.concurrent.Future;
28 import java.util.concurrent.atomic.AtomicLong;
29 import java.util.concurrent.atomic.AtomicReference;
30 import java.util.function.Function;
31 import javax.annotation.PreDestroy;
32 import javax.inject.Inject;
33 import javax.inject.Singleton;
34 import org.eclipse.jdt.annotation.NonNull;
35 import org.opendaylight.controller.md.sal.common.util.jmx.AbstractMXBean;
36 import org.opendaylight.mdsal.binding.api.DataBroker;
37 import org.opendaylight.mdsal.binding.api.DataTreeChangeListener;
38 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
39 import org.opendaylight.mdsal.binding.api.DataTreeModification;
40 import org.opendaylight.mdsal.binding.api.NotificationPublishService;
41 import org.opendaylight.mdsal.binding.api.ReadWriteTransaction;
42 import org.opendaylight.mdsal.binding.api.RpcProviderService;
43 import org.opendaylight.mdsal.binding.api.WriteTransaction;
44 import org.opendaylight.mdsal.common.api.CommitInfo;
45 import org.opendaylight.mdsal.common.api.OptimisticLockFailedException;
46 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
47 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.CancelToast;
48 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.CancelToastInput;
49 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.CancelToastOutput;
50 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.CancelToastOutputBuilder;
51 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.DisplayString;
52 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToast;
53 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastInput;
54 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastOutput;
55 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastOutputBuilder;
56 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.RestockToaster;
57 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.RestockToasterInput;
58 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.RestockToasterOutput;
59 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.RestockToasterOutputBuilder;
60 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.Toaster;
61 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.Toaster.ToasterStatus;
62 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterBuilder;
63 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterOutOfBreadBuilder;
64 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterRestocked;
65 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterRestockedBuilder;
66 import org.opendaylight.yangtools.concepts.Registration;
67 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
68 import org.opendaylight.yangtools.yang.common.ErrorTag;
69 import org.opendaylight.yangtools.yang.common.ErrorType;
70 import org.opendaylight.yangtools.yang.common.RpcError;
71 import org.opendaylight.yangtools.yang.common.RpcResult;
72 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
73 import org.osgi.service.component.annotations.Activate;
74 import org.osgi.service.component.annotations.Component;
75 import org.osgi.service.component.annotations.Deactivate;
76 import org.osgi.service.component.annotations.Reference;
77 import org.osgi.service.metatype.annotations.AttributeDefinition;
78 import org.osgi.service.metatype.annotations.Designate;
79 import org.osgi.service.metatype.annotations.ObjectClassDefinition;
80 import org.slf4j.Logger;
81 import org.slf4j.LoggerFactory;
84 @Component(service = MakeToast.class, immediate = true)
85 @Designate(ocd = OpendaylightToaster.Configuration.class)
86 public final class OpendaylightToaster extends AbstractMXBean
87 implements MakeToast, ToasterProviderRuntimeMXBean, DataTreeChangeListener<Toaster>, AutoCloseable {
88 @ObjectClassDefinition
89 public @interface Configuration {
90 @AttributeDefinition(description = "The name of the toaster's manufacturer", max = "255")
91 String manufacturer() default TOASTER_MANUFACTURER;
92 @AttributeDefinition(description = "The name of the toaster's model", max = "255")
93 String modelNumber() default TOASTER_MODEL_NUMBER;
94 @AttributeDefinition(description = "How many times we attempt to make toast before failing ",
95 min = "0", max = "65535")
96 int maxMakeToastTries() default 2;
99 private static final CancelToastOutput EMPTY_CANCEL_OUTPUT = new CancelToastOutputBuilder().build();
100 private static final MakeToastOutput EMPTY_MAKE_OUTPUT = new MakeToastOutputBuilder().build();
101 private static final RestockToasterOutput EMPTY_RESTOCK_OUTPUT = new RestockToasterOutputBuilder().build();
103 private static final Logger LOG = LoggerFactory.getLogger(OpendaylightToaster.class);
105 private static final InstanceIdentifier<Toaster> TOASTER_IID = InstanceIdentifier.builder(Toaster.class).build();
106 private static final String TOASTER_MANUFACTURER = "Opendaylight";
107 private static final String TOASTER_MODEL_NUMBER = "Model 1 - Binding Aware";
109 private final DataBroker dataBroker;
110 private final NotificationPublishService notificationProvider;
111 private final Registration dataTreeChangeListenerRegistration;
112 private final Registration reg;
114 private final ExecutorService executor;
116 // This holds the Future for the current make toast task and is used to cancel the current toast.
117 private final AtomicReference<Future<?>> currentMakeToastTask = new AtomicReference<>();
119 // Thread safe holders
120 private final AtomicLong amountOfBreadInStock = new AtomicLong(100);
121 private final AtomicLong toastsMade = new AtomicLong(0);
122 private final AtomicLong darknessFactor = new AtomicLong(1000);
124 private final @NonNull DisplayString manufacturer;
125 private final @NonNull DisplayString modelNumber;
126 private final int maxMakeToastTries;
128 public OpendaylightToaster(final DataBroker dataProvider,
129 final NotificationPublishService notificationPublishService, final RpcProviderService rpcProviderService,
130 final String manufacturer, final String modelNumber, final int maxMakeToastTries) {
131 super("OpendaylightToaster", "toaster-provider", null);
132 notificationProvider = requireNonNull(notificationPublishService);
133 dataBroker = requireNonNull(dataProvider);
135 this.manufacturer = new DisplayString(manufacturer);
136 this.modelNumber = new DisplayString(modelNumber);
137 this.maxMakeToastTries = maxMakeToastTries;
139 executor = Executors.newFixedThreadPool(1);
140 reg = rpcProviderService.registerRpcImplementations(
141 (CancelToast) this::cancelToast,
143 (RestockToaster) this::restockToaster);
145 LOG.info("Initializing...");
147 dataTreeChangeListenerRegistration = requireNonNull(dataBroker, "dataBroker must be set")
148 .registerTreeChangeListener(DataTreeIdentifier.of(CONFIGURATION, TOASTER_IID), this);
150 setToasterStatusUp(null).get();
151 } catch (InterruptedException | ExecutionException e) {
152 throw new IllegalStateException("Failed to commit initial data", e);
155 // Register our MXBean.
160 public OpendaylightToaster(final DataBroker dataProvider,
161 final NotificationPublishService notificationPublishService, final RpcProviderService rpcProviderService) {
162 this(dataProvider, notificationPublishService, rpcProviderService, TOASTER_MANUFACTURER, TOASTER_MODEL_NUMBER,
167 public OpendaylightToaster(@Reference final DataBroker dataProvider,
168 @Reference final NotificationPublishService notificationPublishService,
169 @Reference final RpcProviderService rpcProviderService, final @NonNull Configuration configuration) {
170 this(dataProvider, notificationPublishService, rpcProviderService, configuration.manufacturer(),
171 configuration.modelNumber(), configuration.maxMakeToastTries());
175 * Implemented from the AutoCloseable interface.
180 public void close() {
181 LOG.info("Closing...");
183 // Unregister our MXBean.
187 // When we close this service we need to shutdown our executor!
190 if (dataTreeChangeListenerRegistration != null) {
191 dataTreeChangeListenerRegistration.close();
194 if (dataBroker != null) {
195 WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
196 tx.delete(OPERATIONAL,TOASTER_IID);
197 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
199 public void onSuccess(final CommitInfo result) {
200 LOG.debug("Successfully deleted the operational Toaster");
204 public void onFailure(final Throwable failure) {
205 LOG.error("Delete of the operational Toaster failed", failure);
207 }, MoreExecutors.directExecutor());
211 private Toaster buildToaster(final ToasterStatus status) {
212 // note - we are simulating a device whose manufacture and model are
213 // fixed (embedded) into the hardware.
214 // This is why the manufacture and model number are hardcoded.
215 return new ToasterBuilder()
216 .setToasterManufacturer(manufacturer)
217 .setToasterModelNumber(modelNumber)
218 .setToasterStatus(status)
223 * Implemented from the DataTreeChangeListener interface.
226 public void onDataTreeChanged(final List<DataTreeModification<Toaster>> changes) {
227 for (var change: changes) {
228 final var rootNode = change.getRootNode();
229 switch (rootNode.modificationType()) {
231 final var oldToaster = rootNode.dataBefore();
232 final var newToaster = rootNode.dataAfter();
233 LOG.info("onDataTreeChanged - Toaster config with path {} was added or replaced: old Toaster: {}, "
234 + "new Toaster: {}", change.getRootPath().path(), oldToaster, newToaster);
236 final var darkness = newToaster.getDarknessFactor();
237 if (darkness != null) {
238 darknessFactor.set(darkness.toJava());
241 case DELETE -> LOG.info("onDataTreeChanged - Toaster config with path {} was deleted: old Toaster: {}",
242 change.getRootPath().path(), rootNode.dataBefore());
251 * RPC call implemented from the ToasterService interface that cancels the current toast, if any.
253 private ListenableFuture<RpcResult<CancelToastOutput>> cancelToast(final CancelToastInput input) {
254 final var current = currentMakeToastTask.getAndSet(null);
255 if (current != null) {
256 current.cancel(true);
259 // Always return success from the cancel toast call
260 return Futures.immediateFuture(RpcResultBuilder.success(EMPTY_CANCEL_OUTPUT).build());
264 * RPC call implemented from the ToasterService interface that attempts to make toast.
267 public ListenableFuture<RpcResult<MakeToastOutput>> invoke(final MakeToastInput input) {
268 LOG.info("makeToast: {}", input);
269 final var futureResult = SettableFuture.<RpcResult<MakeToastOutput>>create();
270 checkStatusAndMakeToast(input, futureResult, maxMakeToastTries);
274 private static RpcError makeToasterOutOfBreadError() {
275 return RpcResultBuilder.newError(APPLICATION, ErrorTag.RESOURCE_DENIED, "Toaster is out of bread",
276 "out-of-stock", null, null);
279 private static RpcError makeToasterInUseError() {
280 return RpcResultBuilder.newWarning(APPLICATION, ErrorTag.IN_USE, "Toaster is busy", null, null, null);
283 private void checkStatusAndMakeToast(final MakeToastInput input,
284 final SettableFuture<RpcResult<MakeToastOutput>> futureResult, final int tries) {
285 // Read the ToasterStatus and, if currently Up, try to write the status to Down.
286 // If that succeeds, then we essentially have an exclusive lock and can proceed
288 final ReadWriteTransaction tx = dataBroker.newReadWriteTransaction();
289 FluentFuture<Optional<Toaster>> readFuture = tx.read(OPERATIONAL, TOASTER_IID);
291 final ListenableFuture<? extends CommitInfo> commitFuture =
292 Futures.transformAsync(readFuture, toasterData -> {
293 ToasterStatus toasterStatus = ToasterStatus.Up;
294 if (toasterData.isPresent()) {
295 toasterStatus = toasterData.orElseThrow().getToasterStatus();
298 LOG.debug("Read toaster status: {}", toasterStatus);
300 if (toasterStatus == ToasterStatus.Up) {
303 LOG.debug("Toaster is out of bread");
305 return Futures.immediateFailedFuture(
306 new TransactionCommitFailedException("", makeToasterOutOfBreadError()));
309 LOG.debug("Setting Toaster status to Down");
311 // We're not currently making toast - try to update the status to Down
312 // to indicate we're going to make toast. This acts as a lock to prevent
313 // concurrent toasting.
314 tx.put(OPERATIONAL, TOASTER_IID, buildToaster(ToasterStatus.Down));
318 LOG.debug("Oops - already making toast!");
320 // Return an error since we are already making toast. This will get
321 // propagated to the commitFuture below which will interpret the null
322 // TransactionStatus in the RpcResult as an error condition.
324 return Futures.immediateFailedFuture(
325 new TransactionCommitFailedException("", makeToasterInUseError()));
326 }, MoreExecutors.directExecutor());
328 Futures.addCallback(commitFuture, new FutureCallback<CommitInfo>() {
330 public void onSuccess(final CommitInfo result) {
332 currentMakeToastTask.set(executor.submit(new MakeToastTask(input, futureResult)));
336 public void onFailure(final Throwable ex) {
337 if (ex instanceof OptimisticLockFailedException) {
339 // Another thread is likely trying to make toast simultaneously and updated the
340 // status before us. Try reading the status again - if another make toast is
341 // now in progress, we should get ToasterStatus.Down and fail.
344 LOG.debug("Got OptimisticLockFailedException - trying again");
345 checkStatusAndMakeToast(input, futureResult, tries - 1);
347 futureResult.set(RpcResultBuilder.<MakeToastOutput>failed()
348 .withError(ErrorType.APPLICATION, ex.getMessage()).build());
350 } else if (ex instanceof TransactionCommitFailedException) {
351 LOG.debug("Failed to commit Toaster status", ex);
353 // Probably already making toast.
354 futureResult.set(RpcResultBuilder.<MakeToastOutput>failed()
355 .withRpcErrors(((TransactionCommitFailedException)ex).getErrorList()).build());
357 LOG.debug("Unexpected error committing Toaster status", ex);
358 futureResult.set(RpcResultBuilder.<MakeToastOutput>failed().withError(ErrorType.APPLICATION,
359 "Unexpected error committing Toaster status", ex).build());
362 }, MoreExecutors.directExecutor());
366 * RestConf RPC call implemented from the ToasterService interface.
367 * Restocks the bread for the toaster, resets the toastsMade counter to 0, and sends a
368 * ToasterRestocked notification.
370 private ListenableFuture<RpcResult<RestockToasterOutput>> restockToaster(final RestockToasterInput input) {
371 LOG.info("restockToaster: {}", input);
373 amountOfBreadInStock.set(input.getAmountOfBreadToStock().toJava());
375 if (amountOfBreadInStock.get() > 0) {
376 ToasterRestocked reStockedNotification = new ToasterRestockedBuilder()
377 .setAmountOfBread(input.getAmountOfBreadToStock()).build();
378 notificationProvider.offerNotification(reStockedNotification);
381 return Futures.immediateFuture(RpcResultBuilder.success(EMPTY_RESTOCK_OUTPUT).build());
385 * JMX RPC call implemented from the ToasterProviderRuntimeMXBean interface.
388 public void clearToastsMade() {
389 LOG.info("clearToastsMade");
394 * Accesssor method implemented from the ToasterProviderRuntimeMXBean interface.
397 public Long getToastsMade() {
398 return toastsMade.get();
401 private ListenableFuture<?> setToasterStatusUp(final Function<Boolean, MakeToastOutput> resultCallback) {
402 WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
403 tx.put(OPERATIONAL,TOASTER_IID, buildToaster(ToasterStatus.Up));
405 final var future = tx.commit();
406 Futures.addCallback(future, new FutureCallback<CommitInfo>() {
408 public void onSuccess(final CommitInfo result) {
409 LOG.info("Successfully set ToasterStatus to Up");
410 notifyCallback(true);
414 public void onFailure(final Throwable failure) {
415 // We shouldn't get an OptimisticLockFailedException (or any ex) as no
416 // other component should be updating the operational state.
417 LOG.error("Failed to update toaster status", failure);
419 notifyCallback(false);
422 void notifyCallback(final boolean result) {
423 if (resultCallback != null) {
424 resultCallback.apply(result);
427 }, MoreExecutors.directExecutor());
432 private boolean outOfBread() {
433 return amountOfBreadInStock.get() == 0;
436 private class MakeToastTask implements Callable<Void> {
438 final MakeToastInput toastRequest;
439 final SettableFuture<RpcResult<MakeToastOutput>> futureResult;
441 MakeToastTask(final MakeToastInput toastRequest,
442 final SettableFuture<RpcResult<MakeToastOutput>> futureResult) {
443 this.toastRequest = toastRequest;
444 this.futureResult = futureResult;
450 // make toast just sleeps for n seconds per doneness level.
451 Thread.sleep(darknessFactor.get()
452 * toastRequest.getToasterDoneness().toJava());
454 } catch (InterruptedException e) {
455 LOG.info("Interrupted while making the toast");
458 toastsMade.incrementAndGet();
460 amountOfBreadInStock.getAndDecrement();
462 LOG.info("Toaster is out of bread!");
464 notificationProvider.offerNotification(new ToasterOutOfBreadBuilder().build());
467 // Set the Toaster status back to up - this essentially releases the toasting lock.
468 // We can't clear the current toast task nor set the Future result until the
469 // update has been committed so we pass a callback to be notified on completion.
471 setToasterStatusUp(result -> {
472 currentMakeToastTask.set(null);
473 LOG.debug("Toast done");
474 futureResult.set(RpcResultBuilder.success(EMPTY_MAKE_OUTPUT).build());