/** * Connects this channel to a group and gets a state from a specified state provider. * * <p>This method invokes {@code connect()} and then {@code getState}. * * <p>If the FLUSH protocol is in the channel's stack definition, only one flush round is executed * for both connecting and fetching the state rather than two flushes if we invoke {@code connect} * and {@code getState} in succession. * * <p>If the channel is already connected, an error message will be printed to the error log. If * the channel is closed a ChannelClosed exception will be thrown. * * @param cluster_name The cluster name to connect to. Cannot be null. * @param target The state provider. If null, the state will be fetched from the coordinator, * unless this channel is the coordinator. * @param timeout The timeout for the state transfer. * @exception Exception The protocol stack cannot be started, or the JOIN failed * @exception IllegalStateException The channel is closed or disconnected * @exception StateTransferException State transfer was not successful */ public synchronized void connect( String cluster_name, Address target, long timeout, boolean useFlushIfPresent) throws Exception { if (!_preConnect(cluster_name)) return; if (cluster_name == null) { // only connect if we are not a unicast channel state = State.CONNECTED; return; } boolean canFetchState = false; try { Event connect_event = useFlushIfPresent ? new Event(Event.CONNECT_WITH_STATE_TRANSFER_USE_FLUSH, cluster_name) : new Event(Event.CONNECT_WITH_STATE_TRANSFER, cluster_name); _connect(connect_event); state = State.CONNECTED; notifyChannelConnected(this); canFetchState = getView() != null && getView().size() > 1; // if I am not the only member in cluster then if (canFetchState) getState(target, timeout, false); // fetch state from target } finally { // stopFlush if we fetched the state or failed to connect... if ((flushSupported() && useFlushIfPresent) && (canFetchState || state != State.CONNECTED)) stopFlush(); } }
/** * Connects this member to the cluster using the given <code>loadFactor</code>. The <code> * loadFactor</code> defines the (approximate) relative load that this member will receive. * * <p>A good default value is 100, which will give this member 100 nodes on the distributed hash * ring. Giving all members (proportionally) lower values will result in a less evenly distributed * hash. * * @param loadFactor The load factor for this node. * @throws ConnectionFailedException when an error occurs while connecting */ public synchronized void connect(int loadFactor) throws ConnectionFailedException { this.currentLoadFactor = loadFactor; Assert.isTrue(loadFactor >= 0, "Load Factor must be a positive integer value."); Assert.isTrue( channel.getReceiver() == null || channel.getReceiver() == messageReceiver, "The given channel already has a receiver configured. " + "Has the channel been reused with other Connectors?"); try { channel.setReceiver(messageReceiver); if (channel.isConnected() && !clusterName.equals(channel.getClusterName())) { throw new AxonConfigurationException( "The Channel that has been configured with this JGroupsConnector " + "is already connected to another cluster."); } else if (channel.isConnected()) { // we need to fetch state now that we have attached our MessageReceiver channel.getState(null, 10000); } else { // we need to connect. This will automatically fetch state as well. channel.connect(clusterName, null, 10000); } updateMembership(); } catch (Exception e) { joinedCondition.markJoined(false); channel.disconnect(); throw new ConnectionFailedException("Failed to connect to JGroupsConnectorFactoryBean", e); } }
/** Execute when new member join or leave Group */ public void viewAccepted(View v) { memberSize = v.size(); if (mainFrame != null) setTitle(); members.clear(); members.addAll(v.getMembers()); if (v instanceof MergeView) { System.out.println("** " + v); // This is a simple merge function, which fetches the state from the coordinator // on a merge and overwrites all of its own state if (useState && !members.isEmpty()) { Address coord = members.get(0); Address local_addr = channel.getAddress(); if (local_addr != null && !local_addr.equals(coord)) { try { // make a copy of our state first Map<Point, Color> copy = null; if (send_own_state_on_merge) { synchronized (drawPanel.state) { copy = new LinkedHashMap<Point, Color>(drawPanel.state); } } System.out.println("fetching state from " + coord); channel.getState(coord, 5000); if (copy != null) sendOwnState(copy); // multicast my own state so everybody else has it too } catch (Exception e) { e.printStackTrace(); } } } } else System.out.println("** View=" + v); }
/** * 启动连接。 * * @throws Exception */ private void start() throws Exception { channle = new JChannel(); channle.setReceiver(this); channle.connect("ChatCluster"); channle.getState(null, 10000); eventloop(); channle.close(); }
/** Retrieves state from the target member. See {@link #getState(Address,long)} for details. */ public void getState(Address target, long timeout, boolean useFlushIfPresent) throws Exception { Callable<Boolean> flusher = new Callable<Boolean>() { public Boolean call() throws Exception { return Util.startFlush(JChannel.this); } }; getState(target, timeout, useFlushIfPresent ? flusher : null); }
/** Tests issue #2 in http://jira.jboss.com/jira/browse/JGRP-335 */ public void testStateTransferFollowedByUnicast() throws Exception { JChannel a = null; JChannel b = null; try { a = createChannel(true, 2, "A"); a.setReceiver(new SimpleReplier(a, true)); a.connect("testStateTransferFollowedByUnicast"); Address target = a.getAddress(); Message unicast_msg = new Message(target); b = createChannel(a, "B"); b.setReceiver(new SimpleReplier(b, false)); b.connect("testStateTransferFollowedByUnicast"); System.out.println("\n** Getting the state **"); b.getState(null, 10000); // now send unicast, this might block as described in the case b.send(unicast_msg); } finally { Util.close(b, a); } }
@Override protected void executeRuntimeStep(OperationContext context, ModelNode operation) throws OperationFailedException { // get the channel name and channel attribute PathAddress pathAddress = PathAddress.pathAddress(operation.require(OP_ADDR)); String channelName = pathAddress.getElement(pathAddress.size() - 1).getValue(); String attrName = operation.require(NAME).asString(); ChannelMetrics metric = ChannelMetrics.getStat(attrName); // lookup the channel ServiceName channelServiceName = ChannelInstanceResource.CHANNEL_PARENT.append(channelName); ServiceController<?> controller = context.getServiceRegistry(false).getService(channelServiceName); // check that the service has been installed and started boolean started = controller != null && controller.getValue() != null; ModelNode result = new ModelNode(); if (metric == null) { context.getFailureDescription().set(JGroupsMessages.MESSAGES.unknownMetric(attrName)); } else if (!started) { // when the cache service is not available, return a null result } else { JChannel channel = (JChannel) controller.getValue(); switch (metric) { case ADDRESS: result.set(channel.getAddressAsString()); break; case ADDRESS_AS_UUID: result.set(channel.getAddressAsUUID()); break; case DISCARD_OWN_MESSAGES: result.set(channel.getDiscardOwnMessages()); break; case NUM_TASKS_IN_TIMER: result.set(channel.getNumberOfTasksInTimer()); break; case NUM_TIMER_THREADS: result.set(channel.getTimerThreads()); break; case RECEIVED_BYTES: result.set(channel.getReceivedBytes()); break; case RECEIVED_MESSAGES: result.set(channel.getReceivedMessages()); break; case SENT_BYTES: result.set(channel.getSentBytes()); break; case SENT_MESSAGES: result.set(channel.getSentMessages()); break; case STATE: result.set(channel.getState()); break; case STATS_ENABLED: result.set(channel.statsEnabled()); break; case VERSION: result.set(JChannel.getVersion()); break; case VIEW: result.set(channel.getViewAsString()); break; } context.getResult().set(result); } context.completeStep(OperationContext.ResultHandler.NOOP_RESULT_HANDLER); }
/** Retrieves state from the target member. See {@link #getState(Address,long)} for details. */ public void getState(Address target, long timeout, boolean useFlushIfPresent) throws Exception { Callable<Boolean> flusher = () -> Util.startFlush(JChannel.this); getState(target, timeout, useFlushIfPresent ? flusher : null); }
public void getState(Address target, long timeout) throws Exception { getState(target, timeout, true); }
protected void startServer() { final Session session = Session.getSessionUsingInitiativeYearTerm( ApplicationProperties.getProperty("initiative", "woebegon"), ApplicationProperties.getProperty("year", "2010"), ApplicationProperties.getProperty("term", "Fal")); boolean remote = "true".equalsIgnoreCase(ApplicationProperties.getProperty("remote", "true")); if (session == null) { sLog.error( "Academic session not found, use properties initiative, year, and term to set academic session."); System.exit(0); } else { sLog.info("Session: " + session); } iSessionId = session.getUniqueId(); OnlineSectioningLogger.getInstance().setEnabled(false); if (remote) { try { iChannel = new JChannel( JGroupsUtils.getConfigurator( ApplicationProperty.SolverClusterConfiguration.value())); iChannel.setUpHandler(new MuxUpHandler()); iSolverServer = new DummySolverServer(iChannel); iChannel.connect("UniTime:rpc"); iChannel.getState(null, 0); if (getServer() == null) throw new Exception(session.getLabel() + " is not available"); } catch (Exception e) { sLog.error("Failed to access the solver server: " + e.getMessage(), e); if (iChannel != null && iChannel.isConnected()) iChannel.disconnect(); if (iChannel != null && iChannel.isOpen()) iChannel.close(); System.exit(0); } } else { iServer = new InMemoryServer( new OnlineSectioningServerContext() { @Override public boolean isWaitTillStarted() { return true; } @Override public EmbeddedCacheManager getCacheManager() { return null; } @Override public Long getAcademicSessionId() { return session.getUniqueId(); } @Override public LockService getLockService() { return null; } }); } }