Configuration and Auto-Certificates
[aaf/authz.git] / cadi / aaf / src / main / java / org / onap / aaf / cadi / aaf / v2_0 / AbsAAFLocator.java
1 /**
2  * ============LICENSE_START====================================================
3  * org.onap.aaf
4  * ===========================================================================
5  * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
6  * ===========================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END====================================================
19  *
20  */
21
22 package org.onap.aaf.cadi.aaf.v2_0;
23
24 import java.net.URI;
25 import java.net.URISyntaxException;
26 import java.security.SecureRandom;
27 import java.util.ArrayList;
28 import java.util.Iterator;
29 import java.util.LinkedList;
30 import java.util.List;
31 import java.util.NoSuchElementException;
32
33 import org.onap.aaf.cadi.Access;
34 import org.onap.aaf.cadi.Access.Level;
35 import org.onap.aaf.cadi.aaf.Defaults;
36 import org.onap.aaf.cadi.Locator;
37 import org.onap.aaf.cadi.LocatorException;
38 import org.onap.aaf.cadi.config.Config;
39 import org.onap.aaf.cadi.locator.PropertyLocator;
40 import org.onap.aaf.cadi.routing.GreatCircle;
41 import org.onap.aaf.misc.env.Trans;
42 import org.onap.aaf.misc.env.util.Split;
43
44 import locate.v1_0.Endpoint;
45
46 public abstract class AbsAAFLocator<TRANS extends Trans> implements Locator<URI> {
47         protected static final SecureRandom sr = new SecureRandom();
48         private static LocatorCreator locatorCreator;
49         protected final Access access;
50
51         protected final double latitude;
52         protected final double longitude;
53         protected List<EP> epList;
54         protected final String name, version;
55         private String pathInfo = null;
56         private String query = null;
57         private String fragment = null;
58         private boolean additional = false;
59         protected String myhostname;
60         protected int myport;
61         protected final String aaf_locator_host;
62         protected final URI aaf_locator_uri;
63         private long earliest;
64         private final long refreshWait;
65
66
67         public AbsAAFLocator(Access access, String name, final long refreshMin) throws LocatorException {
68                 aaf_locator_host = access.getProperty(Config.AAF_LOCATE_URL, null);
69                 if(aaf_locator_host==null) {
70                         aaf_locator_uri = null;
71                 } else {
72                         try {
73                                 aaf_locator_uri = new URI(aaf_locator_host);
74                         } catch (URISyntaxException e) {
75                                 throw new LocatorException(e);
76                         }
77                 }
78
79                 epList = new LinkedList<>();
80                 refreshWait = refreshMin;
81
82                 this.access = access;
83                 String lat = access.getProperty(Config.CADI_LATITUDE,null);
84                 String lng = access.getProperty(Config.CADI_LONGITUDE,null);
85                 if(lat==null || lng==null) {
86                         throw new LocatorException(Config.CADI_LATITUDE + " and " + Config.CADI_LONGITUDE + " properties are required.");
87                 } else {
88                         latitude = Double.parseDouble(lat);
89                         longitude = Double.parseDouble(lng);
90                 }
91                 if(name.startsWith(Defaults.AAF_NS)) {
92                         String root_ns = access.getProperty(Config.AAF_ROOT_NS, null);
93                         if(root_ns!=null) {
94                                 name=name.replace(Defaults.AAF_NS, root_ns);
95                         }
96                 }
97                 if(name.startsWith("http")) { // simple URL
98                         this.name = name;
99                         this.version = Config.AAF_DEFAULT_VERSION;
100                 } else {
101                         String[] split = Split.split(':', name);
102                         this.name = split[0];
103                         this.version = (split.length > 1) ? split[1] : Config.AAF_DEFAULT_VERSION;
104                 }
105                 
106         }
107
108         /**
109          * This is the way to setup specialized AAFLocators ahead of time.
110          * @param preload
111          */
112         public static void setCreator(LocatorCreator lc) {
113                 locatorCreator = lc; 
114         }
115         
116         public static Locator<URI> create(String key) throws LocatorException {
117                 String name = null;
118                 String version = Config.AAF_DEFAULT_VERSION;
119                 String pathInfo = null;
120                 int prev = key.indexOf("/locate");
121                 if(prev>0) {
122                         prev = key.indexOf('/',prev+6);
123                         if(prev>0) {
124                                 int next = key.indexOf('/',++prev);
125                                 if(next>0) {
126                                         name = key.substring(prev, next);
127                                         pathInfo=key.substring(next);
128                                 } else {
129                                         name = key.substring(prev);
130                                 }
131                                 String[] split = Split.split(':', name);
132                                 switch(split.length) {
133                                         case 3:
134                                         case 2:
135                                                 version = split[1];
136                                                 name = split[0];
137                                                 break;
138                                 }
139                         }
140                 }
141
142                 if(key.startsWith("http")) {
143                         if(name!=null) {
144                                 if(locatorCreator != null) {
145                                         AbsAAFLocator<?> aal = locatorCreator.create(name, version);
146                                         if(pathInfo!=null) {
147                                                 aal.setPathInfo(pathInfo);
148                                         }
149                                         return aal;
150                                 }
151                         } else {
152                                 return new PropertyLocator(key);
153                         }
154                 }
155                 return null;
156         }
157         
158         public static Locator<URI> create(final String name, final String version) throws LocatorException {
159                 return locatorCreator.create(name, version);
160         }
161
162         public interface LocatorCreator {
163                 public AbsAAFLocator<?> create(String key, String version) throws LocatorException;
164                 public void setSelf(String hostname, int port);
165         }
166
167         protected static String nameFromLocatorURI(URI locatorURI) {
168                 String[] path = Split.split('/', locatorURI.getPath());
169                 if(path.length>2 && "locate".equals(path[1])) {
170                         return path[2];
171                 } else {
172                         return locatorURI.toString();
173                 }
174         }
175         
176         /**
177          * Setting "self" excludes this service from the list.  Critical for contacting peers. 
178          */
179         public void setSelf(final String hostname, final int port) {
180                 myhostname=hostname;
181                 myport=port;
182         }
183
184
185         public static void setCreatorSelf(final String hostname, final int port) {
186                 if(locatorCreator!=null) {
187                         locatorCreator.setSelf(hostname,port);
188                 }
189         }
190
191         protected final synchronized void replace(List<EP> list) {
192                 epList = list;
193         }
194         
195         /**
196          * Call _refresh as needed during calls, but actual refresh will not occur if there
197          * are existing entities or if it has been called in the last 10 (settable) seconds.  
198          * Timed Refreshes happen by Scheduled Thread
199          */
200         private final boolean _refresh() {
201                 boolean rv = false;
202                 long now=System.currentTimeMillis();
203                 if(noEntries()) {
204                         if(earliest<now) {
205                                 synchronized(epList) {
206                                         rv = refresh();
207                                         earliest = now + refreshWait; // call only up to 10 seconds.
208                                 }
209                         } else {
210                                 access.log(Level.ERROR, "Must wait at least " + refreshWait/1000 + " seconds for Locator Refresh");
211                         }
212                 }
213                 return rv;
214         }
215
216         private boolean noEntries() {
217                 return epList.size()<=0;
218         }
219
220         @Override
221         public URI get(Item item) throws LocatorException {
222                 if(item==null) {
223                         return null;
224                 } else if(item instanceof AAFLItem) {
225                         return getURI(((AAFLItem)item).uri);
226                 } else {
227                         throw new LocatorException(item.getClass().getName() + " does not belong to AAFLocator");
228                 }
229         }
230
231         @Override
232         public boolean hasItems() {
233                 boolean isEmpty = epList.isEmpty();
234                 if(!isEmpty) {
235                         for(Iterator<EP> iter = epList.iterator(); iter.hasNext(); ) {
236                                 EP ep = iter.next();
237                                 if(ep.valid) {
238                                         return true;
239                                 }
240                         }
241                         isEmpty = true;
242                 }
243                 if(_refresh()) { // is refreshed... check again
244                         isEmpty = epList.isEmpty();
245                 }
246                 return !isEmpty;
247         }
248
249         @Override
250         public void invalidate(Item item) throws LocatorException {
251                 if(item!=null) {
252                         if(item instanceof AAFLItem) {
253                                 AAFLItem ali =(AAFLItem)item; 
254                                 EP ep = ali.ep;
255                                 synchronized(epList) {
256                                         epList.remove(ep);
257                                 }
258                                 ep.invalid();
259                                 ali.iter = getIterator(); // for next guy... fresh iterator
260                         } else {
261                                 throw new LocatorException(item.getClass().getName() + " does not belong to AAFLocator");
262                         }
263                 }
264         }
265
266         @Override
267         public Item best() throws LocatorException {
268                 if(!hasItems()) {
269                         throw new LocatorException("No Entries found for '" + aaf_locator_uri.toString() + "/locate/" + name + ':' + version + '\'');
270                 }
271                 List<EP> lep = new ArrayList<>();
272                 EP first = null;
273                 // Note: Deque is sorted on the way by closest distance
274                 Iterator<EP> iter = getIterator();
275                 EP ep;
276                 while(iter.hasNext()) {
277                         ep = iter.next();
278                         if(ep.valid) {
279                                 if(first==null) {
280                                         first = ep;
281                                         lep.add(first);
282                                 } else {
283                                         if(Math.abs(ep.distance-first.distance)<.1) { // allow for nearby/precision issues.
284                                                 lep.add(ep);
285                                         } else {
286                                                 break;
287                                         }
288                                 }
289                         }
290                 }
291                 switch(lep.size()) {
292                         case 0:
293                                 return null;
294                         case 1:
295                                 return new AAFLItem(iter,first);
296                         default:
297                                 int rand = sr.nextInt(); // Sonar chokes without.
298                                 int i = Math.abs(rand)%lep.size();
299                                 if(i<0) {
300                                         return null;
301                                 } else {
302                                         return new AAFLItem(iter,lep.get(i));
303                                 }
304                         
305                 }
306         }
307
308         private Iterator<EP> getIterator() {
309                 Object[] epa = epList.toArray();
310                 if(epa.length==0) {
311                         _refresh();
312                         epa = epList.toArray();
313                 }
314                 return new EPIterator(epa, epList);
315         }
316
317         public class EPIterator implements Iterator<EP> {
318                 private final Object[] epa;
319                 private final List<EP> epList;
320                 private int idx;
321                 
322                 public EPIterator(Object[] epa, List<EP> epList) {
323                         this.epa = epa;
324                         this.epList = epList;
325                         idx = epa.length>0?0:-1;
326                 }
327
328                 @Override
329                 public boolean hasNext() {
330                         if(idx<0) {
331                                 return false;
332                         } else {
333                                 Object obj;
334                                 while(idx<epa.length) {
335                                         if((obj=epa[idx])==null || !((EP)obj).valid) {
336                                                 ++idx;
337                                                 continue;
338                                         }
339                                         break;
340                                 }
341                                 return idx<epa.length;
342                         }
343                 }
344
345                 @Override
346                 public EP next() {
347                         if(!hasNext() ) {
348                                 throw new NoSuchElementException();
349                         }
350                         return (EP)epa[idx++];
351                 }
352
353                 @Override
354                 public void remove() {
355                         if(idx>=0 && idx<epa.length) {
356                                 synchronized(epList) {
357                                         epList.remove(epa[idx]);
358                                 }
359                         }
360                 }
361         }
362         
363         @Override
364         public Item first()  {
365                 Iterator<EP> iter = getIterator();
366                 EP ep = AAFLItem.next(iter);
367                 if(ep==null) {
368                         return null;
369                 }
370                 return new AAFLItem(iter,ep);
371         }
372
373         @Override
374         public Item next(Item prev) throws LocatorException {
375                 if(prev==null) {
376                         StringBuilder sb = new StringBuilder("Locator Item passed in next(item) is null.");
377                         int lines = 0;
378                         for(StackTraceElement st : Thread.currentThread().getStackTrace()) {
379                                 sb.append("\n\t");
380                                 sb.append(st.toString());
381                                 if(++lines > 5) {
382                                         sb.append("\n\t...");
383                                         break;
384                                 }
385                         }
386                         access.log(Level.ERROR, sb);
387                 } else {
388                         if(prev instanceof AAFLItem) {
389                                 AAFLItem ali = (AAFLItem)prev;
390                                 EP ep = AAFLItem.next(ali.iter);
391                                 if(ep!=null) {
392                                         return new AAFLItem(ali.iter,ep);
393                                 }
394                         } else {
395                                 throw new LocatorException(prev.getClass().getName() + " does not belong to AAFLocator");
396                         }
397                 }
398                 return null;
399         }
400
401         protected static class AAFLItem implements Item {
402                         private Iterator<EP> iter;
403                         private URI uri;
404                         private EP ep;
405         
406                         public AAFLItem(Iterator<EP> iter, EP ep) {
407                                 this.iter = iter;
408                                 this.ep = ep;
409                                 uri = ep.uri;
410                         }
411                         
412                         private static EP next(Iterator<EP> iter) {
413                                 EP ep=null;
414                                 while(iter.hasNext() && (ep==null || !ep.valid)) {
415                                         ep = iter.next();
416                                 }
417                                 return ep;
418                         }
419                         
420                         public String toString() {
421                                 return ep==null?"Locator Item Invalid":ep.toString();
422                         }
423                 }
424
425         protected static class EP implements Comparable<EP> {
426                 public URI uri;
427                 public final double distance;
428                 private boolean valid;
429                 
430                 public EP(final Endpoint ep, double latitude, double longitude) throws URISyntaxException {
431                         uri = new URI(ep.getProtocol(),null,ep.getHostname(),ep.getPort(),null,null,null);
432                         distance = GreatCircle.calc(latitude, longitude, ep.getLatitude(), ep.getLongitude());
433                         valid = true;
434                 }
435
436                 public void invalid() {
437                         valid = false;
438                 }
439
440                 @Override
441                 public int compareTo(EP o) {
442                         if(distance<o.distance) {
443                                 return -1;
444                         } else if(distance>o.distance) {
445                                 return 1;
446                         } else {
447                                 return 0;
448                         }
449                 }
450                 
451                 @Override
452                 public String toString() {
453                         return distance + ": " + uri + (valid?" valid":" invalidate");
454                 }
455         }
456         
457         /* (non-Javadoc)
458          * @see org.onap.aaf.cadi.Locator#destroy()
459          */
460         @Override
461         public void destroy() {
462                 // Nothing to do
463         }
464         
465         @Override
466         public String toString() {
467                 return "AAFLocator for " + name + " on " + getURI();
468         }
469
470         public AbsAAFLocator<TRANS> setPathInfo(String pathInfo) {
471                 this.pathInfo = pathInfo;
472                 additional=true;
473                 return this;
474         }
475
476         public AbsAAFLocator<TRANS> setQuery(String query) {
477                 this.query = query;
478                 additional=true;
479                 return this;
480         }
481
482         public AbsAAFLocator<TRANS>  setFragment(String fragment) {
483                 this.fragment = fragment;
484                 additional=true;
485                 return this;
486         }
487
488         // Core URI, for reporting purposes
489         protected abstract URI getURI();
490
491         protected URI getURI(URI rv) throws LocatorException {
492                 if(additional) {
493                         try {
494                                 return new URI(rv.getScheme(),rv.getUserInfo(),rv.getHost(),rv.getPort(),pathInfo,query,fragment);
495                         } catch (URISyntaxException e) {
496                                 throw new LocatorException("Error copying URL");
497                         }
498                 }
499                 return rv;
500         }
501
502
503 }