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