e4b70d2277474ab2697e887dcc3b6c35672beabf
[controller.git] / opendaylight / md-sal / samples / clustering-test-app / provider / src / main / java / org / opendaylight / controller / clustering / it / provider / CarProvider.java
1 /*
2  * Copyright (c) 2015 Brocade Communications Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.clustering.it.provider;
9
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;
17 import java.util.Set;
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.EntityOwnershipChange;
40 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipListener;
41 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipService;
42 import org.opendaylight.mdsal.eos.common.api.CandidateAlreadyRegisteredException;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.CarId;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.CarService;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.Cars;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.CarsBuilder;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterCommitCohortInput;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterCommitCohortOutput;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterCommitCohortOutputBuilder;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterLoggingDtclInput;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterLoggingDtclOutput;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterLoggingDtclOutputBuilder;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterOwnershipInput;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterOwnershipOutput;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterOwnershipOutputBuilder;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StopStressTestInput;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StopStressTestOutput;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StopStressTestOutputBuilder;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StressTestInput;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StressTestOutput;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StressTestOutputBuilder;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterCommitCohortInput;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterCommitCohortOutput;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterCommitCohortOutputBuilder;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterLoggingDtclsInput;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterLoggingDtclsOutput;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterLoggingDtclsOutputBuilder;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterOwnershipInput;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterOwnershipOutput;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterOwnershipOutputBuilder;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.cars.CarEntry;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.cars.CarEntryBuilder;
73 import org.opendaylight.yangtools.concepts.ListenerRegistration;
74 import org.opendaylight.yangtools.concepts.ObjectRegistration;
75 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
76 import org.opendaylight.yangtools.yang.common.ErrorType;
77 import org.opendaylight.yangtools.yang.common.RpcResult;
78 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
79 import org.opendaylight.yangtools.yang.common.Uint32;
80 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
81 import org.osgi.service.component.annotations.Activate;
82 import org.osgi.service.component.annotations.Component;
83 import org.osgi.service.component.annotations.Deactivate;
84 import org.osgi.service.component.annotations.Reference;
85 import org.slf4j.Logger;
86 import org.slf4j.LoggerFactory;
87
88 /**
89  * Implementation of CarService.
90  *
91  * @author Thomas Pantelis
92  */
93 @Singleton
94 @Component(service = { })
95 @SuppressFBWarnings("SLF4J_ILLEGAL_PASSED_CLASS")
96 public final class CarProvider implements CarService {
97     private static final Logger LOG_PURCHASE_CAR = LoggerFactory.getLogger(PurchaseCarProvider.class);
98
99     private static final Logger LOG_CAR_PROVIDER = LoggerFactory.getLogger(CarProvider.class);
100
101     private static final String ENTITY_TYPE = "cars";
102     private static final InstanceIdentifier<Cars> CARS_IID = InstanceIdentifier.builder(Cars.class).build();
103     private static final DataTreeIdentifier<Cars> CARS_DTID = DataTreeIdentifier.create(
104             LogicalDatastoreType.CONFIGURATION, CARS_IID);
105
106     private final DataBroker dataProvider;
107     private final DOMDataBroker domDataBroker;
108     private final EntityOwnershipService ownershipService;
109     private final AtomicLong succcessCounter = new AtomicLong();
110     private final AtomicLong failureCounter = new AtomicLong();
111
112     private final CarEntityOwnershipListener ownershipListener = new CarEntityOwnershipListener();
113     private final AtomicBoolean registeredListener = new AtomicBoolean();
114
115     private final Set<ListenerRegistration<?>> carsDclRegistrations = ConcurrentHashMap.newKeySet();
116
117     private final Set<ObjectRegistration<?>> regs = new HashSet<>();
118     private final Set<ListenerRegistration<CarDataTreeChangeListener>> carsDtclRegistrations =
119             ConcurrentHashMap.newKeySet();
120
121     private volatile Thread testThread;
122     private volatile boolean stopThread;
123     private final AtomicReference<DOMDataTreeCommitCohortRegistration<CarEntryDataTreeCommitCohort>> commitCohortReg =
124             new AtomicReference<>();
125
126     @Inject
127     @Activate
128     public CarProvider(@Reference final DataBroker dataProvider,
129             @Reference final EntityOwnershipService ownershipService, @Reference final DOMDataBroker domDataBroker,
130             @Reference final RpcProviderService rpcProviderService) {
131         this.dataProvider = dataProvider;
132         this.ownershipService = ownershipService;
133         this.domDataBroker = domDataBroker;
134         regs.add(rpcProviderService.registerRpcImplementation(CarService.class, this));
135     }
136
137     @PreDestroy
138     @Deactivate
139     public void close() {
140         stopThread();
141         closeCommitCohortRegistration();
142         regs.forEach(ObjectRegistration::close);
143         regs.clear();
144     }
145
146     private void stopThread() {
147         if (testThread != null) {
148             stopThread = true;
149             testThread.interrupt();
150             try {
151                 testThread.join();
152             } catch (InterruptedException e) {
153                 // don't care
154             }
155             testThread = null;
156         }
157     }
158
159     @Override
160     public ListenableFuture<RpcResult<StressTestOutput>> stressTest(final StressTestInput input) {
161         final int inputRate;
162         final long inputCount;
163
164         // If rate is not provided, or given as zero, then just return.
165         if (input.getRate() == null || input.getRate().toJava() == 0) {
166             LOG_PURCHASE_CAR.info("Exiting stress test as no rate is given.");
167             return Futures.immediateFuture(RpcResultBuilder.<StressTestOutput>failed()
168                     .withError(ErrorType.PROTOCOL, "invalid rate")
169                     .build());
170         }
171
172         inputRate = input.getRate().toJava();
173         if (input.getCount() != null) {
174             inputCount = input.getCount().toJava();
175         } else {
176             inputCount = 0;
177         }
178
179         LOG_PURCHASE_CAR.info("Stress test starting : rate: {} count: {}", inputRate, inputCount);
180
181         stopThread();
182         // clear counters
183         succcessCounter.set(0);
184         failureCounter.set(0);
185
186         WriteTransaction tx = dataProvider.newWriteOnlyTransaction();
187         InstanceIdentifier<Cars> carsId = InstanceIdentifier.create(Cars.class);
188         tx.merge(LogicalDatastoreType.CONFIGURATION, carsId, new CarsBuilder().build());
189         try {
190             tx.commit().get(5, TimeUnit.SECONDS);
191         } catch (TimeoutException | InterruptedException | ExecutionException e) {
192             LOG_PURCHASE_CAR.error("Put Cars failed",e);
193             return Futures.immediateFuture(RpcResultBuilder.success(new StressTestOutputBuilder().build()).build());
194         }
195
196         stopThread = false;
197         final long sleep = TimeUnit.NANOSECONDS.convert(1000,TimeUnit.MILLISECONDS) / inputRate;
198         final Stopwatch sw = Stopwatch.createUnstarted();
199         testThread = new Thread(() -> {
200             sw.start();
201             AtomicLong count = new AtomicLong();
202             while (!stopThread) {
203                 long id = count.incrementAndGet();
204                 WriteTransaction tx1 = dataProvider.newWriteOnlyTransaction();
205                 CarEntry car = new CarEntryBuilder().setId(new CarId("car" + id)).build();
206                 tx1.put(LogicalDatastoreType.CONFIGURATION,
207                         InstanceIdentifier.<Cars>builder(Cars.class).child(CarEntry.class, car.key()).build(), car);
208                 tx1.commit().addCallback(new FutureCallback<CommitInfo>() {
209
210                     @Override
211                     public void onSuccess(final CommitInfo result) {
212                         // Transaction succeeded
213                         succcessCounter.getAndIncrement();
214                     }
215
216                     @Override
217                     public void onFailure(final Throwable ex) {
218                         // Transaction failed
219                         failureCounter.getAndIncrement();
220                         LOG_CAR_PROVIDER.error("Put Cars failed", ex);
221                     }
222                 }, MoreExecutors.directExecutor());
223                 try {
224                     TimeUnit.NANOSECONDS.sleep(sleep);
225                 } catch (InterruptedException e) {
226                     break;
227                 }
228
229                 if (count.get() % 1000 == 0) {
230                     LOG_PURCHASE_CAR.info("Cars created {}, time: {}", count.get(), sw.elapsed(TimeUnit.SECONDS));
231                 }
232
233                 // Check if a count is specified in input and we have created that many cars.
234                 if (inputCount != 0 && count.get() >= inputCount) {
235                     stopThread = true;
236                 }
237             }
238
239             LOG_PURCHASE_CAR.info("Stress test thread stopping after creating {} cars.", count.get());
240         });
241         testThread.start();
242
243         return Futures.immediateFuture(RpcResultBuilder.success(new StressTestOutputBuilder().build()).build());
244     }
245
246     @Override
247     public ListenableFuture<RpcResult<StopStressTestOutput>> stopStressTest(final StopStressTestInput input) {
248         stopThread();
249         StopStressTestOutputBuilder stopStressTestOutput;
250         stopStressTestOutput = new StopStressTestOutputBuilder()
251                 .setSuccessCount(Uint32.valueOf(succcessCounter.longValue()))
252                 .setFailureCount(Uint32.valueOf(failureCounter.longValue()));
253
254         final StopStressTestOutput result = stopStressTestOutput.build();
255         LOG_PURCHASE_CAR.info("Executed Stop Stress test; No. of cars created {}; "
256                 + "No. of cars failed {}; ", succcessCounter, failureCounter);
257         // clear counters
258         succcessCounter.set(0);
259         failureCounter.set(0);
260         return Futures.immediateFuture(RpcResultBuilder.<StopStressTestOutput>success(result).build());
261     }
262
263
264     @Override
265     public ListenableFuture<RpcResult<RegisterOwnershipOutput>> registerOwnership(final RegisterOwnershipInput input) {
266         if (registeredListener.compareAndSet(false, true)) {
267             ownershipService.registerListener(ENTITY_TYPE, ownershipListener);
268         }
269
270         Entity entity = new Entity(ENTITY_TYPE, input.getCarId());
271         try {
272             ownershipService.registerCandidate(entity);
273         } catch (CandidateAlreadyRegisteredException e) {
274             return RpcResultBuilder.<RegisterOwnershipOutput>failed().withError(ErrorType.APPLICATION,
275                     "Could not register for car " + input.getCarId(), e).buildFuture();
276         }
277
278         return RpcResultBuilder.success(new RegisterOwnershipOutputBuilder().build()).buildFuture();
279     }
280
281     @Override
282     public ListenableFuture<RpcResult<UnregisterOwnershipOutput>> unregisterOwnership(
283             final UnregisterOwnershipInput input) {
284         return RpcResultBuilder.success(new UnregisterOwnershipOutputBuilder().build()).buildFuture();
285     }
286
287     private static class CarEntityOwnershipListener implements EntityOwnershipListener {
288         @Override
289         public void ownershipChanged(final EntityOwnershipChange ownershipChange) {
290             LOG_CAR_PROVIDER.info("ownershipChanged: {}", ownershipChange);
291         }
292     }
293
294     @Override
295     public ListenableFuture<RpcResult<RegisterLoggingDtclOutput>> registerLoggingDtcl(
296             final RegisterLoggingDtclInput input) {
297         LOG_CAR_PROVIDER.info("Registering a new CarDataTreeChangeListener");
298         final ListenerRegistration<CarDataTreeChangeListener> carsDtclRegistration =
299                 dataProvider.registerDataTreeChangeListener(CARS_DTID, new CarDataTreeChangeListener());
300
301         carsDtclRegistrations.add(carsDtclRegistration);
302         return RpcResultBuilder.success(new RegisterLoggingDtclOutputBuilder().build()).buildFuture();
303     }
304
305     @Override
306     public ListenableFuture<RpcResult<UnregisterLoggingDtclsOutput>> unregisterLoggingDtcls(
307             final UnregisterLoggingDtclsInput input) {
308         LOG_CAR_PROVIDER.info("Unregistering the CarDataTreeChangeListener(s)");
309         synchronized (carsDtclRegistrations) {
310             int numListeners = 0;
311             for (ListenerRegistration<CarDataTreeChangeListener> carsDtclRegistration : carsDtclRegistrations) {
312                 carsDtclRegistration.close();
313                 numListeners++;
314             }
315             carsDtclRegistrations.clear();
316             LOG_CAR_PROVIDER.info("Unregistered {} CaraDataTreeChangeListener(s)", numListeners);
317         }
318         return RpcResultBuilder.success(new UnregisterLoggingDtclsOutputBuilder().build()).buildFuture();
319     }
320
321     @Override
322     @SuppressWarnings("checkstyle:IllegalCatch")
323     public ListenableFuture<RpcResult<UnregisterCommitCohortOutput>> unregisterCommitCohort(
324             final UnregisterCommitCohortInput input) {
325         closeCommitCohortRegistration();
326
327         return RpcResultBuilder.success(new UnregisterCommitCohortOutputBuilder().build()).buildFuture();
328     }
329
330     private void closeCommitCohortRegistration() {
331         final DOMDataTreeCommitCohortRegistration<CarEntryDataTreeCommitCohort> reg = commitCohortReg.getAndSet(null);
332         if (reg != null) {
333             reg.close();
334             LOG_CAR_PROVIDER.info("Unregistered commit cohort");
335         }
336     }
337
338     @Override
339     public synchronized ListenableFuture<RpcResult<RegisterCommitCohortOutput>> registerCommitCohort(
340             final RegisterCommitCohortInput input) {
341         if (commitCohortReg.get() != null) {
342             return RpcResultBuilder.success(new RegisterCommitCohortOutputBuilder().build()).buildFuture();
343         }
344
345         final DOMDataTreeCommitCohortRegistry commitCohortRegistry = domDataBroker.getExtensions().getInstance(
346             DOMDataTreeCommitCohortRegistry.class);
347
348         if (commitCohortRegistry == null) {
349             // Shouldn't happen
350             return RpcResultBuilder.<RegisterCommitCohortOutput>failed().withError(ErrorType.APPLICATION,
351                     "DOMDataTreeCommitCohortRegistry not found").buildFuture();
352         }
353
354         // Note: it may look strange that we specify the CarEntry.QNAME twice in the path below. This must be done in
355         // order to register the commit cohort for CarEntry instances. In the underlying data tree, a yang list is
356         // represented as a MapNode with MapEntryNodes representing the child list entries. Therefore, in order to
357         // address a list entry, you must specify the path argument for the MapNode and the path argument for the
358         // MapEntryNode. In the path below, the first CarEntry.QNAME argument addresses the MapNode and, since we want
359         // to address all list entries, the second path argument is wild-carded by specifying just the CarEntry.QNAME.
360         final YangInstanceIdentifier carEntryPath = YangInstanceIdentifier.builder(
361                 YangInstanceIdentifier.of(Cars.QNAME)).node(CarEntry.QNAME).node(CarEntry.QNAME).build();
362         commitCohortReg.set(commitCohortRegistry.registerCommitCohort(new DOMDataTreeIdentifier(
363             LogicalDatastoreType.CONFIGURATION, carEntryPath), new CarEntryDataTreeCommitCohort()));
364
365         LOG_CAR_PROVIDER.info("Registered commit cohort");
366
367         return RpcResultBuilder.success(new RegisterCommitCohortOutputBuilder().build()).buildFuture();
368     }
369 }