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.util.concurrent.FutureCallback;
12 import com.google.common.util.concurrent.Futures;
13 import com.google.common.util.concurrent.ListenableFuture;
14 import com.google.common.util.concurrent.MoreExecutors;
15 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
16 import java.util.HashSet;
18 import java.util.concurrent.ConcurrentHashMap;
19 import java.util.concurrent.ExecutionException;
20 import java.util.concurrent.TimeUnit;
21 import java.util.concurrent.TimeoutException;
22 import java.util.concurrent.atomic.AtomicBoolean;
23 import java.util.concurrent.atomic.AtomicLong;
24 import java.util.concurrent.atomic.AtomicReference;
25 import javax.annotation.PreDestroy;
26 import javax.inject.Inject;
27 import javax.inject.Singleton;
28 import org.opendaylight.mdsal.binding.api.DataBroker;
29 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
30 import org.opendaylight.mdsal.binding.api.RpcProviderService;
31 import org.opendaylight.mdsal.binding.api.WriteTransaction;
32 import org.opendaylight.mdsal.common.api.CommitInfo;
33 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
34 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
35 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistration;
36 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistry;
37 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
38 import org.opendaylight.mdsal.eos.binding.api.Entity;
39 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipListener;
40 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipService;
41 import org.opendaylight.mdsal.eos.common.api.CandidateAlreadyRegisteredException;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.CarId;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.CarService;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.Cars;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.CarsBuilder;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterCommitCohortInput;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterCommitCohortOutput;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterCommitCohortOutputBuilder;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterLoggingDtclInput;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterLoggingDtclOutput;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterLoggingDtclOutputBuilder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterOwnershipInput;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterOwnershipOutput;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterOwnershipOutputBuilder;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StopStressTestInput;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StopStressTestOutput;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StopStressTestOutputBuilder;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StressTestInput;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StressTestOutput;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StressTestOutputBuilder;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterCommitCohortInput;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterCommitCohortOutput;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterCommitCohortOutputBuilder;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterLoggingDtclsInput;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterLoggingDtclsOutput;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterLoggingDtclsOutputBuilder;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterOwnershipInput;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterOwnershipOutput;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterOwnershipOutputBuilder;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.cars.CarEntry;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.cars.CarEntryBuilder;
72 import org.opendaylight.yangtools.concepts.ListenerRegistration;
73 import org.opendaylight.yangtools.concepts.ObjectRegistration;
74 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
75 import org.opendaylight.yangtools.yang.common.ErrorType;
76 import org.opendaylight.yangtools.yang.common.RpcResult;
77 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
78 import org.opendaylight.yangtools.yang.common.Uint32;
79 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
80 import org.osgi.service.component.annotations.Activate;
81 import org.osgi.service.component.annotations.Component;
82 import org.osgi.service.component.annotations.Deactivate;
83 import org.osgi.service.component.annotations.Reference;
84 import org.slf4j.Logger;
85 import org.slf4j.LoggerFactory;
88 * Implementation of CarService.
90 * @author Thomas Pantelis
93 @Component(service = { })
94 @SuppressFBWarnings("SLF4J_ILLEGAL_PASSED_CLASS")
95 public final class CarProvider implements CarService {
96 private static final Logger LOG_PURCHASE_CAR = LoggerFactory.getLogger(PurchaseCarProvider.class);
98 private static final Logger LOG_CAR_PROVIDER = LoggerFactory.getLogger(CarProvider.class);
100 private static final String ENTITY_TYPE = "cars";
101 private static final InstanceIdentifier<Cars> CARS_IID = InstanceIdentifier.builder(Cars.class).build();
102 private static final DataTreeIdentifier<Cars> CARS_DTID = DataTreeIdentifier.create(
103 LogicalDatastoreType.CONFIGURATION, CARS_IID);
105 private final DataBroker dataProvider;
106 private final DOMDataBroker domDataBroker;
107 private final EntityOwnershipService ownershipService;
108 private final AtomicLong succcessCounter = new AtomicLong();
109 private final AtomicLong failureCounter = new AtomicLong();
111 private final EntityOwnershipListener ownershipListener =
112 ownershipChange -> LOG_CAR_PROVIDER.info("ownershipChanged: {}", ownershipChange);
114 private final AtomicBoolean registeredListener = new AtomicBoolean();
116 private final Set<ListenerRegistration<?>> carsDclRegistrations = ConcurrentHashMap.newKeySet();
118 private final Set<ObjectRegistration<?>> regs = new HashSet<>();
119 private final Set<ListenerRegistration<CarDataTreeChangeListener>> carsDtclRegistrations =
120 ConcurrentHashMap.newKeySet();
122 private volatile Thread testThread;
123 private volatile boolean stopThread;
124 private final AtomicReference<DOMDataTreeCommitCohortRegistration<CarEntryDataTreeCommitCohort>> commitCohortReg =
125 new AtomicReference<>();
129 public CarProvider(@Reference final DataBroker dataProvider,
130 @Reference final EntityOwnershipService ownershipService, @Reference final DOMDataBroker domDataBroker,
131 @Reference final RpcProviderService rpcProviderService) {
132 this.dataProvider = dataProvider;
133 this.ownershipService = ownershipService;
134 this.domDataBroker = domDataBroker;
135 regs.add(rpcProviderService.registerRpcImplementation(CarService.class, this));
140 public void close() {
142 closeCommitCohortRegistration();
143 regs.forEach(ObjectRegistration::close);
147 private void stopThread() {
148 if (testThread != null) {
150 testThread.interrupt();
153 } catch (InterruptedException e) {
161 public ListenableFuture<RpcResult<StressTestOutput>> stressTest(final StressTestInput input) {
163 final long inputCount;
165 // If rate is not provided, or given as zero, then just return.
166 if (input.getRate() == null || input.getRate().toJava() == 0) {
167 LOG_PURCHASE_CAR.info("Exiting stress test as no rate is given.");
168 return Futures.immediateFuture(RpcResultBuilder.<StressTestOutput>failed()
169 .withError(ErrorType.PROTOCOL, "invalid rate")
173 inputRate = input.getRate().toJava();
174 if (input.getCount() != null) {
175 inputCount = input.getCount().toJava();
180 LOG_PURCHASE_CAR.info("Stress test starting : rate: {} count: {}", inputRate, inputCount);
184 succcessCounter.set(0);
185 failureCounter.set(0);
187 WriteTransaction tx = dataProvider.newWriteOnlyTransaction();
188 InstanceIdentifier<Cars> carsId = InstanceIdentifier.create(Cars.class);
189 tx.merge(LogicalDatastoreType.CONFIGURATION, carsId, new CarsBuilder().build());
191 tx.commit().get(5, TimeUnit.SECONDS);
192 } catch (TimeoutException | InterruptedException | ExecutionException e) {
193 LOG_PURCHASE_CAR.error("Put Cars failed",e);
194 return Futures.immediateFuture(RpcResultBuilder.success(new StressTestOutputBuilder().build()).build());
198 final long sleep = TimeUnit.NANOSECONDS.convert(1000,TimeUnit.MILLISECONDS) / inputRate;
199 final Stopwatch sw = Stopwatch.createUnstarted();
200 testThread = new Thread(() -> {
202 AtomicLong count = new AtomicLong();
203 while (!stopThread) {
204 long id = count.incrementAndGet();
205 WriteTransaction tx1 = dataProvider.newWriteOnlyTransaction();
206 CarEntry car = new CarEntryBuilder().setId(new CarId("car" + id)).build();
207 tx1.put(LogicalDatastoreType.CONFIGURATION,
208 InstanceIdentifier.<Cars>builder(Cars.class).child(CarEntry.class, car.key()).build(), car);
209 tx1.commit().addCallback(new FutureCallback<CommitInfo>() {
212 public void onSuccess(final CommitInfo result) {
213 // Transaction succeeded
214 succcessCounter.getAndIncrement();
218 public void onFailure(final Throwable ex) {
219 // Transaction failed
220 failureCounter.getAndIncrement();
221 LOG_CAR_PROVIDER.error("Put Cars failed", ex);
223 }, MoreExecutors.directExecutor());
225 TimeUnit.NANOSECONDS.sleep(sleep);
226 } catch (InterruptedException e) {
230 if (count.get() % 1000 == 0) {
231 LOG_PURCHASE_CAR.info("Cars created {}, time: {}", count.get(), sw.elapsed(TimeUnit.SECONDS));
234 // Check if a count is specified in input and we have created that many cars.
235 if (inputCount != 0 && count.get() >= inputCount) {
240 LOG_PURCHASE_CAR.info("Stress test thread stopping after creating {} cars.", count.get());
244 return Futures.immediateFuture(RpcResultBuilder.success(new StressTestOutputBuilder().build()).build());
248 public ListenableFuture<RpcResult<StopStressTestOutput>> stopStressTest(final StopStressTestInput input) {
250 StopStressTestOutputBuilder stopStressTestOutput;
251 stopStressTestOutput = new StopStressTestOutputBuilder()
252 .setSuccessCount(Uint32.valueOf(succcessCounter.longValue()))
253 .setFailureCount(Uint32.valueOf(failureCounter.longValue()));
255 final StopStressTestOutput result = stopStressTestOutput.build();
256 LOG_PURCHASE_CAR.info("Executed Stop Stress test; No. of cars created {}; "
257 + "No. of cars failed {}; ", succcessCounter, failureCounter);
259 succcessCounter.set(0);
260 failureCounter.set(0);
261 return Futures.immediateFuture(RpcResultBuilder.<StopStressTestOutput>success(result).build());
266 public ListenableFuture<RpcResult<RegisterOwnershipOutput>> registerOwnership(final RegisterOwnershipInput input) {
267 if (registeredListener.compareAndSet(false, true)) {
268 ownershipService.registerListener(ENTITY_TYPE, ownershipListener);
271 Entity entity = new Entity(ENTITY_TYPE, input.getCarId());
273 ownershipService.registerCandidate(entity);
274 } catch (CandidateAlreadyRegisteredException e) {
275 return RpcResultBuilder.<RegisterOwnershipOutput>failed().withError(ErrorType.APPLICATION,
276 "Could not register for car " + input.getCarId(), e).buildFuture();
279 return RpcResultBuilder.success(new RegisterOwnershipOutputBuilder().build()).buildFuture();
283 public ListenableFuture<RpcResult<UnregisterOwnershipOutput>> unregisterOwnership(
284 final UnregisterOwnershipInput input) {
285 return RpcResultBuilder.success(new UnregisterOwnershipOutputBuilder().build()).buildFuture();
289 public ListenableFuture<RpcResult<RegisterLoggingDtclOutput>> registerLoggingDtcl(
290 final RegisterLoggingDtclInput input) {
291 LOG_CAR_PROVIDER.info("Registering a new CarDataTreeChangeListener");
292 final ListenerRegistration<CarDataTreeChangeListener> carsDtclRegistration =
293 dataProvider.registerDataTreeChangeListener(CARS_DTID, new CarDataTreeChangeListener());
295 carsDtclRegistrations.add(carsDtclRegistration);
296 return RpcResultBuilder.success(new RegisterLoggingDtclOutputBuilder().build()).buildFuture();
300 public ListenableFuture<RpcResult<UnregisterLoggingDtclsOutput>> unregisterLoggingDtcls(
301 final UnregisterLoggingDtclsInput input) {
302 LOG_CAR_PROVIDER.info("Unregistering the CarDataTreeChangeListener(s)");
303 synchronized (carsDtclRegistrations) {
304 int numListeners = 0;
305 for (ListenerRegistration<CarDataTreeChangeListener> carsDtclRegistration : carsDtclRegistrations) {
306 carsDtclRegistration.close();
309 carsDtclRegistrations.clear();
310 LOG_CAR_PROVIDER.info("Unregistered {} CaraDataTreeChangeListener(s)", numListeners);
312 return RpcResultBuilder.success(new UnregisterLoggingDtclsOutputBuilder().build()).buildFuture();
316 @SuppressWarnings("checkstyle:IllegalCatch")
317 public ListenableFuture<RpcResult<UnregisterCommitCohortOutput>> unregisterCommitCohort(
318 final UnregisterCommitCohortInput input) {
319 closeCommitCohortRegistration();
321 return RpcResultBuilder.success(new UnregisterCommitCohortOutputBuilder().build()).buildFuture();
324 private void closeCommitCohortRegistration() {
325 final DOMDataTreeCommitCohortRegistration<CarEntryDataTreeCommitCohort> reg = commitCohortReg.getAndSet(null);
328 LOG_CAR_PROVIDER.info("Unregistered commit cohort");
333 public synchronized ListenableFuture<RpcResult<RegisterCommitCohortOutput>> registerCommitCohort(
334 final RegisterCommitCohortInput input) {
335 if (commitCohortReg.get() != null) {
336 return RpcResultBuilder.success(new RegisterCommitCohortOutputBuilder().build()).buildFuture();
339 final DOMDataTreeCommitCohortRegistry commitCohortRegistry = domDataBroker.getExtensions().getInstance(
340 DOMDataTreeCommitCohortRegistry.class);
342 if (commitCohortRegistry == null) {
344 return RpcResultBuilder.<RegisterCommitCohortOutput>failed().withError(ErrorType.APPLICATION,
345 "DOMDataTreeCommitCohortRegistry not found").buildFuture();
348 // Note: it may look strange that we specify the CarEntry.QNAME twice in the path below. This must be done in
349 // order to register the commit cohort for CarEntry instances. In the underlying data tree, a yang list is
350 // represented as a MapNode with MapEntryNodes representing the child list entries. Therefore, in order to
351 // address a list entry, you must specify the path argument for the MapNode and the path argument for the
352 // MapEntryNode. In the path below, the first CarEntry.QNAME argument addresses the MapNode and, since we want
353 // to address all list entries, the second path argument is wild-carded by specifying just the CarEntry.QNAME.
354 final YangInstanceIdentifier carEntryPath = YangInstanceIdentifier.builder(
355 YangInstanceIdentifier.of(Cars.QNAME)).node(CarEntry.QNAME).node(CarEntry.QNAME).build();
356 commitCohortReg.set(commitCohortRegistry.registerCommitCohort(new DOMDataTreeIdentifier(
357 LogicalDatastoreType.CONFIGURATION, carEntryPath), new CarEntryDataTreeCommitCohort()));
359 LOG_CAR_PROVIDER.info("Registered commit cohort");
361 return RpcResultBuilder.success(new RegisterCommitCohortOutputBuilder().build()).buildFuture();