summaryrefslogtreecommitdiff
path: root/java/JACE/netsvcs/Token/RemoteLock.java
blob: 824e05a31f0f3eaa72656c6a650b3810b1dc8297 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
package JACE.netsvcs.Token;

import java.io.*;
import JACE.Concurrency.*;
import JACE.ASX.*;
import JACE.Connection.*;
import JACE.OS.*;

/**
 * Proxy used by clients to connect to the token service.  This 
 * implements the AbstractLock interface, so can be used like any
 * other synchronization mechanism.  The user can either use this
 * class directly, or use a proxy which already inputs its type.
 * <P>
 * Currently, a separate instance (and thus a separate socket connection)
 * must be used for each thread which accesses the service.  The token
 * service itself could handle multiple client IDs and token names per
 * connection with the following requirement -- since the service blocks
 * in its operations, a shadow mutex would have to be used in the proxy.
 * <P>
 * It would be best if the user called the close () method after finishing
 * up with a RemoteLock, but that is not absolutely necessary.  The socket
 * will be closed when the JVM exits or finalize is called.  (That will also
 * free the actual token in the token service in case release was never
 * called.)
 * <P>
 * The SLEEPHOOK result is never returned, only SUCCESS or FAILURE.  (C++
 * version doesn't seem to indicate the sleep hook result.)
 *
 *@see MutexHandler
 *@see RWMutexHandler
 *@see JACE.Concurrency.AbstractLock
 *
 *@author Everett Anderson
 */
public class RemoteLock extends SvcHandler implements AbstractLock
{
  /**
   * Accessor for the token name. 
   *
   *@return name of the token
   */
  public String tokenName ()
  {
    return request_.tokenName ();
  }

  /**
   * Set the name of the token.
   */
  public void tokenName (String name)
  {
    request_.tokenName (name);
  }

  /**
   * Accessor for the client ID.
   */
  public String clientID ()
  {
    return request_.clientID ();
  }

  /**
   * Set the client ID.
   */
  public void clientID (String clientID)
  {
    request_.clientID (clientID);
  }

  /**
   * Constructor.
   *
   *@see LockTypes
   *@param tokenType  type of token to create in the token service
   *@param proxyType  type of proxy to define this RemoteLock as
   *@param tokenName  name of the token to connect to in the token service
   *@param clientID   clientID to use to refer to this client
   *@param host       host name of the token service
   *@param port       port to connect to for the token service
   */
  public RemoteLock (int tokenType,
		     int proxyType,
		     String tokenName,
		     String clientID,
		     String host,
		     int port)
  {
    host_ = host;
    port_ = port;

    // Only allocates one reply and one request
    reply_ = new TokenReply ();

    request_ = new TokenRequest (tokenType,
				 proxyType,
				 0,
				 tokenName,
				 clientID);
  }

  /**
   * Reconnect this proxy to the token service. 
   *
   *@exception LockException problem occured in reconnecting
   */
  protected void reconnect () throws LockException
  {
    Connector c = new Connector ();
    c.open (host_, port_);

    try {
      c.connect (this);
    } catch (InstantiationException e) {
      throw new LockException (e.getMessage());
    } catch (IllegalAccessException e) {
      throw new LockException (e.getMessage());
    } catch (IOException e) {
      throw new LockException (e.getMessage());
    }
  }

  /**
   * Check to see if this RemoteLock is connected.
   */
  public boolean connected ()
  {
    return connected_;
  }

  /**
   * Initialize this RemoteLock.  Called by Connector.
   */
  public int open (Object obj)
  {
    connected_ = true;
    return 0;
  }

  /**
   * Shut down the connection to the server.  Current implementation
   * calls close ().
   */
  public int close (long flags)
  {
    return close ();
  }

  /**
   * Shut down the connection to the server and mark this lock
   * as disconnected.
   */
  public int close ()
  {
    if (connected ()) {
      try {
	connected_ = false;
	peer ().close ();
      } catch (IOException e) {
	return -1;
      }
    }
    
    return 0;
  }

  /**
   * Send the given request to the token service, throwing a 
   * LockException on error.
   */
  protected void sendRequest (TokenRequest request) throws LockException
  {
    try {
      if (!connected ())
	reconnect ();

      request.streamOutTo (peer ().dataOutputStream ());

    } catch (IOException e) {
      close ();
      throw new LockException (e.getMessage ());
    }
  }

  /**
   * Receive a reply from the token service, throwing a LockException
   * on error.
   */
  protected void receiveReply (TokenReply reply) throws LockException
  {
    if (!connected ())
      throw new LockException ("Proxy wasn't connected, any replies lost");

    try {

      reply.streamInFrom (peer ().dataInputStream ());

    } catch (IOException e) {
      close ();
      throw new LockException (e.getMessage ());
    }
  }

  /**
   * For errors that shouldn't generate exceptions, return the
   * appropriate result code as defined in AbstractLock.
   *
   *@return AbstractLock.SUCCESS or AbstractLock.FAILURE
   */
  protected int processErrno (TokenReply reply)
  {
    switch (reply.errno ())
      {
      case TokenReply.NO_ERRORS:
	return AbstractLock.SUCCESS;
      case TokenReply.EIO:
	close ();
	return AbstractLock.FAILURE;
      default:
	return AbstractLock.FAILURE;
      }
  }

  /**
   * Make a request to the token service with the given operation
   * type and arguments.
   *
   *@see LockOperations
   *@see LockTypes
   *@param operationType type of operation to perform
   *@param proxyType type of proxy this is
   *@param requeuePosition put this owner at this position in the
   *                       waiting queue (only makes sense if the
   *                       operation is renew)
   *@return AbstractLock.SUCCESS or AbstractLock.FAILURE
   *@exception LockException remote access error occured
   */
  protected int makeRequest (int operationType,
			     int proxyType,
			     int requeuePosition)
    throws LockException
  {
    request_.operationType (operationType);
    request_.proxyType (proxyType);
    request_.requeuePosition (requeuePosition);
    request_.useTimeout (false);

    sendRequest (request_);
    receiveReply (reply_);
    
    // make sure that if someone does send a magic cookie arg back,
    // to keep it going
    request_.arg (reply_.arg ());

    return processErrno (reply_);
  }

  /**
   * Make a request to the token service with the given arguments
   * that must be performed by the given absolute time timeout.
   * Currently, the timeout is managed by the remote service.
   *
   *@see LockOperations
   *@see LockTypes
   *@param operationType type of operation to perform
   *@param proxyType type of proxy this is
   *@param requeuePosition put this owner at this position in the
   *                       waiting queue (only makes sense if the
   *                       operation is renew)
   *@param timeout absolute time timeout to accomplish the operation by
   *@return AbstractLock.SUCCESS or AbstractLock.FAILURE
   *@exception LockException remote access error occured
   */
  protected int makeRequest (int operationType,
			     int proxyType,
			     int requeuePosition,
			     TimeValue timeout)
    throws LockException, TimeoutException
  {
    request_.operationType (operationType);
    request_.proxyType (proxyType);
    request_.requeuePosition (requeuePosition);
    request_.useTimeout (timeout);

    sendRequest (request_);
    receiveReply (reply_);

    request_.arg (reply_.arg ());

    if (reply_.errno () == TokenReply.ETIME)
      throw new TimeoutException (timeout, "Remote Lock");

    return processErrno (reply_);
  }

  /**
   * Acquire ownership of the lock, blocking indefinitely if necessary.  
   * <P>
   *@return    AbstractLock.FAILURE or AbstractLock.SUCCESS
   *@exception LockException a remote error occured
   */
  public int acquire () throws LockException
  {
    return makeRequest (LockOperations.ACQUIRE, 0, 0);
  }

  /**
   * Acquire ownership of the lock by the given absolute time time-out.
   * A value of null for the timeout parameter results in a blocking
   * acquire.
   * A value of TimeValue.zero throws a TimeoutException if the
   * acquire would block.
   * <P>
   *@param timeout  absolute time by which the lock must be acquired
   *@return         appropriate Lock return value (AbstractLock.FAILURE, 
   *                AbstractLock.SUCCESS or AbstractLock.SLEEPHOOK)
   *@exception      LockException a remote error occured
   *@exception      JACE.ASX.TimeoutException thrown when the lock is not
   *                obtained by the desired time
   *@see #tryAcquire
   */
  public int acquire (TimeValue timeout)
    throws LockException, TimeoutException
  {
    return makeRequest (LockOperations.ACQUIRE, 0, 0, timeout);
  }
    
  /**
   * Acquire a read lock, blocking indefinitely if necessary. 
   *
   *@return    AbstractLock.FAILURE or AbstractLock.SUCCESS
   *@exception LockException a remote error occured
   */
  public int acquireRead () throws LockException
  {
    return makeRequest (LockOperations.ACQUIRE,
			LockTypes.READ_LOCK_PROXY,
			0);
  }

  /**
   * Acquire a read lock by the given absolute time time-out.  
   *
   *@param timeout  absolute time by which the lock must be acquired
   *@return         appropriate lock return value (AbstractLock.FAILURE, 
   *                AbstractLock.SUCCESS or AbstractLock.SLEEPHOOK)
   *@exception      LockException a remote error occured
   *@exception      JACE.ASX.TimeoutException thrown when the lock is not
   *                obtained by the desired time
   *@see #tryAcquireRead
   */
  public int acquireRead (TimeValue timeout) 
    throws LockException, TimeoutException
  {
    return makeRequest (LockOperations.ACQUIRE,
			LockTypes.READ_LOCK_PROXY,
			0,
			timeout);
  }

  /**
   * Acquire a write lock, blocking indefinitely if necessary. 
   *
   *@return    AbstractLock.FAILURE or AbstractLock.SUCCESS
   *@exception LockException a remote error occured
   */
  public int acquireWrite () 
    throws LockException
  {
    return makeRequest (LockOperations.ACQUIRE,
			LockTypes.WRITE_LOCK_PROXY,
			0);
  }

  /**
   * Acquire a write lock by the given absolute time time-out.  
   *
   *@param timeout  absolute time by which the lock must be acquired
   *@return         appropriate lock return value (AbstractLock.FAILURE, 
   *                AbstractLock.SUCCESS or AbstractLock.SLEEPHOOK)
   *@exception      LockException a remote error occured
   *@exception      JACE.ASX.TimeoutException thrown when the lock is not
   *                obtained by the desired time
   *@see #tryAcquireWrite
   */
  public int acquireWrite (TimeValue timeout) 
    throws LockException, TimeoutException
  {
    return makeRequest (LockOperations.ACQUIRE,
			LockTypes.WRITE_LOCK_PROXY,
			0,
			timeout);
  }

  
  /**
   * Give up the lock to some number of waiting threads (if any), then 
   * reacquire, blocking indefinitely if necessary.
   * <P>
   * An optimized method that efficiently reacquires the token if no
   * other threads are waiting.  This is useful for situations where
   * you don't want to degrade the quality of service if there are
   * other threads waiting to get the token. 
   * <P>
   *@param     requeuePosition position in the waiters queue to insert
   *           this thread.  If this value is -1 and there are other
   *           threads waiting to obtain the token, this thread is queued
   *           at the end.  If this value is greater than -1, then it
   *           indicates how many entries to skip over before inserting
   *           our thread into the queue.  (For example, if it is 0,
   *           this thread is put at the front of the queue.)  If this 
   *           value is greater than the number of waiters, this thread is
   *           simply put at the end of the current waiters queue.
   *@return    AbstractLock.FAILURE or AbstractLock.SUCCESS
   *@exception LockException a remote error occured
   */
  public int renew (int requeuePosition) 
    throws LockException 
  {
    return makeRequest (LockOperations.RENEW,
			0,
			requeuePosition);
  }

  /**
   * Give up the lock to some waiting threads (if any), then reacquire
   * by the given absolute time time-out.
   * <P>
   * An optimized method that efficiently reacquires the token if no
   * other threads are waiting.  This is useful for situations where
   * you don't want to degrade the quality of service if there are
   * other threads waiting to get the token. 
   * <P>
   * A value of null for the timeout indicates a blocking renew.
   * <P>
   *@param     requeuePosition position in the waiters queue to insert
   *           this thread.  If this value is -1 and there are other
   *           threads waiting to obtain the token, this thread is queued
   *           at the end.  If this value is greater than -1, then it
   *           indicates how many entries to skip over before inserting
   *           our thread into the queue.  (For example, if it is 0,
   *           this thread is put at the front of the queue.)  If this 
   *           value is greater than the number of waiters, this thread is
   *           simply put at the end of the current waiters queue.
   * 
   *@param     timeout absolute time by which the lock must be reacquired
   *
   *@return         appropriate AbstractLock return value 
   *                (AbstractLock.FAILURE or AbstractLock.SUCCESS)
   *@exception      LockException a remote error occured
   *@exception      JACE.ASX.TimeoutException thrown when the lock is not
   *                obtained by the desired time
   */
  public int renew (int requeuePosition, TimeValue timeout) 
    throws LockException, TimeoutException
  {
    return makeRequest (LockOperations.RENEW,
			0,
			requeuePosition,
			timeout);
  }

  /** 
   * Try to acquire the lock without blocking.  
   * <P>
   *@return         appropriate AbstractLock return value 
   *                (AbstractLock.FAILURE or AbstractLock.SUCCESS)
   *@exception      LockException a remote error occured
   */
  public int tryAcquire () throws LockException
  {
    return makeRequest (LockOperations.TRY_ACQUIRE, 0, 0);
  }

  /** 
   * Try to acquire a read lock without blocking.  
   * <P>
   *@return         appropriate AbstractLock return value 
   *                (AbstractLock.FAILURE or AbstractLock.SUCCESS)
   *@exception      LockException a remote error occured
   */
  public int tryAcquireRead () throws LockException
  {
    return makeRequest (LockOperations.TRY_ACQUIRE,
			LockTypes.READ_LOCK_PROXY,
			0);
  }

  /** 
   * Try to acquire a write lock without blocking.  
   * 
   *@return         appropriate AbstractLock return value 
   *                (AbstractLock.FAILURE or AbstractLock.SUCCESS)
   *@exception      LockException a remote error occured
   */
  public int tryAcquireWrite () throws LockException
  {
    return makeRequest (LockOperations.TRY_ACQUIRE,
			LockTypes.WRITE_LOCK_PROXY,
			0);
  }

  /** 
   * Release ownership of this lock.  
   * 
   *@return    appropriate AbstractLock return value 
   *           (AbstractLock.FAILURE or AbstractLock.SUCCESS)
   *@exception LockException a remote error occured
   */
  public int release () throws LockException
  {
    return makeRequest (LockOperations.RELEASE, 0, 0);
  }

  /**
   * Closes the connection to the server (if it is still open).
   */
  protected void finalize () throws Throwable
  {
    close ();
  }

  /**
   * No-op implementation for the sleep hook (unused).
   */
  public void sleepHook () {}

  /** Status of whether this RemoteLock is connected to the server or not */
  protected boolean connected_ = false;

  /** Request object for transmissions to the server */
  protected TokenRequest request_;

  /** Reply object for receiving transmissions from the server */
  protected TokenReply reply_;

  /** Host name of the token service */
  protected String host_;

  /** Port number of the token service */
  protected int port_;
}