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