Debian Codegraph @

gavo/web/producttar.py

raw
1 """
2 Helper functions for producing tar files from tables containing
3 a product column.
4
5 Everything in this module expects the product interface, i.e., tables
6 must at least contain accref, owner, embargo, and accsize fields.
7 """
8
9 #c Copyright 2008-2025, the GAVO project <[email protected]>
10 #c
11 #c This program is free software, covered by the GNU GPL. See the
12 #c COPYING file in the source distribution.
13
14
15 # XXX TODO: this should eventually become a renderer on the product core,
16 # redirected to from the current TarResponse.
17
18 import functools
19 import io
20 import os
21 import tarfile
22 import time
23
24 from gavo import base
25 from gavo import svcs
26 from gavo.protocols import products
27 from gavo.svcs import streaming
28
29
30 MS = base.makeStruct
31
32
33 class UniqueNameGenerator(object):
34 """A factory to build unique names from possibly ambiguous ones.
35
36 If the lower case of a name is not known to an instance, it just returns
37 that name. Otherwise, it disambiguates by adding characters in front
38 of the extension.
39 """
40 def __init__(self):
41 self.knownNames = set()
42
43 def _buildNames(self, baseName):
44 base, ext = os.path.splitext(baseName)
45 yield "dc_data/%s%s"%(base, ext)
46 i = 1
47 while True:
48 yield "dc_data/%s-%03d%s"%(base, i, ext)
49 i += 1
50
51 def makeName(self, baseName):
52 for name in self._buildNames(baseName):
53 if name.lower() not in self.knownNames:
54 self.knownNames.add(name.lower())
55 return str(name)
56
57
58 class ProductTarMaker(object):
59 """A factory for tar files.
60
61 You probably don't want to instantiate it directly but instead get a copy
62 through the getProductMaker function below.
63
64 The main entry point to this class is deliverProductTar.
65 """
66 def __init__(self):
67 self.rd = base.caches.getRD("__system__/products")
68 self.core = self.rd.getById("forTar")
69
70 def _getEmbargoedFile(self, name):
71 stuff = io.BytesIO(b"This file is embargoed. Sorry.\n")
72 b = tarfile.TarInfo(name)
73 b.size = len(stuff.getvalue())
74 b.mtime = time.time()
75 return b, stuff
76
77 def _getTarInfoFromProduct(self, prod, name):
78 """returns a tar info from a general products.PlainProduct instance
79 prod.
80
81 This is relatively inefficient for data that's actually on disk,
82 so you should only use it when data is being computed on the fly.
83 """
84 assert not isinstance(prod, products.UnauthorizedProduct)
85 data = b"".join(prod.iterData())
86 b = tarfile.TarInfo(name)
87 b.size = len(data)
88 b.mtime = time.time()
89 return b, io.BytesIO(data)
90
91 def _getDestName(self, productsTable):
92 """returns a filename for a tar with the stuff in productsTable.
93
94 For now, we just distinguish overflowed and non-overflowed tars.
95 """
96 qs = base.getMetaText(productsTable, "_queryStatus")
97 if qs=="OVERFLOW":
98 return "truncated_data.tar"
99 else:
100 return "data.tar"
101
102 def _productsToTar(self, productList, destination):
103 """actually writes the tar.
104 """
105 nameGen = UniqueNameGenerator()
106 outputTar = tarfile.TarFile.open("data.tar", "w|", destination)
107 for prodRec in productList:
108 src = prodRec
109 if isinstance(src, products.NonExistingProduct):
110 continue # just skip files that somehow don't exist any more
111
112 elif isinstance(src, products.UnauthorizedProduct):
113 outputTar.addfile(*self._getEmbargoedFile(
114 nameGen.makeName(src.name)))
115
116 elif isinstance(src, products.FileProduct):
117 # actual file in the file system
118 outputTar.add(str(src.rAccref.localpath),
119 nameGen.makeName(src.name))
120
121 else: # anything else is read from the src
122 outputTar.addfile(*self._getTarInfoFromProduct(src,
123 nameGen.makeName(src.name)))
124 outputTar.close()
125 return b"" # finish off request if necessary.
126
127 def _streamOutTar(self, productData, request, queryMeta, destName):
128 request.setHeader('content-disposition',
129 'attachment; filename=%s'%destName)
130 request.setHeader("content-type", "application/x-tar")
131
132 def writeTar(dest):
133 self._productsToTar(productData, dest)
134
135 return streaming.streamOut(writeTar, request, queryMeta)
136
137 def deliverProductTar(self, coreResult, request, queryMeta):
138 """causes a tar containing all accrefs mentioned in coreResult
139 to be streamed out via request.
140 """
141 table = coreResult.getPrimaryTable()
142 productColumns = products.getProductColumns(table.tableDef.columns)
143 if not productColumns:
144 raise base.ValidationError("This query does not select any"
145 " columns with access references", "_OUTPUT")
146
147 accrefs = []
148 for row in table:
149 for col in productColumns:
150 accrefs.append(row[col.name])
151
152 inputTable = svcs.CoreArgs.fromRawArgs(
153 self.rd.getById("forTar").inputTable,
154 {"accref": accrefs})
155
156 prods = self.core.run(self.rd.getById("getTar"), inputTable, queryMeta)
157 return self._streamOutTar(prods, request, queryMeta,
158 self._getDestName(table))
159
160
161 @functools.lru_cache(1)
162 def getTarMaker():
163 return ProductTarMaker()