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.binding.api.DataObjectModification.ModificationType.DELETE;
12 import static org.opendaylight.mdsal.binding.api.DataObjectModification.ModificationType.WRITE;
13 import static org.opendaylight.mdsal.common.api.LogicalDatastoreType.CONFIGURATION;
14 import static org.opendaylight.mdsal.common.api.LogicalDatastoreType.OPERATIONAL;
15 import static org.opendaylight.yangtools.yang.common.ErrorType.APPLICATION;
17 import com.google.common.util.concurrent.FluentFuture;
18 import com.google.common.util.concurrent.FutureCallback;
19 import com.google.common.util.concurrent.Futures;
20 import com.google.common.util.concurrent.ListenableFuture;
21 import com.google.common.util.concurrent.MoreExecutors;
22 import com.google.common.util.concurrent.SettableFuture;
23 import java.util.Collection;
24 import java.util.Optional;
25 import java.util.concurrent.Callable;
26 import java.util.concurrent.ExecutionException;
27 import java.util.concurrent.ExecutorService;
28 import java.util.concurrent.Executors;
29 import java.util.concurrent.Future;
30 import java.util.concurrent.atomic.AtomicLong;
31 import java.util.concurrent.atomic.AtomicReference;
32 import java.util.function.Function;
33 import javax.annotation.PreDestroy;
34 import javax.inject.Inject;
35 import javax.inject.Singleton;
36 import org.eclipse.jdt.annotation.NonNull;
37 import org.opendaylight.controller.md.sal.common.util.jmx.AbstractMXBean;
38 import org.opendaylight.mdsal.binding.api.DataBroker;
39 import org.opendaylight.mdsal.binding.api.DataObjectModification;
40 import org.opendaylight.mdsal.binding.api.DataTreeChangeListener;
41 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
42 import org.opendaylight.mdsal.binding.api.DataTreeModification;
43 import org.opendaylight.mdsal.binding.api.NotificationPublishService;
44 import org.opendaylight.mdsal.binding.api.ReadWriteTransaction;
45 import org.opendaylight.mdsal.binding.api.RpcProviderService;
46 import org.opendaylight.mdsal.binding.api.WriteTransaction;
47 import org.opendaylight.mdsal.common.api.CommitInfo;
48 import org.opendaylight.mdsal.common.api.OptimisticLockFailedException;
49 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
50 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.CancelToastInput;
51 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.CancelToastOutput;
52 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.CancelToastOutputBuilder;
53 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.DisplayString;
54 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastInput;
55 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastOutput;
56 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastOutputBuilder;
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.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterService;
67 import org.opendaylight.yangtools.concepts.ListenerRegistration;
68 import org.opendaylight.yangtools.concepts.Registration;
69 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
70 import org.opendaylight.yangtools.yang.common.ErrorTag;
71 import org.opendaylight.yangtools.yang.common.ErrorType;
72 import org.opendaylight.yangtools.yang.common.RpcError;
73 import org.opendaylight.yangtools.yang.common.RpcResult;
74 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
75 import org.opendaylight.yangtools.yang.common.Uint32;
76 import org.osgi.service.component.annotations.Activate;
77 import org.osgi.service.component.annotations.Component;
78 import org.osgi.service.component.annotations.Deactivate;
79 import org.osgi.service.component.annotations.Reference;
80 import org.osgi.service.metatype.annotations.AttributeDefinition;
81 import org.osgi.service.metatype.annotations.Designate;
82 import org.osgi.service.metatype.annotations.ObjectClassDefinition;
83 import org.slf4j.Logger;
84 import org.slf4j.LoggerFactory;
87 @Component(service = ToasterService.class, immediate = true)
88 @Designate(ocd = OpendaylightToaster.Configuration.class)
89 public final class OpendaylightToaster extends AbstractMXBean
90 implements ToasterService, ToasterProviderRuntimeMXBean, DataTreeChangeListener<Toaster>, AutoCloseable {
91 @ObjectClassDefinition
92 public @interface Configuration {
93 @AttributeDefinition(description = "The name of the toaster's manufacturer", max = "255")
94 String manufacturer() default TOASTER_MANUFACTURER;
95 @AttributeDefinition(description = "The name of the toaster's model", max = "255")
96 String modelNumber() default TOASTER_MODEL_NUMBER;
97 @AttributeDefinition(description = "How many times we attempt to make toast before failing ",
98 min = "0", max = "65535")
99 int maxMakeToastTries() default 2;
102 private static final CancelToastOutput EMPTY_CANCEL_OUTPUT = new CancelToastOutputBuilder().build();
103 private static final MakeToastOutput EMPTY_MAKE_OUTPUT = new MakeToastOutputBuilder().build();
104 private static final RestockToasterOutput EMPTY_RESTOCK_OUTPUT = new RestockToasterOutputBuilder().build();
106 private static final Logger LOG = LoggerFactory.getLogger(OpendaylightToaster.class);
108 private static final InstanceIdentifier<Toaster> TOASTER_IID = InstanceIdentifier.builder(Toaster.class).build();
109 private static final String TOASTER_MANUFACTURER = "Opendaylight";
110 private static final String TOASTER_MODEL_NUMBER = "Model 1 - Binding Aware";
112 private final DataBroker dataBroker;
113 private final NotificationPublishService notificationProvider;
114 private final ListenerRegistration<OpendaylightToaster> dataTreeChangeListenerRegistration;
115 private final Registration reg;
117 private final ExecutorService executor;
119 // This holds the Future for the current make toast task and is used to cancel the current toast.
120 private final AtomicReference<Future<?>> currentMakeToastTask = new AtomicReference<>();
122 // Thread safe holders
123 private final AtomicLong amountOfBreadInStock = new AtomicLong(100);
124 private final AtomicLong toastsMade = new AtomicLong(0);
125 private final AtomicLong darknessFactor = new AtomicLong(1000);
127 private final @NonNull DisplayString manufacturer;
128 private final @NonNull DisplayString modelNumber;
129 private final int maxMakeToastTries;
131 public OpendaylightToaster(final DataBroker dataProvider,
132 final NotificationPublishService notificationPublishService, final RpcProviderService rpcProviderService,
133 final String manufacturer, final String modelNumber, final int maxMakeToastTries) {
134 super("OpendaylightToaster", "toaster-provider", null);
135 notificationProvider = requireNonNull(notificationPublishService);
136 dataBroker = requireNonNull(dataProvider);
138 this.manufacturer = new DisplayString(manufacturer);
139 this.modelNumber = new DisplayString(modelNumber);
140 this.maxMakeToastTries = maxMakeToastTries;
142 executor = Executors.newFixedThreadPool(1);
143 reg = rpcProviderService.registerRpcImplementation(ToasterService.class, this);
145 LOG.info("Initializing...");
147 dataTreeChangeListenerRegistration = requireNonNull(dataBroker, "dataBroker must be set")
148 .registerDataTreeChangeListener(DataTreeIdentifier.create(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 Collection<DataTreeModification<Toaster>> changes) {
227 for (DataTreeModification<Toaster> change: changes) {
228 DataObjectModification<Toaster> rootNode = change.getRootNode();
229 if (rootNode.getModificationType() == WRITE) {
230 Toaster oldToaster = rootNode.getDataBefore();
231 Toaster newToaster = rootNode.getDataAfter();
232 LOG.info("onDataTreeChanged - Toaster config with path {} was added or replaced: "
233 + "old Toaster: {}, new Toaster: {}", change.getRootPath().getRootIdentifier(),
234 oldToaster, newToaster);
236 Uint32 darkness = newToaster.getDarknessFactor();
237 if (darkness != null) {
238 darknessFactor.set(darkness.toJava());
240 } else if (rootNode.getModificationType() == DELETE) {
241 LOG.info("onDataTreeChanged - Toaster config with path {} was deleted: old Toaster: {}",
242 change.getRootPath().getRootIdentifier(), rootNode.getDataBefore());
248 * RPC call implemented from the ToasterService interface that cancels the current toast, if any.
251 public ListenableFuture<RpcResult<CancelToastOutput>> cancelToast(final CancelToastInput input) {
252 Future<?> current = currentMakeToastTask.getAndSet(null);
253 if (current != null) {
254 current.cancel(true);
257 // Always return success from the cancel toast call
258 return Futures.immediateFuture(RpcResultBuilder.success(EMPTY_CANCEL_OUTPUT).build());
262 * RPC call implemented from the ToasterService interface that attempts to make toast.
265 public ListenableFuture<RpcResult<MakeToastOutput>> makeToast(final MakeToastInput input) {
266 LOG.info("makeToast: {}", input);
268 final SettableFuture<RpcResult<MakeToastOutput>> futureResult = SettableFuture.create();
270 checkStatusAndMakeToast(input, futureResult, maxMakeToastTries);
275 private static RpcError makeToasterOutOfBreadError() {
276 return RpcResultBuilder.newError(APPLICATION, ErrorTag.RESOURCE_DENIED, "Toaster is out of bread",
277 "out-of-stock", null, null);
280 private static RpcError makeToasterInUseError() {
281 return RpcResultBuilder.newWarning(APPLICATION, ErrorTag.IN_USE, "Toaster is busy", null, null, null);
284 private void checkStatusAndMakeToast(final MakeToastInput input,
285 final SettableFuture<RpcResult<MakeToastOutput>> futureResult, final int tries) {
286 // Read the ToasterStatus and, if currently Up, try to write the status to Down.
287 // If that succeeds, then we essentially have an exclusive lock and can proceed
289 final ReadWriteTransaction tx = dataBroker.newReadWriteTransaction();
290 FluentFuture<Optional<Toaster>> readFuture = tx.read(OPERATIONAL, TOASTER_IID);
292 final ListenableFuture<? extends CommitInfo> commitFuture =
293 Futures.transformAsync(readFuture, toasterData -> {
294 ToasterStatus toasterStatus = ToasterStatus.Up;
295 if (toasterData.isPresent()) {
296 toasterStatus = toasterData.get().getToasterStatus();
299 LOG.debug("Read toaster status: {}", toasterStatus);
301 if (toasterStatus == ToasterStatus.Up) {
304 LOG.debug("Toaster is out of bread");
306 return Futures.immediateFailedFuture(
307 new TransactionCommitFailedException("", makeToasterOutOfBreadError()));
310 LOG.debug("Setting Toaster status to Down");
312 // We're not currently making toast - try to update the status to Down
313 // to indicate we're going to make toast. This acts as a lock to prevent
314 // concurrent toasting.
315 tx.put(OPERATIONAL, TOASTER_IID, buildToaster(ToasterStatus.Down));
319 LOG.debug("Oops - already making toast!");
321 // Return an error since we are already making toast. This will get
322 // propagated to the commitFuture below which will interpret the null
323 // TransactionStatus in the RpcResult as an error condition.
325 return Futures.immediateFailedFuture(
326 new TransactionCommitFailedException("", makeToasterInUseError()));
327 }, MoreExecutors.directExecutor());
329 Futures.addCallback(commitFuture, new FutureCallback<CommitInfo>() {
331 public void onSuccess(final CommitInfo result) {
333 currentMakeToastTask.set(executor.submit(new MakeToastTask(input, futureResult)));
337 public void onFailure(final Throwable ex) {
338 if (ex instanceof OptimisticLockFailedException) {
340 // Another thread is likely trying to make toast simultaneously and updated the
341 // status before us. Try reading the status again - if another make toast is
342 // now in progress, we should get ToasterStatus.Down and fail.
345 LOG.debug("Got OptimisticLockFailedException - trying again");
346 checkStatusAndMakeToast(input, futureResult, tries - 1);
348 futureResult.set(RpcResultBuilder.<MakeToastOutput>failed()
349 .withError(ErrorType.APPLICATION, ex.getMessage()).build());
351 } else if (ex instanceof TransactionCommitFailedException) {
352 LOG.debug("Failed to commit Toaster status", ex);
354 // Probably already making toast.
355 futureResult.set(RpcResultBuilder.<MakeToastOutput>failed()
356 .withRpcErrors(((TransactionCommitFailedException)ex).getErrorList()).build());
358 LOG.debug("Unexpected error committing Toaster status", ex);
359 futureResult.set(RpcResultBuilder.<MakeToastOutput>failed().withError(ErrorType.APPLICATION,
360 "Unexpected error committing Toaster status", ex).build());
363 }, MoreExecutors.directExecutor());
367 * RestConf RPC call implemented from the ToasterService interface.
368 * Restocks the bread for the toaster, resets the toastsMade counter to 0, and sends a
369 * ToasterRestocked notification.
372 public ListenableFuture<RpcResult<RestockToasterOutput>> restockToaster(final RestockToasterInput input) {
373 LOG.info("restockToaster: {}", input);
375 amountOfBreadInStock.set(input.getAmountOfBreadToStock().toJava());
377 if (amountOfBreadInStock.get() > 0) {
378 ToasterRestocked reStockedNotification = new ToasterRestockedBuilder()
379 .setAmountOfBread(input.getAmountOfBreadToStock()).build();
380 notificationProvider.offerNotification(reStockedNotification);
383 return Futures.immediateFuture(RpcResultBuilder.success(EMPTY_RESTOCK_OUTPUT).build());
387 * JMX RPC call implemented from the ToasterProviderRuntimeMXBean interface.
390 public void clearToastsMade() {
391 LOG.info("clearToastsMade");
396 * Accesssor method implemented from the ToasterProviderRuntimeMXBean interface.
399 public Long getToastsMade() {
400 return toastsMade.get();
403 private ListenableFuture<?> setToasterStatusUp(final Function<Boolean, MakeToastOutput> resultCallback) {
404 WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
405 tx.put(OPERATIONAL,TOASTER_IID, buildToaster(ToasterStatus.Up));
407 final var future = tx.commit();
408 Futures.addCallback(future, new FutureCallback<CommitInfo>() {
410 public void onSuccess(final CommitInfo result) {
411 LOG.info("Successfully set ToasterStatus to Up");
412 notifyCallback(true);
416 public void onFailure(final Throwable failure) {
417 // We shouldn't get an OptimisticLockFailedException (or any ex) as no
418 // other component should be updating the operational state.
419 LOG.error("Failed to update toaster status", failure);
421 notifyCallback(false);
424 void notifyCallback(final boolean result) {
425 if (resultCallback != null) {
426 resultCallback.apply(result);
429 }, MoreExecutors.directExecutor());
434 private boolean outOfBread() {
435 return amountOfBreadInStock.get() == 0;
438 private class MakeToastTask implements Callable<Void> {
440 final MakeToastInput toastRequest;
441 final SettableFuture<RpcResult<MakeToastOutput>> futureResult;
443 MakeToastTask(final MakeToastInput toastRequest,
444 final SettableFuture<RpcResult<MakeToastOutput>> futureResult) {
445 this.toastRequest = toastRequest;
446 this.futureResult = futureResult;
452 // make toast just sleeps for n seconds per doneness level.
453 Thread.sleep(darknessFactor.get()
454 * toastRequest.getToasterDoneness().toJava());
456 } catch (InterruptedException e) {
457 LOG.info("Interrupted while making the toast");
460 toastsMade.incrementAndGet();
462 amountOfBreadInStock.getAndDecrement();
464 LOG.info("Toaster is out of bread!");
466 notificationProvider.offerNotification(new ToasterOutOfBreadBuilder().build());
469 // Set the Toaster status back to up - this essentially releases the toasting lock.
470 // We can't clear the current toast task nor set the Future result until the
471 // update has been committed so we pass a callback to be notified on completion.
473 setToasterStatusUp(result -> {
474 currentMakeToastTask.set(null);
475 LOG.debug("Toast done");
476 futureResult.set(RpcResultBuilder.success(EMPTY_MAKE_OUTPUT).build());