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