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.LogicalDatastoreType;
31 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
32 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
33 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeCommitCohortRegistry;
34 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistration;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.CarId;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.CarService;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.Cars;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.CarsBuilder;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterOwnershipInput;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StopStressTestOutput;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StopStressTestOutputBuilder;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StressTestInput;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterOwnershipInput;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.cars.CarEntry;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.cars.CarEntryBuilder;
46 import org.opendaylight.yangtools.concepts.ListenerRegistration;
47 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
48 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
49 import org.opendaylight.yangtools.yang.common.RpcResult;
50 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
56 * @author Thomas Pantelis
58 public class CarProvider implements CarService {
59 private static final Logger LOG_PURCHASE_CAR = LoggerFactory.getLogger(PurchaseCarProvider.class);
61 private static final Logger LOG_CAR_PROVIDER = LoggerFactory.getLogger(CarProvider.class);
63 private static final String ENTITY_TYPE = "cars";
64 private static final InstanceIdentifier<Cars> CARS_IID = InstanceIdentifier.builder(Cars.class).build();
65 private static final DataTreeIdentifier<Cars> CARS_DTID = new DataTreeIdentifier<>(
66 LogicalDatastoreType.CONFIGURATION, CARS_IID);
68 private final DataBroker dataProvider;
69 private final DOMDataBroker domDataBroker;
70 private final EntityOwnershipService ownershipService;
71 private final AtomicLong succcessCounter = new AtomicLong();
72 private final AtomicLong failureCounter = new AtomicLong();
74 private final CarEntityOwnershipListener ownershipListener = new CarEntityOwnershipListener();
75 private final AtomicBoolean registeredListener = new AtomicBoolean();
77 private final Collection<ListenerRegistration<?>> carsDclRegistrations =
78 Sets.newConcurrentHashSet();
79 private final Collection<ListenerRegistration<CarDataTreeChangeListener>> carsDtclRegistrations =
80 Sets.newConcurrentHashSet();
82 private volatile Thread testThread;
83 private volatile boolean stopThread;
84 private final AtomicReference<DOMDataTreeCommitCohortRegistration<CarEntryDataTreeCommitCohort>> commitCohortReg =
85 new AtomicReference<>();
87 public CarProvider(final DataBroker dataProvider, final EntityOwnershipService ownershipService,
88 final DOMDataBroker domDataBroker) {
89 this.dataProvider = dataProvider;
90 this.ownershipService = ownershipService;
91 this.domDataBroker = domDataBroker;
96 unregisterCommitCohort();
99 private void stopThread() {
100 if(testThread != null) {
102 testThread.interrupt();
105 } catch (InterruptedException e) {}
111 public Future<RpcResult<Void>> stressTest(final StressTestInput input) {
113 final long inputCount;
115 // If rate is not provided, or given as zero, then just return.
116 if (input.getRate() == null || input.getRate() == 0) {
117 LOG_PURCHASE_CAR.info("Exiting stress test as no rate is given.");
118 return Futures.immediateFuture(RpcResultBuilder.<Void>failed()
119 .withError(ErrorType.PROTOCOL, "invalid rate")
123 inputRate = input.getRate();
124 if (input.getCount() != null) {
125 inputCount = input.getCount();
130 LOG_PURCHASE_CAR.info("Stress test starting : rate: {} count: {}", inputRate, inputCount);
134 succcessCounter.set(0);
135 failureCounter.set(0);
137 WriteTransaction tx = dataProvider.newWriteOnlyTransaction();
138 InstanceIdentifier<Cars> carsId = InstanceIdentifier.<Cars>builder(Cars.class).build();
139 tx.merge(LogicalDatastoreType.CONFIGURATION, carsId, new CarsBuilder().build());
141 tx.submit().checkedGet(5, TimeUnit.SECONDS);
142 } catch (TransactionCommitFailedException | TimeoutException e) {
143 LOG_PURCHASE_CAR.error("Put Cars failed",e);
144 return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
148 final long sleep = TimeUnit.NANOSECONDS.convert(1000,TimeUnit.MILLISECONDS) / inputRate;
149 final Stopwatch sw = Stopwatch.createUnstarted();
150 testThread = new Thread(() -> {
152 AtomicLong count = new AtomicLong();
154 long id = count.incrementAndGet();
155 WriteTransaction tx1 = dataProvider.newWriteOnlyTransaction();
156 CarEntry car = new CarEntryBuilder().setId(new CarId("car"+id)).build();
157 tx1.put(LogicalDatastoreType.CONFIGURATION,
158 InstanceIdentifier.<Cars>builder(Cars.class).child(CarEntry.class, car.getKey()).build(),
160 CheckedFuture<Void, TransactionCommitFailedException> future = tx1.submit();
161 Futures.addCallback(future, new FutureCallback<Void>() {
164 public void onSuccess(final Void result) {
165 // Transaction succeeded
166 succcessCounter.getAndIncrement();
170 public void onFailure(final Throwable t) {
171 // Transaction failed
172 failureCounter.getAndIncrement();
173 LOG_CAR_PROVIDER.error("Put Cars failed", t);
177 TimeUnit.NANOSECONDS.sleep(sleep);
178 } catch (InterruptedException e) {
182 if(count.get() % 1000 == 0) {
183 LOG_PURCHASE_CAR.info("Cars created {}, time: {}",count.get(),sw.elapsed(TimeUnit.SECONDS));
186 // Check if a count is specified in input and we have created that many cars.
187 if (inputCount != 0 && count.get() >= inputCount) {
192 LOG_PURCHASE_CAR.info("Stress test thread stopping after creating {} cars.", count.get());
196 return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
200 public Future<RpcResult<StopStressTestOutput>> stopStressTest() {
202 StopStressTestOutputBuilder stopStressTestOutput;
203 stopStressTestOutput = new StopStressTestOutputBuilder()
204 .setSuccessCount(succcessCounter.longValue())
205 .setFailureCount(failureCounter.longValue());
207 StopStressTestOutput result = stopStressTestOutput.build();
208 LOG_PURCHASE_CAR.info("Executed Stop Stress test; No. of cars created {}; " +
209 "No. of cars failed {}; ", succcessCounter, failureCounter);
211 succcessCounter.set(0);
212 failureCounter.set(0);
213 return Futures.immediateFuture(RpcResultBuilder.<StopStressTestOutput>success(result).build());
218 public Future<RpcResult<Void>> registerOwnership(final RegisterOwnershipInput input) {
219 if(registeredListener.compareAndSet(false, true)) {
220 ownershipService.registerListener(ENTITY_TYPE, ownershipListener);
223 Entity entity = new Entity(ENTITY_TYPE, input.getCarId());
225 ownershipService.registerCandidate(entity);
226 } catch (CandidateAlreadyRegisteredException e) {
227 return RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION,
228 "Could not register for car " + input.getCarId(), e).buildFuture();
231 return RpcResultBuilder.<Void>success().buildFuture();
235 public Future<RpcResult<Void>> unregisterOwnership(final UnregisterOwnershipInput input) {
236 return RpcResultBuilder.<Void>success().buildFuture();
239 private static class CarEntityOwnershipListener implements EntityOwnershipListener {
241 public void ownershipChanged(final EntityOwnershipChange ownershipChange) {
242 LOG_CAR_PROVIDER.info("ownershipChanged: {}", ownershipChange);
247 public Future<RpcResult<java.lang.Void>> registerLoggingDtcl() {
248 LOG_CAR_PROVIDER.info("Registering a new CarDataTreeChangeListener");
249 final ListenerRegistration<CarDataTreeChangeListener> carsDtclRegistration =
250 dataProvider.registerDataTreeChangeListener(CARS_DTID, new CarDataTreeChangeListener());
252 if (carsDtclRegistration != null) {
253 carsDtclRegistrations.add(carsDtclRegistration);
254 return RpcResultBuilder.<Void>success().buildFuture();
256 return RpcResultBuilder.<Void>failed().buildFuture();
260 public Future<RpcResult<java.lang.Void>> unregisterLoggingDtcls() {
261 LOG_CAR_PROVIDER.info("Unregistering the CarDataTreeChangeListener(s)");
262 synchronized (carsDtclRegistrations) {
263 int numListeners = 0;
264 for (ListenerRegistration<CarDataTreeChangeListener> carsDtclRegistration : carsDtclRegistrations) {
265 carsDtclRegistration.close();
268 carsDtclRegistrations.clear();
269 LOG_CAR_PROVIDER.info("Unregistered {} CaraDataTreeChangeListener(s)", numListeners);
271 return RpcResultBuilder.<Void>success().buildFuture();
275 @SuppressWarnings("checkstyle:IllegalCatch")
276 public Future<RpcResult<Void>> unregisterCommitCohort() {
277 final DOMDataTreeCommitCohortRegistration<CarEntryDataTreeCommitCohort> reg = commitCohortReg.getAndSet(null);
281 LOG_CAR_PROVIDER.info("Unregistered commit cohort");
282 } catch (Exception e) {
283 return RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION,
284 "Error closing commit cohort registration", e).buildFuture();
288 return RpcResultBuilder.<Void>success().buildFuture();
292 public synchronized Future<RpcResult<Void>> registerCommitCohort() {
293 if (commitCohortReg.get() != null) {
294 return RpcResultBuilder.<Void>success().buildFuture();
297 final DOMDataTreeCommitCohortRegistry commitCohortRegistry = (DOMDataTreeCommitCohortRegistry)
298 domDataBroker.getSupportedExtensions().get(DOMDataTreeCommitCohortRegistry.class);
300 if (commitCohortRegistry == null) {
302 return RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION,
303 "DOMDataTreeCommitCohortRegistry not found").buildFuture();
306 // Note: it may look strange that we specify the CarEntry.QNAME twice in the path below. This must be done in
307 // order to register the commit cohort for CarEntry instances. In the underlying data tree, a yang list is
308 // represented as a MapNode with MapEntryNodes representing the child list entries. Therefore, in order to
309 // address a list entry, you must specify the path argument for the MapNode and the path argument for the
310 // MapEntryNode. In the path below, the first CarEntry.QNAME argument addresses the MapNode and, since we want
311 // to address all list entries, the second path argument is wild-carded by specifying just the CarEntry.QNAME.
312 final YangInstanceIdentifier carEntryPath = YangInstanceIdentifier.builder(
313 YangInstanceIdentifier.of(Cars.QNAME)).node(CarEntry.QNAME).node(CarEntry.QNAME).build();
314 commitCohortReg.set(commitCohortRegistry.registerCommitCohort(
315 new org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier(
316 org.opendaylight.mdsal.common.api.LogicalDatastoreType.CONFIGURATION,
317 carEntryPath), new CarEntryDataTreeCommitCohort()));
319 LOG_CAR_PROVIDER.info("Registered commit cohort");
321 return RpcResultBuilder.<Void>success().buildFuture();