blob: 36a19581cc443b9f01de5bf7173f0a04bc79301e [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;
Madan Jampani2f9cc712016-02-15 19:36:21 -080019import static org.slf4j.LoggerFactory.getLogger;
Madan Jampani3289fbf2016-01-13 14:14:27 -080020
21import java.io.ByteArrayInputStream;
22import java.io.DataInputStream;
23import java.io.IOException;
Madan Jampani3289fbf2016-01-13 14:14:27 -080024import java.util.Map;
25import java.util.concurrent.CompletableFuture;
Madan Jampani7efc8dd2016-02-16 13:11:53 -080026import java.util.concurrent.Executors;
27import java.util.concurrent.ScheduledExecutorService;
Madan Jampani3289fbf2016-01-13 14:14:27 -080028import java.util.concurrent.atomic.AtomicBoolean;
29import java.util.function.Consumer;
30
31import org.apache.commons.io.IOUtils;
32import org.onlab.util.Tools;
Madan Jampanif778c962016-01-31 22:56:38 -080033import org.onosproject.cluster.PartitionId;
Madan Jampani3289fbf2016-01-13 14:14:27 -080034import org.onosproject.store.cluster.messaging.MessagingService;
Madan Jampani2f9cc712016-02-15 19:36:21 -080035import org.slf4j.Logger;
Madan Jampani3289fbf2016-01-13 14:14:27 -080036
37import com.google.common.collect.Maps;
38
39import io.atomix.catalyst.transport.Address;
40import io.atomix.catalyst.transport.Connection;
41import io.atomix.catalyst.transport.Server;
Madan Jampani7efc8dd2016-02-16 13:11:53 -080042import io.atomix.catalyst.util.concurrent.CatalystThreadFactory;
Madan Jampani3289fbf2016-01-13 14:14:27 -080043import io.atomix.catalyst.util.concurrent.SingleThreadContext;
44import io.atomix.catalyst.util.concurrent.ThreadContext;
45
46/**
47 * {@link Server} implementation for {@link CopycatTransport}.
48 */
49public class CopycatTransportServer implements Server {
50
Madan Jampani2f9cc712016-02-15 19:36:21 -080051 private final Logger log = getLogger(getClass());
Madan Jampani3289fbf2016-01-13 14:14:27 -080052 private final AtomicBoolean listening = new AtomicBoolean(false);
Madan Jampani71d13e12016-01-13 17:14:35 -080053 private CompletableFuture<Void> listenFuture = new CompletableFuture<>();
Madan Jampani7efc8dd2016-02-16 13:11:53 -080054 private final ScheduledExecutorService executorService;
Madan Jampanif778c962016-01-31 22:56:38 -080055 private final PartitionId partitionId;
Madan Jampani3289fbf2016-01-13 14:14:27 -080056 private final MessagingService messagingService;
57 private final String messageSubject;
58 private final Map<Long, CopycatTransportConnection> connections = Maps.newConcurrentMap();
59
Madan Jampanif778c962016-01-31 22:56:38 -080060 CopycatTransportServer(PartitionId partitionId, MessagingService messagingService) {
61 this.partitionId = checkNotNull(partitionId);
Madan Jampani3289fbf2016-01-13 14:14:27 -080062 this.messagingService = checkNotNull(messagingService);
Madan Jampanif778c962016-01-31 22:56:38 -080063 this.messageSubject = String.format("onos-copycat-%s", partitionId);
Madan Jampani7efc8dd2016-02-16 13:11:53 -080064 this.executorService = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors(),
65 new CatalystThreadFactory("copycat-server-p" + partitionId + "-%d"));
Madan Jampani3289fbf2016-01-13 14:14:27 -080066 }
67
68 @Override
69 public CompletableFuture<Void> listen(Address address, Consumer<Connection> listener) {
Madan Jampani71d13e12016-01-13 17:14:35 -080070 if (listening.compareAndSet(false, true)) {
71 ThreadContext context = ThreadContext.currentContextOrThrow();
72 listen(address, listener, context);
Madan Jampani3289fbf2016-01-13 14:14:27 -080073 }
74 return listenFuture;
75 }
76
Madan Jampani71d13e12016-01-13 17:14:35 -080077 private void listen(Address address, Consumer<Connection> listener, ThreadContext context) {
Madan Jampani3289fbf2016-01-13 14:14:27 -080078 messagingService.registerHandler(messageSubject, (sender, payload) -> {
79 try (DataInputStream input = new DataInputStream(new ByteArrayInputStream(payload))) {
80 long connectionId = input.readLong();
Madan Jampani2f9cc712016-02-15 19:36:21 -080081 AtomicBoolean newConnectionCreated = new AtomicBoolean(false);
Madan Jampani3289fbf2016-01-13 14:14:27 -080082 CopycatTransportConnection connection = connections.computeIfAbsent(connectionId, k -> {
Madan Jampani2f9cc712016-02-15 19:36:21 -080083 newConnectionCreated.set(true);
84 CopycatTransportConnection newConnection = new CopycatTransportConnection(connectionId,
85 CopycatTransport.Mode.SERVER,
86 partitionId,
87 CopycatTransport.toAddress(sender),
88 messagingService,
89 getOrCreateContext(context));
90 log.debug("Created new incoming connection {}", connectionId);
91 newConnection.closeListener(c -> connections.remove(connectionId, c));
92 return newConnection;
Madan Jampani3289fbf2016-01-13 14:14:27 -080093 });
94 byte[] request = IOUtils.toByteArray(input);
95 return CompletableFuture.supplyAsync(
96 () -> {
Madan Jampani2f9cc712016-02-15 19:36:21 -080097 if (newConnectionCreated.get()) {
Madan Jampani3289fbf2016-01-13 14:14:27 -080098 listener.accept(connection);
99 }
100 return connection;
101 }, context.executor()).thenCompose(c -> c.handle(request));
102 } catch (IOException e) {
103 return Tools.exceptionalFuture(e);
104 }
105 });
Madan Jampani3289fbf2016-01-13 14:14:27 -0800106 context.execute(() -> {
107 listenFuture.complete(null);
108 });
109 }
110
111 @Override
112 public CompletableFuture<Void> close() {
113 messagingService.unregisterHandler(messageSubject);
Madan Jampani7efc8dd2016-02-16 13:11:53 -0800114 executorService.shutdown();
Madan Jampani3289fbf2016-01-13 14:14:27 -0800115 return CompletableFuture.completedFuture(null);
116 }
117
118 /**
119 * Returns the current execution context or creates one.
120 */
121 private ThreadContext getOrCreateContext(ThreadContext parentContext) {
122 ThreadContext context = ThreadContext.currentContext();
123 if (context != null) {
124 return context;
125 }
Madan Jampani7efc8dd2016-02-16 13:11:53 -0800126 return new SingleThreadContext(executorService, parentContext.serializer().clone());
Madan Jampani3289fbf2016-01-13 14:14:27 -0800127 }
128}