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 com.google.common.util.concurrent.MoreExecutors;
16 import java.util.Collection;
17 import java.util.concurrent.Future;
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.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.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 * Implementation of CarService.
59 * @author Thomas Pantelis
61 public class CarProvider implements CarService {
62 private static final Logger LOG_PURCHASE_CAR = LoggerFactory.getLogger(PurchaseCarProvider.class);
64 private static final Logger LOG_CAR_PROVIDER = LoggerFactory.getLogger(CarProvider.class);
66 private static final String ENTITY_TYPE = "cars";
67 private static final InstanceIdentifier<Cars> CARS_IID = InstanceIdentifier.builder(Cars.class).build();
68 private static final DataTreeIdentifier<Cars> CARS_DTID = new DataTreeIdentifier<>(
69 LogicalDatastoreType.CONFIGURATION, CARS_IID);
71 private final DataBroker dataProvider;
72 private final DOMDataBroker domDataBroker;
73 private final EntityOwnershipService ownershipService;
74 private final AtomicLong succcessCounter = new AtomicLong();
75 private final AtomicLong failureCounter = new AtomicLong();
77 private final CarEntityOwnershipListener ownershipListener = new CarEntityOwnershipListener();
78 private final AtomicBoolean registeredListener = new AtomicBoolean();
80 private final Collection<ListenerRegistration<?>> carsDclRegistrations =
81 Sets.newConcurrentHashSet();
82 private final Collection<ListenerRegistration<CarDataTreeChangeListener>> carsDtclRegistrations =
83 Sets.newConcurrentHashSet();
85 private volatile Thread testThread;
86 private volatile boolean stopThread;
87 private final AtomicReference<DOMDataTreeCommitCohortRegistration<CarEntryDataTreeCommitCohort>> commitCohortReg =
88 new AtomicReference<>();
90 public CarProvider(final DataBroker dataProvider, final EntityOwnershipService ownershipService,
91 final DOMDataBroker domDataBroker) {
92 this.dataProvider = dataProvider;
93 this.ownershipService = ownershipService;
94 this.domDataBroker = domDataBroker;
99 closeCommitCohortRegistration();
102 private void stopThread() {
103 if (testThread != null) {
105 testThread.interrupt();
108 } catch (InterruptedException e) {
116 public Future<RpcResult<Void>> stressTest(final StressTestInput input) {
118 final long inputCount;
120 // If rate is not provided, or given as zero, then just return.
121 if (input.getRate() == null || input.getRate() == 0) {
122 LOG_PURCHASE_CAR.info("Exiting stress test as no rate is given.");
123 return Futures.immediateFuture(RpcResultBuilder.<Void>failed()
124 .withError(ErrorType.PROTOCOL, "invalid rate")
128 inputRate = input.getRate();
129 if (input.getCount() != null) {
130 inputCount = input.getCount();
135 LOG_PURCHASE_CAR.info("Stress test starting : rate: {} count: {}", inputRate, inputCount);
139 succcessCounter.set(0);
140 failureCounter.set(0);
142 WriteTransaction tx = dataProvider.newWriteOnlyTransaction();
143 InstanceIdentifier<Cars> carsId = InstanceIdentifier.<Cars>builder(Cars.class).build();
144 tx.merge(LogicalDatastoreType.CONFIGURATION, carsId, new CarsBuilder().build());
146 tx.submit().checkedGet(5, TimeUnit.SECONDS);
147 } catch (TransactionCommitFailedException | TimeoutException e) {
148 LOG_PURCHASE_CAR.error("Put Cars failed",e);
149 return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
153 final long sleep = TimeUnit.NANOSECONDS.convert(1000,TimeUnit.MILLISECONDS) / inputRate;
154 final Stopwatch sw = Stopwatch.createUnstarted();
155 testThread = new Thread(() -> {
157 AtomicLong count = new AtomicLong();
158 while (!stopThread) {
159 long id = count.incrementAndGet();
160 WriteTransaction tx1 = dataProvider.newWriteOnlyTransaction();
161 CarEntry car = new CarEntryBuilder().setId(new CarId("car" + id)).build();
162 tx1.put(LogicalDatastoreType.CONFIGURATION,
163 InstanceIdentifier.<Cars>builder(Cars.class).child(CarEntry.class, car.getKey()).build(),
165 CheckedFuture<Void, TransactionCommitFailedException> future = tx1.submit();
166 Futures.addCallback(future, new FutureCallback<Void>() {
169 public void onSuccess(final Void result) {
170 // Transaction succeeded
171 succcessCounter.getAndIncrement();
175 public void onFailure(final Throwable ex) {
176 // Transaction failed
177 failureCounter.getAndIncrement();
178 LOG_CAR_PROVIDER.error("Put Cars failed", ex);
180 }, MoreExecutors.directExecutor());
182 TimeUnit.NANOSECONDS.sleep(sleep);
183 } catch (InterruptedException e) {
187 if (count.get() % 1000 == 0) {
188 LOG_PURCHASE_CAR.info("Cars created {}, time: {}",count.get(),sw.elapsed(TimeUnit.SECONDS));
191 // Check if a count is specified in input and we have created that many cars.
192 if (inputCount != 0 && count.get() >= inputCount) {
197 LOG_PURCHASE_CAR.info("Stress test thread stopping after creating {} cars.", count.get());
201 return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
205 public Future<RpcResult<StopStressTestOutput>> stopStressTest() {
207 StopStressTestOutputBuilder stopStressTestOutput;
208 stopStressTestOutput = new StopStressTestOutputBuilder()
209 .setSuccessCount(succcessCounter.longValue())
210 .setFailureCount(failureCounter.longValue());
212 final StopStressTestOutput result = stopStressTestOutput.build();
213 LOG_PURCHASE_CAR.info("Executed Stop Stress test; No. of cars created {}; "
214 + "No. of cars failed {}; ", succcessCounter, failureCounter);
216 succcessCounter.set(0);
217 failureCounter.set(0);
218 return Futures.immediateFuture(RpcResultBuilder.<StopStressTestOutput>success(result).build());
223 public Future<RpcResult<Void>> registerOwnership(final RegisterOwnershipInput input) {
224 if (registeredListener.compareAndSet(false, true)) {
225 ownershipService.registerListener(ENTITY_TYPE, ownershipListener);
228 Entity entity = new Entity(ENTITY_TYPE, input.getCarId());
230 ownershipService.registerCandidate(entity);
231 } catch (CandidateAlreadyRegisteredException e) {
232 return RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION,
233 "Could not register for car " + input.getCarId(), e).buildFuture();
236 return RpcResultBuilder.<Void>success().buildFuture();
240 public Future<RpcResult<Void>> unregisterOwnership(final UnregisterOwnershipInput input) {
241 return RpcResultBuilder.<Void>success().buildFuture();
244 private static class CarEntityOwnershipListener implements EntityOwnershipListener {
246 public void ownershipChanged(final EntityOwnershipChange ownershipChange) {
247 LOG_CAR_PROVIDER.info("ownershipChanged: {}", ownershipChange);
252 public Future<RpcResult<java.lang.Void>> registerLoggingDtcl() {
253 LOG_CAR_PROVIDER.info("Registering a new CarDataTreeChangeListener");
254 final ListenerRegistration<CarDataTreeChangeListener> carsDtclRegistration =
255 dataProvider.registerDataTreeChangeListener(CARS_DTID, new CarDataTreeChangeListener());
257 carsDtclRegistrations.add(carsDtclRegistration);
258 return RpcResultBuilder.<Void>success().buildFuture();
262 public Future<RpcResult<java.lang.Void>> unregisterLoggingDtcls() {
263 LOG_CAR_PROVIDER.info("Unregistering the CarDataTreeChangeListener(s)");
264 synchronized (carsDtclRegistrations) {
265 int numListeners = 0;
266 for (ListenerRegistration<CarDataTreeChangeListener> carsDtclRegistration : carsDtclRegistrations) {
267 carsDtclRegistration.close();
270 carsDtclRegistrations.clear();
271 LOG_CAR_PROVIDER.info("Unregistered {} CaraDataTreeChangeListener(s)", numListeners);
273 return RpcResultBuilder.<Void>success().buildFuture();
277 @SuppressWarnings("checkstyle:IllegalCatch")
278 public Future<RpcResult<Void>> unregisterCommitCohort() {
279 closeCommitCohortRegistration();
281 return RpcResultBuilder.<Void>success().buildFuture();
284 private void closeCommitCohortRegistration() {
285 final DOMDataTreeCommitCohortRegistration<CarEntryDataTreeCommitCohort> reg = commitCohortReg.getAndSet(null);
288 LOG_CAR_PROVIDER.info("Unregistered commit cohort");
293 public synchronized Future<RpcResult<Void>> registerCommitCohort() {
294 if (commitCohortReg.get() != null) {
295 return RpcResultBuilder.<Void>success().buildFuture();
298 final DOMDataTreeCommitCohortRegistry commitCohortRegistry = (DOMDataTreeCommitCohortRegistry)
299 domDataBroker.getSupportedExtensions().get(DOMDataTreeCommitCohortRegistry.class);
301 if (commitCohortRegistry == null) {
303 return RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION,
304 "DOMDataTreeCommitCohortRegistry not found").buildFuture();
307 // Note: it may look strange that we specify the CarEntry.QNAME twice in the path below. This must be done in
308 // order to register the commit cohort for CarEntry instances. In the underlying data tree, a yang list is
309 // represented as a MapNode with MapEntryNodes representing the child list entries. Therefore, in order to
310 // address a list entry, you must specify the path argument for the MapNode and the path argument for the
311 // MapEntryNode. In the path below, the first CarEntry.QNAME argument addresses the MapNode and, since we want
312 // to address all list entries, the second path argument is wild-carded by specifying just the CarEntry.QNAME.
313 final YangInstanceIdentifier carEntryPath = YangInstanceIdentifier.builder(
314 YangInstanceIdentifier.of(Cars.QNAME)).node(CarEntry.QNAME).node(CarEntry.QNAME).build();
315 commitCohortReg.set(commitCohortRegistry.registerCommitCohort(
316 new org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier(
317 org.opendaylight.mdsal.common.api.LogicalDatastoreType.CONFIGURATION,
318 carEntryPath), new CarEntryDataTreeCommitCohort()));
320 LOG_CAR_PROVIDER.info("Registered commit cohort");
322 return RpcResultBuilder.<Void>success().buildFuture();