-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
nifi.py
1262 lines (1102 loc) · 48.8 KB
/
nifi.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 json
import logging
import ssl
import time
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from enum import Enum
from typing import Callable, Dict, Iterable, List, Optional, Tuple, Union
from urllib.parse import urljoin
import requests
from cached_property import cached_property
from dateutil import parser
from packaging import version
from pydantic import root_validator, validator
from pydantic.fields import Field
from requests import Response
from requests.adapters import HTTPAdapter
from requests.models import HTTPBasicAuth
from requests_gssapi import HTTPSPNEGOAuth
import datahub.emitter.mce_builder as builder
from datahub.configuration.common import AllowDenyPattern
from datahub.configuration.source_common import EnvConfigMixin
from datahub.emitter.mcp import MetadataChangeProposalWrapper
from datahub.emitter.mcp_builder import ContainerKey, gen_containers
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 Source, SourceCapability, SourceReport
from datahub.ingestion.api.workunit import MetadataWorkUnit
from datahub.ingestion.source.common.subtypes import JobContainerSubTypes
from datahub.metadata.schema_classes import (
BrowsePathEntryClass,
BrowsePathsV2Class,
DataFlowInfoClass,
DataJobInfoClass,
DataJobInputOutputClass,
DataPlatformInstanceClass,
DatasetPropertiesClass,
)
from datahub.specific.datajob import DataJobPatchBuilder
logger = logging.getLogger(__name__)
NIFI = "nifi"
# Python requests does not support passing password for key file,
# The same can be achieved by mounting ssl context
# as described here - https://github.com/psf/requests/issues/2519
# and here - https://github.com/psf/requests/issues/1573
class SSLAdapter(HTTPAdapter):
def __init__(self, certfile, keyfile, password=None):
self.context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
self.context.load_cert_chain(
certfile=certfile, keyfile=keyfile, password=password
)
super().__init__()
def init_poolmanager(self, *args, **kwargs):
kwargs["ssl_context"] = self.context
return super().init_poolmanager(*args, **kwargs)
class NifiAuthType(Enum):
NO_AUTH = "NO_AUTH"
SINGLE_USER = "SINGLE_USER"
CLIENT_CERT = "CLIENT_CERT"
KERBEROS = "KERBEROS"
BASIC_AUTH = "BASIC_AUTH"
class ProcessGroupKey(ContainerKey):
process_group_id: str
class NifiSourceConfig(EnvConfigMixin):
site_url: str = Field(
description="URL for Nifi, ending with /nifi/. e.g. https://mynifi.domain/nifi/"
)
auth: NifiAuthType = Field(
default=NifiAuthType.NO_AUTH,
description="Nifi authentication. must be one of : NO_AUTH, SINGLE_USER, CLIENT_CERT, KERBEROS",
)
provenance_days: int = Field(
default=7,
description="time window to analyze provenance events for external datasets",
) # Fetch provenance events for past 1 week
process_group_pattern: AllowDenyPattern = Field(
default=AllowDenyPattern.allow_all(),
description="regex patterns for filtering process groups",
)
# Required for nifi deployments using Remote Process Groups
site_name: str = Field(
default="default",
description="Site name to identify this site with, useful when using input and output ports receiving remote connections",
)
site_url_to_site_name: Dict[str, str] = Field(
default={},
description="Lookup to find site_name for site_url ending with /nifi/, required if using remote process groups in nifi flow",
)
# Required to be set if auth is of type SINGLE_USER
username: Optional[str] = Field(
default=None, description='Nifi username, must be set for auth = "SINGLE_USER"'
)
password: Optional[str] = Field(
default=None, description='Nifi password, must be set for auth = "SINGLE_USER"'
)
# Required to be set if auth is of type CLIENT_CERT
client_cert_file: Optional[str] = Field(
default=None,
description='Path to PEM file containing the public certificates for the user/client identity, must be set for auth = "CLIENT_CERT"',
)
client_key_file: Optional[str] = Field(
default=None, description="Path to PEM file containing the client’s secret key"
)
client_key_password: Optional[str] = Field(
default=None, description="The password to decrypt the client_key_file"
)
# Required to be set if nifi server certificate is not signed by
# root CA trusted by client system, e.g. self-signed certificates
ca_file: Optional[Union[bool, str]] = Field(
default=None,
description="Path to PEM file containing certs for the root CA(s) for the NiFi."
"Set to False to disable SSL verification.",
)
# As of now, container entities retrieval does not respect browsePathsV2 similar to container aspect.
# Consider enabling this when entities with browsePathsV2 pointing to container also get listed in container entities.
emit_process_group_as_container: bool = Field(
default=False,
description="Whether to emit Nifi process groups as container entities.",
)
incremental_lineage: bool = Field(
default=True,
description="When enabled, emits incremental/patch lineage for Nifi processors."
" When disabled, re-states lineage on each run.",
)
@root_validator(skip_on_failure=True)
def validate_auth_params(cla, values):
if values.get("auth") is NifiAuthType.CLIENT_CERT and not values.get(
"client_cert_file"
):
raise ValueError(
"Config `client_cert_file` is required for CLIENT_CERT auth"
)
elif values.get("auth") in (
NifiAuthType.SINGLE_USER,
NifiAuthType.BASIC_AUTH,
) and (not values.get("username") or not values.get("password")):
raise ValueError(
f"Config `username` and `password` is required for {values.get('auth').value} auth"
)
return values
@root_validator(skip_on_failure=True)
def validator_site_url_to_site_name(cls, values):
site_url_to_site_name = values.get("site_url_to_site_name")
site_url = values.get("site_url")
site_name = values.get("site_name")
if site_url_to_site_name is None:
site_url_to_site_name = {}
values["site_url_to_site_name"] = site_url_to_site_name
if site_url not in site_url_to_site_name:
site_url_to_site_name[site_url] = site_name
return values
@validator("site_url")
def validator_site_url(cls, site_url: str) -> str:
assert site_url.startswith(
("http://", "https://")
), "site_url must start with http:// or https://"
if not site_url.endswith("/"):
site_url = site_url + "/"
if not site_url.endswith("/nifi/"):
site_url = site_url + "nifi/"
return site_url
TOKEN_ENDPOINT = "access/token"
KERBEROS_TOKEN_ENDPOINT = "access/kerberos"
ABOUT_ENDPOINT = "flow/about"
CLUSTER_ENDPOINT = "flow/cluster/summary"
PG_ENDPOINT = "flow/process-groups/"
PROVENANCE_ENDPOINT = "provenance"
class NifiType(Enum):
PROCESSOR = "PROCESSOR"
FUNNEL = "FUNNEL"
INPUT_PORT = "INPUT_PORT"
OUTPUT_PORT = "OUTPUT_PORT"
REMOTE_INPUT_PORT = "REMOTE_INPUT_PORT"
REMOTE_OUTPUT_PORT = "REMOTE_OUTPUT_PORT"
class NifiEventType:
CREATE = "CREATE"
FETCH = "FETCH"
SEND = "SEND"
RECEIVE = "RECEIVE"
class NifiProcessorType:
ListS3 = "org.apache.nifi.processors.aws.s3.ListS3"
FetchS3Object = "org.apache.nifi.processors.aws.s3.FetchS3Object"
PutS3Object = "org.apache.nifi.processors.aws.s3.PutS3Object"
ListSFTP = "org.apache.nifi.processors.standard.ListSFTP"
FetchSFTP = "org.apache.nifi.processors.standard.FetchSFTP"
GetSFTP = "org.apache.nifi.processors.standard.GetSFTP"
PutSFTP = "org.apache.nifi.processors.standard.PutSFTP"
# To support new processor type,
# 1. add an entry in KNOWN_INGRESS_EGRESS_PROCESORS
# 2. Implement provenance event analyzer to find external dataset and
# map it in provenance_event_to_lineage_map
class NifiProcessorProvenanceEventAnalyzer:
env: str
KNOWN_INGRESS_EGRESS_PROCESORS = {
NifiProcessorType.ListS3: NifiEventType.CREATE,
NifiProcessorType.FetchS3Object: NifiEventType.FETCH,
NifiProcessorType.PutS3Object: NifiEventType.SEND,
NifiProcessorType.ListSFTP: NifiEventType.CREATE,
NifiProcessorType.FetchSFTP: NifiEventType.FETCH,
NifiProcessorType.GetSFTP: NifiEventType.RECEIVE,
NifiProcessorType.PutSFTP: NifiEventType.SEND,
}
def __init__(self) -> None:
# Map of Nifi processor type to the provenance event analyzer to find lineage
self.provenance_event_to_lineage_map: Dict[
str, Callable[[Dict], ExternalDataset]
] = {
NifiProcessorType.ListS3: self.process_s3_provenance_event,
NifiProcessorType.FetchS3Object: self.process_s3_provenance_event,
NifiProcessorType.PutS3Object: self.process_s3_provenance_event,
NifiProcessorType.ListSFTP: self.process_sftp_provenance_event,
NifiProcessorType.FetchSFTP: self.process_sftp_provenance_event,
NifiProcessorType.GetSFTP: self.process_sftp_provenance_event,
NifiProcessorType.PutSFTP: self.process_sftp_provenance_event,
}
def process_s3_provenance_event(self, event):
attributes = event.get("attributes", [])
s3_bucket = get_attribute_value(attributes, "s3.bucket")
s3_key = get_attribute_value(attributes, "s3.key")
if not s3_key:
s3_key = get_attribute_value(attributes, "filename")
s3_url = f"s3://{s3_bucket}/{s3_key}"
s3_url = s3_url[: s3_url.rindex("/")]
s3_path = s3_url[len("s3://") :]
dataset_name = s3_path.replace("/", ".")
platform = "s3"
dataset_urn = builder.make_dataset_urn(platform, s3_path, self.env)
return ExternalDataset(
platform,
dataset_name,
dict(s3_uri=s3_url),
dataset_urn,
)
def process_sftp_provenance_event(self, event):
attributes = event.get("attributes", [])
remote_host = get_attribute_value(attributes, "sftp.remote.host")
path = get_attribute_value(attributes, "path")
filename = get_attribute_value(attributes, "filename")
absolute_path = f"sftp://{remote_host}/{path}/{filename}"
if remote_host is None or path is None or filename is None:
absolute_path = event.get("transitUri")
absolute_path = absolute_path.replace("/./", "/")
if absolute_path.endswith("/."):
absolute_path = absolute_path[:-2]
absolute_path = absolute_path[: absolute_path.rindex("/")]
dataset_name = absolute_path.replace("sftp://", "").replace("/", ".")
platform = "file"
dataset_urn = builder.make_dataset_urn(platform, dataset_name, self.env)
return ExternalDataset(
platform,
dataset_name,
dict(uri=absolute_path),
dataset_urn,
)
@dataclass
class ExternalDataset:
platform: str
dataset_name: str
dataset_properties: Dict[str, str]
dataset_urn: str
@dataclass
class NifiComponent:
id: str
name: str
type: str
parent_group_id: str
nifi_type: NifiType
comments: Optional[str] = None
status: Optional[str] = None
# present only for nifi remote ports and processors
inlets: Dict[str, ExternalDataset] = field(default_factory=dict)
outlets: Dict[str, ExternalDataset] = field(default_factory=dict)
# present only for processors
config: Optional[Dict] = None
# present only for nifi remote ports
target_uris: Optional[str] = None
parent_rpg_id: Optional[str] = None
# Last successful event time
last_event_time: Optional[str] = None
@dataclass
class NifiProcessGroup:
id: str
name: str
parent_group_id: Optional[str]
@dataclass
class NifiRemoteProcessGroup:
id: str
name: str
parent_group_id: str
remote_ports: Dict[str, NifiComponent]
@dataclass
class NifiFlow:
version: Optional[str]
clustered: Optional[bool]
root_process_group: NifiProcessGroup
components: Dict[str, NifiComponent] = field(default_factory=dict)
remotely_accessible_ports: Dict[str, NifiComponent] = field(default_factory=dict)
connections: List[Tuple[str, str]] = field(default_factory=list)
processGroups: Dict[str, NifiProcessGroup] = field(default_factory=dict)
remoteProcessGroups: Dict[str, NifiRemoteProcessGroup] = field(default_factory=dict)
remote_ports: Dict[str, NifiComponent] = field(default_factory=dict)
def get_attribute_value(attr_lst: List[dict], attr_name: str) -> Optional[str]:
match = [entry for entry in attr_lst if entry["name"] == attr_name]
if len(match) > 0:
return match[0]["value"]
return None
@dataclass
class NifiSourceReport(SourceReport):
filtered: List[str] = field(default_factory=list)
def report_dropped(self, ent_name: str) -> None:
self.filtered.append(ent_name)
# allowRemoteAccess
@platform_name("NiFi", id="nifi")
@config_class(NifiSourceConfig)
@support_status(SupportStatus.CERTIFIED)
@capability(SourceCapability.LINEAGE_COARSE, "Supported. See docs for limitations")
class NifiSource(Source):
config: NifiSourceConfig
report: NifiSourceReport
def __init__(self, config: NifiSourceConfig, ctx: PipelineContext) -> None:
super().__init__(ctx)
self.config = config
self.report = NifiSourceReport()
self.session = requests.Session()
if self.config.ca_file is not None:
self.session.verify = self.config.ca_file
# To keep track of process groups (containers) which have already been ingested
# Required, as we do not ingest all process groups but only those that have known ingress/egress processors
self.processed_pgs: List[str] = []
@cached_property
def rest_api_base_url(self):
return self.config.site_url[: -len("nifi/")] + "nifi-api/"
@classmethod
def create(cls, config_dict: dict, ctx: PipelineContext) -> "Source":
config = NifiSourceConfig.parse_obj(config_dict)
return cls(config, ctx)
def get_report(self) -> SourceReport:
return self.report
def update_flow(self, pg_flow_dto: Dict) -> None: # noqa: C901
"""
Update self.nifi_flow with contents of the input process group `pg_flow_dto`
"""
breadcrumb_dto = pg_flow_dto.get("breadcrumb", {}).get("breadcrumb", {})
nifi_pg = NifiProcessGroup(
breadcrumb_dto.get("id"),
breadcrumb_dto.get("name"),
pg_flow_dto.get("parentGroupId"),
)
self.nifi_flow.processGroups[nifi_pg.id] = nifi_pg
if not self.config.process_group_pattern.allowed(nifi_pg.name):
self.report.report_dropped(f"{nifi_pg.name}.*")
return
flow_dto = pg_flow_dto.get("flow", {})
for processor in flow_dto.get("processors", []):
component = processor.get("component")
self.nifi_flow.components[component.get("id")] = NifiComponent(
component.get("id"),
component.get("name"),
component.get("type"),
component.get("parentGroupId"),
NifiType.PROCESSOR,
config=component.get("config"),
comments=component.get("config", {}).get("comments"),
status=component.get("status", {}).get("runStatus"),
)
for funnel in flow_dto.get("funnels", []):
component = funnel.get("component")
self.nifi_flow.components[component.get("id")] = NifiComponent(
component.get("id"),
component.get("name"),
component.get("type"),
component.get("parentGroupId"),
NifiType.FUNNEL,
comments=component.get("comments"),
status=component.get("status", {}).get("runStatus"),
)
logger.debug(f"Adding funnel {component.get('id')}")
for connection in flow_dto.get("connections", []):
# Exclude self - recursive relationships
if connection.get("sourceId") != connection.get("destinationId"):
self.nifi_flow.connections.append(
(connection.get("sourceId"), connection.get("destinationId"))
)
for inputPort in flow_dto.get("inputPorts", []):
component = inputPort.get("component")
if inputPort.get("allowRemoteAccess"):
self.nifi_flow.remotely_accessible_ports[
component.get("id")
] = NifiComponent(
component.get("id"),
component.get("name"),
component.get("type"),
component.get("parentGroupId"),
NifiType.INPUT_PORT,
comments=component.get("comments"),
status=component.get("status", {}).get("runStatus"),
)
logger.debug(f"Adding remotely accessible port {component.get('id')}")
else:
self.nifi_flow.components[component.get("id")] = NifiComponent(
component.get("id"),
component.get("name"),
component.get("type"),
component.get("parentGroupId"),
NifiType.INPUT_PORT,
comments=component.get("comments"),
status=component.get("status", {}).get("runStatus"),
)
logger.debug(f"Adding port {component.get('id')}")
for outputPort in flow_dto.get("outputPorts", []):
component = outputPort.get("component")
if outputPort.get("allowRemoteAccess"):
self.nifi_flow.remotely_accessible_ports[
component.get("id")
] = NifiComponent(
component.get("id"),
component.get("name"),
component.get("type"),
component.get("parentGroupId"),
NifiType.OUTPUT_PORT,
comments=component.get("comments"),
status=component.get("status", {}).get("runStatus"),
)
logger.debug(f"Adding remotely accessible port {component.get('id')}")
else:
self.nifi_flow.components[component.get("id")] = NifiComponent(
component.get("id"),
component.get("name"),
component.get("type"),
component.get("parentGroupId"),
NifiType.OUTPUT_PORT,
comments=component.get("comments"),
status=component.get("status", {}).get("runStatus"),
)
logger.debug(f"Adding report port {component.get('id')}")
for rpg in flow_dto.get("remoteProcessGroups", []):
rpg_component = rpg.get("component", {})
remote_ports = {}
contents = rpg_component.get("contents", {})
for component in contents.get("outputPorts", []):
if component.get("connected", False):
remote_ports[component.get("id")] = NifiComponent(
component.get("id"),
component.get("name"),
component.get("type"),
rpg_component.get("parentGroupId"),
NifiType.REMOTE_OUTPUT_PORT,
target_uris=rpg_component.get("targetUris"),
parent_rpg_id=rpg_component.get("id"),
comments=component.get("comments"),
status=component.get("status", {}).get("runStatus"),
)
logger.debug(f"Adding remote output port {component.get('id')}")
for component in contents.get("inputPorts", []):
if component.get("connected", False):
remote_ports[component.get("id")] = NifiComponent(
component.get("id"),
component.get("name"),
component.get("type"),
rpg_component.get("parentGroupId"),
NifiType.REMOTE_INPUT_PORT,
target_uris=rpg_component.get("targetUris"),
parent_rpg_id=rpg_component.get("id"),
comments=component.get("comments"),
status=component.get("status", {}).get("runStatus"),
)
logger.debug(f"Adding remote input port {component.get('id')}")
nifi_rpg = NifiRemoteProcessGroup(
rpg_component.get("id"),
rpg_component.get("name"),
component.get("parentGroupId"),
remote_ports,
)
logger.debug(f"Adding remote process group {rpg_component.get('id')}")
self.nifi_flow.components.update(remote_ports)
self.nifi_flow.remoteProcessGroups[nifi_rpg.id] = nifi_rpg
for pg in flow_dto.get("processGroups", []):
pg_response = self.session.get(
url=urljoin(self.rest_api_base_url, PG_ENDPOINT) + pg.get("id")
)
if not pg_response.ok:
self.report.warning(
"Failed to get process group flow " + pg.get("id"),
self.config.site_url,
)
continue
pg_flow_dto = pg_response.json().get("processGroupFlow", {})
self.update_flow(pg_flow_dto)
def update_flow_keep_only_ingress_egress(self):
components_to_del: List[NifiComponent] = []
for component in self.nifi_flow.components.values():
if (
component.nifi_type is NifiType.PROCESSOR
and component.type
not in NifiProcessorProvenanceEventAnalyzer.KNOWN_INGRESS_EGRESS_PROCESORS.keys()
) or component.nifi_type not in [
NifiType.PROCESSOR,
NifiType.REMOTE_INPUT_PORT,
NifiType.REMOTE_OUTPUT_PORT,
]:
components_to_del.append(component)
incoming = list(
filter(lambda x: x[1] == component.id, self.nifi_flow.connections)
)
outgoing = list(
filter(lambda x: x[0] == component.id, self.nifi_flow.connections)
)
# Create new connections from incoming to outgoing
for i in incoming:
for j in outgoing:
self.nifi_flow.connections.append((i[0], j[1]))
# Remove older connections, as we already created
# new connections bypassing component to be deleted
for i in incoming:
self.nifi_flow.connections.remove(i)
for j in outgoing:
self.nifi_flow.connections.remove(j)
for c in components_to_del:
if c.nifi_type is NifiType.PROCESSOR and (
c.name.startswith("Get")
or c.name.startswith("List")
or c.name.startswith("Fetch")
or c.name.startswith("Put")
):
self.report.warning(
f"Dropping NiFi Processor of type {c.type}, id {c.id}, name {c.name} from lineage view. \
This is likely an Ingress or Egress node which may be reading to/writing from external datasets \
However not currently supported in datahub",
self.config.site_url,
)
else:
logger.debug(
f"Dropping NiFi Component of type {c.type}, id {c.id}, name {c.name} from lineage view."
)
del self.nifi_flow.components[c.id]
def create_nifi_flow(self):
about_response = self.session.get(
url=urljoin(self.rest_api_base_url, ABOUT_ENDPOINT)
)
nifi_version: Optional[str] = None
if about_response.ok:
nifi_version = about_response.json().get("about", {}).get("version")
else:
logger.warning("Failed to fetch version for nifi")
cluster_response = self.session.get(
url=urljoin(self.rest_api_base_url, CLUSTER_ENDPOINT)
)
clustered: Optional[bool] = None
if cluster_response.ok:
clustered = (
cluster_response.json().get("clusterSummary", {}).get("clustered")
)
else:
logger.warning("Failed to fetch cluster summary for flow")
pg_response = self.session.get(
url=urljoin(self.rest_api_base_url, PG_ENDPOINT) + "root"
)
pg_response.raise_for_status()
pg_flow_dto = pg_response.json().get("processGroupFlow", {})
breadcrumb_dto = pg_flow_dto.get("breadcrumb", {}).get("breadcrumb", {})
self.nifi_flow = NifiFlow(
version=nifi_version,
clustered=clustered,
root_process_group=NifiProcessGroup(
breadcrumb_dto.get("id"),
breadcrumb_dto.get("name"),
pg_flow_dto.get("parentGroupId"),
),
)
self.update_flow(pg_flow_dto)
self.update_flow_keep_only_ingress_egress()
def fetch_provenance_events(
self,
processor: NifiComponent,
eventType: str,
startDate: datetime,
endDate: Optional[datetime] = None,
) -> Iterable[Dict]:
logger.debug(
f"Fetching {eventType} provenance events for {processor.id}\
of processor type {processor.type}, Start date: {startDate}, End date: {endDate}"
)
provenance_response = self.submit_provenance_query(
processor, eventType, startDate, endDate
)
if provenance_response.ok:
provenance = provenance_response.json().get("provenance", {})
provenance_uri = provenance.get("uri")
provenance_response = self.session.get(provenance_uri)
if provenance_response.ok:
provenance = provenance_response.json().get("provenance", {})
attempts = 5 # wait for at most 5 attempts 5*1= 5 seconds
while (not provenance.get("finished", False)) and attempts > 0:
logger.warning(
f"Provenance query not completed, attempts left : {attempts}"
)
# wait until the uri returns percentcomplete 100
time.sleep(1)
provenance_response = self.session.get(provenance_uri)
attempts -= 1
if provenance_response.ok:
provenance = provenance_response.json().get("provenance", {})
events = provenance.get("results", {}).get("provenanceEvents", [])
last_event_time: Optional[datetime] = None
oldest_event_time: Optional[datetime] = None
for event in events:
event_time = parser.parse(event.get("eventTime"))
# datetime.strptime(
# event.get("eventTime"), "%m/%d/%Y %H:%M:%S.%f %Z"
# )
if not last_event_time or event_time > last_event_time:
last_event_time = event_time
if not oldest_event_time or event_time < oldest_event_time:
oldest_event_time = event_time
yield event
processor.last_event_time = str(last_event_time)
self.delete_provenance(provenance_uri)
total = provenance.get("results", {}).get("total")
totalCount = provenance.get("results", {}).get("totalCount")
if total != str(totalCount):
yield from self.fetch_provenance_events(
processor, eventType, startDate, oldest_event_time
)
else:
self.report.warning(
f"Provenance events could not be fetched for processor \
{processor.id} of type {processor.name}",
self.config.site_url,
)
logger.warning(provenance_response.text)
return
def submit_provenance_query(self, processor, eventType, startDate, endDate):
older_version: bool = self.nifi_flow.version is not None and version.parse(
self.nifi_flow.version
) < version.parse("1.13.0")
if older_version:
searchTerms = {
"ProcessorID": processor.id,
"EventType": eventType,
}
else:
searchTerms = {
"ProcessorID": {"value": processor.id}, # type: ignore
"EventType": {"value": eventType}, # type: ignore
}
payload = json.dumps(
{
"provenance": {
"request": {
"maxResults": 1000,
"summarize": False,
"searchTerms": searchTerms,
"startDate": startDate.strftime("%m/%d/%Y %H:%M:%S %Z"),
"endDate": (
endDate.strftime("%m/%d/%Y %H:%M:%S %Z")
if endDate
else None
),
}
}
}
)
logger.debug(payload)
self.session.headers.update({})
self.session.headers.update({"Content-Type": "application/json"})
provenance_response = self.session.post(
url=urljoin(self.rest_api_base_url, PROVENANCE_ENDPOINT),
data=payload,
)
# Revert to default content-type if basic-auth
if self.config.auth is NifiAuthType.BASIC_AUTH:
self.session.headers.update(
{
"Content-Type": "application/x-www-form-urlencoded",
}
)
return provenance_response
def delete_provenance(self, provenance_uri):
delete_response = self.session.delete(provenance_uri)
if not delete_response.ok:
logger.error("failed to delete provenance ", provenance_uri)
def construct_workunits(self) -> Iterable[MetadataWorkUnit]: # noqa: C901
rootpg = self.nifi_flow.root_process_group
flow_name = rootpg.name # self.config.site_name
flow_urn = self.make_flow_urn()
flow_properties = {}
if self.nifi_flow.clustered is not None:
flow_properties["clustered"] = str(self.nifi_flow.clustered)
if self.nifi_flow.version is not None:
flow_properties["version"] = str(self.nifi_flow.version)
yield self.construct_flow_workunits(
flow_urn, flow_name, self.make_external_url(rootpg.id), flow_properties
)
for component in self.nifi_flow.components.values():
job_name = component.name
job_urn = builder.make_data_job_urn_with_flow(flow_urn, component.id)
incoming = list(
filter(lambda x: x[1] == component.id, self.nifi_flow.connections)
)
outgoing = list(
filter(lambda x: x[0] == component.id, self.nifi_flow.connections)
)
inputJobs = set()
jobProperties = None
if component.nifi_type is NifiType.PROCESSOR:
jobProperties = {
k: str(v)
for k, v in component.config.items() # type: ignore
if k
in [
"schedulingPeriod",
"schedulingStrategy",
"executionNode",
"concurrentlySchedulableTaskCount",
]
}
jobProperties["properties"] = json.dumps(
component.config.get("properties") # type: ignore
)
if component.last_event_time is not None:
jobProperties["last_event_time"] = component.last_event_time
for dataset in component.inlets.values():
yield from self.construct_dataset_workunits(
dataset.platform,
dataset.dataset_name,
dataset.dataset_urn,
datasetProperties=dataset.dataset_properties,
)
for dataset in component.outlets.values():
yield from self.construct_dataset_workunits(
dataset.platform,
dataset.dataset_name,
dataset.dataset_urn,
datasetProperties=dataset.dataset_properties,
)
for edge in incoming:
incoming_from = edge[0]
if incoming_from in self.nifi_flow.remotely_accessible_ports.keys():
dataset_name = f"{self.config.site_name}.{self.nifi_flow.remotely_accessible_ports[incoming_from].name}"
dataset_urn = builder.make_dataset_urn(
NIFI, dataset_name, self.config.env
)
component.inlets[dataset_urn] = ExternalDataset(
NIFI,
dataset_name,
dict(nifi_uri=self.config.site_url),
dataset_urn,
)
else:
inputJobs.add(
builder.make_data_job_urn_with_flow(flow_urn, incoming_from)
)
for edge in outgoing:
outgoing_to = edge[1]
if outgoing_to in self.nifi_flow.remotely_accessible_ports.keys():
dataset_name = f"{self.config.site_name}.{self.nifi_flow.remotely_accessible_ports[outgoing_to].name}"
dataset_urn = builder.make_dataset_urn(
NIFI, dataset_name, self.config.env
)
component.outlets[dataset_urn] = ExternalDataset(
NIFI,
dataset_name,
dict(nifi_uri=self.config.site_url),
dataset_urn,
)
if component.nifi_type is NifiType.REMOTE_INPUT_PORT:
# TODO - if target_uris is not set, but http proxy is used in RPG
site_urls = component.target_uris.split(",") # type: ignore
for site_url in site_urls:
if site_url not in self.config.site_url_to_site_name:
self.report.warning(
f"Site with url {site_url} is being used in flow but\
corresponding site name is not configured via site_url_to_site_name.\
This may result in broken lineage.",
site_url,
)
else:
site_name = self.config.site_url_to_site_name[site_url]
dataset_name = f"{site_name}.{component.name}"
dataset_urn = builder.make_dataset_urn(
NIFI, dataset_name, self.config.env
)
component.outlets[dataset_urn] = ExternalDataset(
NIFI, dataset_name, dict(nifi_uri=site_url), dataset_urn
)
break
if component.nifi_type is NifiType.REMOTE_OUTPUT_PORT:
site_urls = component.target_uris.split(",") # type: ignore
for site_url in site_urls:
if site_url not in self.config.site_url_to_site_name:
self.report.warning(
f"Site with url {site_url} is being used in flow but\
corresponding site name is not configured via site_url_to_site_name.\
This may result in broken lineage.",
self.config.site_url,
)
else:
site_name = self.config.site_url_to_site_name[site_url]
dataset_name = f"{site_name}.{component.name}"
dataset_urn = builder.make_dataset_urn(
NIFI, dataset_name, self.config.env
)
component.inlets[dataset_urn] = ExternalDataset(
NIFI, dataset_name, dict(nifi_uri=site_url), dataset_urn
)
break
if self.config.emit_process_group_as_container:
# We emit process groups only for all nifi components qualifying as datajobs
yield from self.construct_process_group_workunits(
component.parent_group_id
)
yield from self.construct_job_workunits(
job_urn,
job_name,
component.parent_group_id,
external_url=self.make_external_url(
component.parent_group_id, component.id, component.parent_rpg_id
),
job_type=NIFI.upper() + "_" + component.nifi_type.value,
description=component.comments,
job_properties=jobProperties,
inlets=list(component.inlets.keys()),
outlets=list(component.outlets.keys()),
inputJobs=list(inputJobs),
status=component.status,
)
for port in self.nifi_flow.remotely_accessible_ports.values():
dataset_name = f"{self.config.site_name}.{port.name}"
dataset_platform = NIFI
yield from self.construct_dataset_workunits(
dataset_platform,
dataset_name,
external_url=self.make_external_url(port.parent_group_id, port.id),
)
def make_flow_urn(self) -> str:
return builder.make_data_flow_urn(
NIFI, self.nifi_flow.root_process_group.id, self.config.env
)
def process_provenance_events(self):
startDate = datetime.now(timezone.utc) - timedelta(
days=self.config.provenance_days
)
eventAnalyzer = NifiProcessorProvenanceEventAnalyzer()
eventAnalyzer.env = self.config.env
for component in self.nifi_flow.components.values():
if component.nifi_type is NifiType.PROCESSOR:
eventType = eventAnalyzer.KNOWN_INGRESS_EGRESS_PROCESORS[component.type]
events = self.fetch_provenance_events(component, eventType, startDate)
for event in events:
dataset = eventAnalyzer.provenance_event_to_lineage_map[
component.type
](event)
if eventType in [
NifiEventType.CREATE,
NifiEventType.FETCH,
NifiEventType.RECEIVE,
]:
component.inlets[dataset.dataset_urn] = dataset
else:
component.outlets[dataset.dataset_urn] = dataset
def authenticate(self):
if self.config.auth is NifiAuthType.NO_AUTH: