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.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;
59 public class OpendaylightToaster extends AbstractMXBean implements ToasterService, ToasterProviderRuntimeMXBean,
60 DataTreeChangeListener<Toaster>, AutoCloseable {
62 private static final Logger LOG = LoggerFactory.getLogger(OpendaylightToaster.class);
64 public static final InstanceIdentifier<Toaster> TOASTER_IID = InstanceIdentifier.builder(Toaster.class).build();
66 private static final DisplayString TOASTER_MANUFACTURER = new DisplayString("Opendaylight");
67 private static final DisplayString TOASTER_MODEL_NUMBER = new DisplayString("Model 1 - Binding Aware");
69 private NotificationPublishService notificationProvider;
70 private DataBroker dataProvider;
71 private ListenerRegistration<OpendaylightToaster> dataTreeChangeListenerRegistration;
73 private final ExecutorService executor;
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<>();
79 private final AtomicLong amountOfBreadInStock = new AtomicLong( 100 );
81 private final AtomicLong toastsMade = new AtomicLong(0);
83 // Thread safe holder for our darkness multiplier.
84 private final AtomicLong darknessFactor = new AtomicLong( 1000 );
86 private final ToasterAppConfig toasterAppConfig;
88 public OpendaylightToaster() {
89 this(new ToasterAppConfigBuilder().setManufacturer(TOASTER_MANUFACTURER).setModelNumber(TOASTER_MODEL_NUMBER).
90 setMaxMakeToastTries(2).build());
93 public OpendaylightToaster(ToasterAppConfig toasterAppConfig) {
94 super("OpendaylightToaster", "toaster-provider", null);
95 executor = Executors.newFixedThreadPool(1);
96 this.toasterAppConfig = toasterAppConfig;
99 public void setNotificationProvider(final NotificationPublishService notificationPublishService) {
100 this.notificationProvider = notificationPublishService;
103 public void setDataProvider(final DataBroker salDataProvider) {
104 this.dataProvider = salDataProvider;
106 dataProvider.registerDataTreeChangeListener(new DataTreeIdentifier<Toaster>(
107 LogicalDatastoreType.CONFIGURATION, OpendaylightToaster.TOASTER_IID), this);
109 setToasterStatusUp( null );
113 * Implemented from the AutoCloseable interface.
116 public void close() throws ExecutionException, InterruptedException {
117 // When we close this service we need to shutdown our executor!
120 if (dataProvider != null) {
121 dataTreeChangeListenerRegistration.close();
123 WriteTransaction tx = dataProvider.newWriteOnlyTransaction();
124 tx.delete(LogicalDatastoreType.OPERATIONAL,TOASTER_IID);
125 Futures.addCallback( tx.submit(), new FutureCallback<Void>() {
127 public void onSuccess( final Void result ) {
128 LOG.debug( "Delete Toaster commit result: " + result );
132 public void onFailure( final Throwable t ) {
133 LOG.error( "Delete of Toaster failed", t );
139 private Toaster buildToaster( final ToasterStatus status ) {
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 )
151 * Implemented from the DataTreeChangeListener interface.
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);
163 Long darkness = newToaster.getDarknessFactor();
164 if(darkness != null) {
165 darknessFactor.set(darkness);
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());
175 * RPC call implemented from the ToasterService interface that cancels the current
179 public Future<RpcResult<Void>> cancelToast() {
181 Future<?> current = currentMakeToastTask.getAndSet( null );
182 if( current != null ) {
183 current.cancel( true );
186 // Always return success from the cancel toast call.
187 return Futures.immediateFuture( RpcResultBuilder.<Void> success().build() );
191 * RPC call implemented from the ToasterService interface that attempts to make toast.
194 public Future<RpcResult<Void>> makeToast(final MakeToastInput input) {
195 LOG.info("makeToast: " + input);
197 final SettableFuture<RpcResult<Void>> futureResult = SettableFuture.create();
199 checkStatusAndMakeToast( input, futureResult, toasterAppConfig.getMaxMakeToastTries() );
204 private RpcError makeToasterOutOfBreadError() {
205 return RpcResultBuilder.newError( ErrorType.APPLICATION, "resource-denied",
206 "Toaster is out of bread", "out-of-stock", null, null );
209 private RpcError makeToasterInUseError() {
210 return RpcResultBuilder.newWarning( ErrorType.APPLICATION, "in-use",
211 "Toaster is busy", null, null, null );
214 private void checkStatusAndMakeToast( final MakeToastInput input,
215 final SettableFuture<RpcResult<Void>> futureResult,
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
222 final ReadWriteTransaction tx = dataProvider.newReadWriteTransaction();
223 ListenableFuture<Optional<Toaster>> readFuture =
224 tx.read( LogicalDatastoreType.OPERATIONAL, TOASTER_IID );
226 final ListenableFuture<Void> commitFuture =
227 Futures.transform( readFuture, new AsyncFunction<Optional<Toaster>,Void>() {
230 public ListenableFuture<Void> apply(
231 final Optional<Toaster> toasterData ) throws Exception {
233 ToasterStatus toasterStatus = ToasterStatus.Up;
234 if( toasterData.isPresent() ) {
235 toasterStatus = toasterData.get().getToasterStatus();
238 LOG.debug( "Read toaster status: {}", toasterStatus );
240 if( toasterStatus == ToasterStatus.Up ) {
243 LOG.debug( "Toaster is out of bread" );
245 return Futures.immediateFailedCheckedFuture(
246 new TransactionCommitFailedException( "", makeToasterOutOfBreadError() ) );
249 LOG.debug( "Setting Toaster status to Down" );
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 ) );
259 LOG.debug( "Oops - already making toast!" );
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() ) );
269 Futures.addCallback( commitFuture, new FutureCallback<Void>() {
271 public void onSuccess( final Void result ) {
273 currentMakeToastTask.set( executor.submit( new MakeToastTask( input, futureResult ) ) );
277 public void onFailure( final Throwable ex ) {
278 if( ex instanceof OptimisticLockFailedException ) {
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.
284 if( ( tries - 1 ) > 0 ) {
285 LOG.debug( "Got OptimisticLockFailedException - trying again" );
287 checkStatusAndMakeToast( input, futureResult, tries - 1 );
290 futureResult.set( RpcResultBuilder.<Void> failed()
291 .withError( ErrorType.APPLICATION, ex.getMessage() ).build() );
296 LOG.debug( "Failed to commit Toaster status", ex );
298 // Probably already making toast.
299 futureResult.set( RpcResultBuilder.<Void> failed()
300 .withRpcErrors( ((TransactionCommitFailedException)ex).getErrorList() )
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.
313 public Future<RpcResult<java.lang.Void>> restockToaster(final RestockToasterInput input) {
314 LOG.info( "restockToaster: " + input );
316 amountOfBreadInStock.set( input.getAmountOfBreadToStock() );
318 if( amountOfBreadInStock.get() > 0 ) {
319 ToasterRestocked reStockedNotification = new ToasterRestockedBuilder()
320 .setAmountOfBread( input.getAmountOfBreadToStock() ).build();
321 notificationProvider.offerNotification( reStockedNotification );
324 return Futures.immediateFuture( RpcResultBuilder.<Void> success().build() );
328 * JMX RPC call implemented from the ToasterProviderRuntimeMXBean interface.
331 public void clearToastsMade() {
332 LOG.info( "clearToastsMade" );
337 * Accesssor method implemented from the ToasterProviderRuntimeMXBean interface.
340 public Long getToastsMade() {
341 return toastsMade.get();
344 private void setToasterStatusUp( final Function<Boolean,Void> resultCallback ) {
346 WriteTransaction tx = dataProvider.newWriteOnlyTransaction();
347 tx.put( LogicalDatastoreType.OPERATIONAL,TOASTER_IID, buildToaster( ToasterStatus.Up ) );
349 Futures.addCallback( tx.submit(), new FutureCallback<Void>() {
351 public void onSuccess( final Void result ) {
352 notifyCallback( true );
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 );
361 notifyCallback( false );
364 void notifyCallback( final boolean result ) {
365 if( resultCallback != null ) {
366 resultCallback.apply( result );
372 private boolean outOfBread()
374 return amountOfBreadInStock.get() == 0;
377 private class MakeToastTask implements Callable<Void> {
379 final MakeToastInput toastRequest;
380 final SettableFuture<RpcResult<Void>> futureResult;
382 public MakeToastTask( final MakeToastInput toastRequest,
383 final SettableFuture<RpcResult<Void>> futureResult ) {
384 this.toastRequest = toastRequest;
385 this.futureResult = futureResult;
392 // make toast just sleeps for n seconds per doneness level.
393 long darknessFactor = OpendaylightToaster.this.darknessFactor.get();
394 Thread.sleep(darknessFactor * toastRequest.getToasterDoneness());
397 catch( InterruptedException e ) {
398 LOG.info( "Interrupted while making the toast" );
401 toastsMade.incrementAndGet();
403 amountOfBreadInStock.getAndDecrement();
405 LOG.info( "Toaster is out of bread!" );
407 notificationProvider.offerNotification( new ToasterOutOfBreadBuilder().build() );
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.
414 setToasterStatusUp( new Function<Boolean,Void>() {
416 public Void apply( final Boolean result ) {
418 currentMakeToastTask.set( null );
420 LOG.debug("Toast done");
422 futureResult.set( RpcResultBuilder.<Void>success().build() );