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.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.ErrorTag;
66 import org.opendaylight.yangtools.yang.common.ErrorType;
67 import org.opendaylight.yangtools.yang.common.RpcError;
68 import org.opendaylight.yangtools.yang.common.RpcResult;
69 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
70 import org.opendaylight.yangtools.yang.common.Uint16;
71 import org.opendaylight.yangtools.yang.common.Uint32;
72 import org.slf4j.Logger;
73 import org.slf4j.LoggerFactory;
75 public class OpendaylightToaster extends AbstractMXBean
76 implements ToasterService, ToasterProviderRuntimeMXBean, DataTreeChangeListener<Toaster>, AutoCloseable {
78 private static final CancelToastOutput EMPTY_CANCEL_OUTPUT = new CancelToastOutputBuilder().build();
79 private static final MakeToastOutput EMPTY_MAKE_OUTPUT = new MakeToastOutputBuilder().build();
80 private static final RestockToasterOutput EMPTY_RESTOCK_OUTPUT = new RestockToasterOutputBuilder().build();
82 private static final Logger LOG = LoggerFactory.getLogger(OpendaylightToaster.class);
84 private static final InstanceIdentifier<Toaster> TOASTER_IID = InstanceIdentifier.builder(Toaster.class).build();
85 private static final DisplayString TOASTER_MANUFACTURER = new DisplayString("Opendaylight");
86 private static final DisplayString TOASTER_MODEL_NUMBER = new DisplayString("Model 1 - Binding Aware");
88 private DataBroker dataBroker;
89 private NotificationPublishService notificationProvider;
90 private ListenerRegistration<OpendaylightToaster> dataTreeChangeListenerRegistration;
92 private final ExecutorService executor;
94 // This holds the Future for the current make toast task and is used to cancel the current toast.
95 private final AtomicReference<Future<?>> currentMakeToastTask = new AtomicReference<>();
97 // Thread safe holders
98 private final AtomicLong amountOfBreadInStock = new AtomicLong(100);
99 private final AtomicLong toastsMade = new AtomicLong(0);
100 private final AtomicLong darknessFactor = new AtomicLong(1000);
102 private final ToasterAppConfig toasterAppConfig;
104 public OpendaylightToaster() {
105 this(new ToasterAppConfigBuilder().setManufacturer(TOASTER_MANUFACTURER).setModelNumber(TOASTER_MODEL_NUMBER)
106 .setMaxMakeToastTries(Uint16.valueOf(2)).build());
109 public OpendaylightToaster(final ToasterAppConfig toasterAppConfig) {
110 super("OpendaylightToaster", "toaster-provider", null);
111 executor = Executors.newFixedThreadPool(1);
112 this.toasterAppConfig = toasterAppConfig;
115 public void setNotificationProvider(final NotificationPublishService notificationPublishService) {
116 notificationProvider = notificationPublishService;
119 public void setDataBroker(final DataBroker dataBroker) {
120 this.dataBroker = dataBroker;
124 LOG.info("Initializing...");
126 dataTreeChangeListenerRegistration = requireNonNull(dataBroker, "dataBroker must be set")
127 .registerDataTreeChangeListener(DataTreeIdentifier.create(CONFIGURATION, TOASTER_IID), this);
128 setToasterStatusUp(null);
130 // Register our MXBean.
135 * Implemented from the AutoCloseable interface.
138 public void close() {
139 LOG.info("Closing...");
141 // Unregister our MXBean.
144 // When we close this service we need to shutdown our executor!
147 if (dataTreeChangeListenerRegistration != null) {
148 dataTreeChangeListenerRegistration.close();
151 if (dataBroker != null) {
152 WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
153 tx.delete(OPERATIONAL,TOASTER_IID);
154 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
156 public void onSuccess(final CommitInfo result) {
157 LOG.debug("Successfully deleted the operational Toaster");
161 public void onFailure(final Throwable failure) {
162 LOG.error("Delete of the operational Toaster failed", failure);
164 }, MoreExecutors.directExecutor());
168 private Toaster buildToaster(final ToasterStatus status) {
169 // note - we are simulating a device whose manufacture and model are
170 // fixed (embedded) into the hardware.
171 // This is why the manufacture and model number are hardcoded.
172 return new ToasterBuilder().setToasterManufacturer(toasterAppConfig.getManufacturer())
173 .setToasterModelNumber(toasterAppConfig.getModelNumber()).setToasterStatus(status).build();
177 * Implemented from the DataTreeChangeListener interface.
180 public void onDataTreeChanged(final Collection<DataTreeModification<Toaster>> changes) {
181 for (DataTreeModification<Toaster> change: changes) {
182 DataObjectModification<Toaster> rootNode = change.getRootNode();
183 if (rootNode.getModificationType() == WRITE) {
184 Toaster oldToaster = rootNode.getDataBefore();
185 Toaster newToaster = rootNode.getDataAfter();
186 LOG.info("onDataTreeChanged - Toaster config with path {} was added or replaced: "
187 + "old Toaster: {}, new Toaster: {}", change.getRootPath().getRootIdentifier(),
188 oldToaster, newToaster);
190 Uint32 darkness = newToaster.getDarknessFactor();
191 if (darkness != null) {
192 darknessFactor.set(darkness.toJava());
194 } else if (rootNode.getModificationType() == DELETE) {
195 LOG.info("onDataTreeChanged - Toaster config with path {} was deleted: old Toaster: {}",
196 change.getRootPath().getRootIdentifier(), rootNode.getDataBefore());
202 * RPC call implemented from the ToasterService interface that cancels the current toast, if any.
205 public ListenableFuture<RpcResult<CancelToastOutput>> cancelToast(final CancelToastInput input) {
206 Future<?> current = currentMakeToastTask.getAndSet(null);
207 if (current != null) {
208 current.cancel(true);
211 // Always return success from the cancel toast call
212 return Futures.immediateFuture(RpcResultBuilder.success(EMPTY_CANCEL_OUTPUT).build());
216 * RPC call implemented from the ToasterService interface that attempts to make toast.
219 public ListenableFuture<RpcResult<MakeToastOutput>> makeToast(final MakeToastInput input) {
220 LOG.info("makeToast: {}", input);
222 final SettableFuture<RpcResult<MakeToastOutput>> futureResult = SettableFuture.create();
224 checkStatusAndMakeToast(input, futureResult, toasterAppConfig.getMaxMakeToastTries().toJava());
229 private static RpcError makeToasterOutOfBreadError() {
230 return RpcResultBuilder.newError(APPLICATION, ErrorTag.RESOURCE_DENIED, "Toaster is out of bread",
231 "out-of-stock", null, null);
234 private static RpcError makeToasterInUseError() {
235 return RpcResultBuilder.newWarning(APPLICATION, ErrorTag.IN_USE, "Toaster is busy", null, null, null);
238 private void checkStatusAndMakeToast(final MakeToastInput input,
239 final SettableFuture<RpcResult<MakeToastOutput>> futureResult, final int tries) {
240 // Read the ToasterStatus and, if currently Up, try to write the status to Down.
241 // If that succeeds, then we essentially have an exclusive lock and can proceed
243 final ReadWriteTransaction tx = dataBroker.newReadWriteTransaction();
244 FluentFuture<Optional<Toaster>> readFuture = tx.read(OPERATIONAL, TOASTER_IID);
246 final ListenableFuture<? extends CommitInfo> commitFuture =
247 Futures.transformAsync(readFuture, toasterData -> {
248 ToasterStatus toasterStatus = ToasterStatus.Up;
249 if (toasterData.isPresent()) {
250 toasterStatus = toasterData.get().getToasterStatus();
253 LOG.debug("Read toaster status: {}", toasterStatus);
255 if (toasterStatus == ToasterStatus.Up) {
258 LOG.debug("Toaster is out of bread");
260 return Futures.immediateFailedFuture(
261 new TransactionCommitFailedException("", makeToasterOutOfBreadError()));
264 LOG.debug("Setting Toaster status to Down");
266 // We're not currently making toast - try to update the status to Down
267 // to indicate we're going to make toast. This acts as a lock to prevent
268 // concurrent toasting.
269 tx.put(OPERATIONAL, TOASTER_IID, buildToaster(ToasterStatus.Down));
273 LOG.debug("Oops - already making toast!");
275 // Return an error since we are already making toast. This will get
276 // propagated to the commitFuture below which will interpret the null
277 // TransactionStatus in the RpcResult as an error condition.
279 return Futures.immediateFailedFuture(
280 new TransactionCommitFailedException("", makeToasterInUseError()));
281 }, MoreExecutors.directExecutor());
283 Futures.addCallback(commitFuture, new FutureCallback<CommitInfo>() {
285 public void onSuccess(final CommitInfo result) {
287 currentMakeToastTask.set(executor.submit(new MakeToastTask(input, futureResult)));
291 public void onFailure(final Throwable ex) {
292 if (ex instanceof OptimisticLockFailedException) {
294 // Another thread is likely trying to make toast simultaneously and updated the
295 // status before us. Try reading the status again - if another make toast is
296 // now in progress, we should get ToasterStatus.Down and fail.
299 LOG.debug("Got OptimisticLockFailedException - trying again");
300 checkStatusAndMakeToast(input, futureResult, tries - 1);
302 futureResult.set(RpcResultBuilder.<MakeToastOutput>failed()
303 .withError(ErrorType.APPLICATION, ex.getMessage()).build());
305 } else if (ex instanceof TransactionCommitFailedException) {
306 LOG.debug("Failed to commit Toaster status", ex);
308 // Probably already making toast.
309 futureResult.set(RpcResultBuilder.<MakeToastOutput>failed()
310 .withRpcErrors(((TransactionCommitFailedException)ex).getErrorList()).build());
312 LOG.debug("Unexpected error committing Toaster status", ex);
313 futureResult.set(RpcResultBuilder.<MakeToastOutput>failed().withError(ErrorType.APPLICATION,
314 "Unexpected error committing Toaster status", ex).build());
317 }, MoreExecutors.directExecutor());
321 * RestConf RPC call implemented from the ToasterService interface.
322 * Restocks the bread for the toaster, resets the toastsMade counter to 0, and sends a
323 * ToasterRestocked notification.
326 public ListenableFuture<RpcResult<RestockToasterOutput>> restockToaster(final RestockToasterInput input) {
327 LOG.info("restockToaster: {}", input);
329 amountOfBreadInStock.set(input.getAmountOfBreadToStock().toJava());
331 if (amountOfBreadInStock.get() > 0) {
332 ToasterRestocked reStockedNotification = new ToasterRestockedBuilder()
333 .setAmountOfBread(input.getAmountOfBreadToStock()).build();
334 notificationProvider.offerNotification(reStockedNotification);
337 return Futures.immediateFuture(RpcResultBuilder.success(EMPTY_RESTOCK_OUTPUT).build());
341 * JMX RPC call implemented from the ToasterProviderRuntimeMXBean interface.
344 public void clearToastsMade() {
345 LOG.info("clearToastsMade");
350 * Accesssor method implemented from the ToasterProviderRuntimeMXBean interface.
353 public Long getToastsMade() {
354 return toastsMade.get();
357 private void setToasterStatusUp(final Function<Boolean, MakeToastOutput> resultCallback) {
358 WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
359 tx.put(OPERATIONAL,TOASTER_IID, buildToaster(ToasterStatus.Up));
361 Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
363 public void onSuccess(final CommitInfo result) {
364 LOG.info("Successfully set ToasterStatus to Up");
365 notifyCallback(true);
369 public void onFailure(final Throwable failure) {
370 // We shouldn't get an OptimisticLockFailedException (or any ex) as no
371 // other component should be updating the operational state.
372 LOG.error("Failed to update toaster status", failure);
374 notifyCallback(false);
377 void notifyCallback(final boolean result) {
378 if (resultCallback != null) {
379 resultCallback.apply(result);
382 }, MoreExecutors.directExecutor());
385 private boolean outOfBread() {
386 return amountOfBreadInStock.get() == 0;
389 private class MakeToastTask implements Callable<Void> {
391 final MakeToastInput toastRequest;
392 final SettableFuture<RpcResult<MakeToastOutput>> futureResult;
394 MakeToastTask(final MakeToastInput toastRequest,
395 final SettableFuture<RpcResult<MakeToastOutput>> futureResult) {
396 this.toastRequest = toastRequest;
397 this.futureResult = futureResult;
403 // make toast just sleeps for n seconds per doneness level.
404 Thread.sleep(darknessFactor.get()
405 * toastRequest.getToasterDoneness().toJava());
407 } catch (InterruptedException e) {
408 LOG.info("Interrupted while making the toast");
411 toastsMade.incrementAndGet();
413 amountOfBreadInStock.getAndDecrement();
415 LOG.info("Toaster is out of bread!");
417 notificationProvider.offerNotification(new ToasterOutOfBreadBuilder().build());
420 // Set the Toaster status back to up - this essentially releases the toasting lock.
421 // We can't clear the current toast task nor set the Future result until the
422 // update has been committed so we pass a callback to be notified on completion.
424 setToasterStatusUp(result -> {
425 currentMakeToastTask.set(null);
426 LOG.debug("Toast done");
427 futureResult.set(RpcResultBuilder.success(EMPTY_MAKE_OUTPUT).build());