kinto 20.6.1__py3-none-any.whl → 21.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of kinto might be problematic. Click here for more details.

kinto/__init__.py CHANGED
@@ -14,7 +14,7 @@ from kinto.core import utils
14
14
  __version__ = pkg_resources.get_distribution(__package__).version
15
15
 
16
16
  # Implemented HTTP API Version
17
- HTTP_API_VERSION = "1.22"
17
+ HTTP_API_VERSION = "1.23"
18
18
 
19
19
  # Main kinto logger
20
20
  logger = logging.getLogger(__name__)
kinto/config/__init__.py CHANGED
@@ -1,6 +1,9 @@
1
1
  import codecs
2
2
  import logging
3
3
  import os
4
+ from datetime import datetime
5
+ from functools import lru_cache
6
+ from hashlib import sha256
4
7
  from time import strftime
5
8
 
6
9
  from kinto import __version__
@@ -69,3 +72,23 @@ def init(config_file, backend, cache_backend, host="127.0.0.1"):
69
72
  values.update(cache_backend_to_values[cache_backend])
70
73
 
71
74
  render_template("kinto.tpl", config_file, **values)
75
+
76
+
77
+ @lru_cache(maxsize=1)
78
+ def config_attributes():
79
+ """
80
+ Returns a hash of the config `.ini` file content.
81
+ The path is only known from `app.wsgi`, so we have to read
82
+ the environment variable again. Since tests are not run through
83
+ WSGI, then the variable is not set.
84
+ """
85
+ # WARNING: this default value should be the same as `app.wsgi`
86
+ ini_path = os.environ.get("KINTO_INI", os.path.join(".", "config", "kinto.ini"))
87
+ if not os.path.exists(ini_path):
88
+ logger.error(f"Could not find config file at {ini_path}")
89
+ return None
90
+ return {
91
+ "path": ini_path,
92
+ "hash": sha256(open(ini_path, "rb").read()).hexdigest(),
93
+ "modified": datetime.fromtimestamp(os.path.getmtime(ini_path)).isoformat(),
94
+ }
@@ -1,7 +1,6 @@
1
1
  import logging
2
2
  import random
3
3
  import re
4
- import urllib.parse
5
4
  import warnings
6
5
  from datetime import datetime
7
6
 
@@ -466,14 +465,6 @@ def setup_metrics(config):
466
465
  request = event.request
467
466
  metrics_service = config.registry.metrics
468
467
 
469
- try:
470
- endpoint = utils.strip_uri_prefix(request.path)
471
- endpoint = urllib.parse.quote_plus(endpoint, safe="/?&=-_")
472
- except UnicodeDecodeError as e:
473
- # This `on_new_response` callback is also called when a HTTP 400
474
- # is returned because of an invalid UTF-8 path. We still want metrics.
475
- endpoint = str(e)
476
-
477
468
  # Count unique users.
478
469
  user_id = request.prefixed_userid
479
470
  if user_id:
@@ -496,13 +487,27 @@ def setup_metrics(config):
496
487
  (field, enhanced_matchdict.get(field, "")) for field in metrics_matchdict_fields
497
488
  ]
498
489
 
490
+ status = event.response.status_code
491
+
492
+ service = request.current_service
493
+ if service:
494
+ # Use the service name as endpoint if available.
495
+ endpoint = service.name
496
+ elif route := request.matched_route:
497
+ # Use the route name as endpoint if we're not on a Cornice service.
498
+ endpoint = route.name
499
+ else:
500
+ endpoint = (
501
+ "unnamed" if status != 404 else "unknown"
502
+ ) # Do not multiply cardinality for unknown endpoints.
503
+
499
504
  # Count served requests.
500
505
  metrics_service.count(
501
506
  "request_summary",
502
507
  unique=[
503
508
  ("method", request.method.lower()),
504
509
  ("endpoint", endpoint),
505
- ("status", str(event.response.status_code)),
510
+ ("status", str(status)),
506
511
  ]
507
512
  + metrics_matchdict_labels,
508
513
  )
@@ -510,10 +515,11 @@ def setup_metrics(config):
510
515
  try:
511
516
  current = utils.msec_time()
512
517
  duration = current - request._received_at
513
- metrics_service.observe(
518
+ metrics_service.timer(
514
519
  "request_duration",
515
- duration,
516
- labels=[("endpoint", endpoint)] + metrics_matchdict_labels,
520
+ value=duration,
521
+ labels=[("endpoint", endpoint), ("method", request.method.lower())]
522
+ + metrics_matchdict_labels,
517
523
  )
518
524
  except AttributeError: # pragma: no cover
519
525
  # Logging was not setup in this Kinto app (unlikely but possible)
@@ -527,13 +533,11 @@ def setup_metrics(config):
527
533
  )
528
534
 
529
535
  # Count authentication verifications.
530
- if hasattr(request, "authn_type"):
531
- metrics_service.count(f"authn_type.{request.authn_type}")
532
-
533
- # Count view calls.
534
- service = request.current_service
535
- if service:
536
- metrics_service.count(f"view.{service.name}.{request.method}")
536
+ try:
537
+ metrics_service.count("authentication", unique=[("type", request.authn_type)])
538
+ except AttributeError:
539
+ # Not authenticated
540
+ pass
537
541
 
538
542
  config.add_subscriber(on_new_response, NewResponse)
539
543
 
kinto/core/metrics.py CHANGED
@@ -47,7 +47,7 @@ class NoOpTimer:
47
47
 
48
48
  @implementer(IMetricsService)
49
49
  class NoOpMetricsService:
50
- def timer(self, key):
50
+ def timer(self, key, value=None, labels=[]):
51
51
  return NoOpTimer()
52
52
 
53
53
  def observe(self, key, value, labels=[]):
@@ -65,11 +65,12 @@ def watch_execution_time(metrics_service, obj, prefix="", classname=None):
65
65
  classname = classname or utils.classname(obj)
66
66
  members = dir(obj)
67
67
  for name in members:
68
- value = getattr(obj, name)
69
- is_method = isinstance(value, types.MethodType)
68
+ method = getattr(obj, name)
69
+ is_method = isinstance(method, types.MethodType)
70
70
  if not name.startswith("_") and is_method:
71
- statsd_key = f"{prefix}.{classname}.{name}"
72
- decorated_method = metrics_service.timer(statsd_key)(value)
71
+ statsd_key = f"{prefix}.{classname}"
72
+ labels = [("method", name)]
73
+ decorated_method = metrics_service.timer(statsd_key, labels=labels)(method)
73
74
  setattr(obj, name, decorated_method)
74
75
 
75
76
 
kinto/core/views/hello.py CHANGED
@@ -2,6 +2,7 @@ import colander
2
2
  from pyramid.authorization import Authenticated
3
3
  from pyramid.security import NO_PERMISSION_REQUIRED
4
4
 
5
+ from kinto.config import config_attributes
5
6
  from kinto.core import Service
6
7
 
7
8
 
@@ -26,14 +27,17 @@ hello_response_schemas = {
26
27
  def get_hello(request):
27
28
  """Return information regarding the current instance."""
28
29
  settings = request.registry.settings
30
+
29
31
  project_name = settings["project_name"]
30
32
  project_version = settings["project_version"]
33
+
31
34
  data = dict(
32
35
  project_name=project_name,
33
36
  project_version=project_version,
34
37
  http_api_version=settings["http_api_version"],
35
38
  project_docs=settings["project_docs"],
36
39
  url=request.route_url(hello.name),
40
+ config=config_attributes(),
37
41
  )
38
42
 
39
43
  eos = get_eos(request)
@@ -6,6 +6,7 @@ from time import perf_counter as time_now
6
6
 
7
7
  from pyramid.exceptions import ConfigurationError
8
8
  from pyramid.response import Response
9
+ from pyramid.settings import asbool, aslist
9
10
  from zope.interface import implementer
10
11
 
11
12
  from kinto.core import metrics
@@ -49,10 +50,27 @@ def _fix_metric_name(s):
49
50
 
50
51
 
51
52
  class Timer:
52
- def __init__(self, summary):
53
- self.summary = summary
53
+ """
54
+ A decorator to time the execution of a function. It will use the
55
+ `prometheus_client.Histogram` to record the time taken by the function
56
+ in milliseconds. The histogram is passed as an argument to the
57
+ constructor.
58
+
59
+ Main limitation: it does not support `labels` on the decorator.
60
+ """
61
+
62
+ def __init__(self, histogram):
63
+ self.histogram = histogram
54
64
  self._start_time = None
55
65
 
66
+ def set_labels(self, labels):
67
+ if not labels:
68
+ return
69
+ self.histogram = self.histogram.labels(*(label_value for _, label_value in labels))
70
+
71
+ def observe(self, value):
72
+ return self.histogram.observe(value)
73
+
56
74
  def __call__(self, f):
57
75
  @safe_wraps(f)
58
76
  def _wrapped(*args, **kwargs):
@@ -61,7 +79,7 @@ class Timer:
61
79
  return f(*args, **kwargs)
62
80
  finally:
63
81
  dt_ms = 1000.0 * (time_now() - start_time)
64
- self.summary.observe(dt_ms)
82
+ self.histogram.observe(dt_ms)
65
83
 
66
84
  return _wrapped
67
85
 
@@ -79,13 +97,13 @@ class Timer:
79
97
  if self._start_time is None: # pragma: nocover
80
98
  raise RuntimeError("Timer has not started.")
81
99
  dt_ms = 1000.0 * (time_now() - self._start_time)
82
- self.summary.observe(dt_ms)
100
+ self.histogram.observe(dt_ms)
83
101
  return self
84
102
 
85
103
 
86
104
  @implementer(metrics.IMetricsService)
87
105
  class PrometheusService:
88
- def __init__(self, prefix=""):
106
+ def __init__(self, prefix="", exclude_labels=None):
89
107
  prefix_clean = ""
90
108
  if prefix:
91
109
  # In GCP Console, the metrics are grouped by the first
@@ -94,26 +112,49 @@ class PrometheusService:
94
112
  # (eg. `remote-settings` -> `remotesettings_`, `kinto_` -> `kinto_`)
95
113
  prefix_clean = _fix_metric_name(prefix).replace("_", "") + "_"
96
114
  self.prefix = prefix_clean.lower()
115
+ self.exclude_labels = exclude_labels or []
116
+
117
+ def _exclude_labels(self, labels):
118
+ return [
119
+ (label_name, label_value)
120
+ for label_name, label_value in labels
121
+ if label_name not in self.exclude_labels
122
+ ]
97
123
 
98
- def timer(self, key):
124
+ def timer(self, key, value=None, labels=[]):
99
125
  global _METRICS
100
126
  key = self.prefix + key
127
+ labels = self._exclude_labels(labels)
101
128
 
102
129
  if key not in _METRICS:
103
- _METRICS[key] = prometheus_module.Summary(
104
- _fix_metric_name(key), f"Summary of {key}", registry=get_registry()
130
+ _METRICS[key] = prometheus_module.Histogram(
131
+ _fix_metric_name(key),
132
+ f"Histogram of {key}",
133
+ registry=get_registry(),
134
+ labelnames=[label_name for label_name, _ in labels],
105
135
  )
106
136
 
107
- if not isinstance(_METRICS[key], prometheus_module.Summary):
137
+ if not isinstance(_METRICS[key], prometheus_module.Histogram):
108
138
  raise RuntimeError(
109
139
  f"Metric {key} already exists with different type ({_METRICS[key]})"
110
140
  )
111
141
 
112
- return Timer(_METRICS[key])
142
+ timer = Timer(_METRICS[key])
143
+ timer.set_labels(labels)
144
+
145
+ if value is not None:
146
+ # We are timing something.
147
+ return timer.observe(value)
148
+
149
+ # We are not timing anything, just returning the timer object
150
+ # (eg. to be used as decorator or context manager).
151
+ # Note that in this case, the labels values will be the same for all calls.
152
+ return timer
113
153
 
114
154
  def observe(self, key, value, labels=[]):
115
155
  global _METRICS
116
156
  key = self.prefix + key
157
+ labels = self._exclude_labels(labels)
117
158
 
118
159
  if key not in _METRICS:
119
160
  _METRICS[key] = prometheus_module.Summary(
@@ -154,6 +195,7 @@ class PrometheusService:
154
195
  label_name, label_value = unique.rsplit(".", 1)
155
196
  unique = [(label_name, label_value)]
156
197
 
198
+ unique = self._exclude_labels(unique)
157
199
  labels = [
158
200
  (_fix_metric_name(label_name), label_value) for label_name, label_value in unique
159
201
  ]
@@ -199,6 +241,11 @@ def includeme(config):
199
241
  )
200
242
  raise ConfigurationError(error_msg)
201
243
 
244
+ settings = config.get_settings()
245
+
246
+ if not asbool(settings.get("prometheus_created_metrics_enabled", True)):
247
+ prometheus_module.disable_created_metrics()
248
+
202
249
  config.add_api_capability(
203
250
  "prometheus",
204
251
  description="Prometheus metrics.",
@@ -220,7 +267,13 @@ def includeme(config):
220
267
  pass
221
268
  _METRICS.clear()
222
269
 
223
- settings = config.get_settings()
224
270
  prefix = settings.get("prometheus_prefix", settings["project_name"])
225
271
 
226
- config.registry.registerUtility(PrometheusService(prefix=prefix), metrics.IMetricsService)
272
+ # If we want to reduce the metrics cardinality, we can exclude certain
273
+ # labels (eg. records_id). This way all metrics will be grouped by the
274
+ # remaining labels.
275
+ exclude_labels = aslist(settings.get("prometheus_exclude_labels", ""))
276
+
277
+ config.registry.registerUtility(
278
+ PrometheusService(prefix=prefix, exclude_labels=exclude_labels), metrics.IMetricsService
279
+ )
kinto/plugins/statsd.py CHANGED
@@ -1,4 +1,5 @@
1
1
  import warnings
2
+ from datetime import timedelta
2
3
  from urllib.parse import urlparse
3
4
 
4
5
  from pyramid.exceptions import ConfigurationError
@@ -26,7 +27,13 @@ class StatsDService:
26
27
  def __init__(self, host, port, prefix):
27
28
  self._client = statsd_module.StatsClient(host, port, prefix=prefix)
28
29
 
29
- def timer(self, key):
30
+ def timer(self, key, value=None, labels=[]):
31
+ if labels:
32
+ # [("method", "get")] -> "method.get"
33
+ key = f"{key}." + ".".join(f"{label[0]}.{sanitize(label[1])}" for label in labels)
34
+ if value:
35
+ value = timedelta(seconds=value)
36
+ return self._client.timing(key, value)
30
37
  return self._client.timer(key)
31
38
 
32
39
  def observe(self, key, value, labels=[]):
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: kinto
3
- Version: 20.6.1
3
+ Version: 21.1.0
4
4
  Summary: Kinto Web Service - Store, Sync, Share, and Self-Host.
5
5
  Author-email: Mozilla Services <developers@kinto-storage.org>
6
6
  License: Copyright 2012 - Mozilla Foundation
@@ -1,10 +1,10 @@
1
- kinto/__init__.py,sha256=XG7cOyHN0ipQeOSPMW-XFax7uFgAjnCd3Slq0jSFGC4,3299
1
+ kinto/__init__.py,sha256=OLigXJoAE1frrLwNjfAnuuhgfRrk8yL_OrvZpguRzT8,3299
2
2
  kinto/__main__.py,sha256=6XDjWYGtJ36qepn9Of4xL9zc35TfdSeEvHh3s26Aw9c,7913
3
3
  kinto/authorization.py,sha256=i3ttdPTFGzE9CqUQmfC4rR_6dDZJu0jWJMLGl_jFzIE,4919
4
4
  kinto/contribute.json,sha256=HT9QVB8rA8jWIREQoqWfMibfJXMAzbRsixW8F6O6cQY,792
5
5
  kinto/events.py,sha256=NMPvKUdbi25aYHhu9svzQsrEZMa9nyO4mtuMZC5871Q,85
6
6
  kinto/schema_validation.py,sha256=mtAmnl5HwiUsjS2gU8MKH4lkZ1380A5wZht-w9s5X7M,5306
7
- kinto/config/__init__.py,sha256=av8W0utmjheueFqrjTYEDk_vbpm3XYdHcqv5lppNR4k,2131
7
+ kinto/config/__init__.py,sha256=v3EySgWgyqLr2kV6sFkBVgnEgjHwyylbcgYIpdNveKQ,2979
8
8
  kinto/config/kinto.tpl,sha256=Pm9p_oRsBlVoEXPVA2X6Wvv49jMOVv-27jw4rahVlwE,8201
9
9
  kinto/core/__init__.py,sha256=s7PshdeKmpiqI5sW-zdC7p3Ig-e60w4kiUwlKi-impY,8655
10
10
  kinto/core/authentication.py,sha256=HLA0kREC3GMEsrIsHsQYjVNztYfAF01kb8-pLboByFs,1527
@@ -12,8 +12,8 @@ kinto/core/authorization.py,sha256=GywY25KEzuSSAI709dFHDfdLnKxy3SLEYGwW5FkQ7Qc,1
12
12
  kinto/core/decorators.py,sha256=3SAPWXlyPNUSICZ9mz04bcN-UdbnDuFOtU0bQHHzLis,2178
13
13
  kinto/core/errors.py,sha256=JXZjkPYjjC0I6x02d2VJRGeaQ2yZYS2zm5o7_ljfyes,8946
14
14
  kinto/core/events.py,sha256=SYpXgKMtVjiD9fwYJA2Omdom9yA3nBqi9btdvU1I_nc,10345
15
- kinto/core/initialization.py,sha256=ZjmCKc8MYZXv63W2mv--fY8rXSLAnJa7RtCYdfK4jsg,26225
16
- kinto/core/metrics.py,sha256=Y6Mt4PUzy2-oudeGr_oCmtX8nIR4SZkzUlPxr58jr-g,2619
15
+ kinto/core/initialization.py,sha256=1m3lFLjFpApLKRXBa650GkYkR5u71ZUJRGogRYyo0Vs,26299
16
+ kinto/core/metrics.py,sha256=h582cAZawzgJ9AL16t1ScgyVi0trXoJx-6147Ig-Vns,2693
17
17
  kinto/core/openapi.py,sha256=92sZviff4NCxN0jMnu5lPUnF5iQbrKMGy7Cegf-VAME,3876
18
18
  kinto/core/schema.py,sha256=d5L5TQynRYJPkZ8Mu2X7F72xEh6SKDbrHK1CNTdOf2E,3646
19
19
  kinto/core/scripts.py,sha256=02SXVjo579W82AsDF8dyVCRxYVcrMFkjjaNVIgLChh0,1412
@@ -95,13 +95,13 @@ kinto/core/views/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,
95
95
  kinto/core/views/batch.py,sha256=sWNn67YqfTbiqwpbwbm1QyumcVGi8aNhlT5AtLToElI,5657
96
96
  kinto/core/views/errors.py,sha256=2uTy85UBQL1EDIMotzFBhVl14RmWwb3rupbsB0mycbs,6099
97
97
  kinto/core/views/heartbeat.py,sha256=qidZ7fTvuPoJMo7miDnclAm_WsbgqubzsARrv9aCo5U,3336
98
- kinto/core/views/hello.py,sha256=tTjJ2PHKPnmLL41cwF6e0AzPhm4WmojIc0VWHcZNOgI,1961
98
+ kinto/core/views/hello.py,sha256=DipWK5EuuDOyUSHCGTGZKmNBbgyp_SHyPXUje6hc81E,2042
99
99
  kinto/core/views/openapi.py,sha256=PgxplQX1D0zqzlvRxBvd5SzrNMJmsaLfDta_fh-Pr-A,958
100
100
  kinto/core/views/version.py,sha256=-m5G_o0oHTpCgrtfFrHFve6Zqw_gs_szT0Bd8jnNmD4,1419
101
101
  kinto/plugins/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
102
102
  kinto/plugins/flush.py,sha256=poiBOLGXjml0xXHjqDMRdbXJSd6N3SL0mfeGK2vxeHY,812
103
- kinto/plugins/prometheus.py,sha256=Ljirp9K3Gw1iy0I5vzE_Z2fE6yw3gjjHZayu0_2Y2Vw,6985
104
- kinto/plugins/statsd.py,sha256=-VasJZM1xkhTfFa6_0GgWwfPqKnYS2722bSMDLzZ3pI,2469
103
+ kinto/plugins/prometheus.py,sha256=WyE3jULDSMe35S4SJiKbh05AVGDyU9Hc-UR3-7baaGs,8957
104
+ kinto/plugins/statsd.py,sha256=k9sewYZUwm60k9Z799VxbShBP3uPwGVlImaGCPnIrkE,2801
105
105
  kinto/plugins/accounts/__init__.py,sha256=2DeIaXJmMqRca3xVHeJ6xBWmeXAfrCdyg3EvK5jzIak,3670
106
106
  kinto/plugins/accounts/authentication.py,sha256=pCb269FquKGFd6DH8AVTjFnBFlfxcDEYVyxhQp5Y08o,2117
107
107
  kinto/plugins/accounts/scripts.py,sha256=_LNkSpFprOMGHFKkRmmOqK31uoQW28yttPQztmfUt5Q,2001
@@ -141,9 +141,9 @@ kinto/views/contribute.py,sha256=PJoIMLj9_IszSjgZkaCd_TUjekDgNqjpmVTmRN9ztaA,983
141
141
  kinto/views/groups.py,sha256=jOq5fX0-4lwZE8k1q5HME2tU7x9052rtBPF7YqcJ-Qg,3181
142
142
  kinto/views/permissions.py,sha256=F0_eKx201WyLonXJ5vLdGKa9RcFKjvAihrEEhU1JuLw,9069
143
143
  kinto/views/records.py,sha256=lYfACW2L8qcQoyYBD5IX-fTPjFWmGp7GjHq_U4InlyE,5037
144
- kinto-20.6.1.dist-info/licenses/LICENSE,sha256=oNEIMTuTJzppR5ZEyi86yvvtSagveMYXTYFn56zF0Uk,561
145
- kinto-20.6.1.dist-info/METADATA,sha256=VGdr0-TWwOlbW-X1GxdLcIe92XnBzroCTiwtKZ7icEs,8731
146
- kinto-20.6.1.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91
147
- kinto-20.6.1.dist-info/entry_points.txt,sha256=3KlqBWPKY81mrCe_oX0I5s1cRO7Q53nCLbnVr5P9LH4,85
148
- kinto-20.6.1.dist-info/top_level.txt,sha256=EG_YmbZL6FAug9VwopG7JtF9SvH_r0DEnFp-3twPPys,6
149
- kinto-20.6.1.dist-info/RECORD,,
144
+ kinto-21.1.0.dist-info/licenses/LICENSE,sha256=oNEIMTuTJzppR5ZEyi86yvvtSagveMYXTYFn56zF0Uk,561
145
+ kinto-21.1.0.dist-info/METADATA,sha256=rTspJQTHQ907FEjyjIM27a3XT_mxRQIILCnGfyZ3-S8,8731
146
+ kinto-21.1.0.dist-info/WHEEL,sha256=pxyMxgL8-pra_rKaQ4drOZAegBVuX-G_4nRHjjgWbmo,91
147
+ kinto-21.1.0.dist-info/entry_points.txt,sha256=3KlqBWPKY81mrCe_oX0I5s1cRO7Q53nCLbnVr5P9LH4,85
148
+ kinto-21.1.0.dist-info/top_level.txt,sha256=EG_YmbZL6FAug9VwopG7JtF9SvH_r0DEnFp-3twPPys,6
149
+ kinto-21.1.0.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (78.1.0)
2
+ Generator: setuptools (79.0.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5