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_PURCHASE_CAR = LoggerFactory.getLogger(PurchaseCarProvider.class);
62 private static final Logger LOG_CAR_PROVIDER = 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_PURCHASE_CAR.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_PURCHASE_CAR.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_PURCHASE_CAR.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(() -> {
153 AtomicLong count = new AtomicLong();
155 long id = count.incrementAndGet();
156 WriteTransaction tx1 = dataProvider.newWriteOnlyTransaction();
157 CarEntry car = new CarEntryBuilder().setId(new CarId("car"+id)).build();
158 tx1.put(LogicalDatastoreType.CONFIGURATION,
159 InstanceIdentifier.<Cars>builder(Cars.class).child(CarEntry.class, car.getKey()).build(),
161 CheckedFuture<Void, TransactionCommitFailedException> future = tx1.submit();
162 Futures.addCallback(future, new FutureCallback<Void>() {
165 public void onSuccess(final Void result) {
166 // Transaction succeeded
167 succcessCounter.getAndIncrement();
171 public void onFailure(final Throwable t) {
172 // Transaction failed
173 failureCounter.getAndIncrement();
174 LOG_CAR_PROVIDER.error("Put Cars failed", t);
178 TimeUnit.NANOSECONDS.sleep(sleep);
179 } catch (InterruptedException e) {
183 if(count.get() % 1000 == 0) {
184 LOG_PURCHASE_CAR.info("Cars created {}, time: {}",count.get(),sw.elapsed(TimeUnit.SECONDS));
187 // Check if a count is specified in input and we have created that many cars.
188 if (inputCount != 0 && count.get() >= inputCount) {
193 LOG_PURCHASE_CAR.info("Stress test thread stopping after creating {} cars.", count.get());
197 return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
201 public Future<RpcResult<StopStressTestOutput>> stopStressTest() {
203 StopStressTestOutputBuilder stopStressTestOutput;
204 stopStressTestOutput = new StopStressTestOutputBuilder()
205 .setSuccessCount(succcessCounter.longValue())
206 .setFailureCount(failureCounter.longValue());
208 StopStressTestOutput result = stopStressTestOutput.build();
209 LOG_PURCHASE_CAR.info("Executed Stop Stress test; No. of cars created {}; " +
210 "No. of cars failed {}; ", succcessCounter, failureCounter);
212 succcessCounter.set(0);
213 failureCounter.set(0);
214 return Futures.immediateFuture(RpcResultBuilder.<StopStressTestOutput>success(result).build());
219 public Future<RpcResult<Void>> registerOwnership(final RegisterOwnershipInput input) {
220 if(registeredListener.compareAndSet(false, true)) {
221 ownershipService.registerListener(ENTITY_TYPE, ownershipListener);
224 Entity entity = new Entity(ENTITY_TYPE, input.getCarId());
226 ownershipService.registerCandidate(entity);
227 } catch (CandidateAlreadyRegisteredException e) {
228 return RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION,
229 "Could not register for car " + input.getCarId(), e).buildFuture();
232 return RpcResultBuilder.<Void>success().buildFuture();
236 public Future<RpcResult<Void>> unregisterOwnership(final UnregisterOwnershipInput input) {
237 return RpcResultBuilder.<Void>success().buildFuture();
240 private static class CarEntityOwnershipListener implements EntityOwnershipListener {
242 public void ownershipChanged(final EntityOwnershipChange ownershipChange) {
243 LOG_CAR_PROVIDER.info("ownershipChanged: {}", ownershipChange);
248 public Future<RpcResult<java.lang.Void>> registerLoggingDcl() {
249 LOG_CAR_PROVIDER.info("Registering a new CarDataChangeListener");
250 final ListenerRegistration carsDclRegistration = dataProvider.registerDataChangeListener(
251 LogicalDatastoreType.CONFIGURATION, CARS_IID, new CarDataChangeListener(),
252 AsyncDataBroker.DataChangeScope.SUBTREE);
254 if (carsDclRegistration != null) {
255 carsDclRegistrations.add(carsDclRegistration);
256 return RpcResultBuilder.<Void>success().buildFuture();
258 return RpcResultBuilder.<Void>failed().buildFuture();
262 public Future<RpcResult<java.lang.Void>> registerLoggingDtcl() {
263 LOG_CAR_PROVIDER.info("Registering a new CarDataTreeChangeListener");
264 final ListenerRegistration<CarDataTreeChangeListener> carsDtclRegistration =
265 dataProvider.registerDataTreeChangeListener(CARS_DTID, new CarDataTreeChangeListener());
267 if (carsDtclRegistration != null) {
268 carsDtclRegistrations.add(carsDtclRegistration);
269 return RpcResultBuilder.<Void>success().buildFuture();
271 return RpcResultBuilder.<Void>failed().buildFuture();
275 public Future<RpcResult<java.lang.Void>> unregisterLoggingDcls() {
276 LOG_CAR_PROVIDER.info("Unregistering the CarDataChangeListener(s)");
277 synchronized (carsDclRegistrations) {
278 int numListeners = 0;
279 for (ListenerRegistration<?> carsDclRegistration : carsDclRegistrations) {
280 carsDclRegistration.close();
283 carsDclRegistrations.clear();
284 LOG_CAR_PROVIDER.info("Unregistered {} CarDataChangeListener(s)", numListeners);
286 return RpcResultBuilder.<Void>success().buildFuture();
290 public Future<RpcResult<java.lang.Void>> unregisterLoggingDtcls() {
291 LOG_CAR_PROVIDER.info("Unregistering the CarDataTreeChangeListener(s)");
292 synchronized (carsDtclRegistrations) {
293 int numListeners = 0;
294 for (ListenerRegistration<CarDataTreeChangeListener> carsDtclRegistration : carsDtclRegistrations) {
295 carsDtclRegistration.close();
298 carsDtclRegistrations.clear();
299 LOG_CAR_PROVIDER.info("Unregistered {} CaraDataTreeChangeListener(s)", numListeners);
301 return RpcResultBuilder.<Void>success().buildFuture();
305 @SuppressWarnings("checkstyle:IllegalCatch")
306 public Future<RpcResult<Void>> unregisterCommitCohort() {
307 final DOMDataTreeCommitCohortRegistration<CarEntryDataTreeCommitCohort> reg = commitCohortReg.getAndSet(null);
311 LOG_CAR_PROVIDER.info("Unregistered commit cohort");
312 } catch (Exception e) {
313 return RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION,
314 "Error closing commit cohort registration", e).buildFuture();
318 return RpcResultBuilder.<Void>success().buildFuture();
322 public synchronized Future<RpcResult<Void>> registerCommitCohort() {
323 if (commitCohortReg.get() != null) {
324 return RpcResultBuilder.<Void>success().buildFuture();
327 final DOMDataTreeCommitCohortRegistry commitCohortRegistry = (DOMDataTreeCommitCohortRegistry)
328 domDataBroker.getSupportedExtensions().get(DOMDataTreeCommitCohortRegistry.class);
330 if (commitCohortRegistry == null) {
332 return RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION,
333 "DOMDataTreeCommitCohortRegistry not found").buildFuture();
336 // Note: it may look strange that we specify the CarEntry.QNAME twice in the path below. This must be done in
337 // order to register the commit cohort for CarEntry instances. In the underlying data tree, a yang list is
338 // represented as a MapNode with MapEntryNodes representing the child list entries. Therefore, in order to
339 // address a list entry, you must specify the path argument for the MapNode and the path argument for the
340 // MapEntryNode. In the path below, the first CarEntry.QNAME argument addresses the MapNode and, since we want
341 // to address all list entries, the second path argument is wild-carded by specifying just the CarEntry.QNAME.
342 final YangInstanceIdentifier carEntryPath = YangInstanceIdentifier.builder(
343 YangInstanceIdentifier.of(Cars.QNAME)).node(CarEntry.QNAME).node(CarEntry.QNAME).build();
344 commitCohortReg.set(commitCohortRegistry.registerCommitCohort(
345 new org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier(
346 org.opendaylight.mdsal.common.api.LogicalDatastoreType.CONFIGURATION,
347 carEntryPath), new CarEntryDataTreeCommitCohort()));
349 LOG_CAR_PROVIDER.info("Registered commit cohort");
351 return RpcResultBuilder.<Void>success().buildFuture();