Skip to content

Commit

Permalink
Merge pull request #12 from kumuluz/feature/mpMetrics3.0
Browse files Browse the repository at this point in the history
MP Metrics 3.0
  • Loading branch information
urbim authored Dec 9, 2021
2 parents 9c322c6 + 7f0f2d3 commit 734e10e
Show file tree
Hide file tree
Showing 41 changed files with 703 additions and 368 deletions.
70 changes: 70 additions & 0 deletions .github/workflows/kumuluzee-ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
name: KumuluzEE CI

on: [push, pull_request]

jobs:
test:
name: Build and test
runs-on: 'ubuntu-latest'

strategy:
matrix:
java-version: ['11', '17']

steps:
- name: Checkout code
uses: actions/checkout@v2

- name: Set up JDK ${{ matrix.java-version }}
uses: actions/setup-java@v1
with:
java-version: ${{ matrix.java-version }}

- name: Cache Maven packages
uses: actions/cache@v2
with:
path: ~/.m2
key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }}
restore-keys: ${{ runner.os }}-m2

- name: Install
run: mvn --show-version --update-snapshots --batch-mode clean install -DskipTests=true

- name: Test
run: mvn --batch-mode test

publish:
name: Publish to OSSRH
runs-on: 'ubuntu-latest'

needs: test
if: github.ref == 'refs/heads/master' || startsWith(github.ref, 'refs/tags/v')

steps:
- name: Checkout code
uses: actions/checkout@v2

- name: Set up JDK 11
uses: actions/setup-java@v1
with:
java-version: 11

- name: Restore cache
uses: actions/cache@v2
with:
path: ~/.m2
key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }}
restore-keys: ${{ runner.os }}-m2

- name: Restore GPG keys
env:
GPG_KEY: ${{ secrets.OSSRH_GPG_KEY }}
GPG_PUB: ${{ secrets.OSSRH_GPG_PUB }}
run: 'printf "$GPG_KEY" | base64 --decode > "$GITHUB_WORKSPACE/gpg.key" && printf "$GPG_PUB" | base64 --decode > "$GITHUB_WORKSPACE/gpg.pub" && gpg --batch --import "$GITHUB_WORKSPACE/gpg.pub" "$GITHUB_WORKSPACE/gpg.key"'

- name: Publish to OSSRH
env:
OSSRH_USERNAME: Kumuluz
OSSRH_PASSWORD: ${{ secrets.OSSRH_PASSWORD }}
GPG_PASSPHRASE: ${{ secrets.OSSRH_GPG_PASSPHRASE }}
run: mvn --batch-mode source:jar javadoc:jar deploy -Pdeploy -DskipTests=true --settings ./settings.xml;
26 changes: 0 additions & 26 deletions .travis.yml

This file was deleted.

3 changes: 0 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -224,9 +224,6 @@ Alongside metric's name, the following metadata is stored for each metric:
- `description` - A human readable description. Default: `""`.
- `unit` - Unit of the metric. Default: `MetricUnits.NONE`.
- `tags` - Tags of the metric.
- `reusable` - Is the metric reusable. If `false`, the metric can not be registered more than once with the same name
and scope. This is done to prevent hard to spot copy & paste errors. If this behaviour is required, all such metrics
should have the `reusable` flag set to true. Default: `false`.

Metadata is specified using annotation parameters in `@Metric`, `@Gauge`, `@Counted`, `@Metered` and `@Timed`
annotations.
Expand Down
2 changes: 1 addition & 1 deletion core/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
<groupId>com.kumuluz.ee.config</groupId>
<artifactId>kumuluzee-config-mp</artifactId>
<version>${kumuluzee-config-mp.version}</version>
<scope>provided</scope>
<optional>true</optional>
</dependency>

<dependency>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import com.kumuluz.ee.metrics.json.MetricsModule;
import com.kumuluz.ee.metrics.json.models.MetricsCollection;
import com.kumuluz.ee.metrics.prometheus.PrometheusMetricWriter;
import com.kumuluz.ee.metrics.utils.GlobalTagsUtil;
import com.kumuluz.ee.metrics.utils.RequestInfo;
import org.eclipse.microprofile.metrics.MetricID;
import org.eclipse.microprofile.metrics.MetricRegistry;
Expand Down Expand Up @@ -53,8 +54,8 @@ public class KumuluzEEMetricsServlet extends HttpServlet {

private static final String APPLICATION_JSON = "application/json";

private static ObjectMapper metricMapper = new ObjectMapper().registerModule(new MetricsModule(false));
private static ObjectMapper metadataMapper = new ObjectMapper().registerModule(new MetricsModule(true));
private static final ObjectMapper METRIC_MAPPER = new ObjectMapper().registerModule(new MetricsModule(false));
private static final ObjectMapper METADATA_MAPPER = new ObjectMapper().registerModule(new MetricsModule(true));

@Override
public void init(ServletConfig config) throws ServletException {
Expand Down Expand Up @@ -91,7 +92,8 @@ public void service(HttpServletRequest request, HttpServletResponse response) th

if (requestInfo.getRequestType() == RequestInfo.RequestType.PROMETHEUS) {
PrintWriter writer = response.getWriter();
PrometheusMetricWriter prometheusMetricWriter = new PrometheusMetricWriter(writer);
PrometheusMetricWriter prometheusMetricWriter = new PrometheusMetricWriter(writer,
GlobalTagsUtil.getPrometheusGlobalTags());

try {
switch (requestInfo.getMetricsRequested()) {
Expand Down Expand Up @@ -159,8 +161,7 @@ public void service(HttpServletRequest request, HttpServletResponse response) th

private ObjectWriter getWriter(HttpServletRequest request, RequestInfo.RequestType requestType) {
boolean prettyPrintOff = "false".equals(request.getParameter("pretty"));
ObjectMapper mapper = (requestType == RequestInfo.RequestType.JSON_METADATA) ? this.metadataMapper :
this.metricMapper;
ObjectMapper mapper = (requestType == RequestInfo.RequestType.JSON_METADATA) ? METADATA_MAPPER : METRIC_MAPPER;

return prettyPrintOff ? mapper.writer() : mapper.writerWithDefaultPrettyPrinter();
}
Expand Down
20 changes: 6 additions & 14 deletions core/src/main/java/com/kumuluz/ee/metrics/MetricsExtension.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@
import com.kumuluz.ee.metrics.api.*;
import com.kumuluz.ee.metrics.filters.InstrumentedFilter;
import com.kumuluz.ee.metrics.producers.MetricRegistryProducer;
import org.eclipse.microprofile.config.ConfigProvider;
import org.eclipse.microprofile.metrics.*;

import java.lang.management.ClassLoadingMXBean;
Expand Down Expand Up @@ -67,14 +66,6 @@ public void init(KumuluzServerWrapper kumuluzServerWrapper, EeConfig eeConfig) {

log.info("Initialising Metrics common module.");

try {
ConfigProvider.getConfig();
} catch (IllegalStateException | NoClassDefFoundError e) {
log.severe("KumuluzEE Config MP is required in order for KumuluzEE Metrics to work correctly. " +
"Please include it in your dependencies.");
throw e;
}

ConfigurationUtil configurationUtil = ConfigurationUtil.getInstance();

registerBaseMetrics();
Expand Down Expand Up @@ -285,10 +276,11 @@ private org.eclipse.microprofile.metrics.Metric convertMetric(Metric metric, Met
return new ForwardingCounter() {
@Override
public long getCount() {
return ((Number) ((com.codahale.metrics.Gauge) metric).getValue()).longValue();
return ((Number) ((com.codahale.metrics.Gauge<?>) metric).getValue()).longValue();
}
};
} else {
//noinspection unchecked
return (Gauge<Number>) ((com.codahale.metrics.Gauge<Number>) metric)::getValue;
}
} else {
Expand All @@ -298,7 +290,7 @@ public long getCount() {

private void registerNonDropwizardMetrics(MetricRegistry registry, Map<String, Metadata> metadataMap) {
ClassLoadingMXBean classLoadingMXBean = ManagementFactory.getClassLoadingMXBean();
registry.register(metadataMap.get("classloader.currentLoadedClass.count"), (Gauge) classLoadingMXBean::getLoadedClassCount);
registry.register(metadataMap.get("classloader.currentLoadedClass.count"), (Gauge<?>) classLoadingMXBean::getLoadedClassCount);
registry.register(metadataMap.get("classloader.totalLoadedClass.count"), new ForwardingCounter() {
@Override
public long getCount() {
Expand All @@ -313,9 +305,9 @@ public long getCount() {
});

ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
registry.register(metadataMap.get("thread.count"), (Gauge) threadMXBean::getThreadCount);
registry.register(metadataMap.get("thread.daemon.count"), (Gauge) threadMXBean::getDaemonThreadCount);
registry.register(metadataMap.get("thread.max.count"), (Gauge) threadMXBean::getPeakThreadCount);
registry.register(metadataMap.get("thread.count"), (Gauge<?>) threadMXBean::getThreadCount);
registry.register(metadataMap.get("thread.daemon.count"), (Gauge<?>) threadMXBean::getDaemonThreadCount);
registry.register(metadataMap.get("thread.max.count"), (Gauge<?>) threadMXBean::getPeakThreadCount);

OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
registry.register(metadataMap.get("cpu.availableProcessors"),
Expand Down
86 changes: 6 additions & 80 deletions core/src/main/java/com/kumuluz/ee/metrics/MetricsExtensionCDI.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,24 +24,15 @@
import com.kumuluz.ee.metrics.interceptors.utils.GaugeBeanBinding;
import com.kumuluz.ee.metrics.interceptors.utils.RegisterMetricsBinding;
import com.kumuluz.ee.metrics.producers.MetricRegistryProducer;
import com.kumuluz.ee.metrics.utils.AnnotationMetadata;
import com.kumuluz.ee.metrics.utils.MetadataWithTags;
import com.kumuluz.ee.metrics.utils.ProducerMemberRegistration;
import org.eclipse.microprofile.metrics.Metric;
import org.eclipse.microprofile.metrics.MetricRegistry;
import org.eclipse.microprofile.metrics.MetricType;
import org.eclipse.microprofile.metrics.annotation.*;

import javax.enterprise.event.Observes;
import javax.enterprise.inject.Default;
import javax.enterprise.inject.spi.*;
import javax.enterprise.inject.spi.Extension;
import javax.enterprise.inject.spi.ProcessAnnotatedType;
import javax.enterprise.inject.spi.WithAnnotations;
import javax.enterprise.util.AnnotationLiteral;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.LinkedList;
import java.util.List;

/**
* Registers metrics from producer fields and producer methods.
Expand All @@ -52,20 +43,16 @@
*/
public class MetricsExtensionCDI implements Extension {

private MetricRegistry applicationRegistry = MetricRegistryProducer.getApplicationRegistry();

private List<ProducerMemberRegistration> producerMembers = new LinkedList<>();
private final MetricRegistry applicationRegistry = MetricRegistryProducer.getApplicationRegistry();

private static final AnnotationLiteral<Default> DEFAULT = new AnnotationLiteral<Default>() {
};

private static final AnnotationLiteral<GaugeBeanBinding> GAUGE_BEAN_BINDING =
new AnnotationLiteral<GaugeBeanBinding>() {
};
new AnnotationLiteral<>() {};

private static final AnnotationLiteral<RegisterMetricsBinding> REGISTER_METRICS_BINDING =
new AnnotationLiteral<RegisterMetricsBinding>() {
};
new AnnotationLiteral<>() {};

private <X> void registerMetrics(@Observes @WithAnnotations({Counted.class, Metered.class, Timed.class, ConcurrentGauge.class, SimplyTimed.class})
ProcessAnnotatedType<X> pat) {
Expand All @@ -79,65 +66,4 @@ private <X> void registerGauges(@Observes @WithAnnotations({Gauge.class}) Proces
GAUGE_BEAN_BINDING);
pat.setAnnotatedType(decoratedType);
}

private void metricProducerField(@Observes ProcessProducerField<? extends Metric, ?> ppf) {
if (ppf.getAnnotatedProducerField().getAnnotation(org.eclipse.microprofile.metrics.annotation.Metric.class)
!= null) {
Field member = ppf.getAnnotatedProducerField().getJavaMember();
Class<?> bean = member.getDeclaringClass();
MetadataWithTags metadata = AnnotationMetadata.buildMetadata(bean, member,
org.eclipse.microprofile.metrics.annotation.Metric.class, getMetricType(member));
producerMembers.add(new ProducerMemberRegistration(ppf.getBean(), ppf.getAnnotatedProducerField(),
metadata));
}
}

private void metricProducerMethod(@Observes ProcessProducerMethod<? extends Metric, ?> ppm) {
if (ppm.getAnnotatedProducerMethod().getAnnotation(org.eclipse.microprofile.metrics.annotation.Metric.class)
!= null) {
Method member = ppm.getAnnotatedProducerMethod().getJavaMember();
Class<?> bean = member.getDeclaringClass();
MetadataWithTags metadata = AnnotationMetadata.buildMetadata(bean, member,
org.eclipse.microprofile.metrics.annotation.Metric.class, getMetricType(member));
producerMembers.add(new ProducerMemberRegistration(ppm.getBean(), ppm.getAnnotatedProducerMethod(),
metadata));
}
}

private void registerMetrics(@Observes AfterDeploymentValidation adv, BeanManager manager) {
for (ProducerMemberRegistration registration : producerMembers) {
if (registration.getBean().getQualifiers().contains(DEFAULT) &&
!hasInjectionPoints(registration.getMember())) {
applicationRegistry.register(registration.getMetadata().getMetadata(),
getReference(manager, registration.getMember().getBaseType(), registration.getBean()),
registration.getMetadata().getTags());
}
}
}

private static boolean hasInjectionPoints(AnnotatedMember<?> member) {
if (!(member instanceof AnnotatedMethod))
return false;
AnnotatedMethod<?> method = (AnnotatedMethod<?>) member;
for (AnnotatedParameter<?> parameter : method.getParameters()) {
if (parameter.getBaseType().equals(InjectionPoint.class))
return true;
}
return false;
}

@SuppressWarnings("unchecked")
private static <T> T getReference(BeanManager manager, Type type, Bean<?> bean) {
return (T) manager.getReference(bean, type, manager.createCreationalContext(bean));
}

private static <E extends Member> MetricType getMetricType(E element) {
if (element instanceof Field) {
return MetricType.from(((Field) element).getType());
} else if (element instanceof Method) {
return MetricType.from(((Method) element).getReturnType());
} else {
return MetricType.from(element.getClass());
}
}
}
Loading

0 comments on commit 734e10e

Please sign in to comment.