List of usage examples for java.net InetSocketAddress getAddress
public final InetAddress getAddress()
From source file:ch.epfl.eagle.api.EagleFrontendClient.java
/** * Initialize a connection to an eagle scheduler. * @param eagleSchedulerAddr. The socket address of the Eagle scheduler. * @param app. The application id. Note that this must be consistent across frontends * and backends./*from ww w .j av a 2 s. c o m*/ * @param frontendServer. A class which implements the frontend server interface (for * communication from Eagle). * @param listenPort. The port on which to listen for request from the scheduler. * @throws IOException */ public void initialize(InetSocketAddress eagleSchedulerAddr, String app, FrontendService.Iface frontendServer, int listenPort) throws TException, IOException { FrontendService.Processor<FrontendService.Iface> processor = new FrontendService.Processor<FrontendService.Iface>( frontendServer); if (!launchedServerAlready) { try { TServers.launchThreadedThriftServer(listenPort, 8, processor); } catch (IOException e) { LOG.fatal("Couldn't launch server side of frontend", e); } launchedServerAlready = true; } for (int i = 0; i < NUM_CLIENTS; i++) { Client client = TClients.createBlockingSchedulerClient(eagleSchedulerAddr.getAddress().getHostAddress(), eagleSchedulerAddr.getPort(), 60000); clients.add(client); } clients.peek().registerFrontend(app, Network.getIPAddress(new PropertiesConfiguration()) + ":" + listenPort); }
From source file:org.apache.flink.runtime.webmonitor.WebRuntimeMonitor.java
public WebRuntimeMonitor(Configuration config, LeaderRetrievalService leaderRetrievalService, ActorSystem actorSystem) throws IOException, InterruptedException { this.leaderRetrievalService = checkNotNull(leaderRetrievalService); this.timeout = AkkaUtils.getTimeout(config); this.retriever = new JobManagerRetriever(this, actorSystem, AkkaUtils.getTimeout(config), timeout); final WebMonitorConfig cfg = new WebMonitorConfig(config); final String configuredAddress = cfg.getWebFrontendAddress(); final int configuredPort = cfg.getWebFrontendPort(); if (configuredPort < 0) { throw new IllegalArgumentException("Web frontend port is invalid: " + configuredPort); }// w w w .j a va2s . c o m final WebMonitorUtils.LogFileLocation logFiles = WebMonitorUtils.LogFileLocation.find(config); // create an empty directory in temp for the web server String rootDirFileName = "flink-web-" + UUID.randomUUID(); webRootDir = new File(getBaseDir(config), rootDirFileName); LOG.info("Using directory {} for the web interface files", webRootDir); final boolean webSubmitAllow = cfg.isProgramSubmitEnabled(); if (webSubmitAllow) { // create storage for uploads this.uploadDir = getUploadDir(config); // the upload directory should either 1. exist and writable or 2. can be created and writable if (!(uploadDir.exists() && uploadDir.canWrite()) && !(uploadDir.mkdir() && uploadDir.canWrite())) { throw new IOException(String.format("Jar upload directory %s cannot be created or is not writable.", uploadDir.getAbsolutePath())); } LOG.info("Using directory {} for web frontend JAR file uploads", uploadDir); } else { this.uploadDir = null; } ExecutionGraphHolder currentGraphs = new ExecutionGraphHolder(); // - Back pressure stats ---------------------------------------------- stackTraceSamples = new StackTraceSampleCoordinator(actorSystem.dispatcher(), 60000); // Back pressure stats tracker config int cleanUpInterval = config.getInteger(ConfigConstants.JOB_MANAGER_WEB_BACK_PRESSURE_CLEAN_UP_INTERVAL, ConfigConstants.DEFAULT_JOB_MANAGER_WEB_BACK_PRESSURE_CLEAN_UP_INTERVAL); int refreshInterval = config.getInteger(ConfigConstants.JOB_MANAGER_WEB_BACK_PRESSURE_REFRESH_INTERVAL, ConfigConstants.DEFAULT_JOB_MANAGER_WEB_BACK_PRESSURE_REFRESH_INTERVAL); int numSamples = config.getInteger(ConfigConstants.JOB_MANAGER_WEB_BACK_PRESSURE_NUM_SAMPLES, ConfigConstants.DEFAULT_JOB_MANAGER_WEB_BACK_PRESSURE_NUM_SAMPLES); int delay = config.getInteger(ConfigConstants.JOB_MANAGER_WEB_BACK_PRESSURE_DELAY, ConfigConstants.DEFAULT_JOB_MANAGER_WEB_BACK_PRESSURE_DELAY); Time delayBetweenSamples = Time.milliseconds(delay); backPressureStatsTracker = new BackPressureStatsTracker(stackTraceSamples, cleanUpInterval, numSamples, delayBetweenSamples); // -------------------------------------------------------------------- executorService = new ForkJoinPool(); ExecutionContextExecutor context = ExecutionContext$.MODULE$.fromExecutor(executorService); // Config to enable https access to the web-ui boolean enableSSL = config.getBoolean(ConfigConstants.JOB_MANAGER_WEB_SSL_ENABLED, ConfigConstants.DEFAULT_JOB_MANAGER_WEB_SSL_ENABLED) && SSLUtils.getSSLEnabled(config); if (enableSSL) { LOG.info("Enabling ssl for the web frontend"); try { serverSSLContext = SSLUtils.createSSLServerContext(config); } catch (Exception e) { throw new IOException("Failed to initialize SSLContext for the web frontend", e); } } else { serverSSLContext = null; } metricFetcher = new MetricFetcher(actorSystem, retriever, context); String defaultSavepointDir = config.getString(ConfigConstants.SAVEPOINT_DIRECTORY_KEY, null); JobCancellationWithSavepointHandlers cancelWithSavepoint = new JobCancellationWithSavepointHandlers( currentGraphs, context, defaultSavepointDir); RuntimeMonitorHandler triggerHandler = handler(cancelWithSavepoint.getTriggerHandler()); RuntimeMonitorHandler inProgressHandler = handler(cancelWithSavepoint.getInProgressHandler()); router = new Router() // config how to interact with this web server .GET("/config", handler(new DashboardConfigHandler(cfg.getRefreshInterval()))) // the overview - how many task managers, slots, free slots, ... .GET("/overview", handler(new ClusterOverviewHandler(DEFAULT_REQUEST_TIMEOUT))) // job manager configuration .GET("/jobmanager/config", handler(new JobManagerConfigHandler(config))) // overview over jobs .GET("/joboverview", handler(new CurrentJobsOverviewHandler(DEFAULT_REQUEST_TIMEOUT, true, true))) .GET("/joboverview/running", handler(new CurrentJobsOverviewHandler(DEFAULT_REQUEST_TIMEOUT, true, false))) .GET("/joboverview/completed", handler(new CurrentJobsOverviewHandler(DEFAULT_REQUEST_TIMEOUT, false, true))) .GET("/jobs", handler(new CurrentJobIdsHandler(DEFAULT_REQUEST_TIMEOUT))) .GET("/jobs/:jobid", handler(new JobDetailsHandler(currentGraphs, metricFetcher))) .GET("/jobs/:jobid/vertices", handler(new JobDetailsHandler(currentGraphs, metricFetcher))) .GET("/jobs/:jobid/vertices/:vertexid", handler(new JobVertexDetailsHandler(currentGraphs, metricFetcher))) .GET("/jobs/:jobid/vertices/:vertexid/subtasktimes", handler(new SubtasksTimesHandler(currentGraphs))) .GET("/jobs/:jobid/vertices/:vertexid/taskmanagers", handler(new JobVertexTaskManagersHandler(currentGraphs, metricFetcher))) .GET("/jobs/:jobid/vertices/:vertexid/accumulators", handler(new JobVertexAccumulatorsHandler(currentGraphs))) .GET("/jobs/:jobid/vertices/:vertexid/checkpoints", handler(new JobVertexCheckpointsHandler(currentGraphs))) .GET("/jobs/:jobid/vertices/:vertexid/backpressure", handler(new JobVertexBackPressureHandler(currentGraphs, backPressureStatsTracker, refreshInterval))) .GET("/jobs/:jobid/vertices/:vertexid/metrics", handler(new JobVertexMetricsHandler(metricFetcher))) .GET("/jobs/:jobid/vertices/:vertexid/subtasks/accumulators", handler(new SubtasksAllAccumulatorsHandler(currentGraphs))) .GET("/jobs/:jobid/vertices/:vertexid/subtasks/:subtasknum", handler(new SubtaskCurrentAttemptDetailsHandler(currentGraphs, metricFetcher))) .GET("/jobs/:jobid/vertices/:vertexid/subtasks/:subtasknum/attempts/:attempt", handler(new SubtaskExecutionAttemptDetailsHandler(currentGraphs, metricFetcher))) .GET("/jobs/:jobid/vertices/:vertexid/subtasks/:subtasknum/attempts/:attempt/accumulators", handler(new SubtaskExecutionAttemptAccumulatorsHandler(currentGraphs))) .GET("/jobs/:jobid/plan", handler(new JobPlanHandler(currentGraphs))) .GET("/jobs/:jobid/config", handler(new JobConfigHandler(currentGraphs))) .GET("/jobs/:jobid/exceptions", handler(new JobExceptionsHandler(currentGraphs))) .GET("/jobs/:jobid/accumulators", handler(new JobAccumulatorsHandler(currentGraphs))) .GET("/jobs/:jobid/checkpoints", handler(new JobCheckpointsHandler(currentGraphs))) .GET("/jobs/:jobid/metrics", handler(new JobMetricsHandler(metricFetcher))) .GET("/taskmanagers", handler(new TaskManagersHandler(DEFAULT_REQUEST_TIMEOUT, metricFetcher))) .GET("/taskmanagers/:" + TaskManagersHandler.TASK_MANAGER_ID_KEY + "/metrics", handler(new TaskManagersHandler(DEFAULT_REQUEST_TIMEOUT, metricFetcher))) .GET("/taskmanagers/:" + TaskManagersHandler.TASK_MANAGER_ID_KEY + "/log", new TaskManagerLogHandler(retriever, context, jobManagerAddressPromise.future(), timeout, TaskManagerLogHandler.FileMode.LOG, config, enableSSL)) .GET("/taskmanagers/:" + TaskManagersHandler.TASK_MANAGER_ID_KEY + "/stdout", new TaskManagerLogHandler(retriever, context, jobManagerAddressPromise.future(), timeout, TaskManagerLogHandler.FileMode.STDOUT, config, enableSSL)) .GET("/taskmanagers/:" + TaskManagersHandler.TASK_MANAGER_ID_KEY + "/metrics", handler(new TaskManagerMetricsHandler(metricFetcher))) // log and stdout .GET("/jobmanager/log", logFiles.logFile == null ? new ConstantTextHandler("(log file unavailable)") : new StaticFileServerHandler(retriever, jobManagerAddressPromise.future(), timeout, logFiles.logFile, enableSSL)) .GET("/jobmanager/stdout", logFiles.stdOutFile == null ? new ConstantTextHandler("(stdout file unavailable)") : new StaticFileServerHandler(retriever, jobManagerAddressPromise.future(), timeout, logFiles.stdOutFile, enableSSL)) .GET("/jobmanager/metrics", handler(new JobManagerMetricsHandler(metricFetcher))) // Cancel a job via GET (for proper integration with YARN this has to be performed via GET) .GET("/jobs/:jobid/yarn-cancel", handler(new JobCancellationHandler())) // DELETE is the preferred way of canceling a job (Rest-conform) .DELETE("/jobs/:jobid/cancel", handler(new JobCancellationHandler())) .GET("/jobs/:jobid/cancel-with-savepoint", triggerHandler) .GET("/jobs/:jobid/cancel-with-savepoint/target-directory/:targetDirectory", triggerHandler) .GET(JobCancellationWithSavepointHandlers.IN_PROGRESS_URL, inProgressHandler) // stop a job via GET (for proper integration with YARN this has to be performed via GET) .GET("/jobs/:jobid/yarn-stop", handler(new JobStoppingHandler())) // DELETE is the preferred way of stopping a job (Rest-conform) .DELETE("/jobs/:jobid/stop", handler(new JobStoppingHandler())); if (webSubmitAllow) { router // fetch the list of uploaded jars. .GET("/jars", handler(new JarListHandler(uploadDir))) // get plan for an uploaded jar .GET("/jars/:jarid/plan", handler(new JarPlanHandler(uploadDir))) // run a jar .POST("/jars/:jarid/run", handler(new JarRunHandler(uploadDir, timeout, config))) // upload a jar .POST("/jars/upload", handler(new JarUploadHandler(uploadDir))) // delete an uploaded jar from submission interface .DELETE("/jars/:jarid", handler(new JarDeleteHandler(uploadDir))); } else { router // send an Access Denied message (sort of) // Every other GET request will go to the File Server, which will not provide // access to the jar directory anyway, because it doesn't exist in webRootDir. .GET("/jars", handler(new JarAccessDeniedHandler())); } // this handler serves all the static contents router.GET("/:*", new StaticFileServerHandler(retriever, jobManagerAddressPromise.future(), timeout, webRootDir, enableSSL)); // add shutdown hook for deleting the directories and remaining temp files on shutdown try { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { cleanup(); } }); } catch (IllegalStateException e) { // race, JVM is in shutdown already, we can safely ignore this LOG.debug("Unable to add shutdown hook, shutdown already in progress", e); } catch (Throwable t) { // these errors usually happen when the shutdown is already in progress LOG.warn("Error while adding shutdown hook", t); } ChannelInitializer<SocketChannel> initializer = new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { Handler handler = new Handler(router); // SSL should be the first handler in the pipeline if (serverSSLContext != null) { SSLEngine sslEngine = serverSSLContext.createSSLEngine(); sslEngine.setUseClientMode(false); ch.pipeline().addLast("ssl", new SslHandler(sslEngine)); } ch.pipeline().addLast(new HttpServerCodec()).addLast(new ChunkedWriteHandler()) .addLast(new HttpRequestHandler(uploadDir)).addLast(handler.name(), handler) .addLast(new PipelineErrorHandler(LOG)); } }; NioEventLoopGroup bossGroup = new NioEventLoopGroup(1); NioEventLoopGroup workerGroup = new NioEventLoopGroup(); this.bootstrap = new ServerBootstrap(); this.bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(initializer); ChannelFuture ch; if (configuredAddress == null) { ch = this.bootstrap.bind(configuredPort); } else { ch = this.bootstrap.bind(configuredAddress, configuredPort); } this.serverChannel = ch.sync().channel(); InetSocketAddress bindAddress = (InetSocketAddress) serverChannel.localAddress(); String address = bindAddress.getAddress().getHostAddress(); int port = bindAddress.getPort(); LOG.info("Web frontend listening at " + address + ':' + port); }
From source file:com.jkoolcloud.tnt4j.streams.parsers.ActivitySyslogEventParser.java
@Override protected Map<String, Object> getDataMap(Object data) { if (data == null) { return null; }/* w w w .j a v a 2s.c o m*/ SyslogServerEventIF event = (SyslogServerEventIF) data; Map<String, Object> dataMap = new HashMap<>(); dataMap.put(RAW_ACTIVITY_STRING_KEY, Utils.getString(event.getRaw())); Date date = (event.getDate() == null ? new Date() : event.getDate()); String facility = SyslogUtils.getFacilityString(event.getFacility()); OpLevel level = SyslogUtils.getOpLevel(event.getLevel()); int priority = (event.getFacility() << 3) + event.getLevel(); dataMap.put(EventName.name(), facility); dataMap.put(Severity.name(), level); dataMap.put(FIELD_FACILITY, facility); dataMap.put(FIELD_HOSTNAME, event.getHost()); dataMap.put(FIELD_LEVEL, event.getLevel()); dataMap.put(FIELD_PRIORITY, priority); InetSocketAddress from = null; if (event instanceof SyslogServerEvent) { try { Field addressField = event.getClass().getField("inetAddress"); // NON-NLS addressField.setAccessible(true); from = (InetSocketAddress) addressField.get(event); } catch (Exception exc) { } } if (from == null) { dataMap.put(Location.name(), event.getHost()); } else { dataMap.put(FIELD_HOSTADDR, from.getAddress().getHostAddress()); dataMap.put(Location.name(), from.getAddress().getHostAddress()); } dataMap.put(MsgCharSet.name(), event.getCharSet()); if (event instanceof StructuredSyslogServerEvent) { processRFC5424(facility, (StructuredSyslogServerEvent) event, dataMap); } else { processRFC3164(facility, event, dataMap); } String eventKey = String.format("%s/%s", dataMap.get(Location.name()), dataMap.get(ResourceName.name())); // NON-NLS long eventTime = date.getTime(); dataMap.put(EndTime.name(), eventTime * 1000); dataMap.put(ElapsedTime.name(), getUsecSinceLastEvent(eventKey, eventTime)); return suppress(dataMap); }
From source file:org.cloudata.core.commitlog.ServerLocationManager.java
public void removeCommitLogServer(String hostAddrStr) throws IOException { InetSocketAddress hostAddr = new InetSocketAddress(InetAddress.getByName(getHost(hostAddrStr)), getPort(hostAddrStr));//from w w w.j av a 2 s . c o m if (hostAddr.getAddress().equals(InetAddress.getLocalHost())) { localCommitLogServerAddress = null; } logServerAddrList.remove(hostAddr); LOG.info("CommitLogServer [" + hostAddrStr + "] removed"); }
From source file:edu.berkeley.sparrow.api.SparrowFrontendClient.java
/** * Initialize a connection to a sparrow scheduler. * @param sparrowSchedulerAddr. The socket address of the Sparrow scheduler. * @param app. The application id. Note that this must be consistent across frontends * and backends./*from w w w . j a va 2 s . c o m*/ * @param frontendServer. A class which implements the frontend server interface (for * communication from Sparrow). * @param listenPort. The port on which to listen for request from the scheduler. * @throws IOException */ public void initialize(InetSocketAddress sparrowSchedulerAddr, String app, FrontendService.Iface frontendServer, int listenPort) throws TException, IOException { FrontendService.Processor<FrontendService.Iface> processor = new FrontendService.Processor<FrontendService.Iface>( frontendServer); if (!launchedServerAlready) { try { TServers.launchThreadedThriftServer(listenPort, 8, processor); } catch (IOException e) { LOG.fatal("Couldn't launch server side of frontend", e); } launchedServerAlready = true; } for (int i = 0; i < NUM_CLIENTS; i++) { Client client = TClients.createBlockingSchedulerClient( sparrowSchedulerAddr.getAddress().getHostAddress(), sparrowSchedulerAddr.getPort(), 60000); clients.add(client); } clients.peek().registerFrontend(app, Network.getIPAddress(new PropertiesConfiguration()) + ":" + listenPort); }
From source file:org.cloudata.core.commitlog.ServerLocationManager.java
void addCommitLogServers(String hostAddrStr) throws IOException { InetSocketAddress hostAddr = new InetSocketAddress(InetAddress.getByName(getHost(hostAddrStr)), getPort(hostAddrStr));/*from w w w . j av a2 s. c om*/ if (hostAddr.getAddress().equals(InetAddress.getLocalHost())) { localCommitLogServerAddress = hostAddr; } LOG.info("CommitLogServer [" + hostAddrStr + "] is ready"); addrSet.add(hostAddr); }
From source file:org.cloudata.core.commitlog.ServerLocationManager.java
public void addCommitLogServers(String hostAddrStr) throws IOException { InetSocketAddress hostAddr = new InetSocketAddress(InetAddress.getByName(getHost(hostAddrStr)), getPort(hostAddrStr));//from w w w .java2 s . c o m if (hostAddr.getAddress().equals(InetAddress.getLocalHost())) { if (locality) { localCommitLogServerAddress = hostAddr; } } LOG.info("CommitLogServer [" + hostAddrStr + "] is ready"); logServerAddrList.add(hostAddr); }
From source file:Proxy.java
String toString(InetSocketAddress addr) { StringBuilder sb;/* w w w . j a v a2s. co m*/ sb = new StringBuilder(); if (addr == null) return null; sb.append(addr.getAddress().getHostName()).append(':').append(addr.getPort()); if (addr instanceof MyInetSocketAddress) sb.append(" [ssl=").append(((MyInetSocketAddress) addr).ssl()).append(']'); return sb.toString(); }
From source file:org.apache.flink.runtime.taskmanager.TaskManager.java
/** * Determines the IP address of the interface from which the TaskManager can connect to the given JobManager * IP address./*www . j a v a2 s .com*/ * * @param jobManagerAddress The socket address to connect to. * @return The IP address of the interface that connects to the JobManager. * @throws IOException If no connection could be established. */ private static InetAddress getTaskManagerAddress(InetSocketAddress jobManagerAddress) throws IOException { AddressDetectionState strategy = AddressDetectionState.ADDRESS; while (true) { Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces(); while (e.hasMoreElements()) { NetworkInterface n = e.nextElement(); Enumeration<InetAddress> ee = n.getInetAddresses(); while (ee.hasMoreElements()) { InetAddress i = ee.nextElement(); switch (strategy) { case ADDRESS: if (hasCommonPrefix(jobManagerAddress.getAddress().getAddress(), i.getAddress())) { if (tryToConnect(i, jobManagerAddress, strategy.getTimeout())) { LOG.info("Determined " + i + " as the TaskTracker's own IP address"); return i; } } break; case FAST_CONNECT: case SLOW_CONNECT: boolean correct = tryToConnect(i, jobManagerAddress, strategy.getTimeout()); if (correct) { LOG.info("Determined " + i + " as the TaskTracker's own IP address"); return i; } break; default: throw new RuntimeException("Unkown address detection strategy: " + strategy); } } } // state control switch (strategy) { case ADDRESS: strategy = AddressDetectionState.FAST_CONNECT; break; case FAST_CONNECT: strategy = AddressDetectionState.SLOW_CONNECT; break; case SLOW_CONNECT: throw new RuntimeException("The TaskManager is unable to connect to the JobManager (Address: '" + jobManagerAddress + "')."); } if (LOG.isDebugEnabled()) { LOG.debug("Defaulting to detection strategy {}", strategy); } } }
From source file:org.sipfoundry.sipxbridge.symmitron.DataShuffler.java
/** * Send method to send a packet received from a datagram channel to all the active legs of a * bridge./*from w w w . j a v a2 s . c om*/ * * <pre> * send(bridge,datagramChannel, addressWherePacketCameFrom) : * for each sym in bridge do : * if sym.receiver.datagramChannel == datagramChannel && sym.isAutoLearn * sym.receiver.farEnd = addressWherePacketCameFrom * else if sym.transmitter.state == RUNNING : * sym.transmitter.send(byteBuffer) * </pre> * * @param bridge -- the bridge to forward through. * @param datagramChannel -- datagramChannel on which packet was received. * @param remoteAddress -- remote address to send to. * @throws UnknownHostException -- if there was a problem with the specified remote address. */ public static void send(Bridge bridge, DatagramChannel datagramChannel, InetSocketAddress remoteAddress, long stamp, boolean selfRouted) throws UnknownHostException { try { if (logger.isTraceEnabled()) { logger.trace("DataShuffler.send(): BridgeSize = " + bridge.sessions.size()); } /* xx-5907 sipxrelay needs to guard against stray media streams. */ Sym receivedOn = bridge.getReceiverSym(datagramChannel); if (logger.isTraceEnabled()) { logger.trace("DataShuffler : received packet on symId " + receivedOn.getId()); } if (!selfRouted && receivedOn == null) { logger.error("Could not find bridge on which packet was received. Dropping packet"); return; } if (remoteAddress == null) { logger.warn("remoteAddress is null cannot send. Dropping packet."); return; } if (SymmitronServer.filterStrayPackets) { if (!selfRouted && receivedOn.getTransmitter() != null && receivedOn.getTransmitter().getAutoDiscoveryFlag() == AutoDiscoveryFlag.NO_AUTO_DISCOVERY && receivedOn.getTransmitter().getInetAddress() != null && (!receivedOn.getTransmitter().getInetAddress().equals(remoteAddress.getAddress()) || receivedOn.getTransmitter().getPort() != remoteAddress.getPort())) { if (logger.isTraceEnabled()) { logger.trace(String.format( "Discarding packet - remote endpoint does not match transmitter endpoint %s %s %d %d ", receivedOn.getTransmitter().getInetAddress(), remoteAddress.getAddress(), receivedOn.getTransmitter().getPort(), remoteAddress.getPort())); } receivedOn.recordStrayPacket(remoteAddress.getAddress().getHostAddress()); return; } else if (!selfRouted && receivedOn.getTransmitter() != null && receivedOn.getTransmitter().getAutoDiscoveryFlag() == AutoDiscoveryFlag.PORT_ONLY && receivedOn.getTransmitter().getInetAddress() != null && !receivedOn.getTransmitter().getInetAddress().equals(remoteAddress.getAddress())) { if (logger.isTraceEnabled()) { logger.trace(String.format( "Discarding packet - remote endpoint does not match transmitter endpoint %s %s ", receivedOn.getTransmitter().getInetAddress(), remoteAddress.getAddress())); } receivedOn.recordStrayPacket(remoteAddress.getAddress().getHostAddress()); return; } else if (logger.isTraceEnabled() && receivedOn != null && receivedOn.getTransmitter() != null) { if (logger.isTraceEnabled()) { logger.trace("receivedOn : " + receivedOn.getTransmitter().getInetAddress()); } } else if (logger.isTraceEnabled()) { logger.trace("receivedOn : transmitter == null "); } } for (Sym sym : bridge.sessions) { if (sym.getReceiver() != null && datagramChannel == sym.getReceiver().getDatagramChannel()) { if (logger.isTraceEnabled() && remoteAddress != null) { logger.trace("remoteIpAddressAndPort : " + remoteAddress.getAddress().getHostAddress() + ":" + remoteAddress.getPort()); } sym.lastPacketTime = System.currentTimeMillis(); sym.packetsReceived++; bridge.setLastPacketTime(sym.lastPacketTime); /* * Set the remote port of the transmitter side of the connection. This allows * for NAT reboots ( port can change while in progress. This is not relevant * for the LAN side. */ if (sym.getTransmitter() != null) { AutoDiscoveryFlag autoDiscoveryFlag = sym.getTransmitter().getAutoDiscoveryFlag(); if (autoDiscoveryFlag != AutoDiscoveryFlag.NO_AUTO_DISCOVERY) { if (remoteAddress != null) { // This packet was self routed. if (selfRouted) { if (sym.getTransmitter().getIpAddress() != null) { continue; } else { String remoteHostAddress = remoteAddress.getAddress().getHostAddress(); int remotePort = remoteAddress.getPort(); /* This search is done just once on the first auto address discovery for a self * routed packet. Hence the loop is not too alarming subsequently, you dont ever have to look again. * However, there is probably a better way to do this. */ for (Sym tsym : SymmitronServer.getSyms()) { if (tsym.getTransmitter() != null && tsym.getTransmitter().getIpAddress() != null && tsym.getTransmitter().getIpAddress() .equals(remoteHostAddress) && tsym.getTransmitter().getPort() == remotePort) { logger.debug("linking syms for self routed packet "); sym.getTransmitter().setIpAddressAndPort( tsym.getReceiver().getIpAddress(), tsym.getReceiver().getPort()); break; } } if (logger.isTraceEnabled()) { for (Bridge br : SymmitronServer.getBridges()) { logger.trace(br.toString()); } } } } else { if (autoDiscoveryFlag == AutoDiscoveryFlag.IP_ADDRESS_AND_PORT) { sym.getTransmitter().setIpAddressAndPort( remoteAddress.getAddress().getHostAddress(), remoteAddress.getPort()); } else if (autoDiscoveryFlag == AutoDiscoveryFlag.PORT_ONLY) { // Only update the remote port when the IP address matches. OR if the address is not yet set. sym.getTransmitter().setPort(remoteAddress.getPort()); } } } } } continue; } SymTransmitterEndpoint writeChannel = sym.getTransmitter(); if (writeChannel == null) { continue; } try { /* * No need for header rewrite. Just duplicate, flip and push out. Important: * We cannot do this outside the loop. See XECS-2425. */ if (!writeChannel.isOnHold()) { if (!sym.isVisited(stamp)) { sym.setVisited(stamp); ByteBuffer bufferToSend = readBuffer.duplicate(); bufferToSend.flip(); writeChannel.send((ByteBuffer) bufferToSend, stamp); bridge.packetsSent++; writeChannel.packetsSent++; } else { if (logger.isTraceEnabled()) { logger.trace("sym " + sym + " Routing Loop detected!"); } } } else { if (logger.isTraceEnabled()) { logger.trace("WriteChannel on hold." + writeChannel.getIpAddress() + ":" + writeChannel.getPort() + " Not forwarding"); } } } catch (Exception ex) { logger.error("Unexpected error shuffling bytes", ex); SymmitronServer.printBridges(); } } } finally { } }