This repository has been archived by the owner on Jun 5, 2023. It is now read-only.
/
cai_gcp_client.py
1294 lines (1073 loc) · 44.8 KB
/
cai_gcp_client.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
# Copyright 2018 The Forseti Security Authors. All rights reserved.
#
# 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.
"""Cloud Asset and GCP API hybrid client fassade."""
# pylint: disable=too-many-lines
import threading
from google.cloud.forseti.common.util import logger
from google.cloud.forseti.services import db
from google.cloud.forseti.services.inventory.base import gcp
from google.cloud.forseti.services.inventory.base import iam_helpers
from google.cloud.forseti.services.inventory.storage import CaiDataAccess
from google.cloud.forseti.services.inventory.storage import ContentTypes
LOCAL_THREAD = threading.local()
LOGGER = logger.get_logger(__name__)
def _fixup_resource_keys(resource, key_map, only_fixup_lists=False):
"""Correct different attribute names between CAI and json representation.
Args:
resource (dict): The resource dictionary to scan for keys in the
key_map.
key_map (dict): A map of bad_key:good_key pairs, any instance of bad_key
in the resource dict is replaced with an instance of good_key.
only_fixup_lists (bool): If true, only keys that have values which are
lists will be fixed. This allows the case where there is the same
key used for both a scalar entry and a list entry, and only the
list entry should change to the different key.
Returns:
dict: A resource dict with all bad keys replaced with good keys.
"""
fixed_resource = {}
for key, value in resource.items():
if isinstance(value, dict):
# Recursively fix keys in sub dictionaries.
value = _fixup_resource_keys(value, key_map)
elif isinstance(value, list):
# Recursively fix keys in sub dictionaries in lists.
new_value = []
for item in value:
if isinstance(item, dict):
item = _fixup_resource_keys(item, key_map)
new_value.append(item)
value = new_value
# Only replace the old key with the new key if the value of the field
# is a list. This behavior can be overridden by setting the optional
# argument only_fixup_lists to False.
should_update_key = bool(
not only_fixup_lists or isinstance(value, list))
if key in key_map and should_update_key:
fixed_resource[key_map[key]] = value
else:
fixed_resource[key] = value
return fixed_resource
# pylint: disable=too-many-public-methods
class CaiApiClientImpl(gcp.ApiClientImpl):
"""The gcp api client Implementation"""
def __init__(self, config, engine, parallel, session):
"""Initialize.
Args:
config (dict): GCP API client configuration.
engine (object): Database engine to operate on.
parallel (bool): If true, use the parallel crawler implementation.
session (object): Database session.
"""
super(CaiApiClientImpl, self).__init__(config)
self.dao = CaiDataAccess()
self.engine = engine
self.parallel = parallel
self.cai_session = session
self._local = LOCAL_THREAD
@property
def session(self):
"""Return a thread local CAI read only session object.
Returns:
object: A thread local Session.
"""
if not self.parallel:
# SQLite doesn't support per thread sessions cleanly, so use global
# session.
return self.cai_session
if hasattr(self._local, 'cai_session'):
return self._local.cai_session
self._local.cai_session = db.create_readonly_session(engine=self.engine)
return self._local.cai_session
def fetch_bigquery_iam_policy(self, project_id, project_number, dataset_id):
"""Gets IAM policy of a bigquery dataset from Cloud Asset data.
Args:
project_id (str): id of the project to query.
project_number (str): number of the project to query.
dataset_id (str): id of the dataset to query.
Returns:
dict: Dataset IAM Policy.
"""
bigquery_name_fmt = '//bigquery.googleapis.com/projects/{}/datasets/{}'
# Try fetching with project id, if that returns nothing, fall back to
# project number.
resource = self.dao.fetch_cai_asset(
ContentTypes.iam_policy,
'google.cloud.bigquery.Dataset',
bigquery_name_fmt.format(project_id, dataset_id),
self.session)
if not resource:
resource = self.dao.fetch_cai_asset(
ContentTypes.iam_policy,
'google.cloud.bigquery.Dataset',
bigquery_name_fmt.format(project_number, dataset_id),
self.session)
if resource:
return resource
return {}
def fetch_bigquery_dataset_policy(self, project_id, project_number,
dataset_id):
"""Dataset policy Iterator for a dataset from Cloud Asset data.
Args:
project_id (str): id of the project to query.
project_number (str): number of the project to query.
dataset_id (str): id of the dataset to query.
Returns:
dict: Dataset Policy.
"""
resource = self.fetch_bigquery_iam_policy(
project_id, project_number, dataset_id)
if resource:
return iam_helpers.convert_iam_to_bigquery_policy(resource)
# Fall back to live API if the data isn't in the CAI cache.
return super(CaiApiClientImpl, self).fetch_bigquery_dataset_policy(
project_id, project_number, dataset_id)
def iter_bigquery_datasets(self, project_number):
"""Iterate Datasets from Cloud Asset data.
Args:
project_number (str): number of the project to query.
Yields:
dict: Generator of datasets.
"""
resources = list(self.dao.iter_cai_assets(
ContentTypes.resource,
'google.cloud.bigquery.Dataset',
'//cloudresourcemanager.googleapis.com/projects/{}'.format(
project_number),
self.session))
if resources and not all('location' in ds for ds in resources):
LOGGER.info('Datasets missing location key in CAI, '
'falling back to live API.')
resources = list(
super(CaiApiClientImpl,
self).iter_bigquery_datasets(project_number))
for dataset in resources:
yield dataset
def fetch_billing_account_iam_policy(self, account_id):
"""Gets IAM policy of a Billing Account from Cloud Asset data.
Args:
account_id (str): id of the billing account to get policy.
Returns:
dict: Billing Account IAM policy.
"""
resource = self.dao.fetch_cai_asset(
ContentTypes.iam_policy,
'google.cloud.billing.BillingAccount',
'//cloudbilling.googleapis.com/{}'.format(account_id),
self.session)
if resource:
return resource
# Fall back to live API if the data isn't in the CAI cache.
return super(CaiApiClientImpl, self).fetch_billing_account_iam_policy(
account_id)
def iter_billing_accounts(self):
"""Iterate Billing Accounts in an organization from Cloud Asset data.
Yields:
dict: Generator of billing accounts.
"""
resources = self.dao.iter_cai_assets(
ContentTypes.resource,
'google.cloud.billing.BillingAccount',
'', # Billing accounts have no parent resource.
self.session)
for account in resources:
yield account
def _iter_compute_resources(self, asset_type, project_number):
"""Iterate Compute resources from Cloud Asset data.
Args:
asset_type (str): The Compute asset type to iterate.
project_number (str): number of the project to query.
Returns:
generator: A generator of resources from Cloud Asset data.
"""
return self.dao.iter_cai_assets(
ContentTypes.resource,
'google.compute.{}'.format(asset_type),
'//cloudresourcemanager.googleapis.com/projects/{}'.format(
project_number),
self.session)
def iter_compute_autoscalers(self, project_number):
"""Iterate Autoscalers from Cloud Asset data.
Args:
project_number (str): number of the project to query.
Yields:
dict: Generator of autoscaler resources.
"""
resources = self._iter_compute_resources('Autoscaler', project_number)
for autoscaler in resources:
yield autoscaler
def iter_compute_backendbuckets(self, project_number):
"""Iterate Backend buckets from Cloud Asset data.
Args:
project_number (str): number of the project to query.
Yields:
dict: Generator of backend bucket resources.
"""
resources = self._iter_compute_resources('BackendBucket',
project_number)
for backendbucket in resources:
yield backendbucket
def iter_compute_backendservices(self, project_number):
"""Iterate Backend services from Cloud Asset data.
Args:
project_number (str): number of the project to query.
Yields:
dict: Generator of backend service.
"""
cai_to_gcp_key_map = {
'backend': 'backends',
'healthCheck': 'healthChecks',
}
resources = self._iter_compute_resources('BackendService',
project_number)
for backendservice in resources:
yield _fixup_resource_keys(backendservice, cai_to_gcp_key_map)
def iter_compute_disks(self, project_number):
"""Iterate Compute Engine disks from Cloud Asset data.
Args:
project_number (str): number of the project to query.
Yields:
dict: Generator of Compute Disk.
"""
cai_to_gcp_key_map = {
'license': 'licenses',
'guestOsFeature': 'guestOsFeatures',
'user': 'users',
'replicaZone': 'replicaZones',
'licenseCode': 'licenseCodes',
}
resources = self._iter_compute_resources('Disk', project_number)
for disk in resources:
yield _fixup_resource_keys(disk, cai_to_gcp_key_map)
def iter_compute_firewalls(self, project_number):
"""Iterate Compute Engine Firewalls from Cloud Asset data.
Args:
project_number (str): number of the project to query.
Yields:
dict: Generator of Compute Engine Firewall.
"""
cai_to_gcp_key_map = {
'ipProtocol': 'IPProtocol',
'port': 'ports',
'sourceRange': 'sourceRanges',
'sourceServiceAccount': 'sourceServiceAccounts',
'sourceTag': 'sourceTags',
'targetRange': 'targetRanges',
'targetServiceAccount': 'targetServiceAccounts',
'targetTag': 'targetTags',
}
resources = self._iter_compute_resources('Firewall', project_number)
for rule in resources:
yield _fixup_resource_keys(rule, cai_to_gcp_key_map)
def iter_compute_forwardingrules(self, project_number):
"""Iterate Forwarding Rules from Cloud Asset data.
Args:
project_number (str): number of the project to query.
Yields:
dict: Generator of forwarding rule resources.
"""
cai_to_gcp_key_map = {
'ipAddress': 'IPAddress',
'ipProtocol': 'IPProtocol',
}
resources = self._iter_compute_resources('ForwardingRule',
project_number)
for forwarding_rule in resources:
yield _fixup_resource_keys(forwarding_rule, cai_to_gcp_key_map)
def iter_compute_healthchecks(self, project_number):
"""Iterate Health checks from Cloud Asset data.
Args:
project_number (str): number of the project to query.
Yields:
dict: Generator of health check resources.
"""
resources = self._iter_compute_resources('HealthCheck', project_number)
for healthcheck in resources:
yield healthcheck
def iter_compute_httphealthchecks(self, project_number):
"""Iterate HTTP Health checks from Cloud Asset data.
Args:
project_number (str): number of the project to query.
Yields:
dict: Generator of HTTP health check resources.
"""
resources = self._iter_compute_resources('HttpHealthCheck',
project_number)
for httphealthcheck in resources:
yield httphealthcheck
def iter_compute_httpshealthchecks(self, project_number):
"""Iterate HTTPS Health checks from Cloud Asset data.
Args:
project_number (str): number of the project to query.
Yields:
dict: Generator of HTTPS health check resources.
"""
resources = self._iter_compute_resources('HttpsHealthCheck',
project_number)
for httpshealthcheck in resources:
yield httpshealthcheck
def iter_compute_ig_managers(self, project_number):
"""Iterate Instance Group Manager from Cloud Asset data.
Args:
project_number (str): number of the project to query.
Yields:
dict: Generator of instance group manager resources.
"""
cai_to_gcp_key_map = {
'namedPort': 'namedPorts',
'targetPool': 'targetPools',
}
resources = self._iter_compute_resources('InstanceGroupManager',
project_number)
for igmanager in resources:
yield _fixup_resource_keys(igmanager, cai_to_gcp_key_map)
def iter_compute_images(self, project_number):
"""Iterate Images from Cloud Asset data.
Args:
project_number (str): number of the project to query.
Yields:
dict: Generator of image resources.
"""
cai_to_gcp_key_map = {
'guestOsFeature': 'guestOsFeatures',
'license': 'licenses',
'licenseCode': 'licenseCodes',
}
resources = self._iter_compute_resources('Image', project_number)
for image in resources:
yield _fixup_resource_keys(image, cai_to_gcp_key_map)
def iter_compute_instancegroups(self, project_number):
"""Iterate Compute Engine groups from Cloud Asset data.
Args:
project_number (str): number of the project to query.
Yields:
dict: Generator of Compute Instance group.
"""
cai_to_gcp_key_map = {
'namedPort': 'namedPorts',
}
resources = self._iter_compute_resources('InstanceGroup',
project_number)
for instancegroup in resources:
yield _fixup_resource_keys(instancegroup, cai_to_gcp_key_map)
def iter_compute_instances(self, project_number):
"""Iterate compute engine instance from Cloud Asset data.
Args:
project_number (str): number of the project to query.
Yields:
dict: Generator of Compute Engine Instance resources.
"""
cai_to_gcp_key_map = {
'accessConfig': 'accessConfigs',
'aliasIpRange': 'aliasIpRanges',
'disk': 'disks',
'diskConfig': 'diskConfigs',
'guestAccelerator': 'guestAccelerators',
'guestOsFeature': 'guestOsFeatures',
'item': 'items',
'license': 'licenses',
'networkInterface': 'networkInterfaces',
'nodeAffinity': 'nodeAffinities',
'resourcePolicy': 'resourcePolicies',
'scope': 'scopes',
'serviceAccount': 'serviceAccounts',
'tag': 'tags',
}
resources = self._iter_compute_resources('Instance', project_number)
for instance in resources:
yield _fixup_resource_keys(instance, cai_to_gcp_key_map)
def iter_compute_instancetemplates(self, project_number):
"""Iterate Instance Templates from Cloud Asset data.
Args:
project_number (str): number of the project to query.
Yields:
dict: Generator of instance template resources.
"""
cai_to_gcp_key_map = {
'accessConfig': 'accessConfigs',
'aliasIpRange': 'aliasIpRanges',
'disk': 'disks',
'diskConfig': 'diskConfigs',
'guestAccelerator': 'guestAccelerators',
'guestOsFeature': 'guestOsFeatures',
'item': 'items',
'license': 'licenses',
'networkInterface': 'networkInterfaces',
'nodeAffinity': 'nodeAffinities',
'resourcePolicy': 'resourcePolicies',
'scope': 'scopes',
'serviceAccount': 'serviceAccounts',
'tag': 'tags',
}
resources = self._iter_compute_resources('InstanceTemplate',
project_number)
for instancetemplate in resources:
yield _fixup_resource_keys(instancetemplate, cai_to_gcp_key_map)
def iter_compute_licenses(self, project_number):
"""Iterate Licenses from Cloud Asset data.
Args:
project_number (str): number of the project to query.
Yields:
dict: Generator of license resources.
"""
resources = self._iter_compute_resources('License', project_number)
for compute_license in resources:
yield compute_license
def iter_compute_networks(self, project_number):
"""Iterate Networks from Cloud Asset data.
Args:
project_number (str): number of the project to query.
Yields:
dict: Generator of network resources.
"""
cai_to_gcp_key_map = {
'subnetwork': 'subnetworks',
}
resources = self._iter_compute_resources('Network', project_number)
for network in resources:
yield _fixup_resource_keys(network, cai_to_gcp_key_map)
def iter_compute_routers(self, project_number):
"""Iterate Compute Engine routers from Cloud Asset data.
Args:
project_number (str): number of the project to query.
Yields:
dict: Generator of Compute Routers.
"""
cai_to_gcp_key_map = {
'advertisedGroup': 'advertisedGroups',
'advertisedIpRange': 'advertisedIpRanges',
'bgpPeer': 'bgpPeers',
'interface': 'interfaces',
}
resources = self._iter_compute_resources('Router', project_number)
for router in resources:
yield _fixup_resource_keys(router, cai_to_gcp_key_map)
def iter_compute_snapshots(self, project_number):
"""Iterate Compute Engine snapshots from Cloud Asset data.
Args:
project_number (str): number of the project to query.
Yields:
dict: Generator of Compute Snapshots.
"""
cai_to_gcp_key_map = {
'guestOsFeature': 'guestOsFeatures',
'license': 'licenses',
'licenseCode': 'licenseCodes',
}
resources = self._iter_compute_resources('Snapshot', project_number)
for snapshot in resources:
yield _fixup_resource_keys(snapshot, cai_to_gcp_key_map)
def iter_compute_sslcertificates(self, project_number):
"""Iterate SSL certificates from Cloud Asset data.
Args:
project_number (str): number of the project to query.
Yields:
dict: Generator of ssl certificate resources.
"""
resources = self._iter_compute_resources('SslCertificate',
project_number)
for sslcertificate in resources:
yield sslcertificate
def iter_compute_subnetworks(self, project_number):
"""Iterate Subnetworks from Cloud Asset data.
Args:
project_number (str): number of the project to query.
Yields:
dict: Generator of subnetwork resources.
"""
resources = self._iter_compute_resources('Subnetwork',
project_number)
for subnetwork in resources:
yield subnetwork
def iter_compute_targethttpproxies(self, project_number):
"""Iterate Target HTTP proxies from Cloud Asset data.
Args:
project_number (str): number of the project to query.
Yields:
dict: Generator of target http proxy resources.
"""
resources = self._iter_compute_resources('TargetHttpProxy',
project_number)
for targethttpproxy in resources:
yield targethttpproxy
def iter_compute_targethttpsproxies(self, project_number):
"""Iterate Target HTTPS proxies from Cloud Asset data.
Args:
project_number (str): number of the project to query.
Yields:
dict: Generator of target https proxy resources.
"""
cai_to_gcp_key_map = {
'sslCertificate': 'sslCertificates',
}
resources = self._iter_compute_resources('TargetHttpsProxy',
project_number)
for targethttpsproxy in resources:
yield _fixup_resource_keys(targethttpsproxy, cai_to_gcp_key_map)
def iter_compute_targetinstances(self, project_number):
"""Iterate Target Instances from Cloud Asset data.
Args:
project_number (str): number of the project to query.
Yields:
dict: Generator of target instance resources.
"""
resources = self._iter_compute_resources('TargetInstance',
project_number)
for targetinstance in resources:
yield targetinstance
def iter_compute_targetpools(self, project_number):
"""Iterate Target Pools from Cloud Asset data.
Args:
project_number (str): number of the project to query.
Yields:
dict: Generator of target pool resources.
"""
cai_to_gcp_key_map = {
'healthCheck': 'healthChecks',
'instance': 'instances',
}
resources = self._iter_compute_resources('TargetPool', project_number)
for targetpool in resources:
yield _fixup_resource_keys(targetpool, cai_to_gcp_key_map)
def iter_compute_targetsslproxies(self, project_number):
"""Iterate Target SSL proxies from Cloud Asset data.
Args:
project_number (str): number of the project to query.
Yields:
dict: Generator of target ssl proxy resources.
"""
cai_to_gcp_key_map = {
'sslCertificate': 'sslCertificates',
}
resources = self._iter_compute_resources('TargetSslProxy',
project_number)
for targetsslproxy in resources:
yield _fixup_resource_keys(targetsslproxy, cai_to_gcp_key_map)
def iter_compute_targettcpproxies(self, project_number):
"""Iterate Target TCP proxies from Cloud Asset data.
Args:
project_number (str): number of the project to query.
Yields:
dict: Generator of target tcp proxy resources.
"""
resources = self._iter_compute_resources('TargetTcpProxy',
project_number)
for targettcpproxy in resources:
yield targettcpproxy
def iter_compute_urlmaps(self, project_number):
"""Iterate URL maps from Cloud Asset data.
Args:
project_number (str): number of the project to query.
Yields:
dict: Generator of url map resources.
"""
cai_to_gcp_key_map = {
'host': 'hosts',
'hostRule': 'hostRules',
'path': 'paths',
'pathMatcher': 'pathMatchers',
'pathRule': 'pathRules',
'test': 'tests'
}
resources = self._iter_compute_resources('UrlMap', project_number)
for urlmap in resources:
# 'path' can be singular when scalar or plural when a list, so
# turn on only_fixup_lists, so the singular instance isn't munged.
yield _fixup_resource_keys(urlmap, cai_to_gcp_key_map,
only_fixup_lists=True)
def iter_container_clusters(self, project_number):
"""Iterate Kubernetes Engine Cluster from Cloud Asset data.
Args:
project_number (str): number of the project to query.
Yields:
dict: Generator of Kubernetes Engine Cluster resources.
"""
resources = self.dao.iter_cai_assets(
ContentTypes.resource,
'google.container.Cluster',
'//cloudresourcemanager.googleapis.com/projects/{}'.format(
project_number),
self.session)
for cluster in resources:
yield cluster
def fetch_crm_folder(self, folder_id):
"""Fetch Folder data from Cloud Asset data.
Args:
folder_id (str): id of the folder to query.
Returns:
dict: Folder resource.
"""
resource = self.dao.fetch_cai_asset(
ContentTypes.resource,
'google.cloud.resourcemanager.Folder',
'//cloudresourcemanager.googleapis.com/{}'.format(folder_id),
self.session)
if resource:
return resource
# Fall back to live API if the data isn't in the CAI cache.
return super(CaiApiClientImpl, self).fetch_crm_folder(folder_id)
def fetch_crm_folder_iam_policy(self, folder_id):
"""Folder IAM policy in a folder from Cloud Asset data.
Args:
folder_id (str): id of the folder to get policy.
Returns:
dict: Folder IAM policy.
"""
resource = self.dao.fetch_cai_asset(
ContentTypes.iam_policy,
'google.cloud.resourcemanager.Folder',
'//cloudresourcemanager.googleapis.com/{}'.format(folder_id),
self.session)
if resource:
return resource
# Fall back to live API if the data isn't in the CAI cache.
return super(CaiApiClientImpl, self).fetch_crm_folder_iam_policy(
folder_id)
def fetch_crm_organization(self, org_id):
"""Fetch Organization data from Cloud Asset data.
Args:
org_id (str): id of the organization to get.
Returns:
dict: Organization resource.
"""
resource = self.dao.fetch_cai_asset(
ContentTypes.resource,
'google.cloud.resourcemanager.Organization',
'//cloudresourcemanager.googleapis.com/{}'.format(org_id),
self.session)
if resource:
return resource
# Fall back to live API if the data isn't in the CAI cache.
return super(CaiApiClientImpl, self).fetch_crm_organization(org_id)
def fetch_crm_organization_iam_policy(self, org_id):
"""Organization IAM policy from Cloud Asset data.
Args:
org_id (str): id of the organization to get policy.
Returns:
dict: Organization IAM policy.
"""
resource = self.dao.fetch_cai_asset(
ContentTypes.iam_policy,
'google.cloud.resourcemanager.Organization',
'//cloudresourcemanager.googleapis.com/{}'.format(org_id),
self.session)
if resource:
return resource
# Fall back to live API if the data isn't in the CAI cache.
return super(CaiApiClientImpl, self).fetch_crm_organization_iam_policy(
org_id)
def fetch_crm_project(self, project_number):
"""Fetch Project data from Cloud Asset data.
Args:
project_number (str): number of the project to query.
Returns:
dict: Project resource.
"""
resource = self.dao.fetch_cai_asset(
ContentTypes.resource,
'google.cloud.resourcemanager.Project',
'//cloudresourcemanager.googleapis.com/projects/{}'.format(
project_number),
self.session)
if resource:
return resource
# Fall back to live API if the data isn't in the CAI cache.
return super(CaiApiClientImpl, self).fetch_crm_project(project_number)
def fetch_crm_project_iam_policy(self, project_number):
"""Project IAM policy from Cloud Asset data.
Args:
project_number (str): number of the project to query.
Returns:
dict: Project IAM Policy.
"""
resource = self.dao.fetch_cai_asset(
ContentTypes.iam_policy,
'google.cloud.resourcemanager.Project',
'//cloudresourcemanager.googleapis.com/projects/{}'.format(
project_number),
self.session)
if resource:
return resource
# Fall back to live API if the data isn't in the CAI cache.
return super(CaiApiClientImpl, self).fetch_crm_project_iam_policy(
project_number)
def iter_crm_folders(self, parent_id):
"""Iterate Folders from Cloud Asset data.
Args:
parent_id (str): id of the parent of the folder
Yields:
dict: Generator of folders
"""
resources = self.dao.iter_cai_assets(
ContentTypes.resource,
'google.cloud.resourcemanager.Folder',
'//cloudresourcemanager.googleapis.com/{}'.format(parent_id),
self.session)
for folder in resources:
yield folder
def iter_crm_projects(self, parent_type, parent_id):
"""Iterate Projects from Cloud Asset data.
Args:
parent_type (str): type of the parent, "folder" or "organization".
parent_id (str): id of the parent of the folder.
Yields:
dict: Generator of Project resources
"""
resources = self.dao.iter_cai_assets(
ContentTypes.resource,
'google.cloud.resourcemanager.Project',
'//cloudresourcemanager.googleapis.com/{}s/{}'.format(parent_type,
parent_id),
self.session)
for project in resources:
yield project
def iter_dns_managedzones(self, project_number):
"""Iterate CloudDNS Managed Zones from Cloud Asset data.
Args:
project_number (str): number of the parent project.
Yields:
dict: Generator of ManagedZone resources
"""
resources = self.dao.iter_cai_assets(
ContentTypes.resource,
'google.cloud.dns.ManagedZone',
'//cloudresourcemanager.googleapis.com/projects/{}'.format(
project_number),
self.session)
for managedzone in resources:
yield managedzone
def iter_dns_policies(self, project_number):
"""Iterate CloudDNS Policies from Cloud Asset data.
Args:
project_number (str): number of the parent project of the policy.
Yields:
dict: Generator of ManagedZone resources
"""
resources = self.dao.iter_cai_assets(
ContentTypes.resource,
'google.cloud.dns.Policy',
'//cloudresourcemanager.googleapis.com/projects/{}'.format(
project_number),
self.session)
for policy in resources:
yield policy
def fetch_gae_app(self, project_id):
"""Fetch the AppEngine App from Cloud Asset data.
Args:
project_id (str): id of the project to query
Returns:
dict: AppEngine App resource.
"""
resource = self.dao.fetch_cai_asset(
ContentTypes.resource,
'google.appengine.Application',
'//appengine.googleapis.com/apps/{}'.format(project_id),
self.session)
return resource
def iter_gae_services(self, project_id):
"""Iterate gae services from Cloud Asset data.
Args:
project_id (str): id of the project to query
Yields:
dict: Generator of AppEngine Service resources.
"""
resources = self.dao.iter_cai_assets(
ContentTypes.resource,
'google.appengine.Service',
'//appengine.googleapis.com/apps/{}'.format(project_id),
self.session)
for service in resources:
yield service
def iter_gae_versions(self, project_id, service_id):
"""Iterate gae versions from Cloud Asset data.
Args:
project_id (str): id of the project to query
service_id (str): id of the appengine service
Yields:
dict: Generator of AppEngine Version resources.
"""
resources = self.dao.iter_cai_assets(
ContentTypes.resource,
'google.appengine.Version',
'//appengine.googleapis.com/apps/{}/services/{}'.format(project_id,
service_id),
self.session)
for version in resources:
yield version
def fetch_iam_serviceaccount_iam_policy(self, name, unique_id):
"""Service Account IAM policy from Cloud Asset data.
Args:
name (str): The service account name to query, must be in the format
projects/{PROJECT_ID}/serviceAccounts/{SERVICE_ACCOUNT_EMAIL}
unique_id (str): The unique id of the service account.
Returns:
dict: Service Account IAM policy.
"""
# CAI indexes iam policy by service account unique id, not email.
# This transforms the name to the format expected by CAI.
name_parts = name.split('/')
name_parts[-1] = unique_id
name = '/'.join(name_parts)
resource = self.dao.fetch_cai_asset(
ContentTypes.iam_policy,
'google.iam.ServiceAccount',
'//iam.googleapis.com/{}'.format(name),
self.session)
if resource:
return resource