BUG-8858: remove sleeps from test driver
[controller.git] / opendaylight / md-sal / samples / clustering-test-app / provider / src / main / java / org / opendaylight / controller / clustering / it / provider / impl / ProduceTransactionsHandler.java
1 /*
2  * Copyright (c) 2017 Cisco 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
9 package org.opendaylight.controller.clustering.it.provider.impl;
10
11 import com.google.common.base.Preconditions;
12 import com.google.common.util.concurrent.Futures;
13 import com.google.common.util.concurrent.ListenableFuture;
14 import com.google.common.util.concurrent.SettableFuture;
15 import java.util.Collections;
16 import java.util.HashSet;
17 import java.util.Set;
18 import java.util.SplittableRandom;
19 import java.util.concurrent.ExecutionException;
20 import java.util.concurrent.TimeUnit;
21 import java.util.concurrent.TimeoutException;
22 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
23 import org.opendaylight.mdsal.dom.api.DOMDataTreeCursorAwareTransaction;
24 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
25 import org.opendaylight.mdsal.dom.api.DOMDataTreeProducer;
26 import org.opendaylight.mdsal.dom.api.DOMDataTreeProducerException;
27 import org.opendaylight.mdsal.dom.api.DOMDataTreeService;
28 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteCursor;
29 import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.ProduceTransactionsInput;
30 import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.ProduceTransactionsOutput;
31 import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.ProduceTransactionsOutputBuilder;
32 import org.opendaylight.yangtools.yang.common.RpcError;
33 import org.opendaylight.yangtools.yang.common.RpcResult;
34 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
36 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
37 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
39 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 public final class ProduceTransactionsHandler extends AbstractTransactionHandler {
44     private static final Logger LOG = LoggerFactory.getLogger(ProduceTransactionsHandler.class);
45
46     private final SettableFuture<RpcResult<ProduceTransactionsOutput>> future = SettableFuture.create();
47     private final SplittableRandom random = new SplittableRandom();
48     private final Set<Integer> usedValues = new HashSet<>();
49     private final DOMDataTreeIdentifier idListItem;
50     private final DOMDataTreeProducer itemProducer;
51
52     private long insertTx = 0;
53     private long deleteTx = 0;
54
55     private ProduceTransactionsHandler(final DOMDataTreeProducer producer, final DOMDataTreeIdentifier idListItem,
56             final ProduceTransactionsInput input) {
57         super(input);
58         this.itemProducer = Preconditions.checkNotNull(producer);
59         this.idListItem = Preconditions.checkNotNull(idListItem);
60     }
61
62     public static ListenableFuture<RpcResult<ProduceTransactionsOutput>> start(
63             final DOMDataTreeService domDataTreeService, final ProduceTransactionsInput input) {
64         final String id = input.getId();
65         LOG.debug("Filling the item list {} with initial values.", id);
66
67         final YangInstanceIdentifier idListWithKey = ID_INT_YID.node(new NodeIdentifierWithPredicates(ID_INT, ID, id));
68
69         final DOMDataTreeProducer itemProducer = domDataTreeService.createProducer(
70             Collections.singleton(new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, idListWithKey)));
71
72         final DOMDataTreeCursorAwareTransaction tx = itemProducer.createTransaction(false);
73         final DOMDataTreeWriteCursor cursor =
74                 tx.createCursor(new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, idListWithKey));
75
76         final MapNode list = ImmutableNodes.mapNodeBuilder(ITEM).build();
77         cursor.write(list.getIdentifier(), list);
78         cursor.close();
79
80         try {
81             tx.submit().get(INIT_TX_TIMEOUT_SECONDS, TimeUnit.SECONDS);
82         } catch (InterruptedException | ExecutionException | TimeoutException e) {
83             LOG.warn("Unable to fill the initial item list.", e);
84             closeProducer(itemProducer);
85
86             return Futures.immediateFuture(RpcResultBuilder.<ProduceTransactionsOutput>failed()
87                 .withError(RpcError.ErrorType.APPLICATION, "Unexpected-exception", e).build());
88         }
89
90         final ProduceTransactionsHandler handler = new ProduceTransactionsHandler(itemProducer,
91             new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, idListWithKey.node(list.getIdentifier())
92                 .toOptimized()), input);
93         // It is handler's responsibility to close itemProducer when the work is finished.
94         handler.doStart();
95         return handler.future;
96     }
97
98     private static void closeProducer(final DOMDataTreeProducer producer) {
99         try {
100             producer.close();
101         } catch (final DOMDataTreeProducerException exception) {
102             LOG.warn("Failure while closing producer.", exception);
103         }
104     }
105
106     @Override
107     ListenableFuture<Void> execWrite(final long txId) {
108         final int i = random.nextInt(MAX_ITEM + 1);
109         final DOMDataTreeCursorAwareTransaction tx = itemProducer.createTransaction(false);
110         final DOMDataTreeWriteCursor cursor = tx.createCursor(idListItem);
111
112         final NodeIdentifierWithPredicates entryId = new NodeIdentifierWithPredicates(ITEM, NUMBER, i);
113         if (usedValues.contains(i)) {
114             LOG.debug("Deleting item: {}", i);
115             deleteTx++;
116             cursor.delete(entryId);
117             usedValues.remove(i);
118
119         } else {
120             LOG.debug("Inserting item: {}", i);
121             insertTx++;
122
123             final MapEntryNode entry = ImmutableNodes.mapEntryBuilder().withNodeIdentifier(entryId)
124                     .withChild(ImmutableNodes.leafNode(NUMBER, i)).build();
125             cursor.write(entryId, entry);
126             usedValues.add(i);
127         }
128
129         cursor.close();
130
131         return tx.submit();
132     }
133
134     @Override
135     void runFailed(final Throwable cause) {
136         closeProducer(itemProducer);
137         future.set(RpcResultBuilder.<ProduceTransactionsOutput>failed()
138             .withError(RpcError.ErrorType.APPLICATION, "Submit failed", cause).build());
139     }
140
141     @Override
142     void runSuccessful(final long allTx) {
143         closeProducer(itemProducer);
144         final ProduceTransactionsOutput output = new ProduceTransactionsOutputBuilder()
145                 .setAllTx(allTx)
146                 .setInsertTx(insertTx)
147                 .setDeleteTx(deleteTx)
148                 .build();
149         future.set(RpcResultBuilder.<ProduceTransactionsOutput>success()
150                 .withResult(output).build());
151     }
152
153     @Override
154     void runTimedOut(final Exception cause) {
155         closeProducer(itemProducer);
156         future.set(RpcResultBuilder.<ProduceTransactionsOutput>failed()
157             .withError(RpcError.ErrorType.APPLICATION,
158                     "Final submit was timed out by the test provider or was interrupted", cause).build());
159     }
160 }