2 * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.clustering.it.provider;
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 java.util.Collection;
16 import java.util.concurrent.Future;
17 import java.util.concurrent.TimeUnit;
18 import java.util.concurrent.TimeoutException;
19 import java.util.concurrent.atomic.AtomicBoolean;
20 import java.util.concurrent.atomic.AtomicLong;
21 import java.util.concurrent.atomic.AtomicReference;
22 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
23 import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
24 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
25 import org.opendaylight.controller.md.sal.common.api.clustering.CandidateAlreadyRegisteredException;
26 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
27 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipChange;
28 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListener;
29 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
30 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
31 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
32 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
33 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
34 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeCommitCohortRegistry;
35 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistration;
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.RegisterOwnershipInput;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StopStressTestOutput;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StopStressTestOutputBuilder;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StressTestInput;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterOwnershipInput;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.cars.CarEntry;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.cars.CarEntryBuilder;
47 import org.opendaylight.yangtools.concepts.ListenerRegistration;
48 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
49 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
50 import org.opendaylight.yangtools.yang.common.RpcResult;
51 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
52 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
57 * @author Thomas Pantelis
59 public class CarProvider implements CarService {
60 private static final Logger log = LoggerFactory.getLogger(PurchaseCarProvider.class);
62 private static final Logger LOG = LoggerFactory.getLogger(CarProvider.class);
64 private static final String ENTITY_TYPE = "cars";
65 private static final InstanceIdentifier<Cars> CARS_IID = InstanceIdentifier.builder(Cars.class).build();
66 private static final DataTreeIdentifier<Cars> CARS_DTID = new DataTreeIdentifier<>(
67 LogicalDatastoreType.CONFIGURATION, CARS_IID);
69 private final DataBroker dataProvider;
70 private final DOMDataBroker domDataBroker;
71 private final EntityOwnershipService ownershipService;
72 private final AtomicLong succcessCounter = new AtomicLong();
73 private final AtomicLong failureCounter = new AtomicLong();
75 private final CarEntityOwnershipListener ownershipListener = new CarEntityOwnershipListener();
76 private final AtomicBoolean registeredListener = new AtomicBoolean();
78 private final Collection<ListenerRegistration<?>> carsDclRegistrations =
79 Sets.newConcurrentHashSet();
80 private final Collection<ListenerRegistration<CarDataTreeChangeListener>> carsDtclRegistrations =
81 Sets.newConcurrentHashSet();
83 private volatile Thread testThread;
84 private volatile boolean stopThread;
85 private final AtomicReference<DOMDataTreeCommitCohortRegistration<CarEntryDataTreeCommitCohort>> commitCohortReg =
86 new AtomicReference<>();
88 public CarProvider(final DataBroker dataProvider, final EntityOwnershipService ownershipService,
89 final DOMDataBroker domDataBroker) {
90 this.dataProvider = dataProvider;
91 this.ownershipService = ownershipService;
92 this.domDataBroker = domDataBroker;
97 unregisterCommitCohort();
100 private void stopThread() {
101 if(testThread != null) {
103 testThread.interrupt();
106 } catch (InterruptedException e) {}
112 public Future<RpcResult<Void>> stressTest(final StressTestInput input) {
114 final long inputCount;
116 // If rate is not provided, or given as zero, then just return.
117 if (input.getRate() == null || input.getRate() == 0) {
118 log.info("Exiting stress test as no rate is given.");
119 return Futures.immediateFuture(RpcResultBuilder.<Void>failed()
120 .withError(ErrorType.PROTOCOL, "invalid rate")
124 inputRate = input.getRate();
125 if (input.getCount() != null) {
126 inputCount = input.getCount();
131 log.info("Stress test starting : rate: {} count: {}", inputRate, inputCount);
135 succcessCounter.set(0);
136 failureCounter.set(0);
138 WriteTransaction tx = dataProvider.newWriteOnlyTransaction();
139 InstanceIdentifier<Cars> carsId = InstanceIdentifier.<Cars>builder(Cars.class).build();
140 tx.merge(LogicalDatastoreType.CONFIGURATION, carsId, new CarsBuilder().build());
142 tx.submit().checkedGet(5, TimeUnit.SECONDS);
143 } catch (TransactionCommitFailedException | TimeoutException e) {
144 log.error("Put Cars failed",e);
145 return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
149 final long sleep = TimeUnit.NANOSECONDS.convert(1000,TimeUnit.MILLISECONDS) / inputRate;
150 final Stopwatch sw = Stopwatch.createUnstarted();
151 testThread = new Thread() {
155 AtomicLong count = new AtomicLong();
157 long id = count.incrementAndGet();
158 WriteTransaction tx = dataProvider.newWriteOnlyTransaction();
159 CarEntry car = new CarEntryBuilder().setId(new CarId("car"+id)).build();
160 tx.put(LogicalDatastoreType.CONFIGURATION,
161 InstanceIdentifier.<Cars>builder(Cars.class).child(CarEntry.class, car.getKey()).build(),
163 CheckedFuture<Void, TransactionCommitFailedException> future = tx.submit();
164 Futures.addCallback(future, new FutureCallback<Void>() {
167 public void onSuccess(final Void result) {
168 // Transaction succeeded
169 succcessCounter.getAndIncrement();
173 public void onFailure(final Throwable t) {
174 // Transaction failed
175 failureCounter.getAndIncrement();
176 LOG.error("Put Cars failed", t);
180 TimeUnit.NANOSECONDS.sleep(sleep);
181 } catch (InterruptedException e) {
185 if(count.get() % 1000 == 0) {
186 log.info("Cars created {}, time: {}",count.get(),sw.elapsed(TimeUnit.SECONDS));
189 // Check if a count is specified in input and we have created that many cars.
190 if (inputCount != 0 && count.get() >= inputCount) {
195 log.info("Stress test thread stopping after creating {} cars.", count.get());
200 return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
204 public Future<RpcResult<StopStressTestOutput>> stopStressTest() {
206 StopStressTestOutputBuilder stopStressTestOutput;
207 stopStressTestOutput = new StopStressTestOutputBuilder()
208 .setSuccessCount(succcessCounter.longValue())
209 .setFailureCount(failureCounter.longValue());
211 StopStressTestOutput result = stopStressTestOutput.build();
212 log.info("Executed Stop Stress test; No. of cars created {}; " +
213 "No. of cars failed {}; ", succcessCounter, failureCounter);
215 succcessCounter.set(0);
216 failureCounter.set(0);
217 return Futures.immediateFuture(RpcResultBuilder.<StopStressTestOutput>success(result).build());
222 public Future<RpcResult<Void>> registerOwnership(final RegisterOwnershipInput input) {
223 if(registeredListener.compareAndSet(false, true)) {
224 ownershipService.registerListener(ENTITY_TYPE, ownershipListener);
227 Entity entity = new Entity(ENTITY_TYPE, input.getCarId());
229 ownershipService.registerCandidate(entity);
230 } catch (CandidateAlreadyRegisteredException e) {
231 return RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION,
232 "Could not register for car " + input.getCarId(), e).buildFuture();
235 return RpcResultBuilder.<Void>success().buildFuture();
239 public Future<RpcResult<Void>> unregisterOwnership(final UnregisterOwnershipInput input) {
240 return RpcResultBuilder.<Void>success().buildFuture();
243 private static class CarEntityOwnershipListener implements EntityOwnershipListener {
245 public void ownershipChanged(final EntityOwnershipChange ownershipChange) {
246 LOG.info("ownershipChanged: {}", ownershipChange);
251 public Future<RpcResult<java.lang.Void>> registerLoggingDcl() {
252 LOG.info("Registering a new CarDataChangeListener");
253 final ListenerRegistration<?> carsDclRegistration = dataProvider.registerDataChangeListener(
254 LogicalDatastoreType.CONFIGURATION, CARS_IID, new CarDataChangeListener(),
255 AsyncDataBroker.DataChangeScope.SUBTREE);
257 if (carsDclRegistration != null) {
258 carsDclRegistrations.add(carsDclRegistration);
259 return RpcResultBuilder.<Void>success().buildFuture();
261 return RpcResultBuilder.<Void>failed().buildFuture();
265 public Future<RpcResult<java.lang.Void>> registerLoggingDtcl() {
266 LOG.info("Registering a new CarDataTreeChangeListener");
267 final ListenerRegistration<CarDataTreeChangeListener> carsDtclRegistration =
268 dataProvider.registerDataTreeChangeListener(CARS_DTID, new CarDataTreeChangeListener());
270 if (carsDtclRegistration != null) {
271 carsDtclRegistrations.add(carsDtclRegistration);
272 return RpcResultBuilder.<Void>success().buildFuture();
274 return RpcResultBuilder.<Void>failed().buildFuture();
278 public Future<RpcResult<java.lang.Void>> unregisterLoggingDcls() {
279 LOG.info("Unregistering the CarDataChangeListener(s)");
280 synchronized (carsDclRegistrations) {
281 int numListeners = 0;
282 for (ListenerRegistration<?> carsDclRegistration : carsDclRegistrations) {
283 carsDclRegistration.close();
286 carsDclRegistrations.clear();
287 LOG.info("Unregistered {} CarDataChangeListener(s)", numListeners);
289 return RpcResultBuilder.<Void>success().buildFuture();
293 public Future<RpcResult<java.lang.Void>> unregisterLoggingDtcls() {
294 LOG.info("Unregistering the CarDataTreeChangeListener(s)");
295 synchronized (carsDtclRegistrations) {
296 int numListeners = 0;
297 for (ListenerRegistration<CarDataTreeChangeListener> carsDtclRegistration : carsDtclRegistrations) {
298 carsDtclRegistration.close();
301 carsDtclRegistrations.clear();
302 LOG.info("Unregistered {} CaraDataTreeChangeListener(s)", numListeners);
304 return RpcResultBuilder.<Void>success().buildFuture();
308 @SuppressWarnings("checkstyle:IllegalCatch")
309 public Future<RpcResult<Void>> unregisterCommitCohort() {
310 final DOMDataTreeCommitCohortRegistration<CarEntryDataTreeCommitCohort> reg = commitCohortReg.getAndSet(null);
314 LOG.info("Unregistered commit cohort");
315 } catch (Exception e) {
316 return RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION,
317 "Error closing commit cohort registration", e).buildFuture();
321 return RpcResultBuilder.<Void>success().buildFuture();
325 public synchronized Future<RpcResult<Void>> registerCommitCohort() {
326 if (commitCohortReg.get() != null) {
327 return RpcResultBuilder.<Void>success().buildFuture();
330 final DOMDataTreeCommitCohortRegistry commitCohortRegistry = (DOMDataTreeCommitCohortRegistry)
331 domDataBroker.getSupportedExtensions().get(DOMDataTreeCommitCohortRegistry.class);
333 if (commitCohortRegistry == null) {
335 return RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION,
336 "DOMDataTreeCommitCohortRegistry not found").buildFuture();
339 // Note: it may look strange that we specify the CarEntry.QNAME twice in the path below. This must be done in
340 // order to register the commit cohort for CarEntry instances. In the underlying data tree, a yang list is
341 // represented as a MapNode with MapEntryNodes representing the child list entries. Therefore, in order to
342 // address a list entry, you must specify the path argument for the MapNode and the path argument for the
343 // MapEntryNode. In the path below, the first CarEntry.QNAME argument addresses the MapNode and, since we want
344 // to address all list entries, the second path argument is wild-carded by specifying just the CarEntry.QNAME.
345 final YangInstanceIdentifier carEntryPath = YangInstanceIdentifier.builder(
346 YangInstanceIdentifier.of(Cars.QNAME)).node(CarEntry.QNAME).node(CarEntry.QNAME).build();
347 commitCohortReg.set(commitCohortRegistry.registerCommitCohort(
348 new org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier(
349 org.opendaylight.mdsal.common.api.LogicalDatastoreType.CONFIGURATION,
350 carEntryPath), new CarEntryDataTreeCommitCohort()));
352 LOG.info("Registered commit cohort");
354 return RpcResultBuilder.<Void>success().buildFuture();