Merge "Bug 1029: Remove dead code: sal-dom-it"
[controller.git] / opendaylight / md-sal / samples / toaster-provider / src / main / java / org / opendaylight / controller / sample / toaster / provider / OpendaylightToaster.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.sample.toaster.provider;
9
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;
18
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;
45
46 import com.google.common.util.concurrent.Futures;
47
48 public class OpendaylightToaster implements ToasterService, ToasterProviderRuntimeMXBean,
49                                             DataChangeListener, AutoCloseable {
50
51     private static final Logger LOG = LoggerFactory.getLogger(OpendaylightToaster.class);
52
53     public static final InstanceIdentifier<Toaster> TOASTER_IID = InstanceIdentifier.builder(Toaster.class).build();
54
55     private static final DisplayString TOASTER_MANUFACTURER = new DisplayString("Opendaylight");
56     private static final DisplayString TOASTER_MODEL_NUMBER = new DisplayString("Model 1 - Binding Aware");
57
58     private NotificationProviderService notificationProvider;
59     private DataBrokerService dataProvider;
60
61     private final ExecutorService executor;
62
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();
67
68     private final AtomicLong amountOfBreadInStock = new AtomicLong( 100 );
69
70     private final AtomicLong toastsMade = new AtomicLong(0);
71
72     // Thread safe holder for our darkness multiplier.
73     private final AtomicLong darknessFactor = new AtomicLong( 1000 );
74
75     public OpendaylightToaster() {
76         executor = Executors.newFixedThreadPool(1);
77     }
78
79     public void setNotificationProvider(NotificationProviderService salService) {
80         this.notificationProvider = salService;
81     }
82
83     public void setDataProvider(DataBrokerService salDataProvider) {
84         this.dataProvider = salDataProvider;
85         updateStatus();
86     }
87
88     /**
89      * Implemented from the AutoCloseable interface.
90      */
91     @Override
92     public void close() throws ExecutionException, InterruptedException {
93         // When we close this service we need to shutdown our executor!
94         executor.shutdown();
95
96         if (dataProvider != null) {
97             final DataModificationTransaction t = dataProvider.beginTransaction();
98             t.removeOperationalData(TOASTER_IID);
99             t.commit().get();
100         }
101     }
102
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;
107
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);
114         return tb.build();
115     }
116
117     /**
118      * Implemented from the DataChangeListener interface.
119      */
120     @Override
121     public void onDataChanged( DataChangeEvent<InstanceIdentifier<?>, DataObject> change ) {
122         DataObject dataObject = change.getUpdatedConfigurationData().get( TOASTER_IID );
123         if( dataObject instanceof Toaster )
124         {
125             Toaster toaster = (Toaster) dataObject;
126             Long darkness = toaster.getDarknessFactor();
127             if( darkness != null )
128             {
129                 darknessFactor.set( darkness );
130             }
131         }
132     }
133
134     /**
135      * RestConf RPC call implemented from the ToasterService interface.
136      */
137     @Override
138     public Future<RpcResult<Void>> cancelToast() {
139         synchronized (taskLock) {
140             if (currentTask != null) {
141                 currentTask.cancel(true);
142                 currentTask = null;
143             }
144         }
145         // Always return success from the cancel toast call.
146         return Futures.immediateFuture(Rpcs.<Void> getRpcResult(true, Collections.<RpcError> emptySet()));
147     }
148
149     /**
150      * RestConf RPC call implemented from the ToasterService interface.
151      */
152     @Override
153     public Future<RpcResult<Void>> makeToast(MakeToastInput input) {
154         LOG.info("makeToast: " + input);
155
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" );
160
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);
165             }
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);
172             }
173             else {
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
179                 // Future interface.
180                 currentTask = executor.submit(new MakeToastTask(input));
181             }
182         }
183
184         updateStatus();
185         return currentTask;
186     }
187
188     /**
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.
192      */
193     @Override
194     public Future<RpcResult<java.lang.Void>> restockToaster(RestockToasterInput input) {
195         LOG.info( "restockToaster: " + input );
196
197         synchronized( taskLock ) {
198             amountOfBreadInStock.set( input.getAmountOfBreadToStock() );
199
200             if( amountOfBreadInStock.get() > 0 ) {
201                 ToasterRestocked reStockedNotification =
202                     new ToasterRestockedBuilder().setAmountOfBread( input.getAmountOfBreadToStock() ).build();
203                 notificationProvider.publish( reStockedNotification );
204             }
205         }
206
207         return Futures.immediateFuture(Rpcs.<Void> getRpcResult(true, Collections.<RpcError> emptySet()));
208     }
209
210     /**
211      * JMX RPC call implemented from the ToasterProviderRuntimeMXBean interface.
212      */
213     @Override
214     public void clearToastsMade() {
215         LOG.info( "clearToastsMade" );
216         toastsMade.set( 0 );
217     }
218
219     /**
220      * Accesssor method implemented from the ToasterProviderRuntimeMXBean interface.
221      */
222     @Override
223     public Long getToastsMade() {
224         return toastsMade.get();
225     }
226
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());
232
233             try {
234                 t.commit().get();
235             } catch (InterruptedException | ExecutionException e) {
236                 LOG.warn("Failed to update toaster status, operational otherwise", e);
237             }
238         } else {
239             LOG.trace("No data provider configured, not updating status");
240         }
241     }
242
243     private boolean outOfBread()
244     {
245         return amountOfBreadInStock.get() == 0;
246     }
247
248     private class MakeToastTask implements Callable<RpcResult<Void>> {
249
250         final MakeToastInput toastRequest;
251
252         public MakeToastTask(MakeToastInput toast) {
253             toastRequest = toast;
254         }
255
256         @Override
257         public RpcResult<Void> call() {
258             try
259             {
260                 // make toast just sleeps for n secondn per doneness level.
261                 long darknessFactor = OpendaylightToaster.this.darknessFactor.get();
262                 Thread.sleep(darknessFactor * toastRequest.getToasterDoneness());
263
264             }
265             catch( InterruptedException e ) {
266                 LOG.info( "Interrupted while making the toast" );
267             }
268
269             toastsMade.incrementAndGet();
270
271             amountOfBreadInStock.getAndDecrement();
272             if( outOfBread() ) {
273                 LOG.info( "Toaster is out of bread!" );
274
275                 notificationProvider.publish( new ToasterOutOfBreadBuilder().build() );
276             }
277
278             synchronized (taskLock) {
279                 currentTask = null;
280             }
281
282             updateStatus();
283
284             LOG.debug("Toast done");
285
286             return Rpcs.<Void> getRpcResult(true, null, Collections.<RpcError> emptySet());
287         }
288     }
289 }