Improve segmented journal actor metrics
[controller.git] / opendaylight / md-sal / samples / toaster-consumer / src / main / java / org / opendaylight / controller / sample / kitchen / impl / KitchenServiceImpl.java
1 /*
2  * Copyright (c) 2014, 2015 Brocade Communications 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.kitchen.impl;
9
10 import com.google.common.collect.ImmutableList;
11 import com.google.common.collect.ImmutableList.Builder;
12 import com.google.common.util.concurrent.Futures;
13 import com.google.common.util.concurrent.ListenableFuture;
14 import com.google.common.util.concurrent.MoreExecutors;
15 import java.util.List;
16 import java.util.Set;
17 import java.util.concurrent.ExecutionException;
18 import java.util.concurrent.ExecutorService;
19 import java.util.concurrent.Executors;
20 import javax.annotation.PreDestroy;
21 import javax.inject.Inject;
22 import javax.inject.Singleton;
23 import org.opendaylight.controller.md.sal.common.util.jmx.AbstractMXBean;
24 import org.opendaylight.controller.sample.kitchen.api.EggsType;
25 import org.opendaylight.controller.sample.kitchen.api.KitchenService;
26 import org.opendaylight.controller.sample.kitchen.api.KitchenServiceRuntimeMXBean;
27 import org.opendaylight.mdsal.binding.api.NotificationService;
28 import org.opendaylight.mdsal.binding.api.NotificationService.CompositeListener;
29 import org.opendaylight.mdsal.binding.api.RpcService;
30 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToast;
31 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastInputBuilder;
32 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastOutput;
33 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastOutputBuilder;
34 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToastType;
35 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterOutOfBread;
36 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterRestocked;
37 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.WheatBread;
38 import org.opendaylight.yangtools.concepts.Registration;
39 import org.opendaylight.yangtools.yang.common.ErrorTag;
40 import org.opendaylight.yangtools.yang.common.ErrorType;
41 import org.opendaylight.yangtools.yang.common.RpcError;
42 import org.opendaylight.yangtools.yang.common.RpcResult;
43 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
44 import org.opendaylight.yangtools.yang.common.Uint32;
45 import org.osgi.service.component.annotations.Activate;
46 import org.osgi.service.component.annotations.Component;
47 import org.osgi.service.component.annotations.Deactivate;
48 import org.osgi.service.component.annotations.Reference;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 @Singleton
53 @Component(service = KitchenService.class, immediate = true)
54 public final class KitchenServiceImpl extends AbstractMXBean implements KitchenService, KitchenServiceRuntimeMXBean {
55     private static final Logger LOG = LoggerFactory.getLogger(KitchenServiceImpl.class);
56     private static final MakeToastOutput EMPTY_MAKE_OUTPUT = new MakeToastOutputBuilder().build();
57
58     private final ExecutorService executor = Executors.newCachedThreadPool();
59     private final MakeToast makeToast;
60     private final Registration reg;
61
62     private volatile boolean toasterOutOfBread;
63
64     @Inject
65     @Activate
66     public KitchenServiceImpl(@Reference final RpcService rpcService,
67             @Reference final NotificationService notifService) {
68         super("KitchenService", "toaster-consumer", null);
69         makeToast = rpcService.getRpc(MakeToast.class);
70         reg = notifService.registerCompositeListener(new CompositeListener(Set.of(
71             new CompositeListener.Component<>(ToasterOutOfBread.class, notification -> {
72                 LOG.info("ToasterOutOfBread notification");
73                 toasterOutOfBread = true;
74             }),
75             new CompositeListener.Component<>(ToasterRestocked.class, notification -> {
76                 LOG.info("ToasterRestocked notification - amountOfBread: {}", notification.getAmountOfBread());
77                 toasterOutOfBread = false;
78             }))));
79         register();
80     }
81
82     @PreDestroy
83     @Deactivate
84     public void close() {
85         unregister();
86         reg.close();
87     }
88
89     @Override
90     public ListenableFuture<RpcResult<Void>> makeBreakfast(final EggsType eggsType, final ToastType toastType,
91             final int toastDoneness) {
92         // Call makeToast, The OpendaylightToaster impl already returns a ListenableFuture so the conversion is
93         // actually a no-op.
94
95         ListenableFuture<RpcResult<MakeToastOutput>> makeToastFuture = makeToast(toastType, toastDoneness);
96
97         ListenableFuture<RpcResult<Void>> makeEggsFuture = makeEggs(eggsType);
98
99         // Combine the 2 ListenableFutures into 1 containing a list RpcResults.
100
101         ListenableFuture<List<RpcResult<? extends Object>>> combinedFutures = Futures
102                 .allAsList(ImmutableList.of(makeToastFuture, makeEggsFuture));
103
104         // Then transform the RpcResults into 1.
105
106         return Futures.transformAsync(combinedFutures, results -> {
107             boolean atLeastOneSucceeded = false;
108             Builder<RpcError> errorList = ImmutableList.builder();
109             for (RpcResult<? extends Object> result : results) {
110                 if (result.isSuccessful()) {
111                     atLeastOneSucceeded = true;
112                 }
113
114                 if (result.getErrors() != null) {
115                     errorList.addAll(result.getErrors());
116                 }
117             }
118
119             return RpcResultBuilder.<Void>status(atLeastOneSucceeded).withRpcErrors(errorList.build()).buildFuture();
120         }, MoreExecutors.directExecutor());
121     }
122
123     private ListenableFuture<RpcResult<Void>> makeEggs(final EggsType eggsType) {
124         return Futures.submit(() -> RpcResultBuilder.<Void>success().build(), executor);
125     }
126
127     private ListenableFuture<RpcResult<MakeToastOutput>> makeToast(final ToastType toastType, final int toastDoneness) {
128         if (toasterOutOfBread) {
129             LOG.info("We're out of toast but we can make eggs");
130             return RpcResultBuilder.success(EMPTY_MAKE_OUTPUT)
131                 .withWarning(ErrorType.APPLICATION, ErrorTag.PARTIAL_OPERATION,
132                     "Toaster is out of bread but we can make you eggs")
133                 .buildFuture();
134         }
135
136         // Access the ToasterService to make the toast.
137         return makeToast.invoke(new MakeToastInputBuilder()
138             .setToasterDoneness(Uint32.valueOf(toastDoneness))
139             .setToasterToastType(toastType)
140             .build());
141     }
142
143     @Override
144     public Boolean makeScrambledWithWheat() {
145         try {
146             // This call has to block since we must return a result to the JMX client.
147             RpcResult<Void> result = makeBreakfast(EggsType.SCRAMBLED, WheatBread.VALUE, 2).get();
148             if (result.isSuccessful()) {
149                 LOG.info("makeBreakfast succeeded");
150             } else {
151                 LOG.warn("makeBreakfast failed: {}", result.getErrors());
152             }
153
154             return result.isSuccessful();
155         } catch (InterruptedException | ExecutionException e) {
156             LOG.warn("An error occurred while maing breakfast", e);
157         }
158
159         return Boolean.FALSE;
160     }
161 }