Bump to odlparent 2.0.0
[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.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;
15
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;
61
62 public class OpendaylightToaster extends AbstractMXBean
63         implements ToasterService, ToasterProviderRuntimeMXBean, DataTreeChangeListener<Toaster>, AutoCloseable {
64
65     private static final Logger LOG = LoggerFactory.getLogger(OpendaylightToaster.class);
66
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");
70
71     private DataBroker dataBroker;
72     private NotificationPublishService notificationProvider;
73     private ListenerRegistration<OpendaylightToaster> dataTreeChangeListenerRegistration;
74
75     private final ExecutorService executor;
76
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<>();
79
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);
84
85     private final ToasterAppConfig toasterAppConfig;
86
87     public OpendaylightToaster() {
88         this(new ToasterAppConfigBuilder().setManufacturer(TOASTER_MANUFACTURER).setModelNumber(TOASTER_MODEL_NUMBER)
89                 .setMaxMakeToastTries(2).build());
90     }
91
92     public OpendaylightToaster(ToasterAppConfig toasterAppConfig) {
93         super("OpendaylightToaster", "toaster-provider", null);
94         executor = Executors.newFixedThreadPool(1);
95         this.toasterAppConfig = toasterAppConfig;
96     }
97
98     public void setNotificationProvider(final NotificationPublishService notificationPublishService) {
99         this.notificationProvider = notificationPublishService;
100     }
101
102     public void setDataBroker(final DataBroker dataBroker) {
103         this.dataBroker = dataBroker;
104     }
105
106     public void init() {
107         LOG.info("Initializing...");
108
109         Preconditions.checkNotNull(dataBroker, "dataBroker must be set");
110         dataTreeChangeListenerRegistration = dataBroker.registerDataTreeChangeListener(
111                 new DataTreeIdentifier<>(CONFIGURATION, TOASTER_IID), this);
112         setToasterStatusUp(null);
113
114         // Register our MXBean.
115         register();
116     }
117
118     /**
119      * Implemented from the AutoCloseable interface.
120      */
121     @Override
122     public void close() {
123         LOG.info("Closing...");
124
125         // Unregister our MXBean.
126         unregister();
127
128         // When we close this service we need to shutdown our executor!
129         executor.shutdown();
130
131         if (dataTreeChangeListenerRegistration != null) {
132             dataTreeChangeListenerRegistration.close();
133         }
134
135         if (dataBroker != null) {
136             WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
137             tx.delete(OPERATIONAL,TOASTER_IID);
138             Futures.addCallback(tx.submit(), new FutureCallback<Void>() {
139                 @Override
140                 public void onSuccess(final Void result) {
141                     LOG.debug("Successfully deleted the operational Toaster");
142                 }
143
144                 @Override
145                 public void onFailure(final Throwable failure) {
146                     LOG.error("Delete of the operational Toaster failed", failure);
147                 }
148             });
149         }
150     }
151
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();
158     }
159
160     /**
161      * Implemented from the DataTreeChangeListener interface.
162      */
163     @Override
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);
173
174                 Long darkness = newToaster.getDarknessFactor();
175                 if (darkness != null) {
176                     darknessFactor.set(darkness);
177                 }
178             } else if (rootNode.getModificationType() == DELETE) {
179                 LOG.info("onDataTreeChanged - Toaster config with path {} was deleted: old Toaster: {}",
180                         change.getRootPath().getRootIdentifier(), rootNode.getDataBefore());
181             }
182         }
183     }
184
185     /**
186      * RPC call implemented from the ToasterService interface that cancels the current toast, if any.
187      */
188     @Override
189     public Future<RpcResult<Void>> cancelToast() {
190         Future<?> current = currentMakeToastTask.getAndSet(null);
191         if (current != null) {
192             current.cancel(true);
193         }
194
195         // Always return success from the cancel toast call
196         return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
197     }
198
199     /**
200      * RPC call implemented from the ToasterService interface that attempts to make toast.
201      */
202     @Override
203     public Future<RpcResult<Void>> makeToast(final MakeToastInput input) {
204         LOG.info("makeToast: " + input);
205
206         final SettableFuture<RpcResult<Void>> futureResult = SettableFuture.create();
207
208         checkStatusAndMakeToast(input, futureResult, toasterAppConfig.getMaxMakeToastTries());
209
210         return futureResult;
211     }
212
213     private RpcError makeToasterOutOfBreadError() {
214         return RpcResultBuilder.newError(APPLICATION, "resource-denied", "Toaster is out of bread", "out-of-stock",
215                 null, null);
216     }
217
218     private RpcError makeToasterInUseError() {
219         return RpcResultBuilder.newWarning(APPLICATION, "in-use", "Toaster is busy", null, null, null);
220     }
221
222     private void checkStatusAndMakeToast(final MakeToastInput input, final SettableFuture<RpcResult<Void>> futureResult,
223             final int tries) {
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
226         // to make toast.
227         final ReadWriteTransaction tx = dataBroker.newReadWriteTransaction();
228         ListenableFuture<Optional<Toaster>> readFuture = tx.read(OPERATIONAL, TOASTER_IID);
229
230         final ListenableFuture<Void> commitFuture =
231             Futures.transformAsync(readFuture, toasterData -> {
232                 ToasterStatus toasterStatus = ToasterStatus.Up;
233                 if (toasterData.isPresent()) {
234                     toasterStatus = toasterData.get().getToasterStatus();
235                 }
236
237                 LOG.debug("Read toaster status: {}", toasterStatus);
238
239                 if (toasterStatus == ToasterStatus.Up) {
240
241                     if (outOfBread()) {
242                         LOG.debug("Toaster is out of bread");
243                         return Futures.immediateFailedCheckedFuture(
244                                 new TransactionCommitFailedException("", makeToasterOutOfBreadError()));
245                     }
246
247                     LOG.debug("Setting Toaster status to Down");
248
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));
253                     return tx.submit();
254                 }
255
256                 LOG.debug("Oops - already making toast!");
257
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()));
263             });
264
265         Futures.addCallback(commitFuture, new FutureCallback<Void>() {
266             @Override
267             public void onSuccess(final Void result) {
268                 // OK to make toast
269                 currentMakeToastTask.set(executor.submit(new MakeToastTask(input, futureResult)));
270             }
271
272             @Override
273             public void onFailure(final Throwable ex) {
274                 if (ex instanceof OptimisticLockFailedException) {
275
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.
279
280                     if (tries - 1 > 0) {
281                         LOG.debug("Got OptimisticLockFailedException - trying again");
282                         checkStatusAndMakeToast(input, futureResult, tries - 1);
283                     } else {
284                         futureResult.set(RpcResultBuilder.<Void>failed()
285                                 .withError(ErrorType.APPLICATION, ex.getMessage()).build());
286                     }
287                 } else if (ex instanceof TransactionCommitFailedException) {
288                     LOG.debug("Failed to commit Toaster status", ex);
289
290                     // Probably already making toast.
291                     futureResult.set(RpcResultBuilder.<Void>failed()
292                             .withRpcErrors(((TransactionCommitFailedException)ex).getErrorList()).build());
293                 } else {
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());
297                 }
298             }
299         });
300     }
301
302     /**
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.
306      */
307     @Override
308     public Future<RpcResult<java.lang.Void>> restockToaster(final RestockToasterInput input) {
309         LOG.info("restockToaster: " + input);
310
311         amountOfBreadInStock.set(input.getAmountOfBreadToStock());
312
313         if (amountOfBreadInStock.get() > 0) {
314             ToasterRestocked reStockedNotification = new ToasterRestockedBuilder()
315                     .setAmountOfBread(input.getAmountOfBreadToStock()).build();
316             notificationProvider.offerNotification(reStockedNotification);
317         }
318
319         return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
320     }
321
322     /**
323      * JMX RPC call implemented from the ToasterProviderRuntimeMXBean interface.
324      */
325     @Override
326     public void clearToastsMade() {
327         LOG.info("clearToastsMade");
328         toastsMade.set(0);
329     }
330
331     /**
332      * Accesssor method implemented from the ToasterProviderRuntimeMXBean interface.
333      */
334     @Override
335     public Long getToastsMade() {
336         return toastsMade.get();
337     }
338
339     private void setToasterStatusUp(final Function<Boolean,Void> resultCallback) {
340         WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
341         tx.put(OPERATIONAL,TOASTER_IID, buildToaster(ToasterStatus.Up));
342
343         Futures.addCallback(tx.submit(), new FutureCallback<Void>() {
344             @Override
345             public void onSuccess(final Void result) {
346                 LOG.info("Successfully set ToasterStatus to Up");
347                 notifyCallback(true);
348             }
349
350             @Override
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);
355
356                 notifyCallback(false);
357             }
358
359             void notifyCallback(final boolean result) {
360                 if (resultCallback != null) {
361                     resultCallback.apply(result);
362                 }
363             }
364         });
365     }
366
367     private boolean outOfBread() {
368         return amountOfBreadInStock.get() == 0;
369     }
370
371     private class MakeToastTask implements Callable<Void> {
372
373         final MakeToastInput toastRequest;
374         final SettableFuture<RpcResult<Void>> futureResult;
375
376         MakeToastTask(final MakeToastInput toastRequest, final SettableFuture<RpcResult<Void>> futureResult) {
377             this.toastRequest = toastRequest;
378             this.futureResult = futureResult;
379         }
380
381         @Override
382         public Void call() {
383             try {
384                 // make toast just sleeps for n seconds per doneness level.
385                 Thread.sleep(OpendaylightToaster.this.darknessFactor.get() * toastRequest.getToasterDoneness());
386
387             } catch (InterruptedException e) {
388                 LOG.info("Interrupted while making the toast");
389             }
390
391             toastsMade.incrementAndGet();
392
393             amountOfBreadInStock.getAndDecrement();
394             if (outOfBread()) {
395                 LOG.info("Toaster is out of bread!");
396
397                 notificationProvider.offerNotification(new ToasterOutOfBreadBuilder().build());
398             }
399
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.
403
404             setToasterStatusUp(result -> {
405                 currentMakeToastTask.set(null);
406                 LOG.debug("Toast done");
407                 futureResult.set(RpcResultBuilder.<Void>success().build());
408                 return null;
409             });
410
411             return null;
412         }
413     }
414 }