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