Coverage Report

Created: 2026-12-01 06:14

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/mod_auth_openidc/src/metrics.c
Line
Count
Source
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one
3
 * or more contributor license agreements.  See the NOTICE file
4
 * distributed with this work for additional information
5
 * regarding copyright ownership.  The ASF licenses this file
6
 * to you under the Apache License, Version 2.0 (the
7
 * "License"); you may not use this file except in compliance
8
 * with the License.  You may obtain a copy of the License at
9
 *
10
 *   http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing,
13
 * software distributed under the License is distributed on an
14
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
 * KIND, either express or implied.  See the License for the
16
 * specific language governing permissions and limitations
17
 * under the License.
18
 */
19
20
/***************************************************************************
21
 * Copyright (C) 2023-2026 ZmartZone Holding BV
22
 * All rights reserved.
23
 *
24
 * DISCLAIMER OF WARRANTIES:
25
 *
26
 * THE SOFTWARE PROVIDED HEREUNDER IS PROVIDED ON AN "AS IS" BASIS, WITHOUT
27
 * ANY WARRANTIES OR REPRESENTATIONS EXPRESS, IMPLIED OR STATUTORY; INCLUDING,
28
 * WITHOUT LIMITATION, WARRANTIES OF QUALITY, PERFORMANCE, NONINFRINGEMENT,
29
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  NOR ARE THERE ANY
30
 * WARRANTIES CREATED BY A COURSE OR DEALING, COURSE OF PERFORMANCE OR TRADE
31
 * USAGE.  FURTHERMORE, THERE ARE NO WARRANTIES THAT THE SOFTWARE WILL MEET
32
 * YOUR NEEDS OR BE FREE FROM ERRORS, OR THAT THE OPERATION OF THE SOFTWARE
33
 * WILL BE UNINTERRUPTED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
34
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
35
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES HOWEVER CAUSED AND ON ANY THEORY OF
36
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
37
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
38
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39
 *
40
 * @Author: Hans Zandbelt - hans.zandbelt@openidc.com
41
 */
42
43
// clang-format off
44
45
#ifndef WIN32
46
#include <unistd.h>
47
#endif
48
49
#include "util/util.h"
50
#include "http.h"
51
#include "cache/cache.h"
52
#include "cfg/cfg_int.h"
53
#include "metrics.h"
54
#include <limits.h>
55
#include <apr_atomic.h>
56
#include <apr_shm.h>
57
#include <apr_lib.h>
58
59
// NB: formatting matters for docs script from here until clang-format on
60
61
// KEEP THIS: start-of-classes
62
63
#define OM_CLASS_AUTH_TYPE     "authtype"       // Request counter, overall and per AuthType: openid-connect, oauth20 and auth-openidc.
64
#define OM_CLASS_AUTHN         "authn"          // Authentication request creation and response processing.
65
#define OM_CLASS_AUTHZ         "authz"          // Authorization errors per OIDCUnAutzAction (per Require statement, not overall).
66
#define OM_CLASS_REQUIRE_CLAIM "require.claim"  // Match/failure count of Require claim directives (per Require statement, not overall).
67
#define OM_CLASS_CLAIM         "claim"          // Claims per value
68
#define OM_CLASS_PROVIDER      "provider"       // Requests to the provider [token, userinfo, metadata] endpoints.
69
#define OM_CLASS_SESSION       "session"        // Existing session processing.
70
#define OM_CLASS_CACHE         "cache"          // Cache read/write timings and errors.
71
#define OM_CLASS_LOGOUT        "logout"         // Front- and back-channel logout processing.
72
#define OM_CLASS_REDIRECT_URI  "redirect_uri"   // Requests to the Redirect URI, per type.
73
#define OM_CLASS_CONTENT       "content"        // Requests to the content handler, per type of request: info, metrics, jwks, etc.
74
75
// KEEP THIS: end-of-classes
76
77
// NB: order must match the oidc_metrics_timing_type_t enum type in metrics.h
78
79
const oidc_metrics_timing_info_t _oidc_metrics_timings_info[] = {
80
81
  // KEEP THIS: start-of-timers
82
83
  { OM_CLASS_AUTH_TYPE, "handler", "the overall authn+authz processing time" },
84
85
  { OM_CLASS_AUTHN,    "request",  "authentication requests" },
86
  { OM_CLASS_AUTHN,    "response", "authentication responses" },
87
88
  { OM_CLASS_SESSION,  "valid",    "successfully validated existing sessions" },
89
90
  { OM_CLASS_PROVIDER, "metadata", "provider discovery document requests" },
91
  { OM_CLASS_PROVIDER, "token",    "provider token requests" },
92
  { OM_CLASS_PROVIDER, "refresh",  "provider refresh token requests" },
93
  { OM_CLASS_PROVIDER, "userinfo", "provider userinfo requests" },
94
  { OM_CLASS_PROVIDER, "jwks",     "provider JWKs document requests" },
95
  { OM_CLASS_PROVIDER, "par",      "provider pushed authorization requests" },
96
97
  { OM_CLASS_CACHE,    "read",     "cache read requests" },
98
  { OM_CLASS_CACHE,    "write",    "cache write requests" },
99
100
  // KEEP THIS: end-of-timers
101
102
};
103
104
// NB: order must match the oidc_metrics_counter_type_t enum type in metrics.h
105
106
const oidc_metrics_counter_info_t _oidc_metrics_counters_info[] = {
107
#define OIDC_METRICS_COUNTER_INFO(id, class, name, desc) {class, name, desc},
108
    OIDC_METRICS_COUNTERS_LIST(OIDC_METRICS_COUNTER_INFO)
109
#undef OIDC_METRICS_COUNTER_INFO
110
};
111
112
// clang-format on
113
114
/* one entry per oidc_metrics_counter_type_t value */
115
OIDC_STATIC_ASSERT(sizeof(_oidc_metrics_counters_info) / sizeof(oidc_metrics_counter_info_t) == OM_NUMBER_OF_COUNTERS,
116
       counters_info_matches_enum);
117
/* one entry per oidc_metrics_timing_type_t value */
118
OIDC_STATIC_ASSERT(sizeof(_oidc_metrics_timings_info) / sizeof(oidc_metrics_timing_info_t) == OM_NUMBER_OF_TIMINGS,
119
       timings_info_matches_enum);
120
121
typedef struct oidc_metrics_t {
122
  apr_pool_t *pool;
123
  apr_hash_t *counters;
124
  apr_hash_t *timings;
125
} oidc_metrics_t;
126
127
// pointer to the shared memory segment that holds the JSON metrics data
128
static apr_shm_t *_oidc_metrics_cache = NULL;
129
// flag to record if we are a parent process or a child process
130
static apr_byte_t _oidc_metrics_is_parent = FALSE;
131
/* Atomic stop flag shared by the flush, cleanup, and child-init paths. */
132
static volatile apr_uint32_t _oidc_metrics_thread_exit = 0;
133
// mutex to protect the shared memory storage
134
static oidc_cache_mutex_t *_oidc_metrics_global_mutex = NULL;
135
// pointer to the thread that periodically writes the locally gathered metrics to shared memory
136
static apr_thread_t *_oidc_metrics_thread = NULL;
137
// pid that owns _oidc_metrics_thread; used to tell a post-fork stale handle from a same-process double-init
138
static pid_t _oidc_metrics_thread_pid = 0;
139
// local in-memory cached metrics
140
static oidc_metrics_t _oidc_metrics = {NULL, NULL, NULL};
141
// mutex to protect the local metrics hash table
142
static oidc_cache_mutex_t *_oidc_metrics_process_mutex = NULL;
143
144
// default shared memory write interval in seconds
145
0
#define OIDC_METRICS_CACHE_STORAGE_INTERVAL_DEFAULT 5000
146
147
// maximum length of the string representation of the global JSON metrics data in shared memory
148
//   1024 sample size (compact, long keys, large json_int values, no description), timing + counter
149
//   256 number of individual metrics collected
150
//     4 number of vhosts supported
151
0
#define OIDC_METRICS_CACHE_JSON_MAX_DEFAULT (1024 * 256 * 4)
152
153
// NB: "label" is the millisecond le= label of the legacy (deprecated) Prometheus families,
154
//     "label_seconds" the seconds le= label of the idiomatic _seconds families
155
typedef struct oidc_metrics_bucket_t {
156
  const char *name;
157
  const char *label;
158
  const char *label_seconds;
159
  apr_time_t threshold;
160
} oidc_metrics_bucket_t;
161
162
// clang-format off
163
164
static oidc_metrics_bucket_t _oidc_metric_buckets[] = {
165
  { "le01", "le=\"0.1\"", "le=\"0.0001\"", 100 },
166
  { "le05", "le=\"0.5\"", "le=\"0.0005\"", 500 },
167
  { "le1", "le=\"1\"", "le=\"0.001\"", apr_time_from_msec(1) },
168
  { "le5", "le=\"5\"", "le=\"0.005\"", apr_time_from_msec(5) },
169
  { "le10", "le=\"10\"", "le=\"0.01\"", apr_time_from_msec(10) },
170
  { "le50", "le=\"50\"", "le=\"0.05\"", apr_time_from_msec(50) },
171
  { "le100", "le=\"100\"", "le=\"0.1\"", apr_time_from_msec(100) },
172
  { "le500", "le=\"500\"", "le=\"0.5\"", apr_time_from_msec(500) },
173
  { "le1000", "le=\"1000\"", "le=\"1\"", apr_time_from_msec(1000) },
174
    { "le5000", "le=\"5000\"", "le=\"5\"", apr_time_from_msec(5000) },
175
    { "le10000", "le=\"10000\"", "le=\"10\"", apr_time_from_msec(10000) },
176
    { "le30000", "le=\"30000\"", "le=\"30\"", apr_time_from_msec(30000) },
177
    { "inf", "le=\"+Inf\"", "le=\"+Inf\"", 0 }
178
};
179
180
// clang-format on
181
182
0
#define OIDC_METRICS_BUCKET_NUM ((int)(sizeof(_oidc_metric_buckets) / sizeof(oidc_metrics_bucket_t)))
183
184
// NB: matters for Prometheus formatting
185
0
#define OIDC_METRICS_SUM "sum"
186
0
#define OIDC_METRICS_COUNT "count"
187
188
#define OIDC_METRICS_SPECS "specs"
189
190
0
#define OIDC_METRICS_JSON_CLASS_NAME "class"
191
0
#define OIDC_METRICS_JSON_METRIC_NAME "name"
192
0
#define OIDC_METRICS_JSON_DESC "desc"
193
194
0
#define OIDC_METRICS_TIMINGS "timings"
195
0
#define OIDC_METRICS_COUNTERS "counters"
196
197
/*
198
 * convert a Jansson number to a string: apr_psprintf does not understand OIDC_JSON_INT_FORMAT
199
 * ("%lld"), APR spells a 64-bit integer as APR_INT64_T_FMT, and oidc_json_int_t is at most 64
200
 * bits wide
201
 */
202
0
static inline char *_json_int2str(apr_pool_t *pool, oidc_json_int_t n) {
203
0
  return apr_psprintf(pool, "%" APR_INT64_T_FMT, (apr_int64_t)n);
204
0
}
205
206
0
#define OIDC_METRICS_INT_MAX OIDC_JSON_INT_MAX
207
208
/*
209
 * check Jansson specific integer/long number overrun; add is never negative, and a negative cur (which only a
210
 * corrupted shared memory segment can hold) cannot overflow by adding it, while MAX - cur itself would
211
 */
212
0
static inline int _is_overflow(server_rec *s, oidc_json_int_t cur, oidc_json_int_t add) {
213
0
  if ((cur > 0) && (add > (OIDC_METRICS_INT_MAX - cur))) {
214
0
    oidc_swarn(s,
215
0
         "reset metrics since the size (%s) of the integer value would be larger than the "
216
0
         "JSON/libjansson maximum "
217
0
         "(%s)",
218
0
         _json_int2str(s->process->pool, add), _json_int2str(s->process->pool, OIDC_METRICS_INT_MAX));
219
0
    return 1;
220
0
  }
221
0
  return 0;
222
0
}
223
224
// single counter container
225
typedef struct oidc_metrics_counter_t {
226
  oidc_json_int_t count;
227
} oidc_metrics_counter_t;
228
229
// single timing stats container
230
typedef struct oidc_metrics_timing_t {
231
  oidc_json_int_t buckets[OIDC_METRICS_BUCKET_NUM];
232
  apr_time_t sum;
233
  oidc_json_int_t count;
234
} oidc_metrics_timing_t;
235
236
/*
237
 * forget the local collection pool when it goes away: it is a child of the process pool, and at exit
238
 * apr_pool_destroy() of the process pool destroys it before pconf (an older sibling) and so before the pconf
239
 * cleanup that runs oidc_metrics_cleanup(), which must then not destroy it a second time
240
 */
241
0
static apr_status_t oidc_metrics_local_pool_cleanup(void *data) {
242
0
  _oidc_metrics.pool = NULL;
243
0
  _oidc_metrics.counters = NULL;
244
0
  _oidc_metrics.timings = NULL;
245
0
  return APR_SUCCESS;
246
0
}
247
248
/*
249
 * Reinitialize the per-process collection tables in a dedicated child pool.
250
 * Clearing this pool after a flush reclaims all nested hashes, keys and values
251
 * in one operation; the process mutex must be held once request threads exist.
252
 */
253
0
static apr_byte_t oidc_metrics_local_reset(server_rec *s) {
254
0
  apr_pool_t *pool = _oidc_metrics.pool;
255
256
0
  if (pool == NULL) {
257
0
    if (apr_pool_create(&pool, s->process->pool) != APR_SUCCESS) {
258
0
      oidc_serror(s, "apr_pool_create failed: cannot initialize local metrics");
259
0
      return FALSE;
260
0
    }
261
0
  } else {
262
    /* NB: this runs (and so consumes) oidc_metrics_local_pool_cleanup as well, hence the re-registration */
263
0
    apr_pool_clear(pool);
264
0
  }
265
0
  apr_pool_cleanup_register(pool, NULL, oidc_metrics_local_pool_cleanup, apr_pool_cleanup_null);
266
267
0
  _oidc_metrics.pool = pool;
268
0
  _oidc_metrics.counters = apr_hash_make(pool);
269
0
  _oidc_metrics.timings = apr_hash_make(pool);
270
0
  return TRUE;
271
0
}
272
273
// context holder for parsing valid classnames
274
typedef struct oidc_metrics_add_classname_ctx_t {
275
  apr_pool_t *pool;
276
  char **valid_names;
277
} oidc_metrics_add_classname_ctx_t;
278
279
/*
280
 * loop function for parsing valid classnames
281
 */
282
0
static int oidc_metrics_add_classnames(void *rec, const char *key, const char *value) {
283
0
  oidc_metrics_add_classname_ctx_t *ctx = (oidc_metrics_add_classname_ctx_t *)rec;
284
0
  *ctx->valid_names = apr_psprintf(ctx->pool, "%s%s%s", *ctx->valid_names ? *ctx->valid_names : "",
285
0
           *ctx->valid_names ? " | " : "", value);
286
0
  return 1;
287
0
}
288
289
/*
290
 * check if the provided value is a valid classname
291
 */
292
0
apr_byte_t oidc_metrics_is_valid_classname(apr_pool_t *pool, const char *name, char **valid_names) {
293
0
  int i = 0;
294
0
  int n = 0;
295
0
  apr_table_t *names = apr_table_make(pool, 1);
296
0
  oidc_metrics_add_classname_ctx_t ctx = {pool, valid_names};
297
298
0
  n = sizeof(_oidc_metrics_timings_info) / sizeof(oidc_metrics_timing_info_t);
299
0
  for (i = 0; i < n; i++) {
300
0
    apr_table_set(names, _oidc_metrics_timings_info[i].class_name,
301
0
            _oidc_metrics_timings_info[i].class_name);
302
0
  }
303
0
  n = sizeof(_oidc_metrics_counters_info) / sizeof(oidc_metrics_counter_info_t);
304
0
  for (i = 0; i < n; i++) {
305
    // NB: "claim" is the only counter class with a name/value option and is special-cased here (rather
306
    // than driven from a static list)
307
0
    if (_oidc_strcmp(_oidc_metrics_counters_info[i].class_name, "claim") != 0)
308
0
      apr_table_set(names, _oidc_metrics_counters_info[i].class_name,
309
0
              _oidc_metrics_counters_info[i].class_name);
310
0
  }
311
312
0
  *valid_names = NULL;
313
0
  apr_table_do(oidc_metrics_add_classnames, &ctx, names, NULL);
314
0
  *valid_names = apr_psprintf(pool, "%s%s%s", *valid_names ? *valid_names : "", *valid_names ? " | " : "",
315
0
            "claim.id_token.* | claim.userinfo.*");
316
317
0
  return apr_table_get(names, name) ? TRUE
318
0
            : ((_oidc_strstr(name, "claim.id_token.") != NULL) ||
319
0
               (_oidc_strstr(name, "claim.userinfo.") != NULL));
320
0
}
321
322
/*
323
 * retrieve environment variable integer with default setting
324
 */
325
0
static inline int _oidc_metrics_get_env_int(const char *name, int dval) {
326
0
  return _oidc_str_to_int(getenv(name), dval);
327
0
}
328
329
0
#define OIDC_METRICS_CACHE_JSON_MAX_ENV_VAR "OIDC_METRICS_CACHE_JSON_MAX"
330
331
/*
332
 * fixed self-health header kept in the shared memory segment in front of the JSON metrics data;
333
 * 32-bit members only so the apr_atomic_*32 functions cover every supported APR version
334
 */
335
typedef struct oidc_metrics_shm_hdr_t {
336
  // number of flushes/resets that could not be stored because the JSON data outgrew the segment
337
  apr_uint32_t flush_errors;
338
  // seconds-since-epoch timestamp of the last completed flush cycle of this process' flush thread
339
  apr_uint32_t last_flush;
340
} oidc_metrics_shm_hdr_t;
341
342
0
#define OIDC_METRICS_SHM_HDR_SIZE (APR_ALIGN_DEFAULT(sizeof(oidc_metrics_shm_hdr_t)))
343
344
0
static inline oidc_metrics_shm_hdr_t *_oidc_metrics_shm_hdr(void) {
345
0
  return (oidc_metrics_shm_hdr_t *)apr_shm_baseaddr_get(_oidc_metrics_cache);
346
0
}
347
348
0
static inline char *_oidc_metrics_shm_json(void) {
349
0
  return ((char *)apr_shm_baseaddr_get(_oidc_metrics_cache)) + OIDC_METRICS_SHM_HDR_SIZE;
350
0
}
351
352
static apr_size_t _g_oidc_metrics_shm_size = 0;
353
354
/*
355
 * get the maximum size of the serialized JSON metrics data: directive, environment variable or default
356
 */
357
0
static inline apr_size_t _oidc_metrics_shm_size(server_rec *s) {
358
0
  if (_g_oidc_metrics_shm_size == 0) {
359
0
    const oidc_cfg_t *cfg = ap_get_module_config(s->module_config, &auth_openidc_module);
360
0
    int n = oidc_cfg_metrics_cache_json_max_get(cfg);
361
0
    if (n == OIDC_CONFIG_POS_INT_UNSET)
362
0
      n = _oidc_metrics_get_env_int(OIDC_METRICS_CACHE_JSON_MAX_ENV_VAR,
363
0
                  OIDC_METRICS_CACHE_JSON_MAX_DEFAULT);
364
0
    if ((n < 1) || (n > 1024 * 256 * 4 * 100)) {
365
0
      oidc_serror(s, "environment value %s out of bounds, fallback to default",
366
0
            OIDC_METRICS_CACHE_JSON_MAX_ENV_VAR);
367
0
      _g_oidc_metrics_shm_size = OIDC_METRICS_CACHE_JSON_MAX_DEFAULT;
368
0
    } else {
369
0
      _g_oidc_metrics_shm_size = n;
370
0
    }
371
0
  }
372
0
  return _g_oidc_metrics_shm_size;
373
0
}
374
375
/*
376
 * retrieve the (JSON) serialized (global) metrics data from shared memory
377
 */
378
0
static inline char *_oidc_metrics_storage_get(server_rec *s, apr_pool_t *pool) {
379
0
  const char *p = _oidc_metrics_shm_json();
380
0
  return p && (*p != 0) ? apr_pstrndup(pool, p, _oidc_metrics_shm_size(s)) : NULL;
381
0
}
382
383
/*
384
 * store the serialized (global) metrics data in shared memory
385
 */
386
0
static inline void _oidc_metrics_storage_set(server_rec *s, const char *value) {
387
0
  char *p = _oidc_metrics_shm_json();
388
0
  if (value) {
389
0
    apr_size_t n = _oidc_strlen(value) + 1;
390
0
    if (n > _oidc_metrics_shm_size(s)) {
391
0
      apr_atomic_inc32(&_oidc_metrics_shm_hdr()->flush_errors);
392
0
      oidc_serror(s,
393
0
            "json value too large: set or increase " OIDCMetricsCacheJsonMax
394
0
            " (or system environment variable %s) to a value "
395
0
            "larger than %" APR_SIZE_T_FMT,
396
0
            OIDC_METRICS_CACHE_JSON_MAX_ENV_VAR, _oidc_metrics_shm_size(s));
397
0
    } else {
398
0
      _oidc_memcpy(p, value, n);
399
0
    }
400
0
  } else {
401
0
    *p = 0;
402
0
  }
403
0
}
404
405
/*
406
 * parse a string into a JSON object
407
 */
408
0
static oidc_json_t *oidc_metrics_json_load(apr_pool_t *pool, const char *s_json, char **s_err) {
409
0
  oidc_json_t *json = NULL;
410
0
  if (s_json == NULL)
411
0
    s_json = "{}";
412
0
  oidc_json_parse(pool, s_json, 0, &json, s_err);
413
0
  return json;
414
0
}
415
416
/*
417
 * parse a string into a JSON object in a server_rec context
418
 */
419
0
static oidc_json_t *oidc_metrics_json_parse_s(server_rec *s, apr_pool_t *pool, const char *s_json) {
420
0
  char *s_err = NULL;
421
0
  oidc_json_t *json = oidc_metrics_json_load(pool, s_json, &s_err);
422
0
  if (json == NULL)
423
0
    oidc_serror(s, "JSON parsing failed: %s", s_err);
424
0
  return json;
425
0
}
426
427
/*
428
 * recursively reset all integer leaf values within a JSON object tree to 0
429
 */
430
0
static void oidc_metrics_reset_integer_tree(oidc_json_t *json) {
431
0
  void *iter = oidc_json_object_iter(json);
432
0
  while (iter) {
433
0
    oidc_json_t *value = oidc_json_object_iter_value(iter);
434
0
    if (oidc_json_is_integer(value))
435
0
      oidc_json_integer_set(value, 0);
436
0
    else if (oidc_json_is_object(value))
437
0
      oidc_metrics_reset_integer_tree(value);
438
0
    iter = oidc_json_object_iter_next(json, iter);
439
0
  }
440
0
}
441
442
/*
443
 * reset a single timings entry (buckets, sum, count) to 0
444
 */
445
0
static void oidc_metrics_reset_timer(oidc_json_t *j_entry) {
446
0
  for (int i = 0; i < OIDC_METRICS_BUCKET_NUM; i++)
447
0
    oidc_json_object_set_new(j_entry, _oidc_metric_buckets[i].name, oidc_json_integer(0));
448
0
  oidc_json_object_set_new(j_entry, OIDC_METRICS_SUM, oidc_json_integer(0));
449
0
  oidc_json_object_set_new(j_entry, OIDC_METRICS_COUNT, oidc_json_integer(0));
450
0
}
451
452
/*
453
 * reset all counter and timer entries for a single server in the JSON data
454
 */
455
0
static void oidc_metrics_reset_server(const oidc_json_t *j_server) {
456
0
  oidc_json_t *j_entries = NULL;
457
0
  void *iter = NULL;
458
459
0
  j_entries = oidc_json_object_get(j_server, OIDC_METRICS_COUNTERS);
460
0
  if (j_entries)
461
0
    oidc_metrics_reset_integer_tree(j_entries);
462
463
0
  j_entries = oidc_json_object_get(j_server, OIDC_METRICS_TIMINGS);
464
0
  iter = oidc_json_object_iter(j_entries);
465
0
  while (iter) {
466
0
    oidc_metrics_reset_timer(oidc_json_object_iter_value(iter));
467
0
    iter = oidc_json_object_iter_next(j_entries, iter);
468
0
  }
469
0
}
470
471
/*
472
 * reset the serialized (global) metrics data in shared memory
473
 */
474
0
static inline void oidc_metrics_storage_reset(server_rec *s, apr_pool_t *pool) {
475
0
  const char *s_json = NULL;
476
0
  oidc_json_t *json = NULL;
477
0
  void *iter = NULL;
478
479
  /* get the global stringified JSON metrics */
480
0
  s_json = _oidc_metrics_storage_get(s, pool);
481
482
  /* parse the metrics string to JSON */
483
0
  json = oidc_metrics_json_parse_s(s, pool, s_json);
484
0
  if (json == NULL)
485
0
    json = oidc_json_object();
486
487
0
  iter = oidc_json_object_iter(json);
488
0
  while (iter) {
489
0
    oidc_metrics_reset_server(oidc_json_object_iter_value(iter));
490
0
    iter = oidc_json_object_iter_next(json, iter);
491
0
  }
492
493
  /* serialize the metrics data, preserve order is required for Prometheus */
494
0
  s_json = oidc_json_encode(pool, json, OIDC_JSON_COMPACT | OIDC_JSON_PRESERVE_ORDER);
495
496
  /* free the JSON data */
497
0
  oidc_json_decref(json);
498
499
  /* store the serialized metrics data in shared memory */
500
0
  _oidc_metrics_storage_set(s, s_json);
501
0
}
502
503
/*
504
 * create a new timings entry in the collected JSON data
505
 */
506
0
static oidc_json_t *oidc_metrics_timings_new(const oidc_metrics_timing_t *timing) {
507
0
  oidc_json_t *entry = oidc_json_object();
508
0
  for (int i = 0; i < OIDC_METRICS_BUCKET_NUM; i++)
509
0
    oidc_json_object_set_new(entry, _oidc_metric_buckets[i].name, oidc_json_integer(timing->buckets[i]));
510
  /* the sum is kept in microseconds so the _seconds Prometheus family is exact; the
511
   * (documented) json format converts to milliseconds at presentation time */
512
0
  oidc_json_object_set_new(entry, OIDC_METRICS_SUM, oidc_json_integer(timing->sum));
513
0
  oidc_json_object_set_new(entry, OIDC_METRICS_COUNT, oidc_json_integer(timing->count));
514
0
  return entry;
515
0
}
516
517
/*
518
 * update an entry in the collected JSON data
519
 */
520
0
static void oidc_metrics_timings_update(server_rec *s, const oidc_json_t *entry, const oidc_metrics_timing_t *timing) {
521
0
  oidc_json_t *j_member = NULL;
522
0
  oidc_json_int_t n = 0;
523
0
  oidc_json_int_t v = 0;
524
525
  /* every member gets the same overflow reset as the sum: none is ever close to the maximum unless the shared
526
   * memory segment was corrupted, but the addition would then overflow a signed integer */
527
0
  for (int i = 0; i < OIDC_METRICS_BUCKET_NUM; i++) {
528
0
    j_member = oidc_json_object_get(entry, _oidc_metric_buckets[i].name);
529
0
    n = oidc_json_integer_value(j_member);
530
0
    if (_is_overflow(s, n, timing->buckets[i]))
531
0
      n = 0;
532
0
    oidc_json_integer_set(j_member, n + timing->buckets[i]);
533
0
  }
534
535
0
  j_member = oidc_json_object_get(entry, OIDC_METRICS_SUM);
536
0
  n = oidc_json_integer_value(j_member);
537
538
  /* microseconds, matching oidc_metrics_timings_new */
539
0
  v = timing->sum;
540
0
  if (_is_overflow(s, n, v))
541
0
    n = 0;
542
543
0
  oidc_json_integer_set(j_member, n + v);
544
545
0
  j_member = oidc_json_object_get(entry, OIDC_METRICS_COUNT);
546
0
  n = oidc_json_integer_value(j_member);
547
0
  if (_is_overflow(s, n, timing->count))
548
0
    n = 0;
549
0
  oidc_json_integer_set(j_member, n + timing->count);
550
0
}
551
552
0
#define OIDC_METRICS_VALUE_DEFAULT "_"
553
554
/*
555
 * value helper to make sure it is not empty
556
 */
557
0
static inline const char *_metrics_value2key(const char *value) {
558
0
  return (value && _oidc_strcmp(value, "") != 0) ? value : OIDC_METRICS_VALUE_DEFAULT;
559
0
}
560
561
/*
562
 * true when a counter's local values include any other than the default (no value)
563
 */
564
0
static apr_byte_t oidc_metrics_counter_has_values(apr_hash_t *htable) {
565
0
  const char *value = NULL;
566
0
  for (apr_hash_index_t *hi = apr_hash_first(NULL, htable); hi; hi = apr_hash_next(hi)) {
567
0
    apr_hash_this(hi, (const void **)&value, NULL, NULL);
568
0
    if (_oidc_strcmp(value, OIDC_METRICS_VALUE_DEFAULT) != 0)
569
0
      return TRUE;
570
0
  }
571
0
  return FALSE;
572
0
}
573
574
/*
575
 * create a new counter entry in the collected JSON data: a counter only ever recorded without a value is a plain
576
 * integer, one recorded with values is an object keyed by value, which keeps any count recorded without a value
577
 * under the default key; the same counter can be recorded both ways, e.g. a claim that is empty for one user and
578
 * not for another, or an error counter labeled with a failure reason only when one was recorded
579
 */
580
0
static oidc_json_t *oidc_metrics_counter_new(apr_hash_t *htable) {
581
0
  oidc_metrics_counter_t *counter = NULL;
582
0
  const char *value = NULL;
583
0
  oidc_json_t *j_values = NULL;
584
585
0
  if (oidc_metrics_counter_has_values(htable) == FALSE) {
586
0
    counter = apr_hash_get(htable, OIDC_METRICS_VALUE_DEFAULT, APR_HASH_KEY_STRING);
587
0
    return oidc_json_integer(counter ? counter->count : 0);
588
0
  }
589
590
0
  j_values = oidc_json_object();
591
0
  for (apr_hash_index_t *hi = apr_hash_first(NULL, htable); hi; hi = apr_hash_next(hi)) {
592
0
    apr_hash_this(hi, (const void **)&value, NULL, (void **)&counter);
593
0
    oidc_json_object_set_new(j_values, value, oidc_json_integer(counter->count));
594
0
  }
595
0
  return j_values;
596
0
}
597
598
/*
599
 * update a counter entry in the collected JSON data
600
 */
601
0
static void oidc_metrics_counter_update(server_rec *s, oidc_json_t *j_counter, apr_hash_t *htable) {
602
0
  oidc_json_int_t v = 0;
603
0
  oidc_metrics_counter_t *counter = NULL;
604
0
  char *value = NULL;
605
0
  oidc_json_t *j_value = NULL;
606
0
  for (apr_hash_index_t *hi = apr_hash_first(NULL, htable); hi; hi = apr_hash_next(hi)) {
607
0
    apr_hash_this(hi, (const void **)&value, NULL, (void **)&counter);
608
    /* the default value is the counter itself only while it is an integer (oidc_metrics_counter_new) */
609
0
    if (oidc_json_is_integer(j_counter) && (_oidc_strcmp(value, OIDC_METRICS_VALUE_DEFAULT) == 0)) {
610
0
      j_value = j_counter;
611
0
    } else {
612
0
      j_value = oidc_json_object_get(j_counter, value);
613
0
      if (j_value == NULL) {
614
0
        oidc_json_object_set_new(j_counter, value, oidc_json_integer(counter->count));
615
0
        continue;
616
0
      }
617
0
    }
618
0
    v = oidc_json_integer_value(j_value);
619
0
    if (_is_overflow(s, v, counter->count))
620
0
      v = 0;
621
0
    oidc_json_integer_set(j_value, v + counter->count);
622
0
  }
623
0
}
624
625
/*
626
 * get or create the vhost entry in the global metrics
627
 */
628
0
static oidc_json_t *oidc_metrics_server_get(oidc_json_t *json, const char *name) {
629
0
  oidc_json_t *j_server = oidc_json_object_get(json, name);
630
0
  if (j_server == NULL) {
631
0
    j_server = oidc_json_object();
632
0
    oidc_json_object_set_new(j_server, OIDC_METRICS_COUNTERS, oidc_json_object());
633
0
    oidc_json_object_set_new(j_server, OIDC_METRICS_TIMINGS, oidc_json_object());
634
0
    oidc_json_object_set_new(json, name, j_server);
635
0
  }
636
0
  return j_server;
637
0
}
638
639
/*
640
 * convert an enum type value to its corresponding string
641
 */
642
0
static inline char *_oidc_metrics_type_name2key(apr_pool_t *pool, unsigned int type, const char *name) {
643
0
  return (name == NULL) ? apr_psprintf(pool, "%u", type) : apr_psprintf(pool, "%u.%s", type, name);
644
0
}
645
646
/*
647
 * look up the info table entry for the enum type in a "<type>[.<name>]" key: the keys come out of the
648
 * JSON in the shared memory segment that this module writes itself, but a corrupted or stale segment
649
 * (or a key that does not parse) must not turn into an out-of-bounds index into the info tables, so
650
 * the type is checked against the table size right where it indexes it; NULL for a key that does not
651
 * name a type this build knows, which the callers skip
652
 */
653
0
static inline const oidc_metrics_counter_info_t *_oidc_metrics_key2counter_info(const char *key) {
654
0
  unsigned int type = 0;
655
0
  if ((key == NULL) || (sscanf(key, "%u", &type) != 1) || (type >= OM_NUMBER_OF_COUNTERS))
656
0
    return NULL;
657
0
  return &_oidc_metrics_counters_info[type];
658
0
}
659
660
0
static inline const oidc_metrics_timing_info_t *_oidc_metrics_key2timing_info(const char *key) {
661
0
  unsigned int type = 0;
662
0
  if ((key == NULL) || (sscanf(key, "%u", &type) != 1) || (type >= OM_NUMBER_OF_TIMINGS))
663
0
    return NULL;
664
0
  return &_oidc_metrics_timings_info[type];
665
0
}
666
667
/*
668
 * update an existing counter under parent[key] or create a new one from counter_hash
669
 */
670
static void oidc_metrics_counter_set_or_update(server_rec *s, oidc_json_t *parent, const char *key,
671
0
                 apr_hash_t *counter_hash) {
672
0
  oidc_json_t *j_counter = oidc_json_object_get(parent, key);
673
0
  oidc_json_t *j_values = NULL;
674
675
0
  if (j_counter == NULL) {
676
0
    oidc_json_object_set_new(parent, key, oidc_metrics_counter_new(counter_hash));
677
0
    return;
678
0
  }
679
680
  /* a counter so far only recorded without a value now has values too: turn it into an object that keeps the
681
   * count so far under the default key */
682
0
  if (oidc_json_is_integer(j_counter) && (oidc_metrics_counter_has_values(counter_hash) == TRUE)) {
683
0
    j_values = oidc_json_object();
684
0
    oidc_json_object_set(j_values, OIDC_METRICS_VALUE_DEFAULT, j_counter);
685
0
    oidc_json_object_set_new(parent, key, j_values);
686
0
    j_counter = j_values;
687
0
  }
688
689
0
  oidc_metrics_counter_update(s, j_counter, counter_hash);
690
0
}
691
692
/*
693
 * merge a single local counter entry into the global counters object;
694
 * keys of the form "class.name" are nested as j_counters[class][name]
695
 */
696
static void oidc_metrics_store_counter_entry(server_rec *s, apr_pool_t *pool, oidc_json_t *j_counters, const char *key,
697
0
               apr_hash_t *counter_hash) {
698
0
  const char *class_name = apr_pstrdup(pool, key);
699
0
  char *name = _oidc_strstr(class_name, ".");
700
0
  oidc_json_t *j_names = NULL;
701
702
0
  if (name == NULL) {
703
0
    oidc_metrics_counter_set_or_update(s, j_counters, class_name, counter_hash);
704
0
    return;
705
0
  }
706
707
0
  *name++ = '\0';
708
0
  j_names = oidc_json_object_get(j_counters, class_name);
709
0
  if (j_names == NULL) {
710
0
    j_names = oidc_json_object();
711
0
    oidc_json_object_set_new(j_names, name, oidc_metrics_counter_new(counter_hash));
712
0
    oidc_json_object_set_new(j_counters, class_name, j_names);
713
0
    return;
714
0
  }
715
716
0
  oidc_metrics_counter_set_or_update(s, j_names, name, counter_hash);
717
0
}
718
719
/*
720
 * merge all locally collected counters into the global JSON
721
 */
722
0
static void oidc_metrics_store_counters(server_rec *s, apr_pool_t *pool, oidc_json_t *json) {
723
0
  const char *name = NULL;
724
0
  const char *key = NULL;
725
0
  apr_hash_t *server_hash = NULL;
726
0
  apr_hash_t *counter_hash = NULL;
727
0
  oidc_json_t *j_counters = NULL;
728
729
0
  for (apr_hash_index_t *hi1 = apr_hash_first(NULL, _oidc_metrics.counters); hi1; hi1 = apr_hash_next(hi1)) {
730
0
    apr_hash_this(hi1, (const void **)&name, NULL, (void **)&server_hash);
731
0
    j_counters = oidc_json_object_get(oidc_metrics_server_get(json, name), OIDC_METRICS_COUNTERS);
732
0
    for (apr_hash_index_t *hi2 = apr_hash_first(NULL, server_hash); hi2; hi2 = apr_hash_next(hi2)) {
733
0
      apr_hash_this(hi2, (const void **)&key, NULL, (void **)&counter_hash);
734
0
      oidc_metrics_store_counter_entry(s, pool, j_counters, key, counter_hash);
735
0
    }
736
0
  }
737
0
}
738
739
/*
740
 * merge all locally collected timings into the global JSON
741
 */
742
0
static void oidc_metrics_store_timings(server_rec *s, oidc_json_t *json) {
743
0
  const char *name = NULL;
744
0
  const char *key = NULL;
745
0
  apr_hash_t *server_hash = NULL;
746
0
  oidc_metrics_timing_t *timing = NULL;
747
0
  oidc_json_t *j_timings = NULL;
748
0
  const oidc_json_t *j_timer = NULL;
749
750
0
  for (apr_hash_index_t *hi1 = apr_hash_first(NULL, _oidc_metrics.timings); hi1; hi1 = apr_hash_next(hi1)) {
751
0
    apr_hash_this(hi1, (const void **)&name, NULL, (void **)&server_hash);
752
0
    j_timings = oidc_json_object_get(oidc_metrics_server_get(json, name), OIDC_METRICS_TIMINGS);
753
0
    for (apr_hash_index_t *hi2 = apr_hash_first(NULL, server_hash); hi2; hi2 = apr_hash_next(hi2)) {
754
0
      apr_hash_this(hi2, (const void **)&key, NULL, (void **)&timing);
755
0
      j_timer = oidc_json_object_get(j_timings, key);
756
0
      if (j_timer != NULL)
757
0
        oidc_metrics_timings_update(s, j_timer, timing);
758
0
      else
759
0
        oidc_json_object_set_new(j_timings, key, oidc_metrics_timings_new(timing));
760
0
    }
761
0
  }
762
0
}
763
764
/*
765
 * flush the locally gathered metrics data into the global data kept in shared memory
766
 */
767
0
static apr_byte_t oidc_metrics_store(server_rec *s) {
768
0
  const char *s_json = NULL;
769
0
  oidc_json_t *json = NULL;
770
0
  apr_pool_t *pool = NULL;
771
772
0
  if ((apr_hash_count(_oidc_metrics.counters) == 0) && (apr_hash_count(_oidc_metrics.timings) == 0))
773
0
    return TRUE;
774
775
  /* everything below is scratch: the whole document is read, re-serialized and copied
776
   * into shared memory on every flush, so it must not come from the process pool,
777
   * which is never cleared for the lifetime of the server */
778
0
  if (apr_pool_create(&pool, s->process->pool) != APR_SUCCESS) {
779
0
    oidc_serror(s, "apr_pool_create failed: cannot flush metrics");
780
0
    return FALSE;
781
0
  }
782
783
  /* lock the shared memory for other processes */
784
0
  if (oidc_cache_mutex_lock(pool, s, _oidc_metrics_global_mutex) == FALSE) {
785
0
    apr_pool_destroy(pool);
786
0
    return FALSE;
787
0
  }
788
789
  /* get the global stringified JSON metrics */
790
0
  s_json = _oidc_metrics_storage_get(s, pool);
791
792
  /* parse the metrics string to JSON */
793
0
  json = oidc_metrics_json_parse_s(s, pool, s_json);
794
0
  if (json == NULL)
795
0
    json = oidc_json_object();
796
797
0
  oidc_metrics_store_counters(s, pool, json);
798
0
  oidc_metrics_store_timings(s, json);
799
800
  /* serialize the metrics data, preserve order is required for Prometheus */
801
0
  s_json = oidc_json_encode(pool, json, OIDC_JSON_COMPACT | OIDC_JSON_PRESERVE_ORDER);
802
803
  /* free the JSON data */
804
0
  oidc_json_decref(json);
805
806
  /* store the serialized metrics data in shared memory */
807
0
  _oidc_metrics_storage_set(s, s_json);
808
809
  /* unlock the shared memory for other processes; the transfer already completed, so an unlock
810
   * failure (logged by the mutex layer) still reports the data as consumed and a later cycle
811
   * cannot double-count it */
812
0
  (void)oidc_cache_mutex_unlock(pool, s, _oidc_metrics_global_mutex);
813
814
0
  apr_pool_destroy(pool);
815
0
  return TRUE;
816
0
}
817
818
0
#define OIDC_METRICS_CACHE_STORAGE_INTERVAL_ENV_VAR "OIDC_METRICS_CACHE_STORAGE_INTERVAL"
819
820
/*
821
 * obtain the metrics flush interval: directive, environment variable or default
822
 */
823
0
static inline apr_interval_time_t _oidc_metrics_interval(server_rec *s) {
824
0
  const oidc_cfg_t *cfg = ap_get_module_config(s->module_config, &auth_openidc_module);
825
0
  int n = oidc_cfg_metrics_cache_storage_interval_get(cfg);
826
0
  if (n == OIDC_CONFIG_POS_INT_UNSET)
827
0
    n = _oidc_metrics_get_env_int(OIDC_METRICS_CACHE_STORAGE_INTERVAL_ENV_VAR,
828
0
                OIDC_METRICS_CACHE_STORAGE_INTERVAL_DEFAULT);
829
0
  return apr_time_from_msec(n);
830
0
}
831
832
#define OIDC_METRICS_POLL_INTERVAL 250
833
834
/*
835
 * thread that periodically writes the local data into the shared memory
836
 */
837
0
static void *APR_THREAD_FUNC oidc_metrics_thread_run(apr_thread_t *thread, void *data) {
838
0
  server_rec *s = (server_rec *)data;
839
840
  /* sleep for a short random time <0.1s so child processes write-lock on a different frequency */
841
0
  apr_sleep(apr_time_from_msec(oidc_util_rand_int(100)));
842
843
  /* split the flush interval into POLL_INTERVAL-sized ticks so shutdown is observed quickly; if the
844
   * configured interval is shorter than POLL_INTERVAL, use it as the tick directly so we still flush
845
   * on schedule rather than busy-looping with n=0 */
846
0
  apr_interval_time_t interval = _oidc_metrics_interval(s);
847
  /* a misconfigured env var parses to 0 (or negative) — fall back to the default to avoid 0/0 below */
848
0
  if (interval <= 0)
849
0
    interval = apr_time_from_msec(OIDC_METRICS_CACHE_STORAGE_INTERVAL_DEFAULT);
850
0
  apr_interval_time_t tick = apr_time_from_msec(OIDC_METRICS_POLL_INTERVAL);
851
0
  if (tick > interval)
852
0
    tick = interval;
853
0
  int n = (int)(interval / tick);
854
855
  /* NB: test for exit only after flushing, because we need to write our local metrics into the cache before
856
   * exiting, also when asked to exit during the random sleep above */
857
0
  do {
858
859
    /* break up the sleep interval in short intervals so we can exit timely fashion without confusing Apache
860
     * at shutdown */
861
0
    for (int i = 0; (i < n) && (apr_atomic_read32(&_oidc_metrics_thread_exit) == 0); i++)
862
0
      apr_sleep(tick);
863
864
    /* lock the mutex that protects the locally cached metrics */
865
0
    if (oidc_cache_mutex_lock(s->process->pool, s, _oidc_metrics_process_mutex) == FALSE)
866
0
      continue;
867
868
    /* flush the locally cached metrics into the global shared memory */
869
0
    if (oidc_metrics_store(s) == TRUE) {
870
      /* record that a flush cycle completed, for the metrics self-health output */
871
0
      apr_atomic_set32(&_oidc_metrics_shm_hdr()->last_flush,
872
0
           (apr_uint32_t)apr_time_sec(apr_time_now()));
873
874
      /* release all allocations made while gathering this flush interval */
875
0
      oidc_metrics_local_reset(s);
876
0
    }
877
878
    /* unlock the mutex that protects the locally cached metrics */
879
0
    if (oidc_cache_mutex_unlock(s->process->pool, s, _oidc_metrics_process_mutex) == FALSE)
880
0
      break;
881
882
0
  } while (apr_atomic_read32(&_oidc_metrics_thread_exit) == 0);
883
884
  /* NB: don't call apr_thread_exit here because it seems that Apache is cleaning up its own threads */
885
886
0
  return NULL;
887
0
}
888
889
/*
890
 * stop the flush thread, which writes what it gathered into shared memory one last time on its way out; a handle
891
 * inherited over fork() names a thread that does not exist in this process and is just dropped
892
 */
893
0
static void oidc_metrics_thread_stop(server_rec *s) {
894
0
  apr_status_t rv = APR_SUCCESS;
895
896
0
  if ((_oidc_metrics_thread != NULL) && (_oidc_metrics_thread_pid == getpid())) {
897
0
    apr_atomic_set32(&_oidc_metrics_thread_exit, 1);
898
0
    if (apr_thread_join(&rv, _oidc_metrics_thread) != APR_SUCCESS)
899
0
      oidc_serror(s, "apr_thread_join failed");
900
0
    apr_atomic_set32(&_oidc_metrics_thread_exit, 0);
901
0
  }
902
0
  _oidc_metrics_thread = NULL;
903
0
  _oidc_metrics_thread_pid = 0;
904
0
}
905
906
/*
907
 * child pool cleanup: stop the flush thread before the child exits; leaving that to oidc_metrics_cleanup() is too
908
 * late, since that is a pconf cleanup which at exit only runs after apr_terminate() has already destroyed the
909
 * local collection pool that the thread clears after every flush (see oidc_metrics_local_pool_cleanup), and a
910
 * flush landing in between crashes in apr_pool_clear()
911
 */
912
0
static apr_status_t oidc_metrics_child_cleanup(void *data) {
913
0
  oidc_metrics_thread_stop((server_rec *)data);
914
0
  return APR_SUCCESS;
915
0
}
916
917
/*
918
 * server config handlers
919
 */
920
921
/*
922
 * NB: global, yet called for each vhost that has metrics enabled!
923
 */
924
0
apr_byte_t oidc_metrics_post_config(apr_pool_t *pool, server_rec *s) {
925
926
  /* make sure it gets executed exactly once! */
927
0
  if (_oidc_metrics_cache != NULL)
928
0
    return TRUE;
929
930
  /* create the shared memory segment that holds the self-health header plus the
931
   * stringified JSON formatted metrics data */
932
0
  if (apr_shm_create(&_oidc_metrics_cache, OIDC_METRICS_SHM_HDR_SIZE + _oidc_metrics_shm_size(s), NULL,
933
0
         s->process->pool) != APR_SUCCESS)
934
0
    return FALSE;
935
0
  if (_oidc_metrics_cache == NULL)
936
0
    return FALSE;
937
938
  /* initialize the shared memory segment to 0 */
939
0
  char *p = apr_shm_baseaddr_get(_oidc_metrics_cache);
940
0
  _oidc_memset(p, 0, OIDC_METRICS_SHM_HDR_SIZE + _oidc_metrics_shm_size(s));
941
942
  /* flag this as the parent, for shared memory cleanup purposes and "multiple child-init calls" detection */
943
0
  _oidc_metrics_is_parent = TRUE;
944
945
  /* create the pool and hashtables that hold local metrics data */
946
0
  if (oidc_metrics_local_reset(s) == FALSE)
947
0
    return FALSE;
948
949
  /* create and initialize the mutex that guards the shared-memory data */
950
0
  _oidc_metrics_global_mutex = oidc_cache_mutex_create(s->process->pool, TRUE);
951
0
  if (_oidc_metrics_global_mutex == NULL)
952
0
    return FALSE;
953
0
  if (oidc_cache_mutex_post_config(s->process->pool, s, _oidc_metrics_global_mutex, "metrics-global") == FALSE)
954
0
    return FALSE;
955
956
  /* create and initialize the mutex that guards the local metrics tables */
957
0
  _oidc_metrics_process_mutex = oidc_cache_mutex_create(s->process->pool, FALSE);
958
0
  if (_oidc_metrics_process_mutex == NULL)
959
0
    return FALSE;
960
0
  if (oidc_cache_mutex_post_config(s->process->pool, s, _oidc_metrics_process_mutex, "metrics-process") == FALSE)
961
0
    return FALSE;
962
963
  /* NB: no flush thread in the parent: samples are only ever recorded while handling a request, which the parent
964
   * does not do; the processes that do (including a -X single process) start one in oidc_metrics_child_init, and
965
   * a parent thread would race apr_pool_destroy() of the process pool at shutdown, which happens before the pconf
966
   * cleanup that would stop it */
967
968
0
  return TRUE;
969
0
}
970
971
/*
972
 * NB: global, yet called for each vhost that has metrics enabled!
973
 */
974
0
apr_status_t oidc_metrics_child_init(apr_pool_t *p, server_rec *s) {
975
976
  /* make sure this executes only once per child */
977
0
  if (_oidc_metrics_is_parent == FALSE)
978
0
    return APR_SUCCESS;
979
980
0
  if (oidc_cache_mutex_child_init(p, s, _oidc_metrics_global_mutex) != APR_SUCCESS)
981
0
    return APR_EGENERAL;
982
983
0
  if (oidc_cache_mutex_child_init(p, s, _oidc_metrics_process_mutex) != APR_SUCCESS)
984
0
    return APR_EGENERAL;
985
986
  /* stop an existing same-process flush thread; discard inherited handles after a fork */
987
0
  oidc_metrics_thread_stop(s);
988
0
  if (oidc_metrics_local_reset(s) == FALSE)
989
0
    return APR_EGENERAL;
990
991
  /* create the thread only after all state that it accesses has been initialized */
992
0
  if (apr_thread_create(&_oidc_metrics_thread, NULL, oidc_metrics_thread_run, s, s->process->pool) != APR_SUCCESS)
993
0
    return APR_EGENERAL;
994
0
  _oidc_metrics_thread_pid = getpid();
995
996
  /* stop it again when the child pool goes; registered after the mutex child_init calls above so that, cleanups
997
   * running last-in-first-out, the thread's final flush still finds them initialized */
998
0
  apr_pool_cleanup_register(p, s, oidc_metrics_child_cleanup, apr_pool_cleanup_null);
999
1000
  /* flag this is a child */
1001
0
  _oidc_metrics_is_parent = FALSE;
1002
1003
0
  return APR_SUCCESS;
1004
0
}
1005
1006
/*
1007
 * NB: global, yet called for each vhost that has metrics enabled!
1008
 */
1009
0
apr_status_t oidc_metrics_cleanup(server_rec *s) {
1010
1011
  /* make sure it gets executed exactly once! NB: not keyed on the flush thread, which the parent does not run
1012
   * and a child has already stopped in oidc_metrics_child_cleanup by the time it gets here */
1013
0
  if (_oidc_metrics_cache == NULL)
1014
0
    return APR_SUCCESS;
1015
1016
  /* stop the collector thread, if it still runs */
1017
0
  oidc_metrics_thread_stop(s);
1018
1019
  /* delete the shared memory segment if we are in the parent process */
1020
0
  if (_oidc_metrics_is_parent == TRUE)
1021
0
    apr_shm_destroy(_oidc_metrics_cache);
1022
0
  _oidc_metrics_cache = NULL;
1023
  /* the cached segment size lives exactly as long as the segment: the next post_config (a graceful
1024
   * restart, or the next unit test in the same process) sizes a new one from its own configuration */
1025
0
  _g_oidc_metrics_shm_size = 0;
1026
1027
  /* delete the process mutex that guards the local metrics data */
1028
0
  if (oidc_cache_mutex_destroy(s, _oidc_metrics_process_mutex) == FALSE)
1029
0
    return APR_EGENERAL;
1030
0
  _oidc_metrics_process_mutex = NULL;
1031
1032
  /* delete the process mutex that guards the global shared memory segment */
1033
0
  if (oidc_cache_mutex_destroy(s, _oidc_metrics_global_mutex) == FALSE)
1034
0
    return APR_EGENERAL;
1035
0
  _oidc_metrics_global_mutex = NULL;
1036
1037
0
  if (_oidc_metrics.pool != NULL)
1038
0
    apr_pool_destroy(_oidc_metrics.pool);
1039
0
  _oidc_metrics.pool = NULL;
1040
0
  _oidc_metrics.counters = NULL;
1041
0
  _oidc_metrics.timings = NULL;
1042
1043
0
  return APR_SUCCESS;
1044
0
}
1045
1046
/*
1047
 * sampling
1048
 */
1049
1050
/*
1051
 * obtain the local metrics hashtable for the current vhost
1052
 */
1053
0
static inline apr_hash_t *_oidc_metrics_server_hash(const request_rec *r, apr_hash_t *table) {
1054
0
  apr_hash_t *server_hash = NULL;
1055
0
  const char *name = "_default_";
1056
1057
  /* obtain the server name */
1058
0
  if (r->server->server_hostname)
1059
0
    name = r->server->server_hostname;
1060
1061
  /* get the entry to the vhost record, or newly create it */
1062
0
  server_hash = apr_hash_get(table, name, APR_HASH_KEY_STRING);
1063
0
  if (server_hash == NULL) {
1064
0
    server_hash = apr_hash_make(_oidc_metrics.pool);
1065
0
    apr_hash_set(table, name, APR_HASH_KEY_STRING, server_hash);
1066
0
  }
1067
1068
0
  return server_hash;
1069
0
}
1070
1071
/*
1072
 * retrieve or create a local timing for the specified type
1073
 */
1074
0
static inline oidc_metrics_timing_t *_oidc_metrics_timing_get(request_rec *r, unsigned int type) {
1075
0
  oidc_metrics_timing_t *result = NULL;
1076
  /* NB: the lookup key is request-scoped; only the copy the hash retains on insert
1077
   * below is allocated process-wide, since that pool is never cleared */
1078
0
  const char *key = _oidc_metrics_type_name2key(r->pool, type, NULL);
1079
0
  apr_hash_t *server_hash = _oidc_metrics_server_hash(r, _oidc_metrics.timings);
1080
  /* get the entry to the specified metric */
1081
0
  result = apr_hash_get(server_hash, key, APR_HASH_KEY_STRING);
1082
0
  if (result == NULL) {
1083
0
    result = apr_pcalloc(_oidc_metrics.pool, sizeof(oidc_metrics_timing_t));
1084
0
    apr_hash_set(server_hash, apr_pstrdup(_oidc_metrics.pool, key), APR_HASH_KEY_STRING, result);
1085
0
  }
1086
0
  return result;
1087
0
}
1088
1089
/*
1090
 * retrieve or create a counter from a hashtable of values
1091
 */
1092
0
static inline oidc_metrics_counter_t *_oidc_metrics_counter_value_get(apr_hash_t *table, const char *value) {
1093
  /* get the entry to the specified metric */
1094
0
  oidc_metrics_counter_t *result = apr_hash_get(table, value, APR_HASH_KEY_STRING);
1095
0
  if (result == NULL) {
1096
0
    result = apr_pcalloc(_oidc_metrics.pool, sizeof(oidc_metrics_counter_t));
1097
0
    apr_hash_set(table, apr_pstrdup(_oidc_metrics.pool, value), APR_HASH_KEY_STRING, result);
1098
0
  }
1099
0
  return result;
1100
0
}
1101
1102
/*
1103
 * retrieve or create a local counter for the specified type and name
1104
 */
1105
0
static inline apr_hash_t *_oidc_metrics_counter_get(request_rec *r, unsigned int type, const char *name) {
1106
0
  apr_hash_t *result = NULL;
1107
  /* NB: request-scoped lookup key, process-wide copy only on insert - see above */
1108
0
  const char *key = _oidc_metrics_type_name2key(r->pool, type, name);
1109
0
  apr_hash_t *server_hash = _oidc_metrics_server_hash(r, _oidc_metrics.counters);
1110
1111
  /* get the entry to the specified metric */
1112
0
  result = apr_hash_get(server_hash, key, APR_HASH_KEY_STRING);
1113
0
  if (result == NULL) {
1114
0
    result = apr_hash_make(_oidc_metrics.pool);
1115
0
    apr_hash_set(server_hash, apr_pstrdup(_oidc_metrics.pool, key), APR_HASH_KEY_STRING, result);
1116
0
  }
1117
1118
0
  return result;
1119
0
}
1120
1121
/*
1122
 * add/increase a counter metric in the locally cached data
1123
 */
1124
0
void oidc_metrics_counter_inc(request_rec *r, oidc_metrics_counter_type_t type, const char *name, const char *value) {
1125
0
  oidc_metrics_counter_t *counter = NULL;
1126
1127
  /* lock the local metrics cache hashtable */
1128
0
  if (oidc_cache_mutex_lock(r->pool, r->server, _oidc_metrics_process_mutex) == FALSE)
1129
0
    return;
1130
1131
  /* obtain or create the entry for the specified key */
1132
0
  counter = _oidc_metrics_counter_value_get(_oidc_metrics_counter_get(r, type, name), _metrics_value2key(value));
1133
1134
  /* performance */
1135
0
  if (counter->count <= 0) {
1136
    // new counter was created just now or reset earlier
1137
0
    counter->count = 1;
1138
0
  } else {
1139
    // increase after checking possible overflow
1140
0
    if (_is_overflow(r->server, counter->count, 1))
1141
0
      counter->count = 0;
1142
0
    counter->count++;
1143
0
  }
1144
1145
  /* unlock the local metrics cache hashtable */
1146
0
  (void)oidc_cache_mutex_unlock(r->pool, r->server, _oidc_metrics_process_mutex);
1147
0
}
1148
1149
/*
1150
 * zero out a timings entry (count, sum and all buckets)
1151
 */
1152
0
static inline void _oidc_metrics_timing_clear(oidc_metrics_timing_t *timing) {
1153
0
  timing->count = 0;
1154
0
  timing->sum = 0;
1155
0
  for (int i = 0; i < OIDC_METRICS_BUCKET_NUM; i++)
1156
0
    timing->buckets[i] = 0;
1157
0
}
1158
1159
/*
1160
 * increment every bucket whose threshold covers elapsed (buckets are ordered;
1161
 * threshold == 0 marks the open-ended last bucket)
1162
 */
1163
0
static inline void _oidc_metrics_timing_buckets_inc(oidc_metrics_timing_t *timing, apr_time_t elapsed) {
1164
0
  for (int i = 0; i < OIDC_METRICS_BUCKET_NUM; i++) {
1165
0
    if ((elapsed <= _oidc_metric_buckets[i].threshold) || (_oidc_metric_buckets[i].threshold == 0)) {
1166
0
      for (int j = i; j < OIDC_METRICS_BUCKET_NUM; j++)
1167
0
        timing->buckets[j]++;
1168
0
      break;
1169
0
    }
1170
0
  }
1171
0
}
1172
1173
/*
1174
 * add a metrics timing sample to the locally cached data
1175
 */
1176
0
void oidc_metrics_timing_add(request_rec *r, oidc_metrics_timing_type_t type, apr_time_t elapsed) {
1177
0
  oidc_metrics_timing_t *timing = NULL;
1178
1179
0
  if (elapsed < 0) {
1180
0
    oidc_warn(r, "discarding metrics timing [%s.%s]: elapsed (%" APR_TIME_T_FMT ") < 0",
1181
0
        _oidc_metrics_timings_info[type].class_name, _oidc_metrics_timings_info[type].metric_name,
1182
0
        elapsed);
1183
0
    return;
1184
0
  }
1185
1186
  /* lock the local metrics cache hashtable */
1187
0
  if (oidc_cache_mutex_lock(r->pool, r->server, _oidc_metrics_process_mutex) == FALSE)
1188
0
    return;
1189
1190
  /* obtain or create the entry for the specified key */
1191
0
  timing = _oidc_metrics_timing_get(r, type);
1192
1193
  /* reset on overflow; a freshly-created entry already has count/sum/buckets at zero */
1194
0
  if ((timing->count > 0) && _is_overflow(r->server, timing->sum, elapsed))
1195
0
    _oidc_metrics_timing_clear(timing);
1196
1197
0
  _oidc_metrics_timing_buckets_inc(timing, elapsed);
1198
0
  timing->sum += elapsed;
1199
0
  timing->count++;
1200
1201
  /* unlock the local metrics cache hashtable */
1202
0
  (void)oidc_cache_mutex_unlock(r->pool, r->server, _oidc_metrics_process_mutex);
1203
0
}
1204
1205
/*
1206
 * representation handlers
1207
 */
1208
1209
/*
1210
 * the "class.metric" name of a counter, from its info table entry
1211
 */
1212
0
static inline char *_oidc_metrics_counter_info2s(apr_pool_t *pool, const oidc_metrics_counter_info_t *info) {
1213
0
  return apr_psprintf(pool, "%s.%s", info->class_name, info->metric_name);
1214
0
}
1215
1216
/*
1217
 * the "class.metric" name of a timing, from its info table entry
1218
 */
1219
0
static inline char *_oidc_metrics_timing_info2s(apr_pool_t *pool, const oidc_metrics_timing_info_t *info) {
1220
0
  return apr_psprintf(pool, "%s.%s", info->class_name, info->metric_name);
1221
0
}
1222
1223
/*
1224
 * parse a string into a JSON object in the request_rec context
1225
 */
1226
0
static oidc_json_t *oidc_metrics_json_parse_r(request_rec *r, const char *s_json) {
1227
0
  char *s_err = NULL;
1228
0
  oidc_json_t *json = oidc_metrics_json_load(r->pool, s_json, &s_err);
1229
0
  if (json == NULL)
1230
0
    oidc_error(r, "JSON parsing failed: %s", s_err);
1231
0
  return json;
1232
0
}
1233
1234
/*
1235
 * JSON with extended descriptions/names
1236
 */
1237
0
static int oidc_metrics_handle_json(request_rec *r, const char *s_json) {
1238
1239
0
  oidc_json_t *json = NULL;
1240
0
  const oidc_json_t *j_server = NULL;
1241
0
  oidc_json_t *j_timings = NULL;
1242
0
  oidc_json_t *j_counters = NULL;
1243
0
  const oidc_json_t *j_timing = NULL;
1244
0
  oidc_json_t *j_counter = NULL;
1245
0
  oidc_json_t *o_json = NULL;
1246
0
  oidc_json_t *o_server = NULL;
1247
0
  oidc_json_t *o_counters = NULL;
1248
0
  oidc_json_t *o_counter = NULL;
1249
0
  oidc_json_t *o_timings = NULL;
1250
0
  oidc_json_t *o_timing = NULL;
1251
0
  const char *s_server = NULL;
1252
0
  const oidc_metrics_counter_info_t *c_info = NULL;
1253
0
  const oidc_metrics_timing_info_t *t_info = NULL;
1254
0
  void *i1 = NULL;
1255
0
  void *i2 = NULL;
1256
1257
  /* parse the metrics string to JSON */
1258
0
  json = oidc_metrics_json_parse_r(r, s_json);
1259
0
  if (json == NULL)
1260
0
    goto end;
1261
1262
0
  o_json = oidc_json_object();
1263
1264
0
  i1 = oidc_json_object_iter(json);
1265
0
  while (i1) {
1266
0
    s_server = oidc_json_object_iter_key(i1);
1267
0
    j_server = oidc_json_object_iter_value(i1);
1268
1269
0
    o_server = oidc_json_object();
1270
0
    oidc_json_object_set_new(o_json, s_server, o_server);
1271
1272
0
    j_counters = oidc_json_object_get(j_server, OIDC_METRICS_COUNTERS);
1273
0
    o_counters = oidc_json_object();
1274
0
    oidc_json_object_set_new(o_server, OIDC_METRICS_COUNTERS, o_counters);
1275
1276
0
    i2 = oidc_json_object_iter(j_counters);
1277
0
    while (i2) {
1278
0
      c_info = _oidc_metrics_key2counter_info(oidc_json_object_iter_key(i2));
1279
0
      if (c_info == NULL) {
1280
        /* not a counter this build knows: skip it rather than index past the info table */
1281
0
        i2 = oidc_json_object_iter_next(j_counters, i2);
1282
0
        continue;
1283
0
      }
1284
0
      j_counter = oidc_json_object_iter_value(i2);
1285
0
      o_counter = oidc_json_object();
1286
0
      if (oidc_json_is_integer(j_counter))
1287
0
        oidc_json_object_set(o_counter, "count", j_counter);
1288
0
      else
1289
0
        oidc_json_object_set_new(o_counter, "values", oidc_json_deep_copy(j_counter));
1290
0
      oidc_json_object_set_new(o_counter, OIDC_METRICS_JSON_CLASS_NAME,
1291
0
             oidc_json_string(c_info->class_name));
1292
0
      oidc_json_object_set_new(o_counter, OIDC_METRICS_JSON_METRIC_NAME,
1293
0
             oidc_json_string(c_info->metric_name));
1294
0
      oidc_json_object_set_new(o_counter, OIDC_METRICS_JSON_DESC, oidc_json_string(c_info->desc));
1295
0
      oidc_json_object_set_new(o_counters, _oidc_metrics_counter_info2s(r->pool, c_info), o_counter);
1296
0
      i2 = oidc_json_object_iter_next(j_counters, i2);
1297
0
    }
1298
1299
0
    j_timings = oidc_json_object_get(j_server, OIDC_METRICS_TIMINGS);
1300
0
    o_timings = oidc_json_object();
1301
0
    oidc_json_object_set_new(o_server, OIDC_METRICS_TIMINGS, o_timings);
1302
1303
0
    i2 = oidc_json_object_iter(j_timings);
1304
0
    while (i2) {
1305
0
      t_info = _oidc_metrics_key2timing_info(oidc_json_object_iter_key(i2));
1306
0
      if (t_info == NULL) {
1307
0
        i2 = oidc_json_object_iter_next(j_timings, i2);
1308
0
        continue;
1309
0
      }
1310
0
      j_timing = oidc_json_object_iter_value(i2);
1311
1312
0
      o_timing = oidc_json_deep_copy(j_timing);
1313
      /* the shm sum is kept in microseconds; this format documents milliseconds */
1314
0
      oidc_json_object_set_new(
1315
0
          o_timing, OIDC_METRICS_SUM,
1316
0
          oidc_json_integer(
1317
0
        oidc_json_integer_value(oidc_json_object_get(j_timing, OIDC_METRICS_SUM)) / 1000));
1318
0
      oidc_json_object_set_new(o_timing, OIDC_METRICS_JSON_CLASS_NAME,
1319
0
             oidc_json_string(t_info->class_name));
1320
0
      oidc_json_object_set_new(o_timing, OIDC_METRICS_JSON_METRIC_NAME,
1321
0
             oidc_json_string(t_info->metric_name));
1322
0
      oidc_json_object_set_new(o_timing, OIDC_METRICS_JSON_DESC, oidc_json_string(t_info->desc));
1323
1324
0
      oidc_json_object_set_new(o_timings, _oidc_metrics_timing_info2s(r->pool, t_info), o_timing);
1325
1326
0
      i2 = oidc_json_object_iter_next(j_timings, i2);
1327
0
    }
1328
0
    i1 = oidc_json_object_iter_next(json, i1);
1329
0
  }
1330
1331
0
  s_json = oidc_json_encode(r->pool, o_json, OIDC_JSON_COMPACT | OIDC_JSON_PRESERVE_ORDER);
1332
1333
0
  oidc_json_decref(o_json);
1334
0
  oidc_json_decref(json);
1335
1336
0
end:
1337
1338
  /* return the data to the caller */
1339
0
  return oidc_util_http_send(r, s_json, _oidc_strlen(s_json), OIDC_HTTP_CONTENT_TYPE_JSON, OK);
1340
0
}
1341
1342
/*
1343
 * dump the internal shared memory segment
1344
 */
1345
0
static int oidc_metrics_handle_internal(request_rec *r, const char *s_json) {
1346
0
  if (s_json == NULL)
1347
0
    return HTTP_NOT_FOUND;
1348
0
  return oidc_util_http_send(r, s_json, _oidc_strlen(s_json), OIDC_HTTP_CONTENT_TYPE_JSON, OK);
1349
0
}
1350
1351
0
#define OIDC_METRICS_SERVER_PARAM "server_name"
1352
0
#define OIDC_METRICS_COUNTER_PARAM "counter"
1353
0
#define OIDC_METRICS_NAME_PARAM "name"
1354
0
#define OIDC_METRICS_VALUE_PARAM "value"
1355
1356
/*
1357
 * find the counter entry in j_counters whose type matches "class.metric" (s_metric_param)
1358
 */
1359
static oidc_json_t *oidc_metrics_status_find_counter(request_rec *r, oidc_json_t *j_counters,
1360
0
                 const char *s_metric_param) {
1361
0
  const oidc_metrics_counter_info_t *info = NULL;
1362
0
  void *iter = oidc_json_object_iter(j_counters);
1363
0
  while (iter) {
1364
0
    info = _oidc_metrics_key2counter_info(oidc_json_object_iter_key(iter));
1365
0
    if ((info != NULL) && (_oidc_strcmp(_oidc_metrics_counter_info2s(r->pool, info), s_metric_param) == 0))
1366
0
      return oidc_json_object_iter_value(iter);
1367
0
    iter = oidc_json_object_iter_next(j_counters, iter);
1368
0
  }
1369
0
  return NULL;
1370
0
}
1371
1372
/*
1373
 * extract the requested integer value out of a counter entry:
1374
 *   - integer entry: the counter itself
1375
 *   - object entry with value-only selector: j_counter[value]
1376
 *   - object entry with name+value selectors: j_counter[name][value]
1377
 *   - object entry without a value selector: the count that was recorded without a value, if any, so
1378
 *     that a counter keeps answering for it once it is also recorded with values
1379
 */
1380
static oidc_json_t *oidc_metrics_status_select_value(oidc_json_t *j_counter, const char *s_name_param,
1381
0
                 const char *s_value_param) {
1382
0
  const oidc_json_t *j_values = NULL;
1383
0
  if (oidc_json_is_integer(j_counter))
1384
0
    return j_counter;
1385
0
  if (s_value_param == NULL)
1386
0
    s_value_param = OIDC_METRICS_VALUE_DEFAULT;
1387
0
  if (s_name_param == NULL)
1388
0
    return oidc_json_object_get(j_counter, s_value_param);
1389
0
  j_values = oidc_json_object_get(j_counter, s_name_param);
1390
0
  if (j_values == NULL)
1391
0
    return NULL;
1392
0
  return oidc_json_object_get(j_values, s_value_param);
1393
0
}
1394
1395
0
#define OIDC_METRICS_STATUS_PING_KEY "status-ping"
1396
1397
/*
1398
 * readiness variant of format=status (no counter selector): verify that the configured cache
1399
 * backend completes a write/read round-trip and report how provider metadata is configured;
1400
 * returns a 503 with an "ERROR" body when the cache backend is not usable
1401
 */
1402
0
static int oidc_metrics_status_readiness(request_rec *r) {
1403
0
  oidc_cfg_t *cfg = ap_get_module_config(r->server->module_config, &auth_openidc_module);
1404
0
  char *value = NULL;
1405
0
  const char *msg = NULL;
1406
0
  const char *s_provider = NULL;
1407
0
  apr_byte_t ok = FALSE;
1408
1409
  /* write/read round-trip through the configured cache backend */
1410
0
  if ((oidc_cache_set(r, OIDC_CACHE_SECTION_HEALTH, OIDC_METRICS_STATUS_PING_KEY, "OK",
1411
0
          apr_time_now() + apr_time_from_sec(60)) == TRUE) &&
1412
0
      (oidc_cache_get(r, OIDC_CACHE_SECTION_HEALTH, OIDC_METRICS_STATUS_PING_KEY, &value) == TRUE) &&
1413
0
      (value != NULL) && (_oidc_strcmp(value, "OK") == 0))
1414
0
    ok = TRUE;
1415
1416
0
  if (oidc_cfg_metadata_dir_get(cfg) != NULL)
1417
0
    s_provider = "metadata_dir";
1418
0
  else if (oidc_cfg_provider_issuer_get(oidc_cfg_provider_get(cfg)) != NULL)
1419
0
    s_provider = "static";
1420
0
  else
1421
0
    s_provider = "none";
1422
1423
0
  msg = apr_psprintf(r->pool, "%s\ncache: %s: %s\nprovider: metadata: %s\n", ok ? "OK" : "ERROR",
1424
0
         cfg->cache.impl->name, ok ? "ok" : "fail", s_provider);
1425
1426
0
  return oidc_util_http_send(r, msg, _oidc_strlen(msg), "text/plain", ok ? OK : HTTP_SERVICE_UNAVAILABLE);
1427
0
}
1428
1429
/*
1430
 * return status updates
1431
 */
1432
0
static int oidc_metrics_handle_status(request_rec *r, const char *s_json) {
1433
0
  const char *msg = "OK\n";
1434
0
  char *s_metric_param = NULL;
1435
0
  char *s_server_param = NULL;
1436
0
  char *s_name_param = NULL;
1437
0
  char *s_value_param = NULL;
1438
0
  oidc_json_t *json = NULL;
1439
0
  const oidc_json_t *j_server = NULL;
1440
0
  oidc_json_t *j_counters = NULL;
1441
0
  oidc_json_t *j_counter = NULL;
1442
0
  const oidc_json_t *j_value = NULL;
1443
1444
0
  oidc_util_url_parameter_get(r, OIDC_METRICS_SERVER_PARAM, &s_server_param);
1445
0
  oidc_util_url_parameter_get(r, OIDC_METRICS_COUNTER_PARAM, &s_metric_param);
1446
0
  oidc_util_url_parameter_get(r, OIDC_METRICS_NAME_PARAM, &s_name_param);
1447
0
  oidc_util_url_parameter_get(r, OIDC_METRICS_VALUE_PARAM, &s_value_param);
1448
1449
0
  if (s_server_param == NULL)
1450
0
    s_server_param = "localhost";
1451
1452
  /* without a counter selector this is a readiness probe rather than a counter query */
1453
0
  if (s_metric_param == NULL)
1454
0
    return oidc_metrics_status_readiness(r);
1455
1456
0
  json = oidc_metrics_json_parse_r(r, s_json);
1457
0
  if (json == NULL)
1458
0
    goto end;
1459
1460
0
  j_server = oidc_json_object_get(json, s_server_param);
1461
0
  if (j_server == NULL)
1462
0
    goto end;
1463
1464
0
  j_counters = oidc_json_object_get(j_server, OIDC_METRICS_COUNTERS);
1465
0
  if (j_counters == NULL)
1466
0
    goto end;
1467
1468
0
  j_counter = oidc_metrics_status_find_counter(r, j_counters, s_metric_param);
1469
0
  if (j_counter == NULL)
1470
0
    goto end;
1471
1472
0
  j_value = oidc_metrics_status_select_value(j_counter, s_name_param, s_value_param);
1473
0
  if (j_value)
1474
0
    msg = apr_psprintf(r->pool, "OK: %s\n", _json_int2str(r->pool, oidc_json_integer_value(j_value)));
1475
1476
0
end:
1477
1478
0
  if (json)
1479
0
    oidc_json_decref(json);
1480
1481
0
  return oidc_util_http_send(r, msg, _oidc_strlen(msg), "text/plain", OK);
1482
0
}
1483
1484
/*
1485
 * return the bucket table entry for a JSON bucket key
1486
 */
1487
0
static const oidc_metrics_bucket_t *oidc_metrics_prometheus_bucket_get(const char *json_name) {
1488
0
  for (int i = 0; i < OIDC_METRICS_BUCKET_NUM; i++)
1489
0
    if (_oidc_strcmp(_oidc_metric_buckets[i].name, json_name) == 0)
1490
0
      return &_oidc_metric_buckets[i];
1491
0
  return NULL;
1492
0
}
1493
1494
0
#define OIDC_METRICS_PROMETHEUS_PREFIX "oidc"
1495
1496
/*
1497
 * normalize a metric name to something that Prometheus accepts
1498
 */
1499
0
static const char *oidc_metric_prometheus_normalize_name(apr_pool_t *pool, const char *name) {
1500
0
  char *label = apr_psprintf(pool, "%s", name);
1501
0
  for (size_t i = 0; i < _oidc_strlen(label); i++)
1502
0
    if (apr_isalnum(label[i]) == 0)
1503
0
      label[i] = '_';
1504
0
  return apr_psprintf(pool, "%s_%s", OIDC_METRICS_PROMETHEUS_PREFIX, label);
1505
0
}
1506
1507
/* Escape a Prometheus text-format label value: backslash, quote and LF are special. */
1508
0
static const char *oidc_metrics_prometheus_escape_label(apr_pool_t *pool, const char *value) {
1509
0
  apr_size_t len = _oidc_strlen(value);
1510
0
  char *result = apr_palloc(pool, (len * 2) + 1);
1511
0
  char *dst = result;
1512
1513
0
  for (const char *src = value; *src != '\0'; src++) {
1514
0
    switch (*src) {
1515
0
    case '\\':
1516
0
    case '"':
1517
0
      *dst++ = '\\';
1518
0
      *dst++ = *src;
1519
0
      break;
1520
0
    case '\n':
1521
0
      *dst++ = '\\';
1522
0
      *dst++ = 'n';
1523
0
      break;
1524
0
    default:
1525
0
      *dst++ = *src;
1526
0
      break;
1527
0
    }
1528
0
  }
1529
0
  *dst = '\0';
1530
0
  return result;
1531
0
}
1532
1533
0
#define OIDC_METRICS_PROMETHEUS_CONTENT_TYPE "text/plain; version=0.0.4"
1534
1535
0
#define OIDC_METRICS_PROMETHEUS_SERVER "server_name"
1536
0
#define OIDC_METRICS_PROMETHEUS_BUCKET "bucket"
1537
0
#define OIDC_METRICS_PROMETHEUS_VALUE "value"
1538
0
#define OIDC_METRICS_PROMETHEUS_NAME "name"
1539
1540
// loop context for Prometheus output: the output lines, joined once at the end; appending every line to the text
1541
// accumulated so far would copy all of it again for each line, i.e. take time and memory quadratic in the number of
1542
// lines, which grows with every distinct label value recorded
1543
typedef struct oidc_metric_prometheus_callback_ctx_t {
1544
  apr_array_header_t *lines;
1545
  apr_pool_t *pool;
1546
} oidc_metric_prometheus_callback_ctx_t;
1547
1548
/*
1549
 * append per-(name, value) label-pair lines for a single key under a server's counter
1550
 */
1551
static void oidc_metrics_prometheus_counter_named(apr_pool_t *pool, apr_array_header_t *lines, const char *s_start,
1552
0
              const char *s_key, oidc_json_t *j_value) {
1553
0
  void *iter = oidc_json_object_iter(j_value);
1554
0
  while (iter) {
1555
0
    const char *s_value = oidc_json_object_iter_key(iter);
1556
0
    APR_ARRAY_PUSH(lines, const char *) =
1557
0
        apr_psprintf(pool, "%s,%s=\"%s\",%s=\"%s\"} %s\n", s_start, OIDC_METRICS_PROMETHEUS_NAME,
1558
0
         oidc_metrics_prometheus_escape_label(pool, s_key), OIDC_METRICS_PROMETHEUS_VALUE,
1559
0
         oidc_metrics_prometheus_escape_label(pool, s_value),
1560
0
         _json_int2str(pool, oidc_json_integer_value(oidc_json_object_iter_value(iter))));
1561
0
    iter = oidc_json_object_iter_next(j_value, iter);
1562
0
  }
1563
0
}
1564
1565
/*
1566
 * append per-key lines for one server's counter dict; integer entries are value-labeled, sub-dict
1567
 * entries are delegated to oidc_metrics_prometheus_counter_named for name+value labeling
1568
 */
1569
static void oidc_metrics_prometheus_counter_keyed(apr_pool_t *pool, apr_array_header_t *lines, const char *s_start,
1570
0
              oidc_json_t *j_counter) {
1571
0
  void *iter = oidc_json_object_iter(j_counter);
1572
0
  while (iter) {
1573
0
    const char *s_key = oidc_json_object_iter_key(iter);
1574
0
    oidc_json_t *j_value = oidc_json_object_iter_value(iter);
1575
0
    if (oidc_json_is_integer(j_value))
1576
0
      APR_ARRAY_PUSH(lines, const char *) =
1577
0
          apr_psprintf(pool, "%s,%s=\"%s\"} %s\n", s_start, OIDC_METRICS_PROMETHEUS_VALUE,
1578
0
           oidc_metrics_prometheus_escape_label(pool, s_key),
1579
0
           _json_int2str(pool, oidc_json_integer_value(j_value)));
1580
0
    else
1581
0
      oidc_metrics_prometheus_counter_named(pool, lines, s_start, s_key, j_value);
1582
0
    iter = oidc_json_object_iter_next(j_counter, iter);
1583
0
  }
1584
0
}
1585
1586
/*
1587
 * loop function for converting counter metrics to Prometheus output
1588
 */
1589
static int oidc_metrics_prometheus_counters(oidc_metric_prometheus_callback_ctx_t *ctx, const char *key,
1590
0
              oidc_json_t *value) {
1591
0
  oidc_json_t *o_counter = value;
1592
0
  const oidc_metrics_counter_info_t *info = _oidc_metrics_key2counter_info(key);
1593
0
  const char *s_label = NULL;
1594
1595
  /* NB: this callback owns the per-type object that oidc_metrics_prometheus_convert created, even one it skips */
1596
0
  if (info == NULL) {
1597
0
    oidc_json_decref(o_counter);
1598
0
    return 1;
1599
0
  }
1600
1601
0
  s_label = oidc_metric_prometheus_normalize_name(ctx->pool, _oidc_metrics_counter_info2s(ctx->pool, info));
1602
0
  APR_ARRAY_PUSH(ctx->lines, const char *) =
1603
0
      apr_psprintf(ctx->pool, "# HELP %s The number of %s.\n# TYPE %s counter\n", s_label, info->desc, s_label);
1604
1605
0
  void *iter = oidc_json_object_iter(o_counter);
1606
0
  while (iter) {
1607
0
    const char *s_server = oidc_json_object_iter_key(iter);
1608
0
    oidc_json_t *j_counter = oidc_json_object_iter_value(iter);
1609
0
    const char *s_start = apr_psprintf(ctx->pool, "%s{%s=\"%s\"", s_label, OIDC_METRICS_PROMETHEUS_SERVER,
1610
0
               oidc_metrics_prometheus_escape_label(ctx->pool, s_server));
1611
0
    if (oidc_json_is_integer(j_counter))
1612
0
      APR_ARRAY_PUSH(ctx->lines, const char *) =
1613
0
          apr_psprintf(ctx->pool, "%s} %s\n", s_start,
1614
0
           _json_int2str(ctx->pool, oidc_json_integer_value(j_counter)));
1615
0
    else
1616
0
      oidc_metrics_prometheus_counter_keyed(ctx->pool, ctx->lines, s_start, j_counter);
1617
0
    iter = oidc_json_object_iter_next(o_counter, iter);
1618
0
  }
1619
0
  APR_ARRAY_PUSH(ctx->lines, const char *) = "\n";
1620
0
  oidc_json_decref(o_counter);
1621
0
  return 1;
1622
0
}
1623
1624
/*
1625
 * loop function for converting timing metrics to Prometheus output
1626
 */
1627
1628
static int oidc_metrics_prometheus_timings(oidc_metric_prometheus_callback_ctx_t *ctx, const char *key,
1629
0
             oidc_json_t *value) {
1630
0
  const char *s_server = NULL;
1631
0
  const char *s_key = NULL;
1632
0
  const oidc_metrics_bucket_t *bucket = NULL;
1633
0
  oidc_json_t *j_timing = NULL;
1634
0
  const oidc_json_t *j_member = NULL;
1635
0
  oidc_json_t *o_timer = value;
1636
0
  oidc_json_int_t v = 0;
1637
0
  const oidc_metrics_timing_info_t *info = _oidc_metrics_key2timing_info(key);
1638
0
  const char *s_label = NULL;
1639
0
  apr_array_header_t *s_text = NULL;
1640
0
  apr_array_header_t *s_secs = NULL;
1641
1642
  /* NB: owns the per-type object, as in oidc_metrics_prometheus_counters */
1643
0
  if (info == NULL) {
1644
0
    oidc_json_decref(o_timer);
1645
0
    return 1;
1646
0
  }
1647
1648
0
  s_label = oidc_metric_prometheus_normalize_name(ctx->pool, _oidc_metrics_timing_info2s(ctx->pool, info));
1649
  /* the unsuffixed millisecond family is deprecated as of 2.4.20.4 in favor of the
1650
   * Prometheus-idiomatic _seconds family emitted alongside it below, and will be
1651
   * removed in a future release */
1652
0
  s_text = apr_array_make(ctx->pool, 16, sizeof(const char *));
1653
0
  s_secs = apr_array_make(ctx->pool, 16, sizeof(const char *));
1654
0
  APR_ARRAY_PUSH(s_text, const char *) = apr_psprintf(
1655
0
      ctx->pool, "# HELP %s A histogram of %s.\n# TYPE %s histogram\n", s_label, info->desc, s_label);
1656
0
  APR_ARRAY_PUSH(s_secs, const char *) =
1657
0
      apr_psprintf(ctx->pool, "# HELP %s_seconds A histogram of %s in seconds.\n# TYPE %s_seconds histogram\n",
1658
0
       s_label, info->desc, s_label);
1659
1660
0
  void *iter1 = oidc_json_object_iter(o_timer);
1661
0
  while (iter1) {
1662
0
    s_server = oidc_json_object_iter_key(iter1);
1663
0
    const char *s_server_escaped = oidc_metrics_prometheus_escape_label(ctx->pool, s_server);
1664
0
    j_timing = oidc_json_object_iter_value(iter1);
1665
0
    void *iter3 = oidc_json_object_iter(j_timing);
1666
0
    while (iter3) {
1667
0
      s_key = oidc_json_object_iter_key(iter3);
1668
0
      j_member = oidc_json_object_iter_value(iter3);
1669
0
      v = oidc_json_integer_value(j_member);
1670
0
      bucket = oidc_metrics_prometheus_bucket_get(s_key);
1671
0
      if (bucket != NULL) {
1672
0
        APR_ARRAY_PUSH(s_text, const char *) = apr_psprintf(
1673
0
            ctx->pool, "%s_%s{%s,%s=\"%s\"} %s\n", s_label, OIDC_METRICS_PROMETHEUS_BUCKET,
1674
0
            bucket->label, OIDC_METRICS_PROMETHEUS_SERVER, s_server_escaped,
1675
0
            _json_int2str(ctx->pool, v));
1676
0
        APR_ARRAY_PUSH(s_secs, const char *) = apr_psprintf(
1677
0
            ctx->pool, "%s_seconds_%s{%s,%s=\"%s\"} %s\n", s_label,
1678
0
            OIDC_METRICS_PROMETHEUS_BUCKET, bucket->label_seconds,
1679
0
            OIDC_METRICS_PROMETHEUS_SERVER, s_server_escaped, _json_int2str(ctx->pool, v));
1680
0
      } else if (_oidc_strcmp(s_key, OIDC_METRICS_SUM) == 0) {
1681
        /* the sum is kept in microseconds in shared memory: truncate to
1682
         * milliseconds for the legacy family, exact seconds for _seconds */
1683
0
        APR_ARRAY_PUSH(s_text, const char *) = apr_psprintf(
1684
0
            ctx->pool, "%s_%s{%s=\"%s\"} %s\n", s_label, s_key, OIDC_METRICS_PROMETHEUS_SERVER,
1685
0
            s_server_escaped, _json_int2str(ctx->pool, v / 1000));
1686
0
        APR_ARRAY_PUSH(s_secs, const char *) = apr_psprintf(
1687
0
            ctx->pool, "%s_seconds_%s{%s=\"%s\"} %.6f\n", s_label, s_key,
1688
0
            OIDC_METRICS_PROMETHEUS_SERVER, s_server_escaped, (double)v / 1000000.0);
1689
0
      } else {
1690
0
        APR_ARRAY_PUSH(s_text, const char *) = apr_psprintf(
1691
0
            ctx->pool, "%s_%s{%s=\"%s\"} %s\n", s_label, s_key, OIDC_METRICS_PROMETHEUS_SERVER,
1692
0
            s_server_escaped, _json_int2str(ctx->pool, v));
1693
0
        APR_ARRAY_PUSH(s_secs, const char *) = apr_psprintf(
1694
0
            ctx->pool, "%s_seconds_%s{%s=\"%s\"} %s\n", s_label, s_key,
1695
0
            OIDC_METRICS_PROMETHEUS_SERVER, s_server_escaped, _json_int2str(ctx->pool, v));
1696
0
      }
1697
0
      iter3 = oidc_json_object_iter_next(j_timing, iter3);
1698
0
    }
1699
0
    iter1 = oidc_json_object_iter_next(o_timer, iter1);
1700
0
  }
1701
0
  apr_array_cat(ctx->lines, s_text);
1702
0
  APR_ARRAY_PUSH(ctx->lines, const char *) = "\n";
1703
0
  apr_array_cat(ctx->lines, s_secs);
1704
0
  APR_ARRAY_PUSH(ctx->lines, const char *) = "\n";
1705
0
  oidc_json_decref(o_timer);
1706
0
  return 1;
1707
0
}
1708
1709
/*
1710
 * take a list of metrics from a server indexed list and add it to a type indexed list
1711
 */
1712
0
static void oidc_metrics_prometheus_convert(apr_hash_t *hash, const char *server, oidc_json_t *list) {
1713
0
  const char *type = NULL;
1714
0
  oidc_json_t *src = NULL;
1715
0
  oidc_json_t *dst = NULL;
1716
0
  void *iter = oidc_json_object_iter(list);
1717
0
  while (iter) {
1718
0
    type = oidc_json_object_iter_key(iter);
1719
0
    src = oidc_json_object_iter_value(iter);
1720
0
    dst = (oidc_json_t *)apr_hash_get(hash, type, APR_HASH_KEY_STRING);
1721
0
    if (dst) {
1722
0
      oidc_json_object_set(dst, server, src);
1723
0
    } else {
1724
0
      dst = oidc_json_object();
1725
0
      oidc_json_object_set(dst, server, src);
1726
0
      apr_hash_set(hash, type, APR_HASH_KEY_STRING, dst);
1727
0
    }
1728
0
    iter = oidc_json_object_iter_next(list, iter);
1729
0
  }
1730
0
}
1731
1732
/*
1733
 * generate output in Prometheus formatting
1734
 */
1735
0
static int oidc_metrics_handle_prometheus(request_rec *r, const char *s_json) {
1736
0
  oidc_json_t *json = NULL;
1737
0
  const oidc_json_t *j_server = NULL;
1738
0
  const char *s_server = NULL;
1739
0
  apr_hash_t *t_counters = apr_hash_make(r->pool);
1740
0
  apr_hash_t *t_timings = apr_hash_make(r->pool);
1741
0
  apr_hash_index_t *hi = NULL;
1742
0
  const char *name = NULL;
1743
0
  void *value = NULL;
1744
1745
  /* start the output with the build info and the metrics subsystem's own health */
1746
0
  const char *s_self = apr_psprintf(
1747
0
      r->pool,
1748
0
      "# HELP %s_build_info A metric with a constant '1' value labeled by the module build version.\n"
1749
0
      "# TYPE %s_build_info gauge\n"
1750
0
      "%s_build_info{version=\"%s\"} 1\n\n"
1751
0
      "# HELP %s_metrics_flush_errors The number of metrics flushes dropped because the JSON data outgrew the "
1752
0
      "shared memory segment.\n"
1753
0
      "# TYPE %s_metrics_flush_errors counter\n"
1754
0
      "%s_metrics_flush_errors %u\n\n"
1755
0
      "# HELP %s_metrics_last_flush_timestamp_seconds The Unix time of the last completed metrics flush cycle in "
1756
0
      "this server process.\n"
1757
0
      "# TYPE %s_metrics_last_flush_timestamp_seconds gauge\n"
1758
0
      "%s_metrics_last_flush_timestamp_seconds %u\n\n",
1759
0
      OIDC_METRICS_PROMETHEUS_PREFIX, OIDC_METRICS_PROMETHEUS_PREFIX, OIDC_METRICS_PROMETHEUS_PREFIX,
1760
0
      oidc_metrics_prometheus_escape_label(r->pool, NAMEVERSION), OIDC_METRICS_PROMETHEUS_PREFIX,
1761
0
      OIDC_METRICS_PROMETHEUS_PREFIX, OIDC_METRICS_PROMETHEUS_PREFIX,
1762
0
      apr_atomic_read32(&_oidc_metrics_shm_hdr()->flush_errors), OIDC_METRICS_PROMETHEUS_PREFIX,
1763
0
      OIDC_METRICS_PROMETHEUS_PREFIX, OIDC_METRICS_PROMETHEUS_PREFIX,
1764
0
      apr_atomic_read32(&_oidc_metrics_shm_hdr()->last_flush));
1765
1766
0
  oidc_metric_prometheus_callback_ctx_t ctx = {apr_array_make(r->pool, 64, sizeof(const char *)), r->pool};
1767
0
  APR_ARRAY_PUSH(ctx.lines, const char *) = s_self;
1768
0
  void *iter = NULL;
1769
1770
  /* parse the metrics string to JSON */
1771
0
  json = oidc_metrics_json_parse_r(r, s_json);
1772
0
  if (json == NULL)
1773
0
    return OK;
1774
1775
0
  iter = oidc_json_object_iter(json);
1776
0
  while (iter) {
1777
0
    s_server = oidc_json_object_iter_key(iter);
1778
0
    j_server = oidc_json_object_iter_value(iter);
1779
0
    oidc_metrics_prometheus_convert(t_counters, s_server,
1780
0
            oidc_json_object_get(j_server, OIDC_METRICS_COUNTERS));
1781
0
    oidc_metrics_prometheus_convert(t_timings, s_server,
1782
0
            oidc_json_object_get(j_server, OIDC_METRICS_TIMINGS));
1783
0
    iter = oidc_json_object_iter_next(json, iter);
1784
0
  }
1785
1786
0
  for (hi = apr_hash_first(r->pool, t_counters); hi; hi = apr_hash_next(hi)) {
1787
0
    apr_hash_this(hi, (const void **)&name, NULL, &value);
1788
0
    oidc_metrics_prometheus_counters(&ctx, name, value);
1789
0
  }
1790
1791
0
  for (hi = apr_hash_first(r->pool, t_timings); hi; hi = apr_hash_next(hi)) {
1792
0
    apr_hash_this(hi, (const void **)&name, NULL, &value);
1793
0
    oidc_metrics_prometheus_timings(&ctx, name, value);
1794
0
  }
1795
1796
0
  oidc_json_decref(json);
1797
1798
0
  const char *s_result = apr_array_pstrcat(r->pool, ctx.lines, 0);
1799
0
  return oidc_util_http_send(r, s_result, _oidc_strlen(s_result), OIDC_METRICS_PROMETHEUS_CONTENT_TYPE, OK);
1800
0
}
1801
1802
/*
1803
 * definitions for handler callbacks
1804
 */
1805
1806
typedef int (*oidc_metrics_handler_function_t)(request_rec *, const char *);
1807
1808
// holder for output function callback context
1809
typedef struct oidc_metrics_handler_t {
1810
  const char *format;
1811
  oidc_metrics_handler_function_t callback;
1812
  int reset;
1813
} oidc_metrics_content_handler_t;
1814
1815
// output handlers
1816
// NB: no format resets the collected metrics by default (json did before 2.4.20.4);
1817
// a caller that wants the pre-2.4.20.4 behavior passes reset=true explicitly
1818
const oidc_metrics_content_handler_t _oidc_metrics_handlers[] = {
1819
    // first is default
1820
    {"prometheus", oidc_metrics_handle_prometheus, 0},
1821
    {"json", oidc_metrics_handle_json, 0},
1822
    {"internal", oidc_metrics_handle_internal, 0},
1823
    {"status", oidc_metrics_handle_status, 0},
1824
};
1825
1826
0
#define OIDC_CONTENT_HANDLER_MAX ((int)(sizeof(_oidc_metrics_handlers) / sizeof(oidc_metrics_content_handler_t)))
1827
1828
0
#define OIDC_METRICS_RESET_PARAM "reset"
1829
1830
/*
1831
 * see if we are going to reset the cache after this
1832
 */
1833
0
static int oidc_metric_reset(request_rec *r, int dvalue) {
1834
0
  char *s_reset = NULL;
1835
0
  int value = 0;
1836
1837
0
  oidc_util_url_parameter_get(r, OIDC_METRICS_RESET_PARAM, &s_reset);
1838
1839
0
  if (s_reset == NULL)
1840
0
    return dvalue;
1841
1842
0
  if (_oidc_strnatcasecmp(s_reset, "true") == 0)
1843
0
    value = 1;
1844
0
  else if (_oidc_strnatcasecmp(s_reset, "false") == 0)
1845
0
    value = 0;
1846
1847
0
  return value;
1848
0
}
1849
1850
0
#define OIDC_METRICS_FORMAT_PARAM "format"
1851
1852
/*
1853
 * find the format handler
1854
 */
1855
0
const oidc_metrics_content_handler_t *oidc_metrics_find_handler(request_rec *r) {
1856
0
  const oidc_metrics_content_handler_t *handler = NULL;
1857
0
  char *s_format = NULL;
1858
1859
  /* get the specified format */
1860
0
  oidc_util_url_parameter_get(r, OIDC_METRICS_FORMAT_PARAM, &s_format);
1861
1862
0
  if (s_format == NULL)
1863
0
    return &_oidc_metrics_handlers[0];
1864
1865
0
  for (int i = 0; i < OIDC_CONTENT_HANDLER_MAX; i++) {
1866
0
    if (_oidc_strcmp(s_format, _oidc_metrics_handlers[i].format) == 0) {
1867
0
      handler = &_oidc_metrics_handlers[i];
1868
0
      break;
1869
0
    }
1870
0
  }
1871
1872
0
  if (handler == NULL)
1873
0
    oidc_warn(r, "could not find a metrics handler for format: %s", s_format);
1874
1875
0
  return handler;
1876
0
}
1877
1878
/*
1879
 * return the metrics to the caller and flush the storage
1880
 */
1881
0
int oidc_metrics_handle_request(request_rec *r) {
1882
0
  const char *s_json = NULL;
1883
0
  const oidc_metrics_content_handler_t *handler = NULL;
1884
1885
  /* OIDCMetricsPublish without any OIDCMetricsData: the subsystem, and so its mutex and storage,
1886
   * was never initialized */
1887
0
  if (_oidc_metrics_global_mutex == NULL) {
1888
0
    oidc_error(r, "metrics are published on this path but not collected: set " OIDCMetricsData);
1889
0
    return HTTP_NOT_FOUND;
1890
0
  }
1891
1892
  /* get the content handler for the format */
1893
0
  handler = oidc_metrics_find_handler(r);
1894
0
  if (handler == NULL)
1895
0
    return HTTP_NOT_FOUND;
1896
1897
  /* lock the global shared memory */
1898
0
  if (oidc_cache_mutex_lock(r->pool, r->server, _oidc_metrics_global_mutex) == FALSE)
1899
0
    return HTTP_INTERNAL_SERVER_ERROR;
1900
1901
  /* retrieve the JSON formatted metrics as a string; NB: on the request pool, since
1902
   * it is handed to the content handler below, after the mutex has been released */
1903
0
  s_json = _oidc_metrics_storage_get(r->server, r->pool);
1904
1905
  /* now that the metrics have been consumed, clear the shared memory segment */
1906
0
  if (oidc_metric_reset(r, handler->reset))
1907
0
    oidc_metrics_storage_reset(r->server, r->pool);
1908
1909
  /* unlock the global shared memory */
1910
0
  if (oidc_cache_mutex_unlock(r->pool, r->server, _oidc_metrics_global_mutex) == FALSE)
1911
0
    return HTTP_INTERNAL_SERVER_ERROR;
1912
1913
  /* handle the specified format */
1914
0
  return handler->callback(r, s_json);
1915
0
}