Debian Codegraph @

src/java/org/astrogrid/samp/bridge/Bridge.java

raw
1 package org.astrogrid.samp.bridge;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.net.InetAddress;
6 import java.net.MalformedURLException;
7 import java.net.URL;
8 import java.net.UnknownHostException;
9 import java.util.ArrayList;
10 import java.util.Arrays;
11 import java.util.Iterator;
12 import java.util.List;
13 import java.util.logging.Level;
14 import java.util.logging.Logger;
15 import org.astrogrid.samp.SampUtils;
16 import org.astrogrid.samp.client.ClientProfile;
17 import org.astrogrid.samp.client.HubConnection;
18 import org.astrogrid.samp.client.HubConnector;
19 import org.astrogrid.samp.client.SampException;
20 import org.astrogrid.samp.httpd.UtilServer;
21 import org.astrogrid.samp.xmlrpc.LockInfo;
22 import org.astrogrid.samp.xmlrpc.StandardClientProfile;
23 import org.astrogrid.samp.xmlrpc.XmlRpcKit;
24
25 /**
26 * Runs a bridging service between two or more hubs.
27 * For each client on one hub, a proxy client appears on all other
28 * participating hubs. These proxies can be treated in exactly the
29 * same way as normal clients by other registered clients; any
30 * messages sent to/from them will be marshalled over the bridge
31 * in a transparent way. One application for this is to allow
32 * collaboration between users who each have their own hub running.
33 *
34 * <p>A {@link java.lang.Object#notifyAll notifyAll} call is made on
35 * the Bridge object whenever the number of live hubs connected by
36 * the bridge changes.
37 *
38 * @author Mark Taylor
39 * @since 15 Jul 2009
40 */
41 public class Bridge {
42
43 private final ProxyManager[] proxyManagers_;
44 private static final Logger logger_ =
45 Logger.getLogger( Bridge.class.getName() );
46
47 /**
48 * Constructor.
49 *
50 * @param profiles array of SAMP profile objects, one for each
51 * hub which is to participate in the bridge
52 */
53 public Bridge( ClientProfile[] profiles ) throws IOException {
54 int nhub = profiles.length;
55 proxyManagers_ = new ProxyManager[ nhub ];
56 UtilServer server = UtilServer.getInstance();
57 for ( int ih = 0; ih < nhub; ih++ ) {
58 proxyManagers_[ ih ] = new ProxyManager( profiles[ ih ], server ) {
59 protected void managerConnectionChanged( boolean isConnected ) {
60 super.managerConnectionChanged( isConnected );
61 synchronized ( Bridge.this ) {
62 Bridge.this.notifyAll();
63 }
64 }
65 };
66 }
67 for ( int ih = 0; ih < nhub; ih++ ) {
68 proxyManagers_[ ih ].init( proxyManagers_ );
69 }
70 for ( int ih = 0; ih < nhub; ih++ ) {
71 proxyManagers_[ ih ].getManagerConnector().setAutoconnect( 0 );
72 }
73 }
74
75 /**
76 * Returns the client profiles which define the hubs this bridge links.
77 *
78 * @return profile array, one for each connected hub
79 */
80 public ClientProfile[] getProfiles() {
81 int nhub = proxyManagers_.length;
82 ClientProfile[] profiles = new ClientProfile[ nhub ];
83 for ( int ih = 0; ih < nhub; ih++ ) {
84 profiles[ ih ] = proxyManagers_[ ih ].getProfile();
85 }
86 return profiles;
87 }
88
89 /**
90 * Returns the hub connectors representing the bridge client running
91 * on each linked hub. Note this does not include any proxy clients,
92 * only the one-per-hub manager clients.
93 *
94 * @return array of bridge manager clients, one for each hub
95 * (in corresponding positions to the profiles)
96 */
97 public HubConnector[] getBridgeClients() {
98 int nhub = proxyManagers_.length;
99 HubConnector[] connectors = new HubConnector[ nhub ];
100 for ( int ih = 0; ih < nhub; ih++ ) {
101 connectors[ ih ] = proxyManagers_[ ih ].getManagerConnector();
102 }
103 return connectors;
104 }
105
106 /**
107 * Sets up a URL exporter for one of the hubs. This will attempt to
108 * edit transmitted data contents for use in remote contexts;
109 * the main job is to adjust loopback host references in URLs
110 * (127.0.0.1 or localhost) to become fully qualified domain names
111 * for non-local use. It's not an exact science, but a best effort
112 * is made.
113 *
114 * @param index index of the profile for which to export URLs
115 * @param host the name substitute for loopback host identifiers
116 * on the host on which that profile's hub is running
117 */
118 public void exportUrls( int index, String host ) {
119 proxyManagers_[ index ]
120 .setExporter( new UrlExporter( host, isLocalHost( host ) ) );
121 }
122
123 /**
124 * Starts this bridge running.
125 *
126 * @return true iff all the participating hubs have been contacted
127 * successfully
128 */
129 public boolean start() {
130 HubConnector[] connectors = getBridgeClients();
131 boolean allConnected = true;
132 for ( int ih = 0; ih < connectors.length; ih++ ) {
133 HubConnector connector = connectors[ ih ];
134 connector.setActive( true );
135 allConnected = allConnected && connector.isConnected();
136 }
137 return allConnected;
138 }
139
140 /**
141 * Stops this bridge running.
142 * All associated manager and proxy clients are unregistered.
143 */
144 public void stop() {
145 HubConnector[] connectors = getBridgeClients();
146 for ( int ih = 0; ih < connectors.length; ih++ ) {
147 connectors[ ih ].setActive( false );
148 }
149 }
150
151 /**
152 * Returns the number of hubs currently connected by this bridge.
153 * Only connections which are currently live are counted.
154 *
155 * @return number of live hubs
156 */
157 private int getConnectionCount() {
158 HubConnector[] connectors = getBridgeClients();
159 int nc = 0;
160 for ( int ih = 0; ih < connectors.length; ih++ ) {
161 if ( connectors[ ih ].isConnected() ) {
162 nc++;
163 }
164 }
165 return nc;
166 }
167
168 /**
169 * Indicates whether a given hostname corresponds to the local host.
170 *
171 * @param host hostname to test
172 * @return true if <code>host</code> is known to be the local host
173 */
174 private static boolean isLocalHost( String host ) {
175 if ( host == null ) {
176 return false;
177 }
178 if ( SampUtils.getLocalhost().equals( host ) ) {
179 return true;
180 }
181 try {
182 InetAddress hostAddr = InetAddress.getByName( host );
183 return hostAddr != null
184 && ( hostAddr.isLoopbackAddress() ||
185 hostAddr.equals( InetAddress.getLocalHost() ) );
186 }
187 catch ( UnknownHostException e ) {
188 return false;
189 }
190 }
191
192 /**
193 * Main method. Runs a bridge.
194 */
195 public static void main( String[] args ) throws IOException {
196
197 // Unless specially requested, make sure that the local host
198 // is referred to by something publicly useful, not the loopback
199 // address, which would be no good if there will be communications
200 // to/from an external host.
201 String hostspec = System.getProperty( SampUtils.LOCALHOST_PROP );
202 if ( hostspec == null ) {
203 System.setProperty( SampUtils.LOCALHOST_PROP, "[hostname]" );
204 }
205
206 // Run the application.
207 int status = runMain( args );
208 if ( status != 0 ) {
209 System.exit( status );
210 }
211 }
212
213 /**
214 * Does the work for the main method.
215 * Use -help flag.
216 */
217 public static int runMain( String[] args ) throws IOException {
218 String usage = new StringBuffer()
219 .append( "\n Usage:" )
220 .append( "\n " )
221 .append( Bridge.class.getName() )
222 .append( "\n " )
223 .append( " [-help]" )
224 .append( " [-/+verbose]" )
225 .append( " [-[no]exporturls]" )
226 .append( "\n " )
227 .append( " [-nostandard]" )
228 .append( " [-sampdir <lockfile-dir>]" )
229 .append( " [-sampfile <lockfile>]" )
230 .append( " [-sampurl <lockurl>]" )
231 .append( "\n " )
232 .append( " [-keys <xmlrpc-url> <secret>]" )
233 .append( " [-profile <clientprofile-class>]" )
234 .append( "\n" )
235 .toString();
236 List argList = new ArrayList( Arrays.asList( args ) );
237
238 // Handle administrative flags - best done before other parameters.
239 int verbAdjust = 0;
240 for ( Iterator it = argList.iterator(); it.hasNext(); ) {
241 String arg = (String) it.next();
242 if ( arg.equals( "-v" ) || arg.equals( "-verbose" ) ) {
243 it.remove();
244 verbAdjust--;
245 }
246 else if ( arg.equals( "+v" ) || arg.equals( "+verbose" ) ) {
247 it.remove();
248 verbAdjust++;
249 }
250 else if ( arg.equals( "-h" ) || arg.equals( "-help" )
251 || arg.equals( "--help" ) ) {
252 it.remove();
253 System.out.println( usage );
254 return 0;
255 }
256 }
257
258 // Adjust logging in accordance with verbosity flags.
259 int logLevel = Level.WARNING.intValue() + 100 * verbAdjust;
260 Logger.getLogger( "org.astrogrid.samp" )
261 .setLevel( Level.parse( Integer.toString( logLevel ) ) );
262
263 // Assemble list of profiles to use from command line arguments.
264 List profileList = new ArrayList();
265 XmlRpcKit xmlrpcKit = XmlRpcKit.getInstance();
266 ClientProfile standardProfile = new ClientProfile() {
267 public boolean isHubRunning() {
268 return StandardClientProfile.getInstance().isHubRunning();
269 }
270 public HubConnection register() throws SampException {
271 return StandardClientProfile.getInstance().register();
272 }
273 public String toString() {
274 return "standard";
275 }
276 };
277 profileList.add( standardProfile );
278 Boolean reqExportUrls = null;
279 for ( Iterator it = argList.iterator(); it.hasNext(); ) {
280 String arg = (String) it.next();
281
282 // Determine whether to export localhost-type URLs.
283 if ( arg.equals( "-exporturls" ) ) {
284 reqExportUrls = Boolean.TRUE;
285 }
286 else if ( arg.equals( "-noexporturls" ) ) {
287 reqExportUrls = Boolean.FALSE;
288 }
289
290 // Accumulate various profiles.
291 else if ( arg.equals( "-standard" ) ) {
292 it.remove();
293 profileList.remove( standardProfile );
294 profileList.add( standardProfile );
295 }
296 else if ( arg.equals( "-nostandard" ) ) {
297 it.remove();
298 profileList.remove( standardProfile );
299 }
300 else if ( arg.equals( "-sampfile" ) && it.hasNext() ) {
301 it.remove();
302 String fname = (String) it.next();
303 it.remove();
304 final File lockfile = new File( fname );
305 profileList.add( new StandardClientProfile( xmlrpcKit ) {
306 public LockInfo getLockInfo() throws IOException {
307 return LockInfo
308 .readLockFile( SampUtils.fileToUrl( lockfile ) );
309 }
310 public String toString() {
311 return lockfile.toString();
312 }
313 } );
314 }
315 else if ( arg.equals( "-sampdir" ) && it.hasNext() ) {
316 it.remove();
317 final String dirname = (String) it.next();
318 it.remove();
319 final File lockfile =
320 new File( dirname, StandardClientProfile.LOCKFILE_NAME );
321 profileList.add( new StandardClientProfile( xmlrpcKit ) {
322 public LockInfo getLockInfo() throws IOException {
323 return LockInfo
324 .readLockFile( SampUtils.fileToUrl( lockfile ) );
325 }
326 public String toString() {
327 return dirname;
328 }
329 } );
330 }
331 else if ( arg.equals( "-sampurl" ) && it.hasNext() ) {
332 it.remove();
333 final URL lockUrl = new URL( (String) it.next() );
334 it.remove();
335 profileList.add( new StandardClientProfile( xmlrpcKit ) {
336 public LockInfo getLockInfo() throws IOException {
337 return LockInfo.readLockFile( lockUrl );
338 }
339 public String toString() {
340 return lockUrl.toString();
341 }
342 } );
343 }
344 else if ( arg.equals( "-keys" ) && it.hasNext() ) {
345 it.remove();
346 String endpoint = (String) it.next();
347 final URL url;
348 try {
349 url = new URL( endpoint );
350 }
351 catch ( MalformedURLException e ) {
352 System.err.println( "Not a URL: " + endpoint );
353 System.err.println( usage );
354 return 1;
355 }
356 it.remove();
357 if ( ! it.hasNext() ) {
358 System.err.println( usage );
359 return 1;
360 }
361 final String secret = (String) it.next();
362 it.remove();
363 profileList.add( new StandardClientProfile( xmlrpcKit ) {
364 public LockInfo getLockInfo() throws IOException {
365 return new LockInfo( secret, url.toString() );
366 }
367 public String toString() {
368 return url.toString();
369 }
370 } );
371 }
372 else if ( arg.equals( "-profile" ) && it.hasNext() ) {
373 it.remove();
374 String cname = (String) it.next();
375 it.remove();
376 final ClientProfile profile;
377 try {
378 profile =
379 (ClientProfile) Class.forName( cname ).newInstance();
380 }
381 catch ( Exception e ) {
382 System.err.println( "Error instantiating class " + cname
383 + "; " + e );
384 System.err.println( usage );
385 return 1;
386 }
387 profileList.add( profile );
388 }
389 else {
390 it.remove();
391 System.err.println( usage );
392 return 1;
393 }
394 }
395 assert argList.isEmpty();
396
397 // Get the array of profiles to bridge between.
398 ClientProfile[] profiles =
399 (ClientProfile[]) profileList.toArray( new ClientProfile[ 0 ] );
400 if ( profiles.length < 2 ) {
401 System.err.println( ( profiles.length == 0 ? "No" : "Only one" )
402 + " hub specified - no bridging to be done" );
403 if ( args.length == 0 ) {
404 System.err.println( usage );
405 }
406 return 1;
407 }
408
409 // Try to work out what hosts all the profiles are running on.
410 boolean allLocal = true;
411 String[] hosts = new String[ profiles.length ];
412 for ( int ip = 0; ip < profiles.length; ip++ ) {
413 ClientProfile profile = profiles[ ip ];
414 String host = null;
415 if ( profile == standardProfile ) {
416 host = SampUtils.getLocalhost();
417 }
418 else if ( profile instanceof StandardClientProfile ) {
419 URL xurl = ((StandardClientProfile) profile).getLockInfo()
420 .getXmlrpcUrl();
421 if ( xurl != null ) {
422 host = xurl.getHost();
423 }
424 }
425 allLocal = allLocal && isLocalHost( host );
426 hosts[ ip ] = host;
427 }
428
429 // Work out whether to export URLs.
430 final boolean exporturls;
431 if ( reqExportUrls == null ) {
432 if ( allLocal ) {
433 logger_.info( "All hubs apparently on local host; "
434 + "no URL exporting will be attempted" );
435 exporturls = false;
436 }
437 else {
438 logger_.info( "Bridge apparently running between hosts; "
439 + "URL exporting will be attempted" );
440 exporturls = true;
441 }
442 }
443 else {
444 exporturls = reqExportUrls.booleanValue();
445 logger_.info( "By request, URL exporting "
446 + ( exporturls ? "will" : "will not" )
447 + " be attempted" );
448 }
449
450 // Create a bridge.
451 Bridge bridge = new Bridge( profiles );
452
453 // Arrange to export URLs if appropriate.
454 if ( exporturls ) {
455 for ( int ip = 0; ip < profiles.length; ip++ ) {
456 String host = hosts[ ip ];
457 if ( host != null ) {
458 try {
459 InetAddress addr = InetAddress.getByName( host );
460 if ( addr.isLoopbackAddress() ) {
461 addr = InetAddress
462 .getByName( SampUtils.getLocalhost() );
463 }
464 String ehost = addr.getCanonicalHostName();
465 bridge.exportUrls( ip, ehost );
466 }
467 catch ( UnknownHostException e ) {
468 logger_.log( Level.WARNING,
469 "Can't export URLs for host " + host, e );
470 }
471 }
472 }
473 }
474
475 // Start the bridge.
476 if ( ! bridge.start() ) {
477 System.err.println( "Couldn't contact all hubs" );
478 return 1;
479 }
480
481 // Wait until there's only one hub connected.
482 try {
483 synchronized ( bridge ) {
484 while ( bridge.getConnectionCount() > 1 ) {
485 bridge.wait();
486 }
487 }
488 }
489 catch ( InterruptedException e ) {
490 }
491 return 0;
492 }
493 }