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