summaryrefslogtreecommitdiffstats
path: root/client/src/main/java/com/att/cadi/locator/HotPeerLocator.java
blob: 5b756b21ef57dcfa0cf19bb8fc2be8bc84c9e56d (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
/*******************************************************************************
 * ============LICENSE_START====================================================
 * * org.onap.aaf
 * * ===========================================================================
 * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
 * * ===========================================================================
 * * Licensed under the Apache License, Version 2.0 (the "License");
 * * you may not use this file except in compliance with the License.
 * * You may obtain a copy of the License at
 * * 
 *  *      http://www.apache.org/licenses/LICENSE-2.0
 * * 
 *  * Unless required by applicable law or agreed to in writing, software
 * * distributed under the License is distributed on an "AS IS" BASIS,
 * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * * See the License for the specific language governing permissions and
 * * limitations under the License.
 * * ============LICENSE_END====================================================
 * *
 * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
 * *
 ******************************************************************************/
package com.att.cadi.locator;

import com.att.cadi.Access;
import com.att.cadi.Access.Level;
import com.att.cadi.Locator;
import com.att.cadi.LocatorException;
import com.att.cadi.routing.GreatCircle;
import com.att.inno.env.util.Split;

/**
 * This Locator is to handle Hot Peer load protection, when the Servers are 
 * 	1) Static
 * 	2) Well known client URL
 * 
 * The intention is to change traffic over to the Hot Peer, if a server goes down, and reinstate
 * when it is back up.
 * 
 * Example of this kind of Service is a MS Certificate Server
 * 
 *
 *
 * @param <CLIENT>
 */
public abstract class HotPeerLocator<CLIENT> implements Locator<CLIENT> {
		private final String[] urlstrs;
		private final CLIENT[] clients;
		private final long[] failures;
		private final double[] distances;
		private int preferred;
		private long invalidateTime;
		private Thread refreshThread;
		protected Access access;

		/**
		 * Construct:  Expect one or more Strings in the form:
		 * 		192.555.112.223:39/38.88087/-77.30122
		 *    separated by commas
		 * 
		 * @param trans
		 * @param urlstr
		 * @param invalidateTime
		 * @param localLatitude
		 * @param localLongitude
		 * @throws LocatorException
		 */
		@SuppressWarnings("unchecked")
		protected HotPeerLocator(Access access, final String urlstr, final long invalidateTime, final String localLatitude, final String localLongitude) throws LocatorException {
			this.access = access;
	 		urlstrs = Split.split(',', urlstr);
	 		clients = (CLIENT[])new Object[urlstrs.length];
	 		failures = new long[urlstrs.length];
	 		distances= new double[urlstrs.length];
	 		this.invalidateTime = invalidateTime;
	 		
	 		double distance = Double.MAX_VALUE;
	 		for(int i=0;i<urlstrs.length;++i) {
	 			String[] info = Split.split('/', urlstrs[i]);
	 			if(info.length<3) {
	 				throw new LocatorException("Configuration needs LAT and LONG, i.e. ip:port/lat/long");
	 			}
	 			try {
	 				clients[i] = _newClient(urlstrs[i]);
	 				failures[i] = 0L;
	 			} catch(LocatorException le) {
	 				failures[i] = System.currentTimeMillis()+invalidateTime;
	 			}
	 			
	 			double d = GreatCircle.calc(info[1],info[2],localLatitude,localLongitude);
	 			distances[i]=d;
	 			
	 			// find preferred server
	 			if(d<distance) {
	 				preferred = i;
	 				distance=d;
	 			}
	 		}
	 		
	 		access.printf(Level.INIT,"Preferred Client is %s",urlstrs[preferred]);
	 		for(int i=0;i<urlstrs.length;++i) {
	 			if(i!=preferred) {
	 				access.printf(Level.INIT,"Alternate Client is %s",urlstrs[i]);
	 			}
	 		}
		}
		
		protected abstract CLIENT _newClient(String hostInfo) throws LocatorException;
		/**
		 * If client can reconnect, then return.  Otherwise, destroy and return null;
		 * @param client
		 * @return
		 * @throws LocatorException
		 */
		protected abstract CLIENT _invalidate(CLIENT client);
		
		protected abstract void _destroy(CLIENT client);
		
		@Override
		public Item best() throws LocatorException {
			if(failures[preferred]==0L) {
				return new HPItem(preferred);
			} else {
				long now = System.currentTimeMillis();
				double d = Double.MAX_VALUE;
				int best = -1;
				boolean tickle = false;
				// try for best existing client
				for(int i=0;i<urlstrs.length;++i) {
					if(failures[i]<now && distances[i]<d) {
						if(clients[i]!=null) {
							best = i;
							break;
						} else {
							tickle = true; // There's some failed clients which can be restored
						}
					}
				}
				if(best<0 && tickle) {
					tickle=false;
					if(refresh()) {
						// try again
						for(int i=0;i<urlstrs.length;++i) {
							if(failures[i]==0L && distances[i]<d) {
								if(clients[i]!=null) {
									best = i;
									break;
								}
							}
						}
					}
				}
			
				/*
				 * If a valid client is available, but there are some that can refresh, return the client immediately
				 * but start a Thread to do the background Client setup.
				 */
				if(tickle) {
					synchronized(clients) {
						if(refreshThread==null) {
							refreshThread = new Thread(new Runnable(){
								@Override
								public void run() {
									refresh();
									refreshThread = null;
								}
							});
							refreshThread.setDaemon(true);
							refreshThread.start();
						}
					}
				}
				
				if(best<0) {
					throw new LocatorException("No Clients available");
				}

				
				return new HPItem(best);
			}
		}
		

		@Override
		public CLIENT get(Item item) throws LocatorException {
			HPItem hpi = (HPItem)item;
			CLIENT c = clients[hpi.idx];
			if(c==null) {
				if(failures[hpi.idx]>System.currentTimeMillis()) {
					throw new LocatorException("Client requested is invalid");	
				} else {
					synchronized(clients) {
						c = _newClient(urlstrs[hpi.idx]);
						failures[hpi.idx]=0L;
					}
				}
			} else if(failures[hpi.idx]>0){
				throw new LocatorException("Client requested is invalid");
			}
			return c;
		}
		
		public String info(Item item) {
			HPItem hpi = (HPItem)item;
			if(hpi!=null && hpi.idx<urlstrs.length) {
				return urlstrs[hpi.idx];
			} else {
				return "Invalid Item";
			}
		}

		@Override
		public boolean hasItems() {
			for(int i=0;i<clients.length;++i) {
				if(clients[i]!=null && failures[i]==0L) {
					return true;
				}
			}
			return false;
		}
		
		@Override
		public synchronized void invalidate(Item item) throws LocatorException {
			HPItem hpi = (HPItem)item;
			failures[hpi.idx] = System.currentTimeMillis() + invalidateTime;
			CLIENT c = clients[hpi.idx];
			clients[hpi.idx] = _invalidate(c);
		}
		
		@Override
		public Item first() throws LocatorException {
			return new HPItem(0);
		}
		
		@Override
		public Item next(Item item) throws LocatorException {
			HPItem hpi = (HPItem)item;
			if(++hpi.idx>=clients.length) {
				return null;
			}
			return hpi;
		}
		
		@Override
		public boolean refresh() {
			boolean force = !hasItems(); // If no Items at all, reset
			boolean rv = true;
			long now = System.currentTimeMillis();
			for(int i=0;i<clients.length;++i) {
				if(failures[i]>0L && (failures[i]<now || force)) { // retry
					try {
						synchronized(clients) {
							if(clients[i]==null) {
								clients[i]=_newClient(urlstrs[i]);
							}
							failures[i]=0L;
						}
					} catch (LocatorException e) {
						failures[i]=now+invalidateTime;
						rv = false;
					}
				}
			}
			return rv;
		}
		
		@Override
		public void destroy() {
			for(int i=0;i<clients.length;++i) {
				if(clients[i]!=null) {
					_destroy(clients[i]);
					clients[i] = null;
				}
			}
		}

		private static class HPItem implements Item {
			private int idx;

			public HPItem(int i) {
				idx = i;
			}
		}
		

		/*
		 * Convenience Functions
		 */
		public CLIENT bestClient() throws LocatorException {
			return get(best());
		}

		public boolean invalidate(CLIENT client) throws LocatorException {
			for(int i=0;i<clients.length;++i) {
				if(clients[i]==client) { // yes, "==" is appropriate here.. Comparing Java Object Reference
					invalidate(new HPItem(i));
					return true;
				}
			}
			return false;
		}

	}