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