-
Notifications
You must be signed in to change notification settings - Fork 88
/
Copy pathneo4j_proxy.py
1622 lines (1386 loc) · 72.1 KB
/
neo4j_proxy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright Contributors to the Amundsen project.
# SPDX-License-Identifier: Apache-2.0
import logging
import textwrap
import time
from random import randint
from typing import (Any, Dict, Iterable, List, Optional, Tuple, # noqa: F401
Union, no_type_check)
import neo4j
from amundsen_common.models.dashboard import DashboardSummary
from amundsen_common.models.lineage import Lineage, LineageItem
from amundsen_common.models.popular_table import PopularTable
from amundsen_common.models.table import (Application, Badge, Column,
ProgrammaticDescription, Reader,
Source, Stat, Table, Tag, User,
Watermark)
from amundsen_common.models.user import User as UserEntity
from amundsen_common.models.user import UserSchema
from beaker.cache import CacheManager
from beaker.util import parse_cache_config_options
from flask import current_app, has_app_context
from neo4j import BoltStatementResult, Driver, GraphDatabase # noqa: F401
from metadata_service import config
from metadata_service.entity.dashboard_detail import \
DashboardDetail as DashboardDetailEntity
from metadata_service.entity.dashboard_query import \
DashboardQuery as DashboardQueryEntity
from metadata_service.entity.description import Description
from metadata_service.entity.resource_type import ResourceType
from metadata_service.entity.tag_detail import TagDetail
from metadata_service.exception import NotFoundException
from metadata_service.proxy.base_proxy import BaseProxy
from metadata_service.proxy.statsd_utilities import timer_with_counter
from metadata_service.util import UserResourceRel
_CACHE = CacheManager(**parse_cache_config_options({'cache.type': 'memory'}))
# Expire cache every 11 hours + jitter
_GET_POPULAR_TABLE_CACHE_EXPIRY_SEC = 11 * 60 * 60 + randint(0, 3600)
CREATED_EPOCH_MS = 'publisher_created_epoch_ms'
LAST_UPDATED_EPOCH_MS = 'publisher_last_updated_epoch_ms'
PUBLISHED_TAG_PROPERTY_NAME = 'published_tag'
LOGGER = logging.getLogger(__name__)
class Neo4jProxy(BaseProxy):
"""
A proxy to Neo4j (Gateway to Neo4j)
"""
def __init__(self, *,
host: str,
port: int,
user: str = 'neo4j',
password: str = '',
num_conns: int = 50,
max_connection_lifetime_sec: int = 100,
encrypted: bool = False,
validate_ssl: bool = False,
**kwargs: dict) -> None:
"""
There's currently no request timeout from client side where server
side can be enforced via "dbms.transaction.timeout"
By default, it will set max number of connections to 50 and connection time out to 10 seconds.
:param endpoint: neo4j endpoint
:param num_conns: number of connections
:param max_connection_lifetime_sec: max life time the connection can have when it comes to reuse. In other
words, connection life time longer than this value won't be reused and closed on garbage collection. This
value needs to be smaller than surrounding network environment's timeout.
"""
endpoint = f'{host}:{port}'
LOGGER.info('NEO4J endpoint: {}'.format(endpoint))
trust = neo4j.TRUST_SYSTEM_CA_SIGNED_CERTIFICATES if validate_ssl else neo4j.TRUST_ALL_CERTIFICATES
self._driver = GraphDatabase.driver(endpoint, max_connection_pool_size=num_conns,
connection_timeout=10,
max_connection_lifetime=max_connection_lifetime_sec,
auth=(user, password),
encrypted=encrypted,
trust=trust) # type: Driver
def is_healthy(self) -> None:
# throws if cluster unhealthy or can't connect. An alternative would be to use one of
# the HTTP status endpoints, which might be more specific, but don't implicitly test
# our configuration.
with self._driver.session() as session:
session.read_transaction(self._execute_cypher_query,
statement='CALL dbms.cluster.overview()', param_dict={})
@timer_with_counter
def get_table(self, *, table_uri: str) -> Table:
"""
:param table_uri: Table URI
:return: A Table object
"""
cols, last_neo4j_record = self._exec_col_query(table_uri)
readers = self._exec_usage_query(table_uri)
wmk_results, table_writer, timestamp_value, owners, tags, source, badges, prog_descs = \
self._exec_table_query(table_uri)
table = Table(database=last_neo4j_record['db']['name'],
cluster=last_neo4j_record['clstr']['name'],
schema=last_neo4j_record['schema']['name'],
name=last_neo4j_record['tbl']['name'],
tags=tags,
badges=badges,
description=self._safe_get(last_neo4j_record, 'tbl_dscrpt', 'description'),
columns=cols,
owners=owners,
table_readers=readers,
watermarks=wmk_results,
table_writer=table_writer,
last_updated_timestamp=timestamp_value,
source=source,
is_view=self._safe_get(last_neo4j_record, 'tbl', 'is_view'),
programmatic_descriptions=prog_descs
)
return table
@timer_with_counter
def _exec_col_query(self, table_uri: str) -> Tuple:
# Return Value: (Columns, Last Processed Record)
column_level_query = textwrap.dedent("""
MATCH (db:Database)-[:CLUSTER]->(clstr:Cluster)-[:SCHEMA]->(schema:Schema)
-[:TABLE]->(tbl:Table {key: $tbl_key})-[:COLUMN]->(col:Column)
OPTIONAL MATCH (tbl)-[:DESCRIPTION]->(tbl_dscrpt:Description)
OPTIONAL MATCH (col:Column)-[:DESCRIPTION]->(col_dscrpt:Description)
OPTIONAL MATCH (col:Column)-[:STAT]->(stat:Stat)
OPTIONAL MATCH (col:Column)-[:HAS_BADGE]->(badge:Badge)
RETURN db, clstr, schema, tbl, tbl_dscrpt, col, col_dscrpt, collect(distinct stat) as col_stats,
collect(distinct badge) as col_badges
ORDER BY col.sort_order;""")
tbl_col_neo4j_records = self._execute_cypher_query(
statement=column_level_query, param_dict={'tbl_key': table_uri})
cols = []
last_neo4j_record = None
for tbl_col_neo4j_record in tbl_col_neo4j_records:
# Getting last record from this for loop as Neo4j's result's random access is O(n) operation.
col_stats = []
for stat in tbl_col_neo4j_record['col_stats']:
col_stat = Stat(
stat_type=stat['stat_type'],
stat_val=stat['stat_val'],
start_epoch=int(float(stat['start_epoch'])),
end_epoch=int(float(stat['end_epoch']))
)
col_stats.append(col_stat)
column_badges = self._make_badges(tbl_col_neo4j_record['col_badges'])
last_neo4j_record = tbl_col_neo4j_record
col = Column(name=tbl_col_neo4j_record['col']['name'],
description=self._safe_get(tbl_col_neo4j_record, 'col_dscrpt', 'description'),
col_type=tbl_col_neo4j_record['col']['col_type'],
sort_order=int(tbl_col_neo4j_record['col']['sort_order']),
stats=col_stats,
badges=column_badges)
cols.append(col)
if not cols:
raise NotFoundException('Table URI( {table_uri} ) does not exist'.format(table_uri=table_uri))
return sorted(cols, key=lambda item: item.sort_order), last_neo4j_record
@timer_with_counter
def _exec_usage_query(self, table_uri: str) -> List[Reader]:
# Return Value: List[Reader]
usage_query = textwrap.dedent("""\
MATCH (user:User)-[read:READ]->(table:Table {key: $tbl_key})
RETURN user.email as email, read.read_count as read_count, table.name as table_name
ORDER BY read.read_count DESC LIMIT 5;
""")
usage_neo4j_records = self._execute_cypher_query(statement=usage_query,
param_dict={'tbl_key': table_uri})
readers = [] # type: List[Reader]
for usage_neo4j_record in usage_neo4j_records:
reader = Reader(user=User(email=usage_neo4j_record['email']),
read_count=usage_neo4j_record['read_count'])
readers.append(reader)
return readers
@timer_with_counter
def _exec_table_query(self, table_uri: str) -> Tuple:
"""
Queries one Cypher record with watermark list, Application,
,timestamp, owner records and tag records.
"""
# Return Value: (Watermark Results, Table Writer, Last Updated Timestamp, owner records, tag records)
table_level_query = textwrap.dedent("""\
MATCH (tbl:Table {key: $tbl_key})
OPTIONAL MATCH (wmk:Watermark)-[:BELONG_TO_TABLE]->(tbl)
OPTIONAL MATCH (application:Application)-[:GENERATES]->(tbl)
OPTIONAL MATCH (tbl)-[:LAST_UPDATED_AT]->(t:Timestamp)
OPTIONAL MATCH (owner:User)<-[:OWNER]-(tbl)
OPTIONAL MATCH (tbl)-[:TAGGED_BY]->(tag:Tag{tag_type: $tag_normal_type})
OPTIONAL MATCH (tbl)-[:HAS_BADGE]->(badge:Badge)
OPTIONAL MATCH (tbl)-[:SOURCE]->(src:Source)
OPTIONAL MATCH (tbl)-[:DESCRIPTION]->(prog_descriptions:Programmatic_Description)
RETURN collect(distinct wmk) as wmk_records,
application,
t.last_updated_timestamp as last_updated_timestamp,
collect(distinct owner) as owner_records,
collect(distinct tag) as tag_records,
collect(distinct badge) as badge_records,
src,
collect(distinct prog_descriptions) as prog_descriptions
""")
table_records = self._execute_cypher_query(statement=table_level_query,
param_dict={'tbl_key': table_uri,
'tag_normal_type': 'default'})
table_records = table_records.single()
wmk_results = []
table_writer = None
wmk_records = table_records['wmk_records']
for record in wmk_records:
if record['key'] is not None:
watermark_type = record['key'].split('/')[-2]
wmk_result = Watermark(watermark_type=watermark_type,
partition_key=record['partition_key'],
partition_value=record['partition_value'],
create_time=record['create_time'])
wmk_results.append(wmk_result)
tags = []
if table_records.get('tag_records'):
tag_records = table_records['tag_records']
for record in tag_records:
tag_result = Tag(tag_name=record['key'],
tag_type=record['tag_type'])
tags.append(tag_result)
# this is for any badges added with BadgeAPI instead of TagAPI
badges = self._make_badges(table_records.get('badge_records'))
application_record = table_records['application']
if application_record is not None:
table_writer = Application(
application_url=application_record['application_url'],
description=application_record['description'],
name=application_record['name'],
id=application_record.get('id', '')
)
timestamp_value = table_records['last_updated_timestamp']
owner_record = []
for owner in table_records.get('owner_records', []):
owner_record.append(User(email=owner['email']))
src = None
if table_records['src']:
src = Source(source_type=table_records['src']['source_type'],
source=table_records['src']['source'])
prog_descriptions = self._extract_programmatic_descriptions_from_query(
table_records.get('prog_descriptions', [])
)
return wmk_results, table_writer, timestamp_value, owner_record, tags, src, badges, prog_descriptions
def _extract_programmatic_descriptions_from_query(self, raw_prog_descriptions: dict) -> list:
prog_descriptions = []
for prog_description in raw_prog_descriptions:
source = prog_description['description_source']
if source is None:
LOGGER.error("A programmatic description with no source was found... skipping.")
else:
prog_descriptions.append(ProgrammaticDescription(source=source, text=prog_description['description']))
prog_descriptions.sort(key=lambda x: x.source)
return prog_descriptions
@no_type_check
def _safe_get(self, dct, *keys):
"""
Helper method for getting value from nested dict. This also works either key does not exist or value is None.
:param dct:
:param keys:
:return:
"""
for key in keys:
dct = dct.get(key)
if dct is None:
return None
return dct
@timer_with_counter
def _execute_cypher_query(self, *,
statement: str,
param_dict: Dict[str, Any]) -> BoltStatementResult:
if LOGGER.isEnabledFor(logging.DEBUG):
LOGGER.debug('Executing Cypher query: {statement} with params {params}: '.format(statement=statement,
params=param_dict))
start = time.time()
try:
with self._driver.session() as session:
return session.run(statement, **param_dict)
finally:
# TODO: Add support on statsd
if LOGGER.isEnabledFor(logging.DEBUG):
LOGGER.debug('Cypher query execution elapsed for {} seconds'.format(time.time() - start))
# noinspection PyMethodMayBeStatic
def _make_badges(self, badges: Iterable) -> List[Badge]:
"""
Generates a list of Badges objects
:param badges: A list of badges of a table or a column
:return: a list of Badge objects
"""
_badges = []
for badge in badges:
_badges.append(Badge(badge_name=badge["key"], category=badge["category"]))
return _badges
@timer_with_counter
def _get_resource_description(self, *,
resource_type: ResourceType,
uri: str) -> Description:
"""
Get the resource description based on the uri. Any exception will propagate back to api server.
:param resource_type:
:param id:
:return:
"""
description_query = textwrap.dedent("""
MATCH (n:{node_label} {{key: $key}})-[:DESCRIPTION]->(d:Description)
RETURN d.description AS description;
""".format(node_label=resource_type.name))
result = self._execute_cypher_query(statement=description_query,
param_dict={'key': uri})
result = result.single()
return Description(description=result['description'] if result else None)
@timer_with_counter
def get_table_description(self, *,
table_uri: str) -> Union[str, None]:
"""
Get the table description based on table uri. Any exception will propagate back to api server.
:param table_uri:
:return:
"""
return self._get_resource_description(resource_type=ResourceType.Table, uri=table_uri).description
@timer_with_counter
def _put_resource_description(self, *,
resource_type: ResourceType,
uri: str,
description: str) -> None:
"""
Update table description with one from user
:param table_uri: Table uri (key in Neo4j)
:param description: new value for table description
"""
# start neo4j transaction
desc_key = uri + '/_description'
upsert_desc_query = textwrap.dedent("""
MERGE (u:Description {key: $desc_key})
on CREATE SET u={description: $description, key: $desc_key}
on MATCH SET u={description: $description, key: $desc_key}
""")
upsert_desc_tab_relation_query = textwrap.dedent("""
MATCH (n1:Description {{key: $desc_key}}), (n2:{node_label} {{key: $key}})
MERGE (n2)-[r2:DESCRIPTION]->(n1)
RETURN n1.key, n2.key
""".format(node_label=resource_type.name))
start = time.time()
try:
tx = self._driver.session().begin_transaction()
tx.run(upsert_desc_query, {'description': description,
'desc_key': desc_key})
result = tx.run(upsert_desc_tab_relation_query, {'desc_key': desc_key,
'key': uri})
if not result.single():
raise RuntimeError('Failed to update the resource {uri} description'.format(uri=uri))
# end neo4j transaction
tx.commit()
except Exception as e:
LOGGER.exception('Failed to execute update process')
if not tx.closed():
tx.rollback()
# propagate exception back to api
raise e
finally:
if LOGGER.isEnabledFor(logging.DEBUG):
LOGGER.debug('Update process elapsed for {} seconds'.format(time.time() - start))
@timer_with_counter
def put_table_description(self, *,
table_uri: str,
description: str) -> None:
"""
Update table description with one from user
:param table_uri: Table uri (key in Neo4j)
:param description: new value for table description
"""
self._put_resource_description(resource_type=ResourceType.Table,
uri=table_uri,
description=description)
@timer_with_counter
def get_column_description(self, *,
table_uri: str,
column_name: str) -> Union[str, None]:
"""
Get the column description based on table uri. Any exception will propagate back to api server.
:param table_uri:
:param column_name:
:return:
"""
column_description_query = textwrap.dedent("""
MATCH (tbl:Table {key: $tbl_key})-[:COLUMN]->(c:Column {name: $column_name})-[:DESCRIPTION]->(d:Description)
RETURN d.description AS description;
""")
result = self._execute_cypher_query(statement=column_description_query,
param_dict={'tbl_key': table_uri, 'column_name': column_name})
column_descrpt = result.single()
column_description = column_descrpt['description'] if column_descrpt else None
return column_description
@timer_with_counter
def put_column_description(self, *,
table_uri: str,
column_name: str,
description: str) -> None:
"""
Update column description with input from user
:param table_uri:
:param column_name:
:param description:
:return:
"""
column_uri = table_uri + '/' + column_name # type: str
desc_key = column_uri + '/_description'
upsert_desc_query = textwrap.dedent("""
MERGE (u:Description {key: $desc_key})
on CREATE SET u={description: $description, key: $desc_key}
on MATCH SET u={description: $description, key: $desc_key}
""")
upsert_desc_col_relation_query = textwrap.dedent("""
MATCH (n1:Description {key: $desc_key}), (n2:Column {key: $column_key})
MERGE (n2)-[r2:DESCRIPTION]->(n1)
RETURN n1.key, n2.key
""")
start = time.time()
try:
tx = self._driver.session().begin_transaction()
tx.run(upsert_desc_query, {'description': description,
'desc_key': desc_key})
result = tx.run(upsert_desc_col_relation_query, {'desc_key': desc_key,
'column_key': column_uri})
if not result.single():
raise RuntimeError('Failed to update the table {tbl} '
'column {col} description'.format(tbl=table_uri,
col=column_uri))
# end neo4j transaction
tx.commit()
except Exception as e:
LOGGER.exception('Failed to execute update process')
if not tx.closed():
tx.rollback()
# propagate error to api
raise e
finally:
if LOGGER.isEnabledFor(logging.DEBUG):
LOGGER.debug('Update process elapsed for {} seconds'.format(time.time() - start))
@timer_with_counter
def add_owner(self, *,
table_uri: str,
owner: str) -> None:
"""
Update table owner informations.
1. Do a create if not exists query of the owner(user) node.
2. Do a upsert of the owner/owned_by relation.
:param table_uri:
:param owner:
:return:
"""
create_owner_query = textwrap.dedent("""
MERGE (u:User {key: $user_email})
on CREATE SET u={email: $user_email, key: $user_email}
""")
upsert_owner_relation_query = textwrap.dedent("""
MATCH (n1:User {key: $user_email}), (n2:Table {key: $tbl_key})
MERGE (n1)-[r1:OWNER_OF]->(n2)-[r2:OWNER]->(n1)
RETURN n1.key, n2.key
""")
try:
tx = self._driver.session().begin_transaction()
# upsert the node
tx.run(create_owner_query, {'user_email': owner})
result = tx.run(upsert_owner_relation_query, {'user_email': owner,
'tbl_key': table_uri})
if not result.single():
raise RuntimeError('Failed to create relation between '
'owner {owner} and table {tbl}'.format(owner=owner,
tbl=table_uri))
tx.commit()
except Exception as e:
if not tx.closed():
tx.rollback()
# propagate the exception back to api
raise e
@timer_with_counter
def delete_owner(self, *,
table_uri: str,
owner: str) -> None:
"""
Delete the owner / owned_by relationship.
:param table_uri:
:param owner:
:return:
"""
delete_query = textwrap.dedent("""
MATCH (n1:User{key: $user_email}), (n2:Table {key: $tbl_key})
OPTIONAL MATCH (n1)-[r1:OWNER_OF]->(n2)
OPTIONAL MATCH (n2)-[r2:OWNER]->(n1)
DELETE r1,r2
""")
try:
tx = self._driver.session().begin_transaction()
tx.run(delete_query, {'user_email': owner,
'tbl_key': table_uri})
except Exception as e:
# propagate the exception back to api
if not tx.closed():
tx.rollback()
raise e
finally:
tx.commit()
@timer_with_counter
def add_badge(self, *,
id: str,
badge_name: str,
category: str = '',
resource_type: ResourceType) -> None:
LOGGER.info('New badge {} for id {} with category {} '
'and resource type {}'.format(badge_name, id, category, resource_type.name))
validation_query = \
'MATCH (n:{resource_type} {{key: $key}}) return n'.format(resource_type=resource_type.name)
upsert_badge_query = textwrap.dedent("""
MERGE (u:Badge {key: $badge_name})
on CREATE SET u={key: $badge_name, category: $category}
on MATCH SET u={key: $badge_name, category: $category}
""")
upsert_badge_relation_query = textwrap.dedent("""
MATCH(n1:Badge {{key: $badge_name, category: $category}}),
(n2:{resource_type} {{key: $key}})
MERGE (n1)-[r1:BADGE_FOR]->(n2)-[r2:HAS_BADGE]->(n1)
RETURN n1.key, n2.key
""".format(resource_type=resource_type.name))
try:
tx = self._driver.session().begin_transaction()
tbl_result = tx.run(validation_query, {'key': id})
if not tbl_result.single():
raise NotFoundException('id {} does not exist'.format(id))
tx.run(upsert_badge_query, {'badge_name': badge_name,
'category': category})
result = tx.run(upsert_badge_relation_query, {'badge_name': badge_name,
'key': id,
'category': category})
if not result.single():
raise RuntimeError('failed to create relation between '
'badge {badge} and resource {resource} of resource type '
'{resource_type} MORE {q}'.format(badge=badge_name,
resource=id,
resource_type=resource_type,
q=upsert_badge_relation_query))
tx.commit()
except Exception as e:
if not tx.closed():
tx.rollback()
raise e
@timer_with_counter
def delete_badge(self, id: str,
badge_name: str,
category: str,
resource_type: ResourceType) -> None:
# TODO for some reason when deleting it will say it was successful
# even when the badge never existed to begin with
LOGGER.info('Delete badge {} for id {} with category {}'.format(badge_name, id, category))
# only deletes relationshop between badge and resource
delete_query = textwrap.dedent("""
MATCH (b:Badge {{key:$badge_name, category:$category}})-
[r1:BADGE_FOR]->(n:{resource_type} {{key: $key}})-[r2:HAS_BADGE]->(b) DELETE r1,r2
""".format(resource_type=resource_type.name))
try:
tx = self._driver.session().begin_transaction()
tx.run(delete_query, {'badge_name': badge_name,
'key': id,
'category': category})
tx.commit()
except Exception as e:
# propagate the exception back to api
if not tx.closed():
tx.rollback()
raise e
@timer_with_counter
def get_badges(self) -> List:
LOGGER.info('Get all badges')
query = textwrap.dedent("""
MATCH (b:Badge) RETURN b as badge
""")
records = self._execute_cypher_query(statement=query,
param_dict={})
results = []
for record in records:
results.append(Badge(badge_name=record['badge']['key'],
category=record['badge']['category']))
return results
@timer_with_counter
def add_tag(self, *,
id: str,
tag: str,
tag_type: str = 'default',
resource_type: ResourceType = ResourceType.Table) -> None:
"""
Add new tag
1. Create the node with type Tag if the node doesn't exist.
2. Create the relation between tag and table if the relation doesn't exist.
:param id:
:param tag:
:param tag_type:
:param resource_type:
:return: None
"""
LOGGER.info('New tag {} for id {} with type {} and resource type {}'.format(tag, id, tag_type,
resource_type.name))
validation_query = \
'MATCH (n:{resource_type} {{key: $key}}) return n'.format(resource_type=resource_type.name)
upsert_tag_query = textwrap.dedent("""
MERGE (u:Tag {key: $tag})
on CREATE SET u={tag_type: $tag_type, key: $tag}
on MATCH SET u={tag_type: $tag_type, key: $tag}
""")
upsert_tag_relation_query = textwrap.dedent("""
MATCH (n1:Tag {{key: $tag, tag_type: $tag_type}}), (n2:{resource_type} {{key: $key}})
MERGE (n1)-[r1:TAG]->(n2)-[r2:TAGGED_BY]->(n1)
RETURN n1.key, n2.key
""".format(resource_type=resource_type.name))
try:
tx = self._driver.session().begin_transaction()
tbl_result = tx.run(validation_query, {'key': id})
if not tbl_result.single():
raise NotFoundException('id {} does not exist'.format(id))
# upsert the node
tx.run(upsert_tag_query, {'tag': tag,
'tag_type': tag_type})
result = tx.run(upsert_tag_relation_query, {'tag': tag,
'key': id,
'tag_type': tag_type})
if not result.single():
raise RuntimeError('Failed to create relation between '
'tag {tag} and resource {resource} of resource type: {resource_type}'
.format(tag=tag,
resource=id,
resource_type=resource_type.name))
tx.commit()
except Exception as e:
if not tx.closed():
tx.rollback()
# propagate the exception back to api
raise e
@timer_with_counter
def delete_tag(self, *,
id: str,
tag: str,
tag_type: str = 'default',
resource_type: ResourceType = ResourceType.Table) -> None:
"""
Deletes tag
1. Delete the relation between resource and the tag
2. todo(Tao): need to think about whether we should delete the tag if it is an orphan tag.
:param id:
:param tag:
:param tag_type: {default-> normal tag, badge->non writable tag from UI}
:param resource_type:
:return:
"""
LOGGER.info('Delete tag {} for id {} with type {} and resource type: {}'.format(tag, id,
tag_type, resource_type.name))
delete_query = textwrap.dedent("""
MATCH (n1:Tag{{key: $tag, tag_type: $tag_type}})-
[r1:TAG]->(n2:{resource_type} {{key: $key}})-[r2:TAGGED_BY]->(n1) DELETE r1,r2
""".format(resource_type=resource_type.name))
try:
tx = self._driver.session().begin_transaction()
tx.run(delete_query, {'tag': tag,
'key': id,
'tag_type': tag_type})
tx.commit()
except Exception as e:
# propagate the exception back to api
if not tx.closed():
tx.rollback()
raise e
@timer_with_counter
def get_tags(self) -> List:
"""
Get all existing tags from neo4j
:return:
"""
LOGGER.info('Get all the tags')
# todo: Currently all the tags are default type, we could open it up if we want to include badge
query = textwrap.dedent("""
MATCH (t:Tag{tag_type: 'default'})
OPTIONAL MATCH (resource)-[:TAGGED_BY]->(t)
WITH t as tag_name, count(distinct resource.key) as tag_count
WHERE tag_count > 0
RETURN tag_name, tag_count
""")
records = self._execute_cypher_query(statement=query,
param_dict={})
results = []
for record in records:
results.append(TagDetail(tag_name=record['tag_name']['key'],
tag_count=record['tag_count']))
return results
@timer_with_counter
def get_latest_updated_ts(self) -> Optional[int]:
"""
API method to fetch last updated / index timestamp for neo4j, es
:return:
"""
query = textwrap.dedent("""
MATCH (n:Updatedtimestamp{key: 'amundsen_updated_timestamp'}) RETURN n as ts
""")
record = self._execute_cypher_query(statement=query,
param_dict={})
# None means we don't have record for neo4j, es last updated / index ts
record = record.single()
if record:
return record.get('ts', {}).get('latest_timestamp', 0)
else:
return None
@timer_with_counter
def get_statistics(self) -> Dict[str, Any]:
"""
API method to fetch statistics metrics for neo4j
:return: dictionary of statistics
"""
query = textwrap.dedent("""
MATCH (table_node:Table) with count(table_node) as number_of_tables
MATCH p=(item_node)-[r:DESCRIPTION]->(description_node)
WHERE size(description_node.description)>2 and exists(item_node.is_view)
with count(item_node) as number_of_documented_tables, number_of_tables
MATCH p=(item_node)-[r:DESCRIPTION]->(description_node)
WHERE size(description_node.description)>2 and exists(item_node.sort_order)
with count(item_node) as number_of_documented_cols, number_of_documented_tables, number_of_tables
MATCH p=(table_node)-[r:OWNER]->(user_node) with count(distinct table_node) as number_of_tables_with_owners,
count(distinct user_node) as number_of_owners, number_of_documented_cols,
number_of_documented_tables, number_of_tables
MATCH (item_node)-[:DESCRIPTION]->(description_node)
WHERE size(description_node.description)>2 and exists(item_node.is_view)
MATCH (item_node)-[:OWNER]->(user_node)
with count(item_node) as number_of_documented_and_owned_tables,
number_of_tables_with_owners, number_of_owners, number_of_documented_cols,
number_of_documented_tables, number_of_tables
Return number_of_tables, number_of_documented_tables, number_of_documented_cols,
number_of_owners, number_of_tables_with_owners, number_of_documented_and_owned_tables
""")
LOGGER.info('Getting Neo4j Statistics')
records = self._execute_cypher_query(statement=query,
param_dict={})
for record in records:
neo4j_statistics = {'number_of_tables': record['number_of_tables'],
'number_of_documented_tables': record['number_of_documented_tables'],
'number_of_documented_cols': record['number_of_documented_cols'],
'number_of_owners': record['number_of_owners'],
'number_of_tables_with_owners': record['number_of_tables_with_owners'],
'number_of_documented_and_owned_tables': record['number_of_documented_and_owned_tables']
}
return neo4j_statistics
return {}
@_CACHE.cache('_get_global_popular_tables_uris', expire=_GET_POPULAR_TABLE_CACHE_EXPIRY_SEC)
def _get_global_popular_tables_uris(self, num_entries: int) -> List[str]:
"""
Retrieve popular table uris. Will provide tables with top x popularity score.
Popularity score = number of distinct readers * log(total number of reads)
The result of this method will be cached based on the key (num_entries), and the cache will be expired based on
_GET_POPULAR_TABLE_CACHE_EXPIRY_SEC
For score computation, it uses logarithm on total number of reads so that score won't be affected by small
number of users reading a lot of times.
:return: Iterable of table uri
"""
query = textwrap.dedent("""
MATCH (tbl:Table)-[r:READ_BY]->(u:User)
WITH tbl.key as table_key, count(distinct u) as readers, sum(r.read_count) as total_reads
WHERE readers >= $num_readers
RETURN table_key, readers, total_reads, (readers * log(total_reads)) as score
ORDER BY score DESC LIMIT $num_entries;
""")
LOGGER.info('Querying popular tables URIs')
num_readers = current_app.config['POPULAR_TABLE_MINIMUM_READER_COUNT']
records = self._execute_cypher_query(statement=query,
param_dict={'num_readers': num_readers,
'num_entries': num_entries})
return [record['table_key'] for record in records]
@timer_with_counter
@_CACHE.cache('_get_personal_popular_tables_uris', _GET_POPULAR_TABLE_CACHE_EXPIRY_SEC)
def _get_personal_popular_tables_uris(self, num_entries: int,
user_id: str) -> List[str]:
"""
Retrieve personalized popular table uris. Will provide tables with top
popularity score that have been read by a peer of the user_id provided.
The popularity score is defined in the same way as `_get_global_popular_tables_uris`
The result of this method will be cached based on the key (num_entries, user_id),
and the cache will be expired based on _GET_POPULAR_TABLE_CACHE_EXPIRY_SEC
:return: Iterable of table uri
"""
statement = textwrap.dedent("""
MATCH (:User {key:$user_id})<-[:READ_BY]-(:Table)-[:READ_BY]->
(coUser:User)<-[coRead:READ_BY]-(table:Table)
WITH table.key AS table_key, count(DISTINCT coUser) AS co_readers,
sum(coRead.read_count) AS total_co_reads
WHERE co_readers >= $num_readers
RETURN table_key, (co_readers * log(total_co_reads)) AS score
ORDER BY score DESC LIMIT $num_entries;
""")
LOGGER.info('Querying popular tables URIs')
num_readers = current_app.config['POPULAR_TABLE_MINIMUM_READER_COUNT']
records = self._execute_cypher_query(statement=statement,
param_dict={'user_id': user_id,
'num_readers': num_readers,
'num_entries': num_entries})
return [record['table_key'] for record in records]
@timer_with_counter
def get_popular_tables(self, *,
num_entries: int,
user_id: Optional[str] = None) -> List[PopularTable]:
"""
Retrieve popular tables. As popular table computation requires full scan of table and user relationship,
it will utilize cached method _get_popular_tables_uris.
:param num_entries:
:return: Iterable of PopularTable
"""
if user_id is None:
# Get global popular table URIs
table_uris = self._get_global_popular_tables_uris(num_entries)
else:
# Get personalized popular table URIs
table_uris = self._get_personal_popular_tables_uris(num_entries, user_id)
if not table_uris:
return []
query = textwrap.dedent("""
MATCH (db:Database)-[:CLUSTER]->(clstr:Cluster)-[:SCHEMA]->(schema:Schema)-[:TABLE]->(tbl:Table)
WHERE tbl.key IN $table_uris
WITH db.name as database_name, clstr.name as cluster_name, schema.name as schema_name, tbl
OPTIONAL MATCH (tbl)-[:DESCRIPTION]->(dscrpt:Description)
RETURN database_name, cluster_name, schema_name, tbl.name as table_name,
dscrpt.description as table_description;
""")
records = self._execute_cypher_query(statement=query,
param_dict={'table_uris': table_uris})
popular_tables = []
for record in records:
popular_table = PopularTable(database=record['database_name'],
cluster=record['cluster_name'],
schema=record['schema_name'],
name=record['table_name'],
description=self._safe_get(record, 'table_description'))
popular_tables.append(popular_table)
return popular_tables
@timer_with_counter
def get_user(self, *, id: str) -> Union[UserEntity, None]:
"""
Retrieve user detail based on user_id(email).
:param user_id: the email for the given user
:return:
"""
query = textwrap.dedent("""
MATCH (user:User {key: $user_id})
OPTIONAL MATCH (user)-[:MANAGE_BY]->(manager:User)
RETURN user as user_record, manager as manager_record
""")
record = self._execute_cypher_query(statement=query,
param_dict={'user_id': id})
single_result = record.single()
if not single_result:
raise NotFoundException('User {user_id} '
'not found in the graph'.format(user_id=id))