Convert toaster to mdsal APIs
[controller.git] / opendaylight / md-sal / samples / toaster-provider / src / main / java / org / opendaylight / controller / sample / toaster / provider / OpendaylightToaster.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.sample.toaster.provider;
9
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;
15
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;
71
72 public class OpendaylightToaster extends AbstractMXBean
73         implements ToasterService, ToasterProviderRuntimeMXBean, DataTreeChangeListener<Toaster>, AutoCloseable {
74
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();
78
79     private static final Logger LOG = LoggerFactory.getLogger(OpendaylightToaster.class);
80
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");
84
85     private DataBroker dataBroker;
86     private NotificationPublishService notificationProvider;
87     private ListenerRegistration<OpendaylightToaster> dataTreeChangeListenerRegistration;
88
89     private final ExecutorService executor;
90
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<>();
93
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);
98
99     private final ToasterAppConfig toasterAppConfig;
100
101     public OpendaylightToaster() {
102         this(new ToasterAppConfigBuilder().setManufacturer(TOASTER_MANUFACTURER).setModelNumber(TOASTER_MODEL_NUMBER)
103                 .setMaxMakeToastTries(2).build());
104     }
105
106     public OpendaylightToaster(final ToasterAppConfig toasterAppConfig) {
107         super("OpendaylightToaster", "toaster-provider", null);
108         executor = Executors.newFixedThreadPool(1);
109         this.toasterAppConfig = toasterAppConfig;
110     }
111
112     public void setNotificationProvider(final NotificationPublishService notificationPublishService) {
113         this.notificationProvider = notificationPublishService;
114     }
115
116     public void setDataBroker(final DataBroker dataBroker) {
117         this.dataBroker = dataBroker;
118     }
119
120     public void init() {
121         LOG.info("Initializing...");
122
123         Preconditions.checkNotNull(dataBroker, "dataBroker must be set");
124         dataTreeChangeListenerRegistration = dataBroker.registerDataTreeChangeListener(
125                 DataTreeIdentifier.create(CONFIGURATION, TOASTER_IID), this);
126         setToasterStatusUp(null);
127
128         // Register our MXBean.
129         register();
130     }
131
132     /**
133      * Implemented from the AutoCloseable interface.
134      */
135     @Override
136     public void close() {
137         LOG.info("Closing...");
138
139         // Unregister our MXBean.
140         unregister();
141
142         // When we close this service we need to shutdown our executor!
143         executor.shutdown();
144
145         if (dataTreeChangeListenerRegistration != null) {
146             dataTreeChangeListenerRegistration.close();
147         }
148
149         if (dataBroker != null) {
150             WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
151             tx.delete(OPERATIONAL,TOASTER_IID);
152             Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
153                 @Override
154                 public void onSuccess(final CommitInfo result) {
155                     LOG.debug("Successfully deleted the operational Toaster");
156                 }
157
158                 @Override
159                 public void onFailure(final Throwable failure) {
160                     LOG.error("Delete of the operational Toaster failed", failure);
161                 }
162             }, MoreExecutors.directExecutor());
163         }
164     }
165
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();
172     }
173
174     /**
175      * Implemented from the DataTreeChangeListener interface.
176      */
177     @Override
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);
187
188                 Long darkness = newToaster.getDarknessFactor();
189                 if (darkness != null) {
190                     darknessFactor.set(darkness);
191                 }
192             } else if (rootNode.getModificationType() == DELETE) {
193                 LOG.info("onDataTreeChanged - Toaster config with path {} was deleted: old Toaster: {}",
194                         change.getRootPath().getRootIdentifier(), rootNode.getDataBefore());
195             }
196         }
197     }
198
199     /**
200      * RPC call implemented from the ToasterService interface that cancels the current toast, if any.
201      */
202     @Override
203     public ListenableFuture<RpcResult<CancelToastOutput>> cancelToast(final CancelToastInput input) {
204         Future<?> current = currentMakeToastTask.getAndSet(null);
205         if (current != null) {
206             current.cancel(true);
207         }
208
209         // Always return success from the cancel toast call
210         return Futures.immediateFuture(RpcResultBuilder.success(EMPTY_CANCEL_OUTPUT).build());
211     }
212
213     /**
214      * RPC call implemented from the ToasterService interface that attempts to make toast.
215      */
216     @Override
217     public ListenableFuture<RpcResult<MakeToastOutput>> makeToast(final MakeToastInput input) {
218         LOG.info("makeToast: " + input);
219
220         final SettableFuture<RpcResult<MakeToastOutput>> futureResult = SettableFuture.create();
221
222         checkStatusAndMakeToast(input, futureResult, toasterAppConfig.getMaxMakeToastTries());
223
224         return futureResult;
225     }
226
227     private static RpcError makeToasterOutOfBreadError() {
228         return RpcResultBuilder.newError(APPLICATION, "resource-denied", "Toaster is out of bread", "out-of-stock",
229                 null, null);
230     }
231
232     private static RpcError makeToasterInUseError() {
233         return RpcResultBuilder.newWarning(APPLICATION, "in-use", "Toaster is busy", null, null, null);
234     }
235
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
240         // to make toast.
241         final ReadWriteTransaction tx = dataBroker.newReadWriteTransaction();
242         FluentFuture<Optional<Toaster>> readFuture = tx.read(OPERATIONAL, TOASTER_IID);
243
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();
249                 }
250
251                 LOG.debug("Read toaster status: {}", toasterStatus);
252
253                 if (toasterStatus == ToasterStatus.Up) {
254
255                     if (outOfBread()) {
256                         LOG.debug("Toaster is out of bread");
257                         tx.cancel();
258                         return Futures.immediateFailedFuture(
259                                 new TransactionCommitFailedException("", makeToasterOutOfBreadError()));
260                     }
261
262                     LOG.debug("Setting Toaster status to Down");
263
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));
268                     return tx.commit();
269                 }
270
271                 LOG.debug("Oops - already making toast!");
272
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.
276                 tx.cancel();
277                 return Futures.immediateFailedFuture(
278                         new TransactionCommitFailedException("", makeToasterInUseError()));
279             }, MoreExecutors.directExecutor());
280
281         Futures.addCallback(commitFuture, new FutureCallback<CommitInfo>() {
282             @Override
283             public void onSuccess(final CommitInfo result) {
284                 // OK to make toast
285                 currentMakeToastTask.set(executor.submit(new MakeToastTask(input, futureResult)));
286             }
287
288             @Override
289             public void onFailure(final Throwable ex) {
290                 if (ex instanceof OptimisticLockFailedException) {
291
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.
295
296                     if (tries - 1 > 0) {
297                         LOG.debug("Got OptimisticLockFailedException - trying again");
298                         checkStatusAndMakeToast(input, futureResult, tries - 1);
299                     } else {
300                         futureResult.set(RpcResultBuilder.<MakeToastOutput>failed()
301                                 .withError(ErrorType.APPLICATION, ex.getMessage()).build());
302                     }
303                 } else if (ex instanceof TransactionCommitFailedException) {
304                     LOG.debug("Failed to commit Toaster status", ex);
305
306                     // Probably already making toast.
307                     futureResult.set(RpcResultBuilder.<MakeToastOutput>failed()
308                             .withRpcErrors(((TransactionCommitFailedException)ex).getErrorList()).build());
309                 } else {
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());
313                 }
314             }
315         }, MoreExecutors.directExecutor());
316     }
317
318     /**
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.
322      */
323     @Override
324     public ListenableFuture<RpcResult<RestockToasterOutput>> restockToaster(final RestockToasterInput input) {
325         LOG.info("restockToaster: " + input);
326
327         amountOfBreadInStock.set(input.getAmountOfBreadToStock());
328
329         if (amountOfBreadInStock.get() > 0) {
330             ToasterRestocked reStockedNotification = new ToasterRestockedBuilder()
331                     .setAmountOfBread(input.getAmountOfBreadToStock()).build();
332             notificationProvider.offerNotification(reStockedNotification);
333         }
334
335         return Futures.immediateFuture(RpcResultBuilder.success(EMPTY_RESTOCK_OUTPUT).build());
336     }
337
338     /**
339      * JMX RPC call implemented from the ToasterProviderRuntimeMXBean interface.
340      */
341     @Override
342     public void clearToastsMade() {
343         LOG.info("clearToastsMade");
344         toastsMade.set(0);
345     }
346
347     /**
348      * Accesssor method implemented from the ToasterProviderRuntimeMXBean interface.
349      */
350     @Override
351     public Long getToastsMade() {
352         return toastsMade.get();
353     }
354
355     private void setToasterStatusUp(final Function<Boolean, MakeToastOutput> resultCallback) {
356         WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
357         tx.put(OPERATIONAL,TOASTER_IID, buildToaster(ToasterStatus.Up));
358
359         Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
360             @Override
361             public void onSuccess(final CommitInfo result) {
362                 LOG.info("Successfully set ToasterStatus to Up");
363                 notifyCallback(true);
364             }
365
366             @Override
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);
371
372                 notifyCallback(false);
373             }
374
375             void notifyCallback(final boolean result) {
376                 if (resultCallback != null) {
377                     resultCallback.apply(result);
378                 }
379             }
380         }, MoreExecutors.directExecutor());
381     }
382
383     private boolean outOfBread() {
384         return amountOfBreadInStock.get() == 0;
385     }
386
387     private class MakeToastTask implements Callable<Void> {
388
389         final MakeToastInput toastRequest;
390         final SettableFuture<RpcResult<MakeToastOutput>> futureResult;
391
392         MakeToastTask(final MakeToastInput toastRequest,
393             final SettableFuture<RpcResult<MakeToastOutput>> futureResult) {
394             this.toastRequest = toastRequest;
395             this.futureResult = futureResult;
396         }
397
398         @Override
399         public Void call() {
400             try {
401                 // make toast just sleeps for n seconds per doneness level.
402                 Thread.sleep(OpendaylightToaster.this.darknessFactor.get() * toastRequest.getToasterDoneness());
403
404             } catch (InterruptedException e) {
405                 LOG.info("Interrupted while making the toast");
406             }
407
408             toastsMade.incrementAndGet();
409
410             amountOfBreadInStock.getAndDecrement();
411             if (outOfBread()) {
412                 LOG.info("Toaster is out of bread!");
413
414                 notificationProvider.offerNotification(new ToasterOutOfBreadBuilder().build());
415             }
416
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.
420
421             setToasterStatusUp(result -> {
422                 currentMakeToastTask.set(null);
423                 LOG.debug("Toast done");
424                 futureResult.set(RpcResultBuilder.success(EMPTY_MAKE_OUTPUT).build());
425                 return null;
426             });
427
428             return null;
429         }
430     }
431 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.