ea9f7b1d762e3dde09cb24a36d18dd4b397494e6
[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_PURCHASE_CAR = LoggerFactory.getLogger(PurchaseCarProvider.class);
61
62     private static final Logger LOG_CAR_PROVIDER = 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_PURCHASE_CAR.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_PURCHASE_CAR.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_PURCHASE_CAR.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             sw.start();
153             AtomicLong count = new AtomicLong();
154             while(!stopThread) {
155                 long id = count.incrementAndGet();
156                 WriteTransaction tx1 = dataProvider.newWriteOnlyTransaction();
157                 CarEntry car = new CarEntryBuilder().setId(new CarId("car"+id)).build();
158                 tx1.put(LogicalDatastoreType.CONFIGURATION,
159                         InstanceIdentifier.<Cars>builder(Cars.class).child(CarEntry.class, car.getKey()).build(),
160                         car);
161                 CheckedFuture<Void, TransactionCommitFailedException> future = tx1.submit();
162                 Futures.addCallback(future, new FutureCallback<Void>() {
163
164                     @Override
165                     public void onSuccess(final Void result) {
166                         // Transaction succeeded
167                         succcessCounter.getAndIncrement();
168                     }
169
170                     @Override
171                     public void onFailure(final Throwable t) {
172                         // Transaction failed
173                         failureCounter.getAndIncrement();
174                         LOG_CAR_PROVIDER.error("Put Cars failed", t);
175                     }
176                 });
177                 try {
178                     TimeUnit.NANOSECONDS.sleep(sleep);
179                 } catch (InterruptedException e) {
180                     break;
181                 }
182
183                 if(count.get() % 1000 == 0) {
184                     LOG_PURCHASE_CAR.info("Cars created {}, time: {}",count.get(),sw.elapsed(TimeUnit.SECONDS));
185                 }
186
187                 // Check if a count is specified in input and we have created that many cars.
188                 if (inputCount != 0 && count.get() >= inputCount) {
189                     stopThread = true;
190                 }
191             }
192
193             LOG_PURCHASE_CAR.info("Stress test thread stopping after creating {} cars.", count.get());
194         });
195         testThread.start();
196
197         return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
198     }
199
200     @Override
201     public Future<RpcResult<StopStressTestOutput>> stopStressTest() {
202         stopThread();
203         StopStressTestOutputBuilder stopStressTestOutput;
204         stopStressTestOutput = new StopStressTestOutputBuilder()
205                 .setSuccessCount(succcessCounter.longValue())
206                 .setFailureCount(failureCounter.longValue());
207
208         StopStressTestOutput result = stopStressTestOutput.build();
209         LOG_PURCHASE_CAR.info("Executed Stop Stress test; No. of cars created {}; " +
210                 "No. of cars failed {}; ", succcessCounter, failureCounter);
211         // clear counters
212         succcessCounter.set(0);
213         failureCounter.set(0);
214         return Futures.immediateFuture(RpcResultBuilder.<StopStressTestOutput>success(result).build());
215     }
216
217
218     @Override
219     public Future<RpcResult<Void>> registerOwnership(final RegisterOwnershipInput input) {
220         if(registeredListener.compareAndSet(false, true)) {
221             ownershipService.registerListener(ENTITY_TYPE, ownershipListener);
222         }
223
224         Entity entity = new Entity(ENTITY_TYPE, input.getCarId());
225         try {
226             ownershipService.registerCandidate(entity);
227         } catch (CandidateAlreadyRegisteredException e) {
228             return RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION,
229                     "Could not register for car " + input.getCarId(), e).buildFuture();
230         }
231
232         return RpcResultBuilder.<Void>success().buildFuture();
233     }
234
235     @Override
236     public Future<RpcResult<Void>> unregisterOwnership(final UnregisterOwnershipInput input) {
237         return RpcResultBuilder.<Void>success().buildFuture();
238     }
239
240     private static class CarEntityOwnershipListener implements EntityOwnershipListener {
241         @Override
242         public void ownershipChanged(final EntityOwnershipChange ownershipChange) {
243             LOG_CAR_PROVIDER.info("ownershipChanged: {}", ownershipChange);
244         }
245     }
246
247     @Override
248     public Future<RpcResult<java.lang.Void>> registerLoggingDcl() {
249         LOG_CAR_PROVIDER.info("Registering a new CarDataChangeListener");
250         final ListenerRegistration carsDclRegistration = dataProvider.registerDataChangeListener(
251                 LogicalDatastoreType.CONFIGURATION, CARS_IID, new CarDataChangeListener(),
252                 AsyncDataBroker.DataChangeScope.SUBTREE);
253
254         if (carsDclRegistration != null) {
255             carsDclRegistrations.add(carsDclRegistration);
256             return RpcResultBuilder.<Void>success().buildFuture();
257         }
258         return RpcResultBuilder.<Void>failed().buildFuture();
259     }
260
261     @Override
262     public Future<RpcResult<java.lang.Void>> registerLoggingDtcl() {
263         LOG_CAR_PROVIDER.info("Registering a new CarDataTreeChangeListener");
264         final ListenerRegistration<CarDataTreeChangeListener> carsDtclRegistration =
265                 dataProvider.registerDataTreeChangeListener(CARS_DTID, new CarDataTreeChangeListener());
266
267         if (carsDtclRegistration != null) {
268             carsDtclRegistrations.add(carsDtclRegistration);
269             return RpcResultBuilder.<Void>success().buildFuture();
270         }
271         return RpcResultBuilder.<Void>failed().buildFuture();
272     }
273
274     @Override
275     public Future<RpcResult<java.lang.Void>> unregisterLoggingDcls() {
276         LOG_CAR_PROVIDER.info("Unregistering the CarDataChangeListener(s)");
277         synchronized (carsDclRegistrations) {
278             int numListeners = 0;
279             for (ListenerRegistration<?> carsDclRegistration : carsDclRegistrations) {
280                 carsDclRegistration.close();
281                 numListeners++;
282             }
283             carsDclRegistrations.clear();
284             LOG_CAR_PROVIDER.info("Unregistered {} CarDataChangeListener(s)", numListeners);
285         }
286         return RpcResultBuilder.<Void>success().buildFuture();
287     }
288
289     @Override
290     public Future<RpcResult<java.lang.Void>> unregisterLoggingDtcls() {
291         LOG_CAR_PROVIDER.info("Unregistering the CarDataTreeChangeListener(s)");
292         synchronized (carsDtclRegistrations) {
293             int numListeners = 0;
294             for (ListenerRegistration<CarDataTreeChangeListener> carsDtclRegistration : carsDtclRegistrations) {
295                 carsDtclRegistration.close();
296                 numListeners++;
297             }
298             carsDtclRegistrations.clear();
299             LOG_CAR_PROVIDER.info("Unregistered {} CaraDataTreeChangeListener(s)", numListeners);
300         }
301         return RpcResultBuilder.<Void>success().buildFuture();
302     }
303
304     @Override
305     @SuppressWarnings("checkstyle:IllegalCatch")
306     public Future<RpcResult<Void>> unregisterCommitCohort() {
307         final DOMDataTreeCommitCohortRegistration<CarEntryDataTreeCommitCohort> reg = commitCohortReg.getAndSet(null);
308         if (reg != null) {
309             try {
310                 reg.close();
311                 LOG_CAR_PROVIDER.info("Unregistered commit cohort");
312             } catch (Exception e) {
313                 return RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION,
314                         "Error closing commit cohort registration", e).buildFuture();
315             }
316         }
317
318         return RpcResultBuilder.<Void>success().buildFuture();
319     }
320
321     @Override
322     public synchronized Future<RpcResult<Void>> registerCommitCohort() {
323         if (commitCohortReg.get() != null) {
324             return RpcResultBuilder.<Void>success().buildFuture();
325         }
326
327         final DOMDataTreeCommitCohortRegistry commitCohortRegistry = (DOMDataTreeCommitCohortRegistry)
328                 domDataBroker.getSupportedExtensions().get(DOMDataTreeCommitCohortRegistry.class);
329
330         if (commitCohortRegistry == null) {
331             // Shouldn't happen
332             return RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION,
333                     "DOMDataTreeCommitCohortRegistry not found").buildFuture();
334         }
335
336         // Note: it may look strange that we specify the CarEntry.QNAME twice in the path below. This must be done in
337         // order to register the commit cohort for CarEntry instances. In the underlying data tree, a yang list is
338         // represented as a MapNode with MapEntryNodes representing the child list entries. Therefore, in order to
339         // address a list entry, you must specify the path argument for the MapNode and the path argument for the
340         // MapEntryNode. In the path below, the first CarEntry.QNAME argument addresses the MapNode and, since we want
341         // to address all list entries, the second path argument is wild-carded by specifying just the CarEntry.QNAME.
342         final YangInstanceIdentifier carEntryPath = YangInstanceIdentifier.builder(
343                 YangInstanceIdentifier.of(Cars.QNAME)).node(CarEntry.QNAME).node(CarEntry.QNAME).build();
344         commitCohortReg.set(commitCohortRegistry.registerCommitCohort(
345                 new org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier(
346                     org.opendaylight.mdsal.common.api.LogicalDatastoreType.CONFIGURATION,
347                         carEntryPath), new CarEntryDataTreeCommitCohort()));
348
349         LOG_CAR_PROVIDER.info("Registered commit cohort");
350
351         return RpcResultBuilder.<Void>success().buildFuture();
352     }
353 }

©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.