forked from cloud-custodian/cel-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathc7nlib.py
More file actions
1663 lines (1313 loc) · 52.7 KB
/
c7nlib.py
File metadata and controls
1663 lines (1313 loc) · 52.7 KB
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-Copyright: Copyright (c) Capital One Services, LLC
# SPDX-License-Identifier: Apache-2.0
# Copyright 2020 Capital One Services, LLC
#
# 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.
"""
Functions for C7N features when evaluating CEL expressions.
These functions provide a mapping between C7N features and CEL.
These functions are exposed by the global ``FUNCTIONS`` dictionary that is provided
to the CEL evaluation run-time to provide necessary C7N features.
The functions rely on implementation details in the ``CELFilter`` class.
The API
=======
A C7N implementation can use CEL expressions and the :py:mod:`c7nlib` module as follows::
class CELFilter(c7n.filters.core.Filter):
decls = {
"resource": celpy.celtypes.MapType,
"now": celpy.celtypes.TimestampType,
"event": celpy.celtypes.MapType,
}
decls.update(celpy.c7nlib.DECLARATIONS)
def __init__(self, expr: str) -> None:
self.expr = expr
def validate(self) -> None:
cel_env = celpy.Environment(
annotations=self.decls,
runner_class=c7nlib.C7N_Interpreted_Runner)
cel_ast = cel_env.compile(self.expr)
self.pgm = cel_env.program(cel_ast, functions=celpy.c7nlib.FUNCTIONS)
def process(self,
resources: Iterable[celpy.celtypes.MapType]) -> Iterator[celpy.celtypes.MapType]:
now = datetime.datetime.utcnow()
for resource in resources:
with C7NContext(filter=the_filter):
cel_activation = {
"resource": celpy.json_to_cel(resource),
"now": celpy.celtypes.TimestampType(now),
}
if self.pgm.evaluate(cel_activation):
yield resource
The :py:mod:`celpy.c7nlib` library of functions is bound into the CEL :py:class:`celpy.__init__.Runner` object that's built from the AST.
Several variables will be required in the :py:class:`celpy.evaluation.Activation` for use by most CEL expressions
that implement C7N filters:
:resource:
A JSON document describing a cloud resource.
:now:
The current timestamp.
:event:
May be needed; it should be a JSON document describing an AWS CloudWatch event.
The type: value Features
========================
The core value features of C7N require a number of CEL extensions.
- :func:`glob(string, pattern)` uses Python fnmatch rules. This implements ``op: glob``.
- :func:`difference(list, list)` creates intermediate sets and computes the difference
as a boolean value. Any difference is True. This implements ``op: difference``.
- :func:`intersect(list, list)` creats intermediate sets and computes the intersection
as a boolean value. Any interection is True. This implements ``op: intersect``.
- :func:`normalize(string)` supports normalized comparison between strings.
In this case, it means lower cased and trimmed. This implements ``value_type: normalize``.
- :func:`net.cidr_contains` checks to see if a given CIDR block contains a specific
address. See https://www.openpolicyagent.org/docs/latest/policy-reference/#net.
- :func:`net.cidr_size` extracts the prefix length of a parsed CIDR block.
- :func:`version` uses ``disutils.version.LooseVersion`` to compare version strings.
- :func:`resource_count` function. This is TBD.
The type: value_from features
==============================
This relies on ``value_from()`` and ``jmes_path_map()`` functions
In context, it looks like this::
value_from("s3://c7n-resources/exemptions.json", "json")
.jmes_path_map('exemptions.ec2.rehydration.["IamInstanceProfile.Arn"][].*[].*[]')
.contains(resource["IamInstanceProfile"]["Arn"])
The ``value_from()`` function reads values from a given URI.
- A full URI for an S3 bucket.
- A full URI for a server that supports HTTPS GET requests.
If a format is given, this is used, otherwise it's based on the
suffix of the path.
The ``jmes_path_map()`` function compiles and applies a JMESPath
expression against each item in the collection to create a
new collection. To an extent, this repeats functionality
from the ``map()`` macro.
Additional Functions
====================
A number of C7N subclasses of ``Filter`` provide additional features. There are
at least 70-odd functions that are expressed or implied by these filters.
Because the CEL expressions are always part of a ``CELFilter``, all of these
additional C7N features need to be transformed into "mixins" that are implemented
in two places. The function is part of the legacy subclass of ``Filter``,
and the function is also part of ``CELFilter``.
::
class InstanceImageMixin:
# from :py:class:`InstanceImageBase` refactoring
def get_instance_image(self):
pass
class RelatedResourceMixin:
# from :py:class:`RelatedResourceFilter` mixin
def get_related_ids(self):
pass
def get_related(self):
pass
class CredentialReportMixin:
# from :py:class:`c7n.resources.iam.CredentialReport` filter.
def get_credential_report(self):
pass
class ResourceKmsKeyAliasMixin:
# from :py:class:`c7n.resources.kms.ResourceKmsKeyAlias`
def get_matching_aliases(self, resource):
pass
class CrossAccountAccessMixin:
# from :py:class:`c7n.filters.iamaccessfilter.CrossAccountAccessFilter`
def get_accounts(self, resource):
pass
def get_vpcs(self, resource):
pass
def get_vpces(self, resource):
pass
def get_orgids(self, resource):
pass
# from :py:class:`c7n.resources.secretsmanager.CrossAccountAccessFilter`
def get_resource_policy(self, resource):
pass
class SNSCrossAccountMixin:
# from :py:class:`c7n.resources.sns.SNSCrossAccount`
def get_endpoints(self, resource):
pass
def get_protocols(self, resource):
pass
class ImagesUnusedMixin:
# from :py:class:`c7n.resources.ami.ImageUnusedFilter`
def _pull_ec2_images(self, resource):
pass
def _pull_asg_images(self, resource):
pass
class SnapshotUnusedMixin:
# from :py:class:`c7n.resources.ebs.SnapshotUnusedFilter`
def _pull_asg_snapshots(self, resource):
pass
def _pull_ami_snapshots(self, resource):
pass
class IamRoleUsageMixin:
# from :py:class:`c7n.resources.iam.IamRoleUsage`
def service_role_usage(self, resource):
pass
def instance_profile_usage(self, resource):
pass
class SGUsageMixin:
# from :py:class:`c7n.resources.vpc.SGUsage`
def scan_groups(self, resource):
pass
class IsShieldProtectedMixin:
# from :py:mod:`c7n.resources.shield`
def get_type_protections(self, resource):
pass
class ShieldEnabledMixin:
# from :py:class:`c7n.resources.account.ShieldEnabled`
def account_shield_subscriptions(self, resource):
pass
class CELFilter(
InstanceImageMixin, RelatedResourceMixin, CredentialReportMixin,
ResourceKmsKeyAliasMixin, CrossAccountAccessMixin, SNSCrossAccountMixin,
ImagesUnusedMixin, SnapshotUnusedMixin, IamRoleUsageMixin, SGUsageMixin,
Filter,
):
'''Container for functions used by c7nlib to expose data to CEL'''
def __init__(self, data, manager) -> None:
super().__init__(data, manager)
assert data["type"].lower() == "cel"
self.expr = data["expr"]
self.parser = c7n.filters.offhours.ScheduleParser()
def validate(self):
pass # See above example
def process(self, resources):
pass # See above example
This is not the complete list. See the ``tests/test_c7nlib.py`` for the ``celfilter_instance``
fixture which contains **all** of the functions required.
C7N Context Object
==================
A number of the functions require access to C7N features that are not simply part
of the resource being filtered. There are two alternative ways to handle this dependency:
- A global C7N context object that has the current ``CELFilter`` providing
access to C7N internals.
- A ``C7N`` argument to the functions that need C7N access.
This would be provided in the activation context for CEL.
To keep the library functions looking simple, the module global ``C7N`` is used.
This avoids introducing a non-CEL parameter to the :py:mod:`celpy.c7nlib` functions.
The ``C7N`` context object contains the following attributes:
:filter:
The original C7N ``Filter`` object. This provides access to the
resource manager. It can be used to manage supplemental
queries using C7N caches and other resource management.
This is set by the :py:class:`C7NContext` prior to CEL evaluation.
Name Resolution
===============
Note that names are **not** resolved via a lookup in the program object,
an instance of the :py:class:`celpy.Runner` class. To keep these functions
simple, the runner is not part of the run-time, and name resolution
will appear to be "hard-wrired" among these functions.
This is rarely an issue, since most of these functions are independent.
The :func:`value_from` function relies on :func:`text_from` and :func:`parse_text`.
Changing either of these functions with an override won't modify the behavior
of :func:`value_from`.
"""
import csv
import fnmatch
import io
import ipaddress
import json
import logging
import os.path
import sys
import urllib.request
import zlib
from contextlib import closing
from packaging.version import Version
from types import TracebackType
from typing import Any, Callable, Dict, Iterator, List, Optional, Type, Union, cast
from pendulum import parse as parse_date
import jmespath # type: ignore [import-untyped]
from celpy import InterpretedRunner, celtypes
from celpy.adapter import json_to_cel
from celpy.evaluation import Annotation, Context, Evaluator
logger = logging.getLogger(f"celpy.{__name__}")
class C7NContext:
"""
Saves current C7N filter for use by functions in this module.
This is essential for making C7N filter available to *some* of these functions.
::
with C7NContext(filter):
cel_prgm.evaluate(cel_activation)
"""
def __init__(self, filter: Any) -> None:
self.filter = filter
def __repr__(self) -> str: # pragma: no cover
return f"{self.__class__.__name__}(filter={self.filter!r})"
def __enter__(self) -> None:
global C7N
C7N = self
def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc_value: Optional[BaseException],
traceback: Optional[TracebackType],
) -> None:
global C7N
C7N = cast("C7NContext", None)
return
# An object used for access to the C7N filter.
# A module global makes the interface functions much simpler.
# They can rely on `C7N.filter` providing the current `CELFilter` instance.
C7N = cast("C7NContext", None)
def key(source: celtypes.ListType, target: celtypes.StringType) -> celtypes.Value:
"""
The C7N shorthand ``tag:Name`` doesn't translate well to CEL. It extracts a single value
from a sequence of objects with a ``{"Key": x, "Value": y}`` structure; specifically,
the value for ``y`` when ``x == "Name"``.
This function locate a particular "Key": target within a list of {"Key": x, "Value", y} items,
returning the y value if one is found, null otherwise.
In effect, the ``key()`` function::
resource["Tags"].key("Name")["Value"]
is somewhat like::
resource["Tags"].filter(x, x["Key"] == "Name")[0]
But the ``key()`` function doesn't raise an exception if the key is not found,
instead it returns None.
We might want to generalize this into a ``first()`` reduction macro.
``resource["Tags"].first(x, x["Key"] == "Name" ? x["Value"] : null, null)``
This macro returns the first non-null value or the default (which can be ``null``.)
"""
key = celtypes.StringType("Key")
value = celtypes.StringType("Value")
matches: Iterator[celtypes.Value] = (
item
for item in source
if cast(celtypes.StringType, cast(celtypes.MapType, item).get(key)) == target
)
try:
return cast(celtypes.MapType, next(matches)).get(value)
except StopIteration:
return None
def glob(text: celtypes.StringType, pattern: celtypes.StringType) -> celtypes.BoolType:
"""Compare a string with a pattern.
While ``"*.py".glob(some_string)`` seems logical because the pattern the more persistent object,
this seems to cause confusion.
We use ``some_string.glob("*.py")`` to express a regex-like rule. This parallels the CEL
`.matches()` method.
We also support ``glob(some_string, "*.py")``.
"""
return celtypes.BoolType(fnmatch.fnmatch(text, pattern))
def difference(left: celtypes.ListType, right: celtypes.ListType) -> celtypes.BoolType:
"""
Compute the difference between two lists. This is ordered set difference: left - right.
It's true if the result is non-empty: there is an item in the left, not present in the right.
It's false if the result is empty: the lists are the same.
"""
return celtypes.BoolType(bool(set(left) - set(right)))
def intersect(left: celtypes.ListType, right: celtypes.ListType) -> celtypes.BoolType:
"""
Compute the intersection between two lists.
It's true if the result is non-empty: there is an item in both lists.
It's false if the result is empty: there is no common item between the lists.
"""
return celtypes.BoolType(bool(set(left) & set(right)))
def normalize(string: celtypes.StringType) -> celtypes.StringType:
"""
Normalize a string.
"""
return celtypes.StringType(string.lower().strip())
def unique_size(collection: celtypes.ListType) -> celtypes.IntType:
"""
Unique size of a list
"""
return celtypes.IntType(len(set(collection)))
class IPv4Network(ipaddress.IPv4Network):
# Override for net 2 net containment comparison
def __contains__(self, other): # type: ignore[no-untyped-def]
if other is None:
return False
if isinstance(other, ipaddress._BaseNetwork):
return self.supernet_of(other) # type: ignore[no-untyped-call]
return super(IPv4Network, self).__contains__(other)
contains = __contains__
if sys.version_info.major == 3 and sys.version_info.minor <= 6: # pragma: no cover
@staticmethod
def _is_subnet_of(a, b): # type: ignore[no-untyped-def]
try:
# Always false if one is v4 and the other is v6.
if a._version != b._version:
raise TypeError(f"{a} and {b} are not of the same version")
return (
b.network_address <= a.network_address
and b.broadcast_address >= a.broadcast_address
)
except AttributeError:
raise TypeError(
f"Unable to test subnet containment between {a} and {b}"
)
def supernet_of(self, other): # type: ignore[no-untyped-def]
"""Return True if this network is a supernet of other."""
return self._is_subnet_of(other, self) # type: ignore[no-untyped-call]
CIDR = Union[None, IPv4Network, ipaddress.IPv4Address]
CIDR_Class = Union[Type[IPv4Network], Callable[..., ipaddress.IPv4Address]]
def parse_cidr(value: str) -> CIDR:
"""
Process cidr ranges.
This is a union of types outside CEL.
It appears to be Union[None, IPv4Network, ipaddress.IPv4Address]
"""
klass: CIDR_Class = IPv4Network
if "/" not in value:
klass = ipaddress.ip_address # type: ignore[assignment]
v: CIDR
try:
v = klass(value)
except (ipaddress.AddressValueError, ValueError):
v = None
return v
def size_parse_cidr(
value: celtypes.StringType,
) -> Optional[celtypes.IntType]:
"""CIDR prefixlen value"""
cidr = parse_cidr(value)
if cidr and isinstance(cidr, IPv4Network):
return celtypes.IntType(cidr.prefixlen)
else:
return None
class ComparableVersion(Version):
"""
The old LooseVersion could fail on comparing present strings, used
in the value as shorthand for certain options.
The new Version doesn't fail as easily.
"""
def __eq__(self, other: object) -> bool:
try:
return super(ComparableVersion, self).__eq__(other)
except TypeError: # pragma: no cover
return False
def version(
value: celtypes.StringType,
) -> celtypes.Value: # actually, a ComparableVersion
return cast(celtypes.Value, ComparableVersion(value))
def present(
value: celtypes.StringType,
) -> celtypes.Value:
return cast(celtypes.Value, bool(value))
def absent(
value: celtypes.StringType,
) -> celtypes.Value:
return cast(celtypes.Value, not bool(value))
def text_from(
url: celtypes.StringType,
) -> celtypes.Value:
"""
Read raw text from a URL. This can be expanded to accept S3 or other URL's.
"""
req = urllib.request.Request(url, headers={"Accept-Encoding": "gzip"})
raw_data: str
with closing(urllib.request.urlopen(req)) as response:
if response.info().get("Content-Encoding") == "gzip":
raw_data = zlib.decompress(response.read(), zlib.MAX_WBITS | 32).decode(
"utf8"
)
else:
raw_data = response.read().decode("utf-8")
return celtypes.StringType(raw_data)
def parse_text(
source_text: celtypes.StringType, format: celtypes.StringType
) -> celtypes.Value:
"""
Parse raw text using a given format.
"""
if format == "json":
return json_to_cel(json.loads(source_text))
elif format == "txt":
return celtypes.ListType(
[celtypes.StringType(s.rstrip()) for s in source_text.splitlines()]
)
elif format in ("ldjson", "ndjson", "jsonl"):
return celtypes.ListType(
[json_to_cel(json.loads(s)) for s in source_text.splitlines()]
)
elif format == "csv":
return celtypes.ListType(
[json_to_cel(row) for row in csv.reader(io.StringIO(source_text))]
)
elif format == "csv2dict":
return celtypes.ListType(
[json_to_cel(row) for row in csv.DictReader(io.StringIO(source_text))]
)
else:
raise ValueError(f"Unsupported format: {format!r}") # pragma: no cover
def value_from(
url: celtypes.StringType,
format: Optional[celtypes.StringType] = None,
) -> celtypes.Value:
"""
Read values from a URL.
First, do :func:`text_from` to read the source.
Then, do :func:`parse_text` to parse the source, if needed.
This makes the format optional, and deduces it from the URL's path information.
C7N will generally replace this with a function
that leverages a more sophisticated :class:`c7n.resolver.ValuesFrom`.
"""
supported_formats = ("json", "ndjson", "ldjson", "jsonl", "txt", "csv", "csv2dict")
# 1. get format either from arg or URL
if not format:
_, suffix = os.path.splitext(url)
format = celtypes.StringType(suffix[1:])
if format not in supported_formats:
raise ValueError(f"Unsupported format: {format!r}")
# 2. read raw data
# Note this is directly bound to text_from() and does not go though the environment
# or other CEL indirection.
raw_data = cast(celtypes.StringType, text_from(url))
# 3. parse physical format (json, ldjson, ndjson, jsonl, txt, csv, csv2dict)
return parse_text(raw_data, format)
def jmes_path(
source_data: celtypes.Value, path_source: celtypes.StringType
) -> celtypes.Value:
"""
Apply JMESPath to an object read from from a URL.
"""
expression = jmespath.compile(path_source)
return json_to_cel(expression.search(source_data))
def jmes_path_map(
source_data: celtypes.ListType, path_source: celtypes.StringType
) -> celtypes.ListType:
"""
Apply JMESPath to a each object read from from a URL.
This is for ndjson, nljson and jsonl files.
"""
expression = jmespath.compile(path_source)
return celtypes.ListType(
[json_to_cel(expression.search(row)) for row in source_data]
)
def marked_key(
source: celtypes.ListType, target: celtypes.StringType
) -> celtypes.Value:
"""
Examines a list of {"Key": text, "Value": text} mappings
looking for the given Key value.
Parses a ``message:action@action_date`` value into a mapping
{"message": message, "action": action, "action_date": action_date}
If no Key or no Value or the Value isn't the right structure,
the result is a null.
"""
value = key(source, target)
if value is None:
return None
try:
msg, tgt = cast(celtypes.StringType, value).rsplit(":", 1)
action, action_date_str = tgt.strip().split("@", 1)
except ValueError:
return None
return celtypes.MapType(
{
celtypes.StringType("message"): celtypes.StringType(msg),
celtypes.StringType("action"): celtypes.StringType(action),
celtypes.StringType("action_date"): celtypes.TimestampType(action_date_str),
}
)
def image(resource: celtypes.MapType) -> celtypes.Value:
"""
Reach into C7N to get the image details for this EC2 or ASG resource.
Minimally, the creation date is transformed into a CEL timestamp.
We may want to slightly generalize this to json_to_cell() the entire Image object.
The following may be usable, but it seems too complex:
::
C7N.filter.prefetch_instance_images(C7N.policy.resources)
image = C7N.filter.get_instance_image(resource["ImageId"])
return json_to_cel(image)
.. todo:: Refactor C7N
Provide the :py:class:`InstanceImageBase` mixin in a :py:class:`CELFilter` class.
We want to have the image details in the new :py:class:`CELFilter` instance.
"""
# Assuming the :py:class:`CELFilter` class has this method extracted from the legacy filter.
# Requies the policy already did this: C7N.filter.prefetch_instance_images([resource]) to
# populate cache.
image = C7N.filter.get_instance_image(resource)
if image:
creation_date = image["CreationDate"]
image_name = image["Name"]
else:
creation_date = "2000-01-01T01:01:01.000Z"
image_name = ""
return json_to_cel({"CreationDate": parse_date(creation_date), "Name": image_name})
def get_raw_metrics(request: celtypes.MapType) -> celtypes.Value:
"""
Reach into C7N and make a statistics request using the current C7N filter object.
The ``request`` parameter is the request object that is passed through to AWS via
the current C7N filter's manager. The request is a Mapping with the following keys and values:
::
get_raw_metrics({
"Namespace": "AWS/EC2",
"MetricName": "CPUUtilization",
"Dimensions": {"Name": "InstanceId", "Value": resource.InstanceId},
"Statistics": ["Average"],
"StartTime": now - duration("4d"),
"EndTime": now,
"Period": duration("86400s")
})
The request is passed through to AWS more-or-less directly. The result is a CEL
list of values for then requested statistic. A ``.map()`` macro
can be used to compute additional details. An ``.exists()`` macro can filter the
data to look for actionable values.
We would prefer to refactor C7N and implement this with code something like this:
::
C7N.filter.prepare_query(C7N.policy.resources)
data = C7N.filter.get_resource_statistics(client, resource)
return json_to_cel(data)
.. todo:: Refactor C7N
Provide a :py:class:`MetricsAccess` mixin in a :py:class:`CELFilter` class.
We want to have the metrics processing in the new :py:class:`CELFilter` instance.
"""
client = C7N.filter.manager.session_factory().client("cloudwatch")
data = client.get_metric_statistics(
Namespace=request["Namespace"],
MetricName=request["MetricName"],
Statistics=request["Statistics"],
StartTime=request["StartTime"],
EndTime=request["EndTime"],
Period=request["Period"],
Dimensions=request["Dimensions"],
)["Datapoints"]
return json_to_cel(data)
def get_metrics(
resource: celtypes.MapType, request: celtypes.MapType
) -> celtypes.Value:
"""
Reach into C7N and make a statistics request using the current C7N filter.
This builds a request object that is passed through to AWS via the :func:`get_raw_metrics`
function.
The ``request`` parameter is a Mapping with the following keys and values:
::
resource.get_metrics({"MetricName": "CPUUtilization", "Statistic": "Average",
"StartTime": now - duration("4d"), "EndTime": now, "Period": duration("86400s")}
).exists(m, m < 30)
The namespace is derived from the ``C7N.policy``. The dimensions are derived from
the ``C7N.fiter.model``.
.. todo:: Refactor C7N
Provide a :py:class:`MetricsAccess` mixin in a :py:class:`CELFilter` class.
We want to have the metrics processing in the new :py:class:`CELFilter` instance.
"""
dimension = C7N.filter.manager.get_model().dimension
namespace = C7N.filter.manager.resource_type
# TODO: Varies by resource/policy type. Each policy's model may have different dimensions.
dimensions = [{"Name": dimension, "Value": resource.get(dimension)}]
raw_metrics = get_raw_metrics(
cast(
celtypes.MapType,
json_to_cel(
{
"Namespace": namespace,
"MetricName": request["MetricName"],
"Dimensions": dimensions,
"Statistics": [request["Statistic"]],
"StartTime": request["StartTime"],
"EndTime": request["EndTime"],
"Period": request["Period"],
}
),
)
)
return json_to_cel(
[
cast(Dict[str, celtypes.Value], item).get(request["Statistic"])
for item in cast(List[celtypes.Value], raw_metrics)
]
)
def get_raw_health_events(request: celtypes.MapType) -> celtypes.Value:
"""
Reach into C7N and make a health-events request using the current C7N filter.
The ``request`` parameter is the filter object that is passed through to AWS via
the current C7N filter's manager. The request is a List of AWS health events.
::
get_raw_health_events({
"services": ["ELASTICFILESYSTEM"],
"regions": ["us-east-1", "global"],
"eventStatusCodes": ['open', 'upcoming'],
})
"""
client = C7N.filter.manager.session_factory().client(
"health", region_name="us-east-1"
)
data = client.describe_events(filter=request)["events"]
return json_to_cel(data)
def get_health_events(
resource: celtypes.MapType, statuses: Optional[List[celtypes.Value]] = None
) -> celtypes.Value:
"""
Reach into C7N and make a health-event request using the current C7N filter.
This builds a request object that is passed through to AWS via the :func:`get_raw_health_events`
function.
.. todo:: Handle optional list of event types.
"""
if not statuses:
statuses = [celtypes.StringType("open"), celtypes.StringType("upcoming")]
phd_svc_name_map = {
"app-elb": "ELASTICLOADBALANCING",
"ebs": "EBS",
"efs": "ELASTICFILESYSTEM",
"elb": "ELASTICLOADBALANCING",
"emr": "ELASTICMAPREDUCE",
}
m = C7N.filter.manager
service = phd_svc_name_map.get(m.data["resource"], m.get_model().service.upper())
raw_events = get_raw_health_events(
cast(
celtypes.MapType,
json_to_cel(
{
"services": [service],
"regions": [m.config.region, "global"],
"eventStatusCodes": statuses,
}
),
)
)
return raw_events
def get_related_ids(
resource: celtypes.MapType,
) -> celtypes.Value:
"""
Reach into C7N and make a get_related_ids() request using the current C7N filter.
.. todo:: Refactor C7N
Provide the :py:class:`RelatedResourceFilter` mixin in a :py:class:`CELFilter` class.
We want to have the related id's details in the new :py:class:`CELFilter` instance.
"""
# Assuming the :py:class:`CELFilter` class has this method extracted from the legacy filter.
related_ids = C7N.filter.get_related_ids(resource)
return json_to_cel(related_ids)
def get_related_sgs(
resource: celtypes.MapType,
) -> celtypes.Value:
"""
Reach into C7N and make a get_related_sgs() request using the current C7N filter.
"""
security_groups = C7N.filter.get_related_sgs(resource)
return json_to_cel(security_groups)
def get_related_subnets(
resource: celtypes.MapType,
) -> celtypes.Value:
"""
Reach into C7N and make a get_related_subnets() request using the current C7N filter.
"""
subnets = C7N.filter.get_related_subnets(resource)
return json_to_cel(subnets)
def get_related_nat_gateways(
resource: celtypes.MapType,
) -> celtypes.Value:
"""
Reach into C7N and make a get_related_nat_gateways() request using the current C7N filter.
"""
nat_gateways = C7N.filter.get_related_nat_gateways(resource)
return json_to_cel(nat_gateways)
def get_related_igws(
resource: celtypes.MapType,
) -> celtypes.Value:
"""
Reach into C7N and make a get_related_igws() request using the current C7N filter.
"""
igws = C7N.filter.get_related_igws(resource)
return json_to_cel(igws)
def get_related_security_configs(
resource: celtypes.MapType,
) -> celtypes.Value:
"""
Reach into C7N and make a get_related_security_configs() request using the current C7N filter.
"""
security_configs = C7N.filter.get_related_security_configs(resource)
return json_to_cel(security_configs)
def get_related_vpc(
resource: celtypes.MapType,
) -> celtypes.Value:
"""
Reach into C7N and make a get_related_vpc() request using the current C7N filter.
"""
vpc = C7N.filter.get_related_vpc(resource)
return json_to_cel(vpc)
def get_related_kms_keys(
resource: celtypes.MapType,
) -> celtypes.Value:
"""
Reach into C7N and make a get_related_kms_keys() request using the current C7N filter.
"""
vpc = C7N.filter.get_related_kms_keys(resource)
return json_to_cel(vpc)
def security_group(
security_group_id: celtypes.MapType,
) -> celtypes.Value:
"""
Reach into C7N and make a get_related() request using the current C7N filter to get
the security group.
.. todo:: Refactor C7N
Provide the :py:class:`RelatedResourceFilter` mixin in a :py:class:`CELFilter` class.
We want to have the related id's details in the new :py:class:`CELFilter` instance.
See :py:class:`VpcSecurityGroupFilter` subclass of :py:class:`RelatedResourceFilter`.
"""
# Assuming the :py:class:`CELFilter` class has this method extracted from the legacy filter.
security_groups = C7N.filter.get_related([security_group_id])
return json_to_cel(security_groups)
def subnet(
subnet_id: celtypes.Value,
) -> celtypes.Value:
"""
Reach into C7N and make a get_related() request using the current C7N filter to get
the subnet.
.. todo:: Refactor C7N
Provide the :py:class:`RelatedResourceFilter` mixin in a :py:class:`CELFilter` class.
We want to have the related id's details in the new :py:class:`CELFilter` instance.
See :py:class:`VpcSubnetFilter` subclass of :py:class:`RelatedResourceFilter`.
"""
# Get related ID's first, then get items for the related ID's.
subnets = C7N.filter.get_related([subnet_id])
return json_to_cel(subnets)
def flow_logs(
resource: celtypes.MapType,
) -> celtypes.Value:
"""
Reach into C7N and locate the flow logs using the current C7N filter.
.. todo:: Refactor C7N
Provide a separate function to get the flow logs, separate from the
the filter processing.
.. todo:: Refactor :func:`c7nlib.flow_logs` -- it exposes too much implementation detail.
"""
# TODO: Refactor into a function in ``CELFilter``. Should not be here.
client = C7N.filter.manager.session_factory().client("ec2")
logs = client.describe_flow_logs().get("FlowLogs", ())
dimension = C7N.filter.manager.get_model().dimension