/
registry.py
2037 lines (1683 loc) · 66.6 KB
/
registry.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import collections
import datetime
import isodate
import json
import os
import PIL.Image
import rawes
import re
import requests
import sys
import time
import getopt
import yaml
import logging
from dateutil import tz
from dateutil.parser import parse
from distutils.util import strtobool
from django.conf import settings
from django.core import management
from django.conf.urls import url
from django.http import HttpResponse
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from io import BytesIO
from markdown2 import markdown_path
from pycsw import server
from pycsw.core import config, metadata
from pycsw.core import admin as pycsw_admin
from pycsw.core.etree import etree
from pycsw.core.repository import Repository
from pycsw.core.util import wkt2geom
from mapproxy.config.config import load_default_config, load_config
from mapproxy.config.spec import validate_options
from mapproxy.config.validator import validate_references
from mapproxy.config.loader import ProxyConfiguration, ConfigurationError
from mapproxy.response import Response
from mapproxy.version import version
from mapproxy.wsgiapp import MapProxyApp
from shapely.geometry import box
from six.moves.urllib_parse import urlparse, unquote as url_unquote, urlencode
from rawes.elastic_exception import ElasticException
netlocs_dic = {}
__version__ = 0.2
ALLOWED_HOSTS = [os.getenv('REGISTRY_ALLOWED_HOSTS', '*')]
DEBUG = strtobool(os.getenv('REGISTRY_DEBUG', 'True'))
ROOT_URLCONF = 'registry'
DATABASES = {'default': {}} # required regardless of actual usage
SECRET_KEY = os.getenv('REGISTRY_SECRET_KEY', 'Make sure you create a good secret key.')
REGISTRY_MAPPING_PRECISION = os.getenv('REGISTRY_MAPPING_PRECISION', '500m')
REGISTRY_MAPPING_DIST_ERR_PCT = os.getenv('REGISTRY_MAPPING_DIST_ERR_PCT', 0.025)
REGISTRY_SEARCH_URL = os.getenv('REGISTRY_SEARCH_URL', 'http://127.0.0.1:9200')
REGISTRY_SEARCH_USERNAME = os.getenv('REGISTRY_SEARCH_USERNAME')
REGISTRY_SEARCH_PASSWORD = os.getenv('REGISTRY_SEARCH_PASSWORD')
REGISTRY_DATABASE_URL = os.getenv('REGISTRY_DATABASE_URL', 'sqlite:////tmp/registry.db')
REGISTRY_MAXRECORDS_PER_NETLOC = int(os.getenv('REGISTRY_MAXRECORDS_PER_NETLOC', '3600'))
REGISTRY_CSW_MAX_RECORDS = int(os.getenv('REGISTRY_CSW_MAX_RECORDS', '1000'))
REGISTRY_LOG_FILE_PATH = os.getenv('REGISTRY_LOG_FILE_PATH', '/tmp/registry.log')
REGISTRY_LOG_LEVEL = os.getenv('REGISTRY_LOG_LEVEL', 'DEBUG')
PYCSW_LOG_LEVEL = os.getenv('PYCSW_LOG_LEVEL', 'DEBUG')
MAPPROXY_CACHE_DIR = os.getenv('MAPPROXY_CACHE_DIR', '/tmp')
# If MAPPROXY_ERROR_IMAGES is True, wms requests with source errors will return
# an image with the errors printed within it and a 200 status code. Otherwise,
# an xml exception and 500 status code will be returned.
MAPPROXY_ERROR_IMAGES = strtobool(os.getenv('MAPPROXY_ERROR_IMAGES', 'False'))
VCAP_SERVICES = os.environ.get('VCAP_SERVICES', None)
REGISTRY_MAPPINGS_OVERRIDES_FILE = os.environ.get('REGISTRY_MAPPINGS_OVERRIDES_FILE', None)
REGISTRY_MAPPINGS_OVERRIDES = {}
if REGISTRY_MAPPINGS_OVERRIDES_FILE is not None:
try:
with open(REGISTRY_MAPPINGS_OVERRIDES_FILE) as f:
REGISTRY_MAPPINGS_OVERRIDES = json.load(f)
except:
pass
def vcaps_search_url(VCAP_SERVICES, search_url):
"""Extract 'search_url' from user-provided key in VCAP_SERVICES dict
"""
if VCAP_SERVICES:
vcap_config = json.loads(VCAP_SERVICES)
if 'searchly' in vcap_config:
search_url = vcap_config['searchly'][0]['credentials']['sslUri']
try:
search_url = vcap_config['user-provided'][0]['credentials']['search_url']
except KeyError:
pass
return search_url
def vcaps_db_url(VCAP_SERVICES, database_url):
"""Extract database_url from VCAP_SERVICES dict
"""
if VCAP_SERVICES:
vcap_config = json.loads(VCAP_SERVICES)
if 'pg_95_SM_DEV_CODE-A-THON_001' in vcap_config:
database_url = vcap_config['pg_95_SM_DEV_CODE-A-THON_001'][0]['credentials']['uri']
elif 'pg_95_XL_DEV_SHARED_001' in vcap_config:
database_url = vcap_config['pg_95_XL_DEV_SHARED_001'][0]['credentials']['uri']
elif 'pg_95_XL_DEV_CONTENT_001' in vcap_config:
database_url = vcap_config['pg_95_XL_DEV_CONTENT_001'][0]['credentials']['uri']
elif 'pg_95_XL_PROD_CONTENT_001' in vcap_config:
database_url = vcap_config['pg_95_XL_PROD_CONTENT_001'][0]['credentials']['uri']
elif 'pg_95_XL_PROD_SHARED_001' in vcap_config:
database_url = vcap_config['pg_95_XL_PROD_SHARED_001'][0]['credentials']['uri']
return database_url
# Override DATABASE_URL and SEARCH_URL if VCAP_SERVICES is defined.
REGISTRY_SEARCH_URL = vcaps_search_url(VCAP_SERVICES, REGISTRY_SEARCH_URL)
REGISTRY_DATABASE_URL = vcaps_db_url(VCAP_SERVICES, REGISTRY_DATABASE_URL)
TIMEZONE = tz.gettz('America/New_York')
# setup logging
LOGGER = logging.getLogger(__name__)
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '%(asctime)s [%(levelname)s] %(process)d --- [%(module)s %(filename)s:%(lineno)s] : %(message)s'
},
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
'file': {
'level': REGISTRY_LOG_LEVEL,
'class': 'logging.FileHandler',
'filename': REGISTRY_LOG_FILE_PATH,
'formatter': 'verbose',
},
},
'loggers': {
'django': {
'handlers': ['console'],
'level': 'ERROR',
'propagate': True,
},
'pycsw': {
'handlers': ['console', 'file'],
'level': PYCSW_LOG_LEVEL,
'propagate': True,
},
'mapproxy': {
'handlers': ['console'],
'level': 'ERROR',
'propagate': True,
},
'registry': {
'handlers': ['console', 'file'],
'level': REGISTRY_LOG_LEVEL,
'propagate': True,
},
},
}
if not settings.configured:
settings.configure(**locals())
# When importing serializers, Django requires DEFAULT_INDEX_TABLESPACE.
# This variable is set after settings.configure().
from rest_framework import serializers # noqa
PYCSW = {
'repository': {
'source': 'registry.RegistryRepository',
'mappings': 'registry',
'database': REGISTRY_DATABASE_URL,
'table': 'records',
},
'server': {
'maxrecords': '100',
'pretty_print': 'true',
'domaincounts': 'true',
'encoding': 'UTF-8',
'profiles': 'apiso',
'home': '.',
},
'metadata:main': {
'identification_title': 'Registry',
'identification_abstract': 'Registry is a CSW catalogue with faceting capabilities via OpenSearch',
'identification_keywords': 'registry, pycsw',
'identification_keywords_type': 'theme',
'identification_fees': 'None',
'identification_accessconstraints': 'None',
'provider_name': 'Organization Name',
'provider_url': '',
'contact_name': 'Lastname, Firstname',
'contact_position': 'Position Title',
'contact_address': 'Mailing Address',
'contact_city': 'City',
'contact_stateorprovince': 'Administrative Area',
'contact_postalcode': 'Zip or Postal Code',
'contact_country': 'Country',
'contact_phone': '+xx-xxx-xxx-xxxx',
'contact_fax': '+xx-xxx-xxx-xxxx',
'contact_email': 'Email Address',
'contact_url': 'Contact URL',
'contact_hours': 'Hours of Service',
'contact_instructions': 'During hours of service. Off on weekends.',
'contact_role': 'pointOfContact',
},
'manager': {
'transactions': 'false',
'allowed_ips': os.getenv('REGISTRY_ALLOWED_IPS', '*'),
},
}
MD_CORE_MODEL = {
'typename': 'pycsw:CoreMetadata',
'outputschema': 'http://pycsw.org/metadata',
'mappings': {
'pycsw:Identifier': 'identifier',
'pycsw:Typename': 'typename',
'pycsw:Schema': 'schema',
'pycsw:MdSource': 'mdsource',
'pycsw:InsertDate': 'insert_date',
'pycsw:XML': 'xml',
'pycsw:AnyText': 'anytext',
'pycsw:Language': 'language',
'pycsw:Title': 'title',
'pycsw:Abstract': 'abstract',
'pycsw:Keywords': 'keywords',
'pycsw:KeywordType': 'keywordstype',
'pycsw:Format': 'format',
'pycsw:Source': 'source',
'pycsw:Date': 'date',
'pycsw:Modified': 'date_modified',
'pycsw:Type': 'type',
'pycsw:BoundingBox': 'wkt_geometry',
'pycsw:CRS': 'crs',
'pycsw:AlternateTitle': 'title_alternate',
'pycsw:RevisionDate': 'date_revision',
'pycsw:CreationDate': 'date_creation',
'pycsw:PublicationDate': 'date_publication',
'pycsw:OrganizationName': 'organization',
'pycsw:SecurityConstraints': 'securityconstraints',
'pycsw:ParentIdentifier': 'parentidentifier',
'pycsw:TopicCategory': 'topicategory',
'pycsw:ResourceLanguage': 'resourcelanguage',
'pycsw:GeographicDescriptionCode': 'geodescode',
'pycsw:Denominator': 'denominator',
'pycsw:DistanceValue': 'distancevalue',
'pycsw:DistanceUOM': 'distanceuom',
'pycsw:TempExtent_begin': 'time_begin',
'pycsw:TempExtent_end': 'time_end',
'pycsw:ServiceType': 'servicetype',
'pycsw:ServiceTypeVersion': 'servicetypeversion',
'pycsw:Operation': 'operation',
'pycsw:CouplingType': 'couplingtype',
'pycsw:OperatesOn': 'operateson',
'pycsw:OperatesOnIdentifier': 'operatesonidentifier',
'pycsw:OperatesOnName': 'operatesoname',
'pycsw:Degree': 'degree',
'pycsw:AccessConstraints': 'accessconstraints',
'pycsw:OtherConstraints': 'otherconstraints',
'pycsw:Classification': 'classification',
'pycsw:ConditionApplyingToAccessAndUse': 'conditionapplyingtoaccessanduse',
'pycsw:Lineage': 'lineage',
'pycsw:ResponsiblePartyRole': 'responsiblepartyrole',
'pycsw:SpecificationTitle': 'specificationtitle',
'pycsw:SpecificationDate': 'specificationdate',
'pycsw:SpecificationDateType': 'specificationdatetype',
'pycsw:Creator': 'creator',
'pycsw:Publisher': 'publisher',
'pycsw:Contributor': 'contributor',
'pycsw:Relation': 'relation',
'pycsw:Links': 'links',
}
}
# TODO: make registry work using CSRF cookie.
@method_decorator(csrf_exempt, name='dispatch')
def csw_view(request, catalog=None):
"""CSW dispatch view.
Wraps the WSGI call and allows us to tweak any django settings.
"""
# PUT creates catalog, DELETE removes catalog.
# GET and POST are managed by pycsw.
if catalog and request.META['REQUEST_METHOD'] == 'PUT':
message = create_index(catalog)
return HttpResponse(message, status=200)
if catalog and request.META['REQUEST_METHOD'] == 'DELETE':
message, status = delete_records(catalog)
return HttpResponse(message, status=status)
env = request.META.copy()
env.update({'local.app_root': os.path.dirname(__file__),
'REQUEST_URI': request.build_absolute_uri()})
# pycsw prefers absolute urls, let's get them from the request.
url = request.build_absolute_uri().split('?')[0]
PYCSW['server']['url'] = url
PYCSW['metadata:main']['provider_url'] = url
# Enable CSW-T when a catalog is defined in the
if catalog:
PYCSW['manager']['transactions'] = 'true'
csw = server.Csw(PYCSW, env)
csw.orm = 'sqlalchemy'
status, content = csw.dispatch_wsgi()
status_code = int(status[0:3])
response = HttpResponse(content,
content_type=csw.contenttype,
status=status_code,
)
return response
def delete_records(catalog_slug):
'''
This function removes records from both csw database and elasticsearch
'''
pycsw_admin.delete_records(config.StaticContext(),
PYCSW['repository']['database'],
PYCSW['repository']['table'])
message, status = delete_index(catalog_slug)
return message, status
def delete_index(catalog, es=None):
if not es:
es, version = es_connect(url=REGISTRY_SEARCH_URL)
try:
es.delete(catalog)
message, status = 'Catalog {0} removed succesfully'.format(catalog), 200
except ElasticException:
message, status = 'Catalog does not exist!', 404
return message, status
def include_registry_tags(record_dict, xml_file,
query_string='{http://gis.harvard.edu/HHypermap/registry/0.1}property'):
parsed = etree.fromstring(xml_file, etree.XMLParser(resolve_entities=False))
registry_tags = parsed.findall(query_string)
registry_dict = {}
for tag in registry_tags:
registry_dict[tag.attrib['name']] = tag.attrib['value'].encode('ascii', 'ignore').decode('utf-8')
record_dict['registry'] = registry_dict
return record_dict
def parse_references(ref_string):
# Transform references into a list from pycsw string.
ref_list = ref_string.split(",,")[1:]
# Separate elements into list of list.
ref_list = [[data for data in ref.split(',')] for ref in ref_list]
# Construct list of dictionaries.
ref_list = [{'scheme': ref[0], 'url': ref[1].replace('^', '')} for ref in ref_list]
return ref_list
def record_to_dict(record):
# Encodes record title if it is not empty.
if record.title:
record.title = record.title.encode('ascii', 'ignore').decode('utf-8')
bbox = wkt2geom(record.wkt_geometry)
min_x, min_y, max_x, max_y = bbox[0], bbox[1], bbox[2], bbox[3]
record_dict = {
'title': record.title,
'abstract': record.abstract,
'title_alternate': record.title_alternate,
'checks_list': [],
'bbox': bbox,
'min_x': min_x,
'min_y': min_y,
'max_x': max_x,
'max_y': max_y,
'source': record.source,
'source_type': record.type,
'tile_url': '/layer/%s/wmts/%s/default_grid/{z}/{x}/{y}.png' % (record.identifier, record.title_alternate),
'layer_date': record.date_modified,
'layer_originator': record.creator,
'layer_identifier': record.identifier,
'links': {
'xml': '/'.join(['layer', record.identifier, 'xml']),
'yml': '/'.join(['layer', record.identifier, 'yml']),
'png': '/'.join(['layer', record.identifier, 'png'])
},
# 'rectangle': box(min_x, min_y, max_x, max_y),
'layer_geoshape': {
'type': 'envelope',
'coordinates': [
[min_x, max_y], [max_x, min_y]
]
}
}
if(record.format == 'OGC:WMS'):
legend_opts = {
'SERVICE': 'WMS',
'VERSION': '1.1.1',
'REQUEST': 'GetLegendGraphic',
'FORMAT': 'image/png',
'LAYER': record.title_alternate
}
record_dict['legend_url'] = '/layer/%s/service?' % record.identifier + urlencode(legend_opts)
record_dict = include_registry_tags(record_dict, record.xml)
if record.links:
record_dict['references'] = parse_references(record.links)
if record.source:
record_dict['source_host'] = urlparse(record.source).netloc
return record_dict
def check_index_exists(catalog, es=None):
if es is None:
es, version = es_connect(url=REGISTRY_SEARCH_URL)
result = False
indices = es.get('_aliases').keys()
if catalog in indices:
result = True
return result
def create_index(catalog, es=None, version=None):
if es is None:
es, version = es_connect(url=REGISTRY_SEARCH_URL)
mapping = es_mapping(version)
es.put(catalog, data=mapping)
return 'Catalog {0} created succesfully'.format(catalog)
def es_connect(url):
LOGGER.debug('Connecting to elasticsearch at {0}'.format(url))
if REGISTRY_SEARCH_USERNAME is not None and REGISTRY_SEARCH_PASSWORD is not None:
es = rawes.Elastic(url, auth=(REGISTRY_SEARCH_USERNAME, REGISTRY_SEARCH_PASSWORD))
else:
es = rawes.Elastic(url)
version = es.get('')['version']['number']
return es, version
def es_mapping(version):
mappings = {
"mappings": {
"layer": {
"properties": {
"registry": {
"type": "nested",
"properties": {
"category": {
"type": "string",
"index": "not_analyzed"
}
}
},
"references": {
"type": "nested",
"properties": {
"url": {"type": "string", "index": "not_analyzed"},
"scheme": {"type": "string", "index": "not_analyzed"}
}
},
"layer_geoshape": {
"type": "geo_shape",
"tree": "quadtree",
"precision": REGISTRY_MAPPING_PRECISION,
"distance_error_pct": REGISTRY_MAPPING_DIST_ERR_PCT
},
"layer_identifier": {"type": "string", "index": "not_analyzed"},
"title": text_field(version, copy_to="alltext"),
"abstract": text_field(version, copy_to="alltext"),
"alltext": text_field(version)
}
}
}
}
mapping_overrides = REGISTRY_MAPPINGS_OVERRIDES
try:
override_keys = mapping_overrides['mappings']['layer']['properties'].keys()
except:
override_keys = []
for key in override_keys:
mappings['mappings']['layer']['properties'][key] = mapping_overrides['mappings']['layer']['properties'][key]
return mappings
def text_field(version, **kwargs):
field_def = {"type": "string", "index": "analyzed"}
if version == '5.0.0':
field_def = {"type": "text"}
field_def.update(kwargs)
return field_def
def parse_url(url):
parsed_url = urlparse(url)
catalog_slug = parsed_url.path.split('/')[2]
return catalog_slug
class RegistryRepository(Repository):
def __init__(self, *args, **kwargs):
self.catalog = None
if args and hasattr(args[0], 'url'):
url = args[0].url
self.catalog = parse_url(url) if urlparse(url).path != '/csw' else None
try:
self.es, self.version = es_connect(url=REGISTRY_SEARCH_URL)
self.es_status = 200
except requests.exceptions.ConnectionError:
self.es_status = 404
database = PYCSW['repository']['database']
return super(RegistryRepository, self).__init__(database, context=config.StaticContext())
def insert(self, *args, **kwargs):
record = args[0]
LOGGER.debug('inserting record {0}'.format(record))
record.xml = record.xml.decode('utf-8')
super(RegistryRepository, self).insert(*args)
if self.es_status != 200:
return
if not check_index_exists(self.catalog):
LOGGER.warn('Cannot add layer {0}. Catalog {1} does not exist!'.format(record.identifier, self.catalog))
return
if not record.wkt_geometry:
LOGGER.warn('Cannot add layer {0}. Layer without wkt'.format(record.identifier))
return
es_dict = record_to_dict(record)
# TODO: Do not index wrong bounding boxes.
try:
self.es[self.catalog]['layer'].post(data=es_dict)
LOGGER.debug("Record {0} indexed".format(es_dict['title']))
except ElasticException as e:
LOGGER.error(e)
def delete(self, *args, **kwargs):
# Get layer uuid from pycsw.
uuid = args[0]['values'][0]
# Remove layer executing pycsw repository delete function.
count = super(RegistryRepository, self).delete(*args)
if self.es_status != 200:
return count
# Return layer id and catalog from elasticsearch.
_ , layer_id, layer_index = get_data_from_es(self.es, uuid)
self.es.delete('%s/layer/%s' % (layer_index, layer_id))
return count
def parse_get_params(request):
"""
parse all url get params that contains dots in a representation of
serializer field names, for example: d.docs.limit to d_docs_limit.
that makes compatible an actual API client with django-rest-framework
serializers.
:param request:
:return: QueryDict with parsed get params.
"""
get = request.GET.copy()
new_get = request.GET.copy()
for key in get.keys():
if key.count(".") > 0:
new_key = key.replace(".", "_")
new_get[new_key] = get.get(key)
del new_get[key]
return new_get
def parse_datetime_range_to_solr(time_filter):
start, end = parse_datetime_range(time_filter)
left = "*"
right = "*"
if start.get("parsed_datetime"):
left = start.get("parsed_datetime")
if start.get("is_common_era"):
left = start.get("parsed_datetime").isoformat().replace("+00:00", "") + 'Z'
if end.get("parsed_datetime"):
right = end.get("parsed_datetime")
if end.get("is_common_era"):
right = end.get("parsed_datetime").isoformat().replace("+00:00", "") + 'Z'
return "[{0} TO {1}]".format(left, right)
def parse_geo_box(geo_box_str):
"""
parses [-90,-180 TO 90,180] to a shapely.geometry.box
:param geo_box_str:
:return:
"""
from_point_str, to_point_str = parse_solr_geo_range_as_pair(geo_box_str)
from_point = parse_lat_lon(from_point_str)
to_point = parse_lat_lon(to_point_str)
rectangle = box(from_point[0], from_point[1], to_point[0], to_point[1])
return rectangle
def parse_datetime_range(time_filter):
"""
Parse the url param to python objects.
From what time range to divide by a.time.gap into intervals.
Defaults to q.time and otherwise 90 days.
Validate in API: re.search("\\[(.*) TO (.*)\\]", value)
:param time_filter: [2013-03-01 TO 2013-05-01T00:00:00]
:return: datetime.datetime(2013, 3, 1, 0, 0), datetime.datetime(2013, 5, 1, 0, 0)
"""
start, end = parse_solr_time_range_as_pair(time_filter)
start, end = parse_datetime(start), parse_datetime(end)
return start, end
def parse_solr_time_range_as_pair(time_filter):
"""
:param time_filter: [2013-03-01 TO 2013-05-01T00:00:00]
:return: (2013-03-01, 2013-05-01T00:00:00)
"""
pattern = "\\[(.*) TO (.*)\\]"
matcher = re.search(pattern, time_filter)
if matcher:
return matcher.group(1), matcher.group(2)
else:
raise Exception("Regex {0} couldn't parse {1}".format(pattern, time_filter))
def parse_solr_geo_range_as_pair(geo_box_str):
"""
:param geo_box_str: [-90,-180 TO 90,180]
:return: ("-90,-180", "90,180")
"""
pattern = "\\[(.*) TO (.*)\\]"
matcher = re.search(pattern, geo_box_str)
if matcher:
return matcher.group(1), matcher.group(2)
else:
raise Exception("Regex {0} could not parse {1}".format(pattern, geo_box_str))
def parse_lat_lon(point_str):
lat, lon = map(float, point_str.split(','))
return lat, lon
def parse_datetime(date_str):
"""
Parses a date string to date object.
for BCE dates, only supports the year part.
"""
is_common_era = True
date_str_parts = date_str.split("-")
if date_str_parts and date_str_parts[0] == '':
is_common_era = False
# for now, only support BCE years
# assume the datetime comes complete, but
# when it comes only the year, add the missing datetime info:
if len(date_str_parts) == 2:
date_str = date_str + "-01-01T00:00:00Z"
parsed_datetime = {
'is_common_era': is_common_era,
'parsed_datetime': None
}
if is_common_era:
if date_str == '*':
return parsed_datetime # open ended.
default = datetime.datetime.now().replace(
hour=0, minute=0, second=0, microsecond=0,
day=1, month=1
)
parsed_datetime['parsed_datetime'] = parse(date_str, default=default)
return parsed_datetime
parsed_datetime['parsed_datetime'] = date_str
return parsed_datetime
def gap_to_elastic(time_gap):
# elastic units link: https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#time-units
elastic_units = {
"YEARS": 'y',
"MONTHS": 'm',
"WEEKS": 'w',
"DAYS": 'd',
"HOURS": 'h',
"MINUTES": 'm',
"SECONDS": 's'
}
quantity, unit = parse_ISO8601(time_gap)
interval = "{0}{1}".format(str(quantity), elastic_units[unit[0]])
return interval
def parse_ISO8601(time_gap):
"""
P1D to (1, ("DAYS", isodate.Duration(days=1)).
P1Y to (1, ("YEARS", isodate.Duration(years=1)).
:param time_gap: ISO8601 string.
:return: tuple with quantity and unit of time.
"""
matcher = None
if time_gap.count("T"):
units = {
"H": ("HOURS", isodate.Duration(hours=1)),
"M": ("MINUTES", isodate.Duration(minutes=1)),
"S": ("SECONDS", isodate.Duration(seconds=1))
}
matcher = re.search("PT(\d+)([HMS])", time_gap)
if matcher:
quantity = int(matcher.group(1))
unit = matcher.group(2)
return quantity, units.get(unit)
else:
raise Exception("Does not match the pattern: {}".format(time_gap))
else:
units = {
"Y": ("YEARS", isodate.Duration(years=1)),
"M": ("MONTHS", isodate.Duration(months=1)),
"W": ("WEEKS", isodate.Duration(weeks=1)),
"D": ("DAYS", isodate.Duration(days=1))
}
matcher = re.search("P(\d+)([YMWD])", time_gap)
if matcher:
quantity = int(matcher.group(1))
unit = matcher.group(2)
else:
raise Exception("Does not match the pattern: {}".format(time_gap))
return quantity, units.get(unit)
class SearchSerializer(serializers.Serializer):
q_time = serializers.CharField(
required=False,
help_text="Constrains docs by time range. Either side can be '*' to signify open-ended. "
"Otherwise it must be in either format as given in the example. UTC time zone is implied. Example: "
"[2013-03-01 TO 2013-04-01T00:00:00]",
# default="[1900-01-01 TO 2016-12-31T00:00:00]"
)
search_engine_endpoint = serializers.CharField(
required=False,
help_text="Endpoint URL",
)
q_uuid = serializers.CharField(
required=False,
help_text="Layer uuid"
)
q_geo = serializers.CharField(
required=False,
help_text="A rectangular geospatial filter in decimal degrees going from the lower-left to the upper-right. "
"The coordinates are in lat,lon format. "
"Example: [-90,-180 TO 90,180]",
default="[-90,-180 TO 90,180]"
)
q_text = serializers.CharField(
required=False,
help_text="Constrains docs by keyword search query."
)
q_references_url = serializers.CharField(
required=False,
help_text="Constrains docs by reference url search query."
)
q_references_scheme = serializers.CharField(
required=False,
help_text="Constrains docs by reference scheme search query."
)
q_registry_text = serializers.CharField(
required=False,
help_text="Registry keyword search query"
)
q_text_fields = serializers.CharField(
required=False,
help_text="Constrains text search to a list of fields, optionally specifying a boost. "
"Fields are separated by the ':' character, and boosts are a decimal following the '^' character. "
"Example: title^3.0:abstract^1.0:publisher:creator",
default="title^5.0,abstract^2.0,alltext"
)
q_user = serializers.CharField(
required=False,
help_text="Constrains docs by matching exactly a certain user."
)
d_docs_limit = serializers.IntegerField(
required=False,
help_text="How many documents to return.",
default=100
)
d_docs_page = serializers.IntegerField(
required=False,
help_text="When documents to return are more than d_docs_limit they can be paginated by this value.",
default=1
)
d_docs_sort = serializers.ChoiceField(
required=False,
help_text="How to order the documents before returning the top X. 'score' is keyword search relevancy. "
"'time' is time descending. 'distance' is the distance between the doc and the middle of q.geo.",
default="score",
choices=["score", "time", "distance"]
)
a_time_limit = serializers.IntegerField(
required=False,
help_text="Non-0 triggers time/date range faceting. This value is the maximum number of time ranges to "
"return when a.time.gap is unspecified. This is a soft maximum; less will usually be returned. "
"A suggested value is 100. Note that a.time.gap effectively ignores this value. "
"See Solr docs for more details on the query/response format.",
default=0
)
a_time_gap = serializers.CharField(
required=False,
help_text="The consecutive time interval/gap for each time range. Ignores a.time.limit.The format is based on "
"a subset of the ISO-8601 duration format."
)
a_categories_limit = serializers.IntegerField(
required=False,
help_text="Listing the registry categories and their corresponding number of documents indexed. "
"The integer value Limits the received number of categories.",
)
a_hm_gridlevel = serializers.IntegerField(
required=False,
help_text="To explicitly specify the grid level, e.g. to let a user ask for greater or courser resolution "
"than the most recent request. Ignores a.hm.limit."
)
a_hm_limit = serializers.IntegerField(
required=False,
help_text=("Non-0 triggers heatmap/grid faceting. "
"This number is a soft maximum on thenumber of cells it should have. "
"There may be as few as 1/4th this number in return. "
"Note that a.hm.gridLevel can effectively ignore this value. "
"The response heatmap contains a counts grid that can be null or contain null rows when "
"all its values would be 0. See Solr docs for more details on the response format."),
default=0
)
a_hm_filter = serializers.CharField(
required=False,
help_text="To explicitly specify the grid level, e.g. to let a user ask for greater or courser resolution "
"than the most recent request. Ignores a.hm.limit."
)
a_text_limit = serializers.IntegerField(
required=False,
help_text="Returns the most frequently occurring words. WARNING: There is usually a significant performance "
"hit in this due to the extremely high cardinality.",
default=0
)
a_user_limit = serializers.IntegerField(
required=False,
help_text="Returns the most frequently occurring users.",
default=0
)
original_response = serializers.IntegerField(
required=False,
help_text="Returns te original search engine response.",
default=0
)
def validate_q_time(self, value):
"""
Would be for example: [2013-03-01 TO 2013-04-01T00:00:00] and/or [* TO *]
Returns a valid sorl value. [2013-03-01T00:00:00Z TO 2013-04-01T00:00:00Z] and/or [* TO *]
"""
try:
range = parse_datetime_range_to_solr(value)
return range
except Exception as e:
raise serializers.ValidationError(e)
def validate_q_geo(self, value):
"""
Would be for example: [-90,-180 TO 90,180]
"""
try:
rectangle = parse_geo_box(value)
return "[{0},{1} TO {2},{3}]".format(
rectangle.bounds[0],
rectangle.bounds[1],
rectangle.bounds[2],
rectangle.bounds[3],
)
except Exception as e:
raise serializers.ValidationError(e)
def validate_d_docs_page(self, value):
"""
paginations cant be zero or negative.
:param value:
:return:
"""
if value <= 0:
raise serializers.ValidationError("d_docs_page cant be zero or negative")
return value
def create_nested_json(json_path, json_query, json_field):
return {
"nested": {
"path": json_path,
"query": {
"multi_match": {
"query": json_query,
"fields": [json_field]
}
}
}
}
def elasticsearch(serializer, catalog):
"""
https://www.elastic.co/guide/en/elasticsearch/reference/current/_the_search_api.html
:param serializer:
:return:
"""
# Make sure elasticsearch connection is available.
es, version = es_connect(url=REGISTRY_SEARCH_URL)
es_version = int(version[0])
search_engine_endpoint = "_search"
if catalog:
search_engine_endpoint = "{0}/_search".format(catalog)
search_endpoint = serializer.validated_data.get("search_engine_endpoint")
if search_endpoint is not None:
search_engine_endpoint = "{0}/{1}".format(search_endpoint, search_engine_endpoint)
q_text = serializer.validated_data.get("q_text")
q_registry_text = serializer.validated_data.get("q_registry_text")
q_text_fields = serializer.validated_data.get("q_text_fields").split(',')
q_time = serializer.validated_data.get("q_time")
q_geo = serializer.validated_data.get("q_geo")
q_user = serializer.validated_data.get("q_user")
q_uuid = serializer.validated_data.get("q_uuid")
q_references_url = serializer.validated_data.get("q_references_url")
q_references_scheme = serializer.validated_data.get("q_references_scheme")
d_docs_sort = serializer.validated_data.get("d_docs_sort")
d_docs_limit = int(serializer.validated_data.get("d_docs_limit"))
d_docs_page = int(serializer.validated_data.get("d_docs_page"))
a_time_gap = serializer.validated_data.get("a_time_gap")
a_time_limit = serializer.validated_data.get("a_time_limit")
a_categories_limit = serializer.validated_data.get("a_categories_limit")
a_hm_gridlevel = serializer.validated_data.get("a_hm_gridlevel")
a_hm_limit = serializer.validated_data.get("a_hm_limit")
a_hm_filter = serializer.validated_data.get("a_hm_filter")
original_response = serializer.validated_data.get("original_response")
# Dict for search on Elastic engine
must_array = []