summaryrefslogtreecommitdiff
path: root/java/netsvcs/Time/TSClerkHandler.java
blob: fc89b69c45c5efa43fd34ce05defac0ac524eb83 (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
/*************************************************
 *
 * = PACKAGE
 *    netsvcs.Time
 *
 * = FILENAME
 *    TS_Clerk_Handler.java
 *
 *@author Prashant Jain, Everett Anderson
 *
 *************************************************/
package netsvcs.Time;

import java.io.*;
import java.util.Date;
import JACE.OS.*;
import JACE.Connection.*;
import JACE.Reactor.*;
import JACE.ASX.TimeValue;

/**
 * <hr>
 * <p><h2>SYNOPSIS</h2>
 *
 * <blockquote>Requests the remote time on a server at regular
 * intervals.</blockquote>
 *
 * <p><h2>DESCRIPTION</h2>
 *
 * <blockquote>TSClerkHandlers are created by a TSClerkProcessor.  There
 * is one handler for each server that the Clerk Processor factors into
 * its calculations.</blockquote>
 */
public class TSClerkHandler extends SvcHandler
{
  /**
   * Constructor.  TSClerkProcessor specifies the server machine and
   * port, as well as the interval at which to make the query.
   */
  public TSClerkHandler (String hostname, 
			 int port,
			 TimerQueue tq, 
			 int timeout,
			 TSClerkProcessor parent)
  {

    this.hostname_ = hostname;
    this.port_ = port;
    this.tq_ = tq;
    this.timeout_ = timeout;

    this.initialTimeout_ = timeout;
    this.processor_ = parent;

    this.sendMsg_ = new String ("TIME_UPDATE_REQUEST");
  }
  
  /**
   * Called to start this handler in a new thread.  This only
   * does it when the state of the handler is INITIALIZING.
   */
  public int open (Object obj)
  {
    if (this.state_ != RECONNECTING) {

      Thread test = new Thread(this);

      new Thread (this).start ();

    }
    return 0;
  }

  /**
   * Accessor - return the host name of the server
   */
  public String hostname ()
  {
    return this.hostname_;
  }

  /**
   * Accessor - return the port used to contact the server
   */
  public int port ()
  {
    return this.port_;
  }

  /**
   * Accessor - returns the difference between the local time and
   * the remote server. 
   */
  public long delta ()
  {
    return this.delta_;
  }

  /**
   * Called when the thread starts.  Schedules itself with the
   * timer queue.
   */
  public void run ()
  {
    this.timerId_ = this.tq_.scheduleTimer (this,
					    null,
					    new TimeValue (this.timeout_),
					    new TimeValue (this.timeout_));

  }

  /**
   * Accessor - return the state
   */
  public int state() 
  {
    return this.state_;
  }

  /**
   * Sets the state of the handler
   */
  public void state(int newState)
  {
    this.state_ = newState;
  }

  /**
   * Provides a new time out interval (exponentially increasing) so
   * that if the server doesn't respond, we don't keep trying to
   * reconnect as often.  Maximum value is 5 minutes.
   */
  public int recalculateTimeout() 
  {
    this.timeout_ *= 2;

    if (this.timeout_ > this.max_timeout_)
      this.timeout_ = max_timeout_;

    return this.timeout_;
  }

  /**
   * Start the recovery from a server disconnection by closing the
   * port and recalculating the timeout value.
   */
  protected void errorRecovery()
  {
    ACE.DEBUG("Time Service failure with server " + this.hostname_);

    this.timeout_ = this.recalculateTimeout();

    this.reschedule();
  }

  /**
   * Removes this handler from the timer queue, and reschedules it
   * (presumably with a new timeout value)
   */
  public void reschedule()
    {
      this.tq_.cancelTimer(this);

      this.timerId_ = this.tq_.scheduleTimer (this,
					      null,
					      new TimeValue (this.timeout_),
					      new TimeValue (this.timeout_));
    }

  /**
   * Called back by the timer queue.  If the handler isn't connected,
   * it tries to reconnect to the server.  Otherwise, it requests
   * the remote time.  The server is said to have disconnected when
   * an exception is thrown in the socket system, or the result is
   * a string with length <= 0.
   */
  public int handleTimeout (TimeValue tv, Object obj)
  {
    if (this.state_ != CONNECTED) {

      this.processor_.initiateConnection(this);

      // If still not connected
      if (this.state_ != CONNECTED) { 

	// used to set state to reconnecting here
	this.state_ = RECONNECTING;

	// Reschedule to try again later
	this.errorRecovery();
	return 0;
      } 

      // If connected, poll the server at the requested intervals
      this.resetTimeout();
    }

    StringBuffer ack = new StringBuffer ();
    int ackLen;
    try
      {
	// Used to calculate the turn-around time
	long sendTime = System.currentTimeMillis();

	this.peer ().send(this.sendMsg_);
	ackLen = this.peer ().recv (ack);

	long recvTime = System.currentTimeMillis();

	if (ackLen <= 0) {

	  this.state_ = DISCONNECTED;
	  return -1;

	} else {   

	  long delta = (new Long(ack.toString())).longValue() - recvTime;

	  delta += (recvTime - sendTime) / 2;

	  this.delta_ = delta;

          System.err.println("Delta: " + this.delta_);
	}

      }
    catch (NullPointerException e)
      {
	ACE.ERROR ("connection reset by peer");
	this.state_ = DISCONNECTED;
	return -1;
      }
    catch (IOException e)
      {
	ACE.ERROR (e);
	this.state_ = DISCONNECTED;
	return -1;
      }

    return 0;
  }
  
  /**
   * Resets the timer interval to be the one supplied to the
   * constructor.
   */
  public void resetTimeout()
    {
      this.timeout_ = this.initialTimeout_;

      this.reschedule();
    }
    
  private TSClerkProcessor processor_;
  // Reference used to re-establish connections

  public static final int MAX_RETRY_TIMEOUT = 300;
  // Wait at most 5 minutes before trying to reconnect

  // States
  public static final int CONNECTED = 0;
  public static final int DISCONNECTED = 1;
  public static final int RECONNECTING = 2;

  // If there has been a failure, try reconnecting
  // at least every MAX_RETRY_TIMEOUT seconds
  private int max_timeout_ = MAX_RETRY_TIMEOUT;

  // State of the handler
  private int state_ = DISCONNECTED;

  // Difference between the remote time and the local time.
  private long delta_ = 0;

  // Name of the remote host
  private String hostname_;

  // Port used for the connection
  private int port_;

  // Current timer interval
  private int timeout_;

  // Reference to the Clerk Processor's timer queue
  private TimerQueue tq_;

  // Message to send for a time update
  private String sendMsg_;

  // ID of the handler in the queue
  private int timerId_;

  // Desired time interval to receive updates
  private int initialTimeout_;

}