001    /**
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements.  See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache License, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License.  You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    package org.apache.activemq.network;
018    
019    import java.io.IOException;
020    import java.net.URI;
021    import java.net.URISyntaxException;
022    import java.util.Iterator;
023    import java.util.Map;
024    import java.util.concurrent.ConcurrentHashMap;
025    import java.util.concurrent.ConcurrentMap;
026    
027    import javax.management.ObjectName;
028    
029    import org.apache.activemq.broker.BrokerService;
030    import org.apache.activemq.broker.SslContext;
031    import org.apache.activemq.command.DiscoveryEvent;
032    import org.apache.activemq.transport.Transport;
033    import org.apache.activemq.transport.TransportFactory;
034    import org.apache.activemq.transport.discovery.DiscoveryAgent;
035    import org.apache.activemq.transport.discovery.DiscoveryAgentFactory;
036    import org.apache.activemq.transport.discovery.DiscoveryListener;
037    import org.apache.activemq.util.IntrospectionSupport;
038    import org.apache.activemq.util.ServiceStopper;
039    import org.apache.activemq.util.ServiceSupport;
040    import org.apache.activemq.util.URISupport;
041    import org.slf4j.Logger;
042    import org.slf4j.LoggerFactory;
043    
044    /**
045     * A network connector which uses a discovery agent to detect the remote brokers
046     * available and setup a connection to each available remote broker
047     *
048     * @org.apache.xbean.XBean element="networkConnector"
049     *
050     */
051    public class DiscoveryNetworkConnector extends NetworkConnector implements DiscoveryListener {
052        private static final Logger LOG = LoggerFactory.getLogger(DiscoveryNetworkConnector.class);
053    
054        private DiscoveryAgent discoveryAgent;
055        private Map<String, String> parameters;
056        private final ConcurrentMap<URI, DiscoveryEvent> activeEvents = new ConcurrentHashMap<URI, DiscoveryEvent>();
057        public DiscoveryNetworkConnector() {
058        }
059    
060        public DiscoveryNetworkConnector(URI discoveryURI) throws IOException {
061            setUri(discoveryURI);
062        }
063    
064        public void setUri(URI discoveryURI) throws IOException {
065            setDiscoveryAgent(DiscoveryAgentFactory.createDiscoveryAgent(discoveryURI));
066            try {
067                parameters = URISupport.parseParameters(discoveryURI);
068                // allow discovery agent to grab it's parameters
069                IntrospectionSupport.setProperties(getDiscoveryAgent(), parameters);
070            } catch (URISyntaxException e) {
071                LOG.warn("failed to parse query parameters from discoveryURI: " + discoveryURI, e);
072            }
073        }
074    
075        @Override
076        public void onServiceAdd(DiscoveryEvent event) {
077            // Ignore events once we start stopping.
078            if (serviceSupport.isStopped() || serviceSupport.isStopping()) {
079                return;
080            }
081            String url = event.getServiceName();
082            if (url != null) {
083                URI uri;
084                try {
085                    uri = new URI(url);
086                } catch (URISyntaxException e) {
087                    LOG.warn("Could not connect to remote URI: " + url + " due to bad URI syntax: " + e, e);
088                    return;
089                }
090    
091                if (localURI.equals(uri)) {
092                    if (LOG.isDebugEnabled()) {
093                        LOG.debug("not connecting loopback: " + uri);
094                    }
095                    return;
096                }
097    
098                if (connectionFilter != null && !connectionFilter.connectTo(uri)) {
099                    if (LOG.isDebugEnabled()) {
100                        LOG.debug("connectionFilter disallows connection to: " + uri);
101                    }
102                    return;
103                }
104    
105                // Should we try to connect to that URI?
106                if (activeEvents.putIfAbsent(uri, event) != null) {
107                    if (LOG.isDebugEnabled()) {
108                        LOG.debug("Discovery agent generated a duplicate onServiceAdd event for: " + uri);
109                    }
110                    return;
111                }
112    
113                URI connectUri = uri;
114                try {
115                    connectUri = URISupport.applyParameters(connectUri, parameters, DISCOVERED_OPTION_PREFIX);
116                } catch (URISyntaxException e) {
117                    LOG.warn("could not apply query parameters: " + parameters + " to: " + connectUri, e);
118                }
119    
120                if (LOG.isInfoEnabled()) {
121                    LOG.info("Establishing network connection from " + localURI + " to " + connectUri);
122                }
123    
124                Transport remoteTransport;
125                Transport localTransport;
126                try {
127                    // Allows the transport to access the broker's ssl configuration.
128                    SslContext.setCurrentSslContext(getBrokerService().getSslContext());
129                    try {
130                        remoteTransport = TransportFactory.connect(connectUri);
131                    } catch (Exception e) {
132                        LOG.warn("Could not connect to remote URI: " + connectUri + ": " + e.getMessage());
133                        if (LOG.isDebugEnabled()) {
134                            LOG.debug("Connection failure exception: " + e, e);
135                        }
136                        activeEvents.remove(uri);
137                        return;
138                    }
139                    try {
140                        localTransport = createLocalTransport();
141                    } catch (Exception e) {
142                        ServiceSupport.dispose(remoteTransport);
143                        LOG.warn("Could not connect to local URI: " + localURI + ": " + e.getMessage());
144                        if (LOG.isDebugEnabled()) {
145                            LOG.debug("Connection failure exception: " + e, e);
146                        }
147                        activeEvents.remove(uri);
148                        return;
149                    }
150                } finally {
151                    SslContext.setCurrentSslContext(null);
152                }
153                NetworkBridge bridge = createBridge(localTransport, remoteTransport, event);
154                try {
155                    synchronized (bridges) {
156                        bridges.put(uri, bridge);
157                    }
158                    bridge.start();
159                } catch (Exception e) {
160                    ServiceSupport.dispose(localTransport);
161                    ServiceSupport.dispose(remoteTransport);
162                    LOG.warn("Could not start network bridge between: " + localURI + " and: " + uri + " due to: " + e);
163                    if (LOG.isDebugEnabled()) {
164                        LOG.debug("Start failure exception: " + e, e);
165                    }
166                    try {
167                        // Will remove bridge and active event.
168                        discoveryAgent.serviceFailed(event);
169                    } catch (IOException e1) {
170                        if (LOG.isDebugEnabled()) {
171                            LOG.debug("Discovery agent failure while handling failure event: " + e1.getMessage(), e1);
172                        }
173                    }
174                }
175            }
176        }
177    
178        @Override
179        public void onServiceRemove(DiscoveryEvent event) {
180            String url = event.getServiceName();
181            if (url != null) {
182                URI uri;
183                try {
184                    uri = new URI(url);
185                } catch (URISyntaxException e) {
186                    LOG.warn("Could not connect to remote URI: " + url + " due to bad URI syntax: " + e, e);
187                    return;
188                }
189    
190                // Only remove bridge if this is the active discovery event for the URL.
191                if (activeEvents.remove(uri, event)) {
192                    synchronized (bridges) {
193                        bridges.remove(uri);
194                    }
195                }
196            }
197        }
198    
199        public DiscoveryAgent getDiscoveryAgent() {
200            return discoveryAgent;
201        }
202    
203        public void setDiscoveryAgent(DiscoveryAgent discoveryAgent) {
204            this.discoveryAgent = discoveryAgent;
205            if (discoveryAgent != null) {
206                this.discoveryAgent.setDiscoveryListener(this);
207            }
208        }
209    
210        @Override
211        protected void handleStart() throws Exception {
212            if (discoveryAgent == null) {
213                throw new IllegalStateException("You must configure the 'discoveryAgent' property");
214            }
215            this.discoveryAgent.start();
216            super.handleStart();
217        }
218    
219        @Override
220        protected void handleStop(ServiceStopper stopper) throws Exception {
221            for (Iterator<NetworkBridge> i = bridges.values().iterator(); i.hasNext();) {
222                NetworkBridge bridge = i.next();
223                try {
224                    bridge.stop();
225                } catch (Exception e) {
226                    stopper.onException(this, e);
227                }
228            }
229            bridges.clear();
230            activeEvents.clear();
231            try {
232                this.discoveryAgent.stop();
233            } catch (Exception e) {
234                stopper.onException(this, e);
235            }
236    
237            super.handleStop(stopper);
238        }
239    
240        protected NetworkBridge createBridge(Transport localTransport, Transport remoteTransport, final DiscoveryEvent event) {
241            class DiscoverNetworkBridgeListener extends MBeanNetworkListener {
242    
243                public DiscoverNetworkBridgeListener(BrokerService brokerService, ObjectName connectorName) {
244                    super(brokerService, connectorName);
245                }
246    
247                @Override
248                public void bridgeFailed() {
249                    if (!serviceSupport.isStopped()) {
250                        try {
251                            discoveryAgent.serviceFailed(event);
252                        } catch (IOException e) {
253                        }
254                    }
255    
256                }
257            }
258            NetworkBridgeListener listener = new DiscoverNetworkBridgeListener(getBrokerService(), getObjectName());
259    
260            DemandForwardingBridge result = NetworkBridgeFactory.createBridge(this, localTransport, remoteTransport, listener);
261            result.setBrokerService(getBrokerService());
262            return configureBridge(result);
263        }
264    
265        @Override
266        public String toString() {
267            return "DiscoveryNetworkConnector:" + getName() + ":" + getBrokerService();
268        }
269    }