-
Notifications
You must be signed in to change notification settings - Fork 80
/
metrics.py
1995 lines (1743 loc) · 87 KB
/
metrics.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-License-Identifier: Apache-2.0
#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
# Modifications Copyright OpenSearch Contributors. See
# GitHub history for details.
# Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import collections
import glob
import json
import logging
import math
import os
import pickle
import random
import statistics
import sys
import time
import zlib
from enum import Enum, IntEnum
from http.client import responses
import tabulate
from osbenchmark import client, time, exceptions, config, version, paths
from osbenchmark.utils import convert, console, io, versions
class OsClient:
"""
Provides a stripped-down client interface that is easier to exchange for testing
"""
def __init__(self, client, cluster_version=None):
self._client = client
self.logger = logging.getLogger(__name__)
self._cluster_version = cluster_version
# TODO #653: Remove version-specific support for metrics stores before 7.0.0.
def probe_version(self):
info = self.guarded(self._client.info)
try:
self._cluster_version = versions.components(info["version"]["number"])
except BaseException:
msg = "Could not determine version of metrics cluster"
self.logger.exception(msg)
raise exceptions.BenchmarkError(msg)
def put_template(self, name, template):
# TODO #653: Remove version-specific support for metrics stores before 7.0.0 (also adjust template)
if self._cluster_version[0] > 6:
return self.guarded(self._client.indices.put_template, name=name, body=template, params={
# allows to include the type name although it is not allowed anymore by default
"include_type_name": "true"
})
else:
return self.guarded(self._client.indices.put_template, name=name, body=template)
def template_exists(self, name):
return self.guarded(self._client.indices.exists_template, name)
def delete_template(self, name):
self.guarded(self._client.indices.delete_template, name)
def get_index(self, name):
return self.guarded(self._client.indices.get, name)
def create_index(self, index):
# ignore 400 cause by IndexAlreadyExistsException when creating an index
return self.guarded(self._client.indices.create, index=index, ignore=400)
def exists(self, index):
return self.guarded(self._client.indices.exists, index=index)
def refresh(self, index):
return self.guarded(self._client.indices.refresh, index=index)
def bulk_index(self, index, doc_type, items):
# TODO #653: Remove version-specific support for metrics stores before 7.0.0.
# pylint: disable=import-outside-toplevel
import elasticsearch.helpers
if self._cluster_version[0] > 6:
self.guarded(elasticsearch.helpers.bulk, self._client, items, index=index, chunk_size=5000)
else:
self.guarded(elasticsearch.helpers.bulk, self._client, items, index=index, doc_type=doc_type, chunk_size=5000)
def index(self, index, doc_type, item, id=None):
doc = {
"_source": item
}
if id:
doc["_id"] = id
self.bulk_index(index, doc_type, [doc])
def search(self, index, body):
return self.guarded(self._client.search, index=index, body=body)
def guarded(self, target, *args, **kwargs):
# pylint: disable=import-outside-toplevel
import elasticsearch
max_execution_count = 11
execution_count = 0
while execution_count < max_execution_count:
time_to_sleep = 2 ** execution_count + random.random()
execution_count += 1
try:
return target(*args, **kwargs)
except elasticsearch.exceptions.AuthenticationException:
# we know that it is just one host (see OsClientFactory)
node = self._client.transport.hosts[0]
msg = "The configured user could not authenticate against your OpenSearch metrics store running on host [%s] at " \
"port [%s] (wrong password?). Please fix the configuration in [%s]." % \
(node["host"], node["port"], config.ConfigFile().location)
self.logger.exception(msg)
raise exceptions.SystemSetupError(msg)
except elasticsearch.exceptions.AuthorizationException:
node = self._client.transport.hosts[0]
msg = "The configured user does not have enough privileges to run the operation [%s] against your OpenSearch metrics " \
"store running on host [%s] at port [%s]. Please specify a user with enough " \
"privileges in the configuration in [%s]." % \
(target.__name__, node["host"], node["port"], config.ConfigFile().location)
self.logger.exception(msg)
raise exceptions.SystemSetupError(msg)
except elasticsearch.exceptions.ConnectionTimeout:
if execution_count < max_execution_count:
self.logger.debug("Connection timeout in attempt [%d/%d].", execution_count, max_execution_count)
time.sleep(time_to_sleep)
else:
operation = target.__name__
self.logger.exception("Connection timeout while running [%s] (retried %d times).", operation, max_execution_count)
node = self._client.transport.hosts[0]
msg = "A connection timeout occurred while running the operation [%s] against your OpenSearch metrics store on " \
"host [%s] at port [%s]." % (operation, node["host"], node["port"])
raise exceptions.BenchmarkError(msg)
except elasticsearch.exceptions.ConnectionError:
node = self._client.transport.hosts[0]
msg = "Could not connect to your OpenSearch metrics store. Please check that it is running on host [%s] at port [%s]" \
" or fix the configuration in [%s]." % (node["host"], node["port"], config.ConfigFile().location)
self.logger.exception(msg)
raise exceptions.SystemSetupError(msg)
except elasticsearch.TransportError as e:
if e.status_code in (502, 503, 504, 429) and execution_count < max_execution_count:
self.logger.debug("%s (code: %d) in attempt [%d/%d]. Sleeping for [%f] seconds.",
responses[e.status_code], e.status_code, execution_count, max_execution_count, time_to_sleep)
time.sleep(time_to_sleep)
else:
node = self._client.transport.hosts[0]
msg = "A transport error occurred while running the operation [%s] against your OpenSearch metrics store on " \
"host [%s] at port [%s]." % (target.__name__, node["host"], node["port"])
self.logger.exception(msg)
raise exceptions.BenchmarkError(msg)
except elasticsearch.exceptions.ElasticsearchException:
node = self._client.transport.hosts[0]
msg = "An unknown error occurred while running the operation [%s] against your OpenSearch metrics store on host [%s] " \
"at port [%s]." % (target.__name__, node["host"], node["port"])
self.logger.exception(msg)
# this does not necessarily mean it's a system setup problem...
raise exceptions.BenchmarkError(msg)
class OsClientFactory:
"""
Abstracts how the OpenSearch client is created. Intended for testing.
"""
def __init__(self, cfg):
self._config = cfg
host = self._config.opts("results_publishing", "datastore.host")
port = self._config.opts("results_publishing", "datastore.port")
secure = convert.to_bool(self._config.opts("results_publishing", "datastore.secure"))
user = self._config.opts("results_publishing", "datastore.user")
password = self._config.opts("results_publishing", "datastore.password")
verify = self._config.opts("results_publishing", "datastore.ssl.verification_mode", default_value="full", mandatory=False) != "none"
ca_path = self._config.opts("results_publishing", "datastore.ssl.certificate_authorities", default_value=None, mandatory=False)
self.probe_version = self._config.opts("results_publishing", "datastore.probe.cluster_version", default_value=True, mandatory=False)
# Instead of duplicating code, we're just adapting the metrics store specific properties to match the regular client options.
client_options = {
"use_ssl": secure,
"verify_certs": verify,
"timeout": 120
}
if ca_path:
client_options["ca_certs"] = ca_path
if user and password:
client_options["basic_auth_user"] = user
client_options["basic_auth_password"] = password
factory = client.OsClientFactory(hosts=[{"host": host, "port": port}], client_options=client_options)
self._client = factory.create()
def create(self):
c = OsClient(self._client)
if self.probe_version:
c.probe_version()
return c
class IndexTemplateProvider:
"""
Abstracts how the Benchmark index template is retrieved. Intended for testing.
"""
def __init__(self, cfg):
self.script_dir = cfg.opts("node", "benchmark.root")
def metrics_template(self):
return self._read("metrics-template")
def test_executions_template(self):
return self._read("test-executions-template")
def results_template(self):
return self._read("results-template")
def _read(self, template_name):
with open("%s/resources/%s.json" % (self.script_dir, template_name), encoding="utf-8") as f:
return f.read()
class MetaInfoScope(Enum):
"""
Defines the scope of a meta-information. Meta-information provides more context for a metric, for example the concrete version
of OpenSearch that has been benchmarked or environment information like CPU model or OS.
"""
cluster = 1
"""
Cluster level meta-information is valid for all nodes in the cluster (e.g. the benchmarked OpenSearch version)
"""
node = 3
"""
Node level meta-information is valid for a single node (e.g. GC times)
"""
def calculate_results(store, test_execution):
calc = GlobalStatsCalculator(store, test_execution.workload, test_execution.test_procedure)
return calc()
def calculate_system_results(store, node_name):
calc = SystemStatsCalculator(store, node_name)
return calc()
def metrics_store(cfg, read_only=True, workload=None, test_procedure=None, provision_config_instance=None, meta_info=None):
"""
Creates a proper metrics store based on the current configuration.
:param cfg: Config object.
:param read_only: Whether to open the metrics store only for reading (Default: True).
:return: A metrics store implementation.
"""
cls = metrics_store_class(cfg)
store = cls(cfg=cfg, meta_info=meta_info)
logging.getLogger(__name__).info("Creating %s", str(store))
test_execution_id = cfg.opts("system", "test_execution.id")
test_execution_timestamp = cfg.opts("system", "time.start")
selected_provision_config_instance = cfg.opts("builder", "provision_config_instance.names") \
if provision_config_instance is None else provision_config_instance
store.open(
test_execution_id, test_execution_timestamp,
workload, test_procedure, selected_provision_config_instance,
create=not read_only)
return store
def metrics_store_class(cfg):
if cfg.opts("results_publishing", "datastore.type") == "opensearch":
return OsMetricsStore
else:
return InMemoryMetricsStore
def extract_user_tags_from_config(cfg):
"""
Extracts user tags into a structured dict
:param cfg: The current configuration object.
:return: A dict containing user tags. If no user tags are given, an empty dict is returned.
"""
user_tags = cfg.opts("test_execution", "user.tag", mandatory=False)
return extract_user_tags_from_string(user_tags)
def extract_user_tags_from_string(user_tags):
"""
Extracts user tags into a structured dict
:param user_tags: A string containing user tags (tags separated by comma, key and value separated by colon).
:return: A dict containing user tags. If no user tags are given, an empty dict is returned.
"""
user_tags_dict = {}
if user_tags and user_tags.strip() != "":
try:
for user_tag in user_tags.split(","):
user_tag_key, user_tag_value = user_tag.split(":")
user_tags_dict[user_tag_key] = user_tag_value
except ValueError:
msg = "User tag keys and values have to separated by a ':'. Invalid value [%s]" % user_tags
logging.getLogger(__name__).exception(msg)
raise exceptions.SystemSetupError(msg)
return user_tags_dict
class SampleType(IntEnum):
Warmup = 0
Normal = 1
class MetricsStore:
"""
Abstract metrics store
"""
def __init__(self, cfg, clock=time.Clock, meta_info=None):
"""
Creates a new metrics store.
:param cfg: The config object. Mandatory.
:param clock: This parameter is optional and needed for testing.
:param meta_info: This parameter is optional and intended for creating a metrics store with a previously serialized meta-info.
"""
self._config = cfg
self._test_execution_id = None
self._test_execution_timestamp = None
self._workload = None
self._workload_params = cfg.opts("workload", "params", default_value={}, mandatory=False)
self._test_procedure = None
self._provision_config_instance = None
self._provision_config_instance_name = None
self._environment_name = cfg.opts("system", "env.name")
self.opened = False
if meta_info is None:
self._meta_info = {}
else:
self._meta_info = meta_info
# ensure mandatory keys are always present
if MetaInfoScope.cluster not in self._meta_info:
self._meta_info[MetaInfoScope.cluster] = {}
if MetaInfoScope.node not in self._meta_info:
self._meta_info[MetaInfoScope.node] = {}
self._clock = clock
self._stop_watch = self._clock.stop_watch()
self.logger = logging.getLogger(__name__)
def open(self, test_ex_id=None, test_ex_timestamp=None, workload_name=None,\
test_procedure_name=None, provision_config_instance_name=None, ctx=None,\
create=False):
"""
Opens a metrics store for a specific test_execution, workload, test_procedure and provision_config_instance.
:param test_ex_id: The test execution id. This attribute is sufficient to uniquely identify a test_execution.
:param test_ex_timestamp: The test execution timestamp as a datetime.
:param workload_name: Workload name.
:param test_procedure_name: TestProcedure name.
:param provision_config_instance_name: ProvisionConfigInstance name.
:param ctx: An metrics store open context retrieved from another metrics store with ``#open_context``.
:param create: True if an index should be created (if necessary). This is typically True, when attempting to write metrics and
False when it is just opened for reading (as we can assume all necessary indices exist at this point).
"""
if ctx:
self._test_execution_id = ctx["test-execution-id"]
self._test_execution_timestamp = ctx["test-execution-timestamp"]
self._workload = ctx["workload"]
self._test_procedure = ctx["test_procedure"]
self._provision_config_instance = ctx["provision-config-instance"]
else:
self._test_execution_id = test_ex_id
self._test_execution_timestamp = time.to_iso8601(test_ex_timestamp)
self._workload = workload_name
self._test_procedure = test_procedure_name
self._provision_config_instance = provision_config_instance_name
assert self._test_execution_id is not None, "Attempting to open metrics store without a test execution id"
assert self._test_execution_timestamp is not None, "Attempting to open metrics store without a test execution timestamp"
self._provision_config_instance_name = "+".join(self._provision_config_instance) \
if isinstance(self._provision_config_instance, list) \
else self._provision_config_instance
self.logger.info("Opening metrics store for test execution timestamp=[%s], workload=[%s],"
"test_procedure=[%s], provision_config_instance=[%s]",
self._test_execution_timestamp, self._workload, self._test_procedure, self._provision_config_instance)
user_tags = extract_user_tags_from_config(self._config)
for k, v in user_tags.items():
# prefix user tag with "tag_" in order to avoid clashes with our internal meta data
self.add_meta_info(MetaInfoScope.cluster, None, "tag_%s" % k, v)
# Don't store it for each metrics record as it's probably sufficient on test execution level
# self.add_meta_info(MetaInfoScope.cluster, None, "benchmark_version", version.version())
self._stop_watch.start()
self.opened = True
def reset_relative_time(self):
"""
Resets the internal relative-time counter to zero.
"""
self._stop_watch.start()
def flush(self, refresh=True):
"""
Explicitly flushes buffered metrics to the metric store. It is not required to flush before closing the metrics store.
"""
raise NotImplementedError("abstract method")
def close(self):
"""
Closes the metric store. Note that it is mandatory to close the metrics store when it is no longer needed as it only persists
metrics on close (in order to avoid additional latency during the benchmark).
"""
self.logger.info("Closing metrics store.")
self.flush()
self._clear_meta_info()
self.opened = False
def add_meta_info(self, scope, scope_key, key, value):
"""
Adds new meta information to the metrics store. All metrics entries that are created after calling this method are guaranteed to
contain the added meta info (provided is on the same level or a level below, e.g. a cluster level metric will not contain node
level meta information but all cluster level meta information will be contained in a node level metrics record).
:param scope: The scope of the meta information. See MetaInfoScope.
:param scope_key: The key within the scope. For cluster level metrics None is expected, for node level metrics the node name.
:param key: The key of the meta information.
:param value: The value of the meta information.
"""
if scope == MetaInfoScope.cluster:
self._meta_info[MetaInfoScope.cluster][key] = value
elif scope == MetaInfoScope.node:
if scope_key not in self._meta_info[MetaInfoScope.node]:
self._meta_info[MetaInfoScope.node][scope_key] = {}
self._meta_info[MetaInfoScope.node][scope_key][key] = value
else:
raise exceptions.SystemSetupError("Unknown meta info scope [%s]" % scope)
def _clear_meta_info(self):
"""
Clears all internally stored meta-info. This is considered Benchmark internal API and not intended for normal client consumption.
"""
self._meta_info = {
MetaInfoScope.cluster: {},
MetaInfoScope.node: {}
}
@property
def open_context(self):
return {
"test-execution-id": self._test_execution_id,
"test-execution-timestamp": self._test_execution_timestamp,
"workload": self._workload,
"test_procedure": self._test_procedure,
"provision-config-instance": self._provision_config_instance
}
def put_value_cluster_level(self, name, value, unit=None, task=None, operation=None, operation_type=None, sample_type=SampleType.Normal,
absolute_time=None, relative_time=None, meta_data=None):
"""
Adds a new cluster level value metric.
:param name: The name of the metric.
:param value: The metric value. It is expected to be numeric.
:param unit: The unit of this metric value (e.g. ms, docs/s). Optional. Defaults to None.
:param task: The task name to which this value applies. Optional. Defaults to None.
:param operation: The operation name to which this value applies. Optional. Defaults to None.
:param operation_type: The operation type to which this value applies. Optional. Defaults to None.
:param sample_type: Whether this is a warmup or a normal measurement sample. Defaults to SampleType.Normal.
:param absolute_time: The absolute timestamp in seconds since epoch when this metric record is stored. Defaults to None. The metrics
store will derive the timestamp automatically.
:param relative_time: The relative timestamp in seconds since the start of the benchmark when this metric record is stored.
Defaults to None. The metrics store will derive the timestamp automatically.
:param meta_data: A dict, containing additional key-value pairs. Defaults to None.
"""
self._put_metric(MetaInfoScope.cluster, None, name, value, unit, task, operation, operation_type, sample_type, absolute_time,
relative_time, meta_data)
def put_value_node_level(self, node_name, name, value, unit=None, task=None, operation=None, operation_type=None,
sample_type=SampleType.Normal, absolute_time=None, relative_time=None, meta_data=None):
"""
Adds a new node level value metric.
:param name: The name of the metric.
:param node_name: The name of the cluster node for which this metric has been determined.
:param value: The metric value. It is expected to be numeric.
:param unit: The unit of this metric value (e.g. ms, docs/s). Optional. Defaults to None.
:param task: The task name to which this value applies. Optional. Defaults to None.
:param operation: The operation name to which this value applies. Optional. Defaults to None.
:param operation_type: The operation type to which this value applies. Optional. Defaults to None.
:param sample_type: Whether this is a warmup or a normal measurement sample. Defaults to SampleType.Normal.
:param absolute_time: The absolute timestamp in seconds since epoch when this metric record is stored. Defaults to None. The metrics
store will derive the timestamp automatically.
:param relative_time: The relative timestamp in seconds since the start of the benchmark when this metric record is stored.
Defaults to None. The metrics store will derive the timestamp automatically.
:param meta_data: A dict, containing additional key-value pairs. Defaults to None.
"""
self._put_metric(MetaInfoScope.node, node_name, name, value, unit, task, operation, operation_type, sample_type, absolute_time,
relative_time, meta_data)
def _put_metric(self, level, level_key, name, value, unit, task, operation, operation_type, sample_type, absolute_time=None,
relative_time=None, meta_data=None):
if level == MetaInfoScope.cluster:
meta = self._meta_info[MetaInfoScope.cluster].copy()
elif level == MetaInfoScope.node:
meta = self._meta_info[MetaInfoScope.cluster].copy()
if level_key in self._meta_info[MetaInfoScope.node]:
meta.update(self._meta_info[MetaInfoScope.node][level_key])
else:
raise exceptions.SystemSetupError("Unknown meta info level [%s] for metric [%s]" % (level, name))
if meta_data:
meta.update(meta_data)
if absolute_time is None:
absolute_time = self._clock.now()
if relative_time is None:
relative_time = self._stop_watch.split_time()
doc = {
"@timestamp": time.to_epoch_millis(absolute_time),
"relative-time-ms": convert.seconds_to_ms(relative_time),
"test-execution-id": self._test_execution_id,
"test-execution-timestamp": self._test_execution_timestamp,
"environment": self._environment_name,
"workload": self._workload,
"test_procedure": self._test_procedure,
"provision-config-instance": self._provision_config_instance_name,
"name": name,
"value": value,
"unit": unit,
"sample-type": sample_type.name.lower(),
"meta": meta
}
if task:
doc["task"] = task
if operation:
doc["operation"] = operation
if operation_type:
doc["operation-type"] = operation_type
if self._workload_params:
doc["workload-params"] = self._workload_params
self._add(doc)
def put_doc(self, doc, level=None, node_name=None, meta_data=None, absolute_time=None, relative_time=None):
"""
Adds a new document to the metrics store. It will merge additional properties into the doc such as timestamps or workload info.
:param doc: The raw document as a ``dict``. Ownership is transferred to the metrics store (i.e. don't reuse that object).
:param level: Whether these are cluster or node-level metrics. May be ``None`` if not applicable.
:param node_name: The name of the node in case metrics are on node level.
:param meta_data: A dict, containing additional key-value pairs. Defaults to None.
:param absolute_time: The absolute timestamp in seconds since epoch when this metric record is stored. Defaults to None. The metrics
store will derive the timestamp automatically.
:param relative_time: The relative timestamp in seconds since the start of the benchmark when this metric record is stored.
Defaults to None. The metrics store will derive the timestamp automatically.
"""
if level == MetaInfoScope.cluster:
meta = self._meta_info[MetaInfoScope.cluster].copy()
elif level == MetaInfoScope.node:
meta = self._meta_info[MetaInfoScope.cluster].copy()
if node_name in self._meta_info[MetaInfoScope.node]:
meta.update(self._meta_info[MetaInfoScope.node][node_name])
elif level is None:
meta = None
else:
raise exceptions.SystemSetupError("Unknown meta info level [{}]".format(level))
if meta and meta_data:
meta.update(meta_data)
if absolute_time is None:
absolute_time = self._clock.now()
if relative_time is None:
relative_time = self._stop_watch.split_time()
doc.update({
"@timestamp": time.to_epoch_millis(absolute_time),
"relative-time-ms": convert.seconds_to_ms(relative_time),
"test-execution-id": self._test_execution_id,
"test-execution-timestamp": self._test_execution_timestamp,
"environment": self._environment_name,
"workload": self._workload,
"test_procedure": self._test_procedure,
"provision-config-instance": self._provision_config_instance_name,
})
if meta:
doc["meta"] = meta
if self._workload_params:
doc["workload-params"] = self._workload_params
self._add(doc)
def bulk_add(self, memento):
"""
Adds raw metrics store documents previously created with #to_externalizable()
:param memento: The external representation as returned by #to_externalizable().
"""
if memento:
self.logger.debug("Restoring in-memory representation of metrics store.")
for doc in pickle.loads(zlib.decompress(memento)):
self._add(doc)
def to_externalizable(self, clear=False):
raise NotImplementedError("abstract method")
def _add(self, doc):
"""
Adds a new document to the metrics store
:param doc: The new document.
"""
raise NotImplementedError("abstract method")
def get_one(self, name, sample_type=None, node_name=None, task=None, mapper=lambda doc: doc["value"],
sort_key=None, sort_reverse=False):
"""
Gets one value for the given metric name (even if there should be more than one).
:param name: The metric name to query.
:param sample_type The sample type to query. Optional. By default, all samples are considered.
:param node_name The name of the node where this metric was gathered. Optional.
:param task The task name to query. Optional.
:param sort_key The key to sort the docs before returning the first value. Optional.
:param sort_reverse The flag to reverse the sort. Optional.
:return: The corresponding value for the given metric name or None if there is no value.
"""
raise NotImplementedError("abstract method")
@staticmethod
def _first_or_none(values):
return values[0] if values else None
def get(self, name, task=None, operation_type=None, sample_type=None, node_name=None):
"""
Gets all raw values for the given metric name.
:param name: The metric name to query.
:param task The task name to query. Optional.
:param operation_type The operation type to query. Optional.
:param sample_type The sample type to query. Optional. By default, all samples are considered.
:param node_name The name of the node where this metric was gathered. Optional.
:return: A list of all values for the given metric.
"""
return self._get(name, task, operation_type, sample_type, node_name, lambda doc: doc["value"])
def get_raw(self, name, task=None, operation_type=None, sample_type=None, node_name=None, mapper=lambda doc: doc):
"""
Gets all raw records for the given metric name.
:param name: The metric name to query.
:param task The task name to query. Optional.
:param operation_type The operation type to query. Optional.
:param sample_type The sample type to query. Optional. By default, all samples are considered.
:param node_name The name of the node where this metric was gathered. Optional.
:param mapper A record mapper. By default, the complete record is returned.
:return: A list of all raw records for the given metric.
"""
return self._get(name, task, operation_type, sample_type, node_name, mapper)
def get_unit(self, name, task=None, operation_type=None, node_name=None):
"""
Gets the unit for the given metric name.
:param name: The metric name to query.
:param task The task name to query. Optional.
:param operation_type The operation type to query. Optional.
:param node_name The name of the node where this metric was gathered. Optional.
:return: The corresponding unit for the given metric name or None if no metric record is available.
"""
# does not make too much sense to ask for a sample type here
return self._first_or_none(self._get(name, task, operation_type, None, node_name, lambda doc: doc["unit"]))
def _get(self, name, task, operation_type, sample_type, node_name, mapper):
raise NotImplementedError("abstract method")
def get_error_rate(self, task, operation_type=None, sample_type=None):
"""
Gets the error rate for a specific task.
:param task The task name to query.
:param operation_type The operation type to query. Optional.
:param sample_type The sample type to query. Optional. By default, all samples are considered.
:return: A float between 0.0 and 1.0 (inclusive) representing the error rate.
"""
raise NotImplementedError("abstract method")
def get_stats(self, name, task=None, operation_type=None, sample_type=None):
"""
Gets standard statistics for the given metric.
:param name: The metric name to query.
:param task The task name to query. Optional.
:param operation_type The operation type to query. Optional.
:param sample_type The sample type to query. Optional. By default, all samples are considered.
:return: A metric_stats structure.
"""
raise NotImplementedError("abstract method")
def get_percentiles(self, name, task=None, operation_type=None, sample_type=None, percentiles=None):
"""
Retrieves percentile metrics for the given metric.
:param name: The metric name to query.
:param task The task name to query. Optional.
:param operation_type The operation type to query. Optional.
:param sample_type The sample type to query. Optional. By default, all samples are considered.
:param percentiles: An optional list of percentiles to show. If None is provided, by default the 99th, 99.9th and 100th percentile
are determined. Ensure that there are enough data points in the metrics store (e.g. it makes no sense to retrieve a 99.9999
percentile when there are only 10 values).
:return: An ordered dictionary of the determined percentile values in ascending order. Key is the percentile, value is the
determined value at this percentile. If no percentiles could be determined None is returned.
"""
raise NotImplementedError("abstract method")
def get_median(self, name, task=None, operation_type=None, sample_type=None):
"""
Retrieves median value of the given metric.
:param name: The metric name to query.
:param task The task name to query. Optional.
:param operation_type The operation type to query. Optional.
:param sample_type The sample type to query. Optional. By default, all samples are considered.
:return: The median value.
"""
median = "50.0"
percentiles = self.get_percentiles(name, task, operation_type, sample_type, percentiles=[median])
return percentiles[median] if percentiles else None
def get_mean(self, name, task=None, operation_type=None, sample_type=None):
"""
Retrieves mean of the given metric.
:param name: The metric name to query.
:param task The task name to query. Optional.
:param operation_type The operation type to query. Optional.
:param sample_type The sample type to query. Optional. By default, all samples are considered.
:return: The mean.
"""
stats = self.get_stats(name, task, operation_type, sample_type)
return stats["avg"] if stats else None
class OsMetricsStore(MetricsStore):
"""
A metrics store backed by OpenSearch.
"""
METRICS_DOC_TYPE = "_doc"
def __init__(self,
cfg,
client_factory_class=OsClientFactory,
index_template_provider_class=IndexTemplateProvider,
clock=time.Clock, meta_info=None):
"""
Creates a new metrics store.
:param cfg: The config object. Mandatory.
:param client_factory_class: This parameter is optional and needed for testing.
:param index_template_provider_class: This parameter is optional and needed for testing.
:param clock: This parameter is optional and needed for testing.
:param meta_info: This parameter is optional and intended for creating a metrics store with a previously serialized meta-info.
"""
MetricsStore.__init__(self, cfg=cfg, clock=clock, meta_info=meta_info)
self._index = None
self._client = client_factory_class(cfg).create()
self._index_template_provider = index_template_provider_class(cfg)
self._docs = None
def open(self, test_ex_id=None, test_ex_timestamp=None, workload_name=None, \
test_procedure_name=None, provision_config_instance_name=None, ctx=None, \
create=False):
self._docs = []
MetricsStore.open(
self, test_ex_id, test_ex_timestamp,
workload_name, test_procedure_name,
provision_config_instance_name, ctx, create)
self._index = self.index_name()
# reduce a bit of noise in the metrics cluster log
if create:
# always update the mapping to the latest version
self._client.put_template("benchmark-metrics", self._get_template())
if not self._client.exists(index=self._index):
self._client.create_index(index=self._index)
else:
self.logger.info("[%s] already exists.", self._index)
else:
# we still need to check for the correct index name - prefer the one with the suffix
new_name = self._migrated_index_name(self._index)
if self._client.exists(index=new_name):
self._index = new_name
# ensure we can search immediately after opening
self._client.refresh(index=self._index)
def index_name(self):
ts = time.from_is8601(self._test_execution_timestamp)
return "benchmark-metrics-%04d-%02d" % (ts.year, ts.month)
def _migrated_index_name(self, original_name):
return "{}.new".format(original_name)
def _get_template(self):
return self._index_template_provider.metrics_template()
def flush(self, refresh=True):
if self._docs:
sw = time.StopWatch()
sw.start()
self._client.bulk_index(index=self._index, doc_type=OsMetricsStore.METRICS_DOC_TYPE, items=self._docs)
sw.stop()
self.logger.info("Successfully added %d metrics documents for test execution timestamp=[%s], workload=[%s], "
"test_procedure=[%s], provision_config_instance=[%s] in [%f] seconds.",
len(self._docs), self._test_execution_timestamp,
self._workload, self._test_procedure, self._provision_config_instance, sw.total_time())
self._docs = []
# ensure we can search immediately after flushing
if refresh:
self._client.refresh(index=self._index)
def _add(self, doc):
self._docs.append(doc)
def _get(self, name, task, operation_type, sample_type, node_name, mapper):
query = {
"query": self._query_by_name(name, task, operation_type, sample_type, node_name)
}
self.logger.debug("Issuing get against index=[%s], query=[%s].", self._index, query)
result = self._client.search(index=self._index, body=query)
self.logger.debug("Metrics query produced [%s] results.", result["hits"]["total"])
return [mapper(v["_source"]) for v in result["hits"]["hits"]]
def get_one(self, name, sample_type=None, node_name=None, task=None, mapper=lambda doc: doc["value"],
sort_key=None, sort_reverse=False):
order = "desc" if sort_reverse else "asc"
query = {
"query": self._query_by_name(name, task, None, sample_type, node_name),
"size": 1
}
if sort_key:
query["sort"] = [{sort_key: {"order": order}}]
self.logger.debug("Issuing get against index=[%s], query=[%s].", self._index, query)
result = self._client.search(index=self._index, body=query)
hits = result["hits"]["total"]
# OpenSearch 1.0+
if isinstance(hits, dict):
hits = hits["value"]
self.logger.debug("Metrics query produced [%s] results.", hits)
if hits > 0:
return mapper(result["hits"]["hits"][0]["_source"])
else:
return None
def get_error_rate(self, task, operation_type=None, sample_type=None):
query = {
"query": self._query_by_name("service_time", task, operation_type, sample_type, None),
"size": 0,
"aggs": {
"error_rate": {
"terms": {
"field": "meta.success"
}
}
}
}
self.logger.debug("Issuing get_error_rate against index=[%s], query=[%s]", self._index, query)
result = self._client.search(index=self._index, body=query)
buckets = result["aggregations"]["error_rate"]["buckets"]
self.logger.debug("Query returned [%d] buckets.", len(buckets))
count_success = 0
count_errors = 0
for bucket in buckets:
k = bucket["key_as_string"]
doc_count = int(bucket["doc_count"])
self.logger.debug("Processing key [%s] with [%d] docs.", k, doc_count)
if k == "true":
count_success = doc_count
elif k == "false":
count_errors = doc_count
else:
self.logger.warning("Unrecognized bucket key [%s] with [%d] docs.", k, doc_count)
if count_errors == 0:
return 0.0
elif count_success == 0:
return 1.0
else:
return count_errors / (count_errors + count_success)
def get_stats(self, name, task=None, operation_type=None, sample_type=None):
"""
Gets standard statistics for the given metric name.
:return: A metric_stats structure.
"""
query = {
"query": self._query_by_name(name, task, operation_type, sample_type, None),
"size": 0,
"aggs": {
"metric_stats": {
"stats": {
"field": "value"
}
}
}
}
self.logger.debug("Issuing get_stats against index=[%s], query=[%s]", self._index, query)
result = self._client.search(index=self._index, body=query)
return result["aggregations"]["metric_stats"]
def get_percentiles(self, name, task=None, operation_type=None, sample_type=None, percentiles=None):
if percentiles is None:
percentiles = [99, 99.9, 100]
query = {
"query": self._query_by_name(name, task, operation_type, sample_type, None),
"size": 0,
"aggs": {
"percentile_stats": {
"percentiles": {
"field": "value",
"percents": percentiles
}
}
}
}
self.logger.debug("Issuing get_percentiles against index=[%s], query=[%s]", self._index, query)
result = self._client.search(index=self._index, body=query)
hits = result["hits"]["total"]
# OpenSearch 1.0+
if isinstance(hits, dict):
hits = hits["value"]
self.logger.debug("get_percentiles produced %d hits", hits)
if hits > 0:
raw = result["aggregations"]["percentile_stats"]["values"]
return collections.OrderedDict(sorted(raw.items(), key=lambda t: float(t[0])))
else:
return None
def _query_by_name(self, name, task, operation_type, sample_type, node_name):
q = {
"bool": {
"filter": [
{
"term": {
"test-execution-id": self._test_execution_id
}
},
{
"term": {
"name": name
}
}
]
}
}
if task:
q["bool"]["filter"].append({
"term": {
"task": task
}
})
if operation_type:
q["bool"]["filter"].append({
"term": {
"operation-type": operation_type
}
})
if sample_type:
q["bool"]["filter"].append({
"term": {
"sample-type": sample_type.name.lower()
}
})
if node_name:
q["bool"]["filter"].append({
"term": {
"meta.node_name": node_name
}
})
return q