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.Arrays;
11 import java.util.Collections;
12 import java.util.concurrent.Callable;
13 import java.util.concurrent.ExecutionException;
14 import java.util.concurrent.ExecutorService;
15 import java.util.concurrent.Executors;
16 import java.util.concurrent.Future;
17 import java.util.concurrent.atomic.AtomicLong;
19 import org.opendaylight.controller.config.yang.config.toaster_provider.impl.ToasterProviderRuntimeMXBean;
20 import org.opendaylight.controller.md.sal.common.api.data.DataChangeEvent;
21 import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
22 import org.opendaylight.controller.sal.binding.api.data.DataBrokerService;
23 import org.opendaylight.controller.sal.binding.api.data.DataModificationTransaction;
24 import org.opendaylight.controller.sal.common.util.RpcErrors;
25 import org.opendaylight.controller.sal.common.util.Rpcs;
26 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.DisplayString;
27 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastInput;
28 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.Toaster;
29 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.Toaster.ToasterStatus;
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.ToasterBuilder;
32 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterOutOfBreadBuilder;
33 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterRestocked;
34 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterRestockedBuilder;
35 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterService;
36 import org.opendaylight.controller.sal.binding.api.data.DataChangeListener;
37 import org.opendaylight.yangtools.yang.binding.DataObject;
38 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
39 import org.opendaylight.yangtools.yang.common.RpcError;
40 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
41 import org.opendaylight.yangtools.yang.common.RpcResult;
42 import org.opendaylight.yangtools.yang.common.RpcError.ErrorSeverity;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
46 import com.google.common.util.concurrent.Futures;
48 public class OpendaylightToaster implements ToasterService, ToasterProviderRuntimeMXBean,
49 DataChangeListener, AutoCloseable {
51 private static final Logger LOG = LoggerFactory.getLogger(OpendaylightToaster.class);
53 public static final InstanceIdentifier<Toaster> TOASTER_IID = InstanceIdentifier.builder(Toaster.class).build();
55 private static final DisplayString TOASTER_MANUFACTURER = new DisplayString("Opendaylight");
56 private static final DisplayString TOASTER_MODEL_NUMBER = new DisplayString("Model 1 - Binding Aware");
58 private NotificationProviderService notificationProvider;
59 private DataBrokerService dataProvider;
61 private final ExecutorService executor;
63 // As you will see we are using multiple threads here. Therefore we need to be careful about concurrency.
64 // In this case we use the taskLock to provide synchronization for the current task.
65 private volatile Future<RpcResult<Void>> currentTask;
66 private final Object taskLock = new Object();
68 private final AtomicLong amountOfBreadInStock = new AtomicLong( 100 );
70 private final AtomicLong toastsMade = new AtomicLong(0);
72 // Thread safe holder for our darkness multiplier.
73 private final AtomicLong darknessFactor = new AtomicLong( 1000 );
75 public OpendaylightToaster() {
76 executor = Executors.newFixedThreadPool(1);
79 public void setNotificationProvider(NotificationProviderService salService) {
80 this.notificationProvider = salService;
83 public void setDataProvider(DataBrokerService salDataProvider) {
84 this.dataProvider = salDataProvider;
89 * Implemented from the AutoCloseable interface.
92 public void close() throws ExecutionException, InterruptedException {
93 // When we close this service we need to shutdown our executor!
96 if (dataProvider != null) {
97 final DataModificationTransaction t = dataProvider.beginTransaction();
98 t.removeOperationalData(TOASTER_IID);
103 private Toaster buildToaster() {
104 // We don't need to synchronize on currentTask here b/c it's declared volatile and
105 // we're just doing a read.
106 boolean isUp = currentTask == null;
108 // note - we are simulating a device whose manufacture and model are
109 // fixed (embedded) into the hardware.
110 // This is why the manufacture and model number are hardcoded.
111 ToasterBuilder tb = new ToasterBuilder();
112 tb.setToasterManufacturer(TOASTER_MANUFACTURER).setToasterModelNumber(TOASTER_MODEL_NUMBER)
113 .setToasterStatus(isUp ? ToasterStatus.Up : ToasterStatus.Down);
118 * Implemented from the DataChangeListener interface.
121 public void onDataChanged( DataChangeEvent<InstanceIdentifier<?>, DataObject> change ) {
122 DataObject dataObject = change.getUpdatedConfigurationData().get( TOASTER_IID );
123 if( dataObject instanceof Toaster )
125 Toaster toaster = (Toaster) dataObject;
126 Long darkness = toaster.getDarknessFactor();
127 if( darkness != null )
129 darknessFactor.set( darkness );
135 * RestConf RPC call implemented from the ToasterService interface.
138 public Future<RpcResult<Void>> cancelToast() {
139 synchronized (taskLock) {
140 if (currentTask != null) {
141 currentTask.cancel(true);
145 // Always return success from the cancel toast call.
146 return Futures.immediateFuture(Rpcs.<Void> getRpcResult(true, Collections.<RpcError> emptySet()));
150 * RestConf RPC call implemented from the ToasterService interface.
153 public Future<RpcResult<Void>> makeToast(MakeToastInput input) {
154 LOG.info("makeToast: " + input);
156 synchronized (taskLock) {
157 if (currentTask != null) {
158 // return an error since we are already toasting some toast.
159 LOG.info( "Toaster is already making toast" );
161 RpcResult<Void> result = Rpcs.<Void> getRpcResult(false, null, Arrays.asList(
162 RpcErrors.getRpcError( "", "in-use", null, ErrorSeverity.WARNING,
163 "Toaster is busy", ErrorType.APPLICATION, null ) ) );
164 return Futures.immediateFuture(result);
166 else if( outOfBread() ) {
167 RpcResult<Void> result = Rpcs.<Void> getRpcResult(false, null, Arrays.asList(
168 RpcErrors.getRpcError( "out-of-stock", "resource-denied", null, null,
169 "Toaster is out of bread",
170 ErrorType.APPLICATION, null ) ) );
171 return Futures.immediateFuture(result);
174 // Notice that we are moving the actual call to another thread,
175 // allowing this thread to return immediately.
176 // The MD-SAL design encourages asynchronus programming. If the
177 // caller needs to block until the call is
178 // complete then they can leverage the blocking methods on the
180 currentTask = executor.submit(new MakeToastTask(input));
189 * RestConf RPC call implemented from the ToasterService interface.
190 * Restocks the bread for the toaster, resets the toastsMade counter to 0, and sends a
191 * ToasterRestocked notification.
194 public Future<RpcResult<java.lang.Void>> restockToaster(RestockToasterInput input) {
195 LOG.info( "restockToaster: " + input );
197 synchronized( taskLock ) {
198 amountOfBreadInStock.set( input.getAmountOfBreadToStock() );
200 if( amountOfBreadInStock.get() > 0 ) {
201 ToasterRestocked reStockedNotification =
202 new ToasterRestockedBuilder().setAmountOfBread( input.getAmountOfBreadToStock() ).build();
203 notificationProvider.publish( reStockedNotification );
207 return Futures.immediateFuture(Rpcs.<Void> getRpcResult(true, Collections.<RpcError> emptySet()));
211 * JMX RPC call implemented from the ToasterProviderRuntimeMXBean interface.
214 public void clearToastsMade() {
215 LOG.info( "clearToastsMade" );
220 * Accesssor method implemented from the ToasterProviderRuntimeMXBean interface.
223 public Long getToastsMade() {
224 return toastsMade.get();
227 private void updateStatus() {
228 if (dataProvider != null) {
229 final DataModificationTransaction t = dataProvider.beginTransaction();
230 t.removeOperationalData(TOASTER_IID);
231 t.putOperationalData(TOASTER_IID, buildToaster());
235 } catch (InterruptedException | ExecutionException e) {
236 LOG.warn("Failed to update toaster status, operational otherwise", e);
239 LOG.trace("No data provider configured, not updating status");
243 private boolean outOfBread()
245 return amountOfBreadInStock.get() == 0;
248 private class MakeToastTask implements Callable<RpcResult<Void>> {
250 final MakeToastInput toastRequest;
252 public MakeToastTask(MakeToastInput toast) {
253 toastRequest = toast;
257 public RpcResult<Void> call() {
260 // make toast just sleeps for n secondn per doneness level.
261 long darknessFactor = OpendaylightToaster.this.darknessFactor.get();
262 Thread.sleep(darknessFactor * toastRequest.getToasterDoneness());
265 catch( InterruptedException e ) {
266 LOG.info( "Interrupted while making the toast" );
269 toastsMade.incrementAndGet();
271 amountOfBreadInStock.getAndDecrement();
273 LOG.info( "Toaster is out of bread!" );
275 notificationProvider.publish( new ToasterOutOfBreadBuilder().build() );
278 synchronized (taskLock) {
284 LOG.debug("Toast done");
286 return Rpcs.<Void> getRpcResult(true, null, Collections.<RpcError> emptySet());