aboutsummaryrefslogtreecommitdiffstats
path: root/client/src/main/java/org/onap/aaf/cadi/dme2/DME2Locator.java
blob: 47af9ea5efac1d0d444629dc733c7517a7dbc6d5 (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
/*******************************************************************************
 * ============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 org.onap.aaf.cadi.dme2;


import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Random;

import org.onap.aaf.cadi.Access;
import org.onap.aaf.cadi.Locator;
import org.onap.aaf.cadi.LocatorException;
import org.onap.aaf.cadi.Access.Level;

//
import com.att.aft.dme2.api.DME2Exception;
import com.att.aft.dme2.api.DME2Manager;
import com.att.aft.dme2.api.DME2Server;
import com.att.aft.dme2.manager.registry.DME2Endpoint;

public class DME2Locator implements Locator {
	private DME2Manager dm;
	private DME2Endpoint[] endpoints;
	private Access access;
	private String service;
	private String version;
	private String routeOffer;
	private String envContext;
	private String thisMachine;
	private String pathInfo;
	private int thisPort;
	private boolean removeSelf;
	private final static Random random = new Random();

	// Default is to not bother trying to remove self
	public DME2Locator(Access access, DME2Manager dm, String service, String version, String envContext, String routeOffer) throws DME2Exception, UnknownHostException, LocatorException {
		this(access,dm,service,version,envContext,routeOffer,false);
	}
	
	public DME2Locator(Access access, DME2Manager dm, String service, String version, String envContext, String routeOffer, boolean removeSelf) throws DME2Exception, UnknownHostException, LocatorException {
		this.access = access;
		if(dm==null) {
			this.dm = new DME2Manager("DME2Locator created DME2Manager",System.getProperties());
		} else {
			this.dm = dm;
		}
		this.service = service;
		this.version = version;
		this.envContext = envContext;
		this.routeOffer = routeOffer;
		refresh();
		DME2Server server = dm.getServer(); 
		if(server == null) {
			thisMachine = InetAddress.getLocalHost().getHostName();
			thisPort = 0;
		} else {
			try {
				thisMachine = server.getServerProperties().getHostname();
				//thisPort = server.getPort();
				thisPort = server.getServerProperties().getPort();
			} catch(NullPointerException np) { // BAD BOY, DME2...
				access.log(Level.ERROR, "WARNING: DME2 threw a NullPointer Exception getting Server Machine and Port");
				thisMachine = InetAddress.getLocalHost().getHostName();
				thisPort = 0;
			}
		}
		this.removeSelf = removeSelf;
	}

	// Default is to not bother trying to remove self
	public DME2Locator(Access access, DME2Manager dm, String aafurl) throws DME2Exception, UnknownHostException, LocatorException {
		this(access,dm,aafurl,false);
	}
	
	public DME2Locator(Access access, DME2Manager dm, String aafurl, boolean removeSelf) throws DME2Exception, UnknownHostException, LocatorException {
		if(aafurl==null) throw new LocatorException("URL is null");
		this.access = access;
		if(dm==null) {
			dm = this.dm = new DME2Manager("DME2Locator created DME2Manager",System.getProperties());
		} else {
			this.dm = dm;
		}
		String[] split = aafurl.split("/");
		StringBuilder sb = new StringBuilder();
		boolean dme2Entered = false;
		for(String s : split) {
			if(s.startsWith(     "service=")) this.service = s.substring(8);
			else if(s.startsWith("version=")) this.version = s.substring(8);
			else if(s.startsWith("envContext=")) this.envContext = s.substring(11);
			else if(s.startsWith("routeOffer=")) {
				this.routeOffer = s.substring(11);
				dme2Entered = true;
			}
			else if(dme2Entered) {
				sb.append('/');
				sb.append(s);
			}
			pathInfo = sb.toString();
		}
		DME2Server server = dm.getServer(); 
		if(server == null) {
			thisMachine = InetAddress.getLocalHost().getHostName();
			thisPort = 0;
		} else {
			thisMachine = server.getServerProperties().getHostname();
			if(thisMachine==null) { // even if server !=null, apparently, it can be uninitialized
				thisMachine = InetAddress.getLocalHost().getHostName();
				thisPort = 0;
			} else {
				try {
					thisPort = server.getServerProperties().getPort();
				} catch (Exception e) {
					thisPort = 0;
				}
			}			
		}
		this.removeSelf=removeSelf;
		refresh();
	}
	
	@Override
	public boolean refresh() {
		try {
			dm.refresh();
			endpoints = dm.findEndpoints(service, version, envContext, routeOffer, true);
			if(removeSelf) {
				for(int i=0;i<endpoints.length;++i) {
					if(endpoints[i].getPort()==thisPort && endpoints[i].getHost().equals(thisMachine))
						endpoints[i]=null;
				}
			}
			return endpoints.length!=0;
		} catch (Exception e) {
			access.log(Level.ERROR, e.getMessage());
		}
		return false;
	}

	private String noEndpointsString() {
		StringBuilder sb = new StringBuilder("No DME2 Endpoints found for ");
		sb.append(service);
		sb.append('/');
		sb.append(version);
		sb.append('/');
		sb.append(envContext);
		sb.append('/');
		sb.append(routeOffer);
		return sb.toString();
	}

	@Override
	public URI get(Locator.Item item) throws LocatorException {
		if(!hasItems()) 
			throw new LocatorException(noEndpointsString());
		if(item == null) 
			return null;

		Item li = ((Item)item);
		// if URI has been created, use it
		if(li.uri!=null)return li.uri;
	
		// URI not created, create it
		if(li.idx<endpoints.length) {
			DME2Endpoint de = endpoints[li.idx];
			if(de!=null) {
				try {
					return li.uri=new URI(de.getProtocol(),null,de.getHost(),de.getPort(),pathInfo,null,null);
				} catch (URISyntaxException e) {
					throw new LocatorException(e);
				}
			}
		}
		return null;
	}
	
	@Override
	public boolean hasItems() {
		return endpoints!=null && endpoints.length>0;
	}

	@Override
	public void invalidate(Locator.Item item) throws LocatorException {
		if(item instanceof Item) {
			int idx = ((Item)item).idx;
			if(idx<endpoints.length) {
				DME2Endpoint uhoh = endpoints[idx]; // Sometimes, DME2Endpoint, at least on File system, returns bogus entries.
				endpoints[idx]=null;
				boolean noneLeft=true;
				for(int i=0;i<endpoints.length && noneLeft;++i) {
					noneLeft = endpoints[i]==null;
				}
				if(noneLeft && refresh()) { // make sure DME2 isn't giving us the same invalidated entry...
					for(int i=0;i<endpoints.length && noneLeft;++i) {
						DME2Endpoint ep = endpoints[i];
						if(ep != null && 
						   ep.getHost().equals(uhoh.getHost()) &&
						   ep.getPort()==uhoh.getPort()) {
							 endpoints[i]=null;
						}
					}
				}
				
			}
		}
	}

	public class Item implements Locator.Item {
		private final int idx;
		private URI uri;
		private Item(int i) {
			idx = i;
			uri = null;
		}
	}

	@Override
	public Item best() throws LocatorException {
		if(!hasItems()) // checks endpoints
			if(!refresh()) throw new LocatorException("No DME2 Endpoints Available");
		
		// Some endpoints in Array are null.  Need sub array of usable endpoints
		int usable[] = new int[endpoints.length];
		int count=0;
		for(int i=0;i<endpoints.length;++i) {
			if(endpoints[i]!=null) {
				usable[count++] = i;
			}
		}
		switch(count) {
			case 0: refresh(); return null;
			case 1: return new Item(usable[0]);
			default:
				int samemach[] = new int[count];
				int samecount = 0,closecount=0;
				// has to be sortable
				Integer closemach[] = new Integer[count];
				
				// Analyze for Same Machine or Remote machines
				for(int i=0;i<count;++i) {
					DME2Endpoint ep = endpoints[usable[i]];
					String host = ep.getHost();
					if(thisMachine.equalsIgnoreCase(host)) {
						samemach[samecount++] = usable[i];
					} else {
						closemach[closecount++] = usable[i];
					}
				}
				
				switch(samecount) {
					case 0: break;
					case 1: return new Item(samemach[0]);
					default: // return randomized is multiple Endpoints on local machine.
						int i = random.nextInt();
						return new Item(usable[Math.abs(i%samecount)]);
				}
				
				// Analyze for closest remote
				switch(closecount) {
					case 0:	return null;
					case 1: return new Item(closemach[0]);
					default: // return closest machine
						DoubIndex remote[] = new DoubIndex[closecount];
						int remotecount = 0;
						for(int i=0;i<closecount;++i) {
							DME2Endpoint de = endpoints[usable[i]];
							remote[remotecount++] = new DoubIndex(de.getDistance(),i);
						}
						Arrays.sort(remote,new Comparator<DoubIndex> () {
							@Override
							public int compare(DoubIndex a, DoubIndex b) {
								if(a.d<b.d) return -1;
								if(a.d>b.d) return 1;
								return (random.nextInt()%1)==0?1:0;// randomize if the same
							}
							
						});
						return new Item(remote[0].idx);
				}
		}
	}
	
	private class DoubIndex {
		public final double d;
		public final int idx;
		
		public DoubIndex(double doub, int i) {
			d = doub;
			idx = i;
		}
	}
	@Override
	public Item first() {
		if(endpoints==null)return null;
		for(int i=0;i<endpoints.length;++i) {
			if(endpoints[i]!=null)
				return new Item(i); 
		}
		return null;
	}

	@Override
	public Item next(Locator.Item item) throws LocatorException {
		if(endpoints==null || endpoints.length==0 || !(item instanceof Item))return null;
		int idx = ((Item)item).idx +1;
		for(int i=idx;i<endpoints.length;++i) {
			if(endpoints[i]!=null)
				return new Item(i); 
		}
// This is a mistake..  will start infinite loops
//		// Did not have any at end... try beginning
//		for(int i=0;i<idx-1;++i) {
//			if(endpoints[i]!=null)
//				return new Item(i); 
//		}
//		// If still nothing, refresh
//		refresh();
		return null;
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}
}