-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgdaTools.html
More file actions
945 lines (870 loc) · 43.7 KB
/
Copy pathgdaTools.html
File metadata and controls
945 lines (870 loc) · 43.7 KB
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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<meta name="generator" content="pdoc 0.7.5" />
<title>gdascore.gdaTools API documentation</title>
<meta name="description" content="" />
<link href='https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.0/normalize.min.css' rel='stylesheet'>
<link href='https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/8.0.0/sanitize.min.css' rel='stylesheet'>
<link href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/github.min.css" rel="stylesheet">
<style>.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:30px;overflow:hidden}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:1em 0 .50em 0}h3{font-size:1.4em;margin:25px 0 10px 0}h4{margin:0;font-size:105%}a{color:#058;text-decoration:none;transition:color .3s ease-in-out}a:hover{color:#e82}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900}pre code{background:#f8f8f8;font-size:.8em;line-height:1.4em}code{background:#f2f2f1;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{background:#f8f8f8;border:0;border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0;padding:1ex}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{font-weight:bold}#index h4 + ul{margin-bottom:.6em}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-weight:bold;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}.admonition{padding:.1em .5em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.item .name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul{padding-left:1.5em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<style>
</style>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>gdascore.gdaTools</code></h1>
</header>
<section id="section-intro">
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">import copy
import importlib.util
import json
import coloredlogs, logging
import math
import ntpath
import os
import pprint
import sys
coloredlogs.DEFAULT_FIELD_STYLES['asctime'] = {}
coloredlogs.DEFAULT_FIELD_STYLES['levelname'] = {'bold': True, 'color': 'white', 'bright': True}
coloredlogs.DEFAULT_LEVEL_STYLES['info'] = {'color': 'cyan', 'bright': True}
coloredlogs.install(
fmt="[%(levelname)s] %(message)s (%(filename)s, %(funcName)s(), line %(lineno)d, %(asctime)s)",
datefmt='%Y-%m-%d %H:%M',
level=logging.INFO,
)
# for pdoc documentation
__all__ = ["setupGdaAttackParameters"]
from pkg_resources import Requirement, resource_filename
def try_for_config_file(config_rel_path):
####### added by frzmohammadali #######
interested_file = ntpath.basename(config_rel_path)
# case 0: local config path defined by user: when installing by pip
global_config_variable = dict()
config_var = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'global_config', 'config_var.json')
if os.path.isfile(config_var):
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'global_config', 'config_var.json'), 'r') as f:
file_content = f.read()
if len(file_content):
global_config_variable = json.loads(file_content)
try:
potential_path = os.path.join(global_config_variable['config_path'], 'config', interested_file)
except KeyError:
# local config path has not been provided. should look into global_config in next step.
pass
else:
if os.path.isfile(potential_path):
return potential_path
# Case 0.5: global_config: when installing by pip
potential_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'global_config', interested_file)
if os.path.isfile(potential_path):
return potential_path
####### added by frzmohammadali #######
# First case: find config in repository; use paths in PATH and PYTHONPATH as potential repository root folders
for p in sys.path:
if os.path.isfile(os.path.abspath(os.path.join(p, config_rel_path))):
return os.path.abspath(os.path.join(p, config_rel_path))
if "PYTHONPATH" in os.environ:
for p in os.environ["PYTHONPATH"].split(os.pathsep):
if os.path.isfile(os.path.abspath(os.path.join(p, config_rel_path))):
return os.path.abspath(os.path.join(p, config_rel_path))
# Second case: find config inside pip package location
spec = importlib.util.find_spec("gda-score-code")
if spec is not None:
if os.path.isfile(os.path.abspath(resource_filename(Requirement.parse("gda-score-code"), config_rel_path))):
return os.path.abspath(resource_filename(Requirement.parse("gda-score-code"), config_rel_path))
# Third case: look in typical config file locations
if os.path.isfile(os.path.abspath(os.path.join(os.path.expanduser("~"), ".gdaScore", config_rel_path))):
return os.path.abspath(os.path.join(os.path.expanduser("~"), ".gdaScore", config_rel_path))
if os.path.isfile(os.path.abspath(os.path.join(os.sep, "etc", "gdaScore", config_rel_path))):
return os.path.abspath(os.path.join(os.sep, "etc", "gdaScore", config_rel_path))
# Fourth case: we find nothing
return None
def getDatabaseInfo(theDb):
# For backwards compatibility, if this is a string use the old way
if isinstance(theDb, str):
return oldGetDatabaseInfo(theDb)
# Get user name and password
### <OLD WAY> ###
# cred = getCredentials()
# theDb['password'] = cred[theDb['type']]['password']
# theDb['user'] = cred[theDb['type']]['user']
### </OLD WAY> ###
### <NEW WAY> ###
if theDb['type'] == "postgres":
if os.environ.get("GDA_SCORE_RAW_PASS") and os.environ.get("GDA_SCORE_RAW_USER"):
theDb['password'] = os.environ.get("GDA_SCORE_RAW_PASS")
theDb['user'] = os.environ.get("GDA_SCORE_RAW_USER")
else:
logging.critical("GDA_SCORE_RAW_USER and GDA_SCORE_RAW_PASS must be set as environment variables "
"for working with rawDB. see README.md")
sys.exit(0)
elif theDb['type'] == "aircloak":
if os.environ.get("GDA_SCORE_DIFFIX_PASS") and os.environ.get("GDA_SCORE_DIFFIX_USER"):
theDb['password'] = os.environ.get("GDA_SCORE_DIFFIX_PASS")
theDb['user'] = os.environ.get("GDA_SCORE_DIFFIX_USER")
else:
logging.critical("GDA_SCORE_DIFFIX_USER and GDA_SCORE_DIFFIX_PASS must be set as "
"environment variables for working with Aircloak database. see README.md")
sys.exit(0)
elif theDb['type'] == "uber_dp":
# uber_dp interface does not need a password or a username
theDb['password'] = "not_needed"
theDb['user'] = "not_needed"
### </NEW WAY> ###
return theDb
def oldGetDatabaseInfo(dbName):
''' Retrieves the database info from the database config file.
The path to the database config file must be hard-coded here.
'''
path = try_for_config_file(os.path.join("common", "config", "myDatabases.json"))
if path is None:
print(f"ERROR: No config file found")
return None
fh = open(path, "r")
j = json.load(fh)
if dbName in j:
return j[dbName]
else:
print(f"Error: Database '{dbName}' not found in file {path}")
return None
def getMasterConfig():
''' Retrieves master.json from the config file
The path to the database config file must be hard-coded here.
'''
path = try_for_config_file(os.path.join("common", "config", "master.json"))
if path is None:
print(f"ERROR: No config file found (master.json)")
return None
fh = open(path, "r")
j = json.load(fh)
return j
def getCredentials():
''' Retrieves master.json from the config file
The path to the database config file must be hard-coded here.
'''
path = try_for_config_file(os.path.join("common", "config", "myCredentials.json"))
if path is None:
print(f"ERROR: No config file found (myCredentials.json)")
return None
fh = open(path, "r")
j = json.load(fh)
return j
def getAnonDbs(master, anon, dbType):
if dbType == 'link':
databases = 'linkDatabases'
elif dbType == 'pub':
databases = 'pubDatabases'
else:
databases = 'databases'
nextLevel = 0
friendlyNames = [master['anonClasses']['friendlyName']]
pp = pprint.PrettyPrinter(indent=4)
if anon[nextLevel] not in master['anonClasses']:
return (None, friendlyNames, None)
nextDict = master['anonClasses'][anon[nextLevel]]
friendlyNames.append(nextDict['friendlyName'])
while True:
if databases in nextDict:
return (nextDict[databases], friendlyNames, nextDict['service'])
# databases isn't here, so need to look for next level
nextLevel += 1
if nextLevel > (len(anon) - 1):
return (None, friendlyNames, None)
if anon[nextLevel] not in nextDict:
return (None, friendlyNames, None)
nextDict = nextDict[anon[nextLevel]]
friendlyNames.append(nextDict['friendlyName'])
return (None, friendlyNames, None)
def getTab(sourceDbs, useableDbs):
for useDb in useableDbs:
if useDb in sourceDbs:
return useDb
return None
def setupGdaAttackParameters(configInfo=None, utilityMeasure='',
criteria='', attackType=''):
""" Basic prep for input and output of gdaAttack (attack or utility)
If called with no parameters, then this routine
reads a configuration file of the same name as the python file
but with `.json` appended. (I.e. if the python file is `test.py`,
then `test.py.json` is read.) <br/>
Otherwise, `configInfo` is a python dict. <br/>
Either way (json file or python dict), the basic structure of the
configuration is: <br/>
{
"configVersion": "compact1",
"basic": {
"attackType": "Simple List",
"criteria": "linkability"
},
"anonTypes": [
["no_anon"],
["diffix","latest"],
],
"tables": [
["banking","accounts"],
["taxi","rides"],
]
}
The above is for attacks. If utility measure, then the `"basic"`
contents may be for instance: <br/>
"basic": {
"utilityMeasure": "Single Column Count",
"measureParam":"uid",
"samples": 25,
"ranges": [[10,50],[50,100],[100,500],[500,1000],[1000,5000]]
},
Returns a list of data structures that can be used for
class `gdaAttack()`. One such data structure will be returned for
every `anonTypes`/`tables` combination. (The above example would
therefore return four data structures in the list.) <br/>
If `anonTypes` is missing, then `[["no_anon"]]` is used by
default. `basic` is not needed if the configuration is not used
for either an attack or a utility measure. As such, the simplest
valid configuration is: <br/>
{ "tables": [["table","column"]] }
which gives access to the non-anonymized (raw) table. <br/>
If the attack or utility measure has already been run (i.e. there is
a complete scores json file), then `"finished": True` is added to the
returned data structure. <br/>
The other calling parameters are for backwards compatibility. <br/>
"""
pp = pprint.PrettyPrinter(indent=4)
# We can either pull in the config from a file, or from a dict.
# If the former, configFile will be a list.
if configInfo is None:
configInfo = sys.argv
if isinstance(configInfo, list):
usageStr = str(f"""Usage:
Either specify configuration file:
> {configInfo[0]} config.json
Or assume default configuration file '{configInfo[0]}.json':
> {configInfo[0]}
""")
# Pull in config from a json file
if len(configInfo) == 1:
cmdName = os.path.abspath(configInfo[0])
if len(cmdName) == 0:
sys.exit(usageStr)
fileName = cmdName + '.json'
elif len(configInfo) != 2:
sys.exit(usageStr)
else:
fileName = sys.argv[1]
try:
f = open(fileName, 'r')
except:
e = str(f"ERROR: file '{fileName}' not found.\n{usageStr}")
sys.exit(e)
config = json.load(f)
f.close()
else:
# use the dict
config = configInfo
if isinstance(config, list):
# This is the old config style
return oldSetupGdaAttackParameters(config, criteria, attackType)
pmList = []
master = getMasterConfig()
if 'basic' in config and 'criteria' in config['basic']:
criteria = config['basic']['criteria']
else:
# just a dummy value
criteria = 'singlingOut'
if criteria == 'linkability':
(rawDbs, rawFriendlyNames, rawService) = (
getAnonDbs(master, ["no_anon"], 'link'))
else:
(rawDbs, rawFriendlyNames, rawService) = (
getAnonDbs(master, ["no_anon"], ''))
if 'anonTypes' not in config:
config['anonTypes'] = [["no_anon"]]
for anon in config['anonTypes']:
if not isinstance(anon, list):
print("ERROR: The 'anonTypes' config must be a list of lists")
quit()
params = {"anonType": anon}
if criteria == 'linkability':
(anonDbs, anonFriendlyNames, anonService) = (
getAnonDbs(master, anon, 'link'))
else:
pp.pprint(anon)
(anonDbs, anonFriendlyNames, anonService) = (
getAnonDbs(master, anon, ''))
if anonDbs is None:
params["error"] = "Could not find anonymization in master"
pmList.append(params)
continue
for tab in config['tables']:
# For each table, we need to find the database name
params["table"] = tab
db = tab[0]
table = tab[1]
dataFriendlyNames = [master['datasources']['friendlyName']]
if db not in master['datasources']:
params["error"] = "Could not find database in master"
pmList.append(params)
continue
datasource = master['datasources'][db]
dataFriendlyNames.append(datasource['friendlyName'])
if table not in datasource['tables']:
params["error"] = "Could not find table in master"
pmList.append(params)
continue
dataFriendlyNames.append(table)
uid = datasource['tables'][table]['uid']
# We have the right records from master, so build the params
# pp.pprint(anonDbs)
# pp.pprint(rawDbs)
# pp.pprint(datasource)
servs = master['services']
rawTab = getTab(datasource['databases'], rawDbs)
params['rawDb'] = {"dbname": rawTab}
params['rawDb']['port'] = servs[rawService]['port']
params['rawDb']['host'] = servs[rawService]['host']
params['rawDb']['type'] = servs[rawService]['type']
anonTab = getTab(datasource['databases'], anonDbs)
params['anonDb'] = {"dbname": anonTab}
params['anonDb']['port'] = servs[anonService]['port']
params['anonDb']['host'] = servs[anonService]['host']
params['anonDb']['type'] = servs[anonService]['type']
resultsPath = 'results/'
name = os.path.basename(sys.argv[0])
for item in anon:
name += '.' + item
name += '.' + db + '.' + table
params['name'] = name
params['flushCache'] = False
params['verbose'] = False
params['resultsPath'] = 'results/' + name + '.json'
params['table'] = table
params['uid'] = uid
params['friendly'] = {"anonymization": anonFriendlyNames}
params['friendly']['dataSource'] = dataFriendlyNames
params['criteria'] = criteria
if 'basic' in config:
# basic is needed if attack or utility measure
params['basicConfig'] = config['basic']
if 'attackType' in config['basic']:
# This is an attack configuration
params['friendly']['attack'] = [
config['basic']['attackType'], criteria]
# If criteria is linkability, we need to add the
# public linkability db
if criteria == 'linkability':
(pubDbs, pubFriendlyNames, pubService) = (
getAnonDbs(master, anon, 'pub'))
pubTab = getTab(datasource['databases'], pubDbs)
params['pubDb'] = {"dbname": pubTab}
params['pubDb']['port'] = servs[rawService]['port']
params['pubDb']['host'] = servs[rawService]['host']
params['pubDb']['type'] = servs[rawService]['type']
elif 'utilityMeasure' in config['basic']:
# This is a utility configuration
params['friendly']['utility'] = [
config['basic']['utilityMeasure'],
config['basic']['measureParam']]
# pp.pprint(params)
# Need to determine if the results have already been finished
params['finished'] = False
try:
f = open(params['resultsPath'], 'r')
except:
# No prior results for this attack have been posted
pass
else:
# Prior results have been posted. Make sure they are complete.
res = json.load(f)
if 'finished' in res:
params['finished'] = True
new = copy.deepcopy(params)
pmList.append(new)
return pmList
def oldSetupGdaAttackParameters(pmList, criteria, attackType):
for pm in pmList:
if 'criteria' not in pm or len(pm['criteria']) == 0:
if not criteria:
sys.exit("ERROR: criteria must be specified")
pm['criteria'] = criteria
if 'attackType' not in pm or len(pm['attackType']) == 0:
if not attackType:
sys.exit("ERROR: attackType must be specified")
pm['attackType'] = attackType
if 'name' not in pm or len(pm['name']) == 0:
baseName = str(f"{sys.argv[0].replace(os.path.sep, '-').strip('-')}")
if 'anonType' in pm and len(pm['anonType']) > 0:
baseName += str(f".{pm['anonType']}")
if 'anonSubType' in pm and len(pm['anonSubType']) > 0:
baseName += str(f".{pm['anonSubType']}")
if 'dbType' not in pm or len(pm['dbType']) == 0:
baseName += str(f".{pm['rawDb']}.{pm['anonDb']}")
else:
baseName += str(f".{pm['dbType']}")
if 'table' in pm and len(pm['table']) > 0:
baseName += str(f".{pm['table']}")
else:
baseName = pm['name']
# Remove any spaces in the base name
baseName.replace(" ", "")
pm['name'] = baseName
resultsDir = "attackResults";
if 'resultsDir' in pm and len(pm['resultsDir']) > 0:
resultsDir = pm['resultsDir']
resultsPath = resultsDir + "/" + baseName + ".json"
pm['resultsPath'] = resultsPath
pm['finished'] = False
try:
f = open(resultsPath, 'r')
except:
# No prior results for this attack have been posted
pass
else:
# Prior results have been posted. Make sure they are complete.
res = json.load(f)
if 'finished' in res:
pm['finished'] = True
return pmList
def finishGdaAttack(params, score):
""" Stores the attack results in a json file
Returns the attack results data structure"""
if 'finished' in params:
del params['finished']
final = {}
final['score'] = score
final['params'] = params
final['finished'] = True
j = json.dumps(final, sort_keys=True, indent=4)
resultsPath = params['resultsPath']
for _ in range(2):
try:
f = open(resultsPath, 'w')
except:
if not os.path.exists(os.path.dirname(resultsPath)):
os.mkdir(os.path.dirname(resultsPath))
continue
e = str(f"Failed to open {resultsPath} for write")
sys.exit(e)
else:
break
f.write(j)
f.close()
return final
def comma_ize(strings, lastComma=True):
""" Make a single string with input strings separated by commas.
Set `lastComma=False` if there should be no ending comma."""
string = ''
for s in strings:
string += str(f"{s}, ")
if not lastComma:
# snip off the last ', '
ret = string[0:-2]
else:
ret = string
return ret
def makeGroupBy(columns):
""" Make a GROUP BY clause appropriate for list of columns"""
clause = 'GROUP BY '
for val in range(1, len(columns) + 1):
clause += str(f"{val}, ")
# Strip off the last comma and add a space
ret = clause[0:-2] + ' '
return ret
def makeInNotNullConditions(columns):
""" Make the WHERE clause conditions of IS NOT NULL for columns"""
clause = ''
for col in columns:
clause += str(f" {col} IS NOT NULL AND ")
# Strip off the last AND
ret = clause[0:-4]
return ret
def getInterpolatedValue(val0, val1, scoreGrid):
"""Compute interpolated value from grid of mapping tuples
This routine takes as input a list of tuples ("grid") of the form
`(val0,val1,score)`. It maps (val0,val1) values to a corresponding
score. It returns a score that is interpolated between the
scores in the grid. An example of such a grid can be found in
gdaScore.py, called `_defenseGrid1`. Note that val0 and val1 must
go in descending order as shown. Input values that are above the
highest val0 and val1 values will take the score of the first
entry. Input values that are below the lowest val0 and val1 will
take the score of the last entry.
"""
scoreAbove = -1
scoreBelow = -1
for tup in scoreGrid:
tup0 = tup[0]
tup1 = tup[1]
score = tup[2]
if val0 <= tup0 and val1 <= tup1:
tup0Above = tup0
tup1Above = tup1
scoreAbove = score
for tup in reversed(scoreGrid):
tup0 = tup[0]
tup1 = tup[1]
score = tup[2]
if val0 >= tup0 and val1 >= tup1:
tup0Below = tup0
tup1Below = tup1
scoreBelow = score
if scoreAbove == -1 and scoreBelow == -1:
return None
if scoreAbove == -1:
return scoreBelow
if scoreBelow == -1:
return scoreAbove
if scoreAbove == scoreBelow:
return scoreAbove
# Interpolate by treating as right triangle with tup0 as y and
# tup1 as x
yLegFull = tup0Above - tup0Below
xLegFull = tup1Above - tup1Below
hypoFull = math.sqrt((xLegFull ** 2) + (yLegFull ** 2))
yLegPart = val0 - tup0Below
xLegPart = val1 - tup1Below
hypoPart = math.sqrt((xLegPart ** 2) + (yLegPart ** 2))
frac = hypoPart / hypoFull
interpScore = scoreBelow - (frac * (scoreBelow - scoreAbove))
return interpScore
def findSnappedRange(val):
# simple brute force approach
start = 1
# find a starting value less than the target value val
while (1):
if start > val:
start /= 10
else:
break
# then find the pair of snapped values above and below val
while (1):
# the loop always starts at a power of 10
below = start
above = below * 2
if ((below <= val) and (above >= val)):
break
below = start * 2
above = start * 5
if ((below <= val) and (above >= val)):
break
below = start * 5
above = start * 10
if ((below <= val) and (above >= val)):
break
start *= 10
final = below
if ((above - val) < (val - below)):
final = above
return final</code></pre>
</details>
</section>
<section>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-functions">Functions</h2>
<dl>
<dt id="gdascore.gdaTools.setupGdaAttackParameters"><code class="name flex">
<span>def <span class="ident">setupGdaAttackParameters</span></span>(<span>configInfo=None, utilityMeasure='', criteria='', attackType='')</span>
</code></dt>
<dd>
<section class="desc"><p>Basic prep for input and output of gdaAttack (attack or utility)</p>
<p>If called with no parameters, then this routine
reads a configuration file of the same name as the python file
but with <code>.json</code> appended. (I.e. if the python file is <code>test.py</code>,
then <code>test.py.json</code> is read.) <br/>
Otherwise, <code>configInfo</code> is a python dict. <br/>
Either way (json file or python dict), the basic structure of the
configuration is: <br/></p>
<pre><code>{
"configVersion": "compact1",
"basic": {
"attackType": "Simple List",
"criteria": "linkability"
},
"anonTypes": [
["no_anon"],
["diffix","latest"],
],
"tables": [
["banking","accounts"],
["taxi","rides"],
]
}
</code></pre>
<p>The above is for attacks. If utility measure, then the <code>"basic"</code>
contents may be for instance: <br/></p>
<p>"basic": {
"utilityMeasure": "Single Column Count",
"measureParam":"uid",
"samples": 25,
"ranges": [[10,50],[50,100],[100,500],[500,1000],[1000,5000]]
},</p>
<p>Returns a list of data structures that can be used for
class <code>gdaAttack()</code>. One such data structure will be returned for
every <code>anonTypes</code>/<code>tables</code> combination. (The above example would
therefore return four data structures in the list.) <br/>
If <code>anonTypes</code> is missing, then <code>[["no_anon"]]</code> is used by
default. <code>basic</code> is not needed if the configuration is not used
for either an attack or a utility measure. As such, the simplest
valid configuration is: <br/></p>
<pre><code>{ "tables": [["table","column"]] }
</code></pre>
<p>which gives access to the non-anonymized (raw) table. <br/>
If the attack or utility measure has already been run (i.e. there is
a complete scores json file), then <code>"finished": True</code> is added to the
returned data structure. <br/>
The other calling parameters are for backwards compatibility. <br/></p></section>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def setupGdaAttackParameters(configInfo=None, utilityMeasure='',
criteria='', attackType=''):
""" Basic prep for input and output of gdaAttack (attack or utility)
If called with no parameters, then this routine
reads a configuration file of the same name as the python file
but with `.json` appended. (I.e. if the python file is `test.py`,
then `test.py.json` is read.) <br/>
Otherwise, `configInfo` is a python dict. <br/>
Either way (json file or python dict), the basic structure of the
configuration is: <br/>
{
"configVersion": "compact1",
"basic": {
"attackType": "Simple List",
"criteria": "linkability"
},
"anonTypes": [
["no_anon"],
["diffix","latest"],
],
"tables": [
["banking","accounts"],
["taxi","rides"],
]
}
The above is for attacks. If utility measure, then the `"basic"`
contents may be for instance: <br/>
"basic": {
"utilityMeasure": "Single Column Count",
"measureParam":"uid",
"samples": 25,
"ranges": [[10,50],[50,100],[100,500],[500,1000],[1000,5000]]
},
Returns a list of data structures that can be used for
class `gdaAttack()`. One such data structure will be returned for
every `anonTypes`/`tables` combination. (The above example would
therefore return four data structures in the list.) <br/>
If `anonTypes` is missing, then `[["no_anon"]]` is used by
default. `basic` is not needed if the configuration is not used
for either an attack or a utility measure. As such, the simplest
valid configuration is: <br/>
{ "tables": [["table","column"]] }
which gives access to the non-anonymized (raw) table. <br/>
If the attack or utility measure has already been run (i.e. there is
a complete scores json file), then `"finished": True` is added to the
returned data structure. <br/>
The other calling parameters are for backwards compatibility. <br/>
"""
pp = pprint.PrettyPrinter(indent=4)
# We can either pull in the config from a file, or from a dict.
# If the former, configFile will be a list.
if configInfo is None:
configInfo = sys.argv
if isinstance(configInfo, list):
usageStr = str(f"""Usage:
Either specify configuration file:
> {configInfo[0]} config.json
Or assume default configuration file '{configInfo[0]}.json':
> {configInfo[0]}
""")
# Pull in config from a json file
if len(configInfo) == 1:
cmdName = os.path.abspath(configInfo[0])
if len(cmdName) == 0:
sys.exit(usageStr)
fileName = cmdName + '.json'
elif len(configInfo) != 2:
sys.exit(usageStr)
else:
fileName = sys.argv[1]
try:
f = open(fileName, 'r')
except:
e = str(f"ERROR: file '{fileName}' not found.\n{usageStr}")
sys.exit(e)
config = json.load(f)
f.close()
else:
# use the dict
config = configInfo
if isinstance(config, list):
# This is the old config style
return oldSetupGdaAttackParameters(config, criteria, attackType)
pmList = []
master = getMasterConfig()
if 'basic' in config and 'criteria' in config['basic']:
criteria = config['basic']['criteria']
else:
# just a dummy value
criteria = 'singlingOut'
if criteria == 'linkability':
(rawDbs, rawFriendlyNames, rawService) = (
getAnonDbs(master, ["no_anon"], 'link'))
else:
(rawDbs, rawFriendlyNames, rawService) = (
getAnonDbs(master, ["no_anon"], ''))
if 'anonTypes' not in config:
config['anonTypes'] = [["no_anon"]]
for anon in config['anonTypes']:
if not isinstance(anon, list):
print("ERROR: The 'anonTypes' config must be a list of lists")
quit()
params = {"anonType": anon}
if criteria == 'linkability':
(anonDbs, anonFriendlyNames, anonService) = (
getAnonDbs(master, anon, 'link'))
else:
pp.pprint(anon)
(anonDbs, anonFriendlyNames, anonService) = (
getAnonDbs(master, anon, ''))
if anonDbs is None:
params["error"] = "Could not find anonymization in master"
pmList.append(params)
continue
for tab in config['tables']:
# For each table, we need to find the database name
params["table"] = tab
db = tab[0]
table = tab[1]
dataFriendlyNames = [master['datasources']['friendlyName']]
if db not in master['datasources']:
params["error"] = "Could not find database in master"
pmList.append(params)
continue
datasource = master['datasources'][db]
dataFriendlyNames.append(datasource['friendlyName'])
if table not in datasource['tables']:
params["error"] = "Could not find table in master"
pmList.append(params)
continue
dataFriendlyNames.append(table)
uid = datasource['tables'][table]['uid']
# We have the right records from master, so build the params
# pp.pprint(anonDbs)
# pp.pprint(rawDbs)
# pp.pprint(datasource)
servs = master['services']
rawTab = getTab(datasource['databases'], rawDbs)
params['rawDb'] = {"dbname": rawTab}
params['rawDb']['port'] = servs[rawService]['port']
params['rawDb']['host'] = servs[rawService]['host']
params['rawDb']['type'] = servs[rawService]['type']
anonTab = getTab(datasource['databases'], anonDbs)
params['anonDb'] = {"dbname": anonTab}
params['anonDb']['port'] = servs[anonService]['port']
params['anonDb']['host'] = servs[anonService]['host']
params['anonDb']['type'] = servs[anonService]['type']
resultsPath = 'results/'
name = os.path.basename(sys.argv[0])
for item in anon:
name += '.' + item
name += '.' + db + '.' + table
params['name'] = name
params['flushCache'] = False
params['verbose'] = False
params['resultsPath'] = 'results/' + name + '.json'
params['table'] = table
params['uid'] = uid
params['friendly'] = {"anonymization": anonFriendlyNames}
params['friendly']['dataSource'] = dataFriendlyNames
params['criteria'] = criteria
if 'basic' in config:
# basic is needed if attack or utility measure
params['basicConfig'] = config['basic']
if 'attackType' in config['basic']:
# This is an attack configuration
params['friendly']['attack'] = [
config['basic']['attackType'], criteria]
# If criteria is linkability, we need to add the
# public linkability db
if criteria == 'linkability':
(pubDbs, pubFriendlyNames, pubService) = (
getAnonDbs(master, anon, 'pub'))
pubTab = getTab(datasource['databases'], pubDbs)
params['pubDb'] = {"dbname": pubTab}
params['pubDb']['port'] = servs[rawService]['port']
params['pubDb']['host'] = servs[rawService]['host']
params['pubDb']['type'] = servs[rawService]['type']
elif 'utilityMeasure' in config['basic']:
# This is a utility configuration
params['friendly']['utility'] = [
config['basic']['utilityMeasure'],
config['basic']['measureParam']]
# pp.pprint(params)
# Need to determine if the results have already been finished
params['finished'] = False
try:
f = open(params['resultsPath'], 'r')
except:
# No prior results for this attack have been posted
pass
else:
# Prior results have been posted. Make sure they are complete.
res = json.load(f)
if 'finished' in res:
params['finished'] = True
new = copy.deepcopy(params)
pmList.append(new)
return pmList</code></pre>
</details>
</dd>
</dl>
</section>
<section>
</section>
</article>
<nav id="sidebar">
<a href="https://www.gda-score.org/" class="custom-logo-link" rel="home" itemprop="url">
<img src="https://www.gda-score.org/wp-content/uploads/2018/10/GDA_Logo_04.svg" width="250" class="custom-logo" alt="GDA Score"
itemprop="logo" />
</a>
<hr style="margin-top:20px;" />
<h1>Index</h1>
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3>Super-module</h3>
<ul>
<li><code><a title="gdascore" href="index.html">gdascore</a></code></li>
</ul>
</li>
<li><h3><a href="#header-functions">Functions</a></h3>
<ul class="">
<li><code><a title="gdascore.gdaTools.setupGdaAttackParameters" href="#gdascore.gdaTools.setupGdaAttackParameters">setupGdaAttackParameters</a></code></li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<!--<a href="https://www.gda-score.org/legal-notice/">Legal notice</a>
<a href="https://www.gda-score.org/privacy-policy/">Privacy policy</a>-->
<p>Generated by <a href="https://pdoc3.github.io/pdoc"><cite>pdoc</cite> 0.7.5</a>.</p>
</footer>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad()</script>
</body>
</html>