| 1 |
""" |
| 2 |
DaCHS supports dump/restore operations on tables or set of tables. |
| 3 |
This module implements the underlying file format and some utilities. |
| 4 |
|
| 5 |
The file format itself is a tar.gz file with an index.txt consisting of lines |
| 6 |
|
| 7 |
file_name table-id |
| 8 |
|
| 9 |
followed by the files. Table id is DaCHS's usual rd-id#table-id. |
| 10 |
The files contain binary dump material. |
| 11 |
""" |
| 12 |
|
| 13 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 14 |
#c |
| 15 |
#c This program is free software, covered by the GNU GPL. See the |
| 16 |
#c COPYING file in the source distribution. |
| 17 |
|
| 18 |
|
| 19 |
import os |
| 20 |
import sys |
| 21 |
import time |
| 22 |
import tarfile |
| 23 |
from io import BytesIO |
| 24 |
|
| 25 |
from gavo import base |
| 26 |
from gavo import rscdef |
| 27 |
from gavo import utils |
| 28 |
from gavo.rsc import tables |
| 29 |
|
| 30 |
|
| 31 |
def parseIndexFile(srcFile): |
| 32 |
"""parses our index.txt file format and returns (member-name, table-id) |
| 33 |
tuples. |
| 34 |
|
| 35 |
srcFile is an open binary file, probably from TarFile.extractfile. |
| 36 |
|
| 37 |
If you change the index file format, you'll have to change this |
| 38 |
and the corresponding code in createDump. |
| 39 |
""" |
| 40 |
for line in srcFile: |
| 41 |
parts = line.decode("utf-8").strip().split() |
| 42 |
assert len(parts)==2 |
| 43 |
yield parts |
| 44 |
|
| 45 |
|
| 46 |
def iterDbTables(objectId, connection): |
| 47 |
"""iterates over dbtable objects referenced by objectId. |
| 48 |
|
| 49 |
objectId can reference a table def or an RD (in which case all |
| 50 |
onDisk tables from it are returned). Or it can be a table already. |
| 51 |
""" |
| 52 |
if not isinstance(objectId, str): |
| 53 |
# let's believe it's a database table |
| 54 |
# (perhaps check that tableId.tableDef is good?) |
| 55 |
yield objectId |
| 56 |
|
| 57 |
else: |
| 58 |
obj = base.resolveCrossId(objectId) |
| 59 |
if isinstance(obj, rscdef.TableDef): |
| 60 |
yield tables.TableForDef(obj, connection=connection) |
| 61 |
|
| 62 |
elif hasattr(obj, "tables"): # let's assume it's an RD |
| 63 |
for td in obj.tables: |
| 64 |
if td.onDisk and not td.viewStatement: |
| 65 |
yield tables.TableForDef(td, connection=connection) |
| 66 |
|
| 67 |
else: |
| 68 |
raise base.ReportableError("Can only dump by table or RD," |
| 69 |
" but %s is neither"%objectId) |
| 70 |
|
| 71 |
|
| 72 |
def getTablesForIds(tableIds, connection): |
| 73 |
"""returns a list of validated dbtables of all tableIds. |
| 74 |
|
| 75 |
This will raise an exception if any table id or database table doesn't |
| 76 |
exist, or if the on-disk schema doesn't match the definition. |
| 77 |
|
| 78 |
For convenience in internal use, tableIds that already are table |
| 79 |
instances will not be touched. That's a bit tricky, though, because |
| 80 |
you can have data from different transactions when you do that. |
| 81 |
""" |
| 82 |
dbtables = [] |
| 83 |
for tableId in tableIds: |
| 84 |
for table in iterDbTables(tableId, connection): |
| 85 |
table.ensureOnDiskMatches() |
| 86 |
dbtables.append(table) |
| 87 |
return dbtables |
| 88 |
|
| 89 |
|
| 90 |
def createDump(tableIds, destFile, binary=True): |
| 91 |
"""writes a DaCHS dump of tableIds to destFile. |
| 92 |
|
| 93 |
tableIds is a list of rd-id#table-id identifiers (all must resolve), |
| 94 |
destFile is a file object opened for writing. |
| 95 |
""" |
| 96 |
with base.getTableConn() as connection: |
| 97 |
toDump = getTablesForIds(tableIds, connection) |
| 98 |
destTar = tarfile.open(fileobj=destFile, mode="w:gz") |
| 99 |
dumped = [] |
| 100 |
|
| 101 |
if binary: |
| 102 |
namePattern = "table_%03d.dump" |
| 103 |
else: |
| 104 |
namePattern = "table_%03d.textdump" |
| 105 |
|
| 106 |
for index, curTable in enumerate(toDump): |
| 107 |
try: |
| 108 |
dumpedBytes = BytesIO() |
| 109 |
curTable.copyOut(dumpedBytes, binary=binary) |
| 110 |
dumpedBytes.seek(0) |
| 111 |
|
| 112 |
curInfo = tarfile.TarInfo(namePattern%index) |
| 113 |
curInfo.mtime = time.time() |
| 114 |
curInfo.size = len(dumpedBytes.getvalue()) |
| 115 |
destTar.addfile(curInfo, dumpedBytes) |
| 116 |
|
| 117 |
dumped.append((curInfo.name, curTable.tableDef.getFullId())) |
| 118 |
except Exception as msg: |
| 119 |
base.ui.notifyError("Dumping %s failed: %s"%( |
| 120 |
curTable.tableDef.getFullId(), |
| 121 |
utils.safe_str(msg))) |
| 122 |
|
| 123 |
indexText = ("\n".join( |
| 124 |
"%s %s"%d for d in dumped)).encode("utf-8") |
| 125 |
curInfo = tarfile.TarInfo("index.txt") |
| 126 |
curInfo.mtime = time.time() |
| 127 |
curInfo.size = len(indexText) |
| 128 |
destTar.addfile(curInfo, BytesIO(indexText)) |
| 129 |
|
| 130 |
destTar.close() |
| 131 |
|
| 132 |
|
| 133 |
def iterTableInfos(dumpFile): |
| 134 |
"""iterates over table info tuples from an open dump file. |
| 135 |
|
| 136 |
Each tuple has the member name, the table id, a boolean whether |
| 137 |
the table definion is accessible, the UTC unix time the dump |
| 138 |
was made, and the size of the dump. |
| 139 |
""" |
| 140 |
tf = tarfile.open(fileobj=dumpFile, mode="r:gz") |
| 141 |
for memberName, tableId in parseIndexFile(tf.extractfile("index.txt")): |
| 142 |
memberInfo = tf.getmember(memberName) |
| 143 |
tdExists = True |
| 144 |
try: |
| 145 |
base.resolveCrossId(tableId, forceType=rscdef.TableDef) |
| 146 |
except base.NotFoundError: |
| 147 |
tdExists = False |
| 148 |
|
| 149 |
yield (memberName, tableId, tdExists, memberInfo.mtime, memberInfo.size) |
| 150 |
|
| 151 |
|
| 152 |
def restoreDump(dumpFile): |
| 153 |
"""restores a dump. |
| 154 |
|
| 155 |
dumpFile is an open file object containing a file created by createDump. |
| 156 |
|
| 157 |
This comprises recrating all mentioned tables, copying in the associated |
| 158 |
data, and re-creating all indices. |
| 159 |
|
| 160 |
Each table is handled in a separate transaction, we do not stop if a single |
| 161 |
restore has failed. |
| 162 |
""" |
| 163 |
toDo = list(iterTableInfos(dumpFile)) |
| 164 |
dumpFile.seek(0) |
| 165 |
tf = tarfile.open(fileobj=dumpFile, mode="r:gz") |
| 166 |
|
| 167 |
with base.getWritableAdminConn() as connection: |
| 168 |
for memberName, tdId, tdExists, _, _ in toDo: |
| 169 |
if not tdExists: |
| 170 |
base.ui.notifyWarning("Skipping restore of undefined table %s"%tdId) |
| 171 |
continue |
| 172 |
|
| 173 |
try: |
| 174 |
table = tables.TableForDef( |
| 175 |
base.resolveCrossId(tdId, forceType=rscdef.TableDef), |
| 176 |
connection=connection) |
| 177 |
table.recreate() |
| 178 |
table.copyIn(tf.extractfile(memberName), |
| 179 |
binary=memberName.endswith(".dump")) |
| 180 |
table.makeIndices() |
| 181 |
except Exception as msg: |
| 182 |
table.connection.rollback() |
| 183 |
base.ui.notifyError("Restore of %s failed: %s"%( |
| 184 |
tdId, utils.safe_str(msg))) |
| 185 |
else: |
| 186 |
table.connection.commit() |
| 187 |
|
| 188 |
|
| 189 |
################# CLI functions |
| 190 |
|
| 191 |
@utils.exposedFunction([ |
| 192 |
utils.Arg("-t", "--text", |
| 193 |
help="Dump text rather than binary", |
| 194 |
dest="textFormat", |
| 195 |
action="store_true"), |
| 196 |
utils.Arg("dumpFile", help="Name of a file to write the dump to; use - to" |
| 197 |
" dump to stderr."), |
| 198 |
utils.Arg("ids", help="ids of table definitions (as in myres/q#main)" |
| 199 |
" or RDs to dump.", nargs="+")], |
| 200 |
help="Dump one or more tables to DaCHS' dump format.") |
| 201 |
def create(args): |
| 202 |
if args.dumpFile=="-": |
| 203 |
dumpTo = sys.stdout |
| 204 |
else: |
| 205 |
dn = os.path.dirname(args.dumpFile) |
| 206 |
if dn: |
| 207 |
utils.ensureDir(dn) |
| 208 |
dumpTo = open(args.dumpFile, "wb") |
| 209 |
|
| 210 |
try: |
| 211 |
createDump(args.ids, dumpTo, not args.textFormat) |
| 212 |
finally: |
| 213 |
dumpTo.flush() |
| 214 |
|
| 215 |
if dumpTo!=sys.stdout: |
| 216 |
dumpTo.close() |
| 217 |
|
| 218 |
|
| 219 |
@utils.exposedFunction([ |
| 220 |
utils.Arg("source", |
| 221 |
help="File to restore from. Use - to restore from stdin.")], |
| 222 |
help="Restore one or more table(s) from a file created by the create" |
| 223 |
" subcommand before") |
| 224 |
def load(args): |
| 225 |
if args.source=="-": |
| 226 |
loadFrom = sys.stdin |
| 227 |
else: |
| 228 |
loadFrom = open(args.source, "rb") |
| 229 |
restoreDump(loadFrom) |
| 230 |
|
| 231 |
if loadFrom!=sys.stdin: |
| 232 |
loadFrom.close() |
| 233 |
|
| 234 |
|
| 235 |
@utils.exposedFunction([ |
| 236 |
utils.Arg("source", help="File to list")], |
| 237 |
help="List tables and dump metadata from a DaCHS dump.") |
| 238 |
def ls(args): |
| 239 |
import datetime |
| 240 |
|
| 241 |
with open(args.source, "rb") as f: |
| 242 |
data = [] |
| 243 |
for _, tdId, exists, mtime, size in iterTableInfos(f): |
| 244 |
data.append(( |
| 245 |
tdId, |
| 246 |
"probably" if exists else "no", |
| 247 |
datetime.datetime.utcfromtimestamp(mtime).isoformat(), |
| 248 |
size)) |
| 249 |
sys.stdout.write(utils.formatSimpleTable( |
| 250 |
data, |
| 251 |
titles="table restorable? dumped size".split())+"\n") |
| 252 |
|
| 253 |
|
| 254 |
def main(): |
| 255 |
"""does the user interaction. |
| 256 |
""" |
| 257 |
from gavo import rscdesc #noflake: for registration |
| 258 |
args = utils.makeCLIParser(globals()).parse_args() |
| 259 |
args.subAction(args) |