-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathcommand_processor.py
More file actions
535 lines (472 loc) · 19.7 KB
/
command_processor.py
File metadata and controls
535 lines (472 loc) · 19.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
#!/usr/bin/env python
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2019 DataONE
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Process and execute CLI operations."""
import html.entities
import io
import os
import re
import requests
import d1_cli.impl.client
import d1_cli.impl.exceptions
import d1_cli.impl.format_ids
import d1_cli.impl.nodes
import d1_cli.impl.operation_maker
import d1_cli.impl.operation_queue
import d1_cli.impl.session
import d1_cli.impl.util
import d1_common.const
import d1_common.date_time
import d1_common.types.exceptions
import d1_common.url
import d1_common.xml
DEFAULT_PREFIX = ""
DEFAULT_PROMPT = "> "
SOLR_FORMAT_ID_NAME = "formatId"
class CommandProcessor:
def __init__(self):
self._nodes = d1_cli.impl.nodes.Nodes()
self._format_ids = d1_cli.impl.format_ids.FormatIDs()
self._session = d1_cli.impl.session.Session(self._nodes, self._format_ids)
self._session.load(suppress_error=True)
self._object_format_id_cache = None
self._operation_queue = d1_cli.impl.operation_queue.OperationQueue(
self._session
)
self._operation_maker = d1_cli.impl.operation_maker.OperationMaker(
self._session
)
def get_session(self):
return self._session
def get_operation_queue(self):
return self._operation_queue
def get_nodes(self):
return self._nodes
def get_format_ids(self):
return self._format_ids
# -----------------------------------------------------------------------------
# Operations against Coordinating Nodes
# -----------------------------------------------------------------------------
# Read operations.
def ping(self, hosts):
if not len(hosts):
self._ping_base(self._session.get(d1_cli.impl.session.CN_URL_NAME))
self._ping_base(self._session.get(d1_cli.impl.session.MN_URL_NAME))
else:
for host in hosts:
cn_base_url = d1_common.url.makeCNBaseURL(host)
mn_base_url = d1_common.url.makeMNBaseURL(host)
self._ping_base(cn_base_url)
if mn_base_url != cn_base_url:
self._ping_base(mn_base_url)
def search(self, line):
"""CN search."""
if self._session.get(d1_cli.impl.session.QUERY_ENGINE_NAME) == "solr":
return self._search_solr(line)
raise d1_cli.impl.exceptions.InvalidArguments(
"Unsupported query engine: {}".format(
self._session.get(d1_cli.impl.session.QUERY_ENGINE_NAME)
)
)
def list_format_ids(self):
cn_base_url = self._session.get(d1_cli.impl.session.CN_URL_NAME)
self._output(self._format_ids.format(cn_base_url))
def list_nodes(self):
cn_base_url = self._session.get(d1_cli.impl.session.CN_URL_NAME)
self._output(self._nodes.format(cn_base_url))
def resolve(self, pid):
"""Get Object Locations for Object."""
client = d1_cli.impl.client.CLICNClient(
**self._cn_client_connect_params_from_session()
)
object_location_list_pyxb = client.resolve(pid)
for location in object_location_list_pyxb.objectLocation:
d1_cli.impl.util.print_info(location.url)
# Write operations (queued)
def update_access_policy(self, pids):
for pid in pids:
self._queue_update_access_policy(pid)
def update_replication_policy(self, pids):
for pid in pids:
self._queue_update_replication_policy(pid)
# -----------------------------------------------------------------------------
# Operations against Member Nodes
# -----------------------------------------------------------------------------
# Read operations
def science_object_get(self, pid, path):
"""First try the MN set in the session.
Then try to resolve via the CN set in the session.
"""
mn_client = d1_cli.impl.client.CLIMNClient(
**self._mn_client_connect_params_from_session()
)
try:
response = mn_client.get(pid)
except d1_common.types.exceptions.DataONEException:
pass
else:
self._output(response, path)
return
cn_client = d1_cli.impl.client.CLICNClient(
**self._cn_client_connect_params_from_session()
)
object_location_list_pyxb = cn_client.resolve(pid)
for location in object_location_list_pyxb.objectLocation:
try:
params = self._mn_client_connect_params_from_session()
params["base_url"] = location.baseURL
mn_client = d1_cli.impl.client.CLIMNClient(**params)
response = mn_client.get(pid)
except d1_common.types.exceptions.DataONEException:
pass
else:
self._output(response, path)
return
raise d1_cli.impl.exceptions.CLIError("Could not find object: {}".format(pid))
def system_metadata_get(self, pid, path):
sysmeta_pyxb = None
try:
client = d1_cli.impl.client.CLICNClient(
**self._cn_client_connect_params_from_session()
)
sysmeta_pyxb = client.getSystemMetadata(pid)
except d1_common.types.exceptions.DataONEException:
pass
if sysmeta_pyxb is None:
try:
client = d1_cli.impl.client.CLIMNClient(
**self._mn_client_connect_params_from_session()
)
sysmeta_pyxb = client.getSystemMetadata(pid)
except d1_common.types.exceptions.DataONEException:
pass
if sysmeta_pyxb is None:
raise d1_cli.impl.exceptions.CLIError(
"Unable to get System Metadata: {}".format(pid)
)
self._system_metadata_print(sysmeta_pyxb, path)
def log(self, path):
client = d1_cli.impl.client.CLIMNClient(
**self._mn_client_connect_params_from_session()
)
log_pyxb = client.getLogRecords(
fromDate=self._session.get(d1_cli.impl.session.FROM_DATE_NAME),
toDate=self._session.get(d1_cli.impl.session.TO_DATE_NAME),
start=self._session.get(d1_cli.impl.session.START_NAME),
count=self._session.get(d1_cli.impl.session.COUNT_NAME),
)
log_xml = d1_common.xml.serialize_to_xml_str(log_pyxb)
self._output(io.StringIO(log_xml), path)
def list_objects(self, path):
client = d1_cli.impl.client.CLIMNClient(
**self._mn_client_connect_params_from_session()
)
object_list_pyxb = client.listObjects(
fromDate=self._session.get(d1_cli.impl.session.FROM_DATE_NAME),
toDate=self._session.get(d1_cli.impl.session.TO_DATE_NAME),
formatId=self._session.get(d1_cli.impl.session.SEARCH_FORMAT_NAME),
start=self._session.get(d1_cli.impl.session.START_NAME),
count=self._session.get(d1_cli.impl.session.COUNT_NAME),
)
object_list_xml = d1_common.xml.serialize_to_xml_str(object_list_pyxb)
self._output(io.StringIO(object_list_xml), path)
# Write operations (queued)
def science_object_create(self, pid, path, format_id=None):
"""Create a new Science Object on a Member Node."""
self._queue_science_object_create(pid, path, format_id)
def science_object_update(self, pid_old, path, pid_new, format_id=None):
"""Obsolete a Science Object on a Member Node with a different one."""
self._queue_science_object_update(pid_old, path, pid_new, format_id)
def create_package(self, pids):
self._queue_create_package(pids)
def science_object_archive(self, pids):
for pid in pids:
self._queue_science_object_archive(pid)
#
# Private.
#
def _output(self, file_like_object, path=None):
"""Display or save file like object."""
if not path:
self._output_to_display(file_like_object)
else:
self._output_to_file(file_like_object, path)
def _output_to_display(self, file_like_object):
for line in file_like_object:
d1_cli.impl.util.print_info(line.rstrip())
def _output_to_file(self, file_like_object, path):
abs_path = d1_cli.impl.util.os.path.expanduser(path)
if os.path.exists(abs_path):
if not d1_cli.impl.util.confirm(
'You are about to overwrite an existing file at "{}". Continue? '.format(
abs_path
),
default="yes",
):
d1_cli.impl.util.print_info("Cancelled")
if isinstance(file_like_object, requests.Response):
d1_cli.impl.util.copy_requests_stream_to_file(file_like_object, path)
else:
d1_cli.impl.util.copy_file_like_object_to_file(file_like_object, abs_path)
d1_cli.impl.util.print_info("Created file: {}".format(abs_path))
def _pretty(self, xml_doc):
return d1_common.xml.reformat_to_pretty_xml(xml_doc.decode("utf-8"))
def _system_metadata_print(self, sysmeta_pyxb, path=None):
sysmeta_xml = d1_common.xml.serialize_to_xml_str(sysmeta_pyxb)
if path is not None:
path = d1_cli.impl.util.os.path.expanduser(path)
self._output(io.StringIO(sysmeta_xml), path)
def _ping_base(self, base_url):
result = d1_cli.impl.client.CLIBaseClient(base_url).ping()
self._print_ping_result(result, base_url)
def _print_ping_result(self, result, url):
if result:
d1_cli.impl.util.print_info("Responded: {}".format(url))
else:
d1_cli.impl.util.print_error("Did not respond: {}".format(url))
def _search_solr(self, line):
"""Perform a SOLR search."""
try:
query_str = self._create_solr_query(line)
client = d1_cli.impl.client.CLICNClient(
**self._cn_client_connect_params_from_session()
)
object_list_pyxb = client.search(
queryType=d1_common.const.DEFAULT_SEARCH_ENGINE,
query=query_str,
start=self._session.get(d1_cli.impl.session.START_NAME),
rows=self._session.get(d1_cli.impl.session.COUNT_NAME),
)
d1_cli.impl.util.print_info(self._pretty(object_list_pyxb.toxml("utf-8")))
except d1_common.types.exceptions.ServiceFailure as e:
e = "%".join(str(e).splitlines()) # Flatten line
regexp = re.compile(
r"errorCode: (?P<error_code>\d+)%.*%Status code: (?P<status_code>\d+)"
)
result = regexp.search(e)
if (
(result is not None)
and (result.group("error_code") == "500")
and (result.group("status_code") == "400")
): # noqa: E129
result = re.search(
r"<b>description</b> <u>(?P<description>[^<]+)</u>", e
)
msg = re.sub(
"&([^;]+);",
lambda m: chr(html.entities.name2codepoint[m.group(1)]),
result.group("description"),
)
d1_cli.impl.util.print_info("Warning: %s" % msg)
else:
d1_cli.impl.util.print_error("Unexpected error:\n%s" % str(e))
def _create_solr_query(self, line):
"""Actual search - easier to test. """
p0 = ""
if line:
p0 = line.strip()
p1 = self._query_string_to_solr_filter(line)
p2 = self._object_format_to_solr_filter(line)
p3 = self._time_span_to_solr_filter()
result = p0 + p1 + p2 + p3
return result.strip()
def _query_string_to_solr_filter(self, line):
query = self._session.get(d1_cli.impl.session.QUERY_STRING_NAME)
if not query or query == "" or (query == "*:*" and len(line) > 0):
return ""
else:
return " " + query
def _time_span_to_solr_filter(self):
fromdate = self._session.get(d1_cli.impl.session.FROM_DATE_NAME)
todate = self._session.get(d1_cli.impl.session.TO_DATE_NAME)
return " dateModified:[{} TO {}]".format(
d1_common.date_time.http_datetime_str_from_dt(fromdate)
if fromdate
else "*",
d1_common.date_time.http_datetime_str_from_dt(todate) if todate else "*",
)
def _object_format_to_solr_filter(self, line):
search_format_id = self._session.get(d1_cli.impl.session.SEARCH_FORMAT_NAME)
if not search_format_id or search_format_id == "":
return ""
else:
if line.find(SOLR_FORMAT_ID_NAME) >= 0:
d1_cli.impl.util.print_warn(
"Using query format restriction instead: {}".format(
search_format_id
)
)
else:
return " %s:%s" % (SOLR_FORMAT_ID_NAME, search_format_id)
def _mn_client_connect_params_from_session(self):
return self._mn_cn_client_connect_params_from_session(
d1_cli.impl.session.MN_URL_NAME
)
def _cn_client_connect_params_from_session(self):
return self._mn_cn_client_connect_params_from_session(
d1_cli.impl.session.CN_URL_NAME
)
def _mn_cn_client_connect_params_from_session(self, url_name):
anonymous = self._session.get(d1_cli.impl.session.ANONYMOUS_NAME)
return {
"base_url": self._session.get(url_name),
"cert_pem_path": self._session.get(d1_cli.impl.session.CERT_FILENAME_NAME)
if not anonymous
else None,
"cert_key_path": self._session.get(d1_cli.impl.session.KEY_FILENAME_NAME)
if not anonymous
else None,
}
#
# Queuing of write operations
#
def _queue_science_object_create(self, pid, path, format_id):
create_operation = self._operation_maker.create(pid, path, format_id)
self._operation_queue.append(create_operation)
def _queue_science_object_update(self, pid_old, path, pid_new, format_id):
update_operation = self._operation_maker.update(
pid_old, path, pid_new, format_id
)
self._operation_queue.append(update_operation)
def _queue_create_package(self, pids):
archive_operation = self._operation_maker.create_package(pids)
self._operation_queue.append(archive_operation)
def _queue_science_object_archive(self, pid):
archive_operation = self._operation_maker.archive(pid)
self._operation_queue.append(archive_operation)
def _queue_update_access_policy(self, pid):
update_access_policy_operation = self._operation_maker.update_access_policy(pid)
self._operation_queue.append(update_access_policy_operation)
def _queue_update_replication_policy(self, pid):
update_replication_policy_operation = self._operation_maker.update_replication_policy(
pid
)
self._operation_queue.append(update_replication_policy_operation)
# def get_object_by_pid(session, pid, filename=None, resolve=True):
# """ Create a mnclient and look for the object. If the object is not found,
# simply return a None, don't throw an exception. If found, return the
# filename.
# """
# if session is None:
# raise exceptions.InvalidArguments(u'Missing session')
# if pid is None:
# raise exceptions.InvalidArguments(u'Missing pid')
# # Create member node client and try to get the object.
# mn_client = CLIMNClient(session)
# try:
# response = mn_client.get(pid)
# if response is not None:
# fname = _get_fname(filename)
# util.output(response, fname, session.is_verbose())
# return fname
# except d1_common.types.exceptions.DataONEException as e:
# if e.errorCode != 404:
# raise exceptions.CLIError(
# u'Unable to get resolve: {0}\n{1}'.format(pid, e.friendly_format()))
# if resolve:
# cn_client = CLICNClient(session)
# object_location_list = None
# try:
# object_location_list = cn_client.resolve(pid)
# if ((object_location_list is not None)
# and (len(object_location_list.objectLocation) > 0)):
# baseUrl = object_location_list.objectLocation[0].baseURL
# # If there is an object, go get it.
# mn_client = CLIMNClient(session, mn_url=baseUrl)
# response = mn_client.get(pid)
# if response is not None:
# fname = _get_fname(filename)
# util.output(response, os.path.expanduser(fname))
# return fname
# except d1_common.types.exceptions.DataONEException as e:
# if e.errorCode != 404:
# raise exceptions.CLIError(
# u'Unable to get resolve: {0}\n{1}'.format(pid, e.friendly_format()))
# # Nope, didn't find anything
# return None
#
#
#
#
# def get_baseUrl(session, nodeId):
# """ Get the base url of the given node id.
# """
# cn_client = CLICNClient(session)
# try:
# nodes = cn_client.listNodes()
# for node in list(nodes.node):
# if node.identifier.value() == nodeId:
# return node.baseURL
# except (d1_common.types.exceptions.ServiceFailure) as e:
# util.print_error("Unable to get node list.")
# return None
#
#
# def get_sys_meta_by_pid(session, pid, search_mn = False):
# """ Get the system metadata object for this particular pid.
# """
# if not session:
# raise exceptions.InvalidArguments(u'Missing session')
# if not pid:
# raise exceptions.InvalidArguments(u'Missing pid')
#
# sys_meta = None
# try:
# cn_client = CLICNClient(session)
# obsolete = True;
# while obsolete:
# obsolete = False;
# sys_meta = cn_client.getSystemMetadata(pid)
# if not sys_meta:
# return None
# if sys_meta.obsoletedBy:
# msg = (u'Object "%s" has been obsoleted by "%s". '
# + u'Would you rather use that?') % (pid, sys_meta.obsoletedBy)
# if not util.confirm(msg):
# break;
# pid = sys_meta.obsoletedBy
# obsolete = True
# return sys_meta
# except d1_common.types.exceptions.DataONEException as e:
# if e.errorCode != 404:
# raise exceptions.CLIError(
# u'Unable to get system metadata for: {0}\n{1}'.format(pid, e.friendly_format()))
# # Search the member node?
# if not sys_meta and (search_mn is not None) and search_mn:
# try:
# mn_client = CLIMNClient(session)
# obsolete = True;
# while obsolete:
# obsolete = False;
# sys_meta = mn_client.getSystemMetadata(pid)
# if not sys_meta:
# return None
# if sys_meta.obsoletedBy:
# msg = (u'Object "%s" has been obsoleted by "%s". '
# + u'Would you rather use that?') % (pid, sys_meta.obsoletedBy)
# if not util.confirm(msg):
# break;
# pid = sys_meta.obsoletedBy
# obsolete = True
# return sys_meta
# except d1_common.types.exceptions.DataONEException as e:
# if e.errorCode != 404:
# raise exceptions.CLIError(
# u'Unable to get system metadata for: {0}\n{1}'.format(pid, e.friendly_format()))
#
# return sys_meta