| 1 |
""" |
| 2 |
The user interface to importing resources into the VO. |
| 3 |
""" |
| 4 |
|
| 5 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 6 |
#c |
| 7 |
#c This program is free software, covered by the GNU GPL. See the |
| 8 |
#c COPYING file in the source distribution. |
| 9 |
|
| 10 |
|
| 11 |
import argparse |
| 12 |
import sys |
| 13 |
|
| 14 |
from gavo import api |
| 15 |
from gavo import base |
| 16 |
from gavo.protocols import obscore |
| 17 |
from gavo.protocols import tap |
| 18 |
from gavo.user import common |
| 19 |
|
| 20 |
|
| 21 |
class RetvalWatcher(base.ObserverBase): |
| 22 |
"""an Observer giving appropriate program return values. |
| 23 |
|
| 24 |
Basically, we want to return an error signature even if we managed |
| 25 |
to import things if at least once there was an error notification. |
| 26 |
|
| 27 |
We define this "error occurred but we manage" code to 101 here. I'm |
| 28 |
sure we can do better than that. |
| 29 |
""" |
| 30 |
retval = 0 |
| 31 |
|
| 32 |
@base.listensTo("Error") |
| 33 |
def fixRetVal(self, msg): |
| 34 |
self.retval = 101 |
| 35 |
|
| 36 |
|
| 37 |
class TableCollector(base.ObserverBase): |
| 38 |
"""collects the qualified names of tables changed. |
| 39 |
|
| 40 |
This is used to run vacuum analyze on the respective tables before |
| 41 |
the import exits; the the vacuumAll method of this class can do |
| 42 |
that once all importing connections are closed (even if an Observer |
| 43 |
shouldn't do a thing like that...) |
| 44 |
""" |
| 45 |
def __init__(self, eh): |
| 46 |
base.ObserverBase.__init__(self, eh) |
| 47 |
self.tablesChanged = [] |
| 48 |
|
| 49 |
@base.listensTo("DBTableModified") |
| 50 |
def addChangedTable(self, fqName): |
| 51 |
self.tablesChanged.append(fqName) |
| 52 |
|
| 53 |
def vacuumAll(self): |
| 54 |
from gavo import adql |
| 55 |
tableNameSym = adql.getSymbols()["qualifier"] |
| 56 |
|
| 57 |
# do not use a connection from the pool here; they might be debug |
| 58 |
# connections with might implicitly start transactions, which |
| 59 |
# in turn will break vacuuming. |
| 60 |
conn = base.getDBConnection("feed", autocommitted=True) |
| 61 |
for tableName in self.tablesChanged: |
| 62 |
try: |
| 63 |
tableNameSym.parseString(tableName, parseAll=True) |
| 64 |
except base.ParseException: |
| 65 |
# forget about odd table names for now. |
| 66 |
pass |
| 67 |
conn.execute("VACUUM ANALYZE %s"%tableName) |
| 68 |
conn.close() |
| 69 |
|
| 70 |
|
| 71 |
def process(opts, args): |
| 72 |
"""imports the data set described by args governed by opts. |
| 73 |
|
| 74 |
The first item of args is an RD id, any remaining ones are interpreted |
| 75 |
as DD ids within the selected RD. If no DD ids are given, all DDs within |
| 76 |
the RD are processed except those for which auto has been set to False. |
| 77 |
|
| 78 |
opts is either a ParseOption instance or the object returned by |
| 79 |
main's parseOption function below. |
| 80 |
""" |
| 81 |
# process manages its dependencies itself |
| 82 |
retvalWatcher = RetvalWatcher(api.ui) |
| 83 |
opts.buildDependencies = False |
| 84 |
|
| 85 |
# collect tables due for vacuuming |
| 86 |
tableCollector = TableCollector(api.ui) |
| 87 |
|
| 88 |
connection = api.getDBConnection("admin") |
| 89 |
|
| 90 |
resolved = api.getReferencedElement(args[0]) |
| 91 |
if isinstance(resolved, api.RD): |
| 92 |
rd = resolved |
| 93 |
dds = common.getPertainingDDs(rd, args[1:]) |
| 94 |
|
| 95 |
elif isinstance(resolved, api.DataDescriptor): |
| 96 |
rd = resolved.rd |
| 97 |
dds = [resolved] |
| 98 |
if len(args)>1: |
| 99 |
raise api.ReportableError( |
| 100 |
"You cannot give additional identifiers when you import a single DD") |
| 101 |
|
| 102 |
else: |
| 103 |
raise api.ReportableError("args[0] references neither an RD nor a DD") |
| 104 |
|
| 105 |
if not opts.suppressMeta: |
| 106 |
tap.unpublishFromTAP(rd, connection) |
| 107 |
tap.publishToTAP(rd, connection) |
| 108 |
|
| 109 |
dbCatalogChanged = False |
| 110 |
|
| 111 |
for dd in dds: |
| 112 |
if opts.metaOnly: |
| 113 |
api.ui.notifyInfo("Updating meta for %s"%dd.id) |
| 114 |
res = api.Data.create(dd, parseOptions=opts, connection=connection) |
| 115 |
res.updateMeta() |
| 116 |
|
| 117 |
else: |
| 118 |
api.ui.notifyInfo("Making data %s"%dd.getFullId()) |
| 119 |
res = api.makeData(dd, parseOptions=opts, connection=connection) |
| 120 |
dbCatalogChanged = dbCatalogChanged or res.dbCatalogChanged() |
| 121 |
if hasattr(res, "nAffected"): |
| 122 |
api.ui.notifyInfo("Rows affected: %s"%res.nAffected) |
| 123 |
|
| 124 |
# Let's update the date updated independently of dachs pub; not many |
| 125 |
# people bother to re-publish the RD just because they did a re-import. |
| 126 |
if base.UnmanagedQuerier(connection).getTableType("dc.resources"): |
| 127 |
# skip this during bootstrap |
| 128 |
connection.execute("UPDATE dc.resources SET" |
| 129 |
" dateupdated=CURRENT_TIMESTAMP" |
| 130 |
" WHERE sourcerd=%(rdid)s", {"rdid": rd.sourceId}) |
| 131 |
|
| 132 |
# We're committing here so that we don't lose all importing |
| 133 |
# work just because some dependent messes up. |
| 134 |
connection.commit() |
| 135 |
|
| 136 |
if not opts.suppressMeta: |
| 137 |
rd.updateMetaInDB(connection, "import") |
| 138 |
connection.commit() |
| 139 |
|
| 140 |
# re-indexing is a big deal because it may involve primary key |
| 141 |
# operations and, in particular, clustering, which locks the |
| 142 |
# table. Let's take everything out of obscore before doing that. |
| 143 |
if opts.metaPlusIndex: |
| 144 |
with obscore.suspendFromObscore(rd, connection): |
| 145 |
for dd in dds: |
| 146 |
data = api.Data.create(dd, parseOptions=opts, connection=connection) |
| 147 |
for t in data: |
| 148 |
t.dropIndices() |
| 149 |
t.makeIndices() |
| 150 |
|
| 151 |
api.makeDependentsFor(dds, opts, connection, dbCatalogChanged) |
| 152 |
connection.commit() |
| 153 |
|
| 154 |
if not opts.suppressMeta: |
| 155 |
base.tryRemoteReload("__system__/dc_tables") |
| 156 |
|
| 157 |
tableCollector.vacuumAll() |
| 158 |
|
| 159 |
if opts.obtainLimits: |
| 160 |
from gavo.user import limits |
| 161 |
limits.updateForRD(rd, connection) |
| 162 |
|
| 163 |
connection.commit() |
| 164 |
|
| 165 |
return retvalWatcher.retval |
| 166 |
|
| 167 |
|
| 168 |
class HideADQLAction(argparse.Action): |
| 169 |
def __call__(self, parser, namespace, values, option_string=None): |
| 170 |
from gavo.rscdef import tabledef |
| 171 |
tabledef.ADQLVisibilityAttribute.trueValue = "hidden" |
| 172 |
|
| 173 |
|
| 174 |
def main(): |
| 175 |
"""parses the command line and imports a set of data accordingly. |
| 176 |
""" |
| 177 |
def parseCmdline(): |
| 178 |
parser = argparse.ArgumentParser(description="imports all (or just the" |
| 179 |
" selected) data items from an RD into the database.") |
| 180 |
parser.add_argument("-n", "--updateRows", help="Use UPDATE on primary" |
| 181 |
" key rather than INSERT with rows inserted to DBTables.", |
| 182 |
action="store_true", dest="doTableUpdates", default=False) |
| 183 |
parser.add_argument("-d", "--dumpRows", help="Dump raw rows as they are" |
| 184 |
" emitted by the grammar.", dest="dumpRows", action="store_true", |
| 185 |
default=False) |
| 186 |
parser.add_argument("-D", "--dumpIngestees", help="Dump processed" |
| 187 |
" rows as emitted by the row makers.", dest="dumpIngestees", |
| 188 |
action="store_true", default=False) |
| 189 |
parser.add_argument("-R", "--redoIndex", help="Drop indices before" |
| 190 |
" updating a table and recreate them when done", dest="dropIndices", |
| 191 |
action="store_true", default=False) |
| 192 |
parser.add_argument("-m", "--meta-only", help="just update table meta" |
| 193 |
" (privileges, column descriptions,...).", dest="metaOnly", |
| 194 |
action="store_true") |
| 195 |
parser.add_argument("--suppress-meta", help="do not update any metadata" |
| 196 |
" (this is likely only useful for updating DDs that already exist).", |
| 197 |
dest="suppressMeta", action="store_true") |
| 198 |
parser.add_argument("-I", "--meta-and-index", help="do not import, but" |
| 199 |
" update table meta (privileges, column descriptions,...) and recreate" |
| 200 |
" the indices. NOTE: This will at the moment *not* re-create" |
| 201 |
" primary keys because that breaks when there are foreign keys on" |
| 202 |
" the table. We do not see a good solution of this at the moment.", |
| 203 |
dest="metaPlusIndex", action="store_true") |
| 204 |
parser.add_argument("-s", "--system", help="(re-)create system tables, too", |
| 205 |
dest="systemImport", action="store_true") |
| 206 |
parser.add_argument("-v", "--verbose", help="talk a lot while working", |
| 207 |
dest="verbose", action="store_true") |
| 208 |
parser.add_argument("-r", "--reckless", help="Do not validate rows" |
| 209 |
" before ingestion", dest="validateRows", action="store_false", |
| 210 |
default=True) |
| 211 |
parser.add_argument("-M", "--stop-after", help="Stop after having parsed" |
| 212 |
" MAX rows", action="store", dest="maxRows", type=int, |
| 213 |
default=None) |
| 214 |
parser.add_argument("-b", "--batch-size", help="deliver N rows at a time" |
| 215 |
" to the database.", dest="batchSize", action="store", type=int, |
| 216 |
default=5000) |
| 217 |
parser.add_argument("-c", "--continue-bad", help="do not bail out after" |
| 218 |
" an error, just skip the current source and continue with the" |
| 219 |
" next one.", dest="keepGoing", action="store_true", default=False) |
| 220 |
parser.add_argument("-l", "--limits", help="obtain limits for the" |
| 221 |
" primary RD of this import. This is basically like running dachs" |
| 222 |
" limits on the entire RD." |
| 223 |
" You generally want limits, but while trying things out, you don't" |
| 224 |
" want to spend the extra effort. Use -l on the 'last' import or" |
| 225 |
" perhaps when importing known-good RDs.", action="store_true", |
| 226 |
dest="obtainLimits", default=False) |
| 227 |
parser.add_argument("-L", "--commit-after-meta", help="commit the importing" |
| 228 |
" transaction after updating the meta tables. Use this when loading" |
| 229 |
" large (hence -L) data sets to avoid keeping a lock on the meta tables" |
| 230 |
" for the duration of the input, i.e., potentially days. The price" |
| 231 |
" is that users will see empty tables during the import.", |
| 232 |
dest="commitAfterMeta", action="store_true", default=False) |
| 233 |
parser.add_argument("--hide-adql", help="Interpret adql=True on tables" |
| 234 |
" as adql=hidden (this is for fallback mirrors)", nargs=0, |
| 235 |
metavar=None, action=HideADQLAction) |
| 236 |
parser.add_argument("rd", type=str, |
| 237 |
help="An RD id or a file system path of an RD; alternatively, you" |
| 238 |
" can pass a full DD references (something like bla/q#import).") |
| 239 |
parser.add_argument("dds", type=str, nargs="*", |
| 240 |
help="Optional DD ids to restrict the import to these. Non-auto" |
| 241 |
" DDs actually must be mentioned here to import them. You cannot" |
| 242 |
" give extra DD ids if the first argument is a DD reference" |
| 243 |
" (background: they might belong to different RDs, and dachs imp" |
| 244 |
" can only deal with one RD at a time).") |
| 245 |
|
| 246 |
args = parser.parse_args() |
| 247 |
|
| 248 |
if args.metaPlusIndex: |
| 249 |
args.metaOnly = True |
| 250 |
|
| 251 |
return args |
| 252 |
|
| 253 |
|
| 254 |
args = parseCmdline() |
| 255 |
sys.exit(process(args, [args.rd]+args.dds)) |