blob: 390cde3bc3e5edc6cc55ee063853dc239672743a [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;
Madan Jampani3289fbf2016-01-13 14:14:27 -080040 private final Set<CopycatTransportConnection> connections = Sets.newConcurrentHashSet();
41
42 CopycatTransportClient(String clusterName, MessagingService messagingService, CopycatTransport.Mode mode) {
43 this.clusterName = checkNotNull(clusterName);
44 this.messagingService = checkNotNull(messagingService);
45 this.mode = checkNotNull(mode);
Madan Jampani3289fbf2016-01-13 14:14:27 -080046 }
47
48 @Override
49 public CompletableFuture<Connection> connect(Address remoteAddress) {
Madan Jampanib06ccef2016-01-25 10:51:16 -080050 ThreadContext context = ThreadContext.currentContextOrThrow();
Madan Jampani3289fbf2016-01-13 14:14:27 -080051 CopycatTransportConnection connection = new CopycatTransportConnection(
52 nextConnectionId(),
53 CopycatTransport.Mode.CLIENT,
54 clusterName,
55 remoteAddress,
56 messagingService,
57 context);
58 if (mode == CopycatTransport.Mode.CLIENT) {
59 connection.setBidirectional();
60 }
61 connections.add(connection);
62 return CompletableFuture.supplyAsync(() -> connection, context.executor());
63 }
64
65 @Override
66 public CompletableFuture<Void> close() {
67 return CompletableFuture.allOf(connections.stream().map(Connection::close).toArray(CompletableFuture[]::new));
68 }
69
70 private long nextConnectionId() {
71 return RandomUtils.nextLong();
72 }
73 }