alien11689 commented on code in PR #93: URL: https://github.com/apache/aries-rsa/pull/93#discussion_r3143866418
########## discovery/tcp/src/main/java/org/apache/aries/rsa/discovery/tcp/Interest.java: ########## @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.aries.rsa.discovery.tcp; + +import org.apache.aries.rsa.util.StringPlus; +import org.osgi.framework.ServiceReference; +import org.osgi.service.remoteserviceadmin.EndpointDescription; +import org.osgi.service.remoteserviceadmin.EndpointEvent; +import org.osgi.service.remoteserviceadmin.EndpointEventListener; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; + +import static org.osgi.service.remoteserviceadmin.EndpointEventListener.ENDPOINT_LISTENER_SCOPE; + +/** + * An interest is a combination of an EndpointEventListener and its published scope Review Comment: nitpicking: we can make `EndpointEventListener` a link in the javadoc (also in other added) ########## discovery/tcp/src/main/java/org/apache/aries/rsa/discovery/tcp/Interest.java: ########## @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.aries.rsa.discovery.tcp; + +import org.apache.aries.rsa.util.StringPlus; +import org.osgi.framework.ServiceReference; +import org.osgi.service.remoteserviceadmin.EndpointDescription; +import org.osgi.service.remoteserviceadmin.EndpointEvent; +import org.osgi.service.remoteserviceadmin.EndpointEventListener; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; + +import static org.osgi.service.remoteserviceadmin.EndpointEventListener.ENDPOINT_LISTENER_SCOPE; + +/** + * An interest is a combination of an EndpointEventListener and its published scope + * (i.e. the filters defining what endpoints it is interested in). + * <p> + * The Interest class acts as a gatekeeper for an EndpointEventListener - + * it keeps track of its scopes, and when notified of endpoint events, + * it forwards to the listener only those that match what it is interested in. + */ +public class Interest { + private static final Logger LOG = LoggerFactory.getLogger(Interest.class); + + private final List<String> scopes; + private final EndpointEventListener listener; + + public Interest(ServiceReference<?> sref, EndpointEventListener listener) { + this.scopes = StringPlus.normalize(sref.getProperty(ENDPOINT_LISTENER_SCOPE)); + this.listener = listener; + } + + public void notifyListener(EndpointEvent event) { + EndpointDescription endpoint = event.getEndpoint(); + String scope = scopes.stream().filter(endpoint::matches).findFirst().orElse(null); Review Comment: in #92 I left a comment about this line ########## discovery/tcp/src/main/java/org/apache/aries/rsa/discovery/tcp/TcpConnectionManager.java: ########## @@ -0,0 +1,228 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.aries.rsa.discovery.tcp; + +import org.apache.aries.rsa.discovery.tcp.TcpMessage.*; +import org.osgi.service.remoteserviceadmin.EndpointDescription; +import org.osgi.service.remoteserviceadmin.EndpointEvent; +import org.osgi.service.remoteserviceadmin.EndpointEventListener; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.net.*; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import static org.apache.aries.rsa.discovery.tcp.TcpDiscovery.toURI; + +/** + * Manages all TCP connections for this provider, as well as + * the higher-level TCP discovery protocol logic. + * <p> + * This includes accepting incoming connections on a server socket, + * initiating outgoing connections to configured (or discovered) peers, + * connection retry logic after unexpected disconnection, handling + * incoming messages from connections and handling gossip-discovered peers. + * <p> + * In addition to the protocol-level functionality, it keeps track of + * all known local endpoints and notifies all remote peers about them. + */ +public class TcpConnectionManager implements EndpointEventListener { + private static final Logger LOG = LoggerFactory.getLogger(TcpConnectionManager.class); + + private final InterestManager interestManager; + private final String localAddress; + private final String localUuid; + private final long reconnectDelay; + private final boolean gossip; + + private final ExecutorService executor = Executors.newCachedThreadPool(); // for connect/accept threads + private final Set<TcpConnection> connections = ConcurrentHashMap.newKeySet(); // all connections, including before handshake + private final Map<String, TcpConnection> connectionsByUuid = new ConcurrentHashMap<>(); // connections after handshake (known uuid) + private final Map<String, EndpointDescription> localEndpoints = new ConcurrentHashMap<>(); + private final Set<String> peers = ConcurrentHashMap.newKeySet(); // all configured and discovered (gossip) peer addresses + + private ServerSocket serverSocket; + private volatile boolean closing; + + public TcpConnectionManager(InterestManager interestManager, String localAddress, + String localUuid, long reconnectDelay, boolean gossip) { + this.interestManager = interestManager; + this.localAddress = localAddress; + this.localUuid = localUuid; + this.reconnectDelay = reconnectDelay; + this.gossip = gossip; + } + + public void open(String bindAddress, int port, Collection<String> peers) throws IOException { + serverSocket = new ServerSocket(); + serverSocket.setReuseAddress(true); + serverSocket.bind(new InetSocketAddress(bindAddress, port)); + executor.submit(this::acceptLoop); + addPeers(peers); + } + + public void close() throws IOException { Review Comment: can we implement `Closable`? ########## discovery/tcp/src/main/java/org/apache/aries/rsa/discovery/tcp/TcpDiscovery.java: ########## @@ -0,0 +1,204 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.aries.rsa.discovery.tcp; + +import org.apache.aries.rsa.annotations.RSADiscoveryProvider; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceReference; +import org.osgi.framework.ServiceRegistration; +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Deactivate; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.remoteserviceadmin.EndpointEventListener; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Arrays; +import java.util.Dictionary; +import java.util.Hashtable; +import java.util.Objects; +import java.util.stream.Collectors; + +import static org.osgi.framework.Constants.FRAMEWORK_UUID; +import static org.osgi.service.component.annotations.ReferenceCardinality.MULTIPLE; +import static org.osgi.service.component.annotations.ReferencePolicy.DYNAMIC; +import static org.osgi.service.remoteserviceadmin.EndpointEventListener.ENDPOINT_LISTENER_SCOPE; +import static org.osgi.service.remoteserviceadmin.RemoteConstants.ENDPOINT_FRAMEWORK_UUID; + +/** + * The main TCP Discovery provider component. + * <p> + * It initializes the provider using config admin configuration, + * initializes the interest manager and connection manager, + * registers an EndpointEventListener to track locally exported + * endpoints, and listens for registrations of other + * EndpointEventListeners which are managed by the InterestManager. + */ +@RSADiscoveryProvider(protocols = "aries.tcp") +@Component(immediate = true, configurationPid = "org.apache.aries.rsa.discovery.tcp") Review Comment: do we have constant for configuration pid? ########## discovery/tcp/src/main/java/org/apache/aries/rsa/discovery/tcp/TcpConnection.java: ########## @@ -0,0 +1,121 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.aries.rsa.discovery.tcp; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.net.Socket; +import java.util.function.BiConsumer; +import java.util.function.Consumer; + +/** + * A TCP connection between two TCP discovery peers. + * <p> + * This class handles the low-level network reading/writing/serialization, + * while leaving the higher-level logic (including received message handling + * and connection close handling) to the TcpManager. + */ +public class TcpConnection { + private static final Logger LOG = LoggerFactory.getLogger(TcpConnection.class); + + private final Socket socket; + private final ObjectInputStream in; + private final ObjectOutputStream out; + private final Thread readThread; + private final boolean isOutbound; + + private final BiConsumer<TcpConnection, TcpMessage> onMessage; // message handler + private final Consumer<TcpConnection> onClose; // close handler + + private volatile String peerAddress; // the peer host:port, for incoming connections it is set only after handshake + private volatile String peerUuid; // set after handshake + + public TcpConnection(Socket socket, String peerAddress, + BiConsumer<TcpConnection, TcpMessage> onMessage, Consumer<TcpConnection> onClose) throws IOException { + this.socket = socket; + this.isOutbound = peerAddress != null; // inbound only gets peerAddress after handshake + this.peerAddress = peerAddress; + this.onMessage = onMessage; + this.onClose = onClose; + this.out = new ObjectOutputStream(socket.getOutputStream()); // output must be initialized before input + this.out.flush(); // so we don't deadlock on reading object stream header + this.in = new ObjectInputStream(socket.getInputStream()); + readThread = new Thread(null, this::readLoop, getClass().getSimpleName() + "-Reader-" + this); + readThread.start(); + } + + public boolean isOutbound() { + return isOutbound; + } + + public String getPeerAddress() { + return peerAddress; + } + + public void setPeerAddress(String address) { + this.peerAddress = address; + } + + public String getPeerUuid() { + return peerUuid; + } + + public void setPeerUuid(String peerUuid) { + this.peerUuid = peerUuid; + } + + public void send(TcpMessage message) { + try { + synchronized (out) { + out.writeObject(message); + out.flush(); + } + } catch (IOException ioe) { + LOG.error("Error sending TCP message", ioe); + close(); + } + } + + public void close() { + try { + socket.close(); // read thread will get SocketException, fire onClose and die Review Comment: is it ok to stop via the exception? maybe some flag could gently stop the thread? ########## discovery/tcp/src/main/java/org/apache/aries/rsa/discovery/tcp/Interest.java: ########## @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.aries.rsa.discovery.tcp; + +import org.apache.aries.rsa.util.StringPlus; +import org.osgi.framework.ServiceReference; +import org.osgi.service.remoteserviceadmin.EndpointDescription; +import org.osgi.service.remoteserviceadmin.EndpointEvent; +import org.osgi.service.remoteserviceadmin.EndpointEventListener; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; + +import static org.osgi.service.remoteserviceadmin.EndpointEventListener.ENDPOINT_LISTENER_SCOPE; + +/** + * An interest is a combination of an EndpointEventListener and its published scope + * (i.e. the filters defining what endpoints it is interested in). + * <p> + * The Interest class acts as a gatekeeper for an EndpointEventListener - + * it keeps track of its scopes, and when notified of endpoint events, + * it forwards to the listener only those that match what it is interested in. + */ +public class Interest { + private static final Logger LOG = LoggerFactory.getLogger(Interest.class); + + private final List<String> scopes; + private final EndpointEventListener listener; + + public Interest(ServiceReference<?> sref, EndpointEventListener listener) { + this.scopes = StringPlus.normalize(sref.getProperty(ENDPOINT_LISTENER_SCOPE)); + this.listener = listener; + } + + public void notifyListener(EndpointEvent event) { + EndpointDescription endpoint = event.getEndpoint(); + String scope = scopes.stream().filter(endpoint::matches).findFirst().orElse(null); + if (scope != null) { + LOG.info("Calling endpointChanged on {} for filter {}, type {}, endpoint {}", + listener, scope, event.getType(), endpoint); + listener.endpointChanged(event, scope); + } + } + + @Override + public String toString() { + return "Interest [scopes=" + scopes + ", epListener=" + listener.getClass() + "]"; Review Comment: can we rename epListener? ########## discovery/tcp/src/main/java/org/apache/aries/rsa/discovery/tcp/InterestManager.java: ########## @@ -0,0 +1,87 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.aries.rsa.discovery.tcp; + +import org.osgi.framework.ServiceReference; +import org.osgi.service.remoteserviceadmin.EndpointDescription; +import org.osgi.service.remoteserviceadmin.EndpointEvent; +import org.osgi.service.remoteserviceadmin.EndpointEventListener; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import static org.osgi.service.remoteserviceadmin.EndpointEvent.*; + +/** + * Manages all known local EndpointEventListeners along with their interests (scopes), + * as well as all known remote endpoints, and notifies the former about the latter. + */ +public class InterestManager { + // listener to its interest Review Comment: if the comment is necessary then let's make it a javadoc - also for the other fields ########## discovery/tcp/src/main/java/org/apache/aries/rsa/discovery/tcp/TcpConnection.java: ########## @@ -0,0 +1,121 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.aries.rsa.discovery.tcp; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.net.Socket; +import java.util.function.BiConsumer; +import java.util.function.Consumer; + +/** + * A TCP connection between two TCP discovery peers. + * <p> + * This class handles the low-level network reading/writing/serialization, + * while leaving the higher-level logic (including received message handling + * and connection close handling) to the TcpManager. + */ +public class TcpConnection { + private static final Logger LOG = LoggerFactory.getLogger(TcpConnection.class); + + private final Socket socket; + private final ObjectInputStream in; + private final ObjectOutputStream out; + private final Thread readThread; + private final boolean isOutbound; + + private final BiConsumer<TcpConnection, TcpMessage> onMessage; // message handler Review Comment: comments to javadoc? ########## discovery/tcp/pom.xml: ########## @@ -0,0 +1,62 @@ +<?xml version='1.0' encoding='UTF-8' ?> +<!-- + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +--> +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.apache.aries.rsa</groupId> + <artifactId>org.apache.aries.rsa.parent</artifactId> + <version>2.0.0-SNAPSHOT</version> + <relativePath>../../parent/pom.xml</relativePath> + </parent> + + <groupId>org.apache.aries.rsa.discovery</groupId> + <artifactId>org.apache.aries.rsa.discovery.tcp</artifactId> + <packaging>jar</packaging> + <name>Aries Remote Service Admin Discovery TCP</name> + + <properties> + <topDirectoryLocation>../..</topDirectoryLocation> + </properties> + + <dependencies> + <dependency> + <groupId>org.apache.aries.rsa</groupId> + <artifactId>org.apache.aries.rsa.spi</artifactId> + <scope>provided</scope> + </dependency> + + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-core</artifactId> + <version>5.18.0</version> Review Comment: let's make the properties and/or reuse them in the other modules ########## discovery/tcp/src/main/java/org/apache/aries/rsa/discovery/tcp/TcpConnectionManager.java: ########## @@ -0,0 +1,228 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.aries.rsa.discovery.tcp; + +import org.apache.aries.rsa.discovery.tcp.TcpMessage.*; +import org.osgi.service.remoteserviceadmin.EndpointDescription; +import org.osgi.service.remoteserviceadmin.EndpointEvent; +import org.osgi.service.remoteserviceadmin.EndpointEventListener; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.net.*; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import static org.apache.aries.rsa.discovery.tcp.TcpDiscovery.toURI; + +/** + * Manages all TCP connections for this provider, as well as + * the higher-level TCP discovery protocol logic. + * <p> + * This includes accepting incoming connections on a server socket, + * initiating outgoing connections to configured (or discovered) peers, + * connection retry logic after unexpected disconnection, handling + * incoming messages from connections and handling gossip-discovered peers. + * <p> + * In addition to the protocol-level functionality, it keeps track of + * all known local endpoints and notifies all remote peers about them. + */ +public class TcpConnectionManager implements EndpointEventListener { + private static final Logger LOG = LoggerFactory.getLogger(TcpConnectionManager.class); + + private final InterestManager interestManager; + private final String localAddress; + private final String localUuid; + private final long reconnectDelay; + private final boolean gossip; + + private final ExecutorService executor = Executors.newCachedThreadPool(); // for connect/accept threads + private final Set<TcpConnection> connections = ConcurrentHashMap.newKeySet(); // all connections, including before handshake + private final Map<String, TcpConnection> connectionsByUuid = new ConcurrentHashMap<>(); // connections after handshake (known uuid) + private final Map<String, EndpointDescription> localEndpoints = new ConcurrentHashMap<>(); + private final Set<String> peers = ConcurrentHashMap.newKeySet(); // all configured and discovered (gossip) peer addresses + + private ServerSocket serverSocket; + private volatile boolean closing; + + public TcpConnectionManager(InterestManager interestManager, String localAddress, + String localUuid, long reconnectDelay, boolean gossip) { + this.interestManager = interestManager; + this.localAddress = localAddress; + this.localUuid = localUuid; + this.reconnectDelay = reconnectDelay; + this.gossip = gossip; + } + + public void open(String bindAddress, int port, Collection<String> peers) throws IOException { + serverSocket = new ServerSocket(); + serverSocket.setReuseAddress(true); + serverSocket.bind(new InetSocketAddress(bindAddress, port)); + executor.submit(this::acceptLoop); + addPeers(peers); + } + + public void close() throws IOException { + closing = true; + serverSocket.close(); // acceptLoop will get SocketException + connections.forEach(TcpConnection::close); + executor.shutdownNow(); + } + + private void addPeers(Collection<String> peers) { + peers.stream() + .filter(peer -> !this.peers.contains(peer)) // only new ones + .filter(peer -> !localAddress.equals(peer)) // exclude ourself + .forEach(peer -> { + LOG.info("Adding peer {}", peer); + this.peers.add(peer); + executor.submit(() -> connectLoop(peer)); + }); + } + + private void acceptLoop() { + while (true) { + try { + Socket socket = serverSocket.accept(); + executor.submit(() -> onConnected(socket, null)); + } catch (IOException ioe) { + return; // socket closed + } catch (Throwable t) { + LOG.error("Unexpected error in accept loop - shutting down", t); + return; + } + } + } + + private void connectLoop(String address) { + URI uri = toURI(address); + while (!closing) { + try { + Socket socket = new Socket(uri.getHost(), uri.getPort()); + onConnected(socket, address); + return; // connection established; onConnectionClosed will restart this loop if needed + } catch (IOException ioe) { + try { + Thread.sleep(reconnectDelay); + } catch (InterruptedException ie) { + // end loop (shutting down) + return; + } + } catch (Throwable t) { + LOG.error("Unexpected error in connect loop - shutting down", t); + return; + } + } + } + + private void onConnected(Socket socket, String address) { + try { + TcpConnection conn = new TcpConnection(socket, address, this::onMessage, this::onClosed); + connections.add(conn); + conn.send(new HandshakeMessage(localUuid, localAddress, new ArrayList<>(peers))); + // don't send known endpoints yet, only after receiving handshake + } catch (IOException ioe) { + LOG.error("error initializing accepted connection", ioe); Review Comment: it's ok to have only log? ########## discovery/tcp/src/main/java/org/apache/aries/rsa/discovery/tcp/TcpDiscovery.java: ########## @@ -0,0 +1,204 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.aries.rsa.discovery.tcp; + +import org.apache.aries.rsa.annotations.RSADiscoveryProvider; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceReference; +import org.osgi.framework.ServiceRegistration; +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Deactivate; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.remoteserviceadmin.EndpointEventListener; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Arrays; +import java.util.Dictionary; +import java.util.Hashtable; +import java.util.Objects; +import java.util.stream.Collectors; + +import static org.osgi.framework.Constants.FRAMEWORK_UUID; +import static org.osgi.service.component.annotations.ReferenceCardinality.MULTIPLE; +import static org.osgi.service.component.annotations.ReferencePolicy.DYNAMIC; +import static org.osgi.service.remoteserviceadmin.EndpointEventListener.ENDPOINT_LISTENER_SCOPE; +import static org.osgi.service.remoteserviceadmin.RemoteConstants.ENDPOINT_FRAMEWORK_UUID; + +/** + * The main TCP Discovery provider component. + * <p> + * It initializes the provider using config admin configuration, + * initializes the interest manager and connection manager, + * registers an EndpointEventListener to track locally exported + * endpoints, and listens for registrations of other + * EndpointEventListeners which are managed by the InterestManager. + */ +@RSADiscoveryProvider(protocols = "aries.tcp") +@Component(immediate = true, configurationPid = "org.apache.aries.rsa.discovery.tcp") +public class TcpDiscovery { + private static final Logger LOG = LoggerFactory.getLogger(TcpDiscovery.class); + private static final String OWN_LISTENER_PROP = "aries.discovery.tcp"; + public static final int DEFAULT_PORT = 7667; + + @interface Config { + String address() default "localhost:" + DEFAULT_PORT; + String bindAddress() default "0.0.0.0"; + String[] peers() default {}; + long reconnectDelay() default 5000; + boolean gossip() default true; + } + + private InterestManager interestManager; + private TcpConnectionManager connectionManager; + private ServiceRegistration<?> listenerRegistration; + + public TcpDiscovery() { + // initialize in constructor before we start getting reference bind events + interestManager = new InterestManager(); + } + + public static URI toURI(String address) { + try { + URI uri = new URI("tcp://" + address); + if (uri.getPort() == -1) { + uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), + DEFAULT_PORT, uri.getPath(), uri.getQuery(), uri.getFragment()); + } + return uri; + } catch (URISyntaxException urise) { + LOG.error("failed to parse address " + address, urise); + throw new RuntimeException(urise); + } + } + + // merge config from ConfigAdmin, framework properties and system properties + @SuppressWarnings("unchecked") + private <T extends Annotation> T mergeConfig(BundleContext context, String prefix, T config) { + Class<T> cls = (Class<T>)config.annotationType(); + return (T)Proxy.newProxyInstance(cls.getClassLoader(), new Class[] { cls }, + (proxy, method, args) -> { + Object value = method.invoke(config, args); + Object defaultValue = method.getDefaultValue(); + if (method.getDeclaringClass() != Object.class && Objects.deepEquals(value, defaultValue)) { + String prop = prefix + method.getName(); + value = context.getProperty(prop); + if (value == null) { + value = System.getProperty(prop); + } + if (value == null) { + value = defaultValue; + } else if (method.getReturnType() == Boolean.TYPE) { + value = Boolean.valueOf(value.toString()); + } else if (method.getReturnType() == Integer.TYPE) { + value = Integer.valueOf(value.toString()); + } else if (method.getReturnType() == Long.TYPE) { + value = Long.valueOf(value.toString()); + } else if (method.getReturnType() == String[].class) { + value = ((String)value).split("\\s*,\\s*"); + } + } else if (method.getDeclaringClass() == Object.class && method.getName().equals("toString")) { + // add a nice toString that shows all merged config names and values (including arrays) + value = Arrays.stream(cls.getMethods()) + .filter(m -> !m.getDeclaringClass().equals(Annotation.class)) // not Object.class! + .collect(Collectors.<Method, String, Object>toMap(Method::getName, m -> { + try { + Object v = m.invoke(proxy); + return (v == null || v instanceof Object[]) ? Arrays.toString((Object[])v) : v.toString(); + } catch (Exception ignore) { + return "<ERROR>"; + } + })).toString(); + } + return value; + }); + } + + private void initConnectionManager(Config config, String uuid) throws IOException { + String address = config.address(); + String bindAddress = config.bindAddress(); + String[] peers = config.peers(); + if (address == null || address.isEmpty() || address.equals("0.0.0.0")) { Review Comment: can we have constant for `0.0.0.0`? ########## discovery/tcp/src/main/java/org/apache/aries/rsa/discovery/tcp/TcpConnectionManager.java: ########## @@ -0,0 +1,228 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.aries.rsa.discovery.tcp; + +import org.apache.aries.rsa.discovery.tcp.TcpMessage.*; +import org.osgi.service.remoteserviceadmin.EndpointDescription; +import org.osgi.service.remoteserviceadmin.EndpointEvent; +import org.osgi.service.remoteserviceadmin.EndpointEventListener; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.net.*; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import static org.apache.aries.rsa.discovery.tcp.TcpDiscovery.toURI; + +/** + * Manages all TCP connections for this provider, as well as + * the higher-level TCP discovery protocol logic. + * <p> + * This includes accepting incoming connections on a server socket, + * initiating outgoing connections to configured (or discovered) peers, + * connection retry logic after unexpected disconnection, handling + * incoming messages from connections and handling gossip-discovered peers. + * <p> + * In addition to the protocol-level functionality, it keeps track of + * all known local endpoints and notifies all remote peers about them. + */ +public class TcpConnectionManager implements EndpointEventListener { + private static final Logger LOG = LoggerFactory.getLogger(TcpConnectionManager.class); + + private final InterestManager interestManager; + private final String localAddress; + private final String localUuid; + private final long reconnectDelay; + private final boolean gossip; + + private final ExecutorService executor = Executors.newCachedThreadPool(); // for connect/accept threads + private final Set<TcpConnection> connections = ConcurrentHashMap.newKeySet(); // all connections, including before handshake + private final Map<String, TcpConnection> connectionsByUuid = new ConcurrentHashMap<>(); // connections after handshake (known uuid) + private final Map<String, EndpointDescription> localEndpoints = new ConcurrentHashMap<>(); + private final Set<String> peers = ConcurrentHashMap.newKeySet(); // all configured and discovered (gossip) peer addresses + + private ServerSocket serverSocket; + private volatile boolean closing; + + public TcpConnectionManager(InterestManager interestManager, String localAddress, + String localUuid, long reconnectDelay, boolean gossip) { + this.interestManager = interestManager; + this.localAddress = localAddress; + this.localUuid = localUuid; + this.reconnectDelay = reconnectDelay; + this.gossip = gossip; + } + + public void open(String bindAddress, int port, Collection<String> peers) throws IOException { + serverSocket = new ServerSocket(); + serverSocket.setReuseAddress(true); + serverSocket.bind(new InetSocketAddress(bindAddress, port)); + executor.submit(this::acceptLoop); + addPeers(peers); + } + + public void close() throws IOException { + closing = true; + serverSocket.close(); // acceptLoop will get SocketException + connections.forEach(TcpConnection::close); + executor.shutdownNow(); Review Comment: should we shutdown now or add await termination + shutdown? ########## discovery/tcp/src/main/java/org/apache/aries/rsa/discovery/tcp/TcpConnectionManager.java: ########## @@ -0,0 +1,228 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.aries.rsa.discovery.tcp; + +import org.apache.aries.rsa.discovery.tcp.TcpMessage.*; +import org.osgi.service.remoteserviceadmin.EndpointDescription; +import org.osgi.service.remoteserviceadmin.EndpointEvent; +import org.osgi.service.remoteserviceadmin.EndpointEventListener; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.net.*; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import static org.apache.aries.rsa.discovery.tcp.TcpDiscovery.toURI; + +/** + * Manages all TCP connections for this provider, as well as + * the higher-level TCP discovery protocol logic. + * <p> + * This includes accepting incoming connections on a server socket, + * initiating outgoing connections to configured (or discovered) peers, + * connection retry logic after unexpected disconnection, handling + * incoming messages from connections and handling gossip-discovered peers. + * <p> + * In addition to the protocol-level functionality, it keeps track of + * all known local endpoints and notifies all remote peers about them. + */ +public class TcpConnectionManager implements EndpointEventListener { + private static final Logger LOG = LoggerFactory.getLogger(TcpConnectionManager.class); + + private final InterestManager interestManager; + private final String localAddress; + private final String localUuid; + private final long reconnectDelay; + private final boolean gossip; + + private final ExecutorService executor = Executors.newCachedThreadPool(); // for connect/accept threads + private final Set<TcpConnection> connections = ConcurrentHashMap.newKeySet(); // all connections, including before handshake + private final Map<String, TcpConnection> connectionsByUuid = new ConcurrentHashMap<>(); // connections after handshake (known uuid) + private final Map<String, EndpointDescription> localEndpoints = new ConcurrentHashMap<>(); + private final Set<String> peers = ConcurrentHashMap.newKeySet(); // all configured and discovered (gossip) peer addresses + + private ServerSocket serverSocket; + private volatile boolean closing; + + public TcpConnectionManager(InterestManager interestManager, String localAddress, + String localUuid, long reconnectDelay, boolean gossip) { + this.interestManager = interestManager; + this.localAddress = localAddress; + this.localUuid = localUuid; + this.reconnectDelay = reconnectDelay; + this.gossip = gossip; + } + + public void open(String bindAddress, int port, Collection<String> peers) throws IOException { + serverSocket = new ServerSocket(); + serverSocket.setReuseAddress(true); + serverSocket.bind(new InetSocketAddress(bindAddress, port)); + executor.submit(this::acceptLoop); + addPeers(peers); + } + + public void close() throws IOException { + closing = true; + serverSocket.close(); // acceptLoop will get SocketException + connections.forEach(TcpConnection::close); + executor.shutdownNow(); + } + + private void addPeers(Collection<String> peers) { + peers.stream() + .filter(peer -> !this.peers.contains(peer)) // only new ones + .filter(peer -> !localAddress.equals(peer)) // exclude ourself + .forEach(peer -> { + LOG.info("Adding peer {}", peer); + this.peers.add(peer); + executor.submit(() -> connectLoop(peer)); + }); + } + + private void acceptLoop() { + while (true) { + try { + Socket socket = serverSocket.accept(); + executor.submit(() -> onConnected(socket, null)); + } catch (IOException ioe) { + return; // socket closed + } catch (Throwable t) { + LOG.error("Unexpected error in accept loop - shutting down", t); + return; + } + } + } + + private void connectLoop(String address) { + URI uri = toURI(address); + while (!closing) { + try { + Socket socket = new Socket(uri.getHost(), uri.getPort()); + onConnected(socket, address); + return; // connection established; onConnectionClosed will restart this loop if needed + } catch (IOException ioe) { + try { + Thread.sleep(reconnectDelay); + } catch (InterruptedException ie) { + // end loop (shutting down) + return; + } + } catch (Throwable t) { + LOG.error("Unexpected error in connect loop - shutting down", t); + return; + } + } + } + + private void onConnected(Socket socket, String address) { + try { + TcpConnection conn = new TcpConnection(socket, address, this::onMessage, this::onClosed); + connections.add(conn); + conn.send(new HandshakeMessage(localUuid, localAddress, new ArrayList<>(peers))); + // don't send known endpoints yet, only after receiving handshake + } catch (IOException ioe) { + LOG.error("error initializing accepted connection", ioe); + } + } + + public void onClosed(TcpConnection conn) { + connections.remove(conn); + String peerUuid = conn.getPeerUuid(); + if (peerUuid != null) { // passed the handshake + boolean removed = connectionsByUuid.remove(peerUuid, conn); // remove if this is the active connection + if (removed && !closing) { + interestManager.removePeer(peerUuid); // no active connections with peer + } + } + // re-start the connect retry thread if necessary: + // only if we're the outbound peer, and not in the process of shutting down, + // and there isn't already an active (reverse?) connection with the same peer, + // or we don't know who the peer is yet (before handshake) + if (conn.isOutbound() && !closing && (peerUuid == null || !connectionsByUuid.containsKey(peerUuid))) { + executor.submit(() -> connectLoop(conn.getPeerAddress())); + } + } + + private void onMessage(TcpConnection conn, TcpMessage message) { + if (message instanceof HandshakeMessage) { + HandshakeMessage h = (HandshakeMessage) message; + // update the peer data + conn.setPeerAddress(h.getAddress()); + conn.setPeerUuid(h.getUuid()); + // if gossip is enabled, try adding all of this peer's peers, + // as well as the peer itself (in case it found us via its + // own gossip, and we haven't met before) + if (gossip) { + addPeers(h.getPeers()); + addPeers(Collections.singleton(h.getAddress())); + } + // if we already have another connection with this peer (e.g. reverse direction) + // then we keep the old one (which is already in use) and close the new one + boolean existing = connectionsByUuid.putIfAbsent(h.getUuid(), conn) != null; + if (existing) { + // both sides can check if a connection between them already exists, but + // there is a possible race condition where one peer receives the handshake + // and closes the connection before it even had a chance to send its handshake - + // so the other peer will never know the connection is intentionally closed + // and not experiencing connection errors. If it is the outbound side, it will + // keep retrying to connect. to solve this, only the outbound peer is the one + // that closes the connection. The inbound side just doesn't use it until then. + if (conn.isOutbound()) { + conn.close(); + } + return; + } + // send all of our known local endpoints to the new peer + localEndpoints.values().forEach(endpoint -> conn.send(new UpdateMessage(endpoint.getProperties()))); + } else if (message instanceof UpdateMessage) { + UpdateMessage u = (UpdateMessage) message; + EndpointDescription endpoint = new EndpointDescription(u.getProperties()); + interestManager.addEndpoint(endpoint); + } else if (message instanceof RemoveMessage) { Review Comment: maybe we can have final `else` to catch unknown messages? ########## discovery/tcp/src/main/java/org/apache/aries/rsa/discovery/tcp/Interest.java: ########## @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.aries.rsa.discovery.tcp; Review Comment: we are adding many classes - should we put some of them in the internal/impl packages? ########## discovery/tcp/src/main/java/org/apache/aries/rsa/discovery/tcp/TcpConnectionManager.java: ########## @@ -0,0 +1,228 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.aries.rsa.discovery.tcp; + +import org.apache.aries.rsa.discovery.tcp.TcpMessage.*; +import org.osgi.service.remoteserviceadmin.EndpointDescription; +import org.osgi.service.remoteserviceadmin.EndpointEvent; +import org.osgi.service.remoteserviceadmin.EndpointEventListener; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.net.*; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import static org.apache.aries.rsa.discovery.tcp.TcpDiscovery.toURI; + +/** + * Manages all TCP connections for this provider, as well as + * the higher-level TCP discovery protocol logic. + * <p> + * This includes accepting incoming connections on a server socket, + * initiating outgoing connections to configured (or discovered) peers, + * connection retry logic after unexpected disconnection, handling + * incoming messages from connections and handling gossip-discovered peers. + * <p> + * In addition to the protocol-level functionality, it keeps track of + * all known local endpoints and notifies all remote peers about them. + */ +public class TcpConnectionManager implements EndpointEventListener { + private static final Logger LOG = LoggerFactory.getLogger(TcpConnectionManager.class); + + private final InterestManager interestManager; + private final String localAddress; + private final String localUuid; + private final long reconnectDelay; + private final boolean gossip; + + private final ExecutorService executor = Executors.newCachedThreadPool(); // for connect/accept threads + private final Set<TcpConnection> connections = ConcurrentHashMap.newKeySet(); // all connections, including before handshake + private final Map<String, TcpConnection> connectionsByUuid = new ConcurrentHashMap<>(); // connections after handshake (known uuid) + private final Map<String, EndpointDescription> localEndpoints = new ConcurrentHashMap<>(); + private final Set<String> peers = ConcurrentHashMap.newKeySet(); // all configured and discovered (gossip) peer addresses + + private ServerSocket serverSocket; + private volatile boolean closing; + + public TcpConnectionManager(InterestManager interestManager, String localAddress, + String localUuid, long reconnectDelay, boolean gossip) { + this.interestManager = interestManager; + this.localAddress = localAddress; + this.localUuid = localUuid; + this.reconnectDelay = reconnectDelay; + this.gossip = gossip; + } + + public void open(String bindAddress, int port, Collection<String> peers) throws IOException { + serverSocket = new ServerSocket(); + serverSocket.setReuseAddress(true); + serverSocket.bind(new InetSocketAddress(bindAddress, port)); + executor.submit(this::acceptLoop); + addPeers(peers); + } + + public void close() throws IOException { + closing = true; + serverSocket.close(); // acceptLoop will get SocketException + connections.forEach(TcpConnection::close); + executor.shutdownNow(); + } + + private void addPeers(Collection<String> peers) { + peers.stream() + .filter(peer -> !this.peers.contains(peer)) // only new ones + .filter(peer -> !localAddress.equals(peer)) // exclude ourself + .forEach(peer -> { + LOG.info("Adding peer {}", peer); + this.peers.add(peer); + executor.submit(() -> connectLoop(peer)); + }); + } + + private void acceptLoop() { + while (true) { + try { + Socket socket = serverSocket.accept(); + executor.submit(() -> onConnected(socket, null)); + } catch (IOException ioe) { + return; // socket closed + } catch (Throwable t) { + LOG.error("Unexpected error in accept loop - shutting down", t); + return; + } + } + } + + private void connectLoop(String address) { + URI uri = toURI(address); + while (!closing) { + try { + Socket socket = new Socket(uri.getHost(), uri.getPort()); + onConnected(socket, address); + return; // connection established; onConnectionClosed will restart this loop if needed + } catch (IOException ioe) { + try { + Thread.sleep(reconnectDelay); + } catch (InterruptedException ie) { + // end loop (shutting down) + return; + } + } catch (Throwable t) { + LOG.error("Unexpected error in connect loop - shutting down", t); + return; Review Comment: we don;t need to propagate the exceptions or react somewhere higher on the problems? ########## discovery/tcp/src/main/java/org/apache/aries/rsa/discovery/tcp/TcpConnection.java: ########## @@ -0,0 +1,121 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.aries.rsa.discovery.tcp; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.net.Socket; +import java.util.function.BiConsumer; +import java.util.function.Consumer; + +/** + * A TCP connection between two TCP discovery peers. + * <p> + * This class handles the low-level network reading/writing/serialization, + * while leaving the higher-level logic (including received message handling + * and connection close handling) to the TcpManager. + */ +public class TcpConnection { + private static final Logger LOG = LoggerFactory.getLogger(TcpConnection.class); + + private final Socket socket; + private final ObjectInputStream in; + private final ObjectOutputStream out; + private final Thread readThread; + private final boolean isOutbound; + + private final BiConsumer<TcpConnection, TcpMessage> onMessage; // message handler Review Comment: or maybe the field can be renamed so the comment is not necessary? also in the fields below? -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
