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

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