8000 Provide missing user event metrics from aerogear/keycloak-metrics-spi with a key… by bohmber · Pull Request #33046 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions common/src/main/java/org/keycloak/common/Profile.java
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,8 @@ public enum Feature {
PASSKEYS("Passkeys", Type.PREVIEW),

CACHE_EMBEDDED_REMOTE_STORE("Support for remote-store in embedded Infinispan caches", Type.EXPERIMENTAL),

USER_EVENT_METRICS("Collect metrics based on user events", Type.PREVIEW),
Copy link
Copy Markdown
Contributor

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_METRICS as 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=true is IMHO already specific enough. This can later also be extended to include --admin-event-metrics-enabled=true.

Copy link
Copy Markdown
Member

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.

;

private final Type type;
Expand Down
3 changes: 3 additions & 0 deletions docs/guides/server/configuration-metrics.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@ The table below summarizes the available metrics groups:
|Cache
|A set of metrics from Infinispan caches. See <@links.server id="caching"/> for more details.

|Keycloak
|A set of metrics from Keycloak events. See <@links.server id="event-metrics"/> for more details.

|===

</@tmpl.guide>
60 changes: 60 additions & 0 deletions docs/guides/server/event-metrics.adoc
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>
1 change: 1 addition & 0 deletions docs/guides/server/pinned-guides
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ fips
management-interface
health
configuration-metrics
event-metrics
tracing
importExport
vault
Expand Down
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();

}


Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ public enum OptionCategory {
VAULT("Vault", 100, ConfigSupportLevel.SUPPORTED),
LOGGING("Logging", 110, ConfigSupportLevel.SUPPORTED),
TRACING("Tracing", 111, ConfigSupportLevel.PREVIEW),
EVENTS("Events", 112, ConfigSupportLevel.PREVIEW),
TRUSTSTORE("Truststore", 115, ConfigSupportLevel.SUPPORTED),
SECURITY("Security", 120, ConfigSupportLevel.SUPPORTED),
EXPORT("Export", 130, ConfigSupportLevel.SUPPORTED),
Expand Down
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);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ public static void reset() {
MAPPERS.addAll(ConfigKeystorePropertyMappers.getConfigKeystorePropertyMappers());
MAPPERS.addAll(ManagementPropertyMappers.getManagementPropertyMappers());
MAPPERS.addAll(MetricsPropertyMappers.getMetricsPropertyMappers());
MAPPERS.addAll(EventPropertyMappers.getMetricsPropertyMappers());
MAPPERS.addAll(ProxyPropertyMappers.getProxyPropertyMappers());
MAPPERS.addAll(VaultPropertyMappers.getVaultPropertyMappers());
MAPPERS.addAll(FeaturePropertyMappers.getMappers());
Expand Down
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
}
}
Loading
0