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