Migrate toaster-producer to OSGi DS
[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 static java.util.Objects.requireNonNull;
11 import static org.opendaylight.mdsal.binding.api.DataObjectModification.ModificationType.DELETE;
12 import static org.opendaylight.mdsal.binding.api.DataObjectModification.ModificationType.WRITE;
13 import static org.opendaylight.mdsal.common.api.LogicalDatastoreType.CONFIGURATION;
14 import static org.opendaylight.mdsal.common.api.LogicalDatastoreType.OPERATIONAL;
15 import static org.opendaylight.yangtools.yang.common.ErrorType.APPLICATION;
16
17 import com.google.common.util.concurrent.FluentFuture;
18 import com.google.common.util.concurrent.FutureCallback;
19 import com.google.common.util.concurrent.Futures;
20 import com.google.common.util.concurrent.ListenableFuture;
21 import com.google.common.util.concurrent.MoreExecutors;
22 import com.google.common.util.concurrent.SettableFuture;
23 import java.util.Collection;
24 import java.util.Optional;
25 import java.util.concurrent.Callable;
26 import java.util.concurrent.ExecutionException;
27 import java.util.concurrent.ExecutorService;
28 import java.util.concurrent.Executors;
29 import java.util.concurrent.Future;
30 import java.util.concurrent.atomic.AtomicLong;
31 import java.util.concurrent.atomic.AtomicReference;
32 import java.util.function.Function;
33 import javax.annotation.PreDestroy;
34 import javax.inject.Inject;
35 import javax.inject.Singleton;
36 import org.eclipse.jdt.annotation.NonNull;
37 import org.opendaylight.controller.md.sal.common.util.jmx.AbstractMXBean;
38 import org.opendaylight.mdsal.binding.api.DataBroker;
39 import org.opendaylight.mdsal.binding.api.DataObjectModification;
40 import org.opendaylight.mdsal.binding.api.DataTreeChangeListener;
41 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
42 import org.opendaylight.mdsal.binding.api.DataTreeModification;
43 import org.opendaylight.mdsal.binding.api.NotificationPublishService;
44 import org.opendaylight.mdsal.binding.api.ReadWriteTransaction;
45 import org.opendaylight.mdsal.binding.api.RpcProviderService;
46 import org.opendaylight.mdsal.binding.api.WriteTransaction;
47 import org.opendaylight.mdsal.common.api.CommitInfo;
48 import org.opendaylight.mdsal.common.api.OptimisticLockFailedException;
49 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
50 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.CancelToastInput;
51 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.CancelToastOutput;
52 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.CancelToastOutputBuilder;
53 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.DisplayString;
54 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastInput;
55 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastOutput;
56 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastOutputBuilder;
57 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.RestockToasterInput;
58 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.RestockToasterOutput;
59 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.RestockToasterOutputBuilder;
60 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.Toaster;
61 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.Toaster.ToasterStatus;
62 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterBuilder;
63 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterOutOfBreadBuilder;
64 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterRestocked;
65 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterRestockedBuilder;
66 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterService;
67 import org.opendaylight.yangtools.concepts.ListenerRegistration;
68 import org.opendaylight.yangtools.concepts.Registration;
69 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
70 import org.opendaylight.yangtools.yang.common.ErrorTag;
71 import org.opendaylight.yangtools.yang.common.ErrorType;
72 import org.opendaylight.yangtools.yang.common.RpcError;
73 import org.opendaylight.yangtools.yang.common.RpcResult;
74 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
75 import org.opendaylight.yangtools.yang.common.Uint32;
76 import org.osgi.service.component.annotations.Activate;
77 import org.osgi.service.component.annotations.Component;
78 import org.osgi.service.component.annotations.Deactivate;
79 import org.osgi.service.component.annotations.Reference;
80 import org.osgi.service.metatype.annotations.AttributeDefinition;
81 import org.osgi.service.metatype.annotations.Designate;
82 import org.osgi.service.metatype.annotations.ObjectClassDefinition;
83 import org.slf4j.Logger;
84 import org.slf4j.LoggerFactory;
85
86 @Singleton
87 @Component(service = ToasterService.class, immediate = true)
88 @Designate(ocd = OpendaylightToaster.Configuration.class)
89 public final class OpendaylightToaster extends AbstractMXBean
90         implements ToasterService, ToasterProviderRuntimeMXBean, DataTreeChangeListener<Toaster>, AutoCloseable {
91     @ObjectClassDefinition
92     public @interface Configuration {
93         @AttributeDefinition(description = "The name of the toaster's manufacturer", max = "255")
94         String manufacturer() default TOASTER_MANUFACTURER;
95         @AttributeDefinition(description = "The name of the toaster's model", max = "255")
96         String modelNumber() default TOASTER_MODEL_NUMBER;
97         @AttributeDefinition(description = "How many times we attempt to make toast before failing ",
98             min = "0", max = "65535")
99         int maxMakeToastTries() default 2;
100     }
101
102     private static final CancelToastOutput EMPTY_CANCEL_OUTPUT = new CancelToastOutputBuilder().build();
103     private static final MakeToastOutput EMPTY_MAKE_OUTPUT = new MakeToastOutputBuilder().build();
104     private static final RestockToasterOutput EMPTY_RESTOCK_OUTPUT = new RestockToasterOutputBuilder().build();
105
106     private static final Logger LOG = LoggerFactory.getLogger(OpendaylightToaster.class);
107
108     private static final InstanceIdentifier<Toaster> TOASTER_IID = InstanceIdentifier.builder(Toaster.class).build();
109     private static final String TOASTER_MANUFACTURER = "Opendaylight";
110     private static final String TOASTER_MODEL_NUMBER = "Model 1 - Binding Aware";
111
112     private final DataBroker dataBroker;
113     private final NotificationPublishService notificationProvider;
114     private final ListenerRegistration<OpendaylightToaster> dataTreeChangeListenerRegistration;
115     private final Registration reg;
116
117     private final ExecutorService executor;
118
119     // This holds the Future for the current make toast task and is used to cancel the current toast.
120     private final AtomicReference<Future<?>> currentMakeToastTask = new AtomicReference<>();
121
122     // Thread safe holders
123     private final AtomicLong amountOfBreadInStock = new AtomicLong(100);
124     private final AtomicLong toastsMade = new AtomicLong(0);
125     private final AtomicLong darknessFactor = new AtomicLong(1000);
126
127     private final @NonNull DisplayString manufacturer;
128     private final @NonNull DisplayString modelNumber;
129     private final int maxMakeToastTries;
130
131     public OpendaylightToaster(final DataBroker dataProvider,
132             final NotificationPublishService notificationPublishService, final RpcProviderService rpcProviderService,
133             final String manufacturer, final String modelNumber, final int maxMakeToastTries) {
134         super("OpendaylightToaster", "toaster-provider", null);
135         notificationProvider = requireNonNull(notificationPublishService);
136         dataBroker = requireNonNull(dataProvider);
137
138         this.manufacturer = new DisplayString(manufacturer);
139         this.modelNumber = new DisplayString(modelNumber);
140         this.maxMakeToastTries = maxMakeToastTries;
141
142         executor = Executors.newFixedThreadPool(1);
143         reg = rpcProviderService.registerRpcImplementation(ToasterService.class, this);
144
145         LOG.info("Initializing...");
146
147         dataTreeChangeListenerRegistration = requireNonNull(dataBroker, "dataBroker must be set")
148             .registerDataTreeChangeListener(DataTreeIdentifier.create(CONFIGURATION, TOASTER_IID), this);
149         try {
150             setToasterStatusUp(null).get();
151         } catch (InterruptedException | ExecutionException e) {
152             throw new IllegalStateException("Failed to commit initial data", e);
153         }
154
155         // Register our MXBean.
156         register();
157     }
158
159     @Inject
160     public OpendaylightToaster(final DataBroker dataProvider,
161             final NotificationPublishService notificationPublishService, final RpcProviderService rpcProviderService) {
162         this(dataProvider, notificationPublishService, rpcProviderService, TOASTER_MANUFACTURER, TOASTER_MODEL_NUMBER,
163             2);
164     }
165
166     @Activate
167     public OpendaylightToaster(@Reference final DataBroker dataProvider,
168             @Reference final NotificationPublishService notificationPublishService,
169             @Reference final RpcProviderService rpcProviderService, final @NonNull Configuration configuration) {
170         this(dataProvider, notificationPublishService, rpcProviderService, configuration.manufacturer(),
171             configuration.modelNumber(), configuration.maxMakeToastTries());
172     }
173
174     /**
175      * Implemented from the AutoCloseable interface.
176      */
177     @Override
178     @PreDestroy
179     @Deactivate
180     public void close() {
181         LOG.info("Closing...");
182
183         // Unregister our MXBean.
184         unregister();
185         reg.close();
186
187         // When we close this service we need to shutdown our executor!
188         executor.shutdown();
189
190         if (dataTreeChangeListenerRegistration != null) {
191             dataTreeChangeListenerRegistration.close();
192         }
193
194         if (dataBroker != null) {
195             WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
196             tx.delete(OPERATIONAL,TOASTER_IID);
197             Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
198                 @Override
199                 public void onSuccess(final CommitInfo result) {
200                     LOG.debug("Successfully deleted the operational Toaster");
201                 }
202
203                 @Override
204                 public void onFailure(final Throwable failure) {
205                     LOG.error("Delete of the operational Toaster failed", failure);
206                 }
207             }, MoreExecutors.directExecutor());
208         }
209     }
210
211     private Toaster buildToaster(final ToasterStatus status) {
212         // note - we are simulating a device whose manufacture and model are
213         // fixed (embedded) into the hardware.
214         // This is why the manufacture and model number are hardcoded.
215         return new ToasterBuilder()
216             .setToasterManufacturer(manufacturer)
217             .setToasterModelNumber(modelNumber)
218             .setToasterStatus(status)
219             .build();
220     }
221
222     /**
223      * Implemented from the DataTreeChangeListener interface.
224      */
225     @Override
226     public void onDataTreeChanged(final Collection<DataTreeModification<Toaster>> changes) {
227         for (DataTreeModification<Toaster> change: changes) {
228             DataObjectModification<Toaster> rootNode = change.getRootNode();
229             if (rootNode.getModificationType() == WRITE) {
230                 Toaster oldToaster = rootNode.getDataBefore();
231                 Toaster newToaster = rootNode.getDataAfter();
232                 LOG.info("onDataTreeChanged - Toaster config with path {} was added or replaced: "
233                         + "old Toaster: {}, new Toaster: {}", change.getRootPath().getRootIdentifier(),
234                         oldToaster, newToaster);
235
236                 Uint32 darkness = newToaster.getDarknessFactor();
237                 if (darkness != null) {
238                     darknessFactor.set(darkness.toJava());
239                 }
240             } else if (rootNode.getModificationType() == DELETE) {
241                 LOG.info("onDataTreeChanged - Toaster config with path {} was deleted: old Toaster: {}",
242                         change.getRootPath().getRootIdentifier(), rootNode.getDataBefore());
243             }
244         }
245     }
246
247     /**
248      * RPC call implemented from the ToasterService interface that cancels the current toast, if any.
249      */
250     @Override
251     public ListenableFuture<RpcResult<CancelToastOutput>> cancelToast(final CancelToastInput input) {
252         Future<?> current = currentMakeToastTask.getAndSet(null);
253         if (current != null) {
254             current.cancel(true);
255         }
256
257         // Always return success from the cancel toast call
258         return Futures.immediateFuture(RpcResultBuilder.success(EMPTY_CANCEL_OUTPUT).build());
259     }
260
261     /**
262      * RPC call implemented from the ToasterService interface that attempts to make toast.
263      */
264     @Override
265     public ListenableFuture<RpcResult<MakeToastOutput>> makeToast(final MakeToastInput input) {
266         LOG.info("makeToast: {}", input);
267
268         final SettableFuture<RpcResult<MakeToastOutput>> futureResult = SettableFuture.create();
269
270         checkStatusAndMakeToast(input, futureResult, maxMakeToastTries);
271
272         return futureResult;
273     }
274
275     private static RpcError makeToasterOutOfBreadError() {
276         return RpcResultBuilder.newError(APPLICATION, ErrorTag.RESOURCE_DENIED, "Toaster is out of bread",
277             "out-of-stock", null, null);
278     }
279
280     private static RpcError makeToasterInUseError() {
281         return RpcResultBuilder.newWarning(APPLICATION, ErrorTag.IN_USE, "Toaster is busy", null, null, null);
282     }
283
284     private void checkStatusAndMakeToast(final MakeToastInput input,
285             final SettableFuture<RpcResult<MakeToastOutput>> futureResult, final int tries) {
286         // Read the ToasterStatus and, if currently Up, try to write the status to Down.
287         // If that succeeds, then we essentially have an exclusive lock and can proceed
288         // to make toast.
289         final ReadWriteTransaction tx = dataBroker.newReadWriteTransaction();
290         FluentFuture<Optional<Toaster>> readFuture = tx.read(OPERATIONAL, TOASTER_IID);
291
292         final ListenableFuture<? extends CommitInfo> commitFuture =
293             Futures.transformAsync(readFuture, toasterData -> {
294                 ToasterStatus toasterStatus = ToasterStatus.Up;
295                 if (toasterData.isPresent()) {
296                     toasterStatus = toasterData.get().getToasterStatus();
297                 }
298
299                 LOG.debug("Read toaster status: {}", toasterStatus);
300
301                 if (toasterStatus == ToasterStatus.Up) {
302
303                     if (outOfBread()) {
304                         LOG.debug("Toaster is out of bread");
305                         tx.cancel();
306                         return Futures.immediateFailedFuture(
307                                 new TransactionCommitFailedException("", makeToasterOutOfBreadError()));
308                     }
309
310                     LOG.debug("Setting Toaster status to Down");
311
312                     // We're not currently making toast - try to update the status to Down
313                     // to indicate we're going to make toast. This acts as a lock to prevent
314                     // concurrent toasting.
315                     tx.put(OPERATIONAL, TOASTER_IID, buildToaster(ToasterStatus.Down));
316                     return tx.commit();
317                 }
318
319                 LOG.debug("Oops - already making toast!");
320
321                 // Return an error since we are already making toast. This will get
322                 // propagated to the commitFuture below which will interpret the null
323                 // TransactionStatus in the RpcResult as an error condition.
324                 tx.cancel();
325                 return Futures.immediateFailedFuture(
326                         new TransactionCommitFailedException("", makeToasterInUseError()));
327             }, MoreExecutors.directExecutor());
328
329         Futures.addCallback(commitFuture, new FutureCallback<CommitInfo>() {
330             @Override
331             public void onSuccess(final CommitInfo result) {
332                 // OK to make toast
333                 currentMakeToastTask.set(executor.submit(new MakeToastTask(input, futureResult)));
334             }
335
336             @Override
337             public void onFailure(final Throwable ex) {
338                 if (ex instanceof OptimisticLockFailedException) {
339
340                     // Another thread is likely trying to make toast simultaneously and updated the
341                     // status before us. Try reading the status again - if another make toast is
342                     // now in progress, we should get ToasterStatus.Down and fail.
343
344                     if (tries - 1 > 0) {
345                         LOG.debug("Got OptimisticLockFailedException - trying again");
346                         checkStatusAndMakeToast(input, futureResult, tries - 1);
347                     } else {
348                         futureResult.set(RpcResultBuilder.<MakeToastOutput>failed()
349                                 .withError(ErrorType.APPLICATION, ex.getMessage()).build());
350                     }
351                 } else if (ex instanceof TransactionCommitFailedException) {
352                     LOG.debug("Failed to commit Toaster status", ex);
353
354                     // Probably already making toast.
355                     futureResult.set(RpcResultBuilder.<MakeToastOutput>failed()
356                             .withRpcErrors(((TransactionCommitFailedException)ex).getErrorList()).build());
357                 } else {
358                     LOG.debug("Unexpected error committing Toaster status", ex);
359                     futureResult.set(RpcResultBuilder.<MakeToastOutput>failed().withError(ErrorType.APPLICATION,
360                             "Unexpected error committing Toaster status", ex).build());
361                 }
362             }
363         }, MoreExecutors.directExecutor());
364     }
365
366     /**
367      * RestConf RPC call implemented from the ToasterService interface.
368      * Restocks the bread for the toaster, resets the toastsMade counter to 0, and sends a
369      * ToasterRestocked notification.
370      */
371     @Override
372     public ListenableFuture<RpcResult<RestockToasterOutput>> restockToaster(final RestockToasterInput input) {
373         LOG.info("restockToaster: {}", input);
374
375         amountOfBreadInStock.set(input.getAmountOfBreadToStock().toJava());
376
377         if (amountOfBreadInStock.get() > 0) {
378             ToasterRestocked reStockedNotification = new ToasterRestockedBuilder()
379                     .setAmountOfBread(input.getAmountOfBreadToStock()).build();
380             notificationProvider.offerNotification(reStockedNotification);
381         }
382
383         return Futures.immediateFuture(RpcResultBuilder.success(EMPTY_RESTOCK_OUTPUT).build());
384     }
385
386     /**
387      * JMX RPC call implemented from the ToasterProviderRuntimeMXBean interface.
388      */
389     @Override
390     public void clearToastsMade() {
391         LOG.info("clearToastsMade");
392         toastsMade.set(0);
393     }
394
395     /**
396      * Accesssor method implemented from the ToasterProviderRuntimeMXBean interface.
397      */
398     @Override
399     public Long getToastsMade() {
400         return toastsMade.get();
401     }
402
403     private ListenableFuture<?> setToasterStatusUp(final Function<Boolean, MakeToastOutput> resultCallback) {
404         WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
405         tx.put(OPERATIONAL,TOASTER_IID, buildToaster(ToasterStatus.Up));
406
407         final var future = tx.commit();
408         Futures.addCallback(future, new FutureCallback<CommitInfo>() {
409             @Override
410             public void onSuccess(final CommitInfo result) {
411                 LOG.info("Successfully set ToasterStatus to Up");
412                 notifyCallback(true);
413             }
414
415             @Override
416             public void onFailure(final Throwable failure) {
417                 // We shouldn't get an OptimisticLockFailedException (or any ex) as no
418                 // other component should be updating the operational state.
419                 LOG.error("Failed to update toaster status", failure);
420
421                 notifyCallback(false);
422             }
423
424             void notifyCallback(final boolean result) {
425                 if (resultCallback != null) {
426                     resultCallback.apply(result);
427                 }
428             }
429         }, MoreExecutors.directExecutor());
430
431         return future;
432     }
433
434     private boolean outOfBread() {
435         return amountOfBreadInStock.get() == 0;
436     }
437
438     private class MakeToastTask implements Callable<Void> {
439
440         final MakeToastInput toastRequest;
441         final SettableFuture<RpcResult<MakeToastOutput>> futureResult;
442
443         MakeToastTask(final MakeToastInput toastRequest,
444             final SettableFuture<RpcResult<MakeToastOutput>> futureResult) {
445             this.toastRequest = toastRequest;
446             this.futureResult = futureResult;
447         }
448
449         @Override
450         public Void call() {
451             try {
452                 // make toast just sleeps for n seconds per doneness level.
453                 Thread.sleep(darknessFactor.get()
454                         * toastRequest.getToasterDoneness().toJava());
455
456             } catch (InterruptedException e) {
457                 LOG.info("Interrupted while making the toast");
458             }
459
460             toastsMade.incrementAndGet();
461
462             amountOfBreadInStock.getAndDecrement();
463             if (outOfBread()) {
464                 LOG.info("Toaster is out of bread!");
465
466                 notificationProvider.offerNotification(new ToasterOutOfBreadBuilder().build());
467             }
468
469             // Set the Toaster status back to up - this essentially releases the toasting lock.
470             // We can't clear the current toast task nor set the Future result until the
471             // update has been committed so we pass a callback to be notified on completion.
472
473             setToasterStatusUp(result -> {
474                 currentMakeToastTask.set(null);
475                 LOG.debug("Toast done");
476                 futureResult.set(RpcResultBuilder.success(EMPTY_MAKE_OUTPUT).build());
477                 return null;
478             });
479
480             return null;
481         }
482     }
483 }