-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
looker_source.py
1360 lines (1224 loc) · 52.6 KB
/
looker_source.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
import concurrent.futures
import datetime
import json
import logging
import os
from json import JSONDecodeError
from typing import (
Any,
Dict,
Iterable,
List,
MutableMapping,
Optional,
Sequence,
Set,
Tuple,
Union,
cast,
)
from looker_sdk.error import SDKError
from looker_sdk.sdk.api31.models import Dashboard, DashboardElement, FolderBase, Query
from pydantic import Field, validator
import datahub.emitter.mce_builder as builder
from datahub.configuration.common import AllowDenyPattern, ConfigurationError
from datahub.configuration.validate_field_removal import pydantic_removed_field
from datahub.emitter.mcp import MetadataChangeProposalWrapper
from datahub.emitter.mcp_builder import create_embed_mcp
from datahub.ingestion.api.common import PipelineContext
from datahub.ingestion.api.decorators import (
SupportStatus,
capability,
config_class,
platform_name,
support_status,
)
from datahub.ingestion.api.source import (
CapabilityReport,
SourceCapability,
SourceReport,
TestableSource,
TestConnectionReport,
)
from datahub.ingestion.api.workunit import MetadataWorkUnit
from datahub.ingestion.source.looker import looker_usage
from datahub.ingestion.source.looker.looker_common import (
InputFieldElement,
LookerCommonConfig,
LookerDashboard,
LookerDashboardElement,
LookerDashboardSourceReport,
LookerExplore,
LookerExploreRegistry,
LookerUser,
LookerUserRegistry,
LookerUtil,
ViewField,
ViewFieldType,
)
from datahub.ingestion.source.looker.looker_lib_wrapper import (
LookerAPI,
LookerAPIConfig,
)
from datahub.ingestion.source.state.entity_removal_state import GenericCheckpointState
from datahub.ingestion.source.state.stale_entity_removal_handler import (
StaleEntityRemovalHandler,
StatefulStaleMetadataRemovalConfig,
)
from datahub.ingestion.source.state.stateful_ingestion_base import (
StatefulIngestionConfigBase,
StatefulIngestionSourceBase,
)
from datahub.metadata.com.linkedin.pegasus2avro.common import (
AuditStamp,
ChangeAuditStamps,
Status,
)
from datahub.metadata.com.linkedin.pegasus2avro.metadata.snapshot import (
ChartSnapshot,
DashboardSnapshot,
)
from datahub.metadata.com.linkedin.pegasus2avro.mxe import MetadataChangeEvent
from datahub.metadata.schema_classes import (
BrowsePathsClass,
ChangeTypeClass,
ChartInfoClass,
ChartTypeClass,
DashboardInfoClass,
InputFieldClass,
InputFieldsClass,
OwnerClass,
OwnershipClass,
OwnershipTypeClass,
)
from datahub.utilities.source_helpers import (
auto_stale_entity_removal,
auto_status_aspect,
)
logger = logging.getLogger(__name__)
class LookerDashboardSourceConfig(
LookerAPIConfig, LookerCommonConfig, StatefulIngestionConfigBase
):
_removed_github_info = pydantic_removed_field("github_info")
dashboard_pattern: AllowDenyPattern = Field(
AllowDenyPattern.allow_all(),
description="Patterns for selecting dashboard ids that are to be included",
)
chart_pattern: AllowDenyPattern = Field(
AllowDenyPattern.allow_all(),
description="Patterns for selecting chart ids that are to be included",
)
include_deleted: bool = Field(
False, description="Whether to include deleted dashboards."
)
extract_owners: bool = Field(
True,
description="When enabled, extracts ownership from Looker directly. When disabled, ownership is left empty for dashboards and charts.",
)
actor: Optional[str] = Field(
None,
description="This config is deprecated in favor of `extract_owners`. Previously, was the actor to use in ownership properties of ingested metadata.",
)
strip_user_ids_from_email: bool = Field(
False,
description="When enabled, converts Looker user emails of the form name@domain.com to urn:li:corpuser:name when assigning ownership",
)
skip_personal_folders: bool = Field(
False,
description="Whether to skip ingestion of dashboards in personal folders. Setting this to True will only ingest dashboards in the Shared folder space.",
)
max_threads: int = Field(
os.cpu_count() or 40,
description="Max parallelism for Looker API calls. Defaults to cpuCount or 40",
)
external_base_url: Optional[str] = Field(
None,
description="Optional URL to use when constructing external URLs to Looker if the `base_url` is not the correct one to use. For example, `https://looker-public.company.com`. If not provided, the external base URL will default to `base_url`.",
)
extract_usage_history: bool = Field(
False,
description="Whether to ingest usage statistics for dashboards. Setting this to True will query looker system activity explores to fetch historical dashboard usage.",
)
# TODO - stateful ingestion to autodetect usage history interval
extract_usage_history_for_interval: str = Field(
"30 days",
description="Used only if extract_usage_history is set to True. Interval to extract looker dashboard usage history for. See https://docs.looker.com/reference/filter-expressions#date_and_time.",
)
extract_embed_urls: bool = Field(
True,
description="Produce URLs used to render Looker Explores as Previews inside of DataHub UI. Embeds must be enabled inside of Looker to use this feature.",
)
stateful_ingestion: Optional[StatefulStaleMetadataRemovalConfig] = Field(
default=None, description=""
)
@validator("external_base_url", pre=True, always=True)
def external_url_defaults_to_api_config_base_url(
cls, v: Optional[str], *, values: Dict[str, Any], **kwargs: Dict[str, Any]
) -> Optional[str]:
return v or values.get("base_url")
@validator("platform_instance")
def platform_instance_not_supported(cls, v: Optional[str]) -> Optional[str]:
if v is not None:
raise ConfigurationError("Looker Source doesn't support platform instances")
return v
@platform_name("Looker")
@support_status(SupportStatus.CERTIFIED)
@config_class(LookerDashboardSourceConfig)
@capability(SourceCapability.DESCRIPTIONS, "Enabled by default")
@capability(SourceCapability.PLATFORM_INSTANCE, "Enabled by default")
@capability(
SourceCapability.OWNERSHIP, "Enabled by default, configured using `extract_owners`"
)
@capability(
SourceCapability.USAGE_STATS, "Can be enabled using `extract_usage_history`"
)
class LookerDashboardSource(TestableSource, StatefulIngestionSourceBase):
"""
This plugin extracts the following:
- Looker dashboards, dashboard elements (charts) and explores
- Names, descriptions, URLs, chart types, input explores for the charts
- Schemas and input views for explores
- Owners of dashboards
:::note
To get complete Looker metadata integration (including Looker views and lineage to the underlying warehouse tables), you must ALSO use the `lookml` module.
:::
"""
platform = "looker"
source_config: LookerDashboardSourceConfig
reporter: LookerDashboardSourceReport
user_registry: LookerUserRegistry
accessed_dashboards: int = 0
resolved_user_ids: int = 0
email_ids_missing: int = 0 # resolved users with missing email addresses
def __init__(self, config: LookerDashboardSourceConfig, ctx: PipelineContext):
super().__init__(config, ctx)
self.source_config = config
self.reporter = LookerDashboardSourceReport()
self.looker_api: LookerAPI = LookerAPI(self.source_config)
self.user_registry = LookerUserRegistry(self.looker_api)
self.explore_registry = LookerExploreRegistry(self.looker_api, self.reporter)
self.reporter._looker_explore_registry = self.explore_registry
self.reporter._looker_api = self.looker_api
self.explores_to_fetch_set: Dict[Tuple[str, str], List[str]] = {}
# Keep stat generators to generate entity stat aspect later
stat_generator_config: looker_usage.StatGeneratorConfig = (
looker_usage.StatGeneratorConfig(
looker_api_wrapper=self.looker_api,
looker_user_registry=self.user_registry,
interval=self.source_config.extract_usage_history_for_interval,
strip_user_ids_from_email=self.source_config.strip_user_ids_from_email,
platform_name=self.source_config.platform_name,
max_threads=self.source_config.max_threads,
)
)
self.dashboard_stat_generator = looker_usage.create_stat_entity_generator(
looker_usage.SupportedStatEntity.DASHBOARD,
config=stat_generator_config,
)
self.chart_stat_generator = looker_usage.create_stat_entity_generator(
looker_usage.SupportedStatEntity.CHART,
config=stat_generator_config,
)
# Create and register the stateful ingestion use-case handlers.
self.stale_entity_removal_handler = StaleEntityRemovalHandler(
source=self,
config=self.source_config,
state_type_class=GenericCheckpointState,
pipeline_name=self.ctx.pipeline_name,
run_id=self.ctx.run_id,
)
@staticmethod
def test_connection(config_dict: dict) -> TestConnectionReport:
test_report = TestConnectionReport()
try:
test_report.basic_connectivity = CapabilityReport(capable=True)
test_report.capability_report = {}
config = LookerDashboardSourceConfig.parse_obj_allow_extras(config_dict)
permissions = LookerAPI(config).get_available_permissions()
BASIC_INGEST_REQUIRED_PERMISSIONS = {
# TODO: Make this a bit more granular.
"access_data",
"explore",
"manage_models",
"see_datagroups",
"see_lookml",
"see_lookml_dashboards",
"see_looks",
"see_pdts",
"see_queries",
"see_schedules",
"see_sql",
"see_user_dashboards",
"see_users",
}
USAGE_INGEST_REQUIRED_PERMISSIONS = {
"see_system_activity",
}
LookerDashboardSource._set_test_connection_capability(
test_report,
permissions,
SourceCapability.DESCRIPTIONS,
BASIC_INGEST_REQUIRED_PERMISSIONS,
)
LookerDashboardSource._set_test_connection_capability(
test_report,
permissions,
SourceCapability.OWNERSHIP,
BASIC_INGEST_REQUIRED_PERMISSIONS,
)
LookerDashboardSource._set_test_connection_capability(
test_report,
permissions,
SourceCapability.USAGE_STATS,
USAGE_INGEST_REQUIRED_PERMISSIONS,
)
except Exception as e:
logger.exception(f"Failed to test connection due to {e}")
test_report.internal_failure = True
test_report.internal_failure_reason = f"{e}"
if test_report.basic_connectivity is None:
test_report.basic_connectivity = CapabilityReport(
capable=False, failure_reason=f"{e}"
)
return test_report
@staticmethod
def _set_test_connection_capability(
test_report: TestConnectionReport,
permissions: Set[str],
perm: SourceCapability,
required: Set[str],
) -> None:
assert test_report.capability_report is not None
if required.issubset(permissions):
test_report.capability_report[perm] = CapabilityReport(capable=True)
else:
missing = required - permissions
test_report.capability_report[perm] = CapabilityReport(
capable=False,
error_message=f"Missing required permissions: {', '.join(missing)}",
)
@staticmethod
def _extract_view_from_field(field: str) -> str:
assert (
field.count(".") == 1
), f"Error: A field must be prefixed by a view name, field is: {field}"
return field.split(".")[0]
def _get_views_from_fields(self, fields: List[str]) -> List[str]:
field_set = set(fields)
views = set()
for field_name in field_set:
try:
view_name = self._extract_view_from_field(field_name)
views.add(view_name)
except AssertionError:
self.reporter.report_warning(
key=f"chart-field-{field_name}",
reason="The field was not prefixed by a view name. This can happen when the field references another dynamic field.",
)
continue
return list(views)
def _get_input_fields_from_query(
self, query: Optional[Query]
) -> List[InputFieldElement]:
if query is None:
return []
result = []
# query.dynamic_fields can contain:
# - looker table calculations: https://docs.looker.com/exploring-data/using-table-calculations
# - looker custom measures: https://docs.looker.com/de/exploring-data/adding-fields/custom-measure
# - looker custom dimensions: https://docs.looker.com/exploring-data/adding-fields/custom-measure#creating_a_custom_dimension_using_a_looker_expression
try:
dynamic_fields = json.loads(
query.dynamic_fields if query.dynamic_fields is not None else "[]"
)
except JSONDecodeError as e:
logger.warning(
f"Json load failed on loading dynamic field with error: {e}. The field value was: {query.dynamic_fields}"
)
dynamic_fields = []
for field in dynamic_fields:
if "table_calculation" in field:
result.append(
InputFieldElement(
name=field["table_calculation"],
view_field=ViewField(
name=field["table_calculation"],
label=field.get("label"),
field_type=ViewFieldType.UNKNOWN,
type="string",
description="",
),
)
)
if "measure" in field:
# for measure, we can also make sure to index the underlying field that the measure uses
based_on = field.get("based_on")
if based_on is not None:
result.append(
InputFieldElement(
based_on,
view_field=None,
model=query.model,
explore=query.view,
)
)
result.append(
InputFieldElement(
name=field["measure"],
view_field=ViewField(
name=field["measure"],
label=field.get("label"),
field_type=ViewFieldType.MEASURE,
type="string",
description="",
),
)
)
if "dimension" in field:
result.append(
InputFieldElement(
name=field["dimension"],
view_field=ViewField(
name=field["dimension"],
label=field.get("label"),
field_type=ViewFieldType.DIMENSION,
type="string",
description="",
),
)
)
# A query uses fields defined in explores, find the metadata about that field
fields: Sequence[str] = query.fields if query.fields is not None else []
for field in fields:
if field is None:
continue
# we haven't loaded in metadata about the explore yet, so we need to wait until explores are populated later to fetch this
result.append(
InputFieldElement(
name=field, view_field=None, model=query.model, explore=query.view
)
)
# A query uses fields for filtering and those fields are defined in views, find the views those fields use
filters: MutableMapping[str, Any] = (
query.filters if query.filters is not None else {}
)
for field in filters.keys():
if field is None:
continue
# we haven't loaded in metadata about the explore yet, so we need to wait until explores are populated later to fetch this
result.append(
InputFieldElement(
name=field, view_field=None, model=query.model, explore=query.view
)
)
return result
def add_explore_to_fetch(self, model: str, explore: str, via: str) -> None:
if (model, explore) not in self.explores_to_fetch_set:
self.explores_to_fetch_set[(model, explore)] = []
self.explores_to_fetch_set[(model, explore)].append(via)
def _get_looker_dashboard_element( # noqa: C901
self, element: DashboardElement
) -> Optional[LookerDashboardElement]:
# Dashboard elements can use raw usage_queries against explores
explores: List[str]
input_fields: List[InputFieldElement]
if element.id is None:
raise ValueError("Element ID can't be None")
if element.query is not None:
input_fields = self._get_input_fields_from_query(element.query)
# Get the explore from the view directly
explores = [element.query.view] if element.query.view is not None else []
logger.debug(
f"Element {element.title}: Explores added via query: {explores}"
)
for exp in explores:
self.add_explore_to_fetch(
model=element.query.model,
explore=exp,
via=f"look:{element.look_id}:query:{element.dashboard_id}",
)
return LookerDashboardElement(
id=element.id,
title=element.title if element.title is not None else "",
type=element.type,
description=element.subtitle_text,
look_id=None,
query_slug=element.query.slug if element.query.slug is not None else "",
upstream_explores=[
LookerExplore(model_name=element.query.model, name=exp)
for exp in explores
],
input_fields=input_fields,
)
# Dashboard elements can *alternatively* link to an existing look
elif element.look is not None:
# we pick from element title by default, falling back to look title.
title: str = (
element.title
if element.title is not None and element.title != ""
else element.look.title
if element.look.title is not None
else ""
)
if element.look.query is not None:
input_fields = self._get_input_fields_from_query(element.look.query)
if element.look.query.view is not None:
explores = [element.look.query.view]
logger.debug(f"Element {title}: Explores added via look: {explores}")
for exp in explores:
self.add_explore_to_fetch(
model=element.look.query.model,
explore=exp,
via=f"Look:{element.look_id}:query:{element.dashboard_id}",
)
if element.look.query and element.look.query.slug:
slug = element.look.query.slug
else:
slug = ""
return LookerDashboardElement(
id=element.id,
title=title,
type=element.type,
description=element.subtitle_text,
look_id=element.look_id,
query_slug=slug,
upstream_explores=[
LookerExplore(model_name=element.look.query.model, name=exp)
for exp in explores
],
input_fields=input_fields,
)
# Failing the above two approaches, pick out details from result_maker
elif element.result_maker is not None:
model: str = ""
input_fields = []
explores = []
if element.result_maker.query is not None:
model = element.result_maker.query.model
if element.result_maker.query.view is not None:
explores.append(element.result_maker.query.view)
input_fields = self._get_input_fields_from_query(
element.result_maker.query
)
logger.debug(
f"Element {element.title}: Explores added via result_maker: {explores}"
)
for exp in explores:
self.add_explore_to_fetch(
model=element.result_maker.query.model,
explore=exp,
via=f"Look:{element.look_id}:resultmaker:query",
)
# In addition to the query, filters can point to fields as well
assert element.result_maker.filterables is not None
for filterable in element.result_maker.filterables:
if filterable.view is not None and filterable.model is not None:
model = filterable.model
explores.append(filterable.view)
self.add_explore_to_fetch(
model=filterable.model,
explore=filterable.view,
via=f"Look:{element.look_id}:resultmaker:filterable",
)
listen = filterable.listen
query = element.result_maker.query
if listen is not None:
for listener in listen:
if listener.field is not None:
input_fields.append(
InputFieldElement(
listener.field,
view_field=None,
model=query.model if query is not None else "",
explore=query.view if query is not None else "",
)
)
explores = sorted(list(set(explores))) # dedup the list of views
return LookerDashboardElement(
id=element.id,
title=element.title if element.title is not None else "",
type=element.type,
description=element.subtitle_text,
look_id=element.look_id,
query_slug=element.result_maker.query.slug
if element.result_maker.query is not None
and element.result_maker.query.slug is not None
else "",
upstream_explores=[
LookerExplore(model_name=model, name=exp) for exp in explores
],
input_fields=input_fields,
)
logger.debug(f"Element {element.title}: Unable to parse LookerDashboardElement")
return None
def _get_chart_type(
self, dashboard_element: LookerDashboardElement
) -> Optional[str]:
type_mapping = {
"looker_column": ChartTypeClass.BAR,
"looker_scatter": ChartTypeClass.SCATTER,
"looker_line": ChartTypeClass.LINE,
"looker_area": ChartTypeClass.AREA,
"looker_pie": ChartTypeClass.PIE,
"looker_donut_multiples": ChartTypeClass.PIE,
"looker_funnel": ChartTypeClass.BAR,
"looker_timeline": ChartTypeClass.BAR,
"looker_waterfall": ChartTypeClass.BAR,
"text": ChartTypeClass.TEXT,
"single_value": ChartTypeClass.TEXT,
"looker_single_record": ChartTypeClass.TABLE,
"table": ChartTypeClass.TABLE,
"looker_grid": ChartTypeClass.TABLE,
"looker_map": None,
"looker_geo_coordinates": None,
"looker_geo_choropleth": None,
"looker_boxplot": ChartTypeClass.BOX_PLOT,
"vis": None,
}
type_str = dashboard_element.type
if not type_str:
self.reporter.report_warning(
key=f"looker-chart-{dashboard_element.id}",
reason=f"Chart type {type_str} is missing. Setting to None",
)
return None
try:
chart_type = type_mapping[type_str]
except KeyError:
self.reporter.report_warning(
key=f"looker-chart-{dashboard_element.id}",
reason=f"Chart type {type_str} not supported. Setting to None",
)
chart_type = None
return chart_type
def _make_chart_metadata_events(
self, dashboard_element: LookerDashboardElement, dashboard: LookerDashboard
) -> List[Union[MetadataChangeEvent, MetadataChangeProposalWrapper]]:
chart_urn = builder.make_chart_urn(
self.source_config.platform_name, dashboard_element.get_urn_element_id()
)
chart_snapshot = ChartSnapshot(
urn=chart_urn,
aspects=[Status(removed=False)],
)
chart_type = self._get_chart_type(dashboard_element)
chart_info = ChartInfoClass(
type=chart_type,
description=dashboard_element.description or "",
title=dashboard_element.title or "",
lastModified=ChangeAuditStamps(),
chartUrl=dashboard_element.url(self.source_config.external_base_url or ""),
inputs=dashboard_element.get_view_urns(self.source_config),
customProperties={
"upstream_fields": ",".join(
sorted(set(field.name for field in dashboard_element.input_fields))
)
if dashboard_element.input_fields
else ""
},
)
chart_snapshot.aspects.append(chart_info)
ownership = self.get_ownership(dashboard)
if ownership is not None:
chart_snapshot.aspects.append(ownership)
chart_mce = MetadataChangeEvent(proposedSnapshot=chart_snapshot)
proposals: List[Union[MetadataChangeEvent, MetadataChangeProposalWrapper]] = [
chart_mce
]
# If extracting embeds is enabled, produce an MCP for embed URL.
if (
self.source_config.extract_embed_urls
and self.source_config.external_base_url
):
maybe_embed_url = dashboard_element.embed_url(
self.source_config.external_base_url
)
if maybe_embed_url:
proposals.append(
create_embed_mcp(
chart_snapshot.urn,
maybe_embed_url,
)
)
return proposals
def _make_dashboard_metadata_events(
self, looker_dashboard: LookerDashboard, chart_urns: List[str]
) -> List[Union[MetadataChangeEvent, MetadataChangeProposalWrapper]]:
dashboard_urn = builder.make_dashboard_urn(
self.source_config.platform_name, looker_dashboard.get_urn_dashboard_id()
)
dashboard_snapshot = DashboardSnapshot(
urn=dashboard_urn,
aspects=[],
)
dashboard_info = DashboardInfoClass(
description=looker_dashboard.description or "",
title=looker_dashboard.title,
charts=chart_urns,
lastModified=self._get_change_audit_stamps(looker_dashboard),
dashboardUrl=looker_dashboard.url(self.source_config.external_base_url),
)
dashboard_snapshot.aspects.append(dashboard_info)
if looker_dashboard.folder_path is not None:
browse_path = BrowsePathsClass(
paths=[f"/looker/{looker_dashboard.folder_path}"]
)
dashboard_snapshot.aspects.append(browse_path)
ownership = self.get_ownership(looker_dashboard)
if ownership is not None:
dashboard_snapshot.aspects.append(ownership)
dashboard_snapshot.aspects.append(Status(removed=looker_dashboard.is_deleted))
dashboard_mce = MetadataChangeEvent(proposedSnapshot=dashboard_snapshot)
proposals: List[Union[MetadataChangeEvent, MetadataChangeProposalWrapper]] = [
dashboard_mce
]
# If extracting embeds is enabled, produce an MCP for embed URL.
if (
self.source_config.extract_embed_urls
and self.source_config.external_base_url
):
proposals.append(
create_embed_mcp(
dashboard_snapshot.urn,
looker_dashboard.embed_url(self.source_config.external_base_url),
)
)
return proposals
def _make_explore_metadata_events(
self,
) -> Iterable[Union[MetadataChangeEvent, MetadataChangeProposalWrapper]]:
with concurrent.futures.ThreadPoolExecutor(
max_workers=self.source_config.max_threads
) as async_executor:
self.reporter.total_explores = len(self.explores_to_fetch_set)
explore_futures = {
async_executor.submit(self.fetch_one_explore, model, explore): (
model,
explore,
)
for (model, explore) in self.explores_to_fetch_set
}
for future in concurrent.futures.as_completed(explore_futures):
events, explore_id, start_time, end_time = future.result()
del explore_futures[future]
self.reporter.explores_scanned += 1
yield from events
self.reporter.report_upstream_latency(start_time, end_time)
logger.debug(
f"Running time of fetch_one_explore for {explore_id}: {(end_time - start_time).total_seconds()}"
)
def fetch_one_explore(
self, model: str, explore: str
) -> Tuple[
List[Union[MetadataChangeEvent, MetadataChangeProposalWrapper]],
str,
datetime.datetime,
datetime.datetime,
]:
start_time = datetime.datetime.now()
events: List[Union[MetadataChangeEvent, MetadataChangeProposalWrapper]] = []
looker_explore = self.explore_registry.get_explore(model, explore)
if looker_explore is not None:
events = (
looker_explore._to_metadata_events(
self.source_config,
self.reporter,
self.source_config.base_url,
self.source_config.extract_embed_urls,
)
or events
)
return events, f"{model}:{explore}", start_time, datetime.datetime.now()
def _extract_event_urn(
self, event: Union[MetadataChangeEvent, MetadataChangeProposalWrapper]
) -> Optional[str]:
if isinstance(event, MetadataChangeEvent):
return event.proposedSnapshot.urn
else:
return event.entityUrn
def _make_dashboard_and_chart_mces(
self, looker_dashboard: LookerDashboard
) -> Iterable[Union[MetadataChangeEvent, MetadataChangeProposalWrapper]]:
# Step 1: Emit metadata for each Chart inside the Dashboard.
chart_events = []
for element in looker_dashboard.dashboard_elements:
if element.type == "vis":
chart_events.extend(
self._make_chart_metadata_events(element, looker_dashboard)
)
yield from chart_events
# Step 2: Emit metadata events for the Dashboard itself.
chart_urns: Set[
str
] = set() # Collect the unique child chart urns for dashboard input lineage.
for chart_event in chart_events:
chart_event_urn = self._extract_event_urn(chart_event)
if chart_event_urn:
chart_urns.add(chart_event_urn)
dashboard_events = self._make_dashboard_metadata_events(
looker_dashboard, list(chart_urns)
)
for dashboard_event in dashboard_events:
yield dashboard_event
def get_ownership(
self, looker_dashboard: LookerDashboard
) -> Optional[OwnershipClass]:
if looker_dashboard.owner is not None:
owner_urn = looker_dashboard.owner.get_urn(
self.source_config.strip_user_ids_from_email
)
if owner_urn is not None:
ownership: OwnershipClass = OwnershipClass(
owners=[
OwnerClass(
owner=owner_urn,
type=OwnershipTypeClass.DATAOWNER,
)
]
)
return ownership
return None
def _get_change_audit_stamps(
self, looker_dashboard: LookerDashboard
) -> ChangeAuditStamps:
change_audit_stamp: ChangeAuditStamps = ChangeAuditStamps()
if looker_dashboard.created_at is not None:
change_audit_stamp.created.time = round(
looker_dashboard.created_at.timestamp() * 1000
)
if looker_dashboard.owner is not None:
owner_urn = looker_dashboard.owner.get_urn(
self.source_config.strip_user_ids_from_email
)
if owner_urn:
change_audit_stamp.created.actor = owner_urn
if looker_dashboard.last_updated_at is not None:
change_audit_stamp.lastModified.time = round(
looker_dashboard.last_updated_at.timestamp() * 1000
)
if looker_dashboard.last_updated_by is not None:
updated_by_urn = looker_dashboard.last_updated_by.get_urn(
self.source_config.strip_user_ids_from_email
)
if updated_by_urn:
change_audit_stamp.lastModified.actor = updated_by_urn
if (
looker_dashboard.is_deleted
and looker_dashboard.deleted_by is not None
and looker_dashboard.deleted_at is not None
):
deleter_urn = looker_dashboard.deleted_by.get_urn(
self.source_config.strip_user_ids_from_email
)
if deleter_urn:
change_audit_stamp.deleted = AuditStamp(
actor=deleter_urn,
time=round(looker_dashboard.deleted_at.timestamp() * 1000),
)
return change_audit_stamp
def _get_folder_path(self, folder: FolderBase, client: LookerAPI) -> str:
assert folder.id
ancestors = [
ancestor.name for ancestor in client.folder_ancestors(folder_id=folder.id)
]
return "/".join(ancestors + [folder.name])
def _get_looker_dashboard(
self, dashboard: Dashboard, client: LookerAPI
) -> LookerDashboard:
self.accessed_dashboards += 1
if dashboard.folder is None:
logger.debug(f"{dashboard.id} has no folder")
dashboard_folder_path = None
if dashboard.folder is not None:
dashboard_folder_path = self._get_folder_path(dashboard.folder, client)
dashboard_elements: List[LookerDashboardElement] = []
elements = (
dashboard.dashboard_elements
if dashboard.dashboard_elements is not None
else []
)
for element in elements:
self.reporter.report_charts_scanned()
if element.id is not None and not self.source_config.chart_pattern.allowed(
element.id
):
self.reporter.report_charts_dropped(element.id)
continue
looker_dashboard_element = self._get_looker_dashboard_element(element)
if looker_dashboard_element is not None:
dashboard_elements.append(looker_dashboard_element)
if dashboard.id is None or dashboard.title is None:
raise ValueError("Both dashboard ID and title are None")
looker_dashboard = LookerDashboard(
id=dashboard.id,
title=dashboard.title,
description=dashboard.description,
dashboard_elements=dashboard_elements,
created_at=dashboard.created_at,
is_deleted=dashboard.deleted if dashboard.deleted is not None else False,
is_hidden=dashboard.hidden if dashboard.hidden is not None else False,
folder_path=dashboard_folder_path,
owner=self._get_looker_user(dashboard.user_id),
strip_user_ids_from_email=self.source_config.strip_user_ids_from_email,
last_updated_at=dashboard.updated_at,
last_updated_by=self._get_looker_user(dashboard.last_updater_id),
deleted_at=dashboard.deleted_at,
deleted_by=self._get_looker_user(dashboard.deleter_id),
favorite_count=dashboard.favorite_count,
view_count=dashboard.view_count,
last_viewed_at=dashboard.last_viewed_at,
)
return looker_dashboard
def _get_looker_user(self, user_id: Optional[int]) -> Optional[LookerUser]:
user = (
self.user_registry.get_by_id(
user_id,
)
if self.source_config.extract_owners and user_id is not None
else None
)
if user is not None and self.source_config.extract_owners:
# Keep track of how many user ids we were able to resolve
self.resolved_user_ids += 1
if user.email is None:
self.email_ids_missing += 1
return user
def process_metrics_dimensions_and_fields_for_dashboard(
self, dashboard: LookerDashboard
) -> List[MetadataWorkUnit]:
chart_mcps = [
self._make_metrics_dimensions_chart_mcp(element, dashboard)
for element in dashboard.dashboard_elements
]
dashboard_mcp = self._make_metrics_dimensions_dashboard_mcp(dashboard)
mcps = chart_mcps
mcps.append(dashboard_mcp)
workunits = [
MetadataWorkUnit(
id=f"looker-{mcp.aspectName}-{mcp.entityUrn}",
mcp=mcp,
treat_errors_as_warnings=True,
)
for mcp in mcps