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

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.