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 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;
57 public class OpendaylightToaster extends AbstractMXBean implements ToasterService, ToasterProviderRuntimeMXBean,
58 DataTreeChangeListener<Toaster>, AutoCloseable {
60 private static final Logger LOG = LoggerFactory.getLogger(OpendaylightToaster.class);
62 public static final InstanceIdentifier<Toaster> TOASTER_IID = InstanceIdentifier.builder(Toaster.class).build();
64 private static final DisplayString TOASTER_MANUFACTURER = new DisplayString("Opendaylight");
65 private static final DisplayString TOASTER_MODEL_NUMBER = new DisplayString("Model 1 - Binding Aware");
67 private NotificationPublishService notificationProvider;
68 private DataBroker dataProvider;
69 private ListenerRegistration<OpendaylightToaster> dataTreeChangeListenerRegistration;
71 private final ExecutorService executor;
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<>();
77 private final AtomicLong amountOfBreadInStock = new AtomicLong( 100 );
79 private final AtomicLong toastsMade = new AtomicLong(0);
81 // Thread safe holder for our darkness multiplier.
82 private final AtomicLong darknessFactor = new AtomicLong( 1000 );
84 public OpendaylightToaster() {
85 super("OpendaylightToaster", "toaster-provider", null);
86 executor = Executors.newFixedThreadPool(1);
89 public void setNotificationProvider(final NotificationPublishService notificationPublishService) {
90 this.notificationProvider = notificationPublishService;
93 public void setDataProvider(final DataBroker salDataProvider) {
94 this.dataProvider = salDataProvider;
96 dataProvider.registerDataTreeChangeListener(new DataTreeIdentifier<Toaster>(
97 LogicalDatastoreType.CONFIGURATION, OpendaylightToaster.TOASTER_IID), this);
99 setToasterStatusUp( null );
103 * Implemented from the AutoCloseable interface.
106 public void close() throws ExecutionException, InterruptedException {
107 // When we close this service we need to shutdown our executor!
110 if (dataProvider != null) {
111 dataTreeChangeListenerRegistration.close();
113 WriteTransaction tx = dataProvider.newWriteOnlyTransaction();
114 tx.delete(LogicalDatastoreType.OPERATIONAL,TOASTER_IID);
115 Futures.addCallback( tx.submit(), new FutureCallback<Void>() {
117 public void onSuccess( final Void result ) {
118 LOG.debug( "Delete Toaster commit result: " + result );
122 public void onFailure( final Throwable t ) {
123 LOG.error( "Delete of Toaster failed", t );
129 private Toaster buildToaster( final ToasterStatus status ) {
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 )
141 * Implemented from the DataTreeChangeListener interface.
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);
153 Long darkness = newToaster.getDarknessFactor();
154 if(darkness != null) {
155 darknessFactor.set(darkness);
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());
165 * RPC call implemented from the ToasterService interface that cancels the current
169 public Future<RpcResult<Void>> cancelToast() {
171 Future<?> current = currentMakeToastTask.getAndSet( null );
172 if( current != null ) {
173 current.cancel( true );
176 // Always return success from the cancel toast call.
177 return Futures.immediateFuture( RpcResultBuilder.<Void> success().build() );
181 * RPC call implemented from the ToasterService interface that attempts to make toast.
184 public Future<RpcResult<Void>> makeToast(final MakeToastInput input) {
185 LOG.info("makeToast: " + input);
187 final SettableFuture<RpcResult<Void>> futureResult = SettableFuture.create();
189 checkStatusAndMakeToast( input, futureResult, 2 );
194 private RpcError makeToasterOutOfBreadError() {
195 return RpcResultBuilder.newError( ErrorType.APPLICATION, "resource-denied",
196 "Toaster is out of bread", "out-of-stock", null, null );
199 private RpcError makeToasterInUseError() {
200 return RpcResultBuilder.newWarning( ErrorType.APPLICATION, "in-use",
201 "Toaster is busy", null, null, null );
204 private void checkStatusAndMakeToast( final MakeToastInput input,
205 final SettableFuture<RpcResult<Void>> futureResult,
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
212 final ReadWriteTransaction tx = dataProvider.newReadWriteTransaction();
213 ListenableFuture<Optional<Toaster>> readFuture =
214 tx.read( LogicalDatastoreType.OPERATIONAL, TOASTER_IID );
216 final ListenableFuture<Void> commitFuture =
217 Futures.transform( readFuture, new AsyncFunction<Optional<Toaster>,Void>() {
220 public ListenableFuture<Void> apply(
221 final Optional<Toaster> toasterData ) throws Exception {
223 ToasterStatus toasterStatus = ToasterStatus.Up;
224 if( toasterData.isPresent() ) {
225 toasterStatus = toasterData.get().getToasterStatus();
228 LOG.debug( "Read toaster status: {}", toasterStatus );
230 if( toasterStatus == ToasterStatus.Up ) {
233 LOG.debug( "Toaster is out of bread" );
235 return Futures.immediateFailedCheckedFuture(
236 new TransactionCommitFailedException( "", makeToasterOutOfBreadError() ) );
239 LOG.debug( "Setting Toaster status to Down" );
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 ) );
249 LOG.debug( "Oops - already making toast!" );
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() ) );
259 Futures.addCallback( commitFuture, new FutureCallback<Void>() {
261 public void onSuccess( final Void result ) {
263 currentMakeToastTask.set( executor.submit( new MakeToastTask( input, futureResult ) ) );
267 public void onFailure( final Throwable ex ) {
268 if( ex instanceof OptimisticLockFailedException ) {
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.
274 if( ( tries - 1 ) > 0 ) {
275 LOG.debug( "Got OptimisticLockFailedException - trying again" );
277 checkStatusAndMakeToast( input, futureResult, tries - 1 );
280 futureResult.set( RpcResultBuilder.<Void> failed()
281 .withError( ErrorType.APPLICATION, ex.getMessage() ).build() );
286 LOG.debug( "Failed to commit Toaster status", ex );
288 // Probably already making toast.
289 futureResult.set( RpcResultBuilder.<Void> failed()
290 .withRpcErrors( ((TransactionCommitFailedException)ex).getErrorList() )
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.
303 public Future<RpcResult<java.lang.Void>> restockToaster(final RestockToasterInput input) {
304 LOG.info( "restockToaster: " + input );
306 amountOfBreadInStock.set( input.getAmountOfBreadToStock() );
308 if( amountOfBreadInStock.get() > 0 ) {
309 ToasterRestocked reStockedNotification = new ToasterRestockedBuilder()
310 .setAmountOfBread( input.getAmountOfBreadToStock() ).build();
311 notificationProvider.offerNotification( reStockedNotification );
314 return Futures.immediateFuture( RpcResultBuilder.<Void> success().build() );
318 * JMX RPC call implemented from the ToasterProviderRuntimeMXBean interface.
321 public void clearToastsMade() {
322 LOG.info( "clearToastsMade" );
327 * Accesssor method implemented from the ToasterProviderRuntimeMXBean interface.
330 public Long getToastsMade() {
331 return toastsMade.get();
334 private void setToasterStatusUp( final Function<Boolean,Void> resultCallback ) {
336 WriteTransaction tx = dataProvider.newWriteOnlyTransaction();
337 tx.put( LogicalDatastoreType.OPERATIONAL,TOASTER_IID, buildToaster( ToasterStatus.Up ) );
339 Futures.addCallback( tx.submit(), new FutureCallback<Void>() {
341 public void onSuccess( final Void result ) {
342 notifyCallback( true );
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 );
351 notifyCallback( false );
354 void notifyCallback( final boolean result ) {
355 if( resultCallback != null ) {
356 resultCallback.apply( result );
362 private boolean outOfBread()
364 return amountOfBreadInStock.get() == 0;
367 private class MakeToastTask implements Callable<Void> {
369 final MakeToastInput toastRequest;
370 final SettableFuture<RpcResult<Void>> futureResult;
372 public MakeToastTask( final MakeToastInput toastRequest,
373 final SettableFuture<RpcResult<Void>> futureResult ) {
374 this.toastRequest = toastRequest;
375 this.futureResult = futureResult;
382 // make toast just sleeps for n seconds per doneness level.
383 long darknessFactor = OpendaylightToaster.this.darknessFactor.get();
384 Thread.sleep(darknessFactor * toastRequest.getToasterDoneness());
387 catch( InterruptedException e ) {
388 LOG.info( "Interrupted while making the toast" );
391 toastsMade.incrementAndGet();
393 amountOfBreadInStock.getAndDecrement();
395 LOG.info( "Toaster is out of bread!" );
397 notificationProvider.offerNotification( new ToasterOutOfBreadBuilder().build() );
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.
404 setToasterStatusUp( new Function<Boolean,Void>() {
406 public Void apply( final Boolean result ) {
408 currentMakeToastTask.set( null );
410 LOG.debug("Toast done");
412 futureResult.set( RpcResultBuilder.<Void>success().build() );