Deprecated Rpcs and RpcErrors helper classes
[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 java.util.concurrent.Callable;
11 import java.util.concurrent.ExecutionException;
12 import java.util.concurrent.ExecutorService;
13 import java.util.concurrent.Executors;
14 import java.util.concurrent.Future;
15 import java.util.concurrent.atomic.AtomicLong;
16 import java.util.concurrent.atomic.AtomicReference;
17
18 import org.opendaylight.controller.config.yang.config.toaster_provider.impl.ToasterProviderRuntimeMXBean;
19 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
20 import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
21 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
22 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
23 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
24 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
25 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
26 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
27 import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
28 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.DisplayString;
29 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastInput;
30 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.RestockToasterInput;
31 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.Toaster;
32 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.Toaster.ToasterStatus;
33 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterBuilder;
34 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterOutOfBreadBuilder;
35 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterRestocked;
36 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterRestockedBuilder;
37 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterService;
38 import org.opendaylight.yangtools.yang.binding.DataObject;
39 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
40 import org.opendaylight.yangtools.yang.common.RpcError;
41 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
42 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
43 import org.opendaylight.yangtools.yang.common.RpcResult;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 import com.google.common.base.Function;
48 import com.google.common.base.Optional;
49 import com.google.common.util.concurrent.AsyncFunction;
50 import com.google.common.util.concurrent.FutureCallback;
51 import com.google.common.util.concurrent.Futures;
52 import com.google.common.util.concurrent.ListenableFuture;
53 import com.google.common.util.concurrent.SettableFuture;
54
55 public class OpendaylightToaster implements ToasterService, ToasterProviderRuntimeMXBean,
56                                             DataChangeListener, AutoCloseable {
57
58     private static final Logger LOG = LoggerFactory.getLogger(OpendaylightToaster.class);
59
60     public static final InstanceIdentifier<Toaster> TOASTER_IID = InstanceIdentifier.builder(Toaster.class).build();
61
62     private static final DisplayString TOASTER_MANUFACTURER = new DisplayString("Opendaylight");
63     private static final DisplayString TOASTER_MODEL_NUMBER = new DisplayString("Model 1 - Binding Aware");
64
65     private NotificationProviderService notificationProvider;
66     private DataBroker dataProvider;
67
68     private final ExecutorService executor;
69
70     // The following holds the Future for the current make toast task.
71     // This is used to cancel the current toast.
72     private final AtomicReference<Future<?>> currentMakeToastTask = new AtomicReference<>();
73
74     private final AtomicLong amountOfBreadInStock = new AtomicLong( 100 );
75
76     private final AtomicLong toastsMade = new AtomicLong(0);
77
78     // Thread safe holder for our darkness multiplier.
79     private final AtomicLong darknessFactor = new AtomicLong( 1000 );
80
81     public OpendaylightToaster() {
82         executor = Executors.newFixedThreadPool(1);
83     }
84
85     public void setNotificationProvider(final NotificationProviderService salService) {
86         this.notificationProvider = salService;
87     }
88
89     public void setDataProvider(final DataBroker salDataProvider) {
90         this.dataProvider = salDataProvider;
91         setToasterStatusUp( null );
92     }
93
94     /**
95      * Implemented from the AutoCloseable interface.
96      */
97     @Override
98     public void close() throws ExecutionException, InterruptedException {
99         // When we close this service we need to shutdown our executor!
100         executor.shutdown();
101
102         if (dataProvider != null) {
103             WriteTransaction t = dataProvider.newWriteOnlyTransaction();
104             t.delete(LogicalDatastoreType.OPERATIONAL,TOASTER_IID);
105             ListenableFuture<RpcResult<TransactionStatus>> future = t.commit();
106             Futures.addCallback( future, new FutureCallback<RpcResult<TransactionStatus>>() {
107                 @Override
108                 public void onSuccess( RpcResult<TransactionStatus> result ) {
109                     LOG.debug( "Delete Toaster commit result: " + result );
110                 }
111
112                 @Override
113                 public void onFailure( Throwable t ) {
114                     LOG.error( "Delete of Toaster failed", t );
115                 }
116             } );
117         }
118     }
119
120     private Toaster buildToaster( ToasterStatus status ) {
121
122         // note - we are simulating a device whose manufacture and model are
123         // fixed (embedded) into the hardware.
124         // This is why the manufacture and model number are hardcoded.
125         return new ToasterBuilder().setToasterManufacturer( TOASTER_MANUFACTURER )
126                                    .setToasterModelNumber( TOASTER_MODEL_NUMBER )
127                                    .setToasterStatus( status )
128                                    .build();
129     }
130
131     /**
132      * Implemented from the DataChangeListener interface.
133      */
134     @Override
135     public void onDataChanged( final AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> change ) {
136         DataObject dataObject = change.getUpdatedSubtree();
137         if( dataObject instanceof Toaster )
138         {
139             Toaster toaster = (Toaster) dataObject;
140             Long darkness = toaster.getDarknessFactor();
141             if( darkness != null )
142             {
143                 darknessFactor.set( darkness );
144             }
145         }
146     }
147
148     /**
149      * RPC call implemented from the ToasterService interface that cancels the current
150      * toast, if any.
151      */
152     @Override
153     public Future<RpcResult<Void>> cancelToast() {
154
155         Future<?> current = currentMakeToastTask.getAndSet( null );
156         if( current != null ) {
157             current.cancel( true );
158         }
159
160         // Always return success from the cancel toast call.
161         return Futures.immediateFuture( RpcResultBuilder.<Void> success().build() );
162     }
163
164     /**
165      * RPC call implemented from the ToasterService interface that attempts to make toast.
166      */
167     @Override
168     public Future<RpcResult<Void>> makeToast(final MakeToastInput input) {
169         LOG.info("makeToast: " + input);
170
171         final SettableFuture<RpcResult<Void>> futureResult = SettableFuture.create();
172
173         checkStatusAndMakeToast( input, futureResult );
174
175         return futureResult;
176     }
177
178     private RpcError makeToasterOutOfBreadError() {
179         return RpcResultBuilder.newError( ErrorType.APPLICATION, "resource-denied",
180                 "Toaster is out of bread", "out-of-stock", null, null );
181     }
182
183     private RpcError makeToasterInUseError() {
184         return RpcResultBuilder.newWarning( ErrorType.APPLICATION, "in-use",
185                 "Toaster is busy", null, null, null );
186     }
187
188     private void checkStatusAndMakeToast( final MakeToastInput input,
189                                           final SettableFuture<RpcResult<Void>> futureResult ) {
190
191         // Read the ToasterStatus and, if currently Up, try to write the status to Down.
192         // If that succeeds, then we essentially have an exclusive lock and can proceed
193         // to make toast.
194
195         final ReadWriteTransaction tx = dataProvider.newReadWriteTransaction();
196         ListenableFuture<Optional<DataObject>> readFuture =
197                                           tx.read( LogicalDatastoreType.OPERATIONAL, TOASTER_IID );
198
199         final ListenableFuture<RpcResult<TransactionStatus>> commitFuture =
200             Futures.transform( readFuture, new AsyncFunction<Optional<DataObject>,
201                                                                    RpcResult<TransactionStatus>>() {
202
203                 @Override
204                 public ListenableFuture<RpcResult<TransactionStatus>> apply(
205                         Optional<DataObject> toasterData ) throws Exception {
206
207                     ToasterStatus toasterStatus = ToasterStatus.Up;
208                     if( toasterData.isPresent() ) {
209                         toasterStatus = ((Toaster)toasterData.get()).getToasterStatus();
210                     }
211
212                     LOG.debug( "Read toaster status: {}", toasterStatus );
213
214                     if( toasterStatus == ToasterStatus.Up ) {
215
216                         if( outOfBread() ) {
217                             LOG.debug( "Toaster is out of bread" );
218
219                             return Futures.immediateFuture( RpcResultBuilder.<TransactionStatus>failed()
220                                     .withRpcError( makeToasterOutOfBreadError() ).build() );
221                         }
222
223                         LOG.debug( "Setting Toaster status to Down" );
224
225                         // We're not currently making toast - try to update the status to Down
226                         // to indicate we're going to make toast. This acts as a lock to prevent
227                         // concurrent toasting.
228                         tx.put( LogicalDatastoreType.OPERATIONAL, TOASTER_IID,
229                                 buildToaster( ToasterStatus.Down ) );
230                         return tx.commit();
231                     }
232
233                     LOG.debug( "Oops - already making toast!" );
234
235                     // Return an error since we are already making toast. This will get
236                     // propagated to the commitFuture below which will interpret the null
237                     // TransactionStatus in the RpcResult as an error condition.
238                     return Futures.immediateFuture( RpcResultBuilder.<TransactionStatus>failed()
239                             .withRpcError( makeToasterInUseError() ).build() );
240                 }
241         } );
242
243         Futures.addCallback( commitFuture, new FutureCallback<RpcResult<TransactionStatus>>() {
244             @Override
245             public void onSuccess( RpcResult<TransactionStatus> result ) {
246                 if( result.getResult() == TransactionStatus.COMMITED  ) {
247
248                     // OK to make toast
249                     currentMakeToastTask.set( executor.submit(
250                                                     new MakeToastTask( input, futureResult ) ) );
251                 } else {
252
253                     LOG.debug( "Setting error result" );
254
255                     // Either the transaction failed to commit for some reason or, more likely,
256                     // the read above returned ToasterStatus.Down. Either way, fail the
257                     // futureResult and copy the errors.
258
259                     futureResult.set( RpcResultBuilder.<Void>failed().withRpcErrors(
260                                                                      result.getErrors() ).build() );
261                 }
262             }
263
264             @Override
265             public void onFailure( 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                     LOG.debug( "Got OptimisticLockFailedException - trying again" );
273
274                     checkStatusAndMakeToast( input, futureResult );
275
276                 } else {
277
278                     LOG.error( "Failed to commit Toaster status", ex );
279
280                     // Got some unexpected error so fail.
281                     futureResult.set( RpcResultBuilder.<Void> failed()
282                                         .withError( ErrorType.APPLICATION, ex.getMessage() ).build() );
283                 }
284             }
285         } );
286     }
287
288     /**
289      * RestConf RPC call implemented from the ToasterService interface.
290      * Restocks the bread for the toaster, resets the toastsMade counter to 0, and sends a
291      * ToasterRestocked notification.
292      */
293     @Override
294     public Future<RpcResult<java.lang.Void>> restockToaster(final RestockToasterInput input) {
295         LOG.info( "restockToaster: " + input );
296
297         amountOfBreadInStock.set( input.getAmountOfBreadToStock() );
298
299         if( amountOfBreadInStock.get() > 0 ) {
300             ToasterRestocked reStockedNotification = new ToasterRestockedBuilder()
301                 .setAmountOfBread( input.getAmountOfBreadToStock() ).build();
302             notificationProvider.publish( reStockedNotification );
303         }
304
305         return Futures.immediateFuture( RpcResultBuilder.<Void> success().build() );
306     }
307
308     /**
309      * JMX RPC call implemented from the ToasterProviderRuntimeMXBean interface.
310      */
311     @Override
312     public void clearToastsMade() {
313         LOG.info( "clearToastsMade" );
314         toastsMade.set( 0 );
315     }
316
317     /**
318      * Accesssor method implemented from the ToasterProviderRuntimeMXBean interface.
319      */
320     @Override
321     public Long getToastsMade() {
322         return toastsMade.get();
323     }
324
325     private void setToasterStatusUp( final Function<Boolean,Void> resultCallback ) {
326
327         WriteTransaction tx = dataProvider.newWriteOnlyTransaction();
328         tx.put( LogicalDatastoreType.OPERATIONAL,TOASTER_IID, buildToaster( ToasterStatus.Up ) );
329
330         ListenableFuture<RpcResult<TransactionStatus>> commitFuture = tx.commit();
331
332         Futures.addCallback( commitFuture, new FutureCallback<RpcResult<TransactionStatus>>() {
333             @Override
334             public void onSuccess( RpcResult<TransactionStatus> result ) {
335                 if( result.getResult() != TransactionStatus.COMMITED ) {
336                     LOG.error( "Failed to update toaster status: " + result.getErrors() );
337                 }
338
339                 notifyCallback( result.getResult() == TransactionStatus.COMMITED );
340             }
341
342             @Override
343             public void onFailure( 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( 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.publish( 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( new Function<Boolean,Void>() {
402                 @Override
403                 public Void apply( Boolean result ) {
404
405                     currentMakeToastTask.set( null );
406
407                     LOG.debug("Toast done");
408
409                     futureResult.set( RpcResultBuilder.<Void>success().build() );
410
411                     return null;
412                 }
413             } );
414
415             return null;
416         }
417     }
418 }

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