-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearch.py
443 lines (381 loc) · 13.4 KB
/
search.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
import argparse
import logging
import re
import sqlite3
import sys
import requests
INDEX_NODES = [
"esg-dn1.nsc.liu.se",
"esgf-node.llnl.gov",
"esgf-data.dkrz.de",
"esgf.ceda.ac.uk",
"esgf.nci.org.au",
"esgf-node.ipsl.upmc.fr",
]
INDEX = INDEX_NODES[0]
SEARCH = "https://{}/esg-search/search".format(INDEX)
LIMIT = 9000
TIMEOUT = 240 # seconds
TOLERANCE = 120 # if each node (6 index nodes) fails 20 times, abort
class Project():
def find_opendap_url(self, urls):
opendap_url = ""
for url in urls:
if url.endswith("OPENDAP"):
opendap_url = url
return opendap_url
def query(self):
raise NotImplementedError
def parse_record(self, record):
raise NotImplementedError
def get_version(self):
raise NotImplementedError
class Cmip6(Project):
def __init__(self):
super().__init__()
self.core = ("id", "version", "checksum", "checksum_type", "data_node", "index_node", "instance_id",
"master_id", "replica", "size", "timestamp", "title", "tracking_id", "_timestamp")
self.project = ("mip_era", "project", "institution_id", "source_id", "experiment_id", "table_id",
"variable_id", "grid_label", "frequency", "realm", "product", "variant_label",
"further_info_url", "activity_id", "pid", "member_id", "sub_experiment_id")
self.variables = (
"ua", "va", "ta", "hus", "pr", "zg", "thetao", "ua", "wap", "tas", "va", "hur", "vo", "uo", "so", "ta", "hus",
"tos", "thetao", "tasmax")
def query(self):
datanodes = self.get_datanodes()
for datanode in datanodes:
datanode_vars = self.get_variables_for_datanode(datanode)
for v in datanode_vars:
#if v in self.variables:
# yield {"data_node": datanode, "variable_id": v}
yield {"data_node": datanode, "variable_id": v}
def get_datanodes(self):
session = requests.Session()
r = session.get(SEARCH, timeout=TIMEOUT, params={
"facets": "data_node",
"project": "CMIP6",
"limit": 0,
"format": "application/solr+json"})
response = r.json()
session.close()
datanodes = response["facet_counts"]["facet_fields"]["data_node"][::2]
return datanodes
def get_variables_for_datanode(self, datanode):
session = requests.Session()
r = session.get(SEARCH, timeout=TIMEOUT, params={
"facets": "variable_id",
"project": "CMIP6",
"data_node": datanode,
"limit": 0,
"format": "application/solr+json"})
response = r.json()
session.close()
variables = response["facet_counts"]["facet_fields"]["variable_id"][::2]
return variables
def get_version(self, dataset_id):
version = re.sub("\|.*", "", dataset_id)
version = re.sub(".*\.", "", version)
return version
def parse_record(self, record):
row = {}
for field in self.core:
if field not in record:
logging.error(
"Missing CORE field: {} in {}.".format(field, record))
row[field] = ""
elif isinstance(record[field], list):
row[field] = record[field][0]
else:
row[field] = record[field]
for field in self.project:
if field not in record:
row[field] = ""
logging.error(
"Missing PROJECT field: {} in {}.".format(field, record))
elif isinstance(record[field], list):
row[field] = record[field][0]
else:
row[field] = record[field]
row["opendap"] = ""
try:
opendap = self.find_opendap_url(record["url"])
opendap = re.sub("\|.*", "", opendap)
opendap = re.sub("\.html$", "", opendap)
row["opendap"] = opendap
except:
logging.error("Missing OPENDAP field in {}.".format(record))
row["eva_esgf_dataset"] = "_".join([
record["project"][0],
record["activity_id"][0],
record["institution_id"][0],
record["source_id"][0],
record["experiment_id"][0],
record["variant_label"][0],
record["table_id"][0],
record["variable_id"][0],
record["grid_label"][0],
self.get_version(record["dataset_id"]),
record["data_node"]])
if record["sub_experiment_id"][0] == "none":
row["eva_ensemble_aggregation"] = "_".join([
record["project"][0],
record["activity_id"][0],
record["institution_id"][0],
record["source_id"][0],
record["experiment_id"][0],
record["table_id"][0],
record["variable_id"][0],
record["grid_label"][0],
self.get_version(record["dataset_id"]),
record["data_node"]])
else:
row["eva_ensemble_aggregation"] = "_".join([
record["project"][0],
record["activity_id"][0],
record["institution_id"][0],
record["source_id"][0],
record["experiment_id"][0],
record["sub_experiment_id"][0],
record["table_id"][0],
record["variable_id"][0],
record["grid_label"][0],
self.get_version(record["dataset_id"]),
record["data_node"]])
return row
def range_search(session, stop=None, **kwargs):
payload = kwargs
# how many records?
payload["limit"] = 0
payload["format"] = "application/solr+json"
n = session.get(SEARCH,
params=payload,
timeout=TIMEOUT
).json()["response"]["numFound"]
# if stop < n, restrict
if stop is not None and stop < n:
n = stop
# clean payload and start searching
payload = kwargs
i = 0
while i < n:
payload["limit"] = LIMIT
payload["format"] = "application/solr+json"
payload["offset"] = i
r = session.get(SEARCH, params=payload, timeout=TIMEOUT)
print(r.url, flush=True)
for f in r.json()["response"]["docs"]:
yield f
i = i + LIMIT
def createdb(cursor):
cursor.execute("DROP TABLE IF EXISTS cmip6")
cursor.execute("""CREATE TABLE cmip6 (
id TEXT,
version TEXT,
checksum TEXT,
checksum_type VARCHAR(10),
data_node TEXT,
index_node TEXT,
instance_id TEXT,
master_id TEXT,
replica INTEGER,
size UNSIGNED BIG INT,
timestamp TEXT,
title TEXT,
tracking_id TEXT,
_timestamp TEXT,
mip_era TEXT,
project TEXT,
institution_id TEXT,
source_id TEXT,
experiment_id TEXT,
table_id TEXT,
variable_id TEXT,
grid_label TEXT,
frequency TEXT,
realm TEXT,
product TEXT,
variant_label TEXT,
member_id TEXT,
sub_experiment_id TEXT,
activity_id TEXT,
further_info_url TEXT,
pid TEXT,
opendap TEXT,
eva_esgf_dataset TEXT,
eva_ensemble_aggregation TEXT)""")
def search(session, project, query):
payload = {
"project": "CMIP6",
"type": "File",
"distrib": "True"
}
params = payload.copy()
params.update(query)
for record in range_search(session, **params):
fixed = project.parse_record(record)
newrow = (
fixed["id"],
fixed["version"],
fixed["checksum"],
fixed["checksum_type"],
fixed["data_node"],
fixed["index_node"],
fixed["instance_id"],
fixed["master_id"],
str(1 if fixed["replica"] else 0),
str(fixed["size"]),
fixed["timestamp"],
fixed["title"],
fixed["tracking_id"],
fixed["_timestamp"],
fixed["mip_era"],
fixed["project"],
fixed["institution_id"],
fixed["source_id"],
fixed["experiment_id"],
fixed["table_id"],
fixed["variable_id"],
fixed["grid_label"],
fixed["frequency"],
fixed["realm"],
fixed["product"],
fixed["variant_label"],
fixed["member_id"],
fixed["sub_experiment_id"],
fixed["activity_id"],
fixed["further_info_url"],
fixed["pid"],
fixed["opendap"],
fixed["eva_esgf_dataset"],
fixed["eva_ensemble_aggregation"]
)
yield newrow
class Query:
def query(self):
raise NotImplementedError
class ExtensiveQuery(Query):
def __init__(self, project, frm=None, to=None):
self.project = project
self.frm = frm
self.to = to
def query(self):
for q in project.query():
qcopy = q.copy()
if self.frm:
qcopy["from"] = self.frm
if self.to:
qcopy["to"] = self.to
yield qcopy
class SelectionQuery(Query):
def __init__(self, selection):
self.selection = selection
def query(self):
for x in self.parse_selection(self.selection):
yield x
def parse_selection(self, sfile):
q = {}
with open(sfile, "r") as f:
for line in f:
if line == "\n" and q:
yield q
q = {}
elif line != "\n":
params = line.rstrip("\n").split()
for param in params:
k = param.split("=")[0]
v = param.split("=")[1]
q[k] = v
if q:
yield q
if __name__ == "__main__":
# arguments
parser = argparse.ArgumentParser(description="Query ESGF files and store results in sqlite.")
parser.add_argument("-d", "--dest",
type=str,
required=False,
default="db.sqlite",
help="destination file.")
parser.add_argument("-p", "--project",
choices=["CMIP6"],
default="CMIP6",
type=str,
required=False,
help="ESGF project.")
parser.add_argument("-l", "--log-file",
type=str,
required=False,
default="search.log",
help="log file.")
parser.add_argument("-s", "--selection",
type=str,
required=False,
default=None,
help="selection file.")
parser.add_argument("--to",
type=str,
required=False,
default=None,
help="ESGF search 'to' keyword.")
parser.add_argument("--from",
type=str,
required=False,
default=None,
help="ESGF search 'from' keyword.")
parser.set_defaults()
args = vars(parser.parse_args())
logging.basicConfig(filename=args["log_file"],
level=logging.DEBUG)
if args["project"] == "CMIP6":
project = Cmip6()
if args["selection"]:
query = SelectionQuery(args["selection"])
else:
query = ExtensiveQuery(project, args["from"], args["to"])
# create sqlite db and get connection
logging.info("Set up sqlite database.")
conn = sqlite3.connect(args["dest"])
c = conn.cursor()
createdb(c)
# start searching
logging.info("Create Session: {}".format(INDEX))
s = requests.Session()
try:
i = 0
for q in query.query():
inserted = False
tolerance = 0
while not inserted: # loop index nodes while failing
try:
conn.execute("begin")
for row in search(s, project, q):
c.execute(
"INSERT INTO cmip6 VALUES({})".format(
",".join(["?" for _ in range(len(row))])),
row)
conn.commit()
inserted = True
except:
conn.execute("rollback")
logging.exception(
"Failed while retrieving {}.".format(q))
s.close()
# too many errors?
tolerance += 1
if tolerance >= TOLERANCE:
sys.exit(2)
# use new index
i = (i + 1) % len(INDEX_NODES)
INDEX = INDEX_NODES[i]
SEARCH = "https://{}/esg-search/search".format(INDEX)
s = requests.Session()
logging.info("Changing INDEX to: {}.".format(INDEX))
s.close()
finally:
c.execute(
"CREATE INDEX cmip6_data_node ON cmip6(data_node)")
c.execute(
"CREATE INDEX cmip6_eva_esgf_dataset ON cmip6(eva_esgf_dataset)")
c.execute(
"CREATE INDEX cmip6_eva_ensemble_aggregation ON cmip6(eva_ensemble_aggregation)")
c.close()
conn.close()