Debian Codegraph @

src/java/org/astrogrid/samp/xmlrpc/HubRunner.java

raw
1 package org.astrogrid.samp.xmlrpc;
2
3 import java.io.ByteArrayOutputStream;
4 import java.io.File;
5 import java.io.FileInputStream;
6 import java.io.FileOutputStream;
7 import java.io.IOException;
8 import java.io.InputStream;
9 import java.io.OutputStream;
10 import java.net.InetAddress;
11 import java.net.URL;
12 import java.util.ArrayList;
13 import java.util.Arrays;
14 import java.util.Date;
15 import java.util.Iterator;
16 import java.util.List;
17 import java.util.Random;
18 import java.util.Vector;
19 import java.util.logging.Level;
20 import java.util.logging.Logger;
21 import org.astrogrid.samp.SampUtils;
22 import org.astrogrid.samp.client.ClientProfile;
23 import org.astrogrid.samp.client.DefaultClientProfile;
24 import org.astrogrid.samp.client.HubConnection;
25 import org.astrogrid.samp.client.SampException;
26 import org.astrogrid.samp.hub.Hub;
27 import org.astrogrid.samp.hub.HubService;
28 import org.astrogrid.samp.hub.KeyGenerator;
29 import org.astrogrid.samp.hub.LockWriter;
30 import org.astrogrid.samp.hub.MessageRestriction;
31 import org.astrogrid.samp.hub.ProfileToken;
32 import org.astrogrid.samp.httpd.ServerResource;
33 import org.astrogrid.samp.httpd.UtilServer;
34
35 /**
36 * Runs a SAMP hub using the SAMP Standard Profile.
37 * The {@link #start} method must be called to start it up.
38 *
39 * <p>The {@link #main} method can be used to launch a hub from
40 * the command line. Use the <code>-help</code> flag for more information.
41 *
42 * @author Mark Taylor
43 * @since 15 Jul 2008
44 * @deprecated use {@link org.astrogrid.samp.hub.Hub} instead
45 */
46 public class HubRunner {
47
48 private final SampXmlRpcClientFactory xClientFactory_;
49 private final SampXmlRpcServerFactory xServerFactory_;
50 private final HubService hub_;
51 private final File lockfile_;
52 private URL lockUrl_;
53 private LockInfo lockInfo_;
54 private SampXmlRpcServer server_;
55 private HubXmlRpcHandler hubHandler_;
56 private boolean shutdown_;
57
58 private final static ProfileToken STANDARD_PROFILE = new ProfileToken() {
59 public String getProfileName() {
60 return "Standard";
61 }
62 public MessageRestriction getMessageRestriction() {
63 return null;
64 }
65 };
66 private final static Logger logger_ =
67 Logger.getLogger( HubRunner.class.getName() );
68 private final static Random random_ = KeyGenerator.createRandom();
69
70 /**
71 * Constructor.
72 * If the supplied <code>lockfile</code> is null, no lockfile will
73 * be written at hub startup.
74 *
75 * @param xClientFactory XML-RPC client factory implementation
76 * @param xServerFactory XML-RPC server implementation
77 * @param hub object providing hub services
78 * @param lockfile location to use for hub lockfile, or null
79 */
80 public HubRunner( SampXmlRpcClientFactory xClientFactory,
81 SampXmlRpcServerFactory xServerFactory,
82 HubService hub, File lockfile ) {
83 xClientFactory_ = xClientFactory;
84 xServerFactory_ = xServerFactory;
85 hub_ = hub;
86 lockfile_ = lockfile;
87 logger_.warning( "Class " + HubRunner.class.getName()
88 + " is deprecated; use "
89 + Hub.class.getName() + " instead." );
90 }
91
92 /**
93 * Starts the hub and writes the lockfile.
94 *
95 * @throws IOException if a hub is already running or an error occurs
96 */
97 public void start() throws IOException {
98
99 // Check for running or moribund hub.
100 if ( lockfile_ != null && lockfile_.exists() ) {
101 if ( isHubAlive( xClientFactory_, lockfile_ ) ) {
102 throw new IOException( "A hub is already running" );
103 }
104 else {
105 logger_.warning( "Overwriting " + lockfile_ + " lockfile "
106 + "for apparently dead hub" );
107 lockfile_.delete();
108 }
109 }
110
111 // Start up server.
112 try {
113 server_ = xServerFactory_.getServer();
114 }
115 catch ( IOException e ) {
116 throw e;
117 }
118 catch ( Exception e ) {
119 throw (IOException) new IOException( "Can't start XML-RPC server" )
120 .initCause( e );
121 }
122
123 // Start the hub service.
124 hub_.start();
125 String secret = createSecret();
126 ClientProfile connectionFactory = new ClientProfile() {
127 public HubConnection register() throws SampException {
128 return hub_.register( STANDARD_PROFILE );
129 }
130 public boolean isHubRunning() {
131 return hub_.isHubRunning();
132 }
133 };
134 hubHandler_ =
135 new HubXmlRpcHandler( xClientFactory_, connectionFactory, secret,
136 new KeyGenerator( "k:", 16, random_ ) );
137 server_.addHandler( hubHandler_ );
138
139 // Ensure tidy up in case of JVM shutdown.
140 Runtime.getRuntime().addShutdownHook(
141 new Thread( "HubRunner shutdown" ) {
142 public void run() {
143 shutdown();
144 }
145 } );
146
147 // Prepare lockfile information.
148 lockInfo_ = new LockInfo( secret, server_.getEndpoint().toString() );
149 lockInfo_.put( "hub.impl", hub_.getClass().getName() );
150 lockInfo_.put( "hub.start.date", new Date().toString() );
151
152 // Write lockfile information to file if required.
153 if ( lockfile_ != null ) {
154 logger_.info( "Writing new lockfile " + lockfile_ );
155 FileOutputStream out = new FileOutputStream( lockfile_ );
156 try {
157 writeLockInfo( lockInfo_, out );
158 try {
159 LockWriter.setLockPermissions( lockfile_ );
160 logger_.info( "Lockfile permissions set to "
161 + "user access only" );
162 }
163 catch ( IOException e ) {
164 logger_.log( Level.WARNING,
165 "Failed attempt to change " + lockfile_
166 + " permissions to user access only"
167 + " - possible security implications", e );
168 }
169 }
170 finally {
171 try {
172 out.close();
173 }
174 catch ( IOException e ) {
175 logger_.log( Level.WARNING, "Error closing lockfile?", e );
176 }
177 }
178 }
179 }
180
181 /**
182 * Shuts down the hub and tidies up.
183 * May harmlessly be called multiple times.
184 */
185 public synchronized void shutdown() {
186
187 // Return if we have already done this.
188 if ( shutdown_ ) {
189 return;
190 }
191 shutdown_ = true;
192
193 // Delete the lockfile if it exists and if it is the one originally
194 // written by this runner.
195 if ( lockfile_ != null ) {
196 if ( lockfile_.exists() ) {
197 try {
198 LockInfo lockInfo = readLockFile( lockfile_ );
199 if ( lockInfo.getSecret()
200 .equals( lockInfo_.getSecret() ) ) {
201 assert lockInfo.equals( lockInfo_ );
202 boolean deleted = lockfile_.delete();
203 logger_.info( "Lockfile " + lockfile_ + " "
204 + ( deleted ? "deleted"
205 : "deletion attempt failed" ) );
206 }
207 else {
208 logger_.warning( "Lockfile " + lockfile_ + " has been "
209 + " overwritten - not deleting" );
210 }
211 }
212 catch ( Throwable e ) {
213 logger_.log( Level.WARNING,
214 "Failed to delete lockfile " + lockfile_,
215 e );
216 }
217 }
218 else {
219 logger_.warning( "Lockfile " + lockfile_ + " has disappeared" );
220 }
221 }
222
223 // Withdraw service of the lockfile, if one has been published.
224 if ( lockUrl_ != null ) {
225 try {
226 UtilServer.getInstance().getResourceHandler()
227 .removeResource( lockUrl_ );
228 }
229 catch ( IOException e ) {
230 logger_.warning( "Failed to withdraw lockfile URL" );
231 }
232 lockUrl_ = null;
233 }
234
235 // Shut down the hub service if exists. This sends out shutdown
236 // messages to registered clients.
237 if ( hub_ != null ) {
238 try {
239 hub_.shutdown();
240 }
241 catch ( Throwable e ) {
242 logger_.log( Level.WARNING, "Hub service shutdown failed", e );
243 }
244 }
245
246 // Remove the hub XML-RPC handler from the server.
247 if ( hubHandler_ != null && server_ != null ) {
248 server_.removeHandler( hubHandler_ );
249 server_ = null;
250 }
251 lockInfo_ = null;
252 }
253
254 /**
255 * Returns the HubService object used by this runner.
256 *
257 * @return hub service
258 */
259 public HubService getHub() {
260 return hub_;
261 }
262
263 /**
264 * Returns the lockfile information associated with this object.
265 * Only present after {@link #start} has been called.
266 *
267 * @return lock info
268 */
269 public LockInfo getLockInfo() {
270 return lockInfo_;
271 }
272
273 /**
274 * Returns an HTTP URL at which the lockfile for this hub can be found.
275 * The first call to this method causes the lockfile to be published
276 * in this way; subsequent calls return the same value.
277 *
278 * <p>Use this with care; publishing your lockfile means that other people
279 * can connect to your hub and potentially do disruptive things.
280 *
281 * @return lockfile information URL
282 */
283 public URL publishLockfile() throws IOException {
284 if ( lockUrl_ == null ) {
285 ByteArrayOutputStream infoStrm = new ByteArrayOutputStream();
286 writeLockInfo( lockInfo_, infoStrm );
287 infoStrm.close();
288 final byte[] infoBuf = infoStrm.toByteArray();
289 URL url = UtilServer.getInstance().getResourceHandler()
290 .addResource( "samplock", new ServerResource() {
291 public long getContentLength() {
292 return infoBuf.length;
293 }
294 public String getContentType() {
295 return "text/plain";
296 }
297 public void writeBody( OutputStream out ) throws IOException {
298 out.write( infoBuf );
299 }
300 } );
301
302 // Attempt to replace whatever host name is used by the FQDN,
303 // for maximal usefulness to off-host clients.
304 try {
305 url = new URL( url.getProtocol(),
306 InetAddress.getLocalHost()
307 .getCanonicalHostName(),
308 url.getPort(), url.getFile() );
309 }
310 catch ( IOException e ) {
311 }
312 lockUrl_ = url;
313 }
314 return lockUrl_;
315 }
316
317 /**
318 * Used to generate the registration password. May be overridden.
319 *
320 * @return pasword
321 */
322 public String createSecret() {
323 return Long.toHexString( random_.nextLong() );
324 }
325
326 /**
327 * Attempts to determine whether a given lockfile corresponds to a hub
328 * which is still alive.
329 *
330 * @param xClientFactory XML-RPC client factory implementation
331 * @param lockfile lockfile location
332 * @return true if the hub described at <code>lockfile</code> appears
333 * to be alive and well
334 */
335 private static boolean isHubAlive( SampXmlRpcClientFactory xClientFactory,
336 File lockfile ) {
337 LockInfo info;
338 try {
339 info = readLockFile( lockfile );
340 }
341 catch ( Exception e ) {
342 logger_.log( Level.WARNING, "Failed to read lockfile", e );
343 return false;
344 }
345 if ( info == null ) {
346 return false;
347 }
348 URL xurl = info.getXmlrpcUrl();
349 if ( xurl != null ) {
350 try {
351 xClientFactory.createClient( xurl )
352 .callAndWait( "samp.hub.ping", new ArrayList() );
353 return true;
354 }
355 catch ( Exception e ) {
356 logger_.log( Level.WARNING, "Hub ping method failed", e );
357 return false;
358 }
359 }
360 else {
361 logger_.warning( "No XMLRPC URL in lockfile" );
362 return false;
363 }
364 }
365
366 /**
367 * Reads lockinfo from a file.
368 *
369 * @param lockFile file
370 * @return info from file
371 */
372 private static LockInfo readLockFile( File lockFile ) throws IOException {
373 return LockInfo.readLockFile( new FileInputStream( lockFile ) );
374 }
375
376 /**
377 * Writes lockfile information to a given output stream.
378 * The stream is not closed.
379 *
380 * @param info lock info to write
381 * @param out destination stream
382 */
383 private static void writeLockInfo( LockInfo info, OutputStream out )
384 throws IOException {
385 LockWriter writer = new LockWriter( out );
386 writer.writeComment( "SAMP Standard Profile lockfile written "
387 + new Date() );
388 writer.writeComment( "Note contact URL hostname may be "
389 + "configured using "
390 + SampUtils.LOCALHOST_PROP + " property" );
391 writer.writeAssignments( info );
392 out.flush();
393 }
394
395 /**
396 * Main method. Starts a hub.
397 * Use "-help" flag for more information.
398 *
399 * @param args command-line arguments
400 */
401 public static void main( String[] args ) throws IOException {
402 int status = runMain( args );
403 if ( status != 0 ) {
404 System.exit( status );
405 }
406 }
407
408 /**
409 * Does the work for running the {@link #main} method.
410 * System.exit() is not called from this method.
411 * Use "-help" flag for more information.
412 *
413 * @param args command-line arguments
414 * @return 0 means success, non-zero means error status
415 */
416 public static int runMain( String[] args ) throws IOException {
417 StringBuffer ubuf = new StringBuffer();
418 ubuf.append( "\n Usage:" )
419 .append( "\n " )
420 .append( HubRunner.class.getName() )
421 .append( "\n " )
422 .append( " [-help]" )
423 .append( " [-/+verbose]" )
424 .append( "\n " )
425 .append( " [-mode " );
426 HubMode[] modes = HubMode.getAvailableModes();
427 for ( int im = 0; im < modes.length; im++ ) {
428 if ( im > 0 ) {
429 ubuf.append( '|' );
430 }
431 ubuf.append( modes[ im ].getName() );
432 }
433 ubuf.append( ']' )
434 .append( " [-secret <secret>]" )
435 .append( " [-httplock]" )
436 .append( "\n" );
437 String usage = ubuf.toString();
438 List argList = new ArrayList( Arrays.asList( args ) );
439 HubMode hubMode = HubMode.MESSAGE_GUI;
440 if ( ! Arrays.asList( HubMode.getAvailableModes() )
441 .contains( hubMode ) ) {
442 hubMode = HubMode.NO_GUI;
443 }
444 int verbAdjust = 0;
445 XmlRpcKit xmlrpc = null;
446 String secret = null;
447 boolean httplock = false;
448 for ( Iterator it = argList.iterator(); it.hasNext(); ) {
449 String arg = (String) it.next();
450 if ( arg.equals( "-mode" ) && it.hasNext() ) {
451 it.remove();
452 String mode = (String) it.next();
453 it.remove();
454 hubMode = HubMode.getModeFromName( mode );
455 if ( hubMode == null ) {
456 System.err.println( "Unknown mode " + mode );
457 System.err.println( usage );
458 return 1;
459 }
460 }
461 else if ( arg.equals( "-secret" ) && it.hasNext() ) {
462 it.remove();
463 secret = (String) it.next();
464 it.remove();
465 }
466 else if ( arg.equals( "-httplock" ) ) {
467 it.remove();
468 httplock = true;
469 }
470 else if ( arg.startsWith( "-v" ) ) {
471 it.remove();
472 verbAdjust--;
473 }
474 else if ( arg.startsWith( "+v" ) ) {
475 it.remove();
476 verbAdjust++;
477 }
478 else if ( arg.startsWith( "-h" ) ) {
479 it.remove();
480 System.out.println( usage );
481 return 0;
482 }
483 else {
484 System.err.println( usage );
485 return 1;
486 }
487 }
488 assert argList.isEmpty();
489
490 // Adjust logging in accordance with verboseness flags.
491 int logLevel = Level.WARNING.intValue() + 100 * verbAdjust;
492 Logger.getLogger( "org.astrogrid.samp" )
493 .setLevel( Level.parse( Integer.toString( logLevel ) ) );
494
495 // Get the location of the lockfile to write, if any.
496 final File lockfile;
497 if ( httplock ) {
498 lockfile = null;
499 }
500 else {
501 URL lockUrl = StandardClientProfile.getLockUrl();
502 File f = SampUtils.urlToFile( lockUrl );
503 if ( f == null ) {
504 System.err.println( "Can't write lockfile to " + lockUrl );
505 System.err.println( "Try resetting "
506 + DefaultClientProfile.HUBLOC_ENV
507 + " environment variable." );
508 return 1;
509 }
510 else {
511 lockfile = f;
512 }
513 }
514
515 // Start the hub.
516 HubRunner runner = runHub( hubMode, xmlrpc, secret, lockfile );
517
518 // If the lockfile is not the default one, write a message through
519 // the logging system.
520 URL lockfileUrl = httplock ? runner.publishLockfile()
521 : SampUtils.fileToUrl( lockfile );
522 boolean isDflt = StandardClientProfile.getDefaultLockUrl().toString()
523 .equals( lockfileUrl.toString() );
524 String hubassign = DefaultClientProfile.HUBLOC_ENV + "="
525 + StandardClientProfile.STDPROFILE_HUB_PREFIX
526 + lockfileUrl;
527 logger_.log( isDflt ? Level.INFO : Level.WARNING, hubassign );
528
529 // For non-GUI case block indefinitely otherwise the hub (which uses
530 // a daemon thread) will not just exit immediately.
531 if ( hubMode.isDaemon() ) {
532 Object lock = new String( "Indefinite" );
533 synchronized ( lock ) {
534 try {
535 lock.wait();
536 }
537 catch ( InterruptedException e ) {
538 }
539 }
540 }
541
542 // Success return.
543 return 0;
544 }
545
546 /**
547 * Static method which may be used to start a SAMP hub programmatically.
548 * The returned hub is running (<code>start</code> has been called).
549 *
550 * <p>If the hub mode corresponds to one of the GUI options,
551 * one of two things will happen. An attempt will be made to install
552 * an icon in the "system tray"; if this is successful, the attached
553 * popup menu will provide options for displaying the hub window and
554 * for shutting it down. If no system tray is available, the hub window
555 * will be posted directly, and the hub will shut down when this window
556 * is closed. System tray functionality is only available when running
557 * under Java 1.6 or later, and when using a suitable display manager.
558 *
559 * @param hubMode hub mode
560 * @param xmlrpc XML-RPC implementation;
561 * automatically determined if null
562 * @return running hub
563 */
564 public static HubRunner runHub( HubMode hubMode, XmlRpcKit xmlrpc )
565 throws IOException {
566 return runHub( hubMode, xmlrpc, null,
567 SampUtils
568 .urlToFile( StandardClientProfile.getLockUrl() ) );
569 }
570
571 /**
572 * Static method which may be used to start a SAMP hub programmatically,
573 * with a supplied samp.secret string.
574 * The returned hub is running (<code>start</code> has been called).
575 *
576 * <p>If the hub mode corresponds to one of the GUI options,
577 * one of two things will happen. An attempt will be made to install
578 * an icon in the "system tray"; if this is successful, the attached
579 * popup menu will provide options for displaying the hub window and
580 * for shutting it down. If no system tray is available, the hub window
581 * will be posted directly, and the hub will shut down when this window
582 * is closed. System tray functionality is only available when running
583 * under Java 1.6 or later, and when using a suitable display manager.
584 *
585 * @param hubMode hub mode
586 * @param xmlrpc XML-RPC implementation;
587 * automatically determined if null
588 * @param secret samp.secret string to be used for hub connection;
589 * chosen at random if null
590 * @param lockfile location of lockfile to write,
591 * or null for lock to be provided by HTTP
592 * @return running hub
593 */
594 public static HubRunner runHub( HubMode hubMode, XmlRpcKit xmlrpc,
595 final String secret, File lockfile )
596 throws IOException {
597 if ( xmlrpc == null ) {
598 xmlrpc = XmlRpcKit.getInstance();
599 }
600 HubRunner[] hubRunners = new HubRunner[ 1 ];
601 HubRunner runner =
602 new HubRunner( xmlrpc.getClientFactory(), xmlrpc.getServerFactory(),
603 hubMode.createHubService( random_, hubRunners ),
604 lockfile ) {
605 public String createSecret() {
606 return secret == null ? super.createSecret()
607 : secret;
608 }
609 };
610 hubRunners[ 0 ] = runner;
611 runner.start();
612 return runner;
613 }
614
615 /**
616 * Static method which will attempt to start a hub running in
617 * an external JVM. The resulting hub can therefore outlast the
618 * lifetime of the current application.
619 * Because of the OS interaction required, it's hard to make this
620 * bulletproof, and it may fail without an exception, but we do our best.
621 *
622 * @param hubMode hub mode
623 * @see #checkExternalHubAvailability
624 */
625 public static void runExternalHub( HubMode hubMode ) throws IOException {
626 String classpath = System.getProperty( "java.class.path" );
627 if ( classpath == null || classpath.trim().length() == 0 ) {
628 throw new IOException( "No classpath available - JNLP context?" );
629 }
630 File javaHome = new File( System.getProperty( "java.home" ) );
631 File javaExec = new File( new File( javaHome, "bin" ), "java" );
632 String javacmd = ( javaExec.exists() && ! javaExec.isDirectory() )
633 ? javaExec.toString()
634 : "java";
635 String[] propagateProps = new String[] {
636 XmlRpcKit.IMPL_PROP,
637 UtilServer.PORT_PROP,
638 SampUtils.LOCALHOST_PROP,
639 "java.awt.Window.locationByPlatform",
640 };
641 List argList = new ArrayList();
642 argList.add( javacmd );
643 for ( int ip = 0; ip < propagateProps.length; ip++ ) {
644 String propName = propagateProps[ ip ];
645 String propVal = System.getProperty( propName );
646 if ( propVal != null ) {
647 argList.add( "-D" + propName + "=" + propVal );
648 }
649 }
650 argList.add( "-classpath" );
651 argList.add( classpath );
652 argList.add( HubRunner.class.getName() );
653 argList.add( "-mode" );
654 argList.add( hubMode.toString() );
655 String[] args = (String[]) argList.toArray( new String[ 0 ] );
656 StringBuffer cmdbuf = new StringBuffer();
657 for ( int iarg = 0; iarg < args.length; iarg++ ) {
658 if ( iarg > 0 ) {
659 cmdbuf.append( ' ' );
660 }
661 cmdbuf.append( args[ iarg ] );
662 }
663 logger_.info( "Starting external hub" );
664 logger_.info( cmdbuf.toString() );
665 execBackground( args );
666 }
667
668 /**
669 * Attempts to determine whether an external hub can be started using
670 * {@link #runExternalHub}. If it can be determined that such an
671 * attempt would fail, this method will throw an exception with
672 * an informative message. This method succeeding is not a guarantee
673 * that an external hub can be started successfullly.
674 * The behaviour of this method is not expected to change over the
675 * lifetime of a given JVM.
676 */
677 public static void checkExternalHubAvailability() throws IOException {
678 String classpath = System.getProperty( "java.class.path" );
679 if ( classpath == null || classpath.trim().length() == 0 ) {
680 throw new IOException( "No classpath available - JNLP context?" );
681 }
682 if ( System.getProperty( "jnlpx.jvm" ) != null ) {
683 throw new IOException( "Running under WebStart"
684 + " - external hub not likely to work" );
685 }
686 }
687
688 /**
689 * Executes a command in a separate process, and discards any stdout
690 * or stderr output generated by it.
691 * Simply calling <code>Runtime.exec</code> can block the process
692 * until its output is consumed.
693 *
694 * @param cmdarray array containing the command to call and its args
695 */
696 private static void execBackground( String[] cmdarray ) throws IOException {
697 Process process = Runtime.getRuntime().exec( cmdarray );
698 discardBytes( process.getInputStream() );
699 discardBytes( process.getErrorStream() );
700 }
701
702 /**
703 * Ensures that any bytes from a given input stream are discarded.
704 *
705 * @param in input stream
706 */
707 private static void discardBytes( final InputStream in ) {
708 Thread eater = new Thread( "StreamEater" ) {
709 public void run() {
710 try {
711 while ( in.read() >= 0 ) {}
712 in.close();
713 }
714 catch ( IOException e ) {
715 }
716 }
717 };
718 eater.setDaemon( true );
719 eater.start();
720 }
721 }