-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy path_stores.py
1991 lines (1741 loc) · 69.1 KB
/
_stores.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 math
import re
from collections import Counter, defaultdict
from copy import copy
from dataclasses import dataclass
from datetime import date, datetime, timedelta
from enum import Enum, auto
from itertools import groupby
from typing import (
Dict,
Generator,
Iterable,
Iterator,
List,
Optional,
Sequence,
Set,
Tuple,
Union,
)
from uuid import UUID
import pytz
import dateutil.parser
import structlog
from cachetools.func import lru_cache, ttl_cache
from dateutil import tz
from geoalchemy2 import WKBElement, shape as geo_shape
from geoalchemy2.shape import from_shape, to_shape
from shapely.geometry.base import BaseGeometry
from sqlalchemy import DDL, String, and_, exists, func, literal, or_, select, union_all
from sqlalchemy.dialects import postgresql as postgres
from sqlalchemy.dialects.postgresql import TSTZRANGE
from sqlalchemy.engine import Engine
from sqlalchemy.sql import Select
try:
from cubedash._version import version as explorer_version
except ModuleNotFoundError:
explorer_version = "ci-test-pipeline"
from datacube import Datacube
from datacube.drivers.postgres._fields import PgDocField
from datacube.index import Index
from datacube.model import Dataset, DatasetType, Range
from datacube.utils.geometry import Geometry
from cubedash import _utils
from cubedash._utils import ODC_DATASET, ODC_DATASET_LOCATION, ODC_DATASET_TYPE
from cubedash.summary import RegionInfo, TimePeriodOverview, _extents, _schema
from cubedash.summary._extents import (
ProductArrival,
RegionSummary,
dataset_changed_expression,
datetime_expression,
)
from cubedash.summary._schema import (
DATASET_SPATIAL,
FOOTPRINT_SRID_EXPRESSION,
PRODUCT,
REGION,
SPATIAL_QUALITY_STATS,
TIME_OVERVIEW,
PleaseRefresh,
get_srid_name,
refresh_supporting_views,
)
from cubedash.summary._summarise import Summariser
DEFAULT_TTL = 90
_DEFAULT_REFRESH_OLDER_THAN = timedelta(hours=23)
_LOG = structlog.get_logger()
# The default grouping epsg code to use on init of a new Explorer schema.
#
# We'll use a global equal area.
DEFAULT_EPSG = 6933
timezone = pytz.timezone("Australia/Darwin")
class ItemSort(Enum):
# The fastest, but paging is unusable.
UNSORTED = auto()
# Sort by time then dataset id. Stable for paging.
DEFAULT_SORT = auto()
# Sort by time indexed into ODC, most recent first.
# (this doesn't work very efficiently with other filters, like bbox.)
RECENTLY_ADDED = auto()
class GenerateResult(Enum):
"""What happened in a product refresh task?"""
# Product was newly generated (or force-refreshed to recreate everything).
CREATED = 2
# Updated the existing summaries (for months that changed)
UPDATED = 3
# No new changes found.
NO_CHANGES = 1
# Exception was thrown
ERROR = 4
# A unsupported product (eg. Unsupported CRS)
UNSUPPORTED = 5
@dataclass
class ProductSummary:
name: str
dataset_count: int
# Null when dataset_count == 0
time_earliest: Optional[datetime]
time_latest: Optional[datetime]
source_products: List[str]
derived_products: List[str]
# Metadata values that are the same on every dataset.
# (on large products this is judged via sampling, so may not be 100%)
fixed_metadata: Dict[str, Union[str, float, int, datetime]]
# The db-server-local time when this product record+extent was refreshed.
last_refresh_time: datetime
# The `last_refresh_time` last time when summary generation was last fully completed.
# (To find changes, we'll scan any datasets newer than this date)
last_successful_summary_time: datetime = None
# Not recommended for use by users, as ids are local and internal.
# The 'name' is typically used as an identifier, and with ODC itself.
id_: Optional[int] = None
def iter_months(self) -> Generator[date, None, None]:
"""
Iterate through all months in its time range.
"""
if self.dataset_count == 0:
return
start = self.time_earliest.astimezone(timezone) if self.time_earliest else self.time_earliest
end = self.time_latest.astimezone(timezone) if self.time_latest else self.time_latest
if start > end:
raise ValueError(f"Start date must precede end date ({start} < {end})")
year = start.year
month = start.month
while True:
yield date(year, month, 1)
month += 1
if month == 13:
month = 1
year += 1
if (year, month) > (end.year, end.month):
return
@dataclass
class DatasetItem:
dataset_id: UUID
bbox: object
product_name: str
geometry: Geometry
region_code: str
creation_time: datetime
center_time: datetime
odc_dataset: Optional[Dataset] = None
@property
def geom_geojson(self) -> Optional[Dict]:
if self.geometry is None:
return None
return self.geometry.__geo_interface__
def as_geojson(self):
return dict(
id=self.dataset_id,
type="Feature",
bbox=self.bbox,
geometry=self.geom_geojson,
properties={
"datetime": self.center_time,
"odc:product": self.product_name,
"odc:processing_datetime": self.creation_time,
"cubedash:region_code": self.region_code,
},
)
@dataclass
class ProductLocationSample:
"""
The apparent storage location of a product
(judged via a small sampling of datasets)
"""
# eg. 'http', "file", ...
uri_scheme: str
# The common uri prefix across all samples
common_prefix: str
# A few examples of full location URIs
example_uris: List[str]
class SummaryStore:
def __init__(self, index: Index, summariser: Summariser, log=_LOG) -> None:
self.index = index
self.log = log
self._update_listeners = []
self._engine: Engine = _utils.alchemy_engine(index)
self._summariser = summariser
# How much extra time to include in incremental update scans?
# The incremental-updater searches for any datasets with a newer change-timestamp than
# its last successul run. But some earlier-timestamped datasets may not have been
# present last run if they were added in a concurrent, open transaction. And we don't
# want to miss them! So we give a buffer assuming no transaction was open longer than
# this buffer. (It doesn't matter at all if we repeat datasets).
#
# This is not solution of perfection. But ODC's indexing does happen with quick,
# auto-committing transactions, so they're unlikely to actually be open for more
# than a few milliseconds. Fifteen minutes feels very generous.
#
# (You can judge if this assumption has failed by comparing our dataset_spatial
# count(*) to ODC's dataset count(*) for the same product. They should match
# for active datasets.)
#
# tldr: "15 minutes == max expected transaction age of indexer"
self.dataset_overlap_carefulness = timedelta(minutes=15)
def add_change_listener(self, listener):
self._update_listeners.append(listener)
def is_initialised(self) -> bool:
"""
Do our DB schemas exist?
"""
return _schema.has_schema(self._engine)
def is_schema_compatible(self, for_writing_operations_too=False) -> bool:
"""
Have all schema update been applied?
"""
_LOG.debug(
"software.version",
postgis=_schema.get_postgis_versions(self._engine),
explorer=explorer_version,
)
if for_writing_operations_too:
return _schema.is_compatible_generate_schema(self._engine)
else:
return _schema.is_compatible_schema(self._engine)
def init(self, grouping_epsg_code: int = None):
"""
Initialise any schema elements that don't exist.
Takes an epsg_code, of the CRS used internally for summaries.
(Requires `create` permissions in the db)
"""
# Add any missing schema items or patches.
_schema.create_schema(
self._engine, epsg_code=grouping_epsg_code or DEFAULT_EPSG
)
# If they specified an epsg code, make sure the existing schema uses it.
if grouping_epsg_code:
crs_used_by_schema = self.grouping_crs
if crs_used_by_schema != f"EPSG:{grouping_epsg_code}":
raise RuntimeError(
f"""
Tried to initialise with EPSG:{grouping_epsg_code!r},
but the schema is already using {crs_used_by_schema}.
To change the CRS, you need to recreate Explorer's schema.
Eg.
# Drop schema
cubedash-gen --drop
# Create schema with new epsg, and summarise all products again.
cubedash-gen --init --epsg {grouping_epsg_code} --all
(Warning: Resummarising all of your products may take a long time!)
"""
)
refresh_also = _schema.update_schema(self._engine)
if refresh_also:
_refresh_data(refresh_also, store=self)
@classmethod
def create(cls, index: Index, log=_LOG) -> "SummaryStore":
return cls(index, Summariser(_utils.alchemy_engine(index)), log=log)
@property
def grouping_crs(self):
"""
Get the crs name used for grouping summaries.
(the value that was set on ``init()`` of the schema)
"""
return self._get_srid_name(
self._engine.execute(select([FOOTPRINT_SRID_EXPRESSION])).scalar()
)
def close(self):
"""Close any pooled/open connections. Necessary before forking."""
self.index.close()
self._engine.dispose()
def refresh_all_product_extents(
self,
):
for product in self.all_dataset_types():
self.refresh_product_extent(
product.name,
)
self.refresh_stats()
def find_most_recent_change(self, product_name: str):
"""
Find the database-local time of the last dataset that changed for this product.
"""
dataset_type = self.get_dataset_type(product_name)
return self._engine.execute(
select(
[
func.max(dataset_changed_expression()),
]
).where(ODC_DATASET.c.dataset_type_ref == dataset_type.id)
).scalar()
def find_months_needing_update(
self,
product_name: str,
only_those_newer_than: datetime,
) -> Iterable[Tuple[date, int]]:
"""
What months have had dataset changes since they were last generated?
"""
dataset_type = self.get_dataset_type(product_name)
# Find the most-recently updated datasets and group them by month.
return sorted(
(month.date(), count)
for month, count in self._engine.execute(
select(
[
func.date_trunc(
"month", datetime_expression(dataset_type.metadata_type)
).label("month"),
func.count(),
]
)
.where(ODC_DATASET.c.dataset_type_ref == dataset_type.id)
.where(dataset_changed_expression() > only_those_newer_than)
.group_by("month")
.order_by("month")
)
)
def find_years_needing_update(self, product_name: str) -> List[int]:
"""
Find any years that need to be generated.
Either:
1) They don't exist yet, or
2) They existed before and has been deleted or archived, or
3) They have month-records that are newer than our year-record.
"""
updated_months = TIME_OVERVIEW.alias("updated_months")
years = TIME_OVERVIEW.alias("years_needing_update")
product = self.get_product_summary(product_name)
# Years that have already been summarised
summarised_years = {
r[0].year
for r in self._engine.execute(
select([years.c.start_day])
.where(years.c.period_type == "year")
.where(
years.c.product_ref == product.id_,
)
)
}
# Empty product? No years
if product.dataset_count == 0:
# check if the timeoverview needs cleanse
if not summarised_years:
return []
else:
return summarised_years
# All years we are expected to have
expected_years = set(
range(
product.time_earliest.astimezone(timezone).year,
product.time_latest.astimezone(timezone).year + 1
)
)
missing_years = expected_years.difference(summarised_years)
# Years who have month-records updated more recently than their own record.
outdated_years = {
start_day.year
for [start_day] in self._engine.execute(
# Select years
select([years.c.start_day])
.where(years.c.period_type == "year")
.where(
years.c.product_ref == product.id_,
)
# Where there exist months that are more newly created.
.where(
exists(
select([updated_months.c.start_day])
.where(updated_months.c.period_type == "month")
.where(
func.extract("year", updated_months.c.start_day)
== func.extract("year", years.c.start_day)
)
.where(
updated_months.c.product_ref == product.id_,
)
.where(
updated_months.c.generation_time > years.c.generation_time
)
)
)
)
}
return sorted(missing_years.union(outdated_years))
def needs_extent_refresh(self, product_name: str) -> bool:
"""
Does the given product have changes since the last refresh?
"""
existing_product_summary = self.get_product_summary(product_name)
if not existing_product_summary:
# Never been summarised. So, yes!
return True
most_recent_change = self.find_most_recent_change(product_name)
has_new_changes = most_recent_change and (
most_recent_change > existing_product_summary.last_refresh_time
)
_LOG.debug(
"product.last_extent_changes",
product_name=product_name,
last_refresh_time=existing_product_summary.last_refresh_time,
most_recent_change=most_recent_change,
has_new_changes=has_new_changes,
)
return has_new_changes
def refresh_product_extent(
self,
product_name: str,
dataset_sample_size: int = 1000,
scan_for_deleted: bool = False,
only_those_newer_than: datetime = None,
force: bool = False,
) -> Tuple[int, ProductSummary]:
"""
Update Explorer's computed extents for the given product, and record any new
datasets into the spatial table.
Returns the count of changed dataset extents, and the
updated product summary.
"""
# Server-side-timestamp of when we started scanning. We will
# later know that any dataset newer than this timestamp may not
# be in our summaries.
covers_up_to = self._database_time_now()
product = self.index.products.get_by_name(product_name)
_LOG.info("init.product", product_name=product.name)
change_count = _extents.refresh_spatial_extents(
self.index,
product,
clean_up_deleted=scan_for_deleted,
assume_after_date=only_those_newer_than,
)
existing_summary = self.get_product_summary(product_name)
# Did nothing change at all? Just bump the refresh time.
if change_count == 0 and existing_summary and not force:
new_summary = copy(existing_summary)
new_summary.last_refresh_time = covers_up_to
self._persist_product_extent(new_summary)
return 0, new_summary
# if change_count or force_dataset_extent_recompute:
earliest, latest, total_count = self._engine.execute(
select(
(
func.min(DATASET_SPATIAL.c.center_time),
func.max(DATASET_SPATIAL.c.center_time),
func.count(),
)
).where(DATASET_SPATIAL.c.dataset_type_ref == product.id)
).fetchone()
source_products = []
derived_products = []
fixed_metadata = {}
if total_count:
sample_percentage = min(dataset_sample_size / total_count, 1) * 100.0
source_products = self._get_linked_products(
product, kind="source", sample_percentage=sample_percentage
)
derived_products = self._get_linked_products(
product, kind="derived", sample_percentage=sample_percentage
)
fixed_metadata = self._find_product_fixed_metadata(
product, sample_percentage=sample_percentage
)
new_summary = ProductSummary(
product.name,
total_count,
earliest,
latest,
source_products=source_products,
derived_products=derived_products,
fixed_metadata=fixed_metadata,
last_refresh_time=covers_up_to,
)
# TODO: This is an expensive operation. We regenerate them all every time there are changes.
self._refresh_product_regions(product)
self._persist_product_extent(new_summary)
return change_count, new_summary
def _refresh_product_regions(self, dataset_type: DatasetType) -> int:
log = _LOG.bind(product_name=dataset_type.name)
log.info("refresh.regions.start")
log.info("refresh.regions.update.count.and.insert.new")
# add new regions row and/or update existing regions based on dataset_spatial
changed_rows = self._engine.execute(
"""
with srid_groups as (
select cubedash.dataset_spatial.dataset_type_ref as dataset_type_ref,
cubedash.dataset_spatial.region_code as region_code,
ST_Transform(ST_Union(cubedash.dataset_spatial.footprint), 4326) as footprint,
count(*) as count
from cubedash.dataset_spatial
where cubedash.dataset_spatial.dataset_type_ref = %s
and
st_isvalid(cubedash.dataset_spatial.footprint)
group by cubedash.dataset_spatial.dataset_type_ref,
cubedash.dataset_spatial.region_code,
st_srid(cubedash.dataset_spatial.footprint)
)
insert into cubedash.region (dataset_type_ref, region_code, footprint, count)
select srid_groups.dataset_type_ref,
coalesce(srid_groups.region_code, '') as region_code,
ST_SimplifyPreserveTopology(
ST_Union(ST_Buffer(srid_groups.footprint, 0)), 0.0001) as footprint,
sum(srid_groups.count) as count
from srid_groups
group by srid_groups.dataset_type_ref, srid_groups.region_code
on conflict (dataset_type_ref, region_code)
do update set count = excluded.count,
generation_time = now(),
footprint = excluded.footprint
""",
dataset_type.id,
).rowcount
log.info("refresh.regions.update.count.and.insert.new.end")
# delete region rows with no related datasets in dataset_spatial table
log.info("refresh.regions.delete.empty.regions")
changed_rows += self._engine.execute(
"""
delete from cubedash.region
where dataset_type_ref = %s and region_code not in (
select cubedash.dataset_spatial.region_code
from cubedash.dataset_spatial
where cubedash.dataset_spatial.dataset_type_ref = %s
group by cubedash.dataset_spatial.region_code
)
""",
dataset_type.id, dataset_type.id
).rowcount
log.info("refresh.regions.delete.empty.regions.end")
log.info("refresh.regions.end", changed_regions=changed_rows)
return changed_rows
def refresh_stats(self, concurrently=False):
"""
Refresh general statistics tables that cover all products.
This is ideally done once after all needed products have been refreshed.
"""
refresh_supporting_views(self._engine, concurrently=concurrently)
def _find_product_fixed_metadata(
self, product: DatasetType, sample_percentage=0.05
) -> Dict[str, any]:
"""
Find metadata fields that have an identical value in every dataset of the product.
This is expensive, so only the given percentage of datasets will be sampled (but
feel free to sample 100%!)
"""
if not 0.0 < sample_percentage <= 100.0:
raise ValueError(
f"Sample percentage out of range 0>s>=100. Got {sample_percentage!r}"
)
# Get a single dataset, then we'll compare the rest against its values.
first_dataset_fields = self.index.datasets.search_eager(
product=product.name, limit=1
)[0].metadata.fields
simple_field_types = {
"string": str,
"numeric": (float, int),
"double": (float, int),
"integer": int,
"datetime": datetime,
}
candidate_fields: List[Tuple[str, PgDocField]] = [
(name, field)
for name, field in _utils.get_mutable_dataset_search_fields(
self.index, product.metadata_type
).items()
if field.type_name in simple_field_types and name in first_dataset_fields
]
if sample_percentage < 100:
dataset_table = ODC_DATASET.tablesample(
func.system(float(sample_percentage)), name="sampled_dataset"
)
# Replace the table with our sampled one.
for _, field in candidate_fields:
if field.alchemy_column.table == ODC_DATASET:
field.alchemy_column = dataset_table.c[field.alchemy_column.name]
else:
dataset_table = ODC_DATASET
# Give a friendlier error message when a product doesn't match the dataset.
for name, field in candidate_fields:
sample_value = first_dataset_fields[name]
expected_types = simple_field_types[field.type_name]
# noinspection PyTypeHints
if sample_value is not None and not isinstance(
sample_value, expected_types
):
raise ValueError(
f"Product {product.name} field {name!r} is "
f"claimed to be type {expected_types}, but dataset has value {sample_value!r}"
)
_LOG.info(
"product.fixed_metadata_search",
product=product.name,
sample_percentage=round(sample_percentage, 2),
)
result = self._engine.execute(
select(
[
(
func.every(
field.alchemy_expression == first_dataset_fields[field_name]
)
).label(field_name)
for field_name, field in candidate_fields
]
)
.select_from(dataset_table)
.where(dataset_table.c.dataset_type_ref == product.id)
.where(dataset_table.c.archived.is_(None))
).fetchall()
assert len(result) == 1
fixed_fields = {
key: first_dataset_fields[key]
for key, is_fixed in result[0]._mapping.items()
if is_fixed
}
_LOG.info(
"product.fixed_metadata_search.done",
product=product.name,
sample_percentage=round(sample_percentage, 2),
searched_field_count=len(result[0]),
found_field_count=len(fixed_fields),
)
return fixed_fields
def _get_linked_products(
self, product: DatasetType, kind="source", sample_percentage=0.05
) -> List[str]:
"""
Find products with upstream or downstream datasets from this product.
It only samples a percentage of this product's datasets, due to slow speed. (But 1 dataset
would be enough for most products)
"""
if kind not in ("source", "derived"):
raise ValueError(f"Unexpected kind of link: {kind!r}")
if not 0.0 < sample_percentage <= 100.0:
raise ValueError(
f"Sample percentage out of range 0>s>=100. Got {sample_percentage!r}"
)
from_ref, to_ref = "source_dataset_ref", "dataset_ref"
if kind == "derived":
to_ref, from_ref = from_ref, to_ref
# Avoid tablesample (full table scan) when we're getting all of the product anyway.
sample_sql = ""
if sample_percentage < 100:
sample_sql = "tablesample system (%(sample_percentage)s)"
(linked_product_names,) = self._engine.execute(
f"""
with datasets as (
select id from agdc.dataset {sample_sql}
where dataset_type_ref=%(product_id)s
and archived is null
),
linked_datasets as (
select distinct {from_ref} as linked_dataset_ref
from agdc.dataset_source
inner join datasets d on d.id = {to_ref}
),
linked_products as (
select distinct dataset_type_ref
from agdc.dataset
inner join linked_datasets on id = linked_dataset_ref
where archived is null
)
select array_agg(name order by name)
from agdc.dataset_type
inner join linked_products sp on id = dataset_type_ref;
""",
product_id=product.id,
sample_percentage=sample_percentage,
).fetchone()
_LOG.info(
"product.links.{kind}",
extra=dict(kind=kind),
product=product.name,
linked=linked_product_names,
sample_percentage=round(sample_percentage, 2),
)
return list(linked_product_names or [])
def drop_all(self):
"""
Drop all cubedash-specific tables/schema.
"""
self._engine.execute(
DDL(f"drop schema if exists {_schema.CUBEDASH_SCHEMA} cascade")
)
def get(
self,
product_name: str,
year: Optional[int] = None,
month: Optional[int] = None,
day: Optional[int] = None,
) -> Optional[TimePeriodOverview]:
period, start_day = TimePeriodOverview.flat_period_representation(
year, month, day
)
if year and month and day:
# We don't store days, they're quick.
return self._summariser.calculate_summary(
product_name,
year_month_day=(year, month, day),
product_refresh_time=datetime.now(),
)
product = self.get_product_summary(product_name)
if not product:
return None
res = self._engine.execute(
select([TIME_OVERVIEW]).where(
and_(
TIME_OVERVIEW.c.product_ref == product.id_,
TIME_OVERVIEW.c.start_day == start_day,
TIME_OVERVIEW.c.period_type == period,
)
)
).fetchone()
if not res:
return None
return _summary_from_row(res, product_name=product_name)
def get_all_dataset_counts(
self,
) -> Dict[Tuple[str, int, int], int]:
"""
Get dataset count for all (product, year, month) combinations.
"""
res = self._engine.execute(
select(
[
PRODUCT.c.name,
TIME_OVERVIEW.c.start_day,
TIME_OVERVIEW.c.period_type,
TIME_OVERVIEW.c.dataset_count,
]
)
.select_from(TIME_OVERVIEW.join(PRODUCT))
.where(TIME_OVERVIEW.c.product_ref == PRODUCT.c.id)
.order_by(
PRODUCT.c.name, TIME_OVERVIEW.c.start_day, TIME_OVERVIEW.c.period_type
)
)
return {
(
r.name,
*TimePeriodOverview.from_flat_period_representation(
r.period_type, r.start_day
)[:2],
): r.dataset_count
for r in res
}
# These are cached to avoid repeated unnecessary DB queries.
@ttl_cache(ttl=DEFAULT_TTL)
def all_dataset_types(self) -> Iterable[DatasetType]:
return tuple(self.index.products.get_all())
@ttl_cache(ttl=DEFAULT_TTL)
def all_metadata_types(self) -> Iterable[DatasetType]:
return tuple(self.index.metadata_types.get_all())
@ttl_cache(ttl=DEFAULT_TTL)
def get_dataset_type(self, name) -> DatasetType:
for d in self.all_dataset_types():
if d.name == name:
return d
raise KeyError(f"Unknown dataset type {name!r}")
@ttl_cache(ttl=DEFAULT_TTL)
def _dataset_type_by_id(self, id_) -> DatasetType:
for d in self.all_dataset_types():
if d.id == id_:
return d
raise KeyError(f"Unknown dataset type id {id_!r}")
@ttl_cache(ttl=DEFAULT_TTL)
def _product(self, name: str) -> ProductSummary:
row = self._engine.execute(
select(
[
PRODUCT.c.dataset_count,
PRODUCT.c.time_earliest,
PRODUCT.c.time_latest,
PRODUCT.c.last_refresh.label("last_refresh_time"),
PRODUCT.c.last_successful_summary.label(
"last_successful_summary_time"
),
PRODUCT.c.id.label("id_"),
PRODUCT.c.source_product_refs,
PRODUCT.c.derived_product_refs,
PRODUCT.c.fixed_metadata,
]
).where(PRODUCT.c.name == name)
).fetchone()
if not row:
raise ValueError(f"Unknown product {name!r} (initialised?)")
row = dict(row)
source_products = [
self._dataset_type_by_id(id_).name for id_ in row.pop("source_product_refs")
]
derived_products = [
self._dataset_type_by_id(id_).name
for id_ in row.pop("derived_product_refs")
]
return ProductSummary(
name=name,
source_products=source_products,
derived_products=derived_products,
**row,
)
@ttl_cache(ttl=DEFAULT_TTL)
def products_location_samples_all(
self, sample_size: int = 50
) -> Dict[str, List[ProductLocationSample]]:
"""
Get sample locations of all products
This is the same as product_location_samples(), but will be significantly faster
if you need to fetch all products at once.
(It's faster because it does only one DB query round-trip instead of N (where N is
number of products). The latency of repeated round-trips adds up tremendously on
cloud instances.)
"""
queries = []
for dataset_type in self.all_dataset_types():
subquery = (
select(
[
literal(dataset_type.name).label("name"),
(
ODC_DATASET_LOCATION.c.uri_scheme
+ ":"
+ ODC_DATASET_LOCATION.c.uri_body
).label("uri"),
]
)
.select_from(ODC_DATASET_LOCATION.join(ODC_DATASET))
.where(ODC_DATASET.c.dataset_type_ref == dataset_type.id)
.where(ODC_DATASET.c.archived.is_(None))
.limit(sample_size)
)
queries.append(subquery)
product_urls = defaultdict(list)
for product_name, uri in self._engine.execute(union_all(*queries)):
product_urls[product_name].append(uri)
return {
name: list(_common_paths_for_uris(uris))
for name, uris in product_urls.items()
}
@ttl_cache(ttl=DEFAULT_TTL)
def product_location_samples(
self,
name: str,
year: Optional[int] = None,
month: Optional[int] = None,
day: Optional[int] = None,
*,
sample_size: int = 100,
) -> List[ProductLocationSample]:
"""
Sample some dataset locations for the given product, and return
the common location.
Returns one row for each uri scheme found (http, file etc).
"""
search_args = dict()
if year or month or day:
search_args["time"] = _utils.as_time_range(year, month, day)
# Sample 100 dataset uris
uri_samples = sorted(
uri
for [uri] in self.index.datasets.search_returning(
("uri",), product=name, **search_args, limit=sample_size
)
)
return list(_common_paths_for_uris(uri_samples))
def get_quality_stats(self) -> Iterable[Dict]:
stats = self._engine.execute(select([SPATIAL_QUALITY_STATS]))
for row in stats:
d = dict(row)
d["product"] = self._dataset_type_by_id(row["dataset_type_ref"])
d["avg_footprint_bytes"] = (
row["footprint_size"] / row["count"] if row["footprint_size"] else 0
)
yield d
def get_product_summary(self, name: str) -> Optional[ProductSummary]:
try:
return self._product(name)
except ValueError:
return None
@property
def grouping_timezone(self):