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

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