List of usage examples for java.net InetSocketAddress getPort
public final int getPort()
From source file:com.alibaba.wasp.fserver.FServer.java
/** * Starts a FServer at the default location * //ww w . ja va2 s . c om * @param conf * @throws java.io.IOException * @throws InterruptedException */ public FServer(Configuration conf) throws IOException, InterruptedException { this.conf = conf; this.isOnline = false; // Set how many times to retry talking to another server over FConnection. FConnectionManager.setServerSideFConnectionRetries(this.conf, LOG); // Config'ed params this.msgInterval = conf.getInt("wasp.fserver.msginterval", 3 * 1000); this.sleeper = new Sleeper(this.msgInterval, this); this.numEntityGroupsToReport = conf.getInt("wasp.fserver.numentitygroupstoreport", 10); this.rpcTimeout = conf.getInt(FConstants.WASP_RPC_TIMEOUT_KEY, FConstants.DEFAULT_WASP_RPC_TIMEOUT); this.abortRequested = false; this.stopped = false; this.actionManager = new StorageActionManager(conf); // Server to handle client requests. String hostname = Strings .domainNamePointerToHostName(DNS.getDefaultHost(conf.get("wasp.fserver.dns.interface", "default"), conf.get("wasp.fserver.dns.nameserver", "default"))); int port = conf.getInt(FConstants.FSERVER_PORT, FConstants.DEFAULT_FSERVER_PORT); // Creation of a HSA will force a resolve. InetSocketAddress initialIsa = new InetSocketAddress(hostname, port); if (initialIsa.getAddress() == null) { throw new IllegalArgumentException("Failed resolve of " + initialIsa); } this.rpcServer = WaspRPC.getServer(FServer.class, this, new Class<?>[] { ClientProtocol.class, AdminProtocol.class, WaspRPCErrorHandler.class, OnlineEntityGroups.class }, initialIsa.getHostName(), // BindAddress is // IP we got for // this server. initialIsa.getPort(), conf); // Set our address. this.isa = this.rpcServer.getListenerAddress(); this.leases = new Leases(conf.getInt(FConstants.THREAD_WAKE_FREQUENCY, 10 * 1000)); this.startcode = System.currentTimeMillis(); int maxThreads = conf.getInt("wasp.transaction.threads.max", 150); this.pool = new ThreadPoolExecutor(1, maxThreads, 60, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new DaemonThreadFactory("thread factory")); ((ThreadPoolExecutor) this.pool).allowCoreThreadTimeOut(true); this.scannerLeaseTimeoutPeriod = conf.getInt(FConstants.WASP_CLIENT_SCANNER_TIMEOUT_PERIOD, FConstants.DEFAULT_WASP_CLIENT_SCANNER_TIMEOUT_PERIOD); this.driver = new BaseDriver(this); this.splitThread = new SplitThread(this); this.globalEntityGroup = new GlobalEntityGroup(this); }
From source file:de.dal33t.powerfolder.clientserver.ServerClient.java
/** * @param conHan//from w ww. j a v a 2 s .com * @return true if the node is the primary login server for the current * account. account. */ public boolean isPrimaryServer(ConnectionHandler conHan) { if (server.getInfo().equals(conHan.getIdentity().getMemberInfo())) { return true; } if (isTempServerNode(server)) { if (server.getReconnectAddress().equals(conHan.getRemoteAddress())) { return true; } // Try check by hostname / port InetSocketAddress nodeSockAddr = conHan.getRemoteAddress(); InetSocketAddress serverSockAddr = server.getReconnectAddress(); if (nodeSockAddr == null || serverSockAddr == null) { return false; } InetAddress nodeAddr = nodeSockAddr.getAddress(); InetAddress serverAddr = serverSockAddr.getAddress(); if (nodeAddr == null || serverAddr == null) { return false; } String nodeHost = NetworkUtil.getHostAddressNoResolve(nodeAddr); String serverHost = NetworkUtil.getHostAddressNoResolve(serverAddr); int nodePort = nodeSockAddr.getPort(); int serverPort = serverSockAddr.getPort(); return nodeHost.equalsIgnoreCase(serverHost) && nodePort == serverPort; } return false; }
From source file:de.dal33t.powerfolder.clientserver.ServerClient.java
/** * @param node/*from w w w . j a v a2 s .c o m*/ * @return true if the node is the primary login server for the current * account. account. */ public boolean isPrimaryServer(Member node) { if (server.equals(node)) { return true; } if (isTempServerNode(server)) { if (server.getReconnectAddress().equals(node.getReconnectAddress())) { return true; } // Try check by hostname / port InetSocketAddress nodeSockAddr = node.getReconnectAddress(); InetSocketAddress serverSockAddr = server.getReconnectAddress(); if (nodeSockAddr == null || serverSockAddr == null) { return false; } InetAddress nodeAddr = nodeSockAddr.getAddress(); InetAddress serverAddr = serverSockAddr.getAddress(); if (nodeAddr == null || serverAddr == null) { return false; } String nodeHost = NetworkUtil.getHostAddressNoResolve(nodeAddr); String serverHost = NetworkUtil.getHostAddressNoResolve(serverAddr); int nodePort = nodeSockAddr.getPort(); int serverPort = serverSockAddr.getPort(); return nodeHost.equalsIgnoreCase(serverHost) && nodePort == serverPort; } return false; }
From source file:org.apache.hadoop.hdfs.server.namenode.SecondaryNameNode.java
/** * Initialize SecondaryNameNode./*from ww w . ja va2s . c om*/ */ private void initialize(final Configuration conf) throws IOException { final InetSocketAddress infoSocAddr = getHttpAddress(conf); infoBindAddress = infoSocAddr.getHostName(); if (UserGroupInformation.isSecurityEnabled()) { SecurityUtil.login(conf, DFSConfigKeys.DFS_SECONDARY_NAMENODE_KEYTAB_FILE_KEY, DFSConfigKeys.DFS_SECONDARY_NAMENODE_USER_NAME_KEY, infoBindAddress); } // initiate Java VM metrics JvmMetricsSource.create("SecondaryNameNode", conf.get("session.id")); // Create connection to the namenode. shouldRun = true; nameNodeAddr = NameNode.getServiceAddress(conf, true); this.conf = conf; this.namenode = (NamenodeProtocol) RPC.waitForProxy(NamenodeProtocol.class, NamenodeProtocol.versionID, nameNodeAddr, conf); // initialize checkpoint directories fsName = getInfoServer(); checkpointDirs = FSImage.getCheckpointDirs(conf, "/tmp/hadoop/dfs/namesecondary"); checkpointEditsDirs = FSImage.getCheckpointEditsDirs(conf, "/tmp/hadoop/dfs/namesecondary"); checkpointImage = new CheckpointStorage(); checkpointImage.recoverCreate(checkpointDirs, checkpointEditsDirs); // Initialize other scheduling parameters from the configuration checkpointPeriod = conf.getLong("fs.checkpoint.period", 3600); checkpointSize = conf.getLong("fs.checkpoint.size", 4194304); // initialize the webserver for uploading files. // Kerberized SSL servers must be run from the host principal... UserGroupInformation httpUGI = UserGroupInformation.loginUserFromKeytabAndReturnUGI( SecurityUtil.getServerPrincipal( conf.get(DFSConfigKeys.DFS_SECONDARY_NAMENODE_KRB_HTTPS_USER_NAME_KEY), infoBindAddress), conf.get(DFSConfigKeys.DFS_SECONDARY_NAMENODE_KEYTAB_FILE_KEY)); try { infoServer = httpUGI.doAs(new PrivilegedExceptionAction<HttpServer>() { @Override public HttpServer run() throws IOException, InterruptedException { LOG.info("Starting web server as: " + UserGroupInformation.getCurrentUser().getUserName()); int tmpInfoPort = infoSocAddr.getPort(); infoServer = new HttpServer("secondary", infoBindAddress, tmpInfoPort, tmpInfoPort == 0, conf, SecurityUtil.getAdminAcls(conf, DFSConfigKeys.DFS_ADMIN)); if (UserGroupInformation.isSecurityEnabled()) { System.setProperty("https.cipherSuites", Krb5AndCertsSslSocketConnector.KRB5_CIPHER_SUITES.get(0)); InetSocketAddress secInfoSocAddr = NetUtils.createSocketAddr(infoBindAddress + ":" + conf.get("dfs.secondary.https.port", infoBindAddress + ":" + 0)); imagePort = secInfoSocAddr.getPort(); infoServer.addSslListener(secInfoSocAddr, conf, false, true); } infoServer.setAttribute("name.system.image", checkpointImage); infoServer.setAttribute(JspHelper.CURRENT_CONF, conf); infoServer.addInternalServlet("getimage", "/getimage", GetImageServlet.class, true); infoServer.start(); return infoServer; } }); } catch (InterruptedException e) { throw new RuntimeException(e); } LOG.info("Web server init done"); // The web-server port can be ephemeral... ensure we have the correct info infoPort = infoServer.getPort(); if (!UserGroupInformation.isSecurityEnabled()) imagePort = infoPort; conf.set("dfs.secondary.http.address", infoBindAddress + ":" + infoPort); LOG.info("Secondary Web-server up at: " + infoBindAddress + ":" + infoPort); LOG.info("Secondary image servlet up at: " + infoBindAddress + ":" + imagePort); LOG.warn("Checkpoint Period :" + checkpointPeriod + " secs " + "(" + checkpointPeriod / 60 + " min)"); LOG.warn("Log Size Trigger :" + checkpointSize + " bytes " + "(" + checkpointSize / 1024 + " KB)"); }
From source file:edu.umass.cs.reconfiguration.Reconfigurator.java
@SuppressWarnings("unused") @Deprecated/*from www .j a v a 2 s .co m*/ private AddressMessenger<JSONObject> initClientMessenger() { AbstractPacketDemultiplexer<JSONObject> pd = null; Messenger<InetSocketAddress, JSONObject> cMsgr = null; try { int myPort = (this.consistentNodeConfig.getNodePort(getMyID())); if (ReconfigurationConfig.getClientFacingPort(myPort) != myPort) { log.log(Level.INFO, "{0} creating client messenger at {1}:{2}", new Object[] { this, this.consistentNodeConfig.getBindAddress(getMyID()), ReconfigurationConfig.getClientFacingPort(myPort) }); MessageNIOTransport<InetSocketAddress, JSONObject> niot = null; InetSocketAddress isa = new InetSocketAddress(this.consistentNodeConfig.getBindAddress(getMyID()), ReconfigurationConfig.getClientFacingPort(myPort)); cMsgr = new JSONMessenger<InetSocketAddress>( niot = new MessageNIOTransport<InetSocketAddress, JSONObject>(isa.getAddress(), isa.getPort(), (pd = new ReconfigurationPacketDemultiplexer()), ReconfigurationConfig.getClientSSLMode())); if (!niot.getListeningSocketAddress().equals(isa)) throw new IOException("Unable to listen on specified socket address at " + isa); pd.register(clientRequestTypes, this); } } catch (IOException e) { e.printStackTrace(); log.severe(this + ": " + e.getMessage()); System.exit(1); } return cMsgr != null ? cMsgr : (AddressMessenger<JSONObject>) this.messenger; }
From source file:org.apache.hadoop.mapred.MapReduceChildJVM.java
public static List<String> getVMCommand(InetSocketAddress taskAttemptListenerAddr, Task task, String javaHome, String workDir, String logDir, String childTmpDir, ID jvmID) { TaskAttemptID attemptID = task.getTaskID(); JobConf conf = task.conf;/* w w w . j a va 2s . c o m*/ Vector<String> vargs = new Vector<String>(8); vargs.add("exec"); vargs.add(javaHome + "/bin/java"); // Add child (task) java-vm options. // // The following symbols if present in mapred.{map|reduce}.child.java.opts // value are replaced: // + @taskid@ is interpolated with value of TaskID. // Other occurrences of @ will not be altered. // // Example with multiple arguments and substitutions, showing // jvm GC logging, and start of a passwordless JVM JMX agent so can // connect with jconsole and the likes to watch child memory, threads // and get thread dumps. // // <property> // <name>mapred.map.child.java.opts</name> // <value>-Xmx 512M -verbose:gc -Xloggc:/tmp/@taskid@.gc \ // -Dcom.sun.management.jmxremote.authenticate=false \ // -Dcom.sun.management.jmxremote.ssl=false \ // </value> // </property> // // <property> // <name>mapred.reduce.child.java.opts</name> // <value>-Xmx 1024M -verbose:gc -Xloggc:/tmp/@taskid@.gc \ // -Dcom.sun.management.jmxremote.authenticate=false \ // -Dcom.sun.management.jmxremote.ssl=false \ // </value> // </property> // String javaOpts = getChildJavaOpts(conf, task.isMapTask()); javaOpts = javaOpts.replace("@taskid@", attemptID.toString()); String[] javaOptsSplit = javaOpts.split(" "); // Add java.library.path; necessary for loading native libraries. // // 1. We add the 'cwd' of the task to it's java.library.path to help // users distribute native libraries via the DistributedCache. // 2. The user can also specify extra paths to be added to the // java.library.path via mapred.{map|reduce}.child.java.opts. // String libraryPath = workDir; boolean hasUserLDPath = false; for (int i = 0; i < javaOptsSplit.length; i++) { if (javaOptsSplit[i].startsWith("-Djava.library.path=")) { // TODO: Does the above take care of escaped space chars javaOptsSplit[i] += SYSTEM_PATH_SEPARATOR + libraryPath; hasUserLDPath = true; break; } } if (!hasUserLDPath) { vargs.add("-Djava.library.path=" + libraryPath); } for (int i = 0; i < javaOptsSplit.length; i++) { vargs.add(javaOptsSplit[i]); } if (childTmpDir != null) { vargs.add("-Djava.io.tmpdir=" + childTmpDir); } // Setup the log4j prop long logSize = TaskLog.getTaskLogLength(conf); setupLog4jProperties(vargs, logSize, logDir); if (conf.getProfileEnabled()) { if (conf.getProfileTaskRange(task.isMapTask()).isIncluded(task.getPartition())) { File prof = getTaskLogFile(logDir, TaskLog.LogName.PROFILE); vargs.add(String.format(conf.getProfileParams(), prof.toString())); } } // Add main class and its arguments vargs.add(YarnChild.class.getName()); // main of Child // pass TaskAttemptListener's address vargs.add(taskAttemptListenerAddr.getAddress().getHostAddress()); vargs.add(Integer.toString(taskAttemptListenerAddr.getPort())); vargs.add(attemptID.toString()); // pass task identifier // Finally add the jvmID vargs.add(String.valueOf(jvmID.getId())); vargs.add("1>" + getTaskLogFile(logDir, TaskLog.LogName.STDERR)); vargs.add("2>" + getTaskLogFile(logDir, TaskLog.LogName.STDOUT)); // Final commmand StringBuilder mergedCommand = new StringBuilder(); for (CharSequence str : vargs) { mergedCommand.append(str).append(" "); } Vector<String> vargsFinal = new Vector<String>(1); vargsFinal.add(mergedCommand.toString()); return vargsFinal; }
From source file:com.buaa.cfs.conf.Configuration.java
/** * Get the socket address for <code>hostProperty</code> as a <code>InetSocketAddress</code>. If * <code>hostProperty</code> is <code>null</code>, <code>addressProperty</code> will be used. This is useful for * cases where we want to differentiate between host bind address and address clients should use to establish * connection.//from w w w .j a v a 2 s. c o m * * @param hostProperty bind host property name. * @param addressProperty address property name. * @param defaultAddressValue the default value * @param defaultPort the default port * * @return InetSocketAddress */ public InetSocketAddress getSocketAddr(String hostProperty, String addressProperty, String defaultAddressValue, int defaultPort) { InetSocketAddress bindAddr = getSocketAddr(addressProperty, defaultAddressValue, defaultPort); final String host = get(hostProperty); if (host == null || host.isEmpty()) { return bindAddr; } return NetUtils.createSocketAddr(host, bindAddr.getPort(), hostProperty); }
From source file:edu.umass.cs.reconfiguration.Reconfigurator.java
/** * Initiates clear or SSL client messenger based on {@code ssl}. * //www. ja va2 s . c o m * @param ssl * @return */ @SuppressWarnings("unchecked") private AddressMessenger<JSONObject> initClientMessenger(boolean ssl) { AbstractPacketDemultiplexer<JSONObject> pd = null; Messenger<InetSocketAddress, JSONObject> cMsgr = null; try { int myPort = (this.consistentNodeConfig.getNodePort(getMyID())); if ((ssl ? getClientFacingSSLPort(myPort) : getClientFacingClearPort(myPort)) != myPort) { log.log(Level.INFO, "{0} creating {1} client messenger at {2}:{3}", new Object[] { this, ssl ? "SSL" : "", this.consistentNodeConfig.getBindAddress(getMyID()), "" + (ssl ? getClientFacingSSLPort(myPort) : getClientFacingClearPort(myPort)) }); AddressMessenger<?> existing = (ssl ? this.messenger.getSSLClientMessenger() : this.messenger.getClientMessenger()); if (existing == null || existing == this.messenger) { MessageNIOTransport<InetSocketAddress, JSONObject> niot = null; InetSocketAddress isa = new InetSocketAddress( this.consistentNodeConfig.getBindAddress(getMyID()), ssl ? getClientFacingSSLPort(myPort) : getClientFacingClearPort(myPort)); cMsgr = new JSONMessenger<InetSocketAddress>( niot = new MessageNIOTransport<InetSocketAddress, JSONObject>(isa.getAddress(), isa.getPort(), (pd = new ReconfigurationPacketDemultiplexer()), ssl ? ReconfigurationConfig.getClientSSLMode() : SSL_MODES.CLEAR)); if (!niot.getListeningSocketAddress().equals(isa)) throw new IOException("Unable to listen on specified socket address at " + isa + "; created messenger listening instead on " + niot.getListeningSocketAddress()); } else if (!ssl) { log.log(Level.INFO, "{0} adding self as demultiplexer to existing {1} client messenger", new Object[] { this, ssl ? "SSL" : "" }); if (this.messenger.getClientMessenger() instanceof Messenger) ((Messenger<NodeIDType, ?>) this.messenger.getClientMessenger()) .addPacketDemultiplexer(pd = new ReconfigurationPacketDemultiplexer()); } else { log.log(Level.INFO, "{0} adding self as demultiplexer to existing {1} client messenger", new Object[] { this, ssl ? "SSL" : "" }); if (this.messenger.getSSLClientMessenger() instanceof Messenger) ((Messenger<NodeIDType, ?>) this.messenger.getSSLClientMessenger()) .addPacketDemultiplexer(pd = new ReconfigurationPacketDemultiplexer()); } assert (pd != null); pd.register(clientRequestTypes, this); } } catch (IOException e) { e.printStackTrace(); log.severe(this + " failed to initialize client messenger: " + e.getMessage()); System.exit(1); } if (cMsgr != null) if (ssl && this.messenger.getSSLClientMessenger() == null) this.messenger.setSSLClientMessenger(cMsgr); else if (!ssl && this.messenger.getClientMessenger() == null) this.messenger.setClientMessenger(cMsgr); return cMsgr != null ? cMsgr : (AddressMessenger<JSONObject>) this.messenger; }
From source file:de.dal33t.powerfolder.Controller.java
/** * Connects to a remote peer, with ip and port * * @param address//from w ww.ja v a2s . c om * @return the node that connected * @throws ConnectionException * if connection failed * @returns the connected node */ public Member connect(InetSocketAddress address) throws ConnectionException { if (!started) { logInfo("NOT Connecting to " + address + ". Controller not started"); throw new ConnectionException("NOT Connecting to " + address + ". Controller not started"); } if (address.getPort() <= 0) { // connect to defaul port logWarning("Unable to connect, port illegal " + address.getPort()); } logFine("Connecting to " + address + "..."); ConnectionHandler conHan = ioProvider.getConnectionHandlerFactory().tryToConnect(address); // Accept new node return nodeManager.acceptConnection(conHan); }