/
api.py
2344 lines (1993 loc) · 83.3 KB
/
api.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
# -*- encoding: utf-8 -*-
#
# Copyright © 2016-2018 Red Hat, Inc.
# Copyright © 2014-2015 eNovance
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import collections
import functools
import itertools
import logging
import operator
import uuid
import jsonpatch
import pecan
from pecan import rest
import pyparsing
import six
from six.moves.urllib import parse as urllib_parse
import tenacity
import tooz
import voluptuous
import werkzeug.http
import gnocchi
from gnocchi import archive_policy
from gnocchi import calendar
from gnocchi import chef
from gnocchi.cli import metricd
from gnocchi import incoming
from gnocchi import indexer
from gnocchi import json
from gnocchi import resource_type
from gnocchi.rest.aggregates import exceptions
from gnocchi.rest.aggregates import processor
from gnocchi.rest import exceptions as rest_exceptions
from gnocchi import storage
from gnocchi import utils
try:
from gnocchi.rest.prometheus import remote_pb2
import snappy
PROMETHEUS_SUPPORTED = True
except ImportError:
PROMETHEUS_SUPPORTED = False
ATTRGETTER_GRANULARITY = operator.attrgetter("granularity")
LOG = logging.getLogger(__name__)
def arg_to_list(value):
if isinstance(value, list):
return value
elif value:
return [value]
return []
def abort(status_code, detail=''):
"""Like pecan.abort, but make sure detail is a string."""
if status_code == 404 and not detail:
raise RuntimeError("http code 404 must have 'detail' set")
if isinstance(detail, voluptuous.Invalid):
detail = {
'cause': 'Invalid input',
'reason': six.text_type(detail),
'detail': [six.text_type(path) for path in detail.path],
}
elif isinstance(detail, Exception):
detail = detail.jsonify()
LOG.debug("Aborting request. Code [%s]. Details [%s]", status_code, detail)
return pecan.abort(status_code, detail)
def flatten_dict_to_keypairs(d, separator=':'):
"""Generator that produces sequence of keypairs for nested dictionaries.
:param d: dictionaries which may be nested
:param separator: symbol between names
"""
for name, value in sorted(six.iteritems(d)):
if isinstance(value, dict):
for subname, subvalue in flatten_dict_to_keypairs(value,
separator):
yield ('%s%s%s' % (name, separator, subname), subvalue)
else:
yield name, value
def enforce(rule, target):
"""Return the user and project the request should be limited to.
:param rule: The rule name
:param target: The target to enforce on.
"""
creds = pecan.request.auth_helper.get_auth_info(pecan.request)
if not isinstance(target, dict):
if hasattr(target, "jsonify"):
target = target.jsonify()
else:
target = target.__dict__
# Flatten dict
target = dict(flatten_dict_to_keypairs(d=target, separator='.'))
if not pecan.request.policy_enforcer.enforce(rule, target, creds):
abort(403)
def set_resp_location_hdr(location):
location = '%s%s' % (pecan.request.script_name, location)
# NOTE(sileht): according the pep-3333 the headers must be
# str in py2 and py3 even this is not the same thing in both
# version
# see: http://legacy.python.org/dev/peps/pep-3333/#unicode-issues
if six.PY2 and isinstance(location, six.text_type):
location = location.encode('utf-8')
location = urllib_parse.quote(location)
pecan.response.headers['Location'] = location
def set_resp_link_hdr(marker, *args):
# NOTE(sileht): This comes from rfc5988.
# Setting prev, last is too costly/complicated, so just set next for now.
options = {}
for arg in args:
options.update(arg)
if "sorts" in options:
options["sort"] = options["sorts"]
del options["sorts"]
options["marker"] = marker
# NOTE(sileht): To always have the same orders
options = sorted(options.items())
params = urllib_parse.urlencode(options, doseq=True)
pecan.response.headers.add("Link", '<%s?%s>; rel="next"' %
(pecan.request.path_url, params))
def deserialize(expected_content_types=None):
if expected_content_types is None:
expected_content_types = ("application/json", )
mime_type, options = werkzeug.http.parse_options_header(
pecan.request.headers.get('Content-Type'))
if mime_type not in expected_content_types:
abort(415)
try:
params = json.load(pecan.request.body_file)
except Exception as e:
details = rest_exceptions.UnableToDecodeBody(e,
pecan.request.body_file)
LOG.warning(details.jsonify())
abort(400, details)
return params
def validate(schema, data, required=True):
try:
return voluptuous.Schema(schema, required=required)(data)
except voluptuous.Invalid as e:
abort(400, e)
def deserialize_and_validate(schema, required=True,
expected_content_types=None):
return validate(schema,
deserialize(expected_content_types=expected_content_types),
required)
def Timespan(value):
try:
return utils.to_timespan(value)
except ValueError as e:
raise voluptuous.Invalid(e)
def get_bool_param(name, params, default='false'):
return strtobool(name, params.get(name, default))
def strtobool(varname, v):
"""Convert a string to a boolean."""
try:
return utils.strtobool(v)
except ValueError as e:
abort(400, "Unable to parse `%s': %s" % (varname, six.text_type(e)))
RESOURCE_DEFAULT_PAGINATION = [u'revision_start:asc',
u'started_at:asc']
METRIC_DEFAULT_PAGINATION = [u'id:asc']
def get_pagination_options(params, default):
try:
opts = voluptuous.Schema({
voluptuous.Required(
"limit", default=pecan.request.conf.api.max_limit):
voluptuous.All(voluptuous.Coerce(int),
voluptuous.Range(min=1),
voluptuous.Clamp(
min=1, max=pecan.request.conf.api.max_limit)),
"marker": six.text_type,
voluptuous.Required("sort", default=default):
voluptuous.All(
voluptuous.Coerce(arg_to_list),
[six.text_type]),
}, extra=voluptuous.REMOVE_EXTRA)(params)
except voluptuous.Invalid as e:
abort(400, {"cause": "Argument value error",
"reason": str(e)})
opts['sorts'] = opts['sort']
del opts['sort']
return opts
ArchivePolicyDefinitionSchema = voluptuous.Schema(
voluptuous.All([{
"granularity": Timespan,
"points": voluptuous.All(
voluptuous.Coerce(int),
voluptuous.Range(min=1),
),
"timespan": Timespan,
}], voluptuous.Length(min=1)),
)
class ArchivePolicyController(rest.RestController):
def __init__(self, archive_policy):
self.archive_policy = archive_policy
@pecan.expose('json')
def get(self):
ap = pecan.request.indexer.get_archive_policy(self.archive_policy)
if ap:
enforce("get archive policy", ap)
return ap
abort(404, six.text_type(
indexer.NoSuchArchivePolicy(self.archive_policy)))
@pecan.expose('json')
def patch(self):
ap = pecan.request.indexer.get_archive_policy(self.archive_policy)
if not ap:
abort(404, six.text_type(
indexer.NoSuchArchivePolicy(self.archive_policy)))
enforce("update archive policy", ap)
body = deserialize_and_validate(voluptuous.Schema({
voluptuous.Required("definition"): ArchivePolicyDefinitionSchema,
}))
# Validate the data
try:
ap_items = [archive_policy.ArchivePolicyItem(**item) for item in
body['definition']]
except ValueError as e:
abort(400, six.text_type(e))
try:
return pecan.request.indexer.update_archive_policy(
self.archive_policy, ap_items)
except indexer.UnsupportedArchivePolicyChange as e:
abort(400, six.text_type(e))
@pecan.expose()
def delete(self):
# NOTE(jd) I don't think there's any point in fetching and passing the
# archive policy here, as the rule is probably checking the actual role
# of the user, not the content of the AP.
enforce("delete archive policy", {})
try:
pecan.request.indexer.delete_archive_policy(self.archive_policy)
except indexer.NoSuchArchivePolicy as e:
abort(404, six.text_type(e))
except indexer.ArchivePolicyInUse as e:
abort(400, six.text_type(e))
class ArchivePoliciesController(rest.RestController):
@pecan.expose()
def _lookup(self, archive_policy, *remainder):
return ArchivePolicyController(archive_policy), remainder
@pecan.expose('json')
def post(self):
enforce("create archive policy", {})
# NOTE(jd): Initialize this one at run-time because we rely on conf
conf = pecan.request.conf
valid_agg_methods = list(
archive_policy.ArchivePolicy.VALID_AGGREGATION_METHODS_VALUES
)
ArchivePolicySchema = voluptuous.Schema({
voluptuous.Required("name"): six.text_type,
voluptuous.Required("back_window", default=0): voluptuous.All(
voluptuous.Coerce(int),
voluptuous.Range(min=0),
),
voluptuous.Required(
"aggregation_methods",
default=list(conf.archive_policy.default_aggregation_methods)):
valid_agg_methods,
voluptuous.Required("definition"): ArchivePolicyDefinitionSchema,
})
body = deserialize_and_validate(ArchivePolicySchema)
# Validate the data
try:
ap = archive_policy.ArchivePolicy.from_dict(body)
except ValueError as e:
abort(400, six.text_type(e))
enforce("create archive policy", ap)
try:
ap = pecan.request.indexer.create_archive_policy(ap)
except indexer.ArchivePolicyAlreadyExists as e:
abort(409, six.text_type(e))
location = "/archive_policy/" + ap.name
set_resp_location_hdr(location)
pecan.response.status = 201
return ap
@pecan.expose('json')
def get_all(self):
enforce("list archive policy", {})
return pecan.request.indexer.list_archive_policies()
class ArchivePolicyRulesController(rest.RestController):
@pecan.expose()
def _lookup(self, archive_policy_rule, *remainder):
apr = pecan.request.indexer.get_archive_policy_rule(
archive_policy_rule
)
if apr:
return ArchivePolicyRuleController(apr), remainder
abort(404, six.text_type(
indexer.NoSuchArchivePolicyRule(archive_policy_rule)))
@pecan.expose('json')
def post(self):
enforce("create archive policy rule", {})
ArchivePolicyRuleSchema = voluptuous.Schema({
voluptuous.Required("name"): six.text_type,
voluptuous.Required("metric_pattern"): six.text_type,
voluptuous.Required("archive_policy_name"): six.text_type,
})
body = deserialize_and_validate(ArchivePolicyRuleSchema)
enforce("create archive policy rule", body)
try:
ap = pecan.request.indexer.create_archive_policy_rule(
body['name'], body['metric_pattern'],
body['archive_policy_name']
)
except indexer.ArchivePolicyRuleAlreadyExists as e:
abort(409, six.text_type(e))
except indexer.NoSuchArchivePolicy as e:
abort(400, e)
location = "/archive_policy_rule/" + ap.name
set_resp_location_hdr(location)
pecan.response.status = 201
return ap
@pecan.expose('json')
def get_all(self):
enforce("list archive policy rule", {})
return pecan.request.indexer.list_archive_policy_rules()
class ArchivePolicyRuleController(rest.RestController):
def __init__(self, archive_policy_rule):
self.archive_policy_rule = archive_policy_rule
@pecan.expose('json')
def get(self):
enforce("get archive policy rule", self.archive_policy_rule)
return self.archive_policy_rule
@pecan.expose('json')
def patch(self):
ArchivePolicyRuleSchema = voluptuous.Schema({
voluptuous.Required("name"): six.text_type,
})
body = deserialize_and_validate(ArchivePolicyRuleSchema)
enforce("update archive policy rule", {})
try:
return pecan.request.indexer.update_archive_policy_rule(
self.archive_policy_rule.name, body["name"])
except indexer.UnsupportedArchivePolicyRuleChange as e:
abort(400, six.text_type(e))
@pecan.expose()
def delete(self):
# NOTE(jd) I don't think there's any point in fetching and passing the
# archive policy rule here, as the rule is probably checking the actual
# role of the user, not the content of the AP rule.
enforce("delete archive policy rule", {})
try:
pecan.request.indexer.delete_archive_policy_rule(
self.archive_policy_rule.name
)
except indexer.NoSuchArchivePolicyRule as e:
abort(404, six.text_type(e))
def MeasuresListSchema(measures):
try:
times = utils.to_timestamps([m['timestamp'] for m in measures])
except TypeError:
raise voluptuous.Invalid("unexpected measures format")
except ValueError as e:
raise voluptuous.Invalid("unexpected timestamp '%s'" % e)
try:
values = [float(i['value']) for i in measures]
except Exception:
raise voluptuous.Invalid("unexpected measures value")
return (incoming.Measure(t, v) for t, v in six.moves.zip(times, values))
class MetricController(rest.RestController):
_custom_actions = {
'measures': ['POST', 'GET']
}
def __init__(self, metric):
self.metric = metric
def enforce_metric(self, rule):
enforce(rule, json.to_primitive(self.metric))
@pecan.expose('json')
def get_all(self):
self.enforce_metric("get metric")
return self.metric
@pecan.expose('json')
def post_measures(self):
self.enforce_metric("post measures")
measures = deserialize_and_validate(MeasuresListSchema)
if measures:
pecan.request.incoming.add_measures(self.metric.id, measures)
pecan.response.status = 202
@pecan.expose('json')
def get_measures(self, start=None, stop=None, aggregation='mean',
granularity=None, resample=None, refresh=False,
**param):
self.enforce_metric("get measures")
if resample:
if not granularity:
abort(400, 'A granularity must be specified to resample')
try:
resample = (resample if calendar.GROUPINGS.get(resample) else
utils.to_timespan(resample))
except ValueError as e:
abort(400, six.text_type(e))
if granularity is None:
granularity = [d.granularity
for d in self.metric.archive_policy.definition]
start, stop, _, _, _ = validate_qs(
start=start, stop=stop)
else:
start, stop, granularity, _, _ = validate_qs(
start=start, stop=stop, granularity=granularity)
if aggregation not in self.metric.archive_policy.aggregation_methods:
abort(404, {
"cause": "Aggregation method does not exist for this metric",
"detail": {
"metric": self.metric.id,
"aggregation_method": aggregation,
},
})
aggregations = []
for g in sorted(granularity, reverse=True):
agg = self.metric.archive_policy.get_aggregation(
aggregation, g)
if agg is None:
abort(404, six.text_type(
storage.AggregationDoesNotExist(
self.metric, aggregation, g)
))
aggregations.append(agg)
if (strtobool("refresh", refresh) and
pecan.request.incoming.has_unprocessed(self.metric.id)):
try:
pecan.request.chef.refresh_metrics(
[self.metric],
pecan.request.conf.api.operation_timeout)
except chef.SackAlreadyLocked:
abort(503, 'Unable to refresh metric: %s. Metric is locked. '
'Please try again.' % self.metric.id)
try:
results = pecan.request.storage.get_aggregated_measures(
{self.metric: aggregations},
start, stop, resample)[self.metric]
return [(timestamp, results[key].aggregation.granularity, value)
for key in sorted(results.keys(),
reverse=True)
for timestamp, value in results[key]]
except storage.AggregationDoesNotExist as e:
abort(404, six.text_type(e))
except storage.MetricDoesNotExist:
return []
@pecan.expose()
def delete(self):
self.enforce_metric("delete metric")
try:
pecan.request.indexer.delete_metric(self.metric.id)
except indexer.NoSuchMetric as e:
abort(404, six.text_type(e))
class MetricsController(rest.RestController):
@pecan.expose()
def _lookup(self, id, *remainder):
try:
metric_id = uuid.UUID(id)
except ValueError:
abort(404, six.text_type(indexer.NoSuchMetric(id)))
# Load details for ACL
metrics = pecan.request.indexer.list_metrics(
attribute_filter={"=": {"id": metric_id}}, details=True)
if not metrics:
abort(404, six.text_type(indexer.NoSuchMetric(id)))
return MetricController(metrics[0]), remainder
# NOTE(jd) Define this method as it was a voluptuous schema – it's just a
# smarter version of a voluptuous schema, no?
@staticmethod
def MetricSchema(definition):
creator = pecan.request.auth_helper.get_current_user(
pecan.request)
# First basic validation
schema = voluptuous.Schema({
"archive_policy_name": six.text_type,
"resource_id": functools.partial(ResourceID, creator=creator),
"name": six.text_type,
voluptuous.Optional("unit"):
voluptuous.All(six.text_type, voluptuous.Length(max=31)),
})
definition = schema(definition)
archive_policy_name = definition.get('archive_policy_name')
name = definition.get('name')
if name and '/' in name:
abort(400, "'/' is not supported in metric name")
if archive_policy_name is None:
try:
ap = pecan.request.indexer.get_archive_policy_for_metric(name)
except indexer.NoArchivePolicyRuleMatch:
# NOTE(jd) Since this is a schema-like function, we
# should/could raise ValueError, but if we do so, voluptuous
# just returns a "invalid value" with no useful message – so we
# prefer to use abort() to make sure the user has the right
# error message
abort(400, "No archive policy name specified "
"and no archive policy rule found matching "
"the metric name %s" % name)
else:
definition['archive_policy_name'] = ap.name
resource_id = definition.get('resource_id')
if resource_id is None:
original_resource_id = None
else:
if name is None:
abort(400,
{"cause": "Attribute value error",
"detail": "name",
"reason": "Name cannot be null "
"if resource_id is not null"})
original_resource_id, resource_id = resource_id
enforce("create metric", {
"creator": creator,
"archive_policy_name": archive_policy_name,
"resource_id": resource_id,
"original_resource_id": original_resource_id,
"name": name,
"unit": definition.get('unit'),
})
return definition
@pecan.expose('json')
def post(self):
creator = pecan.request.auth_helper.get_current_user(
pecan.request)
body = deserialize_and_validate(self.MetricSchema)
resource_id = body.get('resource_id')
if resource_id is not None:
resource_id = resource_id[1]
try:
m = pecan.request.indexer.create_metric(
uuid.uuid4(),
creator,
resource_id=resource_id,
name=body.get('name'),
unit=body.get('unit'),
archive_policy_name=body['archive_policy_name'])
except indexer.NoSuchArchivePolicy as e:
abort(400, six.text_type(e))
except indexer.NamedMetricAlreadyExists as e:
abort(400, e)
set_resp_location_hdr("/metric/" + str(m.id))
pecan.response.status = 201
return m
MetricListSchema = voluptuous.Schema({
"user_id": six.text_type,
"project_id": six.text_type,
"creator": six.text_type,
"name": six.text_type,
"id": six.text_type,
"unit": six.text_type,
"archive_policy_name": six.text_type,
"status": voluptuous.Any("active", "delete"),
}, extra=voluptuous.REMOVE_EXTRA)
@classmethod
@pecan.expose('json')
def get_all(cls, **kwargs):
filtering = cls.MetricListSchema(kwargs)
# Compat with old user/project API
provided_user_id = filtering.pop('user_id', None)
provided_project_id = filtering.pop('project_id', None)
if provided_user_id is None and provided_project_id is None:
provided_creator = filtering.pop('creator', None)
else:
provided_creator = (
(provided_user_id or "")
+ ":"
+ (provided_project_id or "")
)
pagination_opts = get_pagination_options(kwargs,
METRIC_DEFAULT_PAGINATION)
attr_filters = []
if provided_creator is not None:
attr_filters.append({"=": {"creator": provided_creator}})
for k, v in six.iteritems(filtering):
attr_filters.append({"=": {k: v}})
policy_filter = pecan.request.auth_helper.get_metric_policy_filter(
pecan.request, "list metric")
resource_policy_filter = (
pecan.request.auth_helper.get_resource_policy_filter(
pecan.request, "list metric", resource_type=None,
prefix="resource")
)
try:
metrics = pecan.request.indexer.list_metrics(
attribute_filter={"and": attr_filters},
policy_filter=policy_filter,
resource_policy_filter=resource_policy_filter,
**pagination_opts)
if metrics and len(metrics) >= pagination_opts['limit']:
set_resp_link_hdr(str(metrics[-1].id), kwargs, pagination_opts)
return metrics
except indexer.InvalidPagination as e:
abort(400, six.text_type(e))
_MetricsSchema = voluptuous.Schema({
six.text_type: voluptuous.Any(utils.UUID,
MetricsController.MetricSchema),
})
def MetricsSchema(data):
# NOTE(jd) Before doing any kind of validation, copy the metric name
# into the metric definition. This is required so we have the name
# available when doing the metric validation with its own MetricSchema,
# and so we can do things such as applying archive policy rules.
if isinstance(data, dict):
for metric_name, metric_def in six.iteritems(data):
if isinstance(metric_def, dict):
metric_def['name'] = metric_name
return _MetricsSchema(data)
class NamedMetricController(rest.RestController):
def __init__(self, resource_id, resource_type):
self.resource_id = resource_id
self.resource_type = resource_type
@pecan.expose()
def _lookup(self, name, *remainder):
m = pecan.request.indexer.list_metrics(
details=True,
attribute_filter={"and": [
{"=": {"name": name}},
{"=": {"resource_id": self.resource_id}},
]})
if m:
return MetricController(m[0]), remainder
resource = pecan.request.indexer.get_resource(self.resource_type,
self.resource_id)
if resource:
abort(404, six.text_type(indexer.NoSuchMetric(name)))
else:
abort(404, six.text_type(indexer.NoSuchResource(self.resource_id)))
@pecan.expose('json')
def post(self):
resource = pecan.request.indexer.get_resource(
self.resource_type, self.resource_id)
if not resource:
abort(404, six.text_type(indexer.NoSuchResource(self.resource_id)))
enforce("update resource", resource)
metrics = deserialize_and_validate(MetricsSchema)
try:
r = pecan.request.indexer.update_resource(
self.resource_type,
self.resource_id,
metrics=metrics,
append_metrics=True,
create_revision=False)
except (indexer.NoSuchMetric,
indexer.NoSuchArchivePolicy,
ValueError) as e:
abort(400, six.text_type(e))
except indexer.NamedMetricAlreadyExists as e:
abort(409, six.text_type(e))
except indexer.NoSuchResource as e:
abort(404, six.text_type(e))
return r.metrics
@pecan.expose('json')
def get_all(self):
resource = pecan.request.indexer.get_resource(
self.resource_type, self.resource_id)
if not resource:
abort(404, six.text_type(indexer.NoSuchResource(self.resource_id)))
enforce("get resource", resource)
return pecan.request.indexer.list_metrics(
attribute_filter={"=": {"resource_id": self.resource_id}})
class ResourceHistoryController(rest.RestController):
def __init__(self, resource_id, resource_type):
self.resource_id = resource_id
self.resource_type = resource_type
@pecan.expose('json')
def get(self, **kwargs):
details = get_bool_param('details', kwargs)
pagination_opts = get_pagination_options(
kwargs, RESOURCE_DEFAULT_PAGINATION)
resource = pecan.request.indexer.get_resource(
self.resource_type, self.resource_id)
if not resource:
abort(404, six.text_type(indexer.NoSuchResource(self.resource_id)))
enforce("get resource", resource)
try:
resources = pecan.request.indexer.list_resources(
self.resource_type,
attribute_filter={"=": {"id": self.resource_id}},
details=details,
history=True,
**pagination_opts
)
if resources and len(resources) >= pagination_opts['limit']:
marker = "%s@%s" % (resources[-1].id, resources[-1].revision)
set_resp_link_hdr(marker, kwargs, pagination_opts)
return resources
except indexer.IndexerException as e:
abort(400, six.text_type(e))
def etag_precondition_check(obj):
etag, lastmodified = obj.etag, obj.lastmodified
# NOTE(sileht): Checks and order come from rfc7232
# in webob, the '*' and the absent of the header is handled by
# if_match.__contains__() and if_none_match.__contains__()
# and are identique...
if etag not in pecan.request.if_match:
abort(412)
elif (not pecan.request.environ.get("HTTP_IF_MATCH")
and pecan.request.if_unmodified_since
and pecan.request.if_unmodified_since < lastmodified):
abort(412)
if etag in pecan.request.if_none_match:
if pecan.request.method in ['GET', 'HEAD']:
abort(304)
else:
abort(412)
elif (not pecan.request.environ.get("HTTP_IF_NONE_MATCH")
and pecan.request.if_modified_since
and (pecan.request.if_modified_since >=
lastmodified)
and pecan.request.method in ['GET', 'HEAD']):
abort(304)
def etag_set_headers(obj):
pecan.response.etag = obj.etag
pecan.response.last_modified = obj.lastmodified
def AttributesPath(value):
if value.startswith("/attributes"):
return value
raise ValueError("Only attributes can be modified")
ResourceTypeJsonPatchSchema = voluptuous.Schema([{
"op": voluptuous.Any("add", "remove"),
"path": AttributesPath,
voluptuous.Optional("value"): dict,
}])
class ResourceTypeController(rest.RestController):
def __init__(self, name):
self._name = name
@pecan.expose('json')
def get(self):
try:
rt = pecan.request.indexer.get_resource_type(self._name)
except indexer.NoSuchResourceType as e:
abort(404, six.text_type(e))
enforce("get resource type", rt)
return rt
@pecan.expose('json')
def patch(self):
# NOTE(sileht): should we check for "application/json-patch+json"
# Content-Type ?
try:
rt = pecan.request.indexer.get_resource_type(self._name)
except indexer.NoSuchResourceType as e:
abort(404, six.text_type(e))
enforce("update resource type", rt)
# Ensure this is a valid jsonpatch dict
patch = deserialize_and_validate(
ResourceTypeJsonPatchSchema,
expected_content_types=["application/json-patch+json"])
# Add new attributes to the resource type
rt_json_current = rt.jsonify()
try:
rt_json_next = jsonpatch.apply_patch(rt_json_current, patch)
except jsonpatch.JsonPatchException as e:
abort(400, six.text_type(e))
del rt_json_next['state']
# Validate that the whole new resource_type is valid
schema = pecan.request.indexer.get_resource_type_schema()
try:
rt_json_next = voluptuous.Schema(schema.for_update, required=True)(
rt_json_next)
except voluptuous.Error as e:
abort(400, "Invalid input: %s" % e)
# Get only newly formatted and deleted attributes
add_attrs = {k: v for k, v in rt_json_next["attributes"].items()
if k not in rt_json_current["attributes"]}
del_attrs = [k for k in rt_json_current["attributes"]
if k not in rt_json_next["attributes"]]
if not add_attrs and not del_attrs:
# NOTE(sileht): just returns the resource, the asked changes
# just do nothing
return rt
try:
add_attrs = schema.attributes_from_dict(add_attrs)
except resource_type.InvalidResourceAttribute as e:
abort(400, "Invalid input: %s" % e)
try:
return pecan.request.indexer.update_resource_type(
self._name, add_attributes=add_attrs,
del_attributes=del_attrs)
except indexer.NoSuchResourceType as e:
abort(400, six.text_type(e))
@pecan.expose()
def delete(self):
try:
pecan.request.indexer.get_resource_type(self._name)
except indexer.NoSuchResourceType as e:
abort(404, six.text_type(e))
enforce("delete resource type", resource_type)
try:
pecan.request.indexer.delete_resource_type(self._name)
except (indexer.NoSuchResourceType,
indexer.ResourceTypeInUse) as e:
abort(400, six.text_type(e))
class ResourceTypesController(rest.RestController):
@pecan.expose()
def _lookup(self, name, *remainder):
return ResourceTypeController(name), remainder
@pecan.expose('json')
def post(self):
schema = pecan.request.indexer.get_resource_type_schema()
body = deserialize_and_validate(schema)
body["state"] = "creating"
try:
rt = schema.resource_type_from_dict(**body)
except resource_type.InvalidResourceAttribute as e:
abort(400, "Invalid input: %s" % e)
enforce("create resource type", body)
try:
rt = pecan.request.indexer.create_resource_type(rt)
except indexer.ResourceTypeAlreadyExists as e:
abort(409, six.text_type(e))
set_resp_location_hdr("/resource_type/" + rt.name)
pecan.response.status = 201
return rt
@pecan.expose('json')
def get_all(self, **kwargs):
enforce("list resource type", {})
try:
return pecan.request.indexer.list_resource_types()
except indexer.IndexerException as e:
abort(400, six.text_type(e))
def ResourceSchema(schema):
base_schema = {
voluptuous.Optional('started_at'): utils.to_datetime,
voluptuous.Optional('ended_at'): utils.to_datetime,
voluptuous.Optional('user_id'): voluptuous.Any(None, six.text_type),
voluptuous.Optional('project_id'): voluptuous.Any(None, six.text_type),
voluptuous.Optional('metrics'): MetricsSchema,
}
base_schema.update(schema)
return base_schema
class ResourceController(rest.RestController):
def __init__(self, resource_type, id):
self._resource_type = resource_type
creator = pecan.request.auth_helper.get_current_user(
pecan.request)
try:
self.id = utils.ResourceUUID(id, creator)
except ValueError:
abort(404, six.text_type(indexer.NoSuchResource(id)))
self.metric = NamedMetricController(str(self.id), self._resource_type)
self.history = ResourceHistoryController(str(self.id),
self._resource_type)
@pecan.expose('json')
def get(self):
resource = pecan.request.indexer.get_resource(
self._resource_type, self.id, with_metrics=True)