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.RpcError.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.ExecutorService;
27 import java.util.concurrent.Executors;
28 import java.util.concurrent.Future;
29 import java.util.concurrent.atomic.AtomicLong;
30 import java.util.concurrent.atomic.AtomicReference;
31 import java.util.function.Function;
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.opendaylight.yangtools.yang.common.Uint16;
70 import org.opendaylight.yangtools.yang.common.Uint32;
71 import org.slf4j.Logger;
72 import org.slf4j.LoggerFactory;
74 public class OpendaylightToaster extends AbstractMXBean
75 implements ToasterService, ToasterProviderRuntimeMXBean, DataTreeChangeListener<Toaster>, AutoCloseable {
77 private static final CancelToastOutput EMPTY_CANCEL_OUTPUT = new CancelToastOutputBuilder().build();
78 private static final MakeToastOutput EMPTY_MAKE_OUTPUT = new MakeToastOutputBuilder().build();
79 private static final RestockToasterOutput EMPTY_RESTOCK_OUTPUT = new RestockToasterOutputBuilder().build();
81 private static final Logger LOG = LoggerFactory.getLogger(OpendaylightToaster.class);
83 private static final InstanceIdentifier<Toaster> TOASTER_IID = InstanceIdentifier.builder(Toaster.class).build();
84 private static final DisplayString TOASTER_MANUFACTURER = new DisplayString("Opendaylight");
85 private static final DisplayString TOASTER_MODEL_NUMBER = new DisplayString("Model 1 - Binding Aware");
87 private DataBroker dataBroker;
88 private NotificationPublishService notificationProvider;
89 private ListenerRegistration<OpendaylightToaster> dataTreeChangeListenerRegistration;
91 private final ExecutorService executor;
93 // This holds the Future for the current make toast task and is used to cancel the current toast.
94 private final AtomicReference<Future<?>> currentMakeToastTask = new AtomicReference<>();
96 // Thread safe holders
97 private final AtomicLong amountOfBreadInStock = new AtomicLong(100);
98 private final AtomicLong toastsMade = new AtomicLong(0);
99 private final AtomicLong darknessFactor = new AtomicLong(1000);
101 private final ToasterAppConfig toasterAppConfig;
103 public OpendaylightToaster() {
104 this(new ToasterAppConfigBuilder().setManufacturer(TOASTER_MANUFACTURER).setModelNumber(TOASTER_MODEL_NUMBER)
105 .setMaxMakeToastTries(Uint16.valueOf(2)).build());
108 public OpendaylightToaster(final ToasterAppConfig toasterAppConfig) {
109 super("OpendaylightToaster", "toaster-provider", null);
110 executor = Executors.newFixedThreadPool(1);
111 this.toasterAppConfig = toasterAppConfig;
114 public void setNotificationProvider(final NotificationPublishService notificationPublishService) {
115 this.notificationProvider = notificationPublishService;
118 public void setDataBroker(final DataBroker dataBroker) {
119 this.dataBroker = dataBroker;
123 LOG.info("Initializing...");
125 dataTreeChangeListenerRegistration = requireNonNull(dataBroker, "dataBroker must be set")
126 .registerDataTreeChangeListener(DataTreeIdentifier.create(CONFIGURATION, TOASTER_IID), this);
127 setToasterStatusUp(null);
129 // Register our MXBean.
134 * Implemented from the AutoCloseable interface.
137 public void close() {
138 LOG.info("Closing...");
140 // Unregister our MXBean.
143 // When we close this service we need to shutdown our executor!
146 if (dataTreeChangeListenerRegistration != null) {
147 dataTreeChangeListenerRegistration.close();
150 if (dataBroker != null) {
151 WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
152 tx.delete(OPERATIONAL,TOASTER_IID);
153 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
155 public void onSuccess(final CommitInfo result) {
156 LOG.debug("Successfully deleted the operational Toaster");
160 public void onFailure(final Throwable failure) {
161 LOG.error("Delete of the operational Toaster failed", failure);
163 }, MoreExecutors.directExecutor());
167 private Toaster buildToaster(final ToasterStatus status) {
168 // note - we are simulating a device whose manufacture and model are
169 // fixed (embedded) into the hardware.
170 // This is why the manufacture and model number are hardcoded.
171 return new ToasterBuilder().setToasterManufacturer(toasterAppConfig.getManufacturer())
172 .setToasterModelNumber(toasterAppConfig.getModelNumber()).setToasterStatus(status).build();
176 * Implemented from the DataTreeChangeListener interface.
179 public void onDataTreeChanged(final Collection<DataTreeModification<Toaster>> changes) {
180 for (DataTreeModification<Toaster> change: changes) {
181 DataObjectModification<Toaster> rootNode = change.getRootNode();
182 if (rootNode.getModificationType() == WRITE) {
183 Toaster oldToaster = rootNode.getDataBefore();
184 Toaster newToaster = rootNode.getDataAfter();
185 LOG.info("onDataTreeChanged - Toaster config with path {} was added or replaced: "
186 + "old Toaster: {}, new Toaster: {}", change.getRootPath().getRootIdentifier(),
187 oldToaster, newToaster);
189 Uint32 darkness = newToaster.getDarknessFactor();
190 if (darkness != null) {
191 darknessFactor.set(darkness.toJava());
193 } else if (rootNode.getModificationType() == DELETE) {
194 LOG.info("onDataTreeChanged - Toaster config with path {} was deleted: old Toaster: {}",
195 change.getRootPath().getRootIdentifier(), rootNode.getDataBefore());
201 * RPC call implemented from the ToasterService interface that cancels the current toast, if any.
204 public ListenableFuture<RpcResult<CancelToastOutput>> cancelToast(final CancelToastInput input) {
205 Future<?> current = currentMakeToastTask.getAndSet(null);
206 if (current != null) {
207 current.cancel(true);
210 // Always return success from the cancel toast call
211 return Futures.immediateFuture(RpcResultBuilder.success(EMPTY_CANCEL_OUTPUT).build());
215 * RPC call implemented from the ToasterService interface that attempts to make toast.
218 public ListenableFuture<RpcResult<MakeToastOutput>> makeToast(final MakeToastInput input) {
219 LOG.info("makeToast: {}", input);
221 final SettableFuture<RpcResult<MakeToastOutput>> futureResult = SettableFuture.create();
223 checkStatusAndMakeToast(input, futureResult, toasterAppConfig.getMaxMakeToastTries().toJava());
228 private static RpcError makeToasterOutOfBreadError() {
229 return RpcResultBuilder.newError(APPLICATION, "resource-denied", "Toaster is out of bread", "out-of-stock",
233 private static RpcError makeToasterInUseError() {
234 return RpcResultBuilder.newWarning(APPLICATION, "in-use", "Toaster is busy", null, null, null);
237 private void checkStatusAndMakeToast(final MakeToastInput input,
238 final SettableFuture<RpcResult<MakeToastOutput>> futureResult, final int tries) {
239 // Read the ToasterStatus and, if currently Up, try to write the status to Down.
240 // If that succeeds, then we essentially have an exclusive lock and can proceed
242 final ReadWriteTransaction tx = dataBroker.newReadWriteTransaction();
243 FluentFuture<Optional<Toaster>> readFuture = tx.read(OPERATIONAL, TOASTER_IID);
245 final ListenableFuture<? extends CommitInfo> commitFuture =
246 Futures.transformAsync(readFuture, toasterData -> {
247 ToasterStatus toasterStatus = ToasterStatus.Up;
248 if (toasterData.isPresent()) {
249 toasterStatus = toasterData.get().getToasterStatus();
252 LOG.debug("Read toaster status: {}", toasterStatus);
254 if (toasterStatus == ToasterStatus.Up) {
257 LOG.debug("Toaster is out of bread");
259 return Futures.immediateFailedFuture(
260 new TransactionCommitFailedException("", makeToasterOutOfBreadError()));
263 LOG.debug("Setting Toaster status to Down");
265 // We're not currently making toast - try to update the status to Down
266 // to indicate we're going to make toast. This acts as a lock to prevent
267 // concurrent toasting.
268 tx.put(OPERATIONAL, TOASTER_IID, buildToaster(ToasterStatus.Down));
272 LOG.debug("Oops - already making toast!");
274 // Return an error since we are already making toast. This will get
275 // propagated to the commitFuture below which will interpret the null
276 // TransactionStatus in the RpcResult as an error condition.
278 return Futures.immediateFailedFuture(
279 new TransactionCommitFailedException("", makeToasterInUseError()));
280 }, MoreExecutors.directExecutor());
282 Futures.addCallback(commitFuture, new FutureCallback<CommitInfo>() {
284 public void onSuccess(final CommitInfo result) {
286 currentMakeToastTask.set(executor.submit(new MakeToastTask(input, futureResult)));
290 public void onFailure(final Throwable ex) {
291 if (ex instanceof OptimisticLockFailedException) {
293 // Another thread is likely trying to make toast simultaneously and updated the
294 // status before us. Try reading the status again - if another make toast is
295 // now in progress, we should get ToasterStatus.Down and fail.
298 LOG.debug("Got OptimisticLockFailedException - trying again");
299 checkStatusAndMakeToast(input, futureResult, tries - 1);
301 futureResult.set(RpcResultBuilder.<MakeToastOutput>failed()
302 .withError(ErrorType.APPLICATION, ex.getMessage()).build());
304 } else if (ex instanceof TransactionCommitFailedException) {
305 LOG.debug("Failed to commit Toaster status", ex);
307 // Probably already making toast.
308 futureResult.set(RpcResultBuilder.<MakeToastOutput>failed()
309 .withRpcErrors(((TransactionCommitFailedException)ex).getErrorList()).build());
311 LOG.debug("Unexpected error committing Toaster status", ex);
312 futureResult.set(RpcResultBuilder.<MakeToastOutput>failed().withError(ErrorType.APPLICATION,
313 "Unexpected error committing Toaster status", ex).build());
316 }, MoreExecutors.directExecutor());
320 * RestConf RPC call implemented from the ToasterService interface.
321 * Restocks the bread for the toaster, resets the toastsMade counter to 0, and sends a
322 * ToasterRestocked notification.
325 public ListenableFuture<RpcResult<RestockToasterOutput>> restockToaster(final RestockToasterInput input) {
326 LOG.info("restockToaster: {}", input);
328 amountOfBreadInStock.set(input.getAmountOfBreadToStock().toJava());
330 if (amountOfBreadInStock.get() > 0) {
331 ToasterRestocked reStockedNotification = new ToasterRestockedBuilder()
332 .setAmountOfBread(input.getAmountOfBreadToStock()).build();
333 notificationProvider.offerNotification(reStockedNotification);
336 return Futures.immediateFuture(RpcResultBuilder.success(EMPTY_RESTOCK_OUTPUT).build());
340 * JMX RPC call implemented from the ToasterProviderRuntimeMXBean interface.
343 public void clearToastsMade() {
344 LOG.info("clearToastsMade");
349 * Accesssor method implemented from the ToasterProviderRuntimeMXBean interface.
352 public Long getToastsMade() {
353 return toastsMade.get();
356 private void setToasterStatusUp(final Function<Boolean, MakeToastOutput> resultCallback) {
357 WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
358 tx.put(OPERATIONAL,TOASTER_IID, buildToaster(ToasterStatus.Up));
360 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
362 public void onSuccess(final CommitInfo result) {
363 LOG.info("Successfully set ToasterStatus to Up");
364 notifyCallback(true);
368 public void onFailure(final Throwable failure) {
369 // We shouldn't get an OptimisticLockFailedException (or any ex) as no
370 // other component should be updating the operational state.
371 LOG.error("Failed to update toaster status", failure);
373 notifyCallback(false);
376 void notifyCallback(final boolean result) {
377 if (resultCallback != null) {
378 resultCallback.apply(result);
381 }, MoreExecutors.directExecutor());
384 private boolean outOfBread() {
385 return amountOfBreadInStock.get() == 0;
388 private class MakeToastTask implements Callable<Void> {
390 final MakeToastInput toastRequest;
391 final SettableFuture<RpcResult<MakeToastOutput>> futureResult;
393 MakeToastTask(final MakeToastInput toastRequest,
394 final SettableFuture<RpcResult<MakeToastOutput>> futureResult) {
395 this.toastRequest = toastRequest;
396 this.futureResult = futureResult;
402 // make toast just sleeps for n seconds per doneness level.
403 Thread.sleep(OpendaylightToaster.this.darknessFactor.get()
404 * toastRequest.getToasterDoneness().toJava());
406 } catch (InterruptedException e) {
407 LOG.info("Interrupted while making the toast");
410 toastsMade.incrementAndGet();
412 amountOfBreadInStock.getAndDecrement();
414 LOG.info("Toaster is out of bread!");
416 notificationProvider.offerNotification(new ToasterOutOfBreadBuilder().build());
419 // Set the Toaster status back to up - this essentially releases the toasting lock.
420 // We can't clear the current toast task nor set the Future result until the
421 // update has been committed so we pass a callback to be notified on completion.
423 setToasterStatusUp(result -> {
424 currentMakeToastTask.set(null);
425 LOG.debug("Toast done");
426 futureResult.set(RpcResultBuilder.success(EMPTY_MAKE_OUTPUT).build());