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 org.opendaylight.mdsal.binding.api.DataObjectModification.ModificationType.DELETE;
11 import static org.opendaylight.mdsal.binding.api.DataObjectModification.ModificationType.WRITE;
12 import static org.opendaylight.mdsal.common.api.LogicalDatastoreType.CONFIGURATION;
13 import static org.opendaylight.mdsal.common.api.LogicalDatastoreType.OPERATIONAL;
14 import static org.opendaylight.yangtools.yang.common.RpcError.ErrorType.APPLICATION;
16 import com.google.common.base.Function;
17 import com.google.common.base.Preconditions;
18 import com.google.common.util.concurrent.FluentFuture;
19 import com.google.common.util.concurrent.FutureCallback;
20 import com.google.common.util.concurrent.Futures;
21 import com.google.common.util.concurrent.ListenableFuture;
22 import com.google.common.util.concurrent.MoreExecutors;
23 import com.google.common.util.concurrent.SettableFuture;
24 import java.util.Collection;
25 import java.util.Optional;
26 import java.util.concurrent.Callable;
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 org.opendaylight.controller.md.sal.common.util.jmx.AbstractMXBean;
33 import org.opendaylight.mdsal.binding.api.DataBroker;
34 import org.opendaylight.mdsal.binding.api.DataObjectModification;
35 import org.opendaylight.mdsal.binding.api.DataTreeChangeListener;
36 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
37 import org.opendaylight.mdsal.binding.api.DataTreeModification;
38 import org.opendaylight.mdsal.binding.api.NotificationPublishService;
39 import org.opendaylight.mdsal.binding.api.ReadWriteTransaction;
40 import org.opendaylight.mdsal.binding.api.WriteTransaction;
41 import org.opendaylight.mdsal.common.api.CommitInfo;
42 import org.opendaylight.mdsal.common.api.OptimisticLockFailedException;
43 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
44 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.CancelToastInput;
45 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.CancelToastOutput;
46 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.CancelToastOutputBuilder;
47 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.DisplayString;
48 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastInput;
49 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastOutput;
50 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastOutputBuilder;
51 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.RestockToasterInput;
52 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.RestockToasterOutput;
53 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.RestockToasterOutputBuilder;
54 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.Toaster;
55 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.Toaster.ToasterStatus;
56 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterBuilder;
57 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterOutOfBreadBuilder;
58 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterRestocked;
59 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterRestockedBuilder;
60 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterService;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.toaster.app.config.rev160503.ToasterAppConfig;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.toaster.app.config.rev160503.ToasterAppConfigBuilder;
63 import org.opendaylight.yangtools.concepts.ListenerRegistration;
64 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
65 import org.opendaylight.yangtools.yang.common.RpcError;
66 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
67 import org.opendaylight.yangtools.yang.common.RpcResult;
68 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
72 public class OpendaylightToaster extends AbstractMXBean
73 implements ToasterService, ToasterProviderRuntimeMXBean, DataTreeChangeListener<Toaster>, AutoCloseable {
75 private static final CancelToastOutput EMPTY_CANCEL_OUTPUT = new CancelToastOutputBuilder().build();
76 private static final MakeToastOutput EMPTY_MAKE_OUTPUT = new MakeToastOutputBuilder().build();
77 private static final RestockToasterOutput EMPTY_RESTOCK_OUTPUT = new RestockToasterOutputBuilder().build();
79 private static final Logger LOG = LoggerFactory.getLogger(OpendaylightToaster.class);
81 private static final InstanceIdentifier<Toaster> TOASTER_IID = InstanceIdentifier.builder(Toaster.class).build();
82 private static final DisplayString TOASTER_MANUFACTURER = new DisplayString("Opendaylight");
83 private static final DisplayString TOASTER_MODEL_NUMBER = new DisplayString("Model 1 - Binding Aware");
85 private DataBroker dataBroker;
86 private NotificationPublishService notificationProvider;
87 private ListenerRegistration<OpendaylightToaster> dataTreeChangeListenerRegistration;
89 private final ExecutorService executor;
91 // This holds the Future for the current make toast task and is used to cancel the current toast.
92 private final AtomicReference<Future<?>> currentMakeToastTask = new AtomicReference<>();
94 // Thread safe holders
95 private final AtomicLong amountOfBreadInStock = new AtomicLong(100);
96 private final AtomicLong toastsMade = new AtomicLong(0);
97 private final AtomicLong darknessFactor = new AtomicLong(1000);
99 private final ToasterAppConfig toasterAppConfig;
101 public OpendaylightToaster() {
102 this(new ToasterAppConfigBuilder().setManufacturer(TOASTER_MANUFACTURER).setModelNumber(TOASTER_MODEL_NUMBER)
103 .setMaxMakeToastTries(2).build());
106 public OpendaylightToaster(final ToasterAppConfig toasterAppConfig) {
107 super("OpendaylightToaster", "toaster-provider", null);
108 executor = Executors.newFixedThreadPool(1);
109 this.toasterAppConfig = toasterAppConfig;
112 public void setNotificationProvider(final NotificationPublishService notificationPublishService) {
113 this.notificationProvider = notificationPublishService;
116 public void setDataBroker(final DataBroker dataBroker) {
117 this.dataBroker = dataBroker;
121 LOG.info("Initializing...");
123 Preconditions.checkNotNull(dataBroker, "dataBroker must be set");
124 dataTreeChangeListenerRegistration = dataBroker.registerDataTreeChangeListener(
125 DataTreeIdentifier.create(CONFIGURATION, TOASTER_IID), this);
126 setToasterStatusUp(null);
128 // Register our MXBean.
133 * Implemented from the AutoCloseable interface.
136 public void close() {
137 LOG.info("Closing...");
139 // Unregister our MXBean.
142 // When we close this service we need to shutdown our executor!
145 if (dataTreeChangeListenerRegistration != null) {
146 dataTreeChangeListenerRegistration.close();
149 if (dataBroker != null) {
150 WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
151 tx.delete(OPERATIONAL,TOASTER_IID);
152 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
154 public void onSuccess(final CommitInfo result) {
155 LOG.debug("Successfully deleted the operational Toaster");
159 public void onFailure(final Throwable failure) {
160 LOG.error("Delete of the operational Toaster failed", failure);
162 }, MoreExecutors.directExecutor());
166 private Toaster buildToaster(final ToasterStatus status) {
167 // note - we are simulating a device whose manufacture and model are
168 // fixed (embedded) into the hardware.
169 // This is why the manufacture and model number are hardcoded.
170 return new ToasterBuilder().setToasterManufacturer(toasterAppConfig.getManufacturer())
171 .setToasterModelNumber(toasterAppConfig.getModelNumber()).setToasterStatus(status).build();
175 * Implemented from the DataTreeChangeListener interface.
178 public void onDataTreeChanged(final Collection<DataTreeModification<Toaster>> changes) {
179 for (DataTreeModification<Toaster> change: changes) {
180 DataObjectModification<Toaster> rootNode = change.getRootNode();
181 if (rootNode.getModificationType() == WRITE) {
182 Toaster oldToaster = rootNode.getDataBefore();
183 Toaster newToaster = rootNode.getDataAfter();
184 LOG.info("onDataTreeChanged - Toaster config with path {} was added or replaced: "
185 + "old Toaster: {}, new Toaster: {}", change.getRootPath().getRootIdentifier(),
186 oldToaster, newToaster);
188 Long darkness = newToaster.getDarknessFactor();
189 if (darkness != null) {
190 darknessFactor.set(darkness);
192 } else if (rootNode.getModificationType() == DELETE) {
193 LOG.info("onDataTreeChanged - Toaster config with path {} was deleted: old Toaster: {}",
194 change.getRootPath().getRootIdentifier(), rootNode.getDataBefore());
200 * RPC call implemented from the ToasterService interface that cancels the current toast, if any.
203 public ListenableFuture<RpcResult<CancelToastOutput>> cancelToast(final CancelToastInput input) {
204 Future<?> current = currentMakeToastTask.getAndSet(null);
205 if (current != null) {
206 current.cancel(true);
209 // Always return success from the cancel toast call
210 return Futures.immediateFuture(RpcResultBuilder.success(EMPTY_CANCEL_OUTPUT).build());
214 * RPC call implemented from the ToasterService interface that attempts to make toast.
217 public ListenableFuture<RpcResult<MakeToastOutput>> makeToast(final MakeToastInput input) {
218 LOG.info("makeToast: " + input);
220 final SettableFuture<RpcResult<MakeToastOutput>> futureResult = SettableFuture.create();
222 checkStatusAndMakeToast(input, futureResult, toasterAppConfig.getMaxMakeToastTries());
227 private static RpcError makeToasterOutOfBreadError() {
228 return RpcResultBuilder.newError(APPLICATION, "resource-denied", "Toaster is out of bread", "out-of-stock",
232 private static RpcError makeToasterInUseError() {
233 return RpcResultBuilder.newWarning(APPLICATION, "in-use", "Toaster is busy", null, null, null);
236 private void checkStatusAndMakeToast(final MakeToastInput input,
237 final SettableFuture<RpcResult<MakeToastOutput>> futureResult, final int tries) {
238 // Read the ToasterStatus and, if currently Up, try to write the status to Down.
239 // If that succeeds, then we essentially have an exclusive lock and can proceed
241 final ReadWriteTransaction tx = dataBroker.newReadWriteTransaction();
242 FluentFuture<Optional<Toaster>> readFuture = tx.read(OPERATIONAL, TOASTER_IID);
244 final ListenableFuture<? extends CommitInfo> commitFuture =
245 Futures.transformAsync(readFuture, toasterData -> {
246 ToasterStatus toasterStatus = ToasterStatus.Up;
247 if (toasterData.isPresent()) {
248 toasterStatus = toasterData.get().getToasterStatus();
251 LOG.debug("Read toaster status: {}", toasterStatus);
253 if (toasterStatus == ToasterStatus.Up) {
256 LOG.debug("Toaster is out of bread");
258 return Futures.immediateFailedFuture(
259 new TransactionCommitFailedException("", makeToasterOutOfBreadError()));
262 LOG.debug("Setting Toaster status to Down");
264 // We're not currently making toast - try to update the status to Down
265 // to indicate we're going to make toast. This acts as a lock to prevent
266 // concurrent toasting.
267 tx.put(OPERATIONAL, TOASTER_IID, buildToaster(ToasterStatus.Down));
271 LOG.debug("Oops - already making toast!");
273 // Return an error since we are already making toast. This will get
274 // propagated to the commitFuture below which will interpret the null
275 // TransactionStatus in the RpcResult as an error condition.
277 return Futures.immediateFailedFuture(
278 new TransactionCommitFailedException("", makeToasterInUseError()));
279 }, MoreExecutors.directExecutor());
281 Futures.addCallback(commitFuture, new FutureCallback<CommitInfo>() {
283 public void onSuccess(final CommitInfo result) {
285 currentMakeToastTask.set(executor.submit(new MakeToastTask(input, futureResult)));
289 public void onFailure(final Throwable ex) {
290 if (ex instanceof OptimisticLockFailedException) {
292 // Another thread is likely trying to make toast simultaneously and updated the
293 // status before us. Try reading the status again - if another make toast is
294 // now in progress, we should get ToasterStatus.Down and fail.
297 LOG.debug("Got OptimisticLockFailedException - trying again");
298 checkStatusAndMakeToast(input, futureResult, tries - 1);
300 futureResult.set(RpcResultBuilder.<MakeToastOutput>failed()
301 .withError(ErrorType.APPLICATION, ex.getMessage()).build());
303 } else if (ex instanceof TransactionCommitFailedException) {
304 LOG.debug("Failed to commit Toaster status", ex);
306 // Probably already making toast.
307 futureResult.set(RpcResultBuilder.<MakeToastOutput>failed()
308 .withRpcErrors(((TransactionCommitFailedException)ex).getErrorList()).build());
310 LOG.debug("Unexpected error committing Toaster status", ex);
311 futureResult.set(RpcResultBuilder.<MakeToastOutput>failed().withError(ErrorType.APPLICATION,
312 "Unexpected error committing Toaster status", ex).build());
315 }, MoreExecutors.directExecutor());
319 * RestConf RPC call implemented from the ToasterService interface.
320 * Restocks the bread for the toaster, resets the toastsMade counter to 0, and sends a
321 * ToasterRestocked notification.
324 public ListenableFuture<RpcResult<RestockToasterOutput>> restockToaster(final RestockToasterInput input) {
325 LOG.info("restockToaster: " + input);
327 amountOfBreadInStock.set(input.getAmountOfBreadToStock());
329 if (amountOfBreadInStock.get() > 0) {
330 ToasterRestocked reStockedNotification = new ToasterRestockedBuilder()
331 .setAmountOfBread(input.getAmountOfBreadToStock()).build();
332 notificationProvider.offerNotification(reStockedNotification);
335 return Futures.immediateFuture(RpcResultBuilder.success(EMPTY_RESTOCK_OUTPUT).build());
339 * JMX RPC call implemented from the ToasterProviderRuntimeMXBean interface.
342 public void clearToastsMade() {
343 LOG.info("clearToastsMade");
348 * Accesssor method implemented from the ToasterProviderRuntimeMXBean interface.
351 public Long getToastsMade() {
352 return toastsMade.get();
355 private void setToasterStatusUp(final Function<Boolean, MakeToastOutput> resultCallback) {
356 WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
357 tx.put(OPERATIONAL,TOASTER_IID, buildToaster(ToasterStatus.Up));
359 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
361 public void onSuccess(final CommitInfo result) {
362 LOG.info("Successfully set ToasterStatus to Up");
363 notifyCallback(true);
367 public void onFailure(final Throwable failure) {
368 // We shouldn't get an OptimisticLockFailedException (or any ex) as no
369 // other component should be updating the operational state.
370 LOG.error("Failed to update toaster status", failure);
372 notifyCallback(false);
375 void notifyCallback(final boolean result) {
376 if (resultCallback != null) {
377 resultCallback.apply(result);
380 }, MoreExecutors.directExecutor());
383 private boolean outOfBread() {
384 return amountOfBreadInStock.get() == 0;
387 private class MakeToastTask implements Callable<Void> {
389 final MakeToastInput toastRequest;
390 final SettableFuture<RpcResult<MakeToastOutput>> futureResult;
392 MakeToastTask(final MakeToastInput toastRequest,
393 final SettableFuture<RpcResult<MakeToastOutput>> futureResult) {
394 this.toastRequest = toastRequest;
395 this.futureResult = futureResult;
401 // make toast just sleeps for n seconds per doneness level.
402 Thread.sleep(OpendaylightToaster.this.darknessFactor.get() * toastRequest.getToasterDoneness());
404 } catch (InterruptedException e) {
405 LOG.info("Interrupted while making the toast");
408 toastsMade.incrementAndGet();
410 amountOfBreadInStock.getAndDecrement();
412 LOG.info("Toaster is out of bread!");
414 notificationProvider.offerNotification(new ToasterOutOfBreadBuilder().build());
417 // Set the Toaster status back to up - this essentially releases the toasting lock.
418 // We can't clear the current toast task nor set the Future result until the
419 // update has been committed so we pass a callback to be notified on completion.
421 setToasterStatusUp(result -> {
422 currentMakeToastTask.set(null);
423 LOG.debug("Toast done");
424 futureResult.set(RpcResultBuilder.success(EMPTY_MAKE_OUTPUT).build());