forked from geosolutions-it/geoserver-restconfig
-
Notifications
You must be signed in to change notification settings - Fork 27
/
catalog.py
1471 lines (1255 loc) · 54.7 KB
/
catalog.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
# -*- coding: utf-8 -*-
#########################################################################
#
# Copyright 2019, GeoSolutions Sas.
# All rights reserved.
#
# This source code is licensed under the MIT license found in the
# LICENSE.txt file in the root directory of this source tree.
#
#########################################################################
import logging
from datetime import datetime, timedelta
from geoserver.layer import Layer
from geoserver.resource import FeatureType
from geoserver.service import service_from_index, ServiceWmsSettings
from geoserver.store import (
coveragestore_from_index,
datastore_from_index,
wmsstore_from_index,
UnsavedDataStore,
UnsavedCoverageStore,
UnsavedWmsStore
)
from geoserver.style import Style
from geoserver.support import prepare_upload_bundle, build_url
from geoserver.layergroup import LayerGroup, UnsavedLayerGroup
from geoserver.workspace import workspace_from_index, Workspace
from geoserver.security import user_from_index
from geoserver.settings import GlobalSettings
import os
import re
import base64
from xml.etree.ElementTree import XML
from xml.parsers.expat import ExpatError
import requests
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
from six import string_types
try:
from past.builtins import basestring
except ImportError:
pass
try:
from urllib.parse import urlparse, urlencode, parse_qsl
except ImportError:
from urlparse import urlparse, parse_qsl
from urllib import urlencode
try:
from json.decoder import JSONDecodeError
except ImportError:
JSONDecodeError = ValueError
logger = logging.getLogger("gsconfig.catalog")
class UploadError(Exception):
pass
class ConflictingDataError(Exception):
pass
class AmbiguousRequestError(Exception):
pass
class FailedRequestError(Exception):
pass
def _name(named):
"""Get the name out of an object. This varies based on the type of the input:
* the "name" of a string is itself
* the "name" of None is itself
* the "name" of an object with a property named name is that property -
as long as it's a string
* otherwise, we raise a ValueError
"""
if isinstance(named, string_types) or named is None:
return named
elif hasattr(named, 'name') and isinstance(named.name, string_types):
return named.name
else:
raise ValueError(f"Can't interpret {named} as a name or a configuration object")
class Catalog(object):
"""
The GeoServer catalog represents all of the information in the GeoServer
configuration. This includes:
- Stores of geospatial data
- Resources, or individual coherent datasets within stores
- Styles for resources
- Layers, which combine styles with resources to create a visible map layer
- LayerGroups, which alias one or more layers for convenience
- Workspaces, which provide logical grouping of Stores
- Maps, which provide a set of OWS services with a subset of the server's
Layers
- Namespaces, which provide unique identifiers for resources
"""
def __init__(self, service_url, username="admin", password="geoserver", validate_ssl_certificate=True, access_token=None, retries=3, backoff_factor=0.9):
self.service_url = service_url.strip("/")
self.username = username
self.password = password
self.validate_ssl_certificate = validate_ssl_certificate
self.access_token = access_token
self.retries = retries
self.backoff_factor = backoff_factor
self.setup_connection(retries=self.retries, backoff_factor=self.backoff_factor)
self._cache = {}
self._version = None
def __getstate__(self):
'''http connection cannot be pickled'''
state = dict(vars(self))
state.pop('http', None)
state['http'] = None
return state
def __setstate__(self, state):
'''restore http connection upon unpickling'''
self.__dict__.update(state)
self.setup_connection(retries=self.retries, backoff_factor=self.backoff_factor)
def setup_connection(self, retries=3, backoff_factor=0.9):
self.client = requests.session()
self.client.verify = self.validate_ssl_certificate
parsed_url = urlparse(self.service_url)
retry = Retry(
total = retries or self.retries,
status = retries or self.retries,
read = retries or self.retries,
connect = retries or self.retries,
backoff_factor = backoff_factor or self.backoff_factor,
status_forcelist = [502, 503, 504],
method_whitelist = set(['HEAD', 'TRACE', 'GET', 'PUT', 'POST', 'OPTIONS', 'DELETE'])
)
self.client.mount(f"{parsed_url.scheme}://", HTTPAdapter(max_retries=retry))
def http_request(self, url, data=None, method='get', headers={}, files=None):
req_method = getattr(self.client, method.lower())
if self.access_token:
headers['Authorization'] = f"Bearer {self.access_token}"
parsed_url = urlparse(url)
params = parse_qsl(parsed_url.query.strip())
params.append(('access_token', self.access_token))
params = urlencode(params)
url = f"{parsed_url.scheme}://{parsed_url.netloc}{parsed_url.path}?{params}"
elif self.username and self.password:
valid_uname_pw = base64.b64encode(
f"{self.username}:{self.password}".encode("utf-8")).decode("ascii")
headers['Authorization'] = f'Basic {valid_uname_pw}'
return req_method(url, headers=headers, data=data, files=files)
def get_version(self):
'''obtain the version or just 2.2.x if < 2.3.x
Raises:
FailedRequestError: If the request fails.
'''
if self._version:
return self._version
url = f"{self.service_url}/about/version.xml"
resp = self.http_request(url)
version = None
if resp.status_code == 200:
content = resp.content
if isinstance(content, bytes):
content = content.decode('UTF-8')
dom = XML(content)
resources = dom.findall("resource")
for resource in resources:
if resource.attrib["name"] == "GeoServer":
try:
version = resource.find("Version").text
break
except AttributeError:
pass
# This will raise an exception if the catalog is not available
# If the catalog is available but could not return version information,
# it is an old version that does not support that
if version is None:
# just to inform that version < 2.3.x
version = "2.2.x"
self._version = version
return version
def get_short_version(self):
'''obtain the shory geoserver version
'''
gs_version = self.get_version()
match = re.compile(r'[^\d.]+')
return match.sub('', gs_version).strip('.')
def delete(self, config_object, purge=None, recurse=False):
"""
send a delete request
XXX [more here]
"""
href = urlparse(config_object.href)
netloc = urlparse(self.service_url).netloc
rest_url = href._replace(netloc=netloc).geturl()
# rest_url = config_object.href
params = []
# purge deletes the SLD from disk when a style is deleted
if purge:
params.append(f"purge={str(purge)}")
# recurse deletes the resource when a layer is deleted.
if recurse:
params.append("recurse=true")
if params:
rest_url = f"{rest_url}?{'&'.join(params)}"
headers = {
"Content-type": "application/xml",
"Accept": "application/xml"
}
resp = self.http_request(rest_url, method='delete', headers=headers)
if resp.status_code != 200:
raise FailedRequestError(f'Failed to make DELETE request: {resp.status_code}, {resp.text}')
self._cache.clear()
# do we really need to return anything other than None?
return (resp)
def get_xml(self, rest_url):
cached_response = self._cache.get(rest_url)
def is_valid(cached_response):
return cached_response is not None and datetime.now() - cached_response[0] < timedelta(seconds=5)
def parse_or_raise(xml):
try:
if not isinstance(xml, string_types):
xml = xml.decode()
return XML(xml)
except (ExpatError, SyntaxError) as e:
msg = "GeoServer gave non-XML response for [GET %s]: %s"
msg = msg % (rest_url, xml)
raise Exception(msg, e)
if is_valid(cached_response):
raw_text = cached_response[1]
return parse_or_raise(raw_text)
else:
resp = self.http_request(rest_url, headers={"Accept": "application/xml"})
if resp.status_code == 200:
content = resp.content
if isinstance(content, bytes):
content = content.decode('UTF-8')
self._cache[rest_url] = (datetime.now(), content)
return parse_or_raise(content)
else:
raise FailedRequestError(resp.content)
def reload(self):
url = f"{self.service_url}/reload"
resp = self.http_request(url, method='post')
self._cache.clear()
return resp
def reset(self):
url = f"{self.service_url}/reset"
resp = self.http_request(url, method='post')
self._cache.clear()
return resp
def save(self, obj, content_type="application/xml"):
"""
saves an object to the REST service
gets the object's REST location and the data from the object,
then POSTS the request.
"""
href = urlparse(obj.href)
netloc = urlparse(self.service_url).netloc
rest_url = href._replace(netloc=netloc).geturl()
data = obj.message()
headers = {
"Content-type": content_type,
"Accept": content_type
}
logger.debug(f"{obj.save_method} {obj.href}")
resp = self.http_request(rest_url, method=obj.save_method.lower(), data=data, headers=headers)
if resp.status_code not in (200, 201):
raise FailedRequestError(f'Failed to save to Geoserver catalog: {resp.status_code}, {resp.text}')
self._cache.clear()
return resp
def _return_first_item(self, _list):
if len(_list) == 0:
return None
else:
return _list[0]
def get_stores(self, names=None, workspaces=None):
'''
Returns a list of stores in the catalog. If workspaces is specified will only return stores in those workspaces.
If names is specified, will only return stores that match.
names can either be a comma delimited string or an array.
Will return an empty list if no stores are found.
'''
if workspaces:
if isinstance(workspaces, Workspace):
workspaces = [workspaces]
elif isinstance(workspaces, list) and [w for w in workspaces if isinstance(w, Workspace)]:
# nothing
pass
else:
workspaces = self.get_workspaces(names=workspaces)
else:
workspaces = self.get_workspaces()
stores = []
for ws in workspaces:
ds_list = self.get_xml(ws.datastore_url)
cs_list = self.get_xml(ws.coveragestore_url)
wms_list = self.get_xml(ws.wmsstore_url)
stores.extend([datastore_from_index(self, ws, n) for n in ds_list.findall("dataStore")])
stores.extend([coveragestore_from_index(self, ws, n) for n in cs_list.findall("coverageStore")])
stores.extend([wmsstore_from_index(self, ws, n) for n in wms_list.findall("wmsStore")])
if names is None:
names = []
elif isinstance(names, string_types):
names = [s.strip() for s in names.split(',') if s.strip()]
elif not isinstance(names, list):
names = [names]
if len(names) and not isinstance(names[0], string_types):
names = [_n.name for _n in names]
if stores and names:
return [_s for _s in stores if _s.name in names]
return stores
def get_store(self, name, workspace=None):
'''
Returns a single store object.
Will return None if no store is found.
Will raise an error if more than one store with the same name is found.
'''
stores = self.get_stores(workspaces=[workspace], names=name)
return self._return_first_item(stores)
def create_datastore(self, name, workspace=None):
if isinstance(workspace, string_types):
workspace = self.get_workspaces(names=workspace)[0]
elif workspace is None:
workspace = self.get_default_workspace()
return UnsavedDataStore(self, name, workspace)
def create_wmsstore(self, name, workspace = None, user = None, password = None):
if workspace is None:
workspace = self.get_default_workspace()
return UnsavedWmsStore(self, name, workspace, user, password)
def create_wmslayer(self, workspace, store, name, nativeName=None):
headers = {
"Content-type": "text/xml",
"Accept": "application/xml"
}
# if not provided, fallback to name - this is what geoserver will do
# anyway but nativeName needs to be provided if name is invalid xml
# as this will cause verification errors since geoserver 2.6.1
if nativeName is None:
nativeName = name
url = store.href.replace('.xml', '/wmslayers')
data = f"<wmsLayer><name>{name}</name><nativeName>{nativeName}</nativeName></wmsLayer>"
resp = self.http_request(url, method='post', data=data, headers=headers)
if resp.status_code not in (200, 201):
raise FailedRequestError(f'Failed to create WMS layer: {resp.status_code}, {resp.text}')
self._cache.clear()
return self.get_layer(name)
def add_data_to_store(self, store, name, data, workspace=None, overwrite = False, charset = None):
if isinstance(store, string_types):
store = self.get_stores(names=store, workspaces=[workspace])[0]
if workspace is not None and workspace:
workspace = _name(workspace)
assert store.workspace.name == workspace, f"Specified store ({store}) is not in specified workspace ({workspace})!"
else:
workspace = store.workspace.name
store = store.name
if isinstance(data, dict):
bundle = prepare_upload_bundle(name, data)
else:
bundle = data
params = dict()
if overwrite:
params["update"] = "overwrite"
if charset is not None and charset:
params["charset"] = charset
params["filename"] = f"{name}.zip"
params["target"] = "shp"
# params["configure"] = "all"
headers = {'Content-Type': 'application/zip', 'Accept': 'application/xml'}
upload_url = build_url(
self.service_url,
[
"workspaces",
workspace,
"datastores",
store,
"file.shp"
],
params
)
try:
with open(bundle, "rb") as f:
data = f.read()
resp = self.http_request(upload_url, method='put', data=data, headers=headers)
if resp.status_code != 201:
raise FailedRequestError(f'Failed to add data to store {store} : {resp.status_code}, {resp.text}')
self._cache.clear()
finally:
pass
def create_featurestore(self, name, data, workspace=None, overwrite=False, charset=None):
if workspace is None:
workspace = self.get_default_workspace()
workspace = _name(workspace)
if not overwrite:
stores = self.get_stores(names=name, workspaces=[workspace])
if len(stores) > 0:
msg = f"There is already a store named {name} in workspace {workspace}"
raise ConflictingDataError(msg)
params = dict()
if charset is not None and charset:
params['charset'] = charset
url = build_url(
self.service_url,
[
"workspaces",
workspace,
"datastores",
name,
"file.shp"
],
params
)
# PUT /workspaces/<ws>/datastores/<ds>/file.shp
headers = {
"Content-type": "application/zip",
"Accept": "application/xml"
}
if isinstance(data, dict):
logger.debug('Data is NOT a zipfile')
archive = prepare_upload_bundle(name, data)
else:
logger.debug('Data is a zipfile')
archive = data
file_obj = open(archive, 'rb')
try:
resp = self.http_request(url, method='put', data=file_obj, headers=headers)
if resp.status_code != 201:
raise FailedRequestError(f'Failed to create FeatureStore {name} : {resp.status_code}, {resp.text}')
self._cache.clear()
finally:
file_obj.close()
def create_imagemosaic(self, name, data, configure='first', workspace=None, overwrite=False, charset=None, coverageName=None):
if workspace is None:
workspace = self.get_default_workspace()
workspace = _name(workspace)
if not overwrite:
store = self.get_stores(names=name, workspaces=[workspace])
if store:
raise ConflictingDataError(f"There is already a store named {name}")
params = dict()
if charset is not None and charset:
params['charset'] = charset
if configure.lower() not in ('first', 'none', 'all'):
raise ValueError("configure most be one of: first, none, all")
params['configure'] = configure.lower()
if coverageName:
params['coverageName'] = coverageName
store_type = "file.imagemosaic"
contet_type = "application/zip"
if hasattr(data, 'read'):
# Adding this check only to pass tests. We should drop support for passing a file object
upload_data = data
elif isinstance(data, string_types):
if os.path.splitext(data)[-1] == ".zip":
upload_data = open(data, 'rb')
else:
store_type = "external.imagemosaic"
contet_type = "text/plain"
upload_data = data if data.startswith("file:") else f"file:{data}"
else:
raise ValueError(f"ImageMosaic Dataset or directory: {data} is incorrect")
url = build_url(
self.service_url,
[
"workspaces",
workspace,
"coveragestores",
name,
store_type
],
params
)
# PUT /workspaces/<ws>/coveragestores/<name>/file.imagemosaic?configure=none
headers = {
"Content-type": contet_type,
"Accept": "application/xml"
}
try:
resp = self.http_request(url, method='put', data=upload_data, headers=headers)
if resp.status_code != 201:
raise FailedRequestError(f'Failed to create ImageMosaic {url} : {resp.status_code}, {resp.text}')
self._cache.clear()
finally:
if hasattr(upload_data, "close"):
upload_data.close()
return self.get_stores(names=name, workspaces=[workspace])[0]
def create_coveragestore(self, name, workspace=None, path=None, type='GeoTIFF',
create_layer=True, layer_name=None, source_name=None, upload_data=False, contet_type="image/tiff",
overwrite=False):
"""
Create a coveragestore for locally hosted rasters.
If create_layer is set to true, will create a coverage/layer.
layer_name and source_name are only used if create_layer ia enabled. If not specified, the raster name will be used for both.
"""
if path is None:
raise Exception('You must provide a full path to the raster')
if layer_name is not None and ":" in layer_name:
ws_name, layer_name = layer_name.split(':')
allowed_types = [
'ImageMosaic',
'GeoTIFF',
'Gtopo30',
'WorldImage',
'AIG',
'ArcGrid',
'DTED',
'EHdr',
'ERDASImg',
'ENVIHdr',
'GeoPackage (mosaic)',
'NITF',
'RPFTOC',
'RST',
'VRT'
]
if type is None:
raise Exception('Type must be declared')
elif type not in allowed_types:
raise Exception(f"Type must be one of {', '.join(allowed_types)}")
if workspace is None:
workspace = self.get_default_workspace()
workspace = _name(workspace)
if not overwrite:
stores = self.get_stores(names=name, workspaces=[workspace])
if len(stores) > 0:
msg = f"There is already a store named {name} in workspace {workspace}"
raise ConflictingDataError(msg)
if upload_data is False:
cs = UnsavedCoverageStore(self, name, workspace)
cs.type = type
cs.url = path if path.startswith("file:") else f"file:{path}"
self.save(cs)
if create_layer:
if layer_name is None:
layer_name = os.path.splitext(os.path.basename(path))[0]
if source_name is None:
source_name = os.path.splitext(os.path.basename(path))[0]
data = f"<coverage><name>{layer_name}</name><nativeName>{source_name}</nativeName></coverage>"
url = f"{self.service_url}/workspaces/{workspace}/coveragestores/{name}/coverages.xml"
headers = {"Content-type": "application/xml"}
resp = self.http_request(url, method='post', data=data, headers=headers)
if resp.status_code != 201:
raise FailedRequestError('Failed to create coverage/layer {} for : {}, {}'.format(layer_name, name,
resp.status_code, resp.text))
self._cache.clear()
return self.get_resources(names=layer_name, workspaces=[workspace])[0]
else:
data = open(path, 'rb')
params = {"configure": "first", "coverageName": name}
url = build_url(
self.service_url,
[
"workspaces",
workspace,
"coveragestores",
name,
f"file.{type.lower()}"
],
params
)
headers = {"Content-type": contet_type}
resp = self.http_request(url, method='put', data=data, headers=headers)
if hasattr(data, "close"):
data.close()
if resp.status_code != 201:
raise FailedRequestError('Failed to create coverage/layer {} for : {}, {}'.format(layer_name, name, resp.status_code, resp.text))
return self.get_stores(names=name, workspaces=[workspace])[0]
def add_granule(self, data, store, workspace=None):
'''Harvest/add a granule into an existing imagemosaic'''
ext = os.path.splitext(data)[-1]
if ext == ".zip":
type = "file.imagemosaic"
upload_data = open(data, 'rb')
headers = {
"Content-type": "application/zip",
"Accept": "application/xml"
}
else:
type = "external.imagemosaic"
upload_data = data if data.startswith("file:") else f"file:{data}"
headers = {
"Content-type": "text/plain",
"Accept": "application/xml"
}
params = dict()
workspace_name = workspace
if isinstance(store, string_types):
store_name = store
else:
store_name = store.name
workspace_name = store.workspace.name
if workspace_name is None:
raise ValueError("Must specify workspace")
url = build_url(
self.service_url,
[
"workspaces",
workspace_name,
"coveragestores",
store_name,
type
],
params
)
try:
resp = self.http_request(url, method='post', data=upload_data, headers=headers)
if resp.status_code != 202:
raise FailedRequestError(f'Failed to add granule to mosaic {store} : {resp.status_code}, {resp.text}')
self._cache.clear()
finally:
if hasattr(upload_data, "close"):
upload_data.close()
# maybe return a list of all granules?
return None
def delete_granule(self, coverage, store, granule_id, workspace=None):
'''Deletes a granule of an existing imagemosaic'''
params = dict()
workspace_name = workspace
if isinstance(store, string_types):
store_name = store
else:
store_name = store.name
workspace_name = store.workspace.name
if workspace_name is None:
raise ValueError("Must specify workspace")
url = build_url(
self.service_url,
[
"workspaces",
workspace_name,
"coveragestores",
store_name,
"coverages",
coverage,
"index/granules",
granule_id,
".json"
],
params
)
# DELETE /workspaces/<ws>/coveragestores/<name>/coverages/<coverage>/index/granules/<granule_id>.json
headers = {
"Content-type": "application/json",
"Accept": "application/json"
}
resp = self.http_request(url, method='delete', headers=headers)
if resp.status_code != 200:
raise FailedRequestError(f'Failed to delete granule from mosaic {store} : {resp.status_code}, {resp.text}')
self._cache.clear()
# maybe return a list of all granules?
return None
def list_granules(self, coverage, store, workspace=None, filter=None, limit=None, offset=None):
'''List granules of an imagemosaic'''
params = dict()
if filter is not None and filter:
params['filter'] = filter
if limit is not None and limit:
params['limit'] = limit
if offset is not None and offset:
params['offset'] = offset
workspace_name = workspace
if isinstance(store, string_types):
store_name = store
else:
store_name = store.name
workspace_name = store.workspace.name
if workspace_name is None:
raise ValueError("Must specify workspace")
url = build_url(
self.service_url,
[
"workspaces",
workspace_name,
"coveragestores",
store_name,
"coverages",
coverage,
"index/granules.json"
],
params
)
# GET /workspaces/<ws>/coveragestores/<name>/coverages/<coverage>/index/granules.json
headers = {
"Content-type": "application/json",
"Accept": "application/json"
}
resp = self.http_request(url, headers=headers)
if resp.status_code != 200:
raise FailedRequestError(f'Failed to list granules in mosaic {store} : {resp.status_code}, {resp.text}')
self._cache.clear()
return resp.json()
def mosaic_coverages(self, store):
'''Returns all coverages in a coverage store'''
params = dict()
url = build_url(
self.service_url,
[
"workspaces",
store.workspace.name,
"coveragestores",
store.name,
"coverages.json"
],
params
)
# GET /workspaces/<ws>/coveragestores/<name>/coverages.json
headers = {
"Content-type": "application/json",
"Accept": "application/json"
}
resp = self.http_request(url, headers=headers)
if resp.status_code != 200:
raise FailedRequestError(f'Failed to get mosaic coverages {store} : {resp.status_code}, {resp.text}')
self._cache.clear()
return resp.json()
def mosaic_coverage_schema(self, coverage, store, workspace):
'''Returns the schema of a coverage in a coverage store'''
params = dict()
url = build_url(
self.service_url,
[
"workspaces",
workspace,
"coveragestores",
store,
"coverages",
coverage,
"index.json"
],
params
)
# GET /workspaces/<ws>/coveragestores/<name>/coverages/<coverage>/index.json
headers = {
"Content-type": "application/json",
"Accept": "application/json"
}
resp = self.http_request(url, headers=headers)
if resp.status_code != 200:
raise FailedRequestError(f'Failed to get mosaic schema {store} : {resp.status_code}, {resp.text}')
self._cache.clear()
return resp.json()
def publish_featuretype(self, name, store, native_crs, srs=None, jdbc_virtual_table=None, native_name=None):
'''Publish a featuretype from data in an existing store'''
# @todo native_srs doesn't seem to get detected, even when in the DB
# metadata (at least for postgis in geometry_columns) and then there
# will be a misconfigured layer
if native_crs is None:
raise ValueError("must specify native_crs")
srs = srs or native_crs
feature_type = FeatureType(self, store.workspace, store, name)
# because name is the in FeatureType base class, work around that
# and hack in these others that don't have xml properties
feature_type.dirty['name'] = name
feature_type.dirty['srs'] = srs
feature_type.dirty['nativeCRS'] = native_crs
feature_type.enabled = True
feature_type.advertised = True
feature_type.title = name
if native_name is not None and native_name:
feature_type.native_name = native_name
headers = {
"Content-type": "application/xml",
"Accept": "application/xml"
}
resource_url = store.resource_url
if jdbc_virtual_table is not None and jdbc_virtual_table:
feature_type.metadata = ({'JDBC_VIRTUAL_TABLE': jdbc_virtual_table})
params = dict()
resource_url = build_url(
self.service_url,
[
"workspaces",
store.workspace.name,
"datastores", store.name,
"featuretypes.xml"
],
params
)
resp = self.http_request(resource_url, method='post', data=feature_type.message(), headers=headers)
if resp.status_code not in (200, 201, 202):
raise FailedRequestError(f'Failed to publish feature type {name} : {resp.status_code}, {resp.text}')
self._cache.clear()
feature_type.fetch()
return feature_type
def get_resources(self, names=None, stores=None, workspaces=None):
'''
Resources include feature stores, coverage stores and WMS stores, however does not include layer groups.
names, stores and workspaces can be provided as a comma delimited strings or as arrays, and are used for filtering.
Will always return an array.
'''
if workspaces and not isinstance(workspaces, list):
workspaces = [workspaces]
if not stores:
_stores = self.get_stores(
workspaces=workspaces
)
elif not isinstance(stores, list):
_stores = [stores]
else:
_stores = stores
if isinstance(names, string_types):
names = [s.strip() for s in names.split(',')]
resources = []
for s in _stores:
try:
if isinstance(s, string_types):
if workspaces:
for w in workspaces:
if self.get_store(s, workspace=w):
s = self.get_store(s, workspace=w)
if s:
if names:
for name in names:
_res = s.get_resources(name=name)
if _res:
resources.append(_res)
else:
resources.extend(s.get_resources())
else:
s = self.get_store(s)
if s:
if names:
for name in names:
_res = s.get_resources(name=name)
if _res:
resources.append(_res)
else:
resources.extend(s.get_resources())
elif names:
for name in names:
_res = s.get_resources(name=name)
if _res:
resources.append(_res)
else:
resources.extend(s.get_resources())
except FailedRequestError:
continue
if resources and names:
return ([resource for resource in resources if resource.name in names])
return resources
def get_resource(self, name=None, store=None, workspace=None):
'''
returns a single resource object.
Will return None if no resource is found.
Will raise an error if more than one resource with the same name is found.
'''
if store:
resources = self.get_resources(names=name, stores=[store], workspaces=[workspace])
else:
resources = self.get_resources(names=name, workspaces=[workspace])
return self._return_first_item(resources)
def get_layer(self, name):
try:
lyr = Layer(self, name)
lyr.fetch()
return lyr
except FailedRequestError:
return None
def get_layers(self, resource=None):
if isinstance(resource, string_types):
ws_name = None
if self.get_short_version() >= "2.13":
if ":" in resource:
ws_name, resource = resource.split(':')
if ws_name:
resources = self.get_resources(names=resource, workspaces=[ws_name])
else:
resources = self.get_resources(names=resource)
resource = self._return_first_item(resources)
layers_url = f"{self.service_url}/layers.xml"
data = self.get_xml(layers_url)
lyrs = [Layer(self, l.find("name").text) for l in data.findall("layer")]
if resource is not None:
lyrs = [l for l in lyrs if l.resource.href == resource.href]
# TODO: Filter by style
return lyrs