Repository navigation
Provide missing user event metrics from aerogear/keycloak-metrics-spi with a key… #33046
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| <#import "/templates/guide.adoc" as tmpl> | ||
| <#import "/templates/kc.adoc" as kc> | ||
| <#import "/templates/options.adoc" as opts> | ||
| <#import "/templates/links.adoc" as links> | ||
|
|
||
| <@tmpl.guide | ||
| title="Enabling {project_name} Event Metrics" | ||
| summary="Learn how to enable and use {project_name} Event Metrics" | ||
| preview="true" | ||
| includedOptions="metrics-enabled event-metrics-user-*"> | ||
|
|
||
| Event metrics can provide admins an overview of the different activities in a {project_name} instance. | ||
| For now, only metrics for user events are captured. | ||
| For example, you can monitor the number of logins, login failures, or token refreshes performed. | ||
|
|
||
| The metrics are exposed using the standard metrics endpoint, and you can use it in your own metrics collection system to create dashboards and alerts. | ||
|
|
||
| The metrics are reported as counters per {project_name} instance. | ||
| The counters are reset on the restart of the instance. | ||
| If you have multiple instances running in a cluster, you will need to collect the metrics from all instances and aggregate them to get per a cluster view. | ||
|
|
||
| == Enable event metrics | ||
|
|
||
| To start collecting metrics, enable the feature `user-event-metrics`, enable metrics, and enable the metrics for user events. | ||
|
|
||
| The following shows the required startup parameters: | ||
|
|
||
| <@kc.start parameters="--features=user-event-metrics --metrics-enabled=true --event-metrics-user-enabled=true ..."/> | ||
|
|
||
| By default, there is a separate metric for each realm. | ||
| To break down the metric by client and identity provider, you can add those metrics dimension using the configuration option `event-metrics-user-tags`. | ||
| This can be useful on installations with a small number of clients and IDPs. | ||
| This is not recommended for installations with a large number of clients or IDPs as it will increase the memory usage of {project_name} and as it will increase the load on your monitoring system. | ||
|
|
||
| The following shows how to configure {project_name} to break down the metrics by all three metrics dimensions: | ||
|
|
||
| <@kc.start parameters="... --event-metrics-user-tags=realm,idp,clientId ..."/> | ||
|
|
||
| You can limit the events for which {project_name} will expose metrics. | ||
|
|
||
| The following example limits the events collected to `LOGIN` and `LOGOUT` events: | ||
|
|
||
| <@kc.start parameters="... --event-metrics-user-events=login,logout ..."/> | ||
|
|
||
| All error events will be collected with the primary event type and will have the `error` tag filled with the error code. | ||
|
|
||
| The snippet below is an example of a response provided by the metric endpoint: | ||
|
|
||
| [source] | ||
| ---- | ||
| # HELP keycloak_user_events_total Keycloak user events | ||
| # TYPE keycloak_user_events_total counter | ||
| keycloak_user_events_total{client_id="security-admin-console",error="",event="code_to_token",idp="",realm="master",} 1.0 | ||
| keycloak_user_events_total{client_id="security-admin-console",error="",event="login",idp="",realm="master",} 1.0 | ||
| keycloak_user_events_total{client_id="security-admin-console",error="",event="logout",idp="",realm="master",} 1.0 | ||
| keycloak_user_events_total{client_id="security-admin-console",error="invalid_user_credentials",event="login",idp="",realm="master",} 1.0 | ||
| ---- | ||
|
|
||
|
|
||
| </@tmpl.guide> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -18,6 +18,7 @@ fips | |
| management-interface | ||
| health | ||
| configuration-metrics | ||
| event-metrics | ||
| tracing | ||
| importExport | ||
| vault | ||
|
|
||
30 changes: 30 additions & 0 deletions
30
quarkus/config-api/src/main/java/org/keycloak/config/EventOptions.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| package org.keycloak.config; | ||
|
|
||
| import java.util.List; | ||
|
|
||
| public class EventOptions { | ||
|
|
||
| public static final Option<Boolean> USER_EVENT_METRICS_ENABLED = new OptionBuilder<>("event-metrics-user-enabled", Boolean.class) | ||
| .category(OptionCategory.EVENTS) | ||
| .description("Create metrics based on user events.") | ||
| .buildTime(true) | ||
| .defaultValue(Boolean.FALSE) | ||
| .build(); | ||
|
|
||
| public static final Option<List<String>> USER_EVENT_METRICS_TAGS = OptionBuilder.listOptionBuilder("event-metrics-user-tags", String.class) | ||
| .category(OptionCategory.EVENTS) | ||
| .description("Comma-separated list of tags to be collected for user event metrics. By default only 'realm' is enabled to avoid a high metrics cardinality.") | ||
| .buildTime(false) | ||
| .expectedValues(List.of("realm", "idp", "clientId")) | ||
| .defaultValue(List.of("realm")) | ||
| .build(); | ||
|
|
||
| public static final Option<List<String>> USER_EVENT_METRICS_EVENTS = OptionBuilder.listOptionBuilder("event-metrics-user-events", String.class) | ||
| .category(OptionCategory.EVENTS) | ||
| .description("Comma-separated list of events to be collected for user event metrics. Reduce the number of metrics. If empty or not set, all events create a metric.") | ||
| .buildTime(false) | ||
| .build(); | ||
|
|
||
| } | ||
|
|
||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
45 changes: 45 additions & 0 deletions
45
...rc/main/java/org/keycloak/quarkus/runtime/configuration/mappers/EventPropertyMappers.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| package org.keycloak.quarkus.runtime.configuration.mappers; | ||
|
|
||
| import org.keycloak.common.Profile; | ||
|
|
||
| import static org.keycloak.config.EventOptions.USER_EVENT_METRICS_ENABLED; | ||
| import static org.keycloak.config.EventOptions.USER_EVENT_METRICS_EVENTS; | ||
| import static org.keycloak.config.EventOptions.USER_EVENT_METRICS_TAGS; | ||
| import static org.keycloak.quarkus.runtime.configuration.Configuration.isTrue; | ||
| import static org.keycloak.quarkus.runtime.configuration.mappers.MetricsPropertyMappers.METRICS_ENABLED_MSG; | ||
| import static org.keycloak.quarkus.runtime.configuration.mappers.MetricsPropertyMappers.metricsEnabled; | ||
| import static org.keycloak.quarkus.runtime.configuration.mappers.PropertyMapper.fromOption; | ||
|
|
||
|
|
||
| final class EventPropertyMappers { | ||
|
|
||
| private EventPropertyMappers(){} | ||
|
|
||
| public static PropertyMapper<?>[] getMetricsPropertyMappers() { | ||
| return new PropertyMapper[] { | ||
| fromOption(USER_EVENT_METRICS_ENABLED) | ||
| .to("kc.spi-events-listener-micrometer-user-event-metrics-enabled") | ||
| .isEnabled(EventPropertyMappers::userEventsMetricsEnabled, METRICS_ENABLED_MSG + " and feature " + Profile.Feature.USER_EVENT_METRICS.getKey() + " is enabled") | ||
| .build(), | ||
| fromOption(USER_EVENT_METRICS_TAGS) | ||
| .to("kc.spi-events-listener-micrometer-user-event-metrics-tags") | ||
| .paramLabel("tags") | ||
| .isEnabled(EventPropertyMappers::userEventsMetricsTags, "user event metrics are enabled") | ||
| .build(), | ||
| fromOption(USER_EVENT_METRICS_EVENTS) | ||
| .to("kc.spi-events-listener-micrometer-user-event-metrics-events") | ||
| .paramLabel("events") | ||
| .isEnabled(EventPropertyMappers::userEventsMetricsTags, "user event metrics are enabled") | ||
| .build(), | ||
| }; | ||
| } | ||
|
|
||
| private static boolean userEventsMetricsEnabled() { | ||
| return metricsEnabled() && Profile.isFeatureEnabled(Profile.Feature.USER_EVENT_METRICS); | ||
| } | ||
|
|
||
| private static boolean userEventsMetricsTags() { | ||
| return isTrue(USER_EVENT_METRICS_ENABLED); | ||
| } | ||
|
|
||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
151 changes: 151 additions & 0 deletions
151
...rkus/runtime/services/metrics/events/MicrometerUserEventMetricsEventListenerProvider.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,151 @@ | ||
| /* | ||
| * Copyright 2024 Red Hat, Inc. and/or its affiliates | ||
| * and other contributors as indicated by the @author tags. | ||
| * | ||
| * 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. | ||
| */ | ||
|
|
||
| package org.keycloak.quarkus.runtime.services.metrics.events; | ||
|
|
||
| import io.micrometer.core.instrument.Counter; | ||
| import io.micrometer.core.instrument.Metrics; | ||
| import io.micrometer.core.instrument.Tag; | ||
| import io.micrometer.core.instrument.Tags; | ||
| import io.micrometer.core.instrument.binder.BaseUnits; | ||
| import org.jboss.logging.Logger; | ||
| import org.keycloak.events.Details; | ||
| import org.keycloak.events.Errors; | ||
| import org.keycloak.events.Event; | ||
| import org.keycloak.events.EventListenerProvider; | ||
| import org.keycloak.events.EventListenerTransaction; | ||
| import org.keycloak.events.EventType; | ||
| import org.keycloak.events.admin.AdminEvent; | ||
| import org.keycloak.models.KeycloakSession; | ||
|
|
||
| import java.util.HashSet; | ||
| import java.util.Locale; | ||
|
|
||
| public class MicrometerUserEventMetricsEventListenerProvider implements EventListenerProvider { | ||
|
|
||
| private static final Logger logger = Logger.getLogger(MicrometerUserEventMetricsEventListenerProvider.class); | ||
|
|
||
| private static final String REALM_TAG = "realm"; | ||
| private static final String IDP_TAG = "idp"; | ||
| private static final String CLIENT_ID_TAG = "client.id"; | ||
| private static final String ERROR_TAG = "error"; | ||
| private static final String EVENT_TAG = "event"; | ||
| private static final String DESCRIPTION_OF_EVENT_METER = "Keycloak user events"; | ||
| // Micrometer naming convention that separates lowercase words with a . (dot) character. | ||
| private static final String KEYCLOAK_METER_NAME_PREFIX = "keycloak."; | ||
| private static final String USER_EVENTS_METER_NAME = KEYCLOAK_METER_NAME_PREFIX + "user"; | ||
|
|
||
| private final boolean withIdp; | ||
| private final boolean withRealm; | ||
| private final boolean withClientId; | ||
| private final HashSet<String> events; | ||
|
|
||
| private final EventListenerTransaction tx = | ||
| new EventListenerTransaction(null, this::countEvent); | ||
|
|
||
| public MicrometerUserEventMetricsEventListenerProvider(KeycloakSession session, boolean withIdp, boolean withRealm, boolean withClientId, HashSet<String> events) { | ||
| this.withIdp = withIdp; | ||
| this.withRealm = withRealm; | ||
| this.withClientId = withClientId; | ||
| this.events = events; | ||
| session.getTransactionManager().enlistAfterCompletion(tx); | ||
| } | ||
|
|
||
| @Override | ||
| public void onEvent(Event event) { | ||
| tx.addEvent(event); | ||
| } | ||
|
|
||
| private void countEvent(Event event) { | ||
| logger.debugf("Received user event of type %s in realm %s", | ||
| event.getType().name(), event.getRealmName()); | ||
|
|
||
| String eventTag = format(event.getType()); | ||
| if (events != null && !events.contains(eventTag)) { | ||
| return; | ||
| } | ||
|
|
||
| Counter.Builder counterBuilder = Counter.builder(USER_EVENTS_METER_NAME) | ||
| .description(DESCRIPTION_OF_EVENT_METER) | ||
| .tags(Tags.of(Tag.of(EVENT_TAG, eventTag), | ||
| Tag.of(ERROR_TAG, getError(event)))) | ||
| .baseUnit(BaseUnits.EVENTS); | ||
|
|
||
| if (withRealm) { | ||
| counterBuilder.tag(REALM_TAG, nullToEmpty(event.getRealmName())); | ||
| } | ||
|
|
||
| if (withIdp) { | ||
| counterBuilder.tag(IDP_TAG, getIdentityProvider(event)); | ||
| } | ||
|
|
||
| if (withClientId) { | ||
| counterBuilder.tag(CLIENT_ID_TAG, getClientId(event)); | ||
| } | ||
|
|
||
| counterBuilder.register(Metrics.globa B531 lRegistry) | ||
| .increment(); | ||
| } | ||
|
|
||
| @Override | ||
| public void onEvent(AdminEvent event, boolean includeRepresentation) { | ||
| // do nothing for now | ||
| } | ||
|
|
||
| private String getIdentityProvider(Event event) { | ||
| String identityProvider = null; | ||
| if (event.getDetails() != null) { | ||
| identityProvider = event.getDetails().get(Details.IDENTITY_PROVIDER); | ||
| } | ||
| return nullToEmpty(identityProvider); | ||
| } | ||
|
|
||
|
|
||
| private String getClientId(Event event) { | ||
| // Don't use the clientId as a tag value of the event CLIENT_NOT_FOUND as it would lead to a metrics cardinality explosion | ||
| return nullToEmpty(Errors.CLIENT_NOT_FOUND.equals(event.getError()) | ||
| ? "unknown" : event.getClientId()); | ||
| } | ||
|
|
||
| private String getError(Event event) { | ||
| String error = event.getError(); | ||
| if (error == null && event.getType().name().endsWith("_ERROR")) { | ||
| error = "unknown"; | ||
| } | ||
| return nullToEmpty(error); | ||
| } | ||
|
|
||
| private String nullToEmpty(String value) { | ||
| return value == null ? "" : value; | ||
| } | ||
|
|
||
|
|
||
| public static String format(EventType type) { | ||
| // Remove the error suffix so that all events have the same tag. | ||
| // In dashboards, we can distinguish errors from non-errors by looking at the error tag. | ||
| String name = type.name(); | ||
| if (name.endsWith("_ERROR")) { | ||
| name = name.substring(0, name.length() - "_ERROR".length()); | ||
| } | ||
| return name.toLowerCase(Locale.ROOT); | ||
| } | ||
|
|
||
| @Override | ||
| public void close() { | ||
| // unused | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do you also plan to collect admin event metrics with via the associated
MicrometerMetricsEventListener?If that's the plan, then I'd recommend to use a more generic name for the feature to enable usage metric collection like
USAGE_EVENT_METRICSas this would allow us to also collect metrics based on admin events later, without having to introduce a new feature flag.The feature specific property to enable user event metrics collection
--user-event-metrics-enabled=trueis IMHO already specific enough. This can later also be extended to include--admin-event-metrics-enabled=true.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The user event metrics might become fully supported earlier than the admin event metrics, so I'd like to keep it as is which is fine-grained.