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