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.controller.md.sal.binding.api.DataObjectModification.ModificationType.DELETE;
11 import static org.opendaylight.controller.md.sal.binding.api.DataObjectModification.ModificationType.WRITE;
12 import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.CONFIGURATION;
13 import static org.opendaylight.controller.md.sal.common.api.data.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.Optional;
18 import com.google.common.base.Preconditions;
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.SettableFuture;
23 import java.util.Collection;
24 import java.util.concurrent.Callable;
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 org.opendaylight.controller.md.sal.binding.api.DataBroker;
31 import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
32 import org.opendaylight.controller.md.sal.binding.api.DataTreeChangeListener;
33 import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
34 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
35 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
36 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
37 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
38 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
39 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
40 import org.opendaylight.controller.md.sal.common.util.jmx.AbstractMXBean;
41 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.DisplayString;
42 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastInput;
43 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.RestockToasterInput;
44 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.Toaster;
45 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.Toaster.ToasterStatus;
46 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterBuilder;
47 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterOutOfBreadBuilder;
48 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterRestocked;
49 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterRestockedBuilder;
50 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterService;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.toaster.app.config.rev160503.ToasterAppConfig;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.toaster.app.config.rev160503.ToasterAppConfigBuilder;
53 import org.opendaylight.yangtools.concepts.ListenerRegistration;
54 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
55 import org.opendaylight.yangtools.yang.common.RpcError;
56 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
57 import org.opendaylight.yangtools.yang.common.RpcResult;
58 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
62 public class OpendaylightToaster extends AbstractMXBean
63 implements ToasterService, ToasterProviderRuntimeMXBean, DataTreeChangeListener<Toaster>, AutoCloseable {
65 private static final Logger LOG = LoggerFactory.getLogger(OpendaylightToaster.class);
67 private static final InstanceIdentifier<Toaster> TOASTER_IID = InstanceIdentifier.builder(Toaster.class).build();
68 private static final DisplayString TOASTER_MANUFACTURER = new DisplayString("Opendaylight");
69 private static final DisplayString TOASTER_MODEL_NUMBER = new DisplayString("Model 1 - Binding Aware");
71 private DataBroker dataBroker;
72 private NotificationPublishService notificationProvider;
73 private ListenerRegistration<OpendaylightToaster> dataTreeChangeListenerRegistration;
75 private final ExecutorService executor;
77 // This holds the Future for the current make toast task and is used to cancel the current toast.
78 private final AtomicReference<Future<?>> currentMakeToastTask = new AtomicReference<>();
80 // Thread safe holders
81 private final AtomicLong amountOfBreadInStock = new AtomicLong(100);
82 private final AtomicLong toastsMade = new AtomicLong(0);
83 private final AtomicLong darknessFactor = new AtomicLong(1000);
85 private final ToasterAppConfig toasterAppConfig;
87 public OpendaylightToaster() {
88 this(new ToasterAppConfigBuilder().setManufacturer(TOASTER_MANUFACTURER).setModelNumber(TOASTER_MODEL_NUMBER)
89 .setMaxMakeToastTries(2).build());
92 public OpendaylightToaster(ToasterAppConfig toasterAppConfig) {
93 super("OpendaylightToaster", "toaster-provider", null);
94 executor = Executors.newFixedThreadPool(1);
95 this.toasterAppConfig = toasterAppConfig;
98 public void setNotificationProvider(final NotificationPublishService notificationPublishService) {
99 this.notificationProvider = notificationPublishService;
102 public void setDataBroker(final DataBroker dataBroker) {
103 this.dataBroker = dataBroker;
107 LOG.info("Initializing...");
109 Preconditions.checkNotNull(dataBroker, "dataBroker must be set");
110 dataTreeChangeListenerRegistration = dataBroker.registerDataTreeChangeListener(
111 new DataTreeIdentifier<>(CONFIGURATION, TOASTER_IID), this);
112 setToasterStatusUp(null);
114 // Register our MXBean.
119 * Implemented from the AutoCloseable interface.
122 public void close() {
123 LOG.info("Closing...");
125 // Unregister our MXBean.
128 // When we close this service we need to shutdown our executor!
131 if (dataTreeChangeListenerRegistration != null) {
132 dataTreeChangeListenerRegistration.close();
135 if (dataBroker != null) {
136 WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
137 tx.delete(OPERATIONAL,TOASTER_IID);
138 Futures.addCallback(tx.submit(), new FutureCallback<Void>() {
140 public void onSuccess(final Void result) {
141 LOG.debug("Successfully deleted the operational Toaster");
145 public void onFailure(final Throwable failure) {
146 LOG.error("Delete of the operational Toaster failed", failure);
152 private Toaster buildToaster(final ToasterStatus status) {
153 // note - we are simulating a device whose manufacture and model are
154 // fixed (embedded) into the hardware.
155 // This is why the manufacture and model number are hardcoded.
156 return new ToasterBuilder().setToasterManufacturer(toasterAppConfig.getManufacturer())
157 .setToasterModelNumber(toasterAppConfig.getModelNumber()).setToasterStatus(status).build();
161 * Implemented from the DataTreeChangeListener interface.
164 public void onDataTreeChanged(Collection<DataTreeModification<Toaster>> changes) {
165 for (DataTreeModification<Toaster> change: changes) {
166 DataObjectModification<Toaster> rootNode = change.getRootNode();
167 if (rootNode.getModificationType() == WRITE) {
168 Toaster oldToaster = rootNode.getDataBefore();
169 Toaster newToaster = rootNode.getDataAfter();
170 LOG.info("onDataTreeChanged - Toaster config with path {} was added or replaced: "
171 + "old Toaster: {}, new Toaster: {}", change.getRootPath().getRootIdentifier(),
172 oldToaster, newToaster);
174 Long darkness = newToaster.getDarknessFactor();
175 if (darkness != null) {
176 darknessFactor.set(darkness);
178 } else if (rootNode.getModificationType() == DELETE) {
179 LOG.info("onDataTreeChanged - Toaster config with path {} was deleted: old Toaster: {}",
180 change.getRootPath().getRootIdentifier(), rootNode.getDataBefore());
186 * RPC call implemented from the ToasterService interface that cancels the current toast, if any.
189 public Future<RpcResult<Void>> cancelToast() {
190 Future<?> current = currentMakeToastTask.getAndSet(null);
191 if (current != null) {
192 current.cancel(true);
195 // Always return success from the cancel toast call
196 return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
200 * RPC call implemented from the ToasterService interface that attempts to make toast.
203 public Future<RpcResult<Void>> makeToast(final MakeToastInput input) {
204 LOG.info("makeToast: " + input);
206 final SettableFuture<RpcResult<Void>> futureResult = SettableFuture.create();
208 checkStatusAndMakeToast(input, futureResult, toasterAppConfig.getMaxMakeToastTries());
213 private RpcError makeToasterOutOfBreadError() {
214 return RpcResultBuilder.newError(APPLICATION, "resource-denied", "Toaster is out of bread", "out-of-stock",
218 private RpcError makeToasterInUseError() {
219 return RpcResultBuilder.newWarning(APPLICATION, "in-use", "Toaster is busy", null, null, null);
222 private void checkStatusAndMakeToast(final MakeToastInput input, final SettableFuture<RpcResult<Void>> futureResult,
224 // Read the ToasterStatus and, if currently Up, try to write the status to Down.
225 // If that succeeds, then we essentially have an exclusive lock and can proceed
227 final ReadWriteTransaction tx = dataBroker.newReadWriteTransaction();
228 ListenableFuture<Optional<Toaster>> readFuture = tx.read(OPERATIONAL, TOASTER_IID);
230 final ListenableFuture<Void> commitFuture =
231 Futures.transformAsync(readFuture, toasterData -> {
232 ToasterStatus toasterStatus = ToasterStatus.Up;
233 if (toasterData.isPresent()) {
234 toasterStatus = toasterData.get().getToasterStatus();
237 LOG.debug("Read toaster status: {}", toasterStatus);
239 if (toasterStatus == ToasterStatus.Up) {
242 LOG.debug("Toaster is out of bread");
243 return Futures.immediateFailedCheckedFuture(
244 new TransactionCommitFailedException("", makeToasterOutOfBreadError()));
247 LOG.debug("Setting Toaster status to Down");
249 // We're not currently making toast - try to update the status to Down
250 // to indicate we're going to make toast. This acts as a lock to prevent
251 // concurrent toasting.
252 tx.put(OPERATIONAL, TOASTER_IID, buildToaster(ToasterStatus.Down));
256 LOG.debug("Oops - already making toast!");
258 // Return an error since we are already making toast. This will get
259 // propagated to the commitFuture below which will interpret the null
260 // TransactionStatus in the RpcResult as an error condition.
261 return Futures.immediateFailedCheckedFuture(
262 new TransactionCommitFailedException("", makeToasterInUseError()));
265 Futures.addCallback(commitFuture, new FutureCallback<Void>() {
267 public void onSuccess(final Void result) {
269 currentMakeToastTask.set(executor.submit(new MakeToastTask(input, futureResult)));
273 public void onFailure(final Throwable ex) {
274 if (ex instanceof OptimisticLockFailedException) {
276 // Another thread is likely trying to make toast simultaneously and updated the
277 // status before us. Try reading the status again - if another make toast is
278 // now in progress, we should get ToasterStatus.Down and fail.
281 LOG.debug("Got OptimisticLockFailedException - trying again");
282 checkStatusAndMakeToast(input, futureResult, tries - 1);
284 futureResult.set(RpcResultBuilder.<Void>failed()
285 .withError(ErrorType.APPLICATION, ex.getMessage()).build());
287 } else if (ex instanceof TransactionCommitFailedException) {
288 LOG.debug("Failed to commit Toaster status", ex);
290 // Probably already making toast.
291 futureResult.set(RpcResultBuilder.<Void>failed()
292 .withRpcErrors(((TransactionCommitFailedException)ex).getErrorList()).build());
294 LOG.debug("Unexpected error committing Toaster status", ex);
295 futureResult.set(RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION,
296 "Unexpected error committing Toaster status", ex).build());
303 * RestConf RPC call implemented from the ToasterService interface.
304 * Restocks the bread for the toaster, resets the toastsMade counter to 0, and sends a
305 * ToasterRestocked notification.
308 public Future<RpcResult<java.lang.Void>> restockToaster(final RestockToasterInput input) {
309 LOG.info("restockToaster: " + input);
311 amountOfBreadInStock.set(input.getAmountOfBreadToStock());
313 if (amountOfBreadInStock.get() > 0) {
314 ToasterRestocked reStockedNotification = new ToasterRestockedBuilder()
315 .setAmountOfBread(input.getAmountOfBreadToStock()).build();
316 notificationProvider.offerNotification(reStockedNotification);
319 return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
323 * JMX RPC call implemented from the ToasterProviderRuntimeMXBean interface.
326 public void clearToastsMade() {
327 LOG.info("clearToastsMade");
332 * Accesssor method implemented from the ToasterProviderRuntimeMXBean interface.
335 public Long getToastsMade() {
336 return toastsMade.get();
339 private void setToasterStatusUp(final Function<Boolean,Void> resultCallback) {
340 WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
341 tx.put(OPERATIONAL,TOASTER_IID, buildToaster(ToasterStatus.Up));
343 Futures.addCallback(tx.submit(), new FutureCallback<Void>() {
345 public void onSuccess(final Void result) {
346 LOG.info("Successfully set ToasterStatus to Up");
347 notifyCallback(true);
351 public void onFailure(final Throwable failure) {
352 // We shouldn't get an OptimisticLockFailedException (or any ex) as no
353 // other component should be updating the operational state.
354 LOG.error("Failed to update toaster status", failure);
356 notifyCallback(false);
359 void notifyCallback(final boolean result) {
360 if (resultCallback != null) {
361 resultCallback.apply(result);
367 private boolean outOfBread() {
368 return amountOfBreadInStock.get() == 0;
371 private class MakeToastTask implements Callable<Void> {
373 final MakeToastInput toastRequest;
374 final SettableFuture<RpcResult<Void>> futureResult;
376 MakeToastTask(final MakeToastInput toastRequest, final SettableFuture<RpcResult<Void>> futureResult) {
377 this.toastRequest = toastRequest;
378 this.futureResult = futureResult;
384 // make toast just sleeps for n seconds per doneness level.
385 Thread.sleep(OpendaylightToaster.this.darknessFactor.get() * toastRequest.getToasterDoneness());
387 } catch (InterruptedException e) {
388 LOG.info("Interrupted while making the toast");
391 toastsMade.incrementAndGet();
393 amountOfBreadInStock.getAndDecrement();
395 LOG.info("Toaster is out of bread!");
397 notificationProvider.offerNotification(new ToasterOutOfBreadBuilder().build());
400 // Set the Toaster status back to up - this essentially releases the toasting lock.
401 // We can't clear the current toast task nor set the Future result until the
402 // update has been committed so we pass a callback to be notified on completion.
404 setToasterStatusUp(result -> {
405 currentMakeToastTask.set(null);
406 LOG.debug("Toast done");
407 futureResult.set(RpcResultBuilder.<Void>success().build());