Add explicit init/close methods to OpendaylightToaster
[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.AsyncFunction;
20 import com.google.common.util.concurrent.FutureCallback;
21 import com.google.common.util.concurrent.Futures;
22 import com.google.common.util.concurrent.ListenableFuture;
23 import com.google.common.util.concurrent.SettableFuture;
24 import java.util.Collection;
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 org.opendaylight.controller.md.sal.binding.api.DataBroker;
32 import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
33 import org.opendaylight.controller.md.sal.binding.api.DataTreeChangeListener;
34 import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
35 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
36 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
37 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
38 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
39 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
40 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
41 import org.opendaylight.controller.md.sal.common.util.jmx.AbstractMXBean;
42 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.DisplayString;
43 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastInput;
44 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.RestockToasterInput;
45 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.Toaster;
46 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.Toaster.ToasterStatus;
47 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterBuilder;
48 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterOutOfBreadBuilder;
49 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterRestocked;
50 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterRestockedBuilder;
51 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterService;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.toaster.app.config.rev160503.ToasterAppConfig;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.toaster.app.config.rev160503.ToasterAppConfigBuilder;
54 import org.opendaylight.yangtools.concepts.ListenerRegistration;
55 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
56 import org.opendaylight.yangtools.yang.common.RpcError;
57 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
58 import org.opendaylight.yangtools.yang.common.RpcResult;
59 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
62
63 public class OpendaylightToaster extends AbstractMXBean
64         implements ToasterService, ToasterProviderRuntimeMXBean, DataTreeChangeListener<Toaster>, AutoCloseable {
65
66     private static final Logger LOG = LoggerFactory.getLogger(OpendaylightToaster.class);
67
68     private static final InstanceIdentifier<Toaster> TOASTER_IID = InstanceIdentifier.builder(Toaster.class).build();
69     private static final DisplayString TOASTER_MANUFACTURER = new DisplayString("Opendaylight");
70     private static final DisplayString TOASTER_MODEL_NUMBER = new DisplayString("Model 1 - Binding Aware");
71
72     private DataBroker dataBroker;
73     private NotificationPublishService notificationProvider;
74     private ListenerRegistration<OpendaylightToaster> dataTreeChangeListenerRegistration;
75
76     private final ExecutorService executor;
77
78     // This holds the Future for the current make toast task and is used to cancel the current toast.
79     private final AtomicReference<Future<?>> currentMakeToastTask = new AtomicReference<>();
80
81     // Thread safe holders
82     private final AtomicLong amountOfBreadInStock = new AtomicLong(100);
83     private final AtomicLong toastsMade = new AtomicLong(0);
84     private final AtomicLong darknessFactor = new AtomicLong(1000);
85
86     private final ToasterAppConfig toasterAppConfig;
87
88     public OpendaylightToaster() {
89         this(new ToasterAppConfigBuilder().setManufacturer(TOASTER_MANUFACTURER).setModelNumber(TOASTER_MODEL_NUMBER)
90                 .setMaxMakeToastTries(2).build());
91     }
92
93     public OpendaylightToaster(ToasterAppConfig toasterAppConfig) {
94         super("OpendaylightToaster", "toaster-provider", null);
95         executor = Executors.newFixedThreadPool(1);
96         this.toasterAppConfig = toasterAppConfig;
97     }
98
99     public void setNotificationProvider(final NotificationPublishService notificationPublishService) {
100         this.notificationProvider = notificationPublishService;
101     }
102
103     public void setDataBroker(final DataBroker dataBroker) {
104         this.dataBroker = dataBroker;
105     }
106
107     public void init() {
108         LOG.info("Initializing...");
109
110         Preconditions.checkNotNull(dataBroker, "dataBroker must be set");
111         dataTreeChangeListenerRegistration = dataBroker.registerDataTreeChangeListener(
112                 new DataTreeIdentifier<>(CONFIGURATION, TOASTER_IID), this);
113         setToasterStatusUp(null);
114
115         // Register our MXBean.
116         register();
117     }
118
119     /**
120      * Implemented from the AutoCloseable interface.
121      */
122     @Override
123     public void close() {
124         LOG.info("Closing...");
125
126         // Unregister our MXBean.
127         unregister();
128
129         // When we close this service we need to shutdown our executor!
130         executor.shutdown();
131
132         if (dataTreeChangeListenerRegistration != null) {
133             dataTreeChangeListenerRegistration.close();
134         }
135
136         if (dataBroker != null) {
137             WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
138             tx.delete(OPERATIONAL,TOASTER_IID);
139             Futures.addCallback(tx.submit(), new FutureCallback<Void>() {
140                 @Override
141                 public void onSuccess(final Void result) {
142                     LOG.debug("Successfully deleted the operational Toaster");
143                 }
144
145                 @Override
146                 public void onFailure(final Throwable failure) {
147                     LOG.error("Delete of the operational Toaster failed", failure);
148                 }
149             });
150         }
151     }
152
153     private Toaster buildToaster(final ToasterStatus status) {
154         // note - we are simulating a device whose manufacture and model are
155         // fixed (embedded) into the hardware.
156         // This is why the manufacture and model number are hardcoded.
157         return new ToasterBuilder().setToasterManufacturer(toasterAppConfig.getManufacturer())
158                 .setToasterModelNumber(toasterAppConfig.getModelNumber()).setToasterStatus(status).build();
159     }
160
161     /**
162      * Implemented from the DataTreeChangeListener interface.
163      */
164     @Override
165     public void onDataTreeChanged(Collection<DataTreeModification<Toaster>> changes) {
166         for (DataTreeModification<Toaster> change: changes) {
167             DataObjectModification<Toaster> rootNode = change.getRootNode();
168             if (rootNode.getModificationType() == WRITE) {
169                 Toaster oldToaster = rootNode.getDataBefore();
170                 Toaster newToaster = rootNode.getDataAfter();
171                 LOG.info("onDataTreeChanged - Toaster config with path {} was added or replaced: "
172                         + "old Toaster: {}, new Toaster: {}", change.getRootPath().getRootIdentifier(),
173                         oldToaster, newToaster);
174
175                 Long darkness = newToaster.getDarknessFactor();
176                 if (darkness != null) {
177                     darknessFactor.set(darkness);
178                 }
179             } else if (rootNode.getModificationType() == DELETE) {
180                 LOG.info("onDataTreeChanged - Toaster config with path {} was deleted: old Toaster: {}",
181                         change.getRootPath().getRootIdentifier(), rootNode.getDataBefore());
182             }
183         }
184     }
185
186     /**
187      * RPC call implemented from the ToasterService interface that cancels the current toast, if any.
188      */
189     @Override
190     public Future<RpcResult<Void>> cancelToast() {
191         Future<?> current = currentMakeToastTask.getAndSet(null);
192         if (current != null) {
193             current.cancel(true);
194         }
195
196         // Always return success from the cancel toast call
197         return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
198     }
199
200     /**
201      * RPC call implemented from the ToasterService interface that attempts to make toast.
202      */
203     @Override
204     public Future<RpcResult<Void>> makeToast(final MakeToastInput input) {
205         LOG.info("makeToast: " + input);
206
207         final SettableFuture<RpcResult<Void>> futureResult = SettableFuture.create();
208
209         checkStatusAndMakeToast(input, futureResult, toasterAppConfig.getMaxMakeToastTries());
210
211         return futureResult;
212     }
213
214     private RpcError makeToasterOutOfBreadError() {
215         return RpcResultBuilder.newError(APPLICATION, "resource-denied", "Toaster is out of bread", "out-of-stock",
216                 null, null);
217     }
218
219     private RpcError makeToasterInUseError() {
220         return RpcResultBuilder.newWarning(APPLICATION, "in-use", "Toaster is busy", null, null, null);
221     }
222
223     private void checkStatusAndMakeToast(final MakeToastInput input, final SettableFuture<RpcResult<Void>> futureResult,
224             final int tries) {
225         // Read the ToasterStatus and, if currently Up, try to write the status to Down.
226         // If that succeeds, then we essentially have an exclusive lock and can proceed
227         // to make toast.
228         final ReadWriteTransaction tx = dataBroker.newReadWriteTransaction();
229         ListenableFuture<Optional<Toaster>> readFuture = tx.read(OPERATIONAL, TOASTER_IID);
230
231         final ListenableFuture<Void> commitFuture =
232             Futures.transform(readFuture, (AsyncFunction<Optional<Toaster>, Void>) toasterData -> {
233                 ToasterStatus toasterStatus = ToasterStatus.Up;
234                 if (toasterData.isPresent()) {
235                     toasterStatus = toasterData.get().getToasterStatus();
236                 }
237
238                 LOG.debug("Read toaster status: {}", toasterStatus);
239
240                 if (toasterStatus == ToasterStatus.Up) {
241
242                     if (outOfBread()) {
243                         LOG.debug("Toaster is out of bread");
244                         return Futures.immediateFailedCheckedFuture(
245                                 new TransactionCommitFailedException("", makeToasterOutOfBreadError()));
246                     }
247
248                     LOG.debug("Setting Toaster status to Down");
249
250                     // We're not currently making toast - try to update the status to Down
251                     // to indicate we're going to make toast. This acts as a lock to prevent
252                     // concurrent toasting.
253                     tx.put(OPERATIONAL, TOASTER_IID, buildToaster(ToasterStatus.Down));
254                     return tx.submit();
255                 }
256
257                 LOG.debug("Oops - already making toast!");
258
259                 // Return an error since we are already making toast. This will get
260                 // propagated to the commitFuture below which will interpret the null
261                 // TransactionStatus in the RpcResult as an error condition.
262                 return Futures.immediateFailedCheckedFuture(
263                         new TransactionCommitFailedException("", makeToasterInUseError()));
264             });
265
266         Futures.addCallback(commitFuture, new FutureCallback<Void>() {
267             @Override
268             public void onSuccess(final Void result) {
269                 // OK to make toast
270                 currentMakeToastTask.set(executor.submit(new MakeToastTask(input, futureResult)));
271             }
272
273             @Override
274             public void onFailure(final Throwable ex) {
275                 if (ex instanceof OptimisticLockFailedException) {
276
277                     // Another thread is likely trying to make toast simultaneously and updated the
278                     // status before us. Try reading the status again - if another make toast is
279                     // now in progress, we should get ToasterStatus.Down and fail.
280
281                     if (tries - 1 > 0) {
282                         LOG.debug("Got OptimisticLockFailedException - trying again");
283                         checkStatusAndMakeToast(input, futureResult, tries - 1);
284                     } else {
285                         futureResult.set(RpcResultBuilder.<Void>failed()
286                                 .withError(ErrorType.APPLICATION, ex.getMessage()).build());
287                     }
288                 } else if (ex instanceof TransactionCommitFailedException) {
289                     LOG.debug("Failed to commit Toaster status", ex);
290
291                     // Probably already making toast.
292                     futureResult.set(RpcResultBuilder.<Void>failed()
293                             .withRpcErrors(((TransactionCommitFailedException)ex).getErrorList()).build());
294                 } else {
295                     LOG.debug("Unexpected error committing Toaster status", ex);
296                     futureResult.set(RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION,
297                             "Unexpected error committing Toaster status", ex).build());
298                 }
299             }
300         });
301     }
302
303     /**
304      * RestConf RPC call implemented from the ToasterService interface.
305      * Restocks the bread for the toaster, resets the toastsMade counter to 0, and sends a
306      * ToasterRestocked notification.
307      */
308     @Override
309     public Future<RpcResult<java.lang.Void>> restockToaster(final RestockToasterInput input) {
310         LOG.info("restockToaster: " + input);
311
312         amountOfBreadInStock.set(input.getAmountOfBreadToStock());
313
314         if (amountOfBreadInStock.get() > 0) {
315             ToasterRestocked reStockedNotification = new ToasterRestockedBuilder()
316                     .setAmountOfBread(input.getAmountOfBreadToStock()).build();
317             notificationProvider.offerNotification(reStockedNotification);
318         }
319
320         return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
321     }
322
323     /**
324      * JMX RPC call implemented from the ToasterProviderRuntimeMXBean interface.
325      */
326     @Override
327     public void clearToastsMade() {
328         LOG.info("clearToastsMade");
329         toastsMade.set(0);
330     }
331
332     /**
333      * Accesssor method implemented from the ToasterProviderRuntimeMXBean interface.
334      */
335     @Override
336     public Long getToastsMade() {
337         return toastsMade.get();
338     }
339
340     private void setToasterStatusUp(final Function<Boolean,Void> resultCallback) {
341         WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
342         tx.put(OPERATIONAL,TOASTER_IID, buildToaster(ToasterStatus.Up));
343
344         Futures.addCallback(tx.submit(), new FutureCallback<Void>() {
345             @Override
346             public void onSuccess(final Void result) {
347                 LOG.info("Successfully set ToasterStatus to Up");
348                 notifyCallback(true);
349             }
350
351             @Override
352             public void onFailure(final Throwable failure) {
353                 // We shouldn't get an OptimisticLockFailedException (or any ex) as no
354                 // other component should be updating the operational state.
355                 LOG.error("Failed to update toaster status", failure);
356
357                 notifyCallback(false);
358             }
359
360             void notifyCallback(final boolean result) {
361                 if (resultCallback != null) {
362                     resultCallback.apply(result);
363                 }
364             }
365         });
366     }
367
368     private boolean outOfBread() {
369         return amountOfBreadInStock.get() == 0;
370     }
371
372     private class MakeToastTask implements Callable<Void> {
373
374         final MakeToastInput toastRequest;
375         final SettableFuture<RpcResult<Void>> futureResult;
376
377         MakeToastTask(final MakeToastInput toastRequest, final SettableFuture<RpcResult<Void>> futureResult) {
378             this.toastRequest = toastRequest;
379             this.futureResult = futureResult;
380         }
381
382         @Override
383         public Void call() {
384             try {
385                 // make toast just sleeps for n seconds per doneness level.
386                 Thread.sleep(OpendaylightToaster.this.darknessFactor.get() * toastRequest.getToasterDoneness());
387
388             } catch (InterruptedException e) {
389                 LOG.info("Interrupted while making the toast");
390             }
391
392             toastsMade.incrementAndGet();
393
394             amountOfBreadInStock.getAndDecrement();
395             if (outOfBread()) {
396                 LOG.info("Toaster is out of bread!");
397
398                 notificationProvider.offerNotification(new ToasterOutOfBreadBuilder().build());
399             }
400
401             // Set the Toaster status back to up - this essentially releases the toasting lock.
402             // We can't clear the current toast task nor set the Future result until the
403             // update has been committed so we pass a callback to be notified on completion.
404
405             setToasterStatusUp(result -> {
406                 currentMakeToastTask.set(null);
407                 LOG.debug("Toast done");
408                 futureResult.set(RpcResultBuilder.<Void>success().build());
409                 return null;
410             });
411
412             return null;
413         }
414     }
415 }

©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.