blob: 607e25dc781a5b7e7040bfa3a21241f685aad066 [file] [log] [blame]
Madan Jampani3289fbf2016-01-13 14:14:27 -08001/*
2 * Copyright 2016 Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.store.primitives.impl;
17
18import static com.google.common.base.Preconditions.checkNotNull;
19
20import java.util.Set;
21import java.util.concurrent.CompletableFuture;
22import org.apache.commons.lang.math.RandomUtils;
23import org.onosproject.store.cluster.messaging.MessagingService;
24
25import com.google.common.collect.Sets;
26
27import io.atomix.catalyst.transport.Address;
28import io.atomix.catalyst.transport.Client;
29import io.atomix.catalyst.transport.Connection;
30import io.atomix.catalyst.util.concurrent.ThreadContext;
31
32/**
33 * {@link Client} implementation for {@link CopycatTransport}.
34 */
35public class CopycatTransportClient implements Client {
36
37 private final String clusterName;
38 private final MessagingService messagingService;
39 private final CopycatTransport.Mode mode;
40 private final ThreadContext context;
41 private final Set<CopycatTransportConnection> connections = Sets.newConcurrentHashSet();
42
43 CopycatTransportClient(String clusterName, MessagingService messagingService, CopycatTransport.Mode mode) {
44 this.clusterName = checkNotNull(clusterName);
45 this.messagingService = checkNotNull(messagingService);
46 this.mode = checkNotNull(mode);
47 this.context = ThreadContext.currentContextOrThrow();
48 }
49
50 @Override
51 public CompletableFuture<Connection> connect(Address remoteAddress) {
52 CopycatTransportConnection connection = new CopycatTransportConnection(
53 nextConnectionId(),
54 CopycatTransport.Mode.CLIENT,
55 clusterName,
56 remoteAddress,
57 messagingService,
58 context);
59 if (mode == CopycatTransport.Mode.CLIENT) {
60 connection.setBidirectional();
61 }
62 connections.add(connection);
63 return CompletableFuture.supplyAsync(() -> connection, context.executor());
64 }
65
66 @Override
67 public CompletableFuture<Void> close() {
68 return CompletableFuture.allOf(connections.stream().map(Connection::close).toArray(CompletableFuture[]::new));
69 }
70
71 private long nextConnectionId() {
72 return RandomUtils.nextLong();
73 }
74 }