Skip to content
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

Count users in keycloak_count_users metric #83

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,15 @@ This counter counts the number of response errors (responses where the http stat
keycloak_response_errors{code="500",method="GET",} 1
```

##### keycloak_count_users
This gauge records the count of users.

```c
# HELP keycloak_count_users Count users
# TYPE keycloak_count_users gauge
keycloak_count_users{realm="test",} 1.0
```

## Grafana Dashboard

You can use this dashboard or create yours https://grafana.com/dashboards/10441
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,23 @@
import org.keycloak.events.Event;
import org.keycloak.events.EventListenerProvider;
import org.keycloak.events.admin.AdminEvent;
import org.keycloak.events.admin.ResourceType;
import org.keycloak.events.admin.OperationType;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;

public class MetricsEventListener implements EventListenerProvider {

public final static String ID = "metrics-listener";

private final static Logger logger = Logger.getLogger(MetricsEventListener.class);

private KeycloakSession session;

public MetricsEventListener (KeycloakSession session) {
this.session = session;
}

@Override
public void onEvent(Event event) {
logEventDetails(event);
Expand All @@ -21,6 +31,7 @@ public void onEvent(Event event) {
break;
case REGISTER:
PrometheusExporter.instance().recordRegistration(event);
countUsers(session.realms().getRealm(event.getRealmId()));
break;
case REGISTER_ERROR:
PrometheusExporter.instance().recordRegistrationError(event);
Expand All @@ -37,9 +48,18 @@ public void onEvent(Event event) {
public void onEvent(AdminEvent event, boolean includeRepresentation) {
logAdminEventDetails(event);

if (event.getResourceType() == ResourceType.USER && ( event.getOperationType() == OperationType.CREATE || event.getOperationType() == OperationType.DELETE)) {
countUsers(session.realms().getRealm(event.getRealmId()));
}

PrometheusExporter.instance().recordGenericAdminEvent(event);
}

private void countUsers(RealmModel realm) {
int count = session.users().getUsersCount(realm);
PrometheusExporter.instance().recordCountUsers(realm.getId(), count);
}

private void logEventDetails(Event event) {
logger.infof("Received user event of type %s in realm %s",
event.getType().name(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public class MetricsEventListenerFactory implements EventListenerProviderFactory

@Override
public EventListenerProvider create(KeycloakSession session) {
return new MetricsEventListener();
return new MetricsEventListener(session);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.Counter;
import io.prometheus.client.Gauge;
import io.prometheus.client.Histogram;
import io.prometheus.client.exporter.PushGateway;
import io.prometheus.client.exporter.common.TextFormat;
Expand Down Expand Up @@ -39,6 +40,7 @@ public final class PrometheusExporter {
final Counter totalRegistrationsErrors;
final Counter responseErrors;
final Histogram requestDuration;
final Gauge countUsers;
final PushGateway PUSH_GATEWAY;

private PrometheusExporter() {
Expand Down Expand Up @@ -91,6 +93,12 @@ private PrometheusExporter() {
.labelNames("method")
.register();

countUsers = Gauge.build()
.name("keycloak_count_users")
.help("Count users")
.labelNames("realm")
.register();

// Counters for all user events
for (EventType type : EventType.values()) {
if (type.equals(EventType.LOGIN) || type.equals(EventType.LOGIN_ERROR) || type.equals(EventType.REGISTER)) {
Expand Down Expand Up @@ -250,6 +258,17 @@ private String getIdentityProvider(Event event) {
return identityProvider;
}

/**
* Set count of users
*
* @param realmId The realm
* @param count Count users
*/
public void recordCountUsers(final String realmId, int count) {
countUsers.labels(nullToEmpty(realmId)).set(count);
pushAsync();
}

/**
* Write the Prometheus formatted values of all counters and
* gauges to the stream
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,12 @@ public void shouldCorrectlyRecordResponseErrors() throws IOException {
assertGenericMetric("keycloak_response_errors", 1, tuple("code", "500"), tuple("method", "POST"));
}

@Test
public void shouldCorrectlyRecordCountUsers() throws IOException {
PrometheusExporter.instance().recordCountUsers(DEFAULT_REALM, 5);
assertGenericMetric("keycloak_count_users", 5, tuple("realm", DEFAULT_REALM));
}

@Test
public void shouldTolerateNullLabels() throws IOException {
final Event nullEvent = new Event();
Expand Down