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