Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * JBoss, Home of Professional Open Source.
   * Copyright 2012, Red Hat, Inc., and individual contributors
   * as indicated by the @author tags. See the copyright.txt file in the
   * distribution for a full listing of individual contributors.
   *
   * This is free software; you can redistribute it and/or modify it
   * under the terms of the GNU Lesser General Public License as
   * published by the Free Software Foundation; either version 2.1 of
  * the License, or (at your option) any later version.
  *
  * This software is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with this software; if not, write to the Free
  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
  */
 
 package org.jboss.as.host.controller;
 
 import java.net.URI;
 import java.util.List;
 
 
A connection to a remote domain controller. Once successfully connected this ManagementClientChannelStrategy implementation will try to reconnect with a remote host-controller.

Author(s):
Emanuel Muckenhuber
 
 
     private static final long INTERVAL;
     private static final long TIMEOUT;
 
     static {
         long interval = -1;
         try {
             interval = Long.parseLong(WildFlySecurityManager.getPropertyPrivileged("jboss.as.domain.ping.interval""15000"));
         } catch (Exception e) {
             // TODO log
         } finally {
              = interval > 0 ? interval : 15000;
         }
         long timeout = -1;
         try {
             timeout = Long.parseLong(WildFlySecurityManager.getPropertyPrivileged("jboss.as.domain.ping.timeout""30000"));
         } catch (Exception e) {
             // TODO log
         } finally {
              = timeout > 0 ? timeout : 30000;
         }
     }
     private final String localHostName;
    private final String username;
    private final SecurityRealm realm;
    private final ModelNode localHostInfo;
    private final ExecutorService executorService;
    private final List<DiscoveryOptiondiscoveryOptions;
    private final RunningMode runningMode;
    private URI uri;
    RemoteDomainConnection(final String localHostNamefinal ModelNode localHostInfo,
                           final ProtocolChannelClient.Configuration configurationfinal SecurityRealm realm,
                           final String usernamefinal List<DiscoveryOptiondiscoveryOptions,
                           final ExecutorService executorService,
                           final ScheduledExecutorService scheduledExecutorService,
                           final HostRegistrationCallback callback,
                           final RunningMode runningMode) {
        this. = callback;
        this. = localHostName;
        this. = localHostInfo;
        this. = configuration;
        this. = username;
        this. = realm;
        this. = discoveryOptions;
        this. = executorService;
        this. = new ManagementChannelHandler(thisexecutorService);
        this. = scheduledExecutorService;
        this. = runningMode;
        this. = ProtocolConnectionManager.create(new InitialConnectTask());
    }

    
Try to connect to the remote host.

    protected void connect() throws IOException {
        // Connect to the remote HC
        .connect();
    }

    
The channel handler.

Returns:
the channel handler
        return ;
    }
    @Override
    public Channel getChannel() throws IOException {
        return awaitChannel();
    }

    
Set the configuration uri.

Parameters:
uri the uri
    protected void setUri(URI uri) {
        this. = uri;
    }
    @Override
    public void close() throws IOException {
        try {
            if(prepareClose() && isConnected()) {
                try {
                    .executeRequest(new UnregisterModelControllerRequest(), null).getResult().await();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        } finally {
            try {
                super.close();
            } finally {
                .shutdown();
            }
        }
    }
    protected boolean isConnected() {
        return super.isConnected();
    }

    
Connect and register at the remote domain controller.

Returns:
connection the established connection
Throws:
java.io.IOException
    protected Connection openConnection() throws IOException {
        // Perhaps this can just be done once?
        CallbackHandler callbackHandler = null;
        SSLContext sslContext = null;
        if ( != null) {
            sslContext = .getSSLContext();
            CallbackHandlerFactory handlerFactory = .getSecretCallbackHandlerFactory();
            if (handlerFactory != null) {
                String username = this. != null ? this. : ;
                callbackHandler = handlerFactory.getCallbackHandler(username);
            }
        }
        final ProtocolConnectionConfiguration config = ProtocolConnectionConfiguration.copy();
        config.setCallbackHandler(callbackHandler);
        config.setSslContext(sslContext);
        config.setUri();
        // Connect
        return ProtocolConnectionUtils.connectSync(config);
    }
    @Override
    public void connectionOpened(final Connection connectionthrows IOException {
        final Channel channel = openChannel(connection.getOptionMap());
        if(setChannel(channel)) {
            channel.receiveMessage(.getReceiver());
            channel.addCloseHandler();
            try {
                if ( == .) {
                    // Fetch the domain configuration
                    .executeRequest(new FetchDomainConfigurationRequest(), null).getResult().get();
                } else {
                    // Start the registration process
                    .executeRequest(new RegisterHostControllerRequest(), null).getResult().get();
                }
            } catch (Exception e) {
                if(e.getCause() instanceof IOException) {
                    throw (IOExceptione.getCause();
                }
                throw new IOException(e);
            }
            // Registered
            registered();
        } else {
            channel.closeAsync();
        }
    }
    protected Future<Connectionreconnect() {
        // Reset the connection state
        return .submit(new Callable<Connection>() {
            @Override
            public Connection call() throws Exception {
                final ReconnectPolicy reconnectPolicy = .;
                int reconnectionCount = 0;
                for(;;) {
                    // Try to connect to the remote host controller by looping through all
                    // discovery options
                    String host = null;
                    int port = -1;
                    reconnectPolicy.wait(reconnectionCount);
                    for (DiscoveryOption discoveryOption : ) {
                        try {
                            discoveryOption.discover();
                            host = discoveryOption.getRemoteDomainControllerHost();
                            port = discoveryOption.getRemoteDomainControllerPort();
                            setUri(new URI("remote://" + NetworkUtils.formatPossibleIpv6Address(host) + ":" + port));
                            ..debugf("trying to reconnect to remote host-controller");
                            return .connect();
                        } catch (IOException e) {
                            ..debugf(e"failed to reconnect to the remote host-controller");
                        } catch (IllegalStateException e) {
                            ..debugf(e"failed to reconnect to the remote host-controller");
                        }
                    }
                    reconnectionCount++;
                }
            }
        });
    }

    
Resolve the subsystem versions.

Parameters:
extensions the extensions
Returns:
the resolved subsystem versions
        return .resolveSubsystemVersions(extensions);
    }

    
Apply the remote read domain model result.

Parameters:
result the domain model result
Returns:
whether it was applied successfully or not
    boolean applyDomainModel(ModelNode result) {
        if(! result.hasDefined(.)) {
            return false;
        }
        final List<ModelNodebootOperationsresult.get(.).asList();
        return .applyDomainModel(bootOperations);
    }
    void registered() {
//        schedule(new PingTask());
    }
    private void schedule(PingTask task) {
    }
    interface HostRegistrationCallback {

        
Get the versions for all registered subsystems.

Parameters:
extensions the extension list
Returns:
the subsystem versions
        ModelNode resolveSubsystemVersions(ModelNode extensions);

        
Apply the remote domain model.

Parameters:
result the read-domain-model operation result
Returns:
true if the model was applied successfully, false otherwise
        boolean applyDomainModel(List<ModelNoderesult);

        
Event that the registration was completed.

Parameters:
handler the handler
        void registrationComplete(ManagementChannelHandler handler);
    }

    
The host-controller registration request.
     private abstract class HostControllerConnectRequest extends AbstractManagementRequest<VoidVoid> {
         abstract boolean isRegisterOnComplete();
         @Override
         protected void sendRequest(final ActiveOperation.ResultHandler<VoidresultHandlerfinal ManagementRequestContext<Voidcontextfinal FlushableDataOutput outputthrows IOException {
             output.write(.);
             output.writeUTF();
             ModelNode hostInfo = .clone();
             hostInfo.writeExternal(output);
         }
         @Override
         public void handleRequest(final DataInput inputfinal ActiveOperation.ResultHandler<VoidresultHandlerfinal ManagementRequestContext<Voidcontextthrows IOException {
             byte param = input.readByte();
             // If it failed
             if(param != .) {
                 final byte errorCode = input.readByte();
                 final String message =  input.readUTF();
                 resultHandler.failed(new SlaveRegistrationException(SlaveRegistrationException.ErrorCode.parseCode(errorCode), message));
                 return;
             }
             final ModelNode extensions = new ModelNode();
             extensions.readExternal(input);
             // Enable the send subject
             if (context.getRequestHeader().getVersion() != 1) {
             }
             context.executeAsync(new ManagementRequestContext.AsyncTask<Void>() {
                 @Override
                 public void execute(ManagementRequestContext<VoidvoidManagementRequestContextthrows Exception {
                     //
                     final ModelNode subsystems = resolveSubsystemVersions(extensions);
                     .executeRequest(context.getOperationId(),
                             new RegisterSubsystemsRequest(subsystemsisRegisterOnComplete()));
                 }
             });
         }
     }

    
The host-controller registration request.
        @Override
        public byte getOperationType() {
        }
        @Override
        boolean isRegisterOnComplete() {
            return true;
        }
    }

    
The host-controller fetch domain config request.
        @Override
        public byte getOperationType() {
        }
        @Override
        boolean isRegisterOnComplete() {
            return false;
        }
    }
     private class RegisterSubsystemsRequest extends AbstractManagementRequest<VoidVoid> {
         private final ModelNode subsystems;
         private final boolean registerOnCompletion;
         private RegisterSubsystemsRequest(ModelNode subsystemsboolean registerOnCompletion) {
             this. = subsystems;
             this. = registerOnCompletion;
         }
         @Override
         public byte getOperationType() {
             return .;
         }
         @Override
         protected void sendRequest(ActiveOperation.ResultHandler<VoidregistrationResultResultHandlerManagementRequestContext<VoidvoidManagementRequestContextFlushableDataOutput outputthrows IOException {
             output.writeByte(.);
             .writeExternal(output);
         }
         @Override
         public void handleRequest(final DataInput inputfinal ActiveOperation.ResultHandler<VoidresultHandlerfinal ManagementRequestContext<Voidcontextthrows IOException {
             byte param = input.readByte();
             // If it failed
             if(param != .) {
                 final byte errorCode = input.readByte();
                 final String message =  input.readUTF();
                 resultHandler.failed(new SlaveRegistrationException(SlaveRegistrationException.ErrorCode.parseCode(errorCode), message));
                 return;
             }
             final ModelNode domainModel = new ModelNode();
             domainModel.readExternal(input);
             context.executeAsync(new ManagementRequestContext.AsyncTask<Void>() {
                 @Override
                 public void execute(ManagementRequestContext<VoidvoidManagementRequestContextthrows Exception {
                     // Apply the domain model
                     final boolean success = applyDomainModel(domainModel);
                     if () {
                         if(success) {
                             .executeRequest(context.getOperationId(), new CompleteRegistrationRequest(.));
                         } else {
                             .executeRequest(context.getOperationId(), new CompleteRegistrationRequest(.));
                             resultHandler.failed(new SlaveRegistrationException(..""));
                         }
                     } else {
                         if (success) {
                             throw new UnsupportedOperationException("TODO");
                         } else {
                             resultHandler.failed(new SlaveRegistrationException(..""));
                         }
                     }
                 }
             });
         }
     }
     private class CompleteRegistrationRequest extends AbstractManagementRequest<VoidVoid> {
         private final byte outcome;
         private final String message = "yay!"//
         private CompleteRegistrationRequest(final byte outcome) {
             this. = outcome;
         }
         @Override
         public byte getOperationType() {
         }
         @Override
         protected void sendRequest(final ActiveOperation.ResultHandler<VoidresultHandlerfinal ManagementRequestContext<Voidcontextfinal FlushableDataOutput outputthrows IOException {
             output.writeByte();
             output.writeUTF();
         }
         @Override
         public void handleRequest(DataInput inputActiveOperation.ResultHandler<VoidresultHandlerManagementRequestContext<VoidvoidManagementRequestContextthrows IOException {
             final byte param = input.readByte();
             // If it failed
             if(param != .) {
                 final byte errorCode = input.readByte();
                 final String message =  input.readUTF();
                 resultHandler.failed(new SlaveRegistrationException(SlaveRegistrationException.ErrorCode.parseCode(errorCode), message));
                 return;
             }
             resultHandler.done(null);
         }
     }
        @Override
        public byte getOperationType() {
        }
        @Override
        protected void sendRequest(ActiveOperation.ResultHandler<VoidresultHandlerManagementRequestContext<VoidvoidManagementRequestContextFlushableDataOutput outputthrows IOException {
            output.write(.);
            output.writeUTF();
        }
        @Override
        public void handleRequest(DataInput inputActiveOperation.ResultHandler<VoidresultHandlerManagementRequestContext<VoidvoidManagementRequestContextthrows IOException {
            resultHandler.done(null);
        }
    }
    private class PingTask implements Runnable {
        private Long remoteInstanceID;
        @Override
        public void run() {
            if (isConnected()) {
                boolean fail = false;
                AsyncFuture<Longfuture = null;
                try {
                    if (System.currentTimeMillis() - .getLastMessageReceivedTime() > ) {
                        future = .executeRequest(.null).getResult();
                        Long id = future.get(.);
                        if ( != null && !.equals(id)) {
                            ..masterHostControllerChanged();
                            fail = true;
                        } else {
                             = id;
                        }
                    }
                } catch (IOException e) {
                    ..debug("Caught exception sending ping request"e);
                } catch (InterruptedException e) {
                    safeCancel(future);
                    Thread.currentThread().interrupt();
                } catch (ExecutionException e) {
                    ..debug("Caught exception sending ping request"e);
                } catch (TimeoutException e) {
                    fail = true;
                    safeCancel(future);
                } finally {
                    if (fail) {
                        Channel channel = null;
                        try {
                            channel = .getChannel();
                        } catch (IOException e) {
                            // ignore; shouldn't happen as the channel is already established if this task is running
                        }
                        StreamUtils.safeClose(channel);
                    } else {
                        schedule(this);
                    }
                }
            }
        }
        void safeCancel(Future<?> future) {
            if (future != null) {
                future.cancel(true);
            }
        }
    }
        @Override
        public Connection connect() throws IOException {
            return openConnection();
        }
        @Override
            return RemoteDomainConnection.this;
        }
        @Override
            return new ReconnectTaskWrapper(reconnect());
        }
        @Override
        public void shutdown() {
            //
        }
    }
        private final Future<ConnectionconnectionFuture;
        ReconnectTaskWrapper(Future<ConnectionconnectionFuture) {
            this. = connectionFuture;
        }
        @Override
        public Connection connect() throws IOException {
            final Connection connection = openConnection();
            return connection;
        }
        @Override
            return RemoteDomainConnection.this;
        }
        @Override
            return new ReconnectTaskWrapper(reconnect());
        }
        @Override
        public void shutdown() {
            .cancel(true);
        }
    }
New to GrepCode? Check out our FAQ X