001package ca.uhn.fhir.interceptor.executor; 002 003/*- 004 * #%L 005 * HAPI FHIR - Core Library 006 * %% 007 * Copyright (C) 2014 - 2020 University Health Network 008 * %% 009 * Licensed under the Apache License, Version 2.0 (the "License"); 010 * you may not use this file except in compliance with the License. 011 * You may obtain a copy of the License at 012 * 013 * http://www.apache.org/licenses/LICENSE-2.0 014 * 015 * Unless required by applicable law or agreed to in writing, software 016 * distributed under the License is distributed on an "AS IS" BASIS, 017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 018 * See the License for the specific language governing permissions and 019 * limitations under the License. 020 * #L% 021 */ 022 023import ca.uhn.fhir.interceptor.api.Hook; 024import ca.uhn.fhir.interceptor.api.HookParams; 025import ca.uhn.fhir.interceptor.api.IAnonymousInterceptor; 026import ca.uhn.fhir.interceptor.api.IInterceptorBroadcaster; 027import ca.uhn.fhir.interceptor.api.IInterceptorService; 028import ca.uhn.fhir.interceptor.api.Interceptor; 029import ca.uhn.fhir.interceptor.api.Pointcut; 030import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; 031import com.google.common.annotations.VisibleForTesting; 032import com.google.common.collect.ArrayListMultimap; 033import com.google.common.collect.ListMultimap; 034import com.google.common.collect.Multimaps; 035import org.apache.commons.lang3.Validate; 036import org.apache.commons.lang3.builder.ToStringBuilder; 037import org.apache.commons.lang3.builder.ToStringStyle; 038import org.apache.commons.lang3.reflect.MethodUtils; 039import org.slf4j.Logger; 040import org.slf4j.LoggerFactory; 041 042import javax.annotation.Nonnull; 043import javax.annotation.Nullable; 044import java.lang.annotation.Annotation; 045import java.lang.reflect.AnnotatedElement; 046import java.lang.reflect.InvocationTargetException; 047import java.lang.reflect.Method; 048import java.util.*; 049import java.util.concurrent.atomic.AtomicInteger; 050import java.util.function.Predicate; 051import java.util.stream.Collectors; 052 053public class InterceptorService implements IInterceptorService, IInterceptorBroadcaster { 054 private static final Logger ourLog = LoggerFactory.getLogger(InterceptorService.class); 055 private final List<Object> myInterceptors = new ArrayList<>(); 056 private final ListMultimap<Pointcut, BaseInvoker> myGlobalInvokers = ArrayListMultimap.create(); 057 private final ListMultimap<Pointcut, BaseInvoker> myAnonymousInvokers = ArrayListMultimap.create(); 058 private final Object myRegistryMutex = new Object(); 059 private final ThreadLocal<ListMultimap<Pointcut, BaseInvoker>> myThreadlocalInvokers = new ThreadLocal<>(); 060 private String myName; 061 private boolean myThreadlocalInvokersEnabled = true; 062 063 /** 064 * Constructor which uses a default name of "default" 065 */ 066 public InterceptorService() { 067 this("default"); 068 } 069 070 /** 071 * Constructor 072 * 073 * @param theName The name for this registry (useful for troubleshooting) 074 */ 075 public InterceptorService(String theName) { 076 super(); 077 myName = theName; 078 } 079 080 /** 081 * Are threadlocal interceptors enabled on this registry (defaults to true) 082 */ 083 public boolean isThreadlocalInvokersEnabled() { 084 return myThreadlocalInvokersEnabled; 085 } 086 087 /** 088 * Are threadlocal interceptors enabled on this registry (defaults to true) 089 */ 090 public void setThreadlocalInvokersEnabled(boolean theThreadlocalInvokersEnabled) { 091 myThreadlocalInvokersEnabled = theThreadlocalInvokersEnabled; 092 } 093 094 @VisibleForTesting 095 List<Object> getGlobalInterceptorsForUnitTest() { 096 return myInterceptors; 097 } 098 099 @Override 100 @VisibleForTesting 101 public void registerAnonymousInterceptor(Pointcut thePointcut, IAnonymousInterceptor theInterceptor) { 102 registerAnonymousInterceptor(thePointcut, Interceptor.DEFAULT_ORDER, theInterceptor); 103 } 104 105 public void setName(String theName) { 106 myName = theName; 107 } 108 109 @Override 110 public void registerAnonymousInterceptor(Pointcut thePointcut, int theOrder, IAnonymousInterceptor theInterceptor) { 111 Validate.notNull(thePointcut); 112 Validate.notNull(theInterceptor); 113 synchronized (myRegistryMutex) { 114 115 myAnonymousInvokers.put(thePointcut, new AnonymousLambdaInvoker(thePointcut, theInterceptor, theOrder)); 116 if (!isInterceptorAlreadyRegistered(theInterceptor)) { 117 myInterceptors.add(theInterceptor); 118 } 119 } 120 } 121 122 @Override 123 public List<Object> getAllRegisteredInterceptors() { 124 synchronized (myRegistryMutex) { 125 List<Object> retVal = new ArrayList<>(); 126 retVal.addAll(myInterceptors); 127 return Collections.unmodifiableList(retVal); 128 } 129 } 130 131 @Override 132 @VisibleForTesting 133 public void unregisterAllInterceptors() { 134 synchronized (myRegistryMutex) { 135 myAnonymousInvokers.clear(); 136 myGlobalInvokers.clear(); 137 myInterceptors.clear(); 138 } 139 } 140 141 @Override 142 public void unregisterInterceptors(@Nullable Collection<?> theInterceptors) { 143 if (theInterceptors != null) { 144 theInterceptors.forEach(t -> unregisterInterceptor(t)); 145 } 146 } 147 148 @Override 149 public void registerInterceptors(@Nullable Collection<?> theInterceptors) { 150 if (theInterceptors != null) { 151 theInterceptors.forEach(t -> registerInterceptor(t)); 152 } 153 } 154 155 @Override 156 public void unregisterInterceptorsIf(Predicate<Object> theShouldUnregisterFunction) { 157 unregisterInterceptorsIf(theShouldUnregisterFunction, myGlobalInvokers); 158 unregisterInterceptorsIf(theShouldUnregisterFunction, myAnonymousInvokers); 159 } 160 161 private void unregisterInterceptorsIf(Predicate<Object> theShouldUnregisterFunction, ListMultimap<Pointcut, BaseInvoker> theGlobalInvokers) { 162 theGlobalInvokers.entries().removeIf(t->theShouldUnregisterFunction.test(t.getValue().getInterceptor())); 163 } 164 165 @Override 166 public boolean registerThreadLocalInterceptor(Object theInterceptor) { 167 if (!myThreadlocalInvokersEnabled) { 168 return false; 169 } 170 ListMultimap<Pointcut, BaseInvoker> invokers = getThreadLocalInvokerMultimap(); 171 scanInterceptorAndAddToInvokerMultimap(theInterceptor, invokers); 172 return !invokers.isEmpty(); 173 174 } 175 176 @Override 177 public void unregisterThreadLocalInterceptor(Object theInterceptor) { 178 if (myThreadlocalInvokersEnabled) { 179 ListMultimap<Pointcut, BaseInvoker> invokers = getThreadLocalInvokerMultimap(); 180 invokers.entries().removeIf(t -> t.getValue().getInterceptor() == theInterceptor); 181 if (invokers.isEmpty()) { 182 myThreadlocalInvokers.remove(); 183 } 184 } 185 } 186 187 private ListMultimap<Pointcut, BaseInvoker> getThreadLocalInvokerMultimap() { 188 ListMultimap<Pointcut, BaseInvoker> invokers = myThreadlocalInvokers.get(); 189 if (invokers == null) { 190 invokers = Multimaps.synchronizedListMultimap(ArrayListMultimap.create()); 191 myThreadlocalInvokers.set(invokers); 192 } 193 return invokers; 194 } 195 196 @Override 197 public boolean registerInterceptor(Object theInterceptor) { 198 synchronized (myRegistryMutex) { 199 200 if (isInterceptorAlreadyRegistered(theInterceptor)) { 201 return false; 202 } 203 204 List<HookInvoker> addedInvokers = scanInterceptorAndAddToInvokerMultimap(theInterceptor, myGlobalInvokers); 205 if (addedInvokers.isEmpty()) { 206 ourLog.warn("Interceptor registered with no valid hooks - Type was: {}", theInterceptor.getClass().getName()); 207 return false; 208 } 209 210 // Add to the global list 211 myInterceptors.add(theInterceptor); 212 sortByOrderAnnotation(myInterceptors); 213 214 return true; 215 } 216 } 217 218 private boolean isInterceptorAlreadyRegistered(Object theInterceptor) { 219 for (Object next : myInterceptors) { 220 if (next == theInterceptor) { 221 return true; 222 } 223 } 224 return false; 225 } 226 227 @Override 228 public boolean unregisterInterceptor(Object theInterceptor) { 229 synchronized (myRegistryMutex) { 230 boolean removed = myInterceptors.removeIf(t -> t == theInterceptor); 231 removed |= myGlobalInvokers.entries().removeIf(t -> t.getValue().getInterceptor() == theInterceptor); 232 removed |= myAnonymousInvokers.entries().removeIf(t -> t.getValue().getInterceptor() == theInterceptor); 233 return removed; 234 } 235 } 236 237 private void sortByOrderAnnotation(List<Object> theObjects) { 238 IdentityHashMap<Object, Integer> interceptorToOrder = new IdentityHashMap<>(); 239 for (Object next : theObjects) { 240 Interceptor orderAnnotation = next.getClass().getAnnotation(Interceptor.class); 241 int order = orderAnnotation != null ? orderAnnotation.order() : 0; 242 interceptorToOrder.put(next, order); 243 } 244 245 theObjects.sort((a, b) -> { 246 Integer orderA = interceptorToOrder.get(a); 247 Integer orderB = interceptorToOrder.get(b); 248 return orderA - orderB; 249 }); 250 } 251 252 @Override 253 public Object callHooksAndReturnObject(Pointcut thePointcut, HookParams theParams) { 254 assert haveAppropriateParams(thePointcut, theParams); 255 assert thePointcut.getReturnType() != void.class; 256 257 return doCallHooks(thePointcut, theParams, null); 258 } 259 260 @Override 261 public boolean hasHooks(Pointcut thePointcut) { 262 return myGlobalInvokers.containsKey(thePointcut) 263 || myAnonymousInvokers.containsKey(thePointcut) 264 || hasThreadLocalHooks(thePointcut); 265 } 266 267 private boolean hasThreadLocalHooks(Pointcut thePointcut) { 268 ListMultimap<Pointcut, BaseInvoker> hooks = myThreadlocalInvokersEnabled ? myThreadlocalInvokers.get() : null; 269 return hooks != null && hooks.containsKey(thePointcut); 270 } 271 272 @Override 273 public boolean callHooks(Pointcut thePointcut, HookParams theParams) { 274 assert haveAppropriateParams(thePointcut, theParams); 275 assert thePointcut.getReturnType() == void.class || thePointcut.getReturnType() == boolean.class; 276 277 Object retValObj = doCallHooks(thePointcut, theParams, true); 278 return (Boolean) retValObj; 279 } 280 281 private Object doCallHooks(Pointcut thePointcut, HookParams theParams, Object theRetVal) { 282 List<BaseInvoker> invokers = getInvokersForPointcut(thePointcut); 283 284 /* 285 * Call each hook in order 286 */ 287 for (BaseInvoker nextInvoker : invokers) { 288 Object nextOutcome = nextInvoker.invoke(theParams); 289 Class<?> pointcutReturnType = thePointcut.getReturnType(); 290 if (pointcutReturnType.equals(boolean.class)) { 291 Boolean nextOutcomeAsBoolean = (Boolean) nextOutcome; 292 if (Boolean.FALSE.equals(nextOutcomeAsBoolean)) { 293 ourLog.trace("callHooks({}) for invoker({}) returned false", thePointcut, nextInvoker); 294 theRetVal = false; 295 break; 296 } 297 } else if (pointcutReturnType.equals(void.class) == false) { 298 if (nextOutcome != null) { 299 theRetVal = nextOutcome; 300 break; 301 } 302 } 303 } 304 305 return theRetVal; 306 } 307 308 @VisibleForTesting 309 List<Object> getInterceptorsWithInvokersForPointcut(Pointcut thePointcut) { 310 return getInvokersForPointcut(thePointcut) 311 .stream() 312 .map(BaseInvoker::getInterceptor) 313 .collect(Collectors.toList()); 314 } 315 316 /** 317 * Returns an ordered list of invokers for the given pointcut. Note that 318 * a new and stable list is returned to.. do whatever you want with it. 319 */ 320 private List<BaseInvoker> getInvokersForPointcut(Pointcut thePointcut) { 321 List<BaseInvoker> invokers; 322 323 synchronized (myRegistryMutex) { 324 List<BaseInvoker> globalInvokers = myGlobalInvokers.get(thePointcut); 325 List<BaseInvoker> anonymousInvokers = myAnonymousInvokers.get(thePointcut); 326 List<BaseInvoker> threadLocalInvokers = null; 327 if (myThreadlocalInvokersEnabled) { 328 ListMultimap<Pointcut, BaseInvoker> pointcutToInvokers = myThreadlocalInvokers.get(); 329 if (pointcutToInvokers != null) { 330 threadLocalInvokers = pointcutToInvokers.get(thePointcut); 331 } 332 } 333 invokers = union(globalInvokers, anonymousInvokers, threadLocalInvokers); 334 } 335 336 return invokers; 337 } 338 339 /** 340 * First argument must be the global invoker list!! 341 */ 342 @SafeVarargs 343 private final List<BaseInvoker> union(List<BaseInvoker>... theInvokersLists) { 344 List<BaseInvoker> haveOne = null; 345 boolean haveMultiple = false; 346 for (List<BaseInvoker> nextInvokerList : theInvokersLists) { 347 if (nextInvokerList == null || nextInvokerList.isEmpty()) { 348 continue; 349 } 350 351 if (haveOne == null) { 352 haveOne = nextInvokerList; 353 } else { 354 haveMultiple = true; 355 } 356 } 357 358 if (haveOne == null) { 359 return Collections.emptyList(); 360 } 361 362 List<BaseInvoker> retVal; 363 364 if (haveMultiple == false) { 365 366 // The global list doesn't need to be sorted every time since it's sorted on 367 // insertion each time. Doing so is a waste of cycles.. 368 if (haveOne == theInvokersLists[0]) { 369 retVal = haveOne; 370 } else { 371 retVal = new ArrayList<>(haveOne); 372 retVal.sort(Comparator.naturalOrder()); 373 } 374 375 } else { 376 377 retVal = Arrays 378 .stream(theInvokersLists) 379 .filter(t -> t != null) 380 .flatMap(t -> t.stream()) 381 .sorted() 382 .collect(Collectors.toList()); 383 384 } 385 386 return retVal; 387 } 388 389 /** 390 * Only call this when assertions are enabled, it's expensive 391 */ 392 boolean haveAppropriateParams(Pointcut thePointcut, HookParams theParams) { 393 Validate.isTrue(theParams.getParamsForType().values().size() == thePointcut.getParameterTypes().size(), "Wrong number of params for pointcut %s - Wanted %s but found %s", thePointcut.name(), toErrorString(thePointcut.getParameterTypes()), theParams.getParamsForType().values().stream().map(t -> t != null ? t.getClass().getSimpleName() : "null").sorted().collect(Collectors.toList())); 394 395 List<String> wantedTypes = new ArrayList<>(thePointcut.getParameterTypes()); 396 397 ListMultimap<Class<?>, Object> givenTypes = theParams.getParamsForType(); 398 for (Class<?> nextTypeClass : givenTypes.keySet()) { 399 String nextTypeName = nextTypeClass.getName(); 400 for (Object nextParamValue : givenTypes.get(nextTypeClass)) { 401 Validate.isTrue(nextParamValue == null || nextTypeClass.isAssignableFrom(nextParamValue.getClass()), "Invalid params for pointcut %s - %s is not of type %s", thePointcut.name(), nextParamValue != null ? nextParamValue.getClass() : "null", nextTypeClass); 402 Validate.isTrue(wantedTypes.remove(nextTypeName), "Invalid params for pointcut %s - Wanted %s but found %s", thePointcut.name(), toErrorString(thePointcut.getParameterTypes()), nextTypeName); 403 } 404 } 405 406 return true; 407 } 408 409 private class AnonymousLambdaInvoker extends BaseInvoker { 410 private final IAnonymousInterceptor myHook; 411 private final Pointcut myPointcut; 412 413 public AnonymousLambdaInvoker(Pointcut thePointcut, IAnonymousInterceptor theHook, int theOrder) { 414 super(theHook, theOrder); 415 myHook = theHook; 416 myPointcut = thePointcut; 417 } 418 419 @Override 420 Object invoke(HookParams theParams) { 421 myHook.invoke(myPointcut, theParams); 422 return true; 423 } 424 } 425 426 private abstract static class BaseInvoker implements Comparable<BaseInvoker> { 427 428 private final int myOrder; 429 private final Object myInterceptor; 430 431 BaseInvoker(Object theInterceptor, int theOrder) { 432 myInterceptor = theInterceptor; 433 myOrder = theOrder; 434 } 435 436 public Object getInterceptor() { 437 return myInterceptor; 438 } 439 440 abstract Object invoke(HookParams theParams); 441 442 @Override 443 public int compareTo(BaseInvoker theInvoker) { 444 return myOrder - theInvoker.myOrder; 445 } 446 } 447 448 private static class HookInvoker extends BaseInvoker { 449 450 private final Method myMethod; 451 private final Class<?>[] myParameterTypes; 452 private final int[] myParameterIndexes; 453 private final Pointcut myPointcut; 454 455 /** 456 * Constructor 457 */ 458 private HookInvoker(Hook theHook, @Nonnull Object theInterceptor, @Nonnull Method theHookMethod, int theOrder) { 459 super(theInterceptor, theOrder); 460 myPointcut = theHook.value(); 461 myParameterTypes = theHookMethod.getParameterTypes(); 462 myMethod = theHookMethod; 463 464 Class<?> returnType = theHookMethod.getReturnType(); 465 if (myPointcut.getReturnType().equals(boolean.class)) { 466 Validate.isTrue(boolean.class.equals(returnType) || void.class.equals(returnType), "Method does not return boolean or void: %s", theHookMethod); 467 } else if (myPointcut.getReturnType().equals(void.class)) { 468 Validate.isTrue(void.class.equals(returnType), "Method does not return void: %s", theHookMethod); 469 } else { 470 Validate.isTrue(myPointcut.getReturnType().isAssignableFrom(returnType) || void.class.equals(returnType), "Method does not return %s or void: %s", myPointcut.getReturnType(), theHookMethod); 471 } 472 473 myParameterIndexes = new int[myParameterTypes.length]; 474 Map<Class<?>, AtomicInteger> typeToCount = new HashMap<>(); 475 for (int i = 0; i < myParameterTypes.length; i++) { 476 AtomicInteger counter = typeToCount.computeIfAbsent(myParameterTypes[i], t -> new AtomicInteger(0)); 477 myParameterIndexes[i] = counter.getAndIncrement(); 478 } 479 480 myMethod.setAccessible(true); 481 } 482 483 @Override 484 public String toString() { 485 return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) 486 .append("method", myMethod) 487 .toString(); 488 } 489 490 public Pointcut getPointcut() { 491 return myPointcut; 492 } 493 494 /** 495 * @return Returns true/false if the hook method returns a boolean, returns true otherwise 496 */ 497 @Override 498 Object invoke(HookParams theParams) { 499 500 Object[] args = new Object[myParameterTypes.length]; 501 for (int i = 0; i < myParameterTypes.length; i++) { 502 Class<?> nextParamType = myParameterTypes[i]; 503 if (nextParamType.equals(Pointcut.class)) { 504 args[i] = myPointcut; 505 } else { 506 int nextParamIndex = myParameterIndexes[i]; 507 Object nextParamValue = theParams.get(nextParamType, nextParamIndex); 508 args[i] = nextParamValue; 509 } 510 } 511 512 // Invoke the method 513 try { 514 return myMethod.invoke(getInterceptor(), args); 515 } catch (InvocationTargetException e) { 516 Throwable targetException = e.getTargetException(); 517 if (myPointcut.isShouldLogAndSwallowException(targetException)) { 518 ourLog.error("Exception thrown by interceptor: " + targetException.toString(), targetException); 519 return null; 520 } 521 522 if (targetException instanceof RuntimeException) { 523 throw ((RuntimeException) targetException); 524 } else { 525 throw new InternalErrorException("Failure invoking interceptor for pointcut(s) " + getPointcut(), targetException); 526 } 527 } catch (Exception e) { 528 throw new InternalErrorException(e); 529 } 530 531 } 532 533 } 534 535 private static List<HookInvoker> scanInterceptorAndAddToInvokerMultimap(Object theInterceptor, ListMultimap<Pointcut, BaseInvoker> theInvokers) { 536 Class<?> interceptorClass = theInterceptor.getClass(); 537 int typeOrder = determineOrder(interceptorClass); 538 539 List<HookInvoker> addedInvokers = scanInterceptorForHookMethods(theInterceptor, typeOrder); 540 541 // Invoke the REGISTERED pointcut for any added hooks 542 addedInvokers.stream() 543 .filter(t -> Pointcut.INTERCEPTOR_REGISTERED.equals(t.getPointcut())) 544 .forEach(t -> t.invoke(new HookParams())); 545 546 // Register the interceptor and its various hooks 547 for (HookInvoker nextAddedHook : addedInvokers) { 548 Pointcut nextPointcut = nextAddedHook.getPointcut(); 549 if (nextPointcut.equals(Pointcut.INTERCEPTOR_REGISTERED)) { 550 continue; 551 } 552 theInvokers.put(nextPointcut, nextAddedHook); 553 } 554 555 // Make sure we're always sorted according to the order declared in 556 // @Order 557 for (Pointcut nextPointcut : theInvokers.keys()) { 558 List<BaseInvoker> nextInvokerList = theInvokers.get(nextPointcut); 559 nextInvokerList.sort(Comparator.naturalOrder()); 560 } 561 562 return addedInvokers; 563 } 564 565 /** 566 * @return Returns a list of any added invokers 567 */ 568 private static List<HookInvoker> scanInterceptorForHookMethods(Object theInterceptor, int theTypeOrder) { 569 ArrayList<HookInvoker> retVal = new ArrayList<>(); 570 for (Method nextMethod : theInterceptor.getClass().getMethods()) { 571 Optional<Hook> hook = findAnnotation(nextMethod, Hook.class); 572 573 if (hook.isPresent()) { 574 int methodOrder = theTypeOrder; 575 int methodOrderAnnotation = hook.get().order(); 576 if (methodOrderAnnotation != Interceptor.DEFAULT_ORDER) { 577 methodOrder = methodOrderAnnotation; 578 } 579 580 retVal.add(new HookInvoker(hook.get(), theInterceptor, nextMethod, methodOrder)); 581 } 582 } 583 584 return retVal; 585 } 586 587 private static <T extends Annotation> Optional<T> findAnnotation(AnnotatedElement theObject, Class<T> theHookClass) { 588 T annotation; 589 if (theObject instanceof Method) { 590 annotation = MethodUtils.getAnnotation((Method) theObject, theHookClass, true, true); 591 } else { 592 annotation = theObject.getAnnotation(theHookClass); 593 } 594 return Optional.ofNullable(annotation); 595 } 596 597 private static int determineOrder(Class<?> theInterceptorClass) { 598 int typeOrder = Interceptor.DEFAULT_ORDER; 599 Optional<Interceptor> typeOrderAnnotation = findAnnotation(theInterceptorClass, Interceptor.class); 600 if (typeOrderAnnotation.isPresent()) { 601 typeOrder = typeOrderAnnotation.get().order(); 602 } 603 return typeOrder; 604 } 605 606 private static String toErrorString(List<String> theParameterTypes) { 607 return theParameterTypes 608 .stream() 609 .sorted() 610 .collect(Collectors.joining(",")); 611 } 612 613}