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.md.sal.binding.api.DataBroker;
26 import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
27 import org.opendaylight.controller.md.sal.binding.api.DataTreeChangeListener;
28 import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
29 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
30 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
31 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
32 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
33 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
34 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
35 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
36 import org.opendaylight.controller.md.sal.common.util.jmx.AbstractMXBean;
37 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.DisplayString;
38 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastInput;
39 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.RestockToasterInput;
40 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.Toaster;
41 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.Toaster.ToasterStatus;
42 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterBuilder;
43 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterOutOfBreadBuilder;
44 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterRestocked;
45 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterRestockedBuilder;
46 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterService;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.toaster.app.config.rev160503.ToasterAppConfig;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.toaster.app.config.rev160503.ToasterAppConfigBuilder;
49 import org.opendaylight.yangtools.concepts.ListenerRegistration;
50 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
51 import org.opendaylight.yangtools.yang.common.RpcError;
52 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
53 import org.opendaylight.yangtools.yang.common.RpcResult;
54 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
58 public class OpendaylightToaster extends AbstractMXBean implements ToasterService, ToasterProviderRuntimeMXBean,
59 DataTreeChangeListener<Toaster>, AutoCloseable {
61 private static final Logger LOG = LoggerFactory.getLogger(OpendaylightToaster.class);
63 public static final InstanceIdentifier<Toaster> TOASTER_IID = InstanceIdentifier.builder(Toaster.class).build();
65 private static final DisplayString TOASTER_MANUFACTURER = new DisplayString("Opendaylight");
66 private static final DisplayString TOASTER_MODEL_NUMBER = new DisplayString("Model 1 - Binding Aware");
68 private NotificationPublishService notificationProvider;
69 private DataBroker dataProvider;
70 private ListenerRegistration<OpendaylightToaster> dataTreeChangeListenerRegistration;
72 private final ExecutorService executor;
74 // The following holds the Future for the current make toast task.
75 // This is used to cancel the current toast.
76 private final AtomicReference<Future<?>> currentMakeToastTask = new AtomicReference<>();
78 private final AtomicLong amountOfBreadInStock = new AtomicLong( 100 );
80 private final AtomicLong toastsMade = new AtomicLong(0);
82 // Thread safe holder for our darkness multiplier.
83 private final AtomicLong darknessFactor = new AtomicLong( 1000 );
85 private final ToasterAppConfig toasterAppConfig;
87 public OpendaylightToaster() {
88 this(new ToasterAppConfigBuilder().setManufacturer(TOASTER_MANUFACTURER).setModelNumber(TOASTER_MODEL_NUMBER).
89 setMaxMakeToastTries(2).build());
92 public OpendaylightToaster(ToasterAppConfig toasterAppConfig) {
93 super("OpendaylightToaster", "toaster-provider", null);
94 executor = Executors.newFixedThreadPool(1);
95 this.toasterAppConfig = toasterAppConfig;
98 public void setNotificationProvider(final NotificationPublishService notificationPublishService) {
99 this.notificationProvider = notificationPublishService;
102 public void setDataProvider(final DataBroker salDataProvider) {
103 this.dataProvider = salDataProvider;
105 dataProvider.registerDataTreeChangeListener(new DataTreeIdentifier<Toaster>(
106 LogicalDatastoreType.CONFIGURATION, OpendaylightToaster.TOASTER_IID), this);
108 setToasterStatusUp( null );
112 * Implemented from the AutoCloseable interface.
115 public void close() throws ExecutionException, InterruptedException {
116 // When we close this service we need to shutdown our executor!
119 if (dataProvider != null) {
120 dataTreeChangeListenerRegistration.close();
122 WriteTransaction tx = dataProvider.newWriteOnlyTransaction();
123 tx.delete(LogicalDatastoreType.OPERATIONAL,TOASTER_IID);
124 Futures.addCallback( tx.submit(), new FutureCallback<Void>() {
126 public void onSuccess( final Void result ) {
127 LOG.debug( "Delete Toaster commit result: " + result );
131 public void onFailure( final Throwable t ) {
132 LOG.error( "Delete of Toaster failed", t );
138 private Toaster buildToaster( final ToasterStatus status ) {
140 // note - we are simulating a device whose manufacture and model are
141 // fixed (embedded) into the hardware.
142 // This is why the manufacture and model number are hardcoded.
143 return new ToasterBuilder().setToasterManufacturer( toasterAppConfig.getManufacturer() )
144 .setToasterModelNumber( toasterAppConfig.getModelNumber() )
145 .setToasterStatus( status )
150 * Implemented from the DataTreeChangeListener interface.
153 public void onDataTreeChanged(Collection<DataTreeModification<Toaster>> changes) {
154 for(DataTreeModification<Toaster> change: changes) {
155 DataObjectModification<Toaster> rootNode = change.getRootNode();
156 if(rootNode.getModificationType() == DataObjectModification.ModificationType.WRITE) {
157 Toaster oldToaster = rootNode.getDataBefore();
158 Toaster newToaster = rootNode.getDataAfter();
159 LOG.info("onDataTreeChanged - Toaster config with path {} was added or replaced: old Toaster: {}, new Toaster: {}",
160 change.getRootPath().getRootIdentifier(), oldToaster, newToaster);
162 Long darkness = newToaster.getDarknessFactor();
163 if(darkness != null) {
164 darknessFactor.set(darkness);
166 } else if(rootNode.getModificationType() == DataObjectModification.ModificationType.DELETE) {
167 LOG.info("onDataTreeChanged - Toaster config with path {} was deleted: old Toaster: {}",
168 change.getRootPath().getRootIdentifier(), rootNode.getDataBefore());
174 * RPC call implemented from the ToasterService interface that cancels the current
178 public Future<RpcResult<Void>> cancelToast() {
180 Future<?> current = currentMakeToastTask.getAndSet( null );
181 if( current != null ) {
182 current.cancel( true );
185 // Always return success from the cancel toast call.
186 return Futures.immediateFuture( RpcResultBuilder.<Void> success().build() );
190 * RPC call implemented from the ToasterService interface that attempts to make toast.
193 public Future<RpcResult<Void>> makeToast(final MakeToastInput input) {
194 LOG.info("makeToast: " + input);
196 final SettableFuture<RpcResult<Void>> futureResult = SettableFuture.create();
198 checkStatusAndMakeToast( input, futureResult, toasterAppConfig.getMaxMakeToastTries() );
203 private RpcError makeToasterOutOfBreadError() {
204 return RpcResultBuilder.newError( ErrorType.APPLICATION, "resource-denied",
205 "Toaster is out of bread", "out-of-stock", null, null );
208 private RpcError makeToasterInUseError() {
209 return RpcResultBuilder.newWarning( ErrorType.APPLICATION, "in-use",
210 "Toaster is busy", null, null, null );
213 private void checkStatusAndMakeToast( final MakeToastInput input,
214 final SettableFuture<RpcResult<Void>> futureResult,
217 // Read the ToasterStatus and, if currently Up, try to write the status to Down.
218 // If that succeeds, then we essentially have an exclusive lock and can proceed
221 final ReadWriteTransaction tx = dataProvider.newReadWriteTransaction();
222 ListenableFuture<Optional<Toaster>> readFuture =
223 tx.read( LogicalDatastoreType.OPERATIONAL, TOASTER_IID );
225 final ListenableFuture<Void> commitFuture =
226 Futures.transform( readFuture, new AsyncFunction<Optional<Toaster>,Void>() {
229 public ListenableFuture<Void> apply(
230 final Optional<Toaster> toasterData ) throws Exception {
232 ToasterStatus toasterStatus = ToasterStatus.Up;
233 if( toasterData.isPresent() ) {
234 toasterStatus = toasterData.get().getToasterStatus();
237 LOG.debug( "Read toaster status: {}", toasterStatus );
239 if( toasterStatus == ToasterStatus.Up ) {
242 LOG.debug( "Toaster is out of bread" );
244 return Futures.immediateFailedCheckedFuture(
245 new TransactionCommitFailedException( "", makeToasterOutOfBreadError() ) );
248 LOG.debug( "Setting Toaster status to Down" );
250 // We're not currently making toast - try to update the status to Down
251 // to indicate we're going to make toast. This acts as a lock to prevent
252 // concurrent toasting.
253 tx.put( LogicalDatastoreType.OPERATIONAL, TOASTER_IID,
254 buildToaster( ToasterStatus.Down ) );
258 LOG.debug( "Oops - already making toast!" );
260 // Return an error since we are already making toast. This will get
261 // propagated to the commitFuture below which will interpret the null
262 // TransactionStatus in the RpcResult as an error condition.
263 return Futures.immediateFailedCheckedFuture(
264 new TransactionCommitFailedException( "", makeToasterInUseError() ) );
268 Futures.addCallback( commitFuture, new FutureCallback<Void>() {
270 public void onSuccess( final Void result ) {
272 currentMakeToastTask.set( executor.submit( new MakeToastTask( input, futureResult ) ) );
276 public void onFailure( final Throwable ex ) {
277 if( ex instanceof OptimisticLockFailedException ) {
279 // Another thread is likely trying to make toast simultaneously and updated the
280 // status before us. Try reading the status again - if another make toast is
281 // now in progress, we should get ToasterStatus.Down and fail.
283 if( ( tries - 1 ) > 0 ) {
284 LOG.debug( "Got OptimisticLockFailedException - trying again" );
286 checkStatusAndMakeToast( input, futureResult, tries - 1 );
289 futureResult.set( RpcResultBuilder.<Void> failed()
290 .withError( ErrorType.APPLICATION, ex.getMessage() ).build() );
295 LOG.debug( "Failed to commit Toaster status", ex );
297 // Probably already making toast.
298 futureResult.set( RpcResultBuilder.<Void> failed()
299 .withRpcErrors( ((TransactionCommitFailedException)ex).getErrorList() )
307 * RestConf RPC call implemented from the ToasterService interface.
308 * Restocks the bread for the toaster, resets the toastsMade counter to 0, and sends a
309 * ToasterRestocked notification.
312 public Future<RpcResult<java.lang.Void>> restockToaster(final RestockToasterInput input) {
313 LOG.info( "restockToaster: " + input );
315 amountOfBreadInStock.set( input.getAmountOfBreadToStock() );
317 if( amountOfBreadInStock.get() > 0 ) {
318 ToasterRestocked reStockedNotification = new ToasterRestockedBuilder()
319 .setAmountOfBread( input.getAmountOfBreadToStock() ).build();
320 notificationProvider.offerNotification( reStockedNotification );
323 return Futures.immediateFuture( RpcResultBuilder.<Void> success().build() );
327 * JMX RPC call implemented from the ToasterProviderRuntimeMXBean interface.
330 public void clearToastsMade() {
331 LOG.info( "clearToastsMade" );
336 * Accesssor method implemented from the ToasterProviderRuntimeMXBean interface.
339 public Long getToastsMade() {
340 return toastsMade.get();
343 private void setToasterStatusUp( final Function<Boolean,Void> resultCallback ) {
345 WriteTransaction tx = dataProvider.newWriteOnlyTransaction();
346 tx.put( LogicalDatastoreType.OPERATIONAL,TOASTER_IID, buildToaster( ToasterStatus.Up ) );
348 Futures.addCallback( tx.submit(), new FutureCallback<Void>() {
350 public void onSuccess( final Void result ) {
351 notifyCallback( true );
355 public void onFailure( final Throwable t ) {
356 // We shouldn't get an OptimisticLockFailedException (or any ex) as no
357 // other component should be updating the operational state.
358 LOG.error( "Failed to update toaster status", t );
360 notifyCallback( false );
363 void notifyCallback( final boolean result ) {
364 if( resultCallback != null ) {
365 resultCallback.apply( result );
371 private boolean outOfBread()
373 return amountOfBreadInStock.get() == 0;
376 private class MakeToastTask implements Callable<Void> {
378 final MakeToastInput toastRequest;
379 final SettableFuture<RpcResult<Void>> futureResult;
381 public MakeToastTask( final MakeToastInput toastRequest,
382 final SettableFuture<RpcResult<Void>> futureResult ) {
383 this.toastRequest = toastRequest;
384 this.futureResult = futureResult;
391 // make toast just sleeps for n seconds per doneness level.
392 long darknessFactor = OpendaylightToaster.this.darknessFactor.get();
393 Thread.sleep(darknessFactor * toastRequest.getToasterDoneness());
396 catch( InterruptedException e ) {
397 LOG.info( "Interrupted while making the toast" );
400 toastsMade.incrementAndGet();
402 amountOfBreadInStock.getAndDecrement();
404 LOG.info( "Toaster is out of bread!" );
406 notificationProvider.offerNotification( new ToasterOutOfBreadBuilder().build() );
409 // Set the Toaster status back to up - this essentially releases the toasting lock.
410 // We can't clear the current toast task nor set the Future result until the
411 // update has been committed so we pass a callback to be notified on completion.
413 setToasterStatusUp( new Function<Boolean,Void>() {
415 public Void apply( final Boolean result ) {
417 currentMakeToastTask.set( null );
419 LOG.debug("Toast done");
421 futureResult.set( RpcResultBuilder.<Void>success().build() );