MetricsFilter doesn't consider path variables when using Jersey #5875

Open
heroicefforts opened this Issue May 5, 2016 · 10 comments

Projects

None yet

8 participants

@heroicefforts

The MetricsFilter is unsuitable for REST microservices that are backing a large number of entities. In our case, it was trying to generate gauges and counters for /widget/1 to /widget/60000000. It eventually soaks the heap and causes the server to slow to a crawl as it spends most of its CPU cycles in GC. There should be a big red "caveat" bubble in the documentation that details this scenario.

Ideally, a Spring MVC controller metrics controller should be implemented that works similar to the DropWizard Jersey 2 implementation (plus some RequestMapping introspection), then the MetricsFilter could be disabled by default.

@wilkinsona
Member

The behaviour you've described isn't intended, and it doesn't match what's tested.

In one of the tests there's a request mapping like this: @RequestMapping("templateVarTest/{someVariable}"). It's called with /templateVarTest/foo which results in status.200.templateVarTest.someVariable and response.templateVarTest.someVariable being updated. As you can see, it's the name of the variable in the request mapping rather than the value in the request URI that's used.

Can you please provide a sample or testcase that illustrates the behaviour you have described?

@heroicefforts
heroicefforts commented May 5, 2016 edited

Then, perhaps, it is a consequence of using Jersey with SpringBoot (don't get me started on why we're using both...):

@GET
@Path("/parent/{pid}/child/{cid}")
@Produces("application/json")
@Timed(name="child.reads")
public Response readChild(@Context UriInfo uriInfo, @PathParam("pid") String parentId,
        @PathParam("cid") String childId) { ... } 
@wilkinsona
Member

Thanks. That'll be it. We need to use Jersey's equivalent of Spring MVC's best matching pattern attribute (assuming it has such a thing).

@wilkinsona wilkinsona changed the title from Document caveats of using MetricsFilter to MetricsFilter doesn't consider path variables when using Jersey May 5, 2016
@wilkinsona
Member
wilkinsona commented May 18, 2016 edited

@beckje01 No, I don't think so. It think it's something similar to this that we need to do for Jersey.

@beckje01

Ok so we just need to make sure things are putting that attribute in, this same issue effect Grails 3 as well. So that way anything built on boot the metrics will work for assuming the attribute is set.

@jbellmann

Hi,
maybe this snippet could help here?

@pdavidson

I just ran into this with jersey as well. It didn't saturate our jvm. Just filled up 380GB on our graphite server. I'm disabling the filter using:

endpoints:
  metrics:
    filter:
      enabled: false
@wilkinsona
Member

Adding the following bean to an application will correct the metrics for requests handled by Jersey:

@Bean
public ResourceConfigCustomizer bestMatchingPatternResourceConfigCustomizer(
		final JerseyProperties jerseyProperties) {
	return new ResourceConfigCustomizer() {

		@Override
		public void customize(ResourceConfig config) {
			String applicationPath = determineApplicationPath(jerseyProperties,
					config);
			config.register(new BestMatchingPatternContainerRequestFilter(
					applicationPath));
		}

		private String determineApplicationPath(JerseyProperties jerseyProperties,
				ResourceConfig config) {
			if (StringUtils.hasText(jerseyProperties.getApplicationPath())) {
				return jerseyProperties.getApplicationPath();
			}
			ApplicationPath applicationPath = AnnotationUtils
					.findAnnotation(config.getClass(), ApplicationPath.class);
			return applicationPath == null ? "" : applicationPath.value();
		}

	};

}

/**
 * A {@link ContainerRequestFilter} that sets the
 * {@link HandlerMapping#BEST_MATCHING_PATTERN_ATTRIBUTE} request attribute.
 */
private static final class BestMatchingPatternContainerRequestFilter
		implements ContainerRequestFilter {

	private final String applicationPath;

	private BestMatchingPatternContainerRequestFilter(String applicationPath) {
		this.applicationPath = applicationPath.startsWith("/") ? applicationPath
				: "/" + applicationPath;
	}

	@Override
	public void filter(ContainerRequestContext requestContext)
			throws IOException {
		String matchingPattern = extractMatchingPattern(requestContext);
		requestContext.setProperty(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE,
				matchingPattern);
	}

	private String extractMatchingPattern(
			ContainerRequestContext requestContext) {
		ExtendedUriInfo extendedUriInfo = (ExtendedUriInfo) requestContext
				.getUriInfo();
		List<String> templates = new ArrayList<String>();
		for (UriTemplate matchedTemplate : extendedUriInfo
				.getMatchedTemplates()) {
			String template = matchedTemplate.getTemplate();
			templates.add(template.startsWith("/") ? template : "/" + template);
		}
		if (StringUtils.hasText(this.applicationPath)) {
			templates.add(this.applicationPath);
		}
		Collections.reverse(templates);
		return StringUtils.collectionToDelimitedString(templates, "");
	}

}

Some caveats:

  • I don't like that it uses Spring MVC's request attribute (see #7505)
  • Regular expressions in @Path don't work particularly well (see #7503)
@wilkinsona wilkinsona added this to the 1.5.0 RC1 milestone Nov 30, 2016
@wilkinsona wilkinsona self-assigned this Nov 30, 2016
@soldierkam

The same happens for almost every HttpServlet used in Spring Boot application. MetricsFilter should create new keys only if it knows what mapping was used.

@wilkinsona wilkinsona modified the milestone: 1.5.0 RC1, 2.0.0.M1 Dec 2, 2016
@philwebb philwebb modified the milestone: 2.0.0.M1, 2.0.0 Jan 12, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment