| 1 |
""" |
| 2 |
Products and a core turning accrefs into lists of products. |
| 3 |
|
| 4 |
There is a substantial overlap between what's going on there and datalink |
| 5 |
(and datalink uses some of the products mentioned here). The cutouts |
| 6 |
and scale things here shouldn't be developed on, all this should |
| 7 |
move towards datalink. Meanwhile, we still have siapCutoutCore and |
| 8 |
friends that relies on the mess here, so all this is going to remain |
| 9 |
for the foreseeable future. Just don't extend it. |
| 10 |
|
| 11 |
The "user-visible" part are just accrefs, as modelled by the RAccref |
| 12 |
-- they can contain instructions for cutouts or scaling, hence the additional |
| 13 |
structure. |
| 14 |
|
| 15 |
Using the product table and some logic in this module, such accrefs |
| 16 |
are turned into subclasses of ProductBase. |
| 17 |
|
| 18 |
These have mime types and know how to generate their data through their |
| 19 |
synchronous iterData methods. They must also work as t.w resources and thus |
| 20 |
have implement asynchronuous render(request) methods. It's a bit unfortunate |
| 21 |
that we thus depend on t.w here, but we'd have to reimplement quite a bit of |
| 22 |
it if we don't, and for now it doesn't seem we'll support a different framework |
| 23 |
in the foreseeable future. |
| 24 |
""" |
| 25 |
|
| 26 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 27 |
#c |
| 28 |
#c This program is free software, covered by the GNU GPL. See the |
| 29 |
#c COPYING file in the source distribution. |
| 30 |
|
| 31 |
|
| 32 |
import datetime |
| 33 |
import gzip |
| 34 |
import functools |
| 35 |
import re |
| 36 |
import os |
| 37 |
import urllib.request, urllib.parse, urllib.error |
| 38 |
import urllib.parse |
| 39 |
from io import BytesIO |
| 40 |
|
| 41 |
import numpy |
| 42 |
|
| 43 |
from PIL import Image |
| 44 |
|
| 45 |
from twisted.internet import defer |
| 46 |
from twisted.internet import threads |
| 47 |
from twisted.web import http |
| 48 |
from twisted.web import static |
| 49 |
|
| 50 |
from gavo import base |
| 51 |
from gavo import rscdef |
| 52 |
from gavo import svcs |
| 53 |
from gavo import utils |
| 54 |
from gavo.base import coords |
| 55 |
from gavo.protocols import creds |
| 56 |
from gavo.svcs import streaming |
| 57 |
from gavo.utils import imgtools |
| 58 |
from gavo.utils import fitstools |
| 59 |
from gavo.utils import pyfits |
| 60 |
|
| 61 |
|
| 62 |
# TODO: make this configurable -- globally? by service? |
| 63 |
PREVIEW_SIZE = 200 |
| 64 |
|
| 65 |
PRODUCTS_TDID = "//products#products" |
| 66 |
|
| 67 |
REMOTE_URL_PATTERN = re.compile("(https?|ftp)://") |
| 68 |
|
| 69 |
MS = base.makeStruct |
| 70 |
|
| 71 |
|
| 72 |
@functools.cache |
| 73 |
def productTableColNames(): |
| 74 |
"""returns the names of the columns of the product table in |
| 75 |
DaCHS' capitalisation. |
| 76 |
""" |
| 77 |
return [c.name for c in base.resolveCrossId(PRODUCTS_TDID)] |
| 78 |
|
| 79 |
|
| 80 |
def makePreviewFromFITS(product): |
| 81 |
"""returns image/jpeg bytes for a preview of a product spitting out a |
| 82 |
2D FITS. |
| 83 |
""" |
| 84 |
if hasattr(product, "getFile"): |
| 85 |
# hack to preserve no-so-well-thought out existing functionality |
| 86 |
if product.rAccref.accref.endswith(".gz"): |
| 87 |
inFile = gzip.GzipFile(fileobj=product.getFile()) |
| 88 |
else: |
| 89 |
inFile = product.getFile() |
| 90 |
|
| 91 |
with utils.fitsLock(): |
| 92 |
pixels = numpy.array([row |
| 93 |
for row in fitstools.iterScaledRows(inFile, |
| 94 |
destSize=PREVIEW_SIZE)]) |
| 95 |
else: |
| 96 |
raise NotImplementedError("TODO: Fix fitstools.iterScaledRows" |
| 97 |
" to be more accommodating to weird things") |
| 98 |
return imgtools.jpegFromNumpyArray(pixels) |
| 99 |
|
| 100 |
|
| 101 |
def makePreviewWithPIL(product): |
| 102 |
"""returns image/jpeg bytes for a preview of the PIL-readable product. |
| 103 |
""" |
| 104 |
# TODO: Teach products to at least accept seek(0) and directly read from |
| 105 |
# them; at least make read(None) work properly |
| 106 |
fullsize = BytesIO(product.read(1000000000)) |
| 107 |
im = Image.open(fullsize) |
| 108 |
scale = max(im.size)/float(PREVIEW_SIZE) |
| 109 |
resized = im.resize(( |
| 110 |
int(im.size[0]/scale), |
| 111 |
int(im.size[1]/scale))) |
| 112 |
f = BytesIO() |
| 113 |
resized.save(f, format="jpeg") |
| 114 |
return f.getvalue() |
| 115 |
|
| 116 |
|
| 117 |
_PIL_COMPATIBLE_MIMES = frozenset(['image/jpeg', 'image/png']) |
| 118 |
|
| 119 |
def computePreviewFor(product): |
| 120 |
"""returns a deferred returning image/jpeg bytes containing a |
| 121 |
preview of product. |
| 122 |
|
| 123 |
This only works for a select subset of products. You're usually |
| 124 |
better off using static previews. |
| 125 |
|
| 126 |
This will raise a DataError if it doesn't know how to make a preview. |
| 127 |
""" |
| 128 |
if hasattr(product, "makePreview"): |
| 129 |
return threads.deferToThread(product.makePreview) |
| 130 |
|
| 131 |
sourceMime = product.pr["mime"] |
| 132 |
if sourceMime.endswith('/fits'): |
| 133 |
return threads.deferToThread(makePreviewFromFITS, product) |
| 134 |
elif sourceMime in _PIL_COMPATIBLE_MIMES: |
| 135 |
return threads.deferToThread(makePreviewWithPIL, product) |
| 136 |
else: |
| 137 |
raise base.DataError("Cannot make automatic preview for %s"% |
| 138 |
sourceMime) |
| 139 |
|
| 140 |
|
| 141 |
class PreviewCacheManager(object): |
| 142 |
"""is a class that manages the preview cache. |
| 143 |
|
| 144 |
It's really the class that manages it, so don't bother creating instances. |
| 145 |
|
| 146 |
The normal operation is that you pass the product you want a preview to |
| 147 |
getPreviewFor. If a cached preview already exists, you get back its content |
| 148 |
(the mime type must be taken from the products table). |
| 149 |
|
| 150 |
If the file does not exist yet, some internal magic tries to come up with |
| 151 |
a preview and determines whether it should be cached, in which case it does |
| 152 |
so provided a preview has been generated successfully. |
| 153 |
|
| 154 |
A cache file is touched when it is used, so you can clean up rarely used |
| 155 |
cache files by deleting all files in the preview cache older than some |
| 156 |
limit. |
| 157 |
""" |
| 158 |
cachePath = base.getConfig("web", "previewCache") |
| 159 |
|
| 160 |
@classmethod |
| 161 |
def getCacheName(cls, accref): |
| 162 |
"""returns the full path a preview for accref is be stored under. |
| 163 |
""" |
| 164 |
return os.path.join(cls.cachePath, rscdef.getFlatName(accref)) |
| 165 |
|
| 166 |
@classmethod |
| 167 |
def getCachedPreviewPath(cls, accref): |
| 168 |
"""returns the path to a cached preview if it exists, None otherwise. |
| 169 |
""" |
| 170 |
cacheName = cls.getCacheName(accref) |
| 171 |
if os.path.exists(cacheName): |
| 172 |
return cacheName |
| 173 |
return None |
| 174 |
|
| 175 |
@classmethod |
| 176 |
def saveToCache(self, data, cacheName): |
| 177 |
try: |
| 178 |
with open(cacheName, "wb") as f: |
| 179 |
f.write(data) |
| 180 |
except IOError: # caching failed, don't care |
| 181 |
pass |
| 182 |
return data |
| 183 |
|
| 184 |
@classmethod |
| 185 |
def getPreviewFor(cls, product): |
| 186 |
"""returns a deferred firing the data for a preview. |
| 187 |
|
| 188 |
This will raise a DataError if it doesn't know how to make the |
| 189 |
preview. |
| 190 |
""" |
| 191 |
if not product.rAccref.previewIsCacheable(): |
| 192 |
return computePreviewFor(product) |
| 193 |
|
| 194 |
accref = product.rAccref.accref |
| 195 |
cacheName = cls.getCacheName(accref) |
| 196 |
if os.path.exists(cacheName): |
| 197 |
# Cache hit |
| 198 |
try: |
| 199 |
os.utime(cacheName, None) |
| 200 |
except os.error: |
| 201 |
pass # don't fail just because we can't touch |
| 202 |
|
| 203 |
with open(cacheName, "rb") as f: |
| 204 |
return defer.succeed(f.read()) |
| 205 |
|
| 206 |
else: |
| 207 |
# Cache miss |
| 208 |
return computePreviewFor(product |
| 209 |
).addCallback(cls.saveToCache, cacheName) |
| 210 |
|
| 211 |
|
| 212 |
class ProductBase(object): |
| 213 |
"""A base class for products returned by the product core. |
| 214 |
|
| 215 |
See the module docstring for the big picture. |
| 216 |
|
| 217 |
The constructor arguments of RAccrefs depend on what they are. |
| 218 |
The common interface is the the class method |
| 219 |
fromRAccref(rAccref, authGroups=None). |
| 220 |
It returns None if the RAccref is not for a product of the |
| 221 |
respective sort, the product otherwise. |
| 222 |
|
| 223 |
authGroups is a set of groups authorised for the user when |
| 224 |
controlling access to embargoed products. This is the main |
| 225 |
reason you should never hand out products yourself but always |
| 226 |
expose the to the user through the product core. |
| 227 |
|
| 228 |
The actual constructor requires a RAccref, which is exposed as the |
| 229 |
rAccref attribute. Do not use the productsRow attribute from rAccref, |
| 230 |
though, as constructors may want to manipulate the content of the |
| 231 |
product row (e.g., in NonExistingProduct). Access the product |
| 232 |
row as self.pr in product classes. |
| 233 |
|
| 234 |
In addition to those, all Products have a name attribute, |
| 235 |
which must be something suitable as a file name; the default |
| 236 |
constructor calls a _makeName method to come up with one, and |
| 237 |
you should simply override it. |
| 238 |
|
| 239 |
The iterData method has to yield reasonably-sized chunks of |
| 240 |
data (self.chunkSize should be a good choice). It must be |
| 241 |
synchronous. |
| 242 |
|
| 243 |
Products usually are used as t.w resources. Therefore, they |
| 244 |
must have a render method. This must be asynchronuous, |
| 245 |
i.e., it should not block for extended periods of time. |
| 246 |
|
| 247 |
Products also work as rudimentary files via read and close |
| 248 |
methods; by default, these are implemented on top of iterData. |
| 249 |
Clients must never mix calls to the file interface and to |
| 250 |
iterData. Derived classes that are based on actual files should |
| 251 |
set up optimized read and close methods using the setupRealFile |
| 252 |
class method (look for the getFile method on the instance to see |
| 253 |
if there's a real file). Again, the assumption is made there that clients |
| 254 |
use either iterData or read, but never both. |
| 255 |
|
| 256 |
If a product knows how to (quickly) generate a preview for itself, |
| 257 |
it can define a makePreview() method. This must return content |
| 258 |
for a mime type conventional for that kind of product (which is laid |
| 259 |
down in the products table). |
| 260 |
""" |
| 261 |
chunkSize = 2**16 |
| 262 |
_curIterator = None |
| 263 |
|
| 264 |
def __init__(self, rAccref): |
| 265 |
# If you change things here, change NonExistingProduct's constructor |
| 266 |
# as well. |
| 267 |
self.rAccref = rAccref |
| 268 |
self.pr = self.rAccref.productsRow |
| 269 |
self._makeName() |
| 270 |
|
| 271 |
def _makeName(self): |
| 272 |
self.name = "invalid product" |
| 273 |
|
| 274 |
def __str__(self): |
| 275 |
return "<%s %s (%s)>"%(self.__class__.__name__, |
| 276 |
self.name, |
| 277 |
self.pr["mime"]) |
| 278 |
|
| 279 |
def __repr__(self): |
| 280 |
return str(self) |
| 281 |
|
| 282 |
def __eq__(self, other): |
| 283 |
return (isinstance(other, self.__class__) |
| 284 |
and self.rAccref==other.rAccref) |
| 285 |
|
| 286 |
def __ne__(self, other): |
| 287 |
return not self==other |
| 288 |
|
| 289 |
@classmethod |
| 290 |
def fromRAccref(self, accref, authGroups=None): |
| 291 |
return None # ProductBase is not responsible for anything. |
| 292 |
|
| 293 |
@classmethod |
| 294 |
def setupRealFile(cls, openMethod): |
| 295 |
"""changes cls such that read and close work an an actual file-like |
| 296 |
object rather than the inefficient iterData. |
| 297 |
|
| 298 |
openMethod has to be an instance method of the class returning |
| 299 |
an opened input file. |
| 300 |
""" |
| 301 |
cls._openedInputFile = None |
| 302 |
|
| 303 |
def getFileMethod(self): |
| 304 |
return openMethod(self) |
| 305 |
|
| 306 |
def readMethod(self, size=None): |
| 307 |
if self._openedInputFile is None: |
| 308 |
self._openedInputFile = openMethod(self) |
| 309 |
return self._openedInputFile.read(size) |
| 310 |
|
| 311 |
def closeMethod(self): |
| 312 |
if self._openedInputFile is not None: |
| 313 |
self._openedInputFile.close() |
| 314 |
self._openedInputFile = None |
| 315 |
|
| 316 |
cls.read = readMethod |
| 317 |
cls.close = closeMethod |
| 318 |
cls.getFile = getFileMethod |
| 319 |
|
| 320 |
def iterData(self): |
| 321 |
raise NotImplementedError("Internal error: %s products do not" |
| 322 |
" implement iterData"%self.__class__.__name__) |
| 323 |
|
| 324 |
def render(self, request): |
| 325 |
raise NotImplementedError("Internal error: %s products cannot be" |
| 326 |
" rendered."%self.__class__.__name__) |
| 327 |
|
| 328 |
def read(self, size=None): |
| 329 |
if self._curIterator is None: |
| 330 |
self._curIterator = self.iterData() |
| 331 |
self._readBuf, self._curSize = [], 0 |
| 332 |
|
| 333 |
while size is None or self._curSize<size: |
| 334 |
try: |
| 335 |
chunk = next(self._curIterator) |
| 336 |
except StopIteration: |
| 337 |
break |
| 338 |
self._readBuf.append(chunk) |
| 339 |
self._curSize += len(chunk) |
| 340 |
|
| 341 |
content = b"".join(self._readBuf) |
| 342 |
if size is None: |
| 343 |
self._readBuf, self._curSize = [], 0 |
| 344 |
result = content |
| 345 |
|
| 346 |
else: |
| 347 |
result = content[:size] |
| 348 |
self._readBuf = [content[size:]] |
| 349 |
self._curSize = len(self._readBuf[0]) |
| 350 |
|
| 351 |
return result |
| 352 |
|
| 353 |
def close(self): |
| 354 |
for _ in self.iterData(): |
| 355 |
pass |
| 356 |
self._curIterator = None |
| 357 |
|
| 358 |
|
| 359 |
class FileProduct(ProductBase): |
| 360 |
"""A product corresponding to a local file. |
| 361 |
|
| 362 |
As long as the accessPath in the RAccref's productsRow corresponds |
| 363 |
to a real file and no params are in the RAccref, this will return |
| 364 |
a product. |
| 365 |
""" |
| 366 |
forSaving = True |
| 367 |
|
| 368 |
@classmethod |
| 369 |
def fromRAccref(cls, rAccref, authGroups=None): |
| 370 |
if set(rAccref.params)-set(["preview"]): # not a plain file |
| 371 |
return None |
| 372 |
if os.path.exists(rAccref.localpath): |
| 373 |
return cls(rAccref) |
| 374 |
|
| 375 |
def _makeName(self): |
| 376 |
self.name = os.path.basename(self.rAccref.localpath) |
| 377 |
|
| 378 |
def _openUnderlyingFile(self): |
| 379 |
return open(self.rAccref.localpath, "rb") |
| 380 |
|
| 381 |
def iterData(self): |
| 382 |
with self._openUnderlyingFile() as f: |
| 383 |
data = f.read(self.chunkSize) |
| 384 |
if not data: |
| 385 |
return |
| 386 |
yield data |
| 387 |
|
| 388 |
def render(self, request): |
| 389 |
if self.forSaving: |
| 390 |
request.setHeader("content-disposition", 'attachment; filename="%s"'% |
| 391 |
str(self.name)) |
| 392 |
if request.setLastModified(os.path.getmtime(self.rAccref.localpath) |
| 393 |
)==http.CACHED: |
| 394 |
request.finish() |
| 395 |
return |
| 396 |
|
| 397 |
res = static.File(self.rAccref.localpath) |
| 398 |
# we set the type manually to avoid having different mime types |
| 399 |
# by our and t.w's estimate. This forces us to clamp encoding |
| 400 |
# to None now. I *guess* we should do something about .gz and .bz2 |
| 401 |
res.type = str(self.pr["mime"]) |
| 402 |
res.encoding = None |
| 403 |
return res.render(request) |
| 404 |
|
| 405 |
FileProduct.setupRealFile(FileProduct._openUnderlyingFile) |
| 406 |
|
| 407 |
|
| 408 |
class StaticPreview(FileProduct): |
| 409 |
"""A product that's a cached or pre-computed preview. |
| 410 |
""" |
| 411 |
forSaving = False |
| 412 |
|
| 413 |
@classmethod |
| 414 |
def fromRAccref(cls, rAccref, authGroups=None): |
| 415 |
if not rAccref.params.get("preview"): |
| 416 |
return None |
| 417 |
# no static previews on cutouts |
| 418 |
if rAccref.params.get("sra"): |
| 419 |
return None |
| 420 |
|
| 421 |
previewPath = rAccref.productsRow["preview"] |
| 422 |
localName = None |
| 423 |
|
| 424 |
if previewPath is None: |
| 425 |
return None |
| 426 |
|
| 427 |
elif previewPath=="AUTO": |
| 428 |
localName = PreviewCacheManager.getCachedPreviewPath(rAccref.accref) |
| 429 |
|
| 430 |
else: |
| 431 |
# remote URLs can't happen here as RemotePreview is checked |
| 432 |
# before us. |
| 433 |
localName = base.getConfig("inputsDir") / previewPath |
| 434 |
|
| 435 |
if localName is None: |
| 436 |
return None |
| 437 |
elif os.path.exists(localName): |
| 438 |
rAccref.productsRow["accessPath"] = localName |
| 439 |
rAccref.productsRow["mime"] = rAccref.productsRow["preview_mime" |
| 440 |
] or "image/jpeg" |
| 441 |
return cls(rAccref) |
| 442 |
|
| 443 |
|
| 444 |
class RemoteProduct(ProductBase): |
| 445 |
"""A class for products at remote sites, given by their URL. |
| 446 |
""" |
| 447 |
def _makeName(self): |
| 448 |
self.name = urllib.parse.urlparse(self.pr["accessPath"] |
| 449 |
).path.split("/")[-1] or "file" |
| 450 |
|
| 451 |
def __str__(self): |
| 452 |
return "<Remote %s at %s>"%(self.pr["mime"], self.pr["accessPath"]) |
| 453 |
|
| 454 |
@classmethod |
| 455 |
def fromRAccref(cls, rAccref, authGroups=None): |
| 456 |
if REMOTE_URL_PATTERN.match(rAccref.productsRow["accessPath"]): |
| 457 |
return cls(rAccref) |
| 458 |
|
| 459 |
@classmethod |
| 460 |
def fromURL(cls, url): |
| 461 |
class rAccref: |
| 462 |
productsRow = {"accessPath": url} |
| 463 |
return cls(rAccref) |
| 464 |
|
| 465 |
def iterData(self): |
| 466 |
f = urllib.request.urlopen(self.pr["accessPath"]) |
| 467 |
while True: |
| 468 |
data = f.read(self.chunkSize) |
| 469 |
if not data: |
| 470 |
break |
| 471 |
yield data |
| 472 |
|
| 473 |
def render(self, request): |
| 474 |
destPath = self.pr["accessPath"] |
| 475 |
if destPath.startswith("http://") and request.isSecure(): |
| 476 |
destPath = "https://"+destPath[7:] |
| 477 |
raise svcs.WebRedirect(destPath) |
| 478 |
|
| 479 |
|
| 480 |
class RemotePreview(RemoteProduct): |
| 481 |
"""A preview that's on a remote server. |
| 482 |
""" |
| 483 |
@classmethod |
| 484 |
def fromRAccref(cls, rAccref, authGroups=None): |
| 485 |
if not rAccref.params.get("preview"): |
| 486 |
return None |
| 487 |
# no static previews on cutouts |
| 488 |
if rAccref.params.get("sra"): |
| 489 |
return None |
| 490 |
|
| 491 |
if REMOTE_URL_PATTERN.match(rAccref.productsRow["preview"] or ""): |
| 492 |
rAccref.productsRow["accessPath"] = rAccref.productsRow["preview"] |
| 493 |
rAccref.productsRow["mime"] = rAccref.productsRow["preview_mime"] |
| 494 |
return cls(rAccref) |
| 495 |
|
| 496 |
|
| 497 |
class UnauthorizedProduct(FileProduct): |
| 498 |
"""A local file that is not delivered to the current client. |
| 499 |
|
| 500 |
iterData returns the data for the benefit of preview making. |
| 501 |
However, there is a render method, so the product renderer will |
| 502 |
not use it; it will, instead, raise an Authenticate exception. |
| 503 |
""" |
| 504 |
forSaving = False |
| 505 |
|
| 506 |
@classmethod |
| 507 |
def fromRAccref(cls, rAccref, authGroups=None): |
| 508 |
dbRow = rAccref.productsRow |
| 509 |
if (dbRow["embargo"] is None |
| 510 |
or dbRow["embargo"]<datetime.date.today()): |
| 511 |
return None |
| 512 |
if authGroups is None or dbRow["owner"] not in authGroups: |
| 513 |
return cls(rAccref) |
| 514 |
|
| 515 |
def __str__(self): |
| 516 |
return "<Protected product %s, access denied>"%self.name |
| 517 |
|
| 518 |
def __eq__(self, other): |
| 519 |
return self.__class__==other.__class__ |
| 520 |
|
| 521 |
def render(self, request): |
| 522 |
raise svcs.Authenticate() |
| 523 |
|
| 524 |
|
| 525 |
class NonExistingProduct(ProductBase): |
| 526 |
"""A local file that went away. |
| 527 |
|
| 528 |
iterData here raises an IOError, render an UnknownURI. |
| 529 |
|
| 530 |
These should normally yield 404s. |
| 531 |
|
| 532 |
We don't immediately raise some error here as archive generation |
| 533 |
shouldn't fail just because a single part of it is missing. |
| 534 |
""" |
| 535 |
def __init__(self, rAccref): |
| 536 |
# as rAccref.productsRow is bad here, don't call the base constructor |
| 537 |
self.rAccref = rAccref |
| 538 |
self.pr = { |
| 539 |
'accessPath': None, 'accref': None, |
| 540 |
'embargo': None, 'owner': None, |
| 541 |
'mime': 'text/html', 'sourceTable': None, |
| 542 |
'datalink': None, 'preview': None} |
| 543 |
|
| 544 |
def __str__(self): |
| 545 |
return "<Non-existing product %s>"%self.rAccref.accref |
| 546 |
|
| 547 |
def __eq__(self, other): |
| 548 |
return self.__class__==other.__class__ |
| 549 |
|
| 550 |
@classmethod |
| 551 |
def fromRAccref(cls, rAccref, authGroups=None): |
| 552 |
try: |
| 553 |
rAccref.productsRow |
| 554 |
except base.NotFoundError: |
| 555 |
return cls(rAccref) |
| 556 |
|
| 557 |
def _makeName(self): |
| 558 |
self.name = "missing.html" |
| 559 |
|
| 560 |
def iterData(self): |
| 561 |
raise IOError("%s does not exist"%self.rAccref.accref) |
| 562 |
|
| 563 |
def render(self, request): |
| 564 |
raise svcs.UnknownURI("No dataset with accref %s known here."% |
| 565 |
self.rAccref.accref) |
| 566 |
|
| 567 |
|
| 568 |
class InvalidProduct(NonExistingProduct): |
| 569 |
"""An invalid file. |
| 570 |
|
| 571 |
This is returned by getProductForRAccref if all else fails. This |
| 572 |
usually happens when a file known to the products table is deleted, |
| 573 |
but it could also be an attempt to use unsupported combinations |
| 574 |
of files and parameters. |
| 575 |
|
| 576 |
Since any situation leading here is a bit weird, we probably |
| 577 |
should be doing something else but just return a 404. Hm... |
| 578 |
|
| 579 |
This class always returns an instance from fromRAccref; this means |
| 580 |
any resolution chain ends with it. But it shouldn't be in |
| 581 |
PRODUCT_CLASSES in the first place since the fallback is |
| 582 |
hardcoded into getProductForRAccref. |
| 583 |
""" |
| 584 |
def __str__(self): |
| 585 |
return "<Invalid product %s>"%self.rAccref |
| 586 |
|
| 587 |
@classmethod |
| 588 |
def fromRAccref(cls, rAccref, authGroups=None): |
| 589 |
return cls(rAccref) |
| 590 |
|
| 591 |
def _makeName(self): |
| 592 |
self.name = "invalid.html" |
| 593 |
|
| 594 |
def iterData(self): |
| 595 |
raise IOError("%s is invalid"%self.rAccref) |
| 596 |
|
| 597 |
|
| 598 |
class CutoutProduct(ProductBase): |
| 599 |
"""A class representing cutouts from FITS files. |
| 600 |
|
| 601 |
This only works for local FITS files with two axes. For everything |
| 602 |
else, use datalink. |
| 603 |
|
| 604 |
We assume the cutouts are smallish -- they are, right now, not |
| 605 |
streamed, but accumulated in memory. |
| 606 |
""" |
| 607 |
def _makeName(self): |
| 608 |
self.name = "<cutout-"+os.path.basename(self.pr["accessPath"]) |
| 609 |
|
| 610 |
def __str__(self): |
| 611 |
return "<cutout-%s %s>"%(self.name, self.rAccref.params) |
| 612 |
|
| 613 |
_myKeys = ["ra", "dec", "sra", "sdec"] |
| 614 |
_myKeySet = frozenset(_myKeys) |
| 615 |
|
| 616 |
@classmethod |
| 617 |
def fromRAccref(cls, rAccref, authGroups=None): |
| 618 |
if (len(set(rAccref.params.keys())&cls._myKeySet)==4 |
| 619 |
and rAccref.productsRow["mime"].endswith("/fits")): |
| 620 |
return cls(rAccref) |
| 621 |
|
| 622 |
def _getCutoutHDU(self): |
| 623 |
ra, dec, sra, sdec = [self.rAccref.params[k] for k in self._myKeys] |
| 624 |
with utils.fitsLock(): |
| 625 |
hdus = pyfits.open(self.rAccref.localpath, |
| 626 |
do_not_scale_image_data=True, |
| 627 |
memmap=True) |
| 628 |
try: |
| 629 |
skyWCS = coords.getWCS(hdus[0].header) |
| 630 |
pixelFootprint = numpy.asarray( |
| 631 |
numpy.round(skyWCS.wcs_world2pix([ |
| 632 |
(ra-sra/2., dec-sdec/2.), |
| 633 |
(ra+sra/2., dec+sdec/2.)], 1)), numpy.int32) |
| 634 |
res = fitstools.cutoutFITS(hdus[0], |
| 635 |
(skyWCS.longAxis, min(pixelFootprint[:,0]), max(pixelFootprint[:,0])), |
| 636 |
(skyWCS.latAxis, min(pixelFootprint[:,1]), max(pixelFootprint[:,1]))) |
| 637 |
finally: |
| 638 |
hdus.close() |
| 639 |
|
| 640 |
return res |
| 641 |
|
| 642 |
def iterData(self): |
| 643 |
# we need to write into a BytesIO (rather than to request) because |
| 644 |
# pyfits wants to seek |
| 645 |
res = self._getCutoutHDU() |
| 646 |
bytes = BytesIO() |
| 647 |
res.writeto(bytes) |
| 648 |
|
| 649 |
bytes.seek(0) |
| 650 |
while True: |
| 651 |
res = bytes.read(self.chunkSize) |
| 652 |
if not res: |
| 653 |
break |
| 654 |
yield res |
| 655 |
|
| 656 |
def _writeStuffTo(self, destF): |
| 657 |
for chunk in self.iterData(): |
| 658 |
destF.write(chunk) |
| 659 |
|
| 660 |
def render(self, request): |
| 661 |
request.setHeader("content-type", "application/fits") |
| 662 |
return streaming.streamOut(self._writeStuffTo, request) |
| 663 |
|
| 664 |
def makePreview(self): |
| 665 |
img = imgtools.scaleNumpyArray(self._getCutoutHDU().data, PREVIEW_SIZE) |
| 666 |
return imgtools.jpegFromNumpyArray(img) |
| 667 |
|
| 668 |
|
| 669 |
class ScaledFITSProduct(ProductBase): |
| 670 |
"""A class representing a scaled FITS file. |
| 671 |
|
| 672 |
Right now, this only works for local FITS files. Still, the |
| 673 |
class is constructed with a full rAccref. |
| 674 |
""" |
| 675 |
def __init__(self, rAccref): |
| 676 |
ProductBase.__init__(self, rAccref) |
| 677 |
self.scale = rAccref.params["scale"] |
| 678 |
self.baseAccref = rAccref.accref |
| 679 |
|
| 680 |
def __str__(self): |
| 681 |
return "<%s scaled by %s>"%(self.name, self.scale) |
| 682 |
|
| 683 |
@classmethod |
| 684 |
def fromRAccref(cls, rAccref, authGroups=None): |
| 685 |
if ("scale" in rAccref.params |
| 686 |
and rAccref.productsRow["mime"].endswith("/fits")): |
| 687 |
return cls(rAccref) |
| 688 |
|
| 689 |
def _makeName(self): |
| 690 |
self.name = "scaled-"+os.path.basename(self.pr["accref"]) |
| 691 |
|
| 692 |
def iterData(self): |
| 693 |
scale = int(self.scale) |
| 694 |
if scale<2: |
| 695 |
scale = 2 |
| 696 |
|
| 697 |
for stuff in fitstools.iterScaledBytes( |
| 698 |
self.rAccref.localpath, |
| 699 |
scale, |
| 700 |
extraCards={"FULLURL": str(makeProductLink(self.baseAccref))}): |
| 701 |
yield stuff |
| 702 |
|
| 703 |
def _writeStuffTo(self, destF): |
| 704 |
for chunk in self.iterData(): |
| 705 |
destF.write(chunk) |
| 706 |
|
| 707 |
def render(self, request): |
| 708 |
request.setHeader("content-type", "application/fits") |
| 709 |
return streaming.streamOut(self._writeStuffTo, request) |
| 710 |
|
| 711 |
|
| 712 |
# The following list is checked by getProductForRAccref in sequence. |
| 713 |
# Each product is asked in turn, and the first that matches wins. |
| 714 |
# So, ORDER IS ALL-IMPORTANT here. |
| 715 |
PRODUCT_CLASSES = [ |
| 716 |
RemotePreview, |
| 717 |
StaticPreview, |
| 718 |
NonExistingProduct, |
| 719 |
UnauthorizedProduct, |
| 720 |
RemoteProduct, |
| 721 |
CutoutProduct, |
| 722 |
ScaledFITSProduct, |
| 723 |
FileProduct, |
| 724 |
] |
| 725 |
|
| 726 |
def getProductForRAccref(rAccref, authGroups=None): |
| 727 |
"""returns a product for a RAccref. |
| 728 |
|
| 729 |
This tries, in sequence, to make a product using each element |
| 730 |
of PRODUCT_CLASSES' fromRAccref method. If nothing succeeds, |
| 731 |
it will return an InvalidProduct. |
| 732 |
|
| 733 |
If rAccref is a string, the function makes a real RAccref through |
| 734 |
RAccref's fromString method from it. |
| 735 |
""" |
| 736 |
if not isinstance(rAccref, RAccref): |
| 737 |
rAccref = RAccref.fromString(rAccref) |
| 738 |
for prodClass in PRODUCT_CLASSES: |
| 739 |
res = prodClass.fromRAccref(rAccref, authGroups) |
| 740 |
if res is not None: |
| 741 |
return res |
| 742 |
return InvalidProduct.fromRAccref(rAccref, authGroups) |
| 743 |
|
| 744 |
|
| 745 |
class ProductCore(svcs.DBCore): |
| 746 |
"""A core retrieving paths and/or data from the product table. |
| 747 |
|
| 748 |
You will not usually mention this core in your RDs. It is mainly |
| 749 |
used internally to serve /getproduct queries. |
| 750 |
|
| 751 |
It is instantiated from within //products.rd and relies on |
| 752 |
tables within that RD. |
| 753 |
|
| 754 |
The input data consists of accref; you can use the string form |
| 755 |
of RAccrefs, and if you renderer wants, it can pass in ready-made |
| 756 |
RAccrefs. You can pass accrefs in through both an accref |
| 757 |
param and table rows. |
| 758 |
|
| 759 |
The accref param is the normal way if you just want to retrieve a single |
| 760 |
image, the table case is for building tar files and such. There is one core |
| 761 |
instance in //products for each case. |
| 762 |
|
| 763 |
The core returns a list of instances of a subclass of ProductBase above. |
| 764 |
|
| 765 |
This core and its supporting machinery handles all the fancy product |
| 766 |
functionality (user authorization, cutouts, ...). |
| 767 |
""" |
| 768 |
name_ = "productCore" |
| 769 |
|
| 770 |
def _getRAccrefs(self, inputTable): |
| 771 |
"""returns a list of RAccref requested within inputTable. |
| 772 |
""" |
| 773 |
keys = [] |
| 774 |
args = inputTable.args |
| 775 |
if args["accref"]: |
| 776 |
keys.extend(RAccref.fromString(a) for a in args["accref"]) |
| 777 |
|
| 778 |
if args.get("pattern"): |
| 779 |
try: |
| 780 |
tablepat, filepat = args["pattern"].split("#") |
| 781 |
except ValueError: |
| 782 |
raise base.ValidationError( |
| 783 |
"Must be of the form tablepattern#filepattern", "pattern") |
| 784 |
with base.getTableConn() as conn: |
| 785 |
for row in conn.queryToDicts( |
| 786 |
"SELECT accref FROM dc.products" |
| 787 |
" WHERE" |
| 788 |
" accref LIKE %(filepat)s" |
| 789 |
" AND sourceTable LIKE %(tablepat)s", |
| 790 |
{"filepat": filepat, "tablepat": tablepat}): |
| 791 |
keys.append(RAccref.fromString(row["accref"])) |
| 792 |
|
| 793 |
return keys |
| 794 |
|
| 795 |
def _getGroups(self, authUser): |
| 796 |
if authUser is None: |
| 797 |
return set() |
| 798 |
elif authUser=="gavoadmin": |
| 799 |
return utils.AllEncompassingSet() |
| 800 |
else: |
| 801 |
return creds.getGroupsForAuthUser(authUser) |
| 802 |
|
| 803 |
def run(self, service, inputTable, queryMeta): |
| 804 |
"""returns a list of {"source": product} dicts for products matching |
| 805 |
the inputTable. |
| 806 |
""" |
| 807 |
authGroups = frozenset() |
| 808 |
if queryMeta["user_pretend"]: |
| 809 |
authGroups = self._getGroups(queryMeta.getAuthUser()) |
| 810 |
|
| 811 |
return [getProductForRAccref(r, authGroups) |
| 812 |
for r in self._getRAccrefs(inputTable)] |
| 813 |
|
| 814 |
|
| 815 |
class RAccref(object): |
| 816 |
"""A product key including possible modifiers. |
| 817 |
|
| 818 |
The product key is in the accref attribute. |
| 819 |
|
| 820 |
The modifiers come in the params dictionary. It contains (typed) |
| 821 |
values, the possible keys of which are given in _buildKeys. The |
| 822 |
values in passed in the inputDict constructor argument are parsed, |
| 823 |
anything not in _buildKeys is discarded. |
| 824 |
|
| 825 |
In principle, these modifiers are just the query part of a URL, |
| 826 |
and they generally come from the arguments of a web request. However, |
| 827 |
we don't want to carry around all request args, just those meant |
| 828 |
for product generation. |
| 829 |
|
| 830 |
One major reason for having this class is serialization into URL-parts. |
| 831 |
Basically, stringifying a RAccref yields something that can be pasted |
| 832 |
to <server root>/getproduct to yield the product URL. For the |
| 833 |
path part, this means just percent-escaping blanks, plusses and percents |
| 834 |
in the file name. The parameters are urlencoded and appended with |
| 835 |
a question mark. This representation is be parsed by the fromString |
| 836 |
function. |
| 837 |
|
| 838 |
RAccrefs have a (read only) property productsRow attribute -- that's |
| 839 |
a dictionary containing the row for accres from //products#products |
| 840 |
if that exists. If it doesn't, accessing the property will raise |
| 841 |
an NotFoundError. |
| 842 |
""" |
| 843 |
|
| 844 |
_buildKeys = dict(( |
| 845 |
("dm", str), # data model, VOTable generation |
| 846 |
("ra", float), # cutouts |
| 847 |
("dec", float), # cutouts |
| 848 |
("sra", float), # cutouts |
| 849 |
("sdec", float),# cutouts |
| 850 |
("scale", int), # FITS scaling |
| 851 |
("preview", base.parseBooleanLiteral), # return a preview? |
| 852 |
)) |
| 853 |
|
| 854 |
def __init__(self, accref, inputDict={}): |
| 855 |
self.accref = accref |
| 856 |
self.params = self._parseInputDict(inputDict) |
| 857 |
|
| 858 |
@classmethod |
| 859 |
def fromPathAndArgs(cls, path, args): |
| 860 |
"""returns a rich accref from a path and a parse_qs-dictionary args. |
| 861 |
|
| 862 |
(it's mainly a helper for fromRequest and fromString). |
| 863 |
""" |
| 864 |
inputDict = {} |
| 865 |
for key, value in args.items(): |
| 866 |
if len(value)>0: |
| 867 |
inputDict[key] = value[-1] |
| 868 |
|
| 869 |
return cls(path, inputDict) |
| 870 |
|
| 871 |
@classmethod |
| 872 |
def fromRequest(cls, path, request): |
| 873 |
"""returns a rich accref from a t.w request. |
| 874 |
|
| 875 |
Basically, it raises an error if there's no key at all, it will return |
| 876 |
a (string) accref if no processing is desired, and it will return |
| 877 |
a RAccref if any processing is requested. |
| 878 |
""" |
| 879 |
return cls.fromPathAndArgs(path, request.strargs) |
| 880 |
|
| 881 |
@classmethod |
| 882 |
def fromString(cls, keyString): |
| 883 |
"""returns a fat product key from a string representation. |
| 884 |
|
| 885 |
As a convenience, if keyString already is a RAccref, |
| 886 |
it is returned unchanged. |
| 887 |
""" |
| 888 |
if isinstance(keyString, RAccref): |
| 889 |
return keyString |
| 890 |
|
| 891 |
qSep = keyString.rfind("?") |
| 892 |
if qSep!=-1: |
| 893 |
return cls.fromPathAndArgs( |
| 894 |
unquoteProductKey(keyString[:qSep]), |
| 895 |
urllib.parse.parse_qs(keyString[qSep+1:])) |
| 896 |
|
| 897 |
return cls(unquoteProductKey(keyString)) |
| 898 |
|
| 899 |
@property |
| 900 |
def productsRow(self): |
| 901 |
"""returns the row in dc.products corresponding to this RAccref's |
| 902 |
accref, or raises a NotFoundError. |
| 903 |
""" |
| 904 |
try: |
| 905 |
return self._productsRowCache |
| 906 |
except AttributeError: |
| 907 |
|
| 908 |
with base.getTableConn() as conn: |
| 909 |
res = [dict(zip(productTableColNames(), row)) |
| 910 |
for row in conn.query( |
| 911 |
"SELECT * FROM dc.products WHERE accref=%(accref)s", |
| 912 |
{"accref": self.accref})] |
| 913 |
|
| 914 |
if not res: |
| 915 |
raise base.NotFoundError(self.accref, "accref", "product table", |
| 916 |
hint="Product URLs may disappear, though in general they should" |
| 917 |
" not. If you have an IVOID (pubDID) for the file you are trying to" |
| 918 |
" locate, you may still find it by querying the ivoa.obscore table" |
| 919 |
" using TAP and ADQL.") |
| 920 |
self._productsRowCache = res[0] |
| 921 |
|
| 922 |
# make sure whatever can end up being written to something |
| 923 |
# file-like |
| 924 |
for key in ["mime", "accessPath", "accref"]: |
| 925 |
self._productsRowCache[key] = str(self._productsRowCache[key]) |
| 926 |
|
| 927 |
return self._productsRowCache |
| 928 |
|
| 929 |
def __str__(self): |
| 930 |
# See the class docstring on quoting considerations. |
| 931 |
res = quoteProductKey(self.accref) |
| 932 |
args = urllib.parse.urlencode(dict( |
| 933 |
(k,str(v)) for k, v in sorted(self.params.items()))) |
| 934 |
if args: |
| 935 |
res = res+"?"+args |
| 936 |
return res |
| 937 |
|
| 938 |
def __repr__(self): |
| 939 |
return str(self) |
| 940 |
|
| 941 |
def __eq__(self, other): |
| 942 |
return (isinstance(other, RAccref) |
| 943 |
and self.accref==other.accref |
| 944 |
and self.params==other.params) |
| 945 |
|
| 946 |
def __ne__(self, other): |
| 947 |
return not self.__eq__(other) |
| 948 |
|
| 949 |
def _parseInputDict(self, inputDict): |
| 950 |
res = {} |
| 951 |
for key, val in inputDict.items(): |
| 952 |
if val is not None and key in self._buildKeys: |
| 953 |
try: |
| 954 |
res[key] = self._buildKeys[key](val) |
| 955 |
except (ValueError, TypeError): |
| 956 |
raise base.ValidationError( |
| 957 |
"Invalid value for constructor argument to %s:" |
| 958 |
" %s=%r"%(self.__class__.__name__, key, val), "accref") |
| 959 |
return res |
| 960 |
|
| 961 |
@property |
| 962 |
def localpath(self): |
| 963 |
try: |
| 964 |
return self._localpathCache |
| 965 |
except AttributeError: |
| 966 |
self._localpathCache = \ |
| 967 |
base.getConfig("inputsDir") / self.productsRow["accessPath"] |
| 968 |
return self._localpathCache |
| 969 |
|
| 970 |
def previewIsCacheable(self): |
| 971 |
"""returns True if the a preview generated for this rAccref |
| 972 |
is representative for all representative rAccrefs. |
| 973 |
|
| 974 |
Basically, scaled versions all have the same preview, cutouts do not. |
| 975 |
""" |
| 976 |
if "ra" in self.params: |
| 977 |
return False |
| 978 |
return True |
| 979 |
|
| 980 |
|
| 981 |
def unquoteProductKey(key): |
| 982 |
"""reverses quoteProductKey. |
| 983 |
""" |
| 984 |
return urllib.parse.unquote(key) |
| 985 |
|
| 986 |
|
| 987 |
def getProductColumns(colSeq): |
| 988 |
"""returns the columns within colSeq that contain product links of some |
| 989 |
sort. |
| 990 |
""" |
| 991 |
return [col for col in colSeq if col.displayHint.get("type")=="product"] |
| 992 |
|
| 993 |
|
| 994 |
@utils.document |
| 995 |
def quoteProductKey(key): |
| 996 |
"""returns key as getproduct URL-part. |
| 997 |
|
| 998 |
If ``key`` is a string, it is quoted as a naked accref so it's usable |
| 999 |
as the path part of an URL. If it's an ``RAccref``, it is just stringified. |
| 1000 |
The result is something that can be used after getproduct in URLs |
| 1001 |
in any case. |
| 1002 |
""" |
| 1003 |
if isinstance(key, RAccref): |
| 1004 |
return str(key) |
| 1005 |
return urllib.parse.quote(key) |
| 1006 |
rscdef.addProcDefObject("quoteProductKey", quoteProductKey) |
| 1007 |
|
| 1008 |
|
| 1009 |
@utils.document |
| 1010 |
def makeProductLink(key, withHost=True, useHost=None): |
| 1011 |
"""returns the URL at which a product can be retrieved. |
| 1012 |
|
| 1013 |
key can be an accref string or an RAccref. |
| 1014 |
|
| 1015 |
Note that this is using the preferred host as the basic URL. If |
| 1016 |
you are running dual-protocol http/https and you ingest results |
| 1017 |
of this function into the database, it is advisable to cut off |
| 1018 |
the scheme part of the URI (e.g., ``split(":", 1)[-1]``). In |
| 1019 |
data products served, DaCHS will then put in the scheme used |
| 1020 |
for the query. |
| 1021 |
|
| 1022 |
DaCHS (almost always) also allows full http URIs as accrefs. These |
| 1023 |
will be returned unchanged. |
| 1024 |
""" |
| 1025 |
if hasattr(key, "startswith") and ( |
| 1026 |
key.startswith("http://") or key.startswith("https://")): |
| 1027 |
return key |
| 1028 |
|
| 1029 |
url = base.makeSitePath("/getproduct/%s"%RAccref.fromString(key)) |
| 1030 |
if withHost: |
| 1031 |
if useHost is None: |
| 1032 |
useHost = base.getCurrentServerURL() |
| 1033 |
url = urllib.parse.urljoin(useHost, url) |
| 1034 |
return url |
| 1035 |
rscdef.addProcDefObject("makeProductLink", makeProductLink) |
| 1036 |
|
| 1037 |
|
| 1038 |
def formatProductLink(val, useHost): |
| 1039 |
"""turns a string val into a product link. |
| 1040 |
|
| 1041 |
This is faily ad-hoc: if val looks like a URL, it is left alone, |
| 1042 |
else turn it into a link into our product service (which means val |
| 1043 |
must be an accref into the product table). |
| 1044 |
""" |
| 1045 |
if val: |
| 1046 |
# type check to allow cut-out or scaled accrefs (which need |
| 1047 |
# makeProductLink in any case) |
| 1048 |
if isinstance(val, str) and utils.looksLikeURLPat.match(val): |
| 1049 |
return val |
| 1050 |
else: |
| 1051 |
return makeProductLink(val, withHost=True, useHost=useHost) |
| 1052 |
|
| 1053 |
|
| 1054 |
def _productMapperFactory(colDesc): |
| 1055 |
"""A value mapper factory for product links. |
| 1056 |
|
| 1057 |
Within the DC, any column called accref, with a display hint of |
| 1058 |
type=product, a UCD of VOX:Image_AccessReference, or a utype |
| 1059 |
of Access.Reference may contain a key into the product table. |
| 1060 |
Here, we map those to links to the get renderer unless they look |
| 1061 |
like a URL to begin with. |
| 1062 |
""" |
| 1063 |
if not ( |
| 1064 |
colDesc["utype"]=="ssa:Access.Reference" |
| 1065 |
or colDesc["ucd"]=="VOX:Image_AccessReference" |
| 1066 |
or colDesc["displayHint"].get("type")=="product"): |
| 1067 |
return |
| 1068 |
|
| 1069 |
return functools.partial( |
| 1070 |
formatProductLink, useHost=base.getCurrentServerURL()) |
| 1071 |
|
| 1072 |
utils.registerDefaultMF(_productMapperFactory) |