2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.sample.toaster.provider;
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;
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;
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;
55 public class OpendaylightToaster implements ToasterService, ToasterProviderRuntimeMXBean,
56 DataChangeListener, AutoCloseable {
58 private static final Logger LOG = LoggerFactory.getLogger(OpendaylightToaster.class);
60 public static final InstanceIdentifier<Toaster> TOASTER_IID = InstanceIdentifier.builder(Toaster.class).build();
62 private static final DisplayString TOASTER_MANUFACTURER = new DisplayString("Opendaylight");
63 private static final DisplayString TOASTER_MODEL_NUMBER = new DisplayString("Model 1 - Binding Aware");
65 private NotificationProviderService notificationProvider;
66 private DataBroker dataProvider;
68 private final ExecutorService executor;
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<>();
74 private final AtomicLong amountOfBreadInStock = new AtomicLong( 100 );
76 private final AtomicLong toastsMade = new AtomicLong(0);
78 // Thread safe holder for our darkness multiplier.
79 private final AtomicLong darknessFactor = new AtomicLong( 1000 );
81 public OpendaylightToaster() {
82 executor = Executors.newFixedThreadPool(1);
85 public void setNotificationProvider(final NotificationProviderService salService) {
86 this.notificationProvider = salService;
89 public void setDataProvider(final DataBroker salDataProvider) {
90 this.dataProvider = salDataProvider;
91 setToasterStatusUp( null );
95 * Implemented from the AutoCloseable interface.
98 public void close() throws ExecutionException, InterruptedException {
99 // When we close this service we need to shutdown our executor!
102 if (dataProvider != null) {
103 WriteTransaction tx = dataProvider.newWriteOnlyTransaction();
104 tx.delete(LogicalDatastoreType.OPERATIONAL,TOASTER_IID);
105 Futures.addCallback( tx.submit(), new FutureCallback<Void>() {
107 public void onSuccess( final Void result ) {
108 LOG.debug( "Delete Toaster commit result: " + result );
112 public void onFailure( final Throwable t ) {
113 LOG.error( "Delete of Toaster failed", t );
119 private Toaster buildToaster( final ToasterStatus status ) {
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 )
131 * Implemented from the DataChangeListener interface.
134 public void onDataChanged( final AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> change ) {
135 DataObject dataObject = change.getUpdatedSubtree();
136 if( dataObject instanceof Toaster )
138 Toaster toaster = (Toaster) dataObject;
139 Long darkness = toaster.getDarknessFactor();
140 if( darkness != null )
142 darknessFactor.set( darkness );
148 * RPC call implemented from the ToasterService interface that cancels the current
152 public Future<RpcResult<Void>> cancelToast() {
154 Future<?> current = currentMakeToastTask.getAndSet( null );
155 if( current != null ) {
156 current.cancel( true );
159 // Always return success from the cancel toast call.
160 return Futures.immediateFuture( RpcResultBuilder.<Void> success().build() );
164 * RPC call implemented from the ToasterService interface that attempts to make toast.
167 public Future<RpcResult<Void>> makeToast(final MakeToastInput input) {
168 LOG.info("makeToast: " + input);
170 final SettableFuture<RpcResult<Void>> futureResult = SettableFuture.create();
172 checkStatusAndMakeToast( input, futureResult, 2 );
177 private RpcError makeToasterOutOfBreadError() {
178 return RpcResultBuilder.newError( ErrorType.APPLICATION, "resource-denied",
179 "Toaster is out of bread", "out-of-stock", null, null );
182 private RpcError makeToasterInUseError() {
183 return RpcResultBuilder.newWarning( ErrorType.APPLICATION, "in-use",
184 "Toaster is busy", null, null, null );
187 private void checkStatusAndMakeToast( final MakeToastInput input,
188 final SettableFuture<RpcResult<Void>> futureResult,
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
195 final ReadWriteTransaction tx = dataProvider.newReadWriteTransaction();
196 ListenableFuture<Optional<Toaster>> readFuture =
197 tx.read( LogicalDatastoreType.OPERATIONAL, TOASTER_IID );
199 final ListenableFuture<Void> commitFuture =
200 Futures.transform( readFuture, new AsyncFunction<Optional<Toaster>,Void>() {
203 public ListenableFuture<Void> apply(
204 final Optional<Toaster> toasterData ) throws Exception {
206 ToasterStatus toasterStatus = ToasterStatus.Up;
207 if( toasterData.isPresent() ) {
208 toasterStatus = toasterData.get().getToasterStatus();
211 LOG.debug( "Read toaster status: {}", toasterStatus );
213 if( toasterStatus == ToasterStatus.Up ) {
216 LOG.debug( "Toaster is out of bread" );
218 return Futures.immediateFailedCheckedFuture(
219 new TransactionCommitFailedException( "", makeToasterOutOfBreadError() ) );
222 LOG.debug( "Setting Toaster status to Down" );
224 // We're not currently making toast - try to update the status to Down
225 // to indicate we're going to make toast. This acts as a lock to prevent
226 // concurrent toasting.
227 tx.put( LogicalDatastoreType.OPERATIONAL, TOASTER_IID,
228 buildToaster( ToasterStatus.Down ) );
232 LOG.debug( "Oops - already making toast!" );
234 // Return an error since we are already making toast. This will get
235 // propagated to the commitFuture below which will interpret the null
236 // TransactionStatus in the RpcResult as an error condition.
237 return Futures.immediateFailedCheckedFuture(
238 new TransactionCommitFailedException( "", makeToasterInUseError() ) );
242 Futures.addCallback( commitFuture, new FutureCallback<Void>() {
244 public void onSuccess( final Void result ) {
246 currentMakeToastTask.set( executor.submit( new MakeToastTask( input, futureResult ) ) );
250 public void onFailure( final Throwable ex ) {
251 if( ex instanceof OptimisticLockFailedException ) {
253 // Another thread is likely trying to make toast simultaneously and updated the
254 // status before us. Try reading the status again - if another make toast is
255 // now in progress, we should get ToasterStatus.Down and fail.
257 if( ( tries - 1 ) > 0 ) {
258 LOG.debug( "Got OptimisticLockFailedException - trying again" );
260 checkStatusAndMakeToast( input, futureResult, tries - 1 );
263 futureResult.set( RpcResultBuilder.<Void> failed()
264 .withError( ErrorType.APPLICATION, ex.getMessage() ).build() );
269 LOG.debug( "Failed to commit Toaster status", ex );
271 // Probably already making toast.
272 futureResult.set( RpcResultBuilder.<Void> failed()
273 .withRpcErrors( ((TransactionCommitFailedException)ex).getErrorList() )
281 * RestConf RPC call implemented from the ToasterService interface.
282 * Restocks the bread for the toaster, resets the toastsMade counter to 0, and sends a
283 * ToasterRestocked notification.
286 public Future<RpcResult<java.lang.Void>> restockToaster(final RestockToasterInput input) {
287 LOG.info( "restockToaster: " + input );
289 amountOfBreadInStock.set( input.getAmountOfBreadToStock() );
291 if( amountOfBreadInStock.get() > 0 ) {
292 ToasterRestocked reStockedNotification = new ToasterRestockedBuilder()
293 .setAmountOfBread( input.getAmountOfBreadToStock() ).build();
294 notificationProvider.publish( reStockedNotification );
297 return Futures.immediateFuture( RpcResultBuilder.<Void> success().build() );
301 * JMX RPC call implemented from the ToasterProviderRuntimeMXBean interface.
304 public void clearToastsMade() {
305 LOG.info( "clearToastsMade" );
310 * Accesssor method implemented from the ToasterProviderRuntimeMXBean interface.
313 public Long getToastsMade() {
314 return toastsMade.get();
317 private void setToasterStatusUp( final Function<Boolean,Void> resultCallback ) {
319 WriteTransaction tx = dataProvider.newWriteOnlyTransaction();
320 tx.put( LogicalDatastoreType.OPERATIONAL,TOASTER_IID, buildToaster( ToasterStatus.Up ) );
322 Futures.addCallback( tx.submit(), new FutureCallback<Void>() {
324 public void onSuccess( final Void result ) {
325 notifyCallback( true );
329 public void onFailure( final Throwable t ) {
330 // We shouldn't get an OptimisticLockFailedException (or any ex) as no
331 // other component should be updating the operational state.
332 LOG.error( "Failed to update toaster status", t );
334 notifyCallback( false );
337 void notifyCallback( final boolean result ) {
338 if( resultCallback != null ) {
339 resultCallback.apply( result );
345 private boolean outOfBread()
347 return amountOfBreadInStock.get() == 0;
350 private class MakeToastTask implements Callable<Void> {
352 final MakeToastInput toastRequest;
353 final SettableFuture<RpcResult<Void>> futureResult;
355 public MakeToastTask( final MakeToastInput toastRequest,
356 final SettableFuture<RpcResult<Void>> futureResult ) {
357 this.toastRequest = toastRequest;
358 this.futureResult = futureResult;
365 // make toast just sleeps for n seconds per doneness level.
366 long darknessFactor = OpendaylightToaster.this.darknessFactor.get();
367 Thread.sleep(darknessFactor * toastRequest.getToasterDoneness());
370 catch( InterruptedException e ) {
371 LOG.info( "Interrupted while making the toast" );
374 toastsMade.incrementAndGet();
376 amountOfBreadInStock.getAndDecrement();
378 LOG.info( "Toaster is out of bread!" );
380 notificationProvider.publish( new ToasterOutOfBreadBuilder().build() );
383 // Set the Toaster status back to up - this essentially releases the toasting lock.
384 // We can't clear the current toast task nor set the Future result until the
385 // update has been committed so we pass a callback to be notified on completion.
387 setToasterStatusUp( new Function<Boolean,Void>() {
389 public Void apply( final Boolean result ) {
391 currentMakeToastTask.set( null );
393 LOG.debug("Toast done");
395 futureResult.set( RpcResultBuilder.<Void>success().build() );