Improve readability of Toaster code (incl. Java 8 lambda, static import)
[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.common.api.data.LogicalDatastoreType.CONFIGURATION;
11 import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.OPERATIONAL;
12 import static org.opendaylight.yangtools.yang.common.RpcError.ErrorType.APPLICATION;
13 import static org.opendaylight.controller.md.sal.binding.api.DataObjectModification.ModificationType.DELETE;
14 import static org.opendaylight.controller.md.sal.binding.api.DataObjectModification.ModificationType.WRITE;
15
16 import com.google.common.base.Function;
17 import com.google.common.base.Optional;
18 import com.google.common.util.concurrent.AsyncFunction;
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.ExecutionException;
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 dataProvider;
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 setDataProvider(final DataBroker salDataProvider) {
104         this.dataProvider = salDataProvider;
105         dataProvider.registerDataTreeChangeListener(new DataTreeIdentifier<>(CONFIGURATION, TOASTER_IID), this);
106         setToasterStatusUp(null);
107     }
108
109     /**
110      * Implemented from the AutoCloseable interface.
111      */
112     @Override
113     public void close() throws ExecutionException, InterruptedException {
114         // When we close this service we need to shutdown our executor!
115         executor.shutdown();
116
117         if (dataProvider != null) {
118             dataTreeChangeListenerRegistration.close();
119
120             WriteTransaction tx = dataProvider.newWriteOnlyTransaction();
121             tx.delete(OPERATIONAL,TOASTER_IID);
122             Futures.addCallback( tx.submit(), new FutureCallback<Void>() {
123                 @Override
124                 public void onSuccess( final Void result ) {
125                     LOG.debug( "Delete Toaster commit result: " + result );
126                 }
127
128                 @Override
129                 public void onFailure( final Throwable t ) {
130                     LOG.error( "Delete of Toaster failed", t );
131                 }
132             } );
133         }
134     }
135
136     private Toaster buildToaster( final ToasterStatus status ) {
137         // note - we are simulating a device whose manufacture and model are
138         // fixed (embedded) into the hardware.
139         // This is why the manufacture and model number are hardcoded.
140         return new ToasterBuilder().setToasterManufacturer( toasterAppConfig.getManufacturer() )
141                                    .setToasterModelNumber( toasterAppConfig.getModelNumber() )
142                                    .setToasterStatus( status )
143                                    .build();
144     }
145
146     /**
147      * Implemented from the DataTreeChangeListener interface.
148      */
149     @Override
150     public void onDataTreeChanged(Collection<DataTreeModification<Toaster>> changes) {
151         for(DataTreeModification<Toaster> change: changes) {
152             DataObjectModification<Toaster> rootNode = change.getRootNode();
153             if(rootNode.getModificationType() == WRITE) {
154                 Toaster oldToaster = rootNode.getDataBefore();
155                 Toaster newToaster = rootNode.getDataAfter();
156                 LOG.info("onDataTreeChanged - Toaster config with path {} was added or replaced: old Toaster: {}, new Toaster: {}",
157                         change.getRootPath().getRootIdentifier(), oldToaster, newToaster);
158
159                 Long darkness = newToaster.getDarknessFactor();
160                 if(darkness != null) {
161                     darknessFactor.set(darkness);
162                 }
163             } else if(rootNode.getModificationType() == DELETE) {
164                 LOG.info("onDataTreeChanged - Toaster config with path {} was deleted: old Toaster: {}",
165                         change.getRootPath().getRootIdentifier(), rootNode.getDataBefore());
166             }
167         }
168     }
169
170     /**
171      * RPC call implemented from the ToasterService interface that cancels the current toast, if any.
172      */
173     @Override
174     public Future<RpcResult<Void>> cancelToast() {
175         Future<?> current = currentMakeToastTask.getAndSet( null );
176         if( current != null ) {
177             current.cancel( true );
178         }
179
180         // Always return success from the cancel toast call
181         return Futures.immediateFuture( RpcResultBuilder.<Void> success().build() );
182     }
183
184     /**
185      * RPC call implemented from the ToasterService interface that attempts to make toast.
186      */
187     @Override
188     public Future<RpcResult<Void>> makeToast(final MakeToastInput input) {
189         LOG.info("makeToast: " + input);
190
191         final SettableFuture<RpcResult<Void>> futureResult = SettableFuture.create();
192
193         checkStatusAndMakeToast( input, futureResult, toasterAppConfig.getMaxMakeToastTries() );
194
195         return futureResult;
196     }
197
198     private RpcError makeToasterOutOfBreadError() {
199         return RpcResultBuilder.newError( APPLICATION, "resource-denied",
200                 "Toaster is out of bread", "out-of-stock", null, null );
201     }
202
203     private RpcError makeToasterInUseError() {
204         return RpcResultBuilder.newWarning( APPLICATION, "in-use",
205                 "Toaster is busy", null, null, null );
206     }
207
208     private void checkStatusAndMakeToast( final MakeToastInput input,
209                                           final SettableFuture<RpcResult<Void>> futureResult,
210                                           final int tries ) {
211
212         // Read the ToasterStatus and, if currently Up, try to write the status to Down.
213         // If that succeeds, then we essentially have an exclusive lock and can proceed
214         // to make toast.
215
216         final ReadWriteTransaction tx = dataProvider.newReadWriteTransaction();
217         ListenableFuture<Optional<Toaster>> readFuture = tx.read(OPERATIONAL, TOASTER_IID);
218
219         final ListenableFuture<Void> commitFuture =
220             Futures.transform( readFuture, (AsyncFunction<Optional<Toaster>, Void>) toasterData -> {
221
222                     ToasterStatus toasterStatus = ToasterStatus.Up;
223                     if( toasterData.isPresent() ) {
224                         toasterStatus = toasterData.get().getToasterStatus();
225                     }
226
227                     LOG.debug( "Read toaster status: {}", toasterStatus );
228
229                     if( toasterStatus == ToasterStatus.Up ) {
230
231                         if( outOfBread() ) {
232                             LOG.debug( "Toaster is out of bread" );
233
234                             return Futures.immediateFailedCheckedFuture(
235                                     new TransactionCommitFailedException( "", makeToasterOutOfBreadError() ) );
236                         }
237
238                         LOG.debug( "Setting Toaster status to Down" );
239
240                         // We're not currently making toast - try to update the status to Down
241                         // to indicate we're going to make toast. This acts as a lock to prevent
242                         // concurrent toasting.
243                         tx.put( OPERATIONAL, TOASTER_IID,
244                                 buildToaster( ToasterStatus.Down ) );
245                         return tx.submit();
246                     }
247
248                     LOG.debug( "Oops - already making toast!" );
249
250                     // Return an error since we are already making toast. This will get
251                     // propagated to the commitFuture below which will interpret the null
252                     // TransactionStatus in the RpcResult as an error condition.
253                     return Futures.immediateFailedCheckedFuture(
254                             new TransactionCommitFailedException( "", makeToasterInUseError() ) );
255         } );
256
257         Futures.addCallback( commitFuture, new FutureCallback<Void>() {
258             @Override
259             public void onSuccess( final Void result ) {
260                 // OK to make toast
261                 currentMakeToastTask.set( executor.submit( new MakeToastTask( input, futureResult ) ) );
262             }
263
264             @Override
265             public void onFailure( final Throwable ex ) {
266                 if( ex instanceof OptimisticLockFailedException ) {
267
268                     // Another thread is likely trying to make toast simultaneously and updated the
269                     // status before us. Try reading the status again - if another make toast is
270                     // now in progress, we should get ToasterStatus.Down and fail.
271
272                     if( ( tries - 1 ) > 0 ) {
273                         LOG.debug( "Got OptimisticLockFailedException - trying again" );
274
275                         checkStatusAndMakeToast( input, futureResult, tries - 1 );
276                     }
277                     else {
278                         futureResult.set( RpcResultBuilder.<Void> failed()
279                                 .withError( ErrorType.APPLICATION, ex.getMessage() ).build() );
280                     }
281
282                 } else {
283
284                     LOG.debug( "Failed to commit Toaster status", ex );
285
286                     // Probably already making toast.
287                     futureResult.set( RpcResultBuilder.<Void> failed()
288                             .withRpcErrors( ((TransactionCommitFailedException)ex).getErrorList() )
289                             .build() );
290                 }
291             }
292         } );
293     }
294
295     /**
296      * RestConf RPC call implemented from the ToasterService interface.
297      * Restocks the bread for the toaster, resets the toastsMade counter to 0, and sends a
298      * ToasterRestocked notification.
299      */
300     @Override
301     public Future<RpcResult<java.lang.Void>> restockToaster(final RestockToasterInput input) {
302         LOG.info( "restockToaster: " + input );
303
304         amountOfBreadInStock.set( input.getAmountOfBreadToStock() );
305
306         if( amountOfBreadInStock.get() > 0 ) {
307             ToasterRestocked reStockedNotification = new ToasterRestockedBuilder()
308                 .setAmountOfBread( input.getAmountOfBreadToStock() ).build();
309             notificationProvider.offerNotification( reStockedNotification );
310         }
311
312         return Futures.immediateFuture( RpcResultBuilder.<Void> success().build() );
313     }
314
315     /**
316      * JMX RPC call implemented from the ToasterProviderRuntimeMXBean interface.
317      */
318     @Override
319     public void clearToastsMade() {
320         LOG.info( "clearToastsMade" );
321         toastsMade.set( 0 );
322     }
323
324     /**
325      * Accesssor method implemented from the ToasterProviderRuntimeMXBean interface.
326      */
327     @Override
328     public Long getToastsMade() {
329         return toastsMade.get();
330     }
331
332     private void setToasterStatusUp( final Function<Boolean,Void> resultCallback ) {
333         WriteTransaction tx = dataProvider.newWriteOnlyTransaction();
334         tx.put( OPERATIONAL,TOASTER_IID, buildToaster( ToasterStatus.Up ) );
335
336         Futures.addCallback( tx.submit(), new FutureCallback<Void>() {
337             @Override
338             public void onSuccess( final Void result ) {
339                 notifyCallback( true );
340             }
341
342             @Override
343             public void onFailure( final Throwable t ) {
344                 // We shouldn't get an OptimisticLockFailedException (or any ex) as no
345                 // other component should be updating the operational state.
346                 LOG.error( "Failed to update toaster status", t );
347
348                 notifyCallback( false );
349             }
350
351             void notifyCallback( final boolean result ) {
352                 if( resultCallback != null ) {
353                     resultCallback.apply( result );
354                 }
355             }
356         } );
357     }
358
359     private boolean outOfBread()
360     {
361         return amountOfBreadInStock.get() == 0;
362     }
363
364     private class MakeToastTask implements Callable<Void> {
365
366         final MakeToastInput toastRequest;
367         final SettableFuture<RpcResult<Void>> futureResult;
368
369         public MakeToastTask( final MakeToastInput toastRequest,
370                               final SettableFuture<RpcResult<Void>> futureResult ) {
371             this.toastRequest = toastRequest;
372             this.futureResult = futureResult;
373         }
374
375         @Override
376         public Void call() {
377             try
378             {
379                 // make toast just sleeps for n seconds per doneness level.
380                 long darknessFactor = OpendaylightToaster.this.darknessFactor.get();
381                 Thread.sleep(darknessFactor * toastRequest.getToasterDoneness());
382
383             }
384             catch( InterruptedException e ) {
385                 LOG.info( "Interrupted while making the toast" );
386             }
387
388             toastsMade.incrementAndGet();
389
390             amountOfBreadInStock.getAndDecrement();
391             if( outOfBread() ) {
392                 LOG.info( "Toaster is out of bread!" );
393
394                 notificationProvider.offerNotification( new ToasterOutOfBreadBuilder().build() );
395             }
396
397             // Set the Toaster status back to up - this essentially releases the toasting lock.
398             // We can't clear the current toast task nor set the Future result until the
399             // update has been committed so we pass a callback to be notified on completion.
400
401             setToasterStatusUp( result -> {
402
403                     currentMakeToastTask.set( null );
404
405                     LOG.debug("Toast done");
406
407                     futureResult.set( RpcResultBuilder.<Void>success().build() );
408
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.