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