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