Adjust for Binding RPC codegen changes
[controller.git] / opendaylight / md-sal / samples / clustering-test-app / provider / src / main / java / org / opendaylight / controller / clustering / it / provider / CarProvider.java
1 /*
2  * Copyright (c) 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.clustering.it.provider;
9
10 import com.google.common.base.Stopwatch;
11 import com.google.common.collect.Sets;
12 import com.google.common.util.concurrent.CheckedFuture;
13 import com.google.common.util.concurrent.FutureCallback;
14 import com.google.common.util.concurrent.Futures;
15 import com.google.common.util.concurrent.ListenableFuture;
16 import com.google.common.util.concurrent.MoreExecutors;
17 import java.util.Collection;
18 import java.util.concurrent.TimeUnit;
19 import java.util.concurrent.TimeoutException;
20 import java.util.concurrent.atomic.AtomicBoolean;
21 import java.util.concurrent.atomic.AtomicLong;
22 import java.util.concurrent.atomic.AtomicReference;
23 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
24 import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
25 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
26 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
27 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
28 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
29 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeCommitCohortRegistry;
30 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistration;
31 import org.opendaylight.mdsal.eos.binding.api.Entity;
32 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipChange;
33 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipListener;
34 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipService;
35 import org.opendaylight.mdsal.eos.common.api.CandidateAlreadyRegisteredException;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.CarId;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.CarService;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.Cars;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.CarsBuilder;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterCommitCohortInput;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterCommitCohortOutput;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterCommitCohortOutputBuilder;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterLoggingDtclInput;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterLoggingDtclOutput;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterLoggingDtclOutputBuilder;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterOwnershipInput;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterOwnershipOutput;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterOwnershipOutputBuilder;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StopStressTestInput;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StopStressTestOutput;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StopStressTestOutputBuilder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StressTestInput;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StressTestOutput;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StressTestOutputBuilder;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterCommitCohortInput;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterCommitCohortOutput;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterCommitCohortOutputBuilder;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterLoggingDtclsInput;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterLoggingDtclsOutput;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterLoggingDtclsOutputBuilder;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterOwnershipInput;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterOwnershipOutput;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterOwnershipOutputBuilder;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.cars.CarEntry;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.cars.CarEntryBuilder;
66 import org.opendaylight.yangtools.concepts.ListenerRegistration;
67 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
68 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
69 import org.opendaylight.yangtools.yang.common.RpcResult;
70 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
71 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
72 import org.slf4j.Logger;
73 import org.slf4j.LoggerFactory;
74
75 /**
76  * Implementation of CarService.
77  *
78  * @author Thomas Pantelis
79  */
80 public class CarProvider implements CarService {
81     private static final Logger LOG_PURCHASE_CAR = LoggerFactory.getLogger(PurchaseCarProvider.class);
82
83     private static final Logger LOG_CAR_PROVIDER = LoggerFactory.getLogger(CarProvider.class);
84
85     private static final String ENTITY_TYPE = "cars";
86     private static final InstanceIdentifier<Cars> CARS_IID = InstanceIdentifier.builder(Cars.class).build();
87     private static final DataTreeIdentifier<Cars> CARS_DTID = new DataTreeIdentifier<>(
88             LogicalDatastoreType.CONFIGURATION, CARS_IID);
89
90     private final DataBroker dataProvider;
91     private final DOMDataBroker domDataBroker;
92     private final EntityOwnershipService ownershipService;
93     private final AtomicLong succcessCounter = new AtomicLong();
94     private final AtomicLong failureCounter = new AtomicLong();
95
96     private final CarEntityOwnershipListener ownershipListener = new CarEntityOwnershipListener();
97     private final AtomicBoolean registeredListener = new AtomicBoolean();
98
99     private final Collection<ListenerRegistration<?>> carsDclRegistrations =
100             Sets.newConcurrentHashSet();
101     private final Collection<ListenerRegistration<CarDataTreeChangeListener>> carsDtclRegistrations =
102             Sets.newConcurrentHashSet();
103
104     private volatile Thread testThread;
105     private volatile boolean stopThread;
106     private final AtomicReference<DOMDataTreeCommitCohortRegistration<CarEntryDataTreeCommitCohort>> commitCohortReg =
107             new AtomicReference<>();
108
109     public CarProvider(final DataBroker dataProvider, final EntityOwnershipService ownershipService,
110             final DOMDataBroker domDataBroker) {
111         this.dataProvider = dataProvider;
112         this.ownershipService = ownershipService;
113         this.domDataBroker = domDataBroker;
114     }
115
116     public void close() {
117         stopThread();
118         closeCommitCohortRegistration();
119     }
120
121     private void stopThread() {
122         if (testThread != null) {
123             stopThread = true;
124             testThread.interrupt();
125             try {
126                 testThread.join();
127             } catch (InterruptedException e) {
128                 // don't care
129             }
130             testThread = null;
131         }
132     }
133
134     @Override
135     public ListenableFuture<RpcResult<StressTestOutput>> stressTest(final StressTestInput input) {
136         final int inputRate;
137         final long inputCount;
138
139         // If rate is not provided, or given as zero, then just return.
140         if (input.getRate() == null || input.getRate() == 0) {
141             LOG_PURCHASE_CAR.info("Exiting stress test as no rate is given.");
142             return Futures.immediateFuture(RpcResultBuilder.<StressTestOutput>failed()
143                     .withError(ErrorType.PROTOCOL, "invalid rate")
144                     .build());
145         }
146
147         inputRate = input.getRate();
148         if (input.getCount() != null) {
149             inputCount = input.getCount();
150         } else {
151             inputCount = 0;
152         }
153
154         LOG_PURCHASE_CAR.info("Stress test starting : rate: {} count: {}", inputRate, inputCount);
155
156         stopThread();
157         // clear counters
158         succcessCounter.set(0);
159         failureCounter.set(0);
160
161         WriteTransaction tx = dataProvider.newWriteOnlyTransaction();
162         InstanceIdentifier<Cars> carsId = InstanceIdentifier.<Cars>builder(Cars.class).build();
163         tx.merge(LogicalDatastoreType.CONFIGURATION, carsId, new CarsBuilder().build());
164         try {
165             tx.submit().checkedGet(5, TimeUnit.SECONDS);
166         } catch (TransactionCommitFailedException | TimeoutException e) {
167             LOG_PURCHASE_CAR.error("Put Cars failed",e);
168             return Futures.immediateFuture(RpcResultBuilder.success(new StressTestOutputBuilder().build()).build());
169         }
170
171         stopThread = false;
172         final long sleep = TimeUnit.NANOSECONDS.convert(1000,TimeUnit.MILLISECONDS) / inputRate;
173         final Stopwatch sw = Stopwatch.createUnstarted();
174         testThread = new Thread(() -> {
175             sw.start();
176             AtomicLong count = new AtomicLong();
177             while (!stopThread) {
178                 long id = count.incrementAndGet();
179                 WriteTransaction tx1 = dataProvider.newWriteOnlyTransaction();
180                 CarEntry car = new CarEntryBuilder().setId(new CarId("car" + id)).build();
181                 tx1.put(LogicalDatastoreType.CONFIGURATION,
182                         InstanceIdentifier.<Cars>builder(Cars.class).child(CarEntry.class, car.getKey()).build(),
183                         car);
184                 CheckedFuture<Void, TransactionCommitFailedException> future = tx1.submit();
185                 Futures.addCallback(future, new FutureCallback<Void>() {
186
187                     @Override
188                     public void onSuccess(final Void result) {
189                         // Transaction succeeded
190                         succcessCounter.getAndIncrement();
191                     }
192
193                     @Override
194                     public void onFailure(final Throwable ex) {
195                         // Transaction failed
196                         failureCounter.getAndIncrement();
197                         LOG_CAR_PROVIDER.error("Put Cars failed", ex);
198                     }
199                 }, MoreExecutors.directExecutor());
200                 try {
201                     TimeUnit.NANOSECONDS.sleep(sleep);
202                 } catch (InterruptedException e) {
203                     break;
204                 }
205
206                 if (count.get() % 1000 == 0) {
207                     LOG_PURCHASE_CAR.info("Cars created {}, time: {}", count.get(), sw.elapsed(TimeUnit.SECONDS));
208                 }
209
210                 // Check if a count is specified in input and we have created that many cars.
211                 if (inputCount != 0 && count.get() >= inputCount) {
212                     stopThread = true;
213                 }
214             }
215
216             LOG_PURCHASE_CAR.info("Stress test thread stopping after creating {} cars.", count.get());
217         });
218         testThread.start();
219
220         return Futures.immediateFuture(RpcResultBuilder.success(new StressTestOutputBuilder().build()).build());
221     }
222
223     @Override
224     public ListenableFuture<RpcResult<StopStressTestOutput>> stopStressTest(final StopStressTestInput input) {
225         stopThread();
226         StopStressTestOutputBuilder stopStressTestOutput;
227         stopStressTestOutput = new StopStressTestOutputBuilder()
228                 .setSuccessCount(succcessCounter.longValue())
229                 .setFailureCount(failureCounter.longValue());
230
231         final StopStressTestOutput result = stopStressTestOutput.build();
232         LOG_PURCHASE_CAR.info("Executed Stop Stress test; No. of cars created {}; "
233                 + "No. of cars failed {}; ", succcessCounter, failureCounter);
234         // clear counters
235         succcessCounter.set(0);
236         failureCounter.set(0);
237         return Futures.immediateFuture(RpcResultBuilder.<StopStressTestOutput>success(result).build());
238     }
239
240
241     @Override
242     public ListenableFuture<RpcResult<RegisterOwnershipOutput>> registerOwnership(final RegisterOwnershipInput input) {
243         if (registeredListener.compareAndSet(false, true)) {
244             ownershipService.registerListener(ENTITY_TYPE, ownershipListener);
245         }
246
247         Entity entity = new Entity(ENTITY_TYPE, input.getCarId());
248         try {
249             ownershipService.registerCandidate(entity);
250         } catch (CandidateAlreadyRegisteredException e) {
251             return RpcResultBuilder.<RegisterOwnershipOutput>failed().withError(ErrorType.APPLICATION,
252                     "Could not register for car " + input.getCarId(), e).buildFuture();
253         }
254
255         return RpcResultBuilder.success(new RegisterOwnershipOutputBuilder().build()).buildFuture();
256     }
257
258     @Override
259     public ListenableFuture<RpcResult<UnregisterOwnershipOutput>> unregisterOwnership(
260             final UnregisterOwnershipInput input) {
261         return RpcResultBuilder.success(new UnregisterOwnershipOutputBuilder().build()).buildFuture();
262     }
263
264     private static class CarEntityOwnershipListener implements EntityOwnershipListener {
265         @Override
266         public void ownershipChanged(final EntityOwnershipChange ownershipChange) {
267             LOG_CAR_PROVIDER.info("ownershipChanged: {}", ownershipChange);
268         }
269     }
270
271     @Override
272     public ListenableFuture<RpcResult<RegisterLoggingDtclOutput>> registerLoggingDtcl(
273             final RegisterLoggingDtclInput input) {
274         LOG_CAR_PROVIDER.info("Registering a new CarDataTreeChangeListener");
275         final ListenerRegistration<CarDataTreeChangeListener> carsDtclRegistration =
276                 dataProvider.registerDataTreeChangeListener(CARS_DTID, new CarDataTreeChangeListener());
277
278         carsDtclRegistrations.add(carsDtclRegistration);
279         return RpcResultBuilder.success(new RegisterLoggingDtclOutputBuilder().build()).buildFuture();
280     }
281
282     @Override
283     public ListenableFuture<RpcResult<UnregisterLoggingDtclsOutput>> unregisterLoggingDtcls(
284             final UnregisterLoggingDtclsInput input) {
285         LOG_CAR_PROVIDER.info("Unregistering the CarDataTreeChangeListener(s)");
286         synchronized (carsDtclRegistrations) {
287             int numListeners = 0;
288             for (ListenerRegistration<CarDataTreeChangeListener> carsDtclRegistration : carsDtclRegistrations) {
289                 carsDtclRegistration.close();
290                 numListeners++;
291             }
292             carsDtclRegistrations.clear();
293             LOG_CAR_PROVIDER.info("Unregistered {} CaraDataTreeChangeListener(s)", numListeners);
294         }
295         return RpcResultBuilder.success(new UnregisterLoggingDtclsOutputBuilder().build()).buildFuture();
296     }
297
298     @Override
299     @SuppressWarnings("checkstyle:IllegalCatch")
300     public ListenableFuture<RpcResult<UnregisterCommitCohortOutput>> unregisterCommitCohort(
301             final UnregisterCommitCohortInput input) {
302         closeCommitCohortRegistration();
303
304         return RpcResultBuilder.success(new UnregisterCommitCohortOutputBuilder().build()).buildFuture();
305     }
306
307     private void closeCommitCohortRegistration() {
308         final DOMDataTreeCommitCohortRegistration<CarEntryDataTreeCommitCohort> reg = commitCohortReg.getAndSet(null);
309         if (reg != null) {
310             reg.close();
311             LOG_CAR_PROVIDER.info("Unregistered commit cohort");
312         }
313     }
314
315     @Override
316     public synchronized ListenableFuture<RpcResult<RegisterCommitCohortOutput>> registerCommitCohort(
317             final RegisterCommitCohortInput input) {
318         if (commitCohortReg.get() != null) {
319             return RpcResultBuilder.success(new RegisterCommitCohortOutputBuilder().build()).buildFuture();
320         }
321
322         final DOMDataTreeCommitCohortRegistry commitCohortRegistry = (DOMDataTreeCommitCohortRegistry)
323                 domDataBroker.getSupportedExtensions().get(DOMDataTreeCommitCohortRegistry.class);
324
325         if (commitCohortRegistry == null) {
326             // Shouldn't happen
327             return RpcResultBuilder.<RegisterCommitCohortOutput>failed().withError(ErrorType.APPLICATION,
328                     "DOMDataTreeCommitCohortRegistry not found").buildFuture();
329         }
330
331         // Note: it may look strange that we specify the CarEntry.QNAME twice in the path below. This must be done in
332         // order to register the commit cohort for CarEntry instances. In the underlying data tree, a yang list is
333         // represented as a MapNode with MapEntryNodes representing the child list entries. Therefore, in order to
334         // address a list entry, you must specify the path argument for the MapNode and the path argument for the
335         // MapEntryNode. In the path below, the first CarEntry.QNAME argument addresses the MapNode and, since we want
336         // to address all list entries, the second path argument is wild-carded by specifying just the CarEntry.QNAME.
337         final YangInstanceIdentifier carEntryPath = YangInstanceIdentifier.builder(
338                 YangInstanceIdentifier.of(Cars.QNAME)).node(CarEntry.QNAME).node(CarEntry.QNAME).build();
339         commitCohortReg.set(commitCohortRegistry.registerCommitCohort(
340                 new org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier(
341                     org.opendaylight.mdsal.common.api.LogicalDatastoreType.CONFIGURATION,
342                         carEntryPath), new CarEntryDataTreeCommitCohort()));
343
344         LOG_CAR_PROVIDER.info("Registered commit cohort");
345
346         return RpcResultBuilder.success(new RegisterCommitCohortOutputBuilder().build()).buildFuture();
347     }
348 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.