Remove CarEntityOwnershipListener
[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.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;
86
87 /**
88  * Implementation of CarService.
89  *
90  * @author Thomas Pantelis
91  */
92 @Singleton
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);
97
98     private static final Logger LOG_CAR_PROVIDER = LoggerFactory.getLogger(CarProvider.class);
99
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);
104
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();
110
111     private final EntityOwnershipListener ownershipListener =
112         ownershipChange -> LOG_CAR_PROVIDER.info("ownershipChanged: {}", ownershipChange);
113
114     private final AtomicBoolean registeredListener = new AtomicBoolean();
115
116     private final Set<ListenerRegistration<?>> carsDclRegistrations = ConcurrentHashMap.newKeySet();
117
118     private final Set<ObjectRegistration<?>> regs = new HashSet<>();
119     private final Set<ListenerRegistration<CarDataTreeChangeListener>> carsDtclRegistrations =
120             ConcurrentHashMap.newKeySet();
121
122     private volatile Thread testThread;
123     private volatile boolean stopThread;
124     private final AtomicReference<DOMDataTreeCommitCohortRegistration<CarEntryDataTreeCommitCohort>> commitCohortReg =
125             new AtomicReference<>();
126
127     @Inject
128     @Activate
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));
136     }
137
138     @PreDestroy
139     @Deactivate
140     public void close() {
141         stopThread();
142         closeCommitCohortRegistration();
143         regs.forEach(ObjectRegistration::close);
144         regs.clear();
145     }
146
147     private void stopThread() {
148         if (testThread != null) {
149             stopThread = true;
150             testThread.interrupt();
151             try {
152                 testThread.join();
153             } catch (InterruptedException e) {
154                 // don't care
155             }
156             testThread = null;
157         }
158     }
159
160     @Override
161     public ListenableFuture<RpcResult<StressTestOutput>> stressTest(final StressTestInput input) {
162         final int inputRate;
163         final long inputCount;
164
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")
170                     .build());
171         }
172
173         inputRate = input.getRate().toJava();
174         if (input.getCount() != null) {
175             inputCount = input.getCount().toJava();
176         } else {
177             inputCount = 0;
178         }
179
180         LOG_PURCHASE_CAR.info("Stress test starting : rate: {} count: {}", inputRate, inputCount);
181
182         stopThread();
183         // clear counters
184         succcessCounter.set(0);
185         failureCounter.set(0);
186
187         WriteTransaction tx = dataProvider.newWriteOnlyTransaction();
188         InstanceIdentifier<Cars> carsId = InstanceIdentifier.create(Cars.class);
189         tx.merge(LogicalDatastoreType.CONFIGURATION, carsId, new CarsBuilder().build());
190         try {
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());
195         }
196
197         stopThread = false;
198         final long sleep = TimeUnit.NANOSECONDS.convert(1000,TimeUnit.MILLISECONDS) / inputRate;
199         final Stopwatch sw = Stopwatch.createUnstarted();
200         testThread = new Thread(() -> {
201             sw.start();
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>() {
210
211                     @Override
212                     public void onSuccess(final CommitInfo result) {
213                         // Transaction succeeded
214                         succcessCounter.getAndIncrement();
215                     }
216
217                     @Override
218                     public void onFailure(final Throwable ex) {
219                         // Transaction failed
220                         failureCounter.getAndIncrement();
221                         LOG_CAR_PROVIDER.error("Put Cars failed", ex);
222                     }
223                 }, MoreExecutors.directExecutor());
224                 try {
225                     TimeUnit.NANOSECONDS.sleep(sleep);
226                 } catch (InterruptedException e) {
227                     break;
228                 }
229
230                 if (count.get() % 1000 == 0) {
231                     LOG_PURCHASE_CAR.info("Cars created {}, time: {}", count.get(), sw.elapsed(TimeUnit.SECONDS));
232                 }
233
234                 // Check if a count is specified in input and we have created that many cars.
235                 if (inputCount != 0 && count.get() >= inputCount) {
236                     stopThread = true;
237                 }
238             }
239
240             LOG_PURCHASE_CAR.info("Stress test thread stopping after creating {} cars.", count.get());
241         });
242         testThread.start();
243
244         return Futures.immediateFuture(RpcResultBuilder.success(new StressTestOutputBuilder().build()).build());
245     }
246
247     @Override
248     public ListenableFuture<RpcResult<StopStressTestOutput>> stopStressTest(final StopStressTestInput input) {
249         stopThread();
250         StopStressTestOutputBuilder stopStressTestOutput;
251         stopStressTestOutput = new StopStressTestOutputBuilder()
252                 .setSuccessCount(Uint32.valueOf(succcessCounter.longValue()))
253                 .setFailureCount(Uint32.valueOf(failureCounter.longValue()));
254
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);
258         // clear counters
259         succcessCounter.set(0);
260         failureCounter.set(0);
261         return Futures.immediateFuture(RpcResultBuilder.<StopStressTestOutput>success(result).build());
262     }
263
264
265     @Override
266     public ListenableFuture<RpcResult<RegisterOwnershipOutput>> registerOwnership(final RegisterOwnershipInput input) {
267         if (registeredListener.compareAndSet(false, true)) {
268             ownershipService.registerListener(ENTITY_TYPE, ownershipListener);
269         }
270
271         Entity entity = new Entity(ENTITY_TYPE, input.getCarId());
272         try {
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();
277         }
278
279         return RpcResultBuilder.success(new RegisterOwnershipOutputBuilder().build()).buildFuture();
280     }
281
282     @Override
283     public ListenableFuture<RpcResult<UnregisterOwnershipOutput>> unregisterOwnership(
284             final UnregisterOwnershipInput input) {
285         return RpcResultBuilder.success(new UnregisterOwnershipOutputBuilder().build()).buildFuture();
286     }
287
288     @Override
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());
294
295         carsDtclRegistrations.add(carsDtclRegistration);
296         return RpcResultBuilder.success(new RegisterLoggingDtclOutputBuilder().build()).buildFuture();
297     }
298
299     @Override
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();
307                 numListeners++;
308             }
309             carsDtclRegistrations.clear();
310             LOG_CAR_PROVIDER.info("Unregistered {} CaraDataTreeChangeListener(s)", numListeners);
311         }
312         return RpcResultBuilder.success(new UnregisterLoggingDtclsOutputBuilder().build()).buildFuture();
313     }
314
315     @Override
316     @SuppressWarnings("checkstyle:IllegalCatch")
317     public ListenableFuture<RpcResult<UnregisterCommitCohortOutput>> unregisterCommitCohort(
318             final UnregisterCommitCohortInput input) {
319         closeCommitCohortRegistration();
320
321         return RpcResultBuilder.success(new UnregisterCommitCohortOutputBuilder().build()).buildFuture();
322     }
323
324     private void closeCommitCohortRegistration() {
325         final DOMDataTreeCommitCohortRegistration<CarEntryDataTreeCommitCohort> reg = commitCohortReg.getAndSet(null);
326         if (reg != null) {
327             reg.close();
328             LOG_CAR_PROVIDER.info("Unregistered commit cohort");
329         }
330     }
331
332     @Override
333     public synchronized ListenableFuture<RpcResult<RegisterCommitCohortOutput>> registerCommitCohort(
334             final RegisterCommitCohortInput input) {
335         if (commitCohortReg.get() != null) {
336             return RpcResultBuilder.success(new RegisterCommitCohortOutputBuilder().build()).buildFuture();
337         }
338
339         final DOMDataTreeCommitCohortRegistry commitCohortRegistry = domDataBroker.getExtensions().getInstance(
340             DOMDataTreeCommitCohortRegistry.class);
341
342         if (commitCohortRegistry == null) {
343             // Shouldn't happen
344             return RpcResultBuilder.<RegisterCommitCohortOutput>failed().withError(ErrorType.APPLICATION,
345                     "DOMDataTreeCommitCohortRegistry not found").buildFuture();
346         }
347
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()));
358
359         LOG_CAR_PROVIDER.info("Registered commit cohort");
360
361         return RpcResultBuilder.success(new RegisterCommitCohortOutputBuilder().build()).buildFuture();
362     }
363 }