-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
tableau.py
3038 lines (2694 loc) · 116 KB
/
tableau.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 logging
import re
import time
from collections import OrderedDict
from dataclasses import dataclass
from datetime import datetime
from functools import lru_cache
from typing import (
Any,
Callable,
Dict,
Iterable,
List,
Optional,
Set,
Tuple,
Type,
Union,
cast,
)
from urllib.parse import quote, urlparse
import dateutil.parser as dp
import tableauserverclient as TSC
from pydantic import root_validator, validator
from pydantic.fields import Field
from requests.adapters import HTTPAdapter
from tableauserverclient import (
PersonalAccessTokenAuth,
Server,
ServerResponseError,
SiteItem,
TableauAuth,
)
from tableauserverclient.server.endpoint.exceptions import NonXMLResponseError
from urllib3 import Retry
import datahub.emitter.mce_builder as builder
from datahub.configuration.common import (
AllowDenyPattern,
ConfigModel,
ConfigurationError,
)
from datahub.configuration.source_common import (
DatasetLineageProviderConfigBase,
DatasetSourceConfigMixin,
)
from datahub.configuration.validate_field_deprecation import pydantic_field_deprecated
from datahub.emitter.mcp import MetadataChangeProposalWrapper
from datahub.emitter.mcp_builder import (
ContainerKey,
add_entity_to_container,
gen_containers,
)
from datahub.ingestion.api.common import PipelineContext
from datahub.ingestion.api.decorators import (
SourceCapability,
SupportStatus,
capability,
config_class,
platform_name,
support_status,
)
from datahub.ingestion.api.source import (
CapabilityReport,
MetadataWorkUnitProcessor,
Source,
TestableSource,
TestConnectionReport,
)
from datahub.ingestion.api.workunit import MetadataWorkUnit
from datahub.ingestion.source import tableau_constant as c
from datahub.ingestion.source.common.subtypes import (
BIContainerSubTypes,
DatasetSubTypes,
)
from datahub.ingestion.source.state.stale_entity_removal_handler import (
StaleEntityRemovalHandler,
StaleEntityRemovalSourceReport,
StatefulStaleMetadataRemovalConfig,
)
from datahub.ingestion.source.state.stateful_ingestion_base import (
StatefulIngestionConfigBase,
StatefulIngestionSourceBase,
)
from datahub.ingestion.source.tableau_common import (
FIELD_TYPE_MAPPING,
MetadataQueryException,
TableauLineageOverrides,
TableauUpstreamReference,
clean_query,
custom_sql_graphql_query,
dashboard_graphql_query,
database_servers_graphql_query,
database_tables_graphql_query,
embedded_datasource_graphql_query,
get_filter_pages,
get_overridden_info,
get_unique_custom_sql,
make_filter,
make_fine_grained_lineage_class,
make_upstream_class,
published_datasource_graphql_query,
query_metadata,
sheet_graphql_query,
tableau_field_to_schema_field,
workbook_graphql_query,
)
from datahub.metadata.com.linkedin.pegasus2avro.common import (
AuditStamp,
ChangeAuditStamps,
InputField,
InputFields,
)
from datahub.metadata.com.linkedin.pegasus2avro.dataset import (
DatasetLineageType,
FineGrainedLineage,
FineGrainedLineageDownstreamType,
FineGrainedLineageUpstreamType,
Upstream,
UpstreamLineage,
)
from datahub.metadata.com.linkedin.pegasus2avro.metadata.snapshot import (
ChartSnapshot,
DashboardSnapshot,
DatasetSnapshot,
)
from datahub.metadata.com.linkedin.pegasus2avro.mxe import MetadataChangeEvent
from datahub.metadata.com.linkedin.pegasus2avro.schema import (
NullTypeClass,
OtherSchema,
SchemaField,
SchemaFieldDataType,
SchemaMetadata,
)
from datahub.metadata.schema_classes import (
BrowsePathsClass,
ChangeTypeClass,
ChartInfoClass,
ChartUsageStatisticsClass,
DashboardInfoClass,
DashboardUsageStatisticsClass,
DataPlatformInstanceClass,
DatasetPropertiesClass,
EmbedClass,
OwnerClass,
OwnershipClass,
OwnershipTypeClass,
SubTypesClass,
ViewPropertiesClass,
)
from datahub.sql_parsing.sql_parsing_result_utils import (
transform_parsing_result_to_in_tables_schemas,
)
from datahub.sql_parsing.sqlglot_lineage import (
ColumnLineageInfo,
SqlParsingResult,
create_lineage_sql_parsed_result,
)
from datahub.utilities import config_clean
from datahub.utilities.urns.dataset_urn import DatasetUrn
try:
# On earlier versions of the tableauserverclient, the NonXMLResponseError
# was thrown when reauthentication was needed. We'll keep both exceptions
# around for now, but can remove this in the future.
from tableauserverclient.server.endpoint.exceptions import ( # type: ignore
NotSignedInError,
)
REAUTHENTICATE_ERRORS: Tuple[Type[Exception], ...] = (
NotSignedInError,
NonXMLResponseError,
)
except ImportError:
REAUTHENTICATE_ERRORS = (NonXMLResponseError,)
logger: logging.Logger = logging.getLogger(__name__)
# Replace / with |
REPLACE_SLASH_CHAR = "|"
class TableauConnectionConfig(ConfigModel):
connect_uri: str = Field(description="Tableau host URL.")
username: Optional[str] = Field(
default=None,
description="Tableau username, must be set if authenticating using username/password.",
)
password: Optional[str] = Field(
default=None,
description="Tableau password, must be set if authenticating using username/password.",
)
token_name: Optional[str] = Field(
default=None,
description="Tableau token name, must be set if authenticating using a personal access token.",
)
token_value: Optional[str] = Field(
default=None,
description="Tableau token value, must be set if authenticating using a personal access token.",
)
site: str = Field(
default="",
description="Tableau Site. Always required for Tableau Online. Use emptystring to connect with Default site on Tableau Server.",
)
platform_instance: Optional[str] = Field(
default=None,
description="Unique relationship between the Tableau Server and site",
)
max_retries: int = Field(3, description="Number of retries for failed requests.")
ssl_verify: Union[bool, str] = Field(
default=True,
description="Whether to verify SSL certificates. If using self-signed certificates, set to false or provide the path to the .pem certificate bundle.",
)
extract_column_level_lineage: bool = Field(
True,
description="When enabled, extracts column-level lineage from Tableau Datasources",
)
@validator("connect_uri")
def remove_trailing_slash(cls, v):
return config_clean.remove_trailing_slashes(v)
def get_tableau_auth(
self, site: str
) -> Union[TableauAuth, PersonalAccessTokenAuth]:
# https://tableau.github.io/server-client-python/docs/api-ref#authentication
authentication: Union[TableauAuth, PersonalAccessTokenAuth]
if self.username and self.password:
authentication = TableauAuth(
username=self.username,
password=self.password,
site_id=site,
)
elif self.token_name and self.token_value:
authentication = PersonalAccessTokenAuth(
self.token_name, self.token_value, site
)
else:
raise ConfigurationError(
"Tableau Source: Either username/password or token_name/token_value must be set"
)
return authentication
def make_tableau_client(self, site: str) -> Server:
authentication: Union[
TableauAuth, PersonalAccessTokenAuth
] = self.get_tableau_auth(site)
try:
server = Server(
self.connect_uri,
use_server_version=True,
http_options={
# As per https://community.tableau.com/s/question/0D54T00000F33bdSAB/tableauserverclient-signin-with-ssl-certificate
"verify": bool(self.ssl_verify),
**(
{"cert": self.ssl_verify}
if isinstance(self.ssl_verify, str)
else {}
),
},
)
# From https://stackoverflow.com/a/50159273/5004662.
server._session.trust_env = False
# Setup request retries.
adapter = HTTPAdapter(
max_retries=Retry(
total=self.max_retries,
backoff_factor=1,
status_forcelist=[429, 500, 502, 503, 504],
)
)
server._session.mount("http://", adapter)
server._session.mount("https://", adapter)
server.auth.sign_in(authentication)
return server
except ServerResponseError as e:
if isinstance(authentication, PersonalAccessTokenAuth):
# Docs on token expiry in Tableau:
# https://help.tableau.com/current/server/en-us/security_personal_access_tokens.htm#token-expiry
logger.info(
"Error authenticating with Tableau. Note that Tableau personal access tokens "
"expire if not used for 15 days or if over 1 year old"
)
raise ValueError(
f"Unable to login (invalid/expired credentials or missing permissions): {str(e)}"
) from e
except Exception as e:
raise ValueError(
f"Unable to login (check your Tableau connection and credentials): {str(e)}"
) from e
class TableauConfig(
DatasetLineageProviderConfigBase,
StatefulIngestionConfigBase,
DatasetSourceConfigMixin,
TableauConnectionConfig,
):
projects: Optional[List[str]] = Field(
default=["default"],
description="[deprecated] Use project_pattern instead. List of tableau "
"projects ",
)
_deprecate_projects = pydantic_field_deprecated("projects")
# Tableau project pattern
project_pattern: AllowDenyPattern = Field(
default=AllowDenyPattern.allow_all(),
description="Filter for specific Tableau projects. For example, use 'My Project' to ingest a root-level Project with name 'My Project', or 'My Project/Nested Project' to ingest a nested Project with name 'Nested Project'. "
"By default, all Projects nested inside a matching Project will be included in ingestion. "
"You can both allow and deny projects based on their name using their name, or a Regex pattern. "
"Deny patterns always take precedence over allow patterns. "
"By default, all projects will be ingested.",
)
project_path_separator: str = Field(
default="/",
description="The separator used for the project_pattern field between project names. By default, we use a slash. "
"You can change this if your Tableau projects contain slashes in their names, and you'd like to filter by project.",
)
default_schema_map: Dict[str, str] = Field(
default={}, description="Default schema to use when schema is not found."
)
ingest_tags: Optional[bool] = Field(
default=False,
description="Ingest Tags from source. This will override Tags entered from UI",
)
ingest_owner: Optional[bool] = Field(
default=False,
description="Ingest Owner from source. This will override Owner info entered from UI",
)
ingest_tables_external: bool = Field(
default=False,
description="Ingest details for tables external to (not embedded in) tableau as entities.",
)
page_size: int = Field(
default=10,
description="[advanced] Number of metadata objects (e.g. CustomSQLTable, PublishedDatasource, etc) to query at a time using the Tableau API.",
)
# We've found that even with a small workbook page size (e.g. 10), the Tableau API often
# returns warnings like this:
# {
# 'message': 'Showing partial results. The request exceeded the 20000 node limit. Use pagination, additional filtering, or both in the query to adjust results.',
# 'extensions': {
# 'severity': 'WARNING',
# 'code': 'NODE_LIMIT_EXCEEDED',
# 'properties': {
# 'nodeLimit': 20000
# }
# }
# }
# Reducing the page size for the workbook queries helps to avoid this.
workbook_page_size: int = Field(
default=1,
description="[advanced] Number of workbooks to query at a time using the Tableau API.",
)
env: str = Field(
default=builder.DEFAULT_ENV,
description="Environment to use in namespace when constructing URNs.",
)
lineage_overrides: Optional[TableauLineageOverrides] = Field(
default=None,
description="Mappings to change generated dataset urns. Use only if you really know what you are doing.",
)
database_hostname_to_platform_instance_map: Optional[Dict[str, str]] = Field(
default=None,
description="Mappings to change platform instance in generated dataset urns based on database. Use only if you really know what you are doing.",
)
extract_usage_stats: bool = Field(
default=False,
description="[experimental] Extract usage statistics for dashboards and charts.",
)
stateful_ingestion: Optional[StatefulStaleMetadataRemovalConfig] = Field(
default=None, description=""
)
ingest_embed_url: Optional[bool] = Field(
default=False,
description="Ingest a URL to render an embedded Preview of assets within Tableau.",
)
ingest_external_links_for_dashboards: Optional[bool] = Field(
default=True,
description="Ingest a URL to link out to from dashboards.",
)
ingest_external_links_for_charts: Optional[bool] = Field(
default=True,
description="Ingest a URL to link out to from charts.",
)
extract_project_hierarchy: bool = Field(
default=True,
description="Whether to extract entire project hierarchy for nested projects.",
)
extract_lineage_from_unsupported_custom_sql_queries: bool = Field(
default=False,
description="[Experimental] Whether to extract lineage from unsupported custom sql queries using SQL parsing",
)
force_extraction_of_lineage_from_custom_sql_queries: bool = Field(
default=False,
description="[Experimental] Force extraction of lineage from custom sql queries using SQL parsing, ignoring Tableau metadata",
)
sql_parsing_disable_schema_awareness: bool = Field(
default=False,
description="[Experimental] Ignore pre ingested tables schemas during parsing of SQL queries "
"(allows to workaround ingestion errors when pre ingested schema and queries are out of sync)",
)
ingest_multiple_sites: bool = Field(
False,
description="When enabled, ingests multiple sites the user has access to. If the user doesn't have access to the default site, specify an initial site to query in the site property. By default all sites the user has access to will be ingested. You can filter sites with the site_name_pattern property. This flag is currently only supported for Tableau Server. Tableau Cloud is not supported.",
)
site_name_pattern: AllowDenyPattern = Field(
default=AllowDenyPattern.allow_all(),
description="Filter for specific Tableau sites. "
"By default, all sites will be included in the ingestion. "
"You can both allow and deny sites based on their name using their name, or a Regex pattern. "
"Deny patterns always take precedence over allow patterns. "
"This property is currently only supported for Tableau Server. Tableau Cloud is not supported. ",
)
add_site_container: bool = Field(
False,
description="When enabled, sites are added as containers and therefore visible in the folder structure within Datahub.",
)
# pre = True because we want to take some decision before pydantic initialize the configuration to default values
@root_validator(pre=True)
def projects_backward_compatibility(cls, values: Dict) -> Dict:
projects = values.get("projects")
project_pattern = values.get("project_pattern")
if project_pattern is None and projects:
logger.warning(
"project_pattern is not set but projects is set. projects is deprecated, please use "
"project_pattern instead."
)
logger.info("Initializing project_pattern from projects")
values["project_pattern"] = AllowDenyPattern(
allow=[f"^{prj}$" for prj in projects]
)
elif project_pattern != AllowDenyPattern.allow_all() and projects:
raise ValueError("projects is deprecated. Please use project_pattern only.")
return values
class WorkbookKey(ContainerKey):
workbook_id: str
class ProjectKey(ContainerKey):
project_id: str
class SiteKey(ContainerKey):
site_id: str
@dataclass
class UsageStat:
view_count: int
@dataclass
class TableauProject:
id: str
name: str
description: str
parent_id: Optional[str]
parent_name: Optional[str] # Name of parent project
path: List[str]
@dataclass
class DatabaseTable:
"""
Corresponds to unique database table identified by DataHub.
It is possible for logically table to be represented by different instances of [databaseTable]
(https://help.tableau.com/current/api/metadata_api/en-us/reference/databasetable.doc.html)
if Tableau can not identify them as same table (e.g. in Custom SQLs). Assuming that, all such
instances will generate same URN in DataHub, this class captures group all databaseTable instances,
that the URN represents - all browse paths and id of most informative (with columns) instance.
"""
urn: str
id: Optional[
str
] = None # is not None only for tables that came from Tableau metadata
num_cols: Optional[int] = None
paths: Optional[
Set[str]
] = None # maintains all browse paths encountered for this table
parsed_columns: Optional[
Set[str]
] = None # maintains all columns encountered for this table during parsing SQL queries
def update_table(
self,
id: Optional[str] = None,
num_tbl_cols: Optional[int] = None,
path: Optional[str] = None,
parsed_columns: Optional[Set[str]] = None,
) -> None:
if path:
if self.paths:
self.paths.add(path)
else:
self.paths = {path}
# the new instance of table has columns information, prefer its id.
if not self.num_cols and num_tbl_cols:
self.id = id
self.num_cols = num_tbl_cols
if parsed_columns:
if self.parsed_columns:
self.parsed_columns.update(parsed_columns)
else:
self.parsed_columns = parsed_columns
class TableauSourceReport(StaleEntityRemovalSourceReport):
get_all_datasources_query_failed: bool = False
num_get_datasource_query_failures: int = 0
num_datasource_field_skipped_no_name: int = 0
num_csql_field_skipped_no_name: int = 0
num_table_field_skipped_no_name: int = 0
num_upstream_table_skipped_no_name: int = 0
@platform_name("Tableau")
@config_class(TableauConfig)
@support_status(SupportStatus.CERTIFIED)
@capability(SourceCapability.PLATFORM_INSTANCE, "Enabled by default")
@capability(SourceCapability.DOMAINS, "Requires transformer", supported=False)
@capability(SourceCapability.DESCRIPTIONS, "Enabled by default")
@capability(
SourceCapability.USAGE_STATS,
"Dashboard/Chart view counts, enabled using extract_usage_stats config",
)
@capability(
SourceCapability.DELETION_DETECTION,
"Enabled by default when stateful ingestion is turned on.",
)
@capability(SourceCapability.OWNERSHIP, "Requires recipe configuration")
@capability(SourceCapability.TAGS, "Requires recipe configuration")
@capability(SourceCapability.LINEAGE_COARSE, "Enabled by default")
@capability(
SourceCapability.LINEAGE_FINE,
"Enabled by default, configure using `extract_column_level_lineage`",
)
class TableauSource(StatefulIngestionSourceBase, TestableSource):
platform = "tableau"
def __hash__(self):
return id(self)
def __init__(
self,
config: TableauConfig,
ctx: PipelineContext,
):
super().__init__(config, ctx)
self.config: TableauConfig = config
self.report: TableauSourceReport = TableauSourceReport()
self.server: Optional[Server] = None
self._authenticate(self.config.site)
def _authenticate(self, site_content_url: str) -> None:
try:
logger.info(f"Authenticated to Tableau site: '{site_content_url}'")
self.server = self.config.make_tableau_client(site_content_url)
# Note that we're not catching ConfigurationError, since we want that to throw.
except ValueError as e:
self.report.failure(
title="Tableau Login Error",
message="Failed to authenticate with Tableau.",
exc=e,
)
@staticmethod
def test_connection(config_dict: dict) -> TestConnectionReport:
test_report = TestConnectionReport()
try:
source_config = TableauConfig.parse_obj_allow_extras(config_dict)
source_config.make_tableau_client(source_config.site)
test_report.basic_connectivity = CapabilityReport(capable=True)
except Exception as e:
test_report.basic_connectivity = CapabilityReport(
capable=False, failure_reason=str(e)
)
return test_report
def get_report(self) -> TableauSourceReport:
return self.report
@classmethod
def create(cls, config_dict: dict, ctx: PipelineContext) -> Source:
config = TableauConfig.parse_obj(config_dict)
return cls(config, ctx)
def get_workunit_processors(self) -> List[Optional[MetadataWorkUnitProcessor]]:
return [
*super().get_workunit_processors(),
StaleEntityRemovalHandler.create(
self, self.config, self.ctx
).workunit_processor,
]
def get_workunits_internal(self) -> Iterable[MetadataWorkUnit]:
if self.server is None or not self.server.is_signed_in():
return
try:
if self.config.ingest_multiple_sites:
for site in list(TSC.Pager(self.server.sites)):
if (
site.state != "Active"
or not self.config.site_name_pattern.allowed(site.name)
):
logger.info(
f"Skip site '{site.name}' as it's excluded in site_name_pattern or inactive."
)
continue
self.server.auth.switch_site(site)
site_source = TableauSiteSource(
config=self.config,
ctx=self.ctx,
site=site,
report=self.report,
server=self.server,
platform=self.platform,
)
logger.info(f"Ingesting assets of site '{site.content_url}'.")
yield from site_source.ingest_tableau_site()
else:
site = self.server.sites.get_by_id(self.server.site_id)
site_source = TableauSiteSource(
config=self.config,
ctx=self.ctx,
site=site,
report=self.report,
server=self.server,
platform=self.platform,
)
yield from site_source.ingest_tableau_site()
except MetadataQueryException as md_exception:
self.report.failure(
title="Failed to Retrieve Tableau Metadata",
message="Unable to retrieve metadata from tableau.",
context=str(md_exception),
)
def close(self) -> None:
try:
if self.server is not None:
self.server.auth.sign_out()
except Exception as ex:
logger.warning(
"During graceful closing of Tableau source a sign-out call was tried but ended up with"
" an Exception (%s). Continuing closing of the source",
ex,
)
self.server = None
super().close()
class TableauSiteSource:
def __init__(
self,
config: TableauConfig,
ctx: PipelineContext,
site: SiteItem,
report: TableauSourceReport,
server: Server,
platform: str,
):
self.config: TableauConfig = config
self.report = report
self.server: Server = server
self.ctx: PipelineContext = ctx
self.site: SiteItem = site
self.platform = platform
self.database_tables: Dict[str, DatabaseTable] = {}
self.tableau_stat_registry: Dict[str, UsageStat] = {}
self.tableau_project_registry: Dict[str, TableauProject] = {}
self.workbook_project_map: Dict[str, str] = {}
self.datasource_project_map: Dict[str, str] = {}
# This map keeps track of the database server connection hostnames.
self.database_server_hostname_map: Dict[str, str] = {}
# This list keeps track of sheets in workbooks so that we retrieve those
# when emitting sheets.
self.sheet_ids: List[str] = []
# This list keeps track of dashboards in workbooks so that we retrieve those
# when emitting dashboards.
self.dashboard_ids: List[str] = []
# This list keeps track of embedded datasources in workbooks so that we retrieve those
# when emitting embedded data sources.
self.embedded_datasource_ids_being_used: List[str] = []
# This list keeps track of datasource being actively used by workbooks so that we only retrieve those
# when emitting published data sources.
self.datasource_ids_being_used: List[str] = []
# This list keeps track of datasource being actively used by workbooks so that we only retrieve those
# when emitting custom SQL data sources.
self.custom_sql_ids_being_used: List[str] = []
@property
def no_env_browse_prefix(self) -> str:
# Prefix to use with browse path (v1)
# This is for charts and dashboards.
platform_with_instance = (
f"{self.platform}/{self.config.platform_instance}"
if self.config.platform_instance
else self.platform
)
return f"/{platform_with_instance}{self.site_name_browse_path}"
@property
def site_name_browse_path(self) -> str:
site_name_prefix = (
self.site.name if self.site and self.config.add_site_container else ""
)
return f"/{site_name_prefix}" if site_name_prefix else ""
@property
def dataset_browse_prefix(self) -> str:
# datasets also have the env in the browse path
return f"/{self.config.env.lower()}{self.no_env_browse_prefix}"
def _re_authenticate(self):
tableau_auth: Union[
TableauAuth, PersonalAccessTokenAuth
] = self.config.get_tableau_auth(self.site.content_url)
self.server.auth.sign_in(tableau_auth)
def _populate_usage_stat_registry(self) -> None:
if self.server is None:
return
view: TSC.ViewItem
for view in TSC.Pager(self.server.views, usage=True):
if not view.id:
continue
self.tableau_stat_registry[view.id] = UsageStat(view_count=view.total_views)
logger.debug("Tableau stats %s", self.tableau_stat_registry)
def _populate_database_server_hostname_map(self) -> None:
def maybe_parse_hostname():
# If the connection string is a URL instead of a hostname, parse it
# and extract the hostname, otherwise just return the connection string.
parsed_host_name = urlparse(server_connection).hostname
if parsed_host_name:
return parsed_host_name
return server_connection
for database_server in self.get_connection_objects(
database_servers_graphql_query, c.DATABASE_SERVERS_CONNECTION
):
database_server_id = database_server.get(c.ID)
server_connection = database_server.get(c.HOST_NAME)
host_name = maybe_parse_hostname()
if host_name:
self.database_server_hostname_map[str(database_server_id)] = host_name
def _get_all_project(self) -> Dict[str, TableauProject]:
all_project_map: Dict[str, TableauProject] = {}
def fetch_projects():
if self.server is None:
return all_project_map
for project in TSC.Pager(self.server.projects):
all_project_map[project.id] = TableauProject(
id=project.id,
name=project.name,
parent_id=project.parent_id,
parent_name=None,
description=project.description,
path=[],
)
# Set parent project name
for _project_id, project in all_project_map.items():
if (
project.parent_id is not None
and project.parent_id in all_project_map
):
project.parent_name = all_project_map[project.parent_id].name
def set_project_path():
def form_path(project_id: str) -> List[str]:
cur_proj = all_project_map[project_id]
ancestors = [cur_proj.name]
while cur_proj.parent_id is not None:
if cur_proj.parent_id not in all_project_map:
self.report.report_warning(
"project-issue",
f"Parent project {cur_proj.parent_id} not found. We need Site Administrator Explorer permissions.",
)
break
cur_proj = all_project_map[cur_proj.parent_id]
ancestors = [cur_proj.name, *ancestors]
return ancestors
for project in all_project_map.values():
project.path = form_path(project_id=project.id)
logger.debug(f"Project {project.name}({project.id})")
logger.debug(f"Project path = {project.path}")
fetch_projects()
set_project_path()
return all_project_map
def _is_allowed_project(self, project: TableauProject) -> bool:
# Either project name or project path should exist in allow
is_allowed: bool = self.config.project_pattern.allowed(
project.name
) or self.config.project_pattern.allowed(self._get_project_path(project))
if is_allowed is False:
logger.info(
f"project({project.name}) is not allowed as per project_pattern"
)
return is_allowed
def _is_denied_project(self, project: TableauProject) -> bool:
# Either project name or project path should exist in deny
for deny_pattern in self.config.project_pattern.deny:
# Either name or project path is denied
if re.match(
deny_pattern, project.name, self.config.project_pattern.regex_flags
) or re.match(
deny_pattern,
self._get_project_path(project),
self.config.project_pattern.regex_flags,
):
return True
logger.info(f"project({project.name}) is not denied as per project_pattern")
return False
def _init_tableau_project_registry(self, all_project_map: dict) -> None:
list_of_skip_projects: List[TableauProject] = []
projects_to_ingest = {}
for project in all_project_map.values():
# Skip project if it is not allowed
logger.debug(f"Evaluating project pattern for {project.name}")
if self._is_allowed_project(project) is False:
list_of_skip_projects.append(project)
logger.debug(f"Project {project.name} is skipped")
continue
logger.debug(f"Project {project.name} is added in project registry")
projects_to_ingest[project.id] = project
# We rely on automatic browse paths (v2) when creating containers. That's why we need to sort the projects here.
# Otherwise, nested projects will not have the correct browse paths if not created in correct order / hierarchy.
self.tableau_project_registry = OrderedDict(
sorted(projects_to_ingest.items(), key=lambda item: len(item[1].path))
)
if self.config.extract_project_hierarchy is False:
logger.debug(
"Skipping project hierarchy processing as configuration extract_project_hierarchy is "
"disabled"
)
return
logger.debug("Reevaluating projects as extract_project_hierarchy is enabled")
for project in list_of_skip_projects:
if (
project.parent_id in self.tableau_project_registry
and self._is_denied_project(project) is False
):
logger.debug(f"Project {project.name} is added in project registry")
self.tableau_project_registry[project.id] = project
def _init_datasource_registry(self) -> None:
if self.server is None:
return
try:
for ds in TSC.Pager(self.server.datasources):
if ds.project_id not in self.tableau_project_registry:
logger.debug(
f"project id ({ds.project_id}) of datasource {ds.name} is not present in project "
f"registry"
)
continue
self.datasource_project_map[ds.id] = ds.project_id
except Exception as e:
self.report.get_all_datasources_query_failed = True
logger.info(f"Get all datasources query failed due to error {e}")
logger.debug("Error stack trace", exc_info=True)
def _init_workbook_registry(self) -> None:
if self.server is None:
return
for wb in TSC.Pager(self.server.workbooks):
if wb.project_id not in self.tableau_project_registry:
logger.debug(
f"project id ({wb.project_id}) of workbook {wb.name} is not present in project "
f"registry"
)
continue
self.workbook_project_map[wb.id] = wb.project_id
def _populate_projects_registry(self) -> None:
if self.server is None:
return
logger.info("Initializing site project registry")
all_project_map: Dict[str, TableauProject] = self._get_all_project()
self._init_tableau_project_registry(all_project_map)
self._init_datasource_registry()
self._init_workbook_registry()
logger.debug(f"All site projects {all_project_map}")
logger.debug(f"Projects selected for ingestion {self.tableau_project_registry}")
logger.debug(
f"Tableau data-sources {self.datasource_project_map}",
)
logger.debug(
f"Tableau workbooks {self.workbook_project_map}",
)
def get_data_platform_instance(self) -> DataPlatformInstanceClass:
return DataPlatformInstanceClass(
platform=builder.make_data_platform_urn(self.platform),
instance=(
builder.make_dataplatform_instance_urn(
self.platform, self.config.platform_instance
)
if self.config.platform_instance
else None
),
)
def get_connection_object_page(
self,
query: str,
connection_type: str,
query_filter: str,
count: int = 0,
offset: int = 0,
retry_on_auth_error: bool = True,
retries_remaining: Optional[int] = None,
) -> Tuple[dict, int, int]:
retries_remaining = retries_remaining or self.config.max_retries
logger.debug(
f"Query {connection_type} to get {count} objects with offset {offset}"
f" and filter {query_filter}"
)
try:
assert self.server is not None
query_data = query_metadata(
self.server, query, connection_type, count, offset, query_filter
)
except REAUTHENTICATE_ERRORS:
if not retry_on_auth_error:
raise
# If ingestion has been running for over 2 hours, the Tableau
# temporary credentials will expire. If this happens, this exception
# will be thrown and we need to re-authenticate and retry.
self._re_authenticate()
return self.get_connection_object_page(
query,
connection_type,
query_filter,
count,
offset,
retry_on_auth_error=False,
retries_remaining=retries_remaining,