Bug 4105: Remove EntityOwnershipCandidate
[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.util.concurrent.Futures;
12 import java.util.concurrent.Future;
13 import java.util.concurrent.TimeUnit;
14 import java.util.concurrent.TimeoutException;
15 import java.util.concurrent.atomic.AtomicBoolean;
16 import java.util.concurrent.atomic.AtomicLong;
17 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
18 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
19 import org.opendaylight.controller.md.sal.common.api.clustering.CandidateAlreadyRegisteredException;
20 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
21 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipChange;
22 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListener;
23 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
24 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
25 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.CarId;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.CarService;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.Cars;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.CarsBuilder;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterOwnershipInput;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StressTestInput;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterOwnershipInput;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.cars.CarEntry;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.cars.CarEntryBuilder;
35 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
36 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
37 import org.opendaylight.yangtools.yang.common.RpcResult;
38 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 /**
43  * @author Thomas Pantelis
44  */
45 public class CarProvider implements CarService {
46     private static final Logger log = LoggerFactory.getLogger(PurchaseCarProvider.class);
47
48     private final DataBroker dataProvider;
49     private final EntityOwnershipService ownershipService;
50     private static final Logger LOG = LoggerFactory.getLogger(CarProvider.class);
51
52     private static final String ENTITY_TYPE = "cars";
53
54     private final CarEntityOwnershipListener ownershipListener = new CarEntityOwnershipListener();
55     private final AtomicBoolean registeredListener = new AtomicBoolean();
56
57     private volatile Thread testThread;
58     private volatile boolean stopThread;
59
60     public CarProvider(DataBroker dataProvider, EntityOwnershipService ownershipService) {
61         this.dataProvider = dataProvider;
62         this.ownershipService = ownershipService;
63     }
64
65     private void stopThread() {
66         if(testThread != null) {
67             stopThread = true;
68             testThread.interrupt();
69             try {
70                 testThread.join();
71             } catch (InterruptedException e) {}
72             testThread = null;
73         }
74     }
75
76     @Override
77     public Future<RpcResult<Void>> stressTest(StressTestInput input) {
78         final int inputRate, inputCount;
79
80         // If rate is not provided, or given as zero, then just return.
81         if ((input.getRate() == null) || (input.getRate() == 0)) {
82             log.info("Exiting stress test as no rate is given.");
83             return Futures.immediateFuture(RpcResultBuilder.<Void>failed()
84                                            .withError(ErrorType.PROTOCOL, "invalid rate")
85                                            .build());
86         } else {
87             inputRate = input.getRate();
88         }
89
90         if (input.getCount() != null) {
91             inputCount = input.getCount();
92         } else {
93             inputCount = 0;
94         }
95
96         log.info("Stress test starting : rate: {} count: {}", inputRate, inputCount);
97
98         stopThread();
99
100         WriteTransaction tx = dataProvider.newWriteOnlyTransaction();
101         InstanceIdentifier<Cars> carsId = InstanceIdentifier.<Cars>builder(Cars.class).build();
102         tx.merge(LogicalDatastoreType.CONFIGURATION, carsId, new CarsBuilder().build());
103         try {
104             tx.submit().checkedGet(5, TimeUnit.SECONDS);
105         } catch (TransactionCommitFailedException | TimeoutException e) {
106             log.error("Put Cars failed",e);
107             return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
108         }
109
110         stopThread = false;
111         final long sleep = TimeUnit.NANOSECONDS.convert(1000,TimeUnit.MILLISECONDS) / inputRate;
112         final Stopwatch sw = Stopwatch.createUnstarted();
113         testThread = new Thread() {
114             @Override
115             public void run() {
116                 sw.start();
117                 AtomicLong count = new AtomicLong();
118                 while(!stopThread) {
119                     long id = count.incrementAndGet();
120                     WriteTransaction tx = dataProvider.newWriteOnlyTransaction();
121                     CarEntry car = new CarEntryBuilder().setId(new CarId("car"+id)).build();
122                     tx.put(LogicalDatastoreType.CONFIGURATION,
123                             InstanceIdentifier.<Cars>builder(Cars.class).child(CarEntry.class, car.getKey()).build(),
124                             car);
125                     tx.submit();
126                     try {
127                         TimeUnit.NANOSECONDS.sleep(sleep);
128                     } catch (InterruptedException e) {
129                         break;
130                     }
131
132                     if((count.get() % 1000) == 0) {
133                         log.info("Cars created {}, time: {}",count.get(),sw.elapsed(TimeUnit.SECONDS));
134                     }
135
136                     // Check if a count is specified in input and we have created that many cars.
137                     if ((inputCount != 0) && (count.get() >= inputCount)) {
138                         stopThread = true;
139                     }
140                 }
141
142                 log.info("Stress test thread stopping after creating {} cars.", count.get());
143             }
144         };
145         testThread.start();
146
147         return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
148     }
149
150     @Override
151     public Future<RpcResult<Void>> stopStressTest() {
152         stopThread();
153         return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
154     }
155
156
157     @Override
158     public Future<RpcResult<Void>> registerOwnership(RegisterOwnershipInput input) {
159         if(registeredListener.compareAndSet(false, true)) {
160             ownershipService.registerListener(ENTITY_TYPE, ownershipListener);
161         }
162
163         Entity entity = new Entity(ENTITY_TYPE, input.getCarId());
164         try {
165             ownershipService.registerCandidate(entity);
166         } catch (CandidateAlreadyRegisteredException e) {
167             return RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION,
168                     "Could not register for car " + input.getCarId(), e).buildFuture();
169         }
170
171         return RpcResultBuilder.<Void>success().buildFuture();
172     }
173
174     @Override
175     public Future<RpcResult<Void>> unregisterOwnership(UnregisterOwnershipInput input) {
176         return RpcResultBuilder.<Void>success().buildFuture();
177     }
178
179     private static class CarEntityOwnershipListener implements EntityOwnershipListener {
180         @Override
181         public void ownershipChanged(EntityOwnershipChange ownershipChange) {
182             LOG.info("ownershipChanged: {}", ownershipChange);
183         }
184     }
185 }

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