X-Git-Url: https://git.pterodactylus.net/?a=blobdiff_plain;f=src%2Fnet%2Fpterodactylus%2Fjsite%2Fcore%2FNodeManager.java;h=3a1f68bac7e733f73de8ccda100f7ff5dd0fc4c1;hb=708d0d9f54df2f6c02f31c75555a029ec8702614;hp=fe52fd772b980d49c2b71a4025a98538b935608f;hpb=f7bfc2672693384db5c7a9ee252f6a548e513489;p=jSite2.git diff --git a/src/net/pterodactylus/jsite/core/NodeManager.java b/src/net/pterodactylus/jsite/core/NodeManager.java index fe52fd7..3a1f68b 100644 --- a/src/net/pterodactylus/jsite/core/NodeManager.java +++ b/src/net/pterodactylus/jsite/core/NodeManager.java @@ -19,16 +19,20 @@ package net.pterodactylus.jsite.core; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; +import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; @@ -36,18 +40,19 @@ import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; -import net.pterodactylus.fcp.highlevel.HighLevelClient; -import net.pterodactylus.fcp.highlevel.HighLevelClientListener; +import net.pterodactylus.fcp.highlevel.FcpClient; +import net.pterodactylus.fcp.highlevel.FcpException; +import net.pterodactylus.jsite.util.IdGenerator; import net.pterodactylus.util.io.Closer; import net.pterodactylus.util.logging.Logging; +import net.pterodactylus.util.number.Hex; /** * TODO - * + * * @author David ‘Bombe’ Roden <bombe@freenetproject.org> - * @version $Id$ */ -public class NodeManager implements HighLevelClientListener { +public class NodeManager implements Iterable, PropertyChangeListener { /** Logger. */ private static final Logger logger = Logging.getLogger(NodeManager.class.getName()); @@ -61,24 +66,24 @@ public class NodeManager implements HighLevelClientListener { /** Object used for synchronization. */ private final Object syncObject = new Object(); - /** Node listeners. */ - private List nodeListeners = Collections.synchronizedList(new ArrayList()); + /** Node listener support. */ + private final NodeListenerSupport nodeListenerSupport = new NodeListenerSupport(); /** All nodes. */ - private List nodes = Collections.synchronizedList(new ArrayList()); + private final List nodes = Collections.synchronizedList(new ArrayList()); - /** All FCP connections. */ - private Map nodeClients = Collections.synchronizedMap(new HashMap()); + /** Map from node ID to node. */ + private final Map idNodes = Collections.synchronizedMap(new HashMap()); - /** Keeps track of which connection is in use right now. */ - private Set usedConnections = Collections.synchronizedSet(new HashSet()); + /** Map from node to client. */ + private final Map nodeClients = Collections.synchronizedMap(new HashMap()); - /** Maps nodes to high-level clients. */ - private Map clientNodes = Collections.synchronizedMap(new HashMap()); + /** Collection of currently connected nodes. */ + private final Set connectedNodes = Collections.synchronizedSet(new HashSet()); /** * Creates a new FCP collector. - * + * * @param clientName * The name of the FCP client * @param directory @@ -95,49 +100,22 @@ public class NodeManager implements HighLevelClientListener { /** * Adds the given listener to the list of listeners. - * + * * @param nodeListener * The listener to add */ public void addNodeListener(NodeListener nodeListener) { - nodeListeners.add(nodeListener); + nodeListenerSupport.addListener(nodeListener); } /** * Removes the given listener from the list of listeners. - * + * * @param nodeListener * The listener to remove */ public void removeNodeListener(NodeListener nodeListener) { - nodeListeners.remove(nodeListener); - } - - /** - * Notifies all listeners that the given node was connected. - * - * @param node - * The node that is now connected - */ - private void fireNodeConnected(Node node) { - for (NodeListener nodeListener: nodeListeners) { - nodeListener.nodeConnected(node); - } - } - - /** - * Notifies all listeners that the given node was disconnected. - * - * @param node - * The node that is now disconnected - * @param throwable - * The exception that caused the disconnect, or null - * if there was no exception - */ - private void fireNodeDisconnected(Node node, Throwable throwable) { - for (NodeListener nodeListener: nodeListeners) { - nodeListener.nodeDisconnected(node, throwable); - } + nodeListenerSupport.removeListener(nodeListener); } // @@ -146,7 +124,7 @@ public class NodeManager implements HighLevelClientListener { /** * Returns the directory in which the nodes are stored. - * + * * @return The directory the nodes are stored in */ public String getDirectory() { @@ -155,7 +133,7 @@ public class NodeManager implements HighLevelClientListener { /** * Checks whether the given node is already connected. - * + * * @param node * The node to check * @return true if the node is already connected, @@ -165,17 +143,37 @@ public class NodeManager implements HighLevelClientListener { return nodes.contains(node); } + /** + * Returns whether the given node is currently connected. + * + * @param node + * The node to check + * @return true if the node is currently connected, + * false otherwise + */ + public boolean isNodeConnected(Node node) { + return connectedNodes.contains(node); + } + + /** + * {@inheritDoc} + */ + public Iterator iterator() { + return nodes.iterator(); + } + // // ACTIONS // /** * Loads nodes. - * + * * @throws IOException * if an I/O error occurs loading the nodes */ public void load() throws IOException { + logger.log(Level.FINEST, "load()"); File directoryFile = new File(directory); File nodeFile = new File(directoryFile, "nodes.properties"); if (!nodeFile.exists() || !nodeFile.isFile() || !nodeFile.canRead()) { @@ -193,6 +191,10 @@ public class NodeManager implements HighLevelClientListener { List loadedNodes = new ArrayList(); while (nodeProperties.containsKey("nodes." + ++nodeIndex + ".name")) { String nodePrefix = "nodes." + nodeIndex; + String nodeId = nodeProperties.getProperty(nodePrefix + ".id"); + if (nodeId == null) { + nodeId = Hex.toHex(IdGenerator.generateId()); + } String nodeName = nodeProperties.getProperty(nodePrefix + ".name"); if (!Verifier.verifyNodeName(nodeName)) { logger.log(Level.WARNING, "invalid node name “" + nodeName + "”, skipping…"); @@ -217,24 +219,29 @@ public class NodeManager implements HighLevelClientListener { continue; } Node newNode = new Node(); + newNode.setId(nodeId); newNode.setName(nodeName); newNode.setHostname(nodeHostname); newNode.setPort(nodePort); loadedNodes.add(newNode); } + logger.log(Level.FINE, "loaded " + loadedNodes.size() + " nodes from config"); synchronized (syncObject) { nodes.clear(); - nodes.addAll(loadedNodes); + for (Node node : loadedNodes) { + addNode(node); + } } } /** * Saves all configured nodes. - * + * * @throws IOException * if an I/O error occurs saving the nodes */ public void save() throws IOException { + logger.log(Level.FINEST, "save()"); File directoryFile = new File(directory); if (!directoryFile.exists()) { if (!directoryFile.mkdirs()) { @@ -243,8 +250,9 @@ public class NodeManager implements HighLevelClientListener { } Properties nodeProperties = new Properties(); int nodeIndex = -1; - for (Node node: nodes) { + for (Node node : nodes) { String nodePrefix = "nodes." + ++nodeIndex; + nodeProperties.setProperty(nodePrefix + ".id", node.getId()); nodeProperties.setProperty(nodePrefix + ".name", node.getName()); nodeProperties.setProperty(nodePrefix + ".hostname", node.getHostname()); nodeProperties.setProperty(nodePrefix + ".port", String.valueOf(node.getPort())); @@ -261,161 +269,138 @@ public class NodeManager implements HighLevelClientListener { /** * Adds the given node to this manager. - * + * * @see #connect(Node) * @param node * The node to connect to + * @return true if the node was added, false if + * the node was not added because it was already known */ - public void addNode(Node node) { - synchronized (syncObject) { - if (!nodes.contains(node)) { - nodes.add(node); - } + public boolean addNode(Node node) { + logger.log(Level.FINEST, "addNode(node=" + node + ")"); + if (nodes.contains(node)) { + logger.log(Level.WARNING, "was told to add already known node: " + node); + return false; } + node.addPropertyChangeListener(this); + nodes.add(node); + idNodes.put(node.getId(), node); + nodeListenerSupport.fireNodeAdded(node); + return true; } /** * Removes the given node from the node manager, disconnecting it if it is * currently connected. - * + * * @param node * The node to remove */ public void removeNode(Node node) { + logger.log(Level.FINEST, "removeNode(node=" + node + ")"); synchronized (syncObject) { if (!nodes.contains(node)) { return; } - if (nodeClients.containsKey(node)) { - disconnect(node); - } + nodes.remove(node); + idNodes.remove(node.getId()); + node.removePropertyChangeListener(this); + nodeListenerSupport.fireNodeRemoved(node); } } /** * Tries to establish a connection with the given node. - * + * * @param node * The node to connect to */ public void connect(Node node) { + logger.log(Level.FINEST, "connect(node=" + node + ")"); + if (!nodes.contains(node)) { + logger.log(Level.WARNING, "Was told to connect to node (" + node + ") I don’t know about!"); + return; + } try { - HighLevelClient highLevelClient = new HighLevelClient(clientName, node.getHostname(), node.getPort()); - synchronized (syncObject) { - clientNodes.put(highLevelClient, node); - nodeClients.put(node, highLevelClient); - } - highLevelClient.addHighLevelClientListener(this); - highLevelClient.connect(); + FcpClient fcpClient = new FcpClient(clientName, node.getHostname(), node.getPort()); + fcpClient.connect(); + nodeListenerSupport.fireNodeConnected(node); + } catch (UnknownHostException uhe1) { + nodeListenerSupport.fireNodeConnectionFailed(node, uhe1); } catch (IOException ioe1) { - fireNodeDisconnected(node, ioe1); + nodeListenerSupport.fireNodeConnectionFailed(node, ioe1); + } catch (FcpException fe1) { + nodeListenerSupport.fireNodeConnectionFailed(node, fe1); } } /** * Disconnects the given node without removing it. - * + * * @param node * The node to disconnect */ public void disconnect(Node node) { - synchronized (syncObject) { - if (!nodes.contains(node)) { - return; - } - HighLevelClient highLevelClient = nodeClients.get(node); - highLevelClient.disconnect(); - } + logger.log(Level.FINEST, "disconnect(node=" + node + ")"); } /** * Returns a list of all nodes. - * + * * @return A list of all nodes */ public List getNodes() { return Collections.unmodifiableList(nodes); } - // - // PRIVATE METHODS - // + /** + * Returns the node identified by the given ID. + * + * @param id + * The ID of the node + * @return The node with the given ID, or null if no such node + * was found + */ + Node getNode(String id) { + return idNodes.get(id); + } /** - * Finds a currently unused high-level client, optionally waiting until a - * client is free and marking it used. - * - * @param wait - * true to wait for a free connection, - * false to return null - * @param markAsUsed - * true to mark the connection as used before - * returning it, false not to mark it - * @return An unused FCP connection, or null if no connection - * could be found + * Generates a new SSK key pair. + * + * @return An array with the private key at index 0 and the + * public key at index 1 + * @throws IOException + * if an I/O error occurs communicating with the node + * @throws JSiteException + * if there is a problem with the node */ - @SuppressWarnings("unused") - private HighLevelClient findUnusedClient(boolean wait, boolean markAsUsed) { - synchronized (syncObject) { - HighLevelClient freeHighLevelClient = null; - while (freeHighLevelClient == null) { - for (HighLevelClient highLevelClient: nodeClients.values()) { - if (!usedConnections.contains(highLevelClient)) { - freeHighLevelClient = highLevelClient; - break; - } - } - if (freeHighLevelClient != null) { - if (markAsUsed) { - usedConnections.add(freeHighLevelClient); - } - return freeHighLevelClient; - } - if (!wait) { - return null; - } - try { - syncObject.wait(); - } catch (InterruptedException e) { - /* ignore, just re-check. */ - } - } - /* we never get here, but the compiler doesn't realize. */ - return null; + public String[] generateKeyPair() throws IOException, JSiteException { + logger.log(Level.FINEST, "generateKeyPair()"); + if (nodes.isEmpty()) { + throw new NoNodeException("no node configured"); } + return null; } // - // INTERFACE HighLevelClientListener + // PRIVATE METHODS // - /** - * {@inheritDoc} - */ - public void clientConnected(HighLevelClient highLevelClient) { - logger.log(Level.FINER, "clientConnected(c=" + highLevelClient + ")"); - Node node = clientNodes.get(highLevelClient); - if (node == null) { - logger.log(Level.WARNING, "got event for unknown client"); - return; - } - fireNodeConnected(node); - } + // + // INTERFACE PropertyChangeListener + // /** * {@inheritDoc} */ - public void clientDisconnected(HighLevelClient highLevelClient, Throwable throwable) { - logger.log(Level.FINER, "clientDisconnected(c=" + highLevelClient + ",t=" + throwable + ")"); - synchronized (syncObject) { - Node node = clientNodes.remove(highLevelClient); - if (node == null) { - logger.log(Level.WARNING, "got event for unknown client"); - return; + public void propertyChange(PropertyChangeEvent propertyChangeEvent) { + Object eventSource = propertyChangeEvent.getSource(); + if (eventSource instanceof Node) { + String propertyName = propertyChangeEvent.getPropertyName(); + if ("hostname".equals(propertyName) || "port".equals(propertyName)) { + /* TODO - reconnect. */ } - nodeClients.remove(node); - usedConnections.remove(highLevelClient); - fireNodeDisconnected(node, throwable); } }