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