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

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