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.DataChangeListener;
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.clustering.CandidateAlreadyRegisteredException;
27 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
28 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipChange;
29 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListener;
30 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
31 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
32 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
33 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
34 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
35 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeCommitCohortRegistry;
36 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistration;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.CarId;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.CarService;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.Cars;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.CarsBuilder;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterOwnershipInput;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StopStressTestOutput;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StopStressTestOutputBuilder;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StressTestInput;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterOwnershipInput;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.cars.CarEntry;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.cars.CarEntryBuilder;
48 import org.opendaylight.yangtools.concepts.ListenerRegistration;
49 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
50 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
51 import org.opendaylight.yangtools.yang.common.RpcResult;
52 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
53 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
58 * @author Thomas Pantelis
60 public class CarProvider implements CarService {
61 private static final Logger LOG_PURCHASE_CAR = LoggerFactory.getLogger(PurchaseCarProvider.class);
63 private static final Logger LOG_CAR_PROVIDER = LoggerFactory.getLogger(CarProvider.class);
65 private static final String ENTITY_TYPE = "cars";
66 private static final InstanceIdentifier CARS_IID = InstanceIdentifier.builder(Cars.class).build();
67 private static final DataTreeIdentifier<Cars> CARS_DTID = new DataTreeIdentifier<>(
68 LogicalDatastoreType.CONFIGURATION, CARS_IID);
70 private final DataBroker dataProvider;
71 private final DOMDataBroker domDataBroker;
72 private final EntityOwnershipService ownershipService;
73 private final AtomicLong succcessCounter = new AtomicLong();
74 private final AtomicLong failureCounter = new AtomicLong();
76 private final CarEntityOwnershipListener ownershipListener = new CarEntityOwnershipListener();
77 private final AtomicBoolean registeredListener = new AtomicBoolean();
79 private final Collection<ListenerRegistration<DataChangeListener>> carsDclRegistrations =
80 Sets.newConcurrentHashSet();
81 private final Collection<ListenerRegistration<CarDataTreeChangeListener>> carsDtclRegistrations =
82 Sets.newConcurrentHashSet();
84 private volatile Thread testThread;
85 private volatile boolean stopThread;
86 private final AtomicReference<DOMDataTreeCommitCohortRegistration<CarEntryDataTreeCommitCohort>> commitCohortReg =
87 new AtomicReference<>();
89 public CarProvider(DataBroker dataProvider, EntityOwnershipService ownershipService,
90 DOMDataBroker domDataBroker) {
91 this.dataProvider = dataProvider;
92 this.ownershipService = ownershipService;
93 this.domDataBroker = domDataBroker;
98 unregisterCommitCohort();
101 private void stopThread() {
102 if(testThread != null) {
104 testThread.interrupt();
107 } catch (InterruptedException e) {}
113 public Future<RpcResult<Void>> stressTest(StressTestInput input) {
115 final long inputCount;
117 // If rate is not provided, or given as zero, then just return.
118 if (input.getRate() == null || input.getRate() == 0) {
119 LOG_PURCHASE_CAR.info("Exiting stress test as no rate is given.");
120 return Futures.immediateFuture(RpcResultBuilder.<Void>failed()
121 .withError(ErrorType.PROTOCOL, "invalid rate")
124 inputRate = input.getRate();
127 if (input.getCount() != null) {
128 inputCount = input.getCount();
133 LOG_PURCHASE_CAR.info("Stress test starting : rate: {} count: {}", inputRate, inputCount);
137 succcessCounter.set(0);
138 failureCounter.set(0);
140 WriteTransaction tx = dataProvider.newWriteOnlyTransaction();
141 InstanceIdentifier<Cars> carsId = InstanceIdentifier.<Cars>builder(Cars.class).build();
142 tx.merge(LogicalDatastoreType.CONFIGURATION, carsId, new CarsBuilder().build());
144 tx.submit().checkedGet(5, TimeUnit.SECONDS);
145 } catch (TransactionCommitFailedException | TimeoutException e) {
146 LOG_PURCHASE_CAR.error("Put Cars failed",e);
147 return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
151 final long sleep = TimeUnit.NANOSECONDS.convert(1000,TimeUnit.MILLISECONDS) / inputRate;
152 final Stopwatch sw = Stopwatch.createUnstarted();
153 testThread = new Thread(() -> {
155 AtomicLong count = new AtomicLong();
157 long id = count.incrementAndGet();
158 WriteTransaction tx1 = dataProvider.newWriteOnlyTransaction();
159 CarEntry car = new CarEntryBuilder().setId(new CarId("car"+id)).build();
160 tx1.put(LogicalDatastoreType.CONFIGURATION,
161 InstanceIdentifier.<Cars>builder(Cars.class).child(CarEntry.class, car.getKey()).build(),
163 CheckedFuture<Void, TransactionCommitFailedException> future = tx1.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_CAR_PROVIDER.error("Put Cars failed", t);
180 TimeUnit.NANOSECONDS.sleep(sleep);
181 } catch (InterruptedException e) {
185 if(count.get() % 1000 == 0) {
186 LOG_PURCHASE_CAR.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_PURCHASE_CAR.info("Stress test thread stopping after creating {} cars.", count.get());
199 return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
203 public Future<RpcResult<StopStressTestOutput>> stopStressTest() {
205 StopStressTestOutputBuilder stopStressTestOutput;
206 stopStressTestOutput = new StopStressTestOutputBuilder()
207 .setSuccessCount(succcessCounter.longValue())
208 .setFailureCount(failureCounter.longValue());
210 StopStressTestOutput result = stopStressTestOutput.build();
211 LOG_PURCHASE_CAR.info("Executed Stop Stress test; No. of cars created {}; " +
212 "No. of cars failed {}; ", succcessCounter, failureCounter);
214 succcessCounter.set(0);
215 failureCounter.set(0);
216 return Futures.immediateFuture(RpcResultBuilder.<StopStressTestOutput>success(result).build());
221 public Future<RpcResult<Void>> registerOwnership(RegisterOwnershipInput input) {
222 if(registeredListener.compareAndSet(false, true)) {
223 ownershipService.registerListener(ENTITY_TYPE, ownershipListener);
226 Entity entity = new Entity(ENTITY_TYPE, input.getCarId());
228 ownershipService.registerCandidate(entity);
229 } catch (CandidateAlreadyRegisteredException e) {
230 return RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION,
231 "Could not register for car " + input.getCarId(), e).buildFuture();
234 return RpcResultBuilder.<Void>success().buildFuture();
238 public Future<RpcResult<Void>> unregisterOwnership(UnregisterOwnershipInput input) {
239 return RpcResultBuilder.<Void>success().buildFuture();
242 private static class CarEntityOwnershipListener implements EntityOwnershipListener {
244 public void ownershipChanged(EntityOwnershipChange ownershipChange) {
245 LOG_CAR_PROVIDER.info("ownershipChanged: {}", ownershipChange);
250 public Future<RpcResult<java.lang.Void>> registerLoggingDcl() {
251 LOG_CAR_PROVIDER.info("Registering a new CarDataChangeListener");
252 final ListenerRegistration carsDclRegistration = dataProvider.registerDataChangeListener(
253 LogicalDatastoreType.CONFIGURATION, CARS_IID, new CarDataChangeListener(),
254 AsyncDataBroker.DataChangeScope.SUBTREE);
256 if (carsDclRegistration != null) {
257 carsDclRegistrations.add(carsDclRegistration);
258 return RpcResultBuilder.<Void>success().buildFuture();
260 return RpcResultBuilder.<Void>failed().buildFuture();
264 public Future<RpcResult<java.lang.Void>> registerLoggingDtcl() {
265 LOG_CAR_PROVIDER.info("Registering a new CarDataTreeChangeListener");
266 final ListenerRegistration<CarDataTreeChangeListener> carsDtclRegistration =
267 dataProvider.registerDataTreeChangeListener(CARS_DTID, new CarDataTreeChangeListener());
269 if (carsDtclRegistration != null) {
270 carsDtclRegistrations.add(carsDtclRegistration);
271 return RpcResultBuilder.<Void>success().buildFuture();
273 return RpcResultBuilder.<Void>failed().buildFuture();
277 public Future<RpcResult<java.lang.Void>> unregisterLoggingDcls() {
278 LOG_CAR_PROVIDER.info("Unregistering the CarDataChangeListener(s)");
279 synchronized (carsDclRegistrations) {
280 int numListeners = 0;
281 for (ListenerRegistration<DataChangeListener> carsDclRegistration : carsDclRegistrations) {
282 carsDclRegistration.close();
285 carsDclRegistrations.clear();
286 LOG_CAR_PROVIDER.info("Unregistered {} CarDataChangeListener(s)", numListeners);
288 return RpcResultBuilder.<Void>success().buildFuture();
292 public Future<RpcResult<java.lang.Void>> unregisterLoggingDtcls() {
293 LOG_CAR_PROVIDER.info("Unregistering the CarDataTreeChangeListener(s)");
294 synchronized (carsDtclRegistrations) {
295 int numListeners = 0;
296 for (ListenerRegistration<CarDataTreeChangeListener> carsDtclRegistration : carsDtclRegistrations) {
297 carsDtclRegistration.close();
300 carsDtclRegistrations.clear();
301 LOG_CAR_PROVIDER.info("Unregistered {} CaraDataTreeChangeListener(s)", numListeners);
303 return RpcResultBuilder.<Void>success().buildFuture();
307 @SuppressWarnings("checkstyle:IllegalCatch")
308 public Future<RpcResult<Void>> unregisterCommitCohort() {
309 final DOMDataTreeCommitCohortRegistration<CarEntryDataTreeCommitCohort> reg = commitCohortReg.getAndSet(null);
313 LOG_CAR_PROVIDER.info("Unregistered commit cohort");
314 } catch (Exception e) {
315 return RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION,
316 "Error closing commit cohort registration", e).buildFuture();
320 return RpcResultBuilder.<Void>success().buildFuture();
324 public synchronized Future<RpcResult<Void>> registerCommitCohort() {
325 if (commitCohortReg.get() != null) {
326 return RpcResultBuilder.<Void>success().buildFuture();
329 final DOMDataTreeCommitCohortRegistry commitCohortRegistry = (DOMDataTreeCommitCohortRegistry)
330 domDataBroker.getSupportedExtensions().get(DOMDataTreeCommitCohortRegistry.class);
332 if (commitCohortRegistry == null) {
334 return RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION,
335 "DOMDataTreeCommitCohortRegistry not found").buildFuture();
338 // Note: it may look strange that we specify the CarEntry.QNAME twice in the path below. This must be done in
339 // order to register the commit cohort for CarEntry instances. In the underlying data tree, a yang list is
340 // represented as a MapNode with MapEntryNodes representing the child list entries. Therefore, in order to
341 // address a list entry, you must specify the path argument for the MapNode and the path argument for the
342 // MapEntryNode. In the path below, the first CarEntry.QNAME argument addresses the MapNode and, since we want
343 // to address all list entries, the second path argument is wild-carded by specifying just the CarEntry.QNAME.
344 final YangInstanceIdentifier carEntryPath = YangInstanceIdentifier.builder(
345 YangInstanceIdentifier.of(Cars.QNAME)).node(CarEntry.QNAME).node(CarEntry.QNAME).build();
346 commitCohortReg.set(commitCohortRegistry.registerCommitCohort(
347 new org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier(
348 org.opendaylight.mdsal.common.api.LogicalDatastoreType.CONFIGURATION,
349 carEntryPath), new CarEntryDataTreeCommitCohort()));
351 LOG_CAR_PROVIDER.info("Registered commit cohort");
353 return RpcResultBuilder.<Void>success().buildFuture();