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