| 1 |
""" |
| 2 |
DC administration interface. |
| 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 pathlib |
| 12 |
import re |
| 13 |
import sys |
| 14 |
|
| 15 |
from gavo import base |
| 16 |
from gavo import utils |
| 17 |
from gavo import rscdef |
| 18 |
from gavo import rscdesc #noflake: for cache registration |
| 19 |
from gavo import svcs |
| 20 |
from gavo.protocols import creds |
| 21 |
from gavo.protocols import uws |
| 22 |
from gavo.utils import Arg, exposedFunction, makeCLIParser |
| 23 |
|
| 24 |
|
| 25 |
@exposedFunction([ |
| 26 |
Arg("user", help="the user name"), |
| 27 |
Arg("password", help="a password for the user"), |
| 28 |
Arg("remarks", help="optional remarks", |
| 29 |
default="", nargs='?')], |
| 30 |
help="add a user/password pair and a matching group to the DC server") |
| 31 |
def adduser(querier, args): |
| 32 |
try: |
| 33 |
creds.addUser(querier.connection, args.user, args.password, args.remarks) |
| 34 |
except base.IntegrityError: |
| 35 |
raise base.ui.logOldExc(base.ReportableError("User %s already exists." |
| 36 |
" Use 'changeuser' command to edit."%args.user)) |
| 37 |
|
| 38 |
|
| 39 |
@exposedFunction([ |
| 40 |
Arg("user", help="the user name to remove")], |
| 41 |
help="remove a user from the DC server") |
| 42 |
def deluser(querier, args): |
| 43 |
rowsAffected = creds.delUser(querier.connection, args.user) |
| 44 |
if not rowsAffected: |
| 45 |
sys.stderr.write("Warning: No rows deleted while deleting user %s\n"% |
| 46 |
args.user) |
| 47 |
|
| 48 |
|
| 49 |
@exposedFunction([ |
| 50 |
Arg("user", help="the user name"), |
| 51 |
Arg("password", help="a password for the user"), |
| 52 |
Arg("remarks", help="optional remarks", |
| 53 |
default="", nargs='?')], |
| 54 |
help="change remarks and/or password for a DC user") |
| 55 |
def changeuser(querier, args): |
| 56 |
creds.changeUser(querier.connection, |
| 57 |
args.user, args.password, args.remarks) |
| 58 |
|
| 59 |
|
| 60 |
@exposedFunction([ |
| 61 |
Arg("user", help="a user name"), |
| 62 |
Arg("group", help="the group to add the user to")], |
| 63 |
help="add a user to a group") |
| 64 |
def addtogroup(querier, args): |
| 65 |
try: |
| 66 |
creds.addToGroup(querier.connection, args.user, args.group) |
| 67 |
except Exception: |
| 68 |
raise base.ui.logOldExc(base.ReportableError( |
| 69 |
"User %s does not exist."%args.user)) |
| 70 |
|
| 71 |
|
| 72 |
@exposedFunction([ |
| 73 |
Arg("user", help="a user name"), |
| 74 |
Arg("group", help="the group to remove the user from")], |
| 75 |
help="remove a user from a group") |
| 76 |
def delfromgroup(querier, args): |
| 77 |
if not creds.removeFromGroup(querier.connection, args.user, args.group): |
| 78 |
sys.stderr.write("Warning: No rows deleted while deleting user" |
| 79 |
" %s from group %s\n"%(args.user, args.group)) |
| 80 |
|
| 81 |
|
| 82 |
@exposedFunction(help="list users known to the DC") |
| 83 |
def listusers(querier, args): |
| 84 |
data = list(querier.connection.query("SELECT username, groupname, remarks" |
| 85 |
" FROM dc.users NATURAL JOIN dc.groups ORDER BY username")) |
| 86 |
curUser = None |
| 87 |
for user, group, remark in data: |
| 88 |
if user!=curUser: |
| 89 |
print("\n%s (%s) --"%(user, remark), end=' ') |
| 90 |
curUser = user |
| 91 |
print(group, end=' ') |
| 92 |
print() |
| 93 |
|
| 94 |
|
| 95 |
@exposedFunction([ |
| 96 |
Arg("-f", help="also remove all jobs in ERROR and ABORTED states (only use" |
| 97 |
" if you are sure what you are doing).", action="store_true", |
| 98 |
dest="includeFailed"), |
| 99 |
Arg("-p", help="also remove all jobs in PENDING states (only use" |
| 100 |
" if you are sure what you are doing).", action="store_true", |
| 101 |
dest="includeForgotten"), |
| 102 |
Arg("--all", help="remove all jobs (this is extremely unfriendly." |
| 103 |
" Don't use this on public UWSes)", action="store_true", |
| 104 |
dest="includeAll"), |
| 105 |
Arg("--nuke-completed", help="also remove COMPLETEd jobs (this is" |
| 106 |
" unfriendly. Don't do this on public UWSes).", action="store_true", |
| 107 |
dest="includeCompleted"),], |
| 108 |
help="remove expired UWS jobs") |
| 109 |
def cleantap(querier, args): |
| 110 |
from gavo.protocols import tap |
| 111 |
tap.WORKER_SYSTEM.cleanupJobsTable(includeFailed=args.includeFailed, |
| 112 |
includeCompleted=args.includeCompleted, |
| 113 |
includeAll=args.includeAll, |
| 114 |
includeForgotten=args.includeForgotten) |
| 115 |
|
| 116 |
|
| 117 |
@exposedFunction([ |
| 118 |
Arg("jobId", help="id of the job to abort"), |
| 119 |
Arg("helpMsg", help="A helpful message to add to the abort message")], |
| 120 |
help="manually abort a TAP job and send some message to a user") |
| 121 |
def tapabort(querier, args): |
| 122 |
from gavo.protocols import tap |
| 123 |
|
| 124 |
tap.WORKER_SYSTEM.changeToPhase(args.jobId, uws.ERROR, |
| 125 |
"Job aborted by an administrator, probably because the query\n" |
| 126 |
" should be written differently to be less of a resource hog.\n" |
| 127 |
" Here's what the administrator had to say:\n\n"+args.helpMsg+ |
| 128 |
"\n\nIf you have further questions, just send a mail to "+ |
| 129 |
base.getMetaText(base.caches.getRD("//tap").getById("run"), |
| 130 |
"contact.email")) |
| 131 |
|
| 132 |
|
| 133 |
@exposedFunction([Arg(help="rd#table-id of the table containing the" |
| 134 |
" products that should get cached previews", dest="tableId"), |
| 135 |
Arg("-w", type=str, |
| 136 |
help="width to compute the preview for", dest="width", default="200"),], |
| 137 |
help="Precompute previews for the product interface columns in a table.") |
| 138 |
def cacheprev(querier, args): |
| 139 |
from gavo.protocols.products import PreviewCacheManager, getProductForRAccref |
| 140 |
from twisted.internet import reactor |
| 141 |
|
| 142 |
td = base.resolveId(None, args.tableId) |
| 143 |
rows = querier.queryToDicts( |
| 144 |
td.getSimpleQuery(["accref", "mime"])) |
| 145 |
|
| 146 |
def runNext(token): |
| 147 |
try: |
| 148 |
row = next(rows) |
| 149 |
res = PreviewCacheManager.getPreviewFor( |
| 150 |
getProductForRAccref(row["accref"])) |
| 151 |
|
| 152 |
if getattr(res, "result", None): # don't add a callback on a |
| 153 |
# fired deferred or you'll exhaust the stack |
| 154 |
reactor.callLater(0.1, runNext, "continue") |
| 155 |
else: |
| 156 |
res.addCallback(runNext) |
| 157 |
return res |
| 158 |
except StopIteration: |
| 159 |
pass |
| 160 |
except: |
| 161 |
import traceback |
| 162 |
traceback.print_exc() |
| 163 |
reactor.stop() |
| 164 |
return "" |
| 165 |
|
| 166 |
reactor.callLater(0, runNext, "startup") |
| 167 |
reactor.run() |
| 168 |
|
| 169 |
|
| 170 |
@exposedFunction([Arg(help="rd#table-id of the table to look at", |
| 171 |
dest="tableId")], |
| 172 |
help="Make suggestions for UCDs of columns not having one (based" |
| 173 |
" on their descriptions; this uses a GAVO web service).") |
| 174 |
def suggestucds(querier, args): |
| 175 |
from gavo import api |
| 176 |
from gavo import votable |
| 177 |
|
| 178 |
apiURL = "http://dc.zah.uni-heidelberg.de/ucds/ui/ui/api" |
| 179 |
|
| 180 |
def getMatches(description): |
| 181 |
res = utils.urlopenRemote(apiURL, data={"description": description}) |
| 182 |
data, metadata = votable.load(res) |
| 183 |
if metadata: |
| 184 |
return list(metadata.iterDicts(data)) |
| 185 |
else: |
| 186 |
return [] |
| 187 |
|
| 188 |
td = api.getReferencedElement(args.tableId, forceType=api.TableDef) |
| 189 |
for col in td: |
| 190 |
if (not col.ucd or col.ucd=="XXX") and col.description: |
| 191 |
try: |
| 192 |
res = [(row["score"], row["ucd"], row["is_valid"]) |
| 193 |
for row in getMatches(col.description)] |
| 194 |
res.sort() |
| 195 |
res.reverse() |
| 196 |
print(col.name) |
| 197 |
for score, ucd, is_valid in res: |
| 198 |
if is_valid: |
| 199 |
print(" ", ucd) |
| 200 |
else: |
| 201 |
print(f" (invalid: {ucd})") |
| 202 |
except IOError: |
| 203 |
# remote failure, guess it's "no matches" (TODO: distinguish) |
| 204 |
pass |
| 205 |
|
| 206 |
|
| 207 |
@exposedFunction([Arg(help="rd#table-id of the table of interest", |
| 208 |
dest="tableId")], |
| 209 |
help="Show the statements to create the indices on a table.") |
| 210 |
def indexStatements(querier, args): |
| 211 |
import re |
| 212 |
td = rscdef.getReferencedElement(args.tableId, forceType=rscdef.TableDef) |
| 213 |
for ind in td.indices: |
| 214 |
print("\n".join(re.sub(r"\s+", " ", s) for s in ind.iterCode())) |
| 215 |
|
| 216 |
|
| 217 |
@exposedFunction([Arg(help="rd#exec-id of the execute element to run (note:" |
| 218 |
" the title won't work, you have to give the thing an id to use adm exec).", |
| 219 |
dest="execId")], |
| 220 |
help="Execute the contents of an RD execute element. You must" |
| 221 |
" give that element an explicit id in order to make this work.") |
| 222 |
def execute(querier, args): |
| 223 |
from gavo.user import logui |
| 224 |
logui.LoggingUI(base.ui) |
| 225 |
execEl = rscdef.getReferencedElement(args.execId, rscdef.Execute) |
| 226 |
execEl.callable().join() |
| 227 |
|
| 228 |
|
| 229 |
@exposedFunction([Arg(help="Package resource path" |
| 230 |
" (like '/inputs/__system__/scs.rd); for system RDs, the special" |
| 231 |
" //rd-id syntax is supported.", |
| 232 |
dest="path")], |
| 233 |
help="Dump the source of a distribution file; this is useful when you want" |
| 234 |
" to override them and you are running DaCHS from a zipped egg") |
| 235 |
def dumpDF(querier, args): |
| 236 |
import pkg_resources |
| 237 |
if args.path.startswith("//"): |
| 238 |
args.path = "inputs/__system__"+args.path[1:]+".rd" |
| 239 |
try: |
| 240 |
with pkg_resources.resource_stream('gavo', "resources/"+args.path) as f: |
| 241 |
sys.stdout.buffer.write(f.read()) |
| 242 |
except FileNotFoundError: |
| 243 |
raise base.ReportableError("No such distribution file: %s\n"%args.path) |
| 244 |
|
| 245 |
|
| 246 |
@exposedFunction([Arg(help="XML file", dest="path", nargs='+')], |
| 247 |
help="Validate a file against built-in VO schemas and with built-in" |
| 248 |
" schema validator.") |
| 249 |
def xsdValidate(querier, args): |
| 250 |
from gavo.helpers import testtricks |
| 251 |
rtval = 0 |
| 252 |
|
| 253 |
for path in args.path: |
| 254 |
print(path, end=" -- ") |
| 255 |
try: |
| 256 |
with open(path, "rb") as f: |
| 257 |
msgs = testtricks.getXSDErrors(f.read()) |
| 258 |
except Exception as ex: |
| 259 |
msgs = [str(ex)] |
| 260 |
if not msgs: |
| 261 |
print("valid") |
| 262 |
else: |
| 263 |
print(msgs) |
| 264 |
rtval = 1 |
| 265 |
|
| 266 |
return rtval |
| 267 |
|
| 268 |
|
| 269 |
@exposedFunction([Arg(help="IVOID to mark as deleted", dest="ivoid")], |
| 270 |
help="Add a registry entry for a deleted record with IVOID. This" |
| 271 |
" should only be necessary if you accidentally manually removed" |
| 272 |
" records from your dc.resources table.") |
| 273 |
def makedelrec(querier, args): |
| 274 |
from gavo import registry |
| 275 |
|
| 276 |
authority, path = registry.parseIdentifier(args.ivoid) |
| 277 |
if authority not in registry.getManagedAuthorities(): |
| 278 |
raise base.ReportableError("You can only declare ivo ids from your" |
| 279 |
" own authority as deleted.") |
| 280 |
|
| 281 |
registry.makeDeletedRecord(args.ivoid, querier.connection) |
| 282 |
|
| 283 |
|
| 284 |
@exposedFunction([], help="Update the TAP_SCHEMA metadata for all" |
| 285 |
" RDs mentioned in TAP_SCHEMA (deprecated; use" |
| 286 |
" dachs imp //tap refresh instead)") |
| 287 |
def updateTAPSchema(querier, args): |
| 288 |
from gavo import rsc |
| 289 |
rsc.makeData( |
| 290 |
base.resolveCrossId("//tap#refresh"), |
| 291 |
connection=querier.connection) |
| 292 |
|
| 293 |
|
| 294 |
@exposedFunction([Arg(help="Password to hash", dest="pw")], |
| 295 |
help="Hash a password (typically for [web]adminpasswd)") |
| 296 |
def hashPasswd(querier, args): |
| 297 |
from gavo.protocols import creds |
| 298 |
print(creds.hashPassword(args.pw)) |
| 299 |
|
| 300 |
|
| 301 |
def _getConstantPrefix(path): |
| 302 |
"""returns the segments of path without a wildcard. |
| 303 |
""" |
| 304 |
segs = [] |
| 305 |
for seg in path.split("/"): |
| 306 |
if "*" in seg or "?" in seg: |
| 307 |
break |
| 308 |
segs.append(seg) |
| 309 |
return "/".join(segs) |
| 310 |
|
| 311 |
|
| 312 |
@exposedFunction([Arg(help="Id of a data element importing what you want to" |
| 313 |
" turn into a HiPS", dest="dataId"), |
| 314 |
Arg(help="Minimal Order to generate (0 is full sky, 4 is an area about" |
| 315 |
" 4 degrees in diameter)", dest="minOrder")], |
| 316 |
help="Write a Hipsgen parameter file to stdout") |
| 317 |
def hipsgen(querier, args): |
| 318 |
data = rscdef.getReferencedElement(args.dataId, |
| 319 |
forceType=rscdef.DataDescriptor) |
| 320 |
|
| 321 |
for pat in data.sources.patterns: |
| 322 |
print("in={}".format(_getConstantPrefix(pat))) |
| 323 |
|
| 324 |
print("minOrder={}".format(args.minOrder)) |
| 325 |
|
| 326 |
for m in data.rd.iterMeta("creator.name"): |
| 327 |
print("creator: {}".format(m.getContent("text"))) |
| 328 |
break |
| 329 |
|
| 330 |
# now find some publication we can piggyback on; we'll take the |
| 331 |
# first we find. |
| 332 |
from gavo.registry import publication |
| 333 |
for dest, rec in publication.RDRscRecGrammar(None).parse(data.rd): |
| 334 |
if dest=="resources": |
| 335 |
print("id={}".format(rec["ivoid"])) |
| 336 |
break |
| 337 |
|
| 338 |
print("status=public clonable") |
| 339 |
print("title={}".format(base.getMetaText(data, "title"))) |
| 340 |
print("out=hips") |
| 341 |
|
| 342 |
|
| 343 |
def _normalizeWhitespace(s): |
| 344 |
return re.sub(r"\s+", " ", s) |
| 345 |
|
| 346 |
|
| 347 |
def _getBoundsFromIntervals(intervals): |
| 348 |
return (min((i[0] for i in intervals), default=None), |
| 349 |
max((i[1] for i in intervals), default=None)) |
| 350 |
|
| 351 |
|
| 352 |
def _getHipsFillers(svc): |
| 353 |
"""returns a dictionary of HiPS propertes keys to values fillable |
| 354 |
from svcs. |
| 355 |
""" |
| 356 |
res = {} |
| 357 |
|
| 358 |
for metaKey, hipsKey in [ |
| 359 |
("description", "obs_description"), |
| 360 |
("creator.name", "hips_creator"), |
| 361 |
("source", "bib_reference"), |
| 362 |
("rights", "obs_copyright"), |
| 363 |
("coverage.waveband", "obs_regime"), |
| 364 |
("rights.rightsURI", "obs_copyright_url"),]: |
| 365 |
for m in svc.rd.iterMeta(metaKey): |
| 366 |
res[hipsKey] = _normalizeWhitespace(m.getContent( |
| 367 |
"text", macroPackage=svc.rd)) |
| 368 |
break |
| 369 |
|
| 370 |
res["hips_service_url"] = svc.getURL("hips") |
| 371 |
|
| 372 |
minTime, maxTime = _getBoundsFromIntervals(svc.rd.coverage.temporal) |
| 373 |
minE, maxE = _getBoundsFromIntervals(svc.rd.coverage.spectral) |
| 374 |
if minE: |
| 375 |
maxLambda = base.PLANCK_H*base.LIGHT_C/minE |
| 376 |
if maxE: |
| 377 |
minLambda = base.PLANCK_H*base.LIGHT_C/maxE |
| 378 |
|
| 379 |
for hipsKey, val in [ |
| 380 |
("t_min", minTime), |
| 381 |
("t_max", maxTime), |
| 382 |
("em_min", minLambda), |
| 383 |
("em_max", maxLambda)]: |
| 384 |
if val is not None: |
| 385 |
res[hipsKey] = val |
| 386 |
|
| 387 |
return res |
| 388 |
|
| 389 |
|
| 390 |
def _editProp(propLn, fillers): |
| 391 |
"""edits a hips properties template line with fillers if appropriate. |
| 392 |
|
| 393 |
What we edit is lines commented out with keys present in fillers. |
| 394 |
Unedited lines are returned stripped but otherwise unchanged. |
| 395 |
""" |
| 396 |
propLn = propLn.strip() |
| 397 |
mat = re.match(r"(#?)(\w+)\s+=\s+(.*)", propLn) |
| 398 |
if not mat: |
| 399 |
raise base.ReportableError(f"Invalid properties line: {propLn}") |
| 400 |
|
| 401 |
isTemplate, key, value = mat.groups() |
| 402 |
if isTemplate and key in fillers: |
| 403 |
propLn = "{:21s}= {}".format(key, fillers[key]) |
| 404 |
|
| 405 |
return propLn |
| 406 |
|
| 407 |
|
| 408 |
@exposedFunction([Arg(help="Reference to the HiPS-serving service", |
| 409 |
dest="svcId"), |
| 410 |
Arg("-d", "--hipsdir", help="Directory the HiPS is stored in", |
| 411 |
type=pathlib.Path, dest="hipsDir", default="hips")], |
| 412 |
help="Fill out the templated elements in hipsDir's properties file.") |
| 413 |
def hipsfill(querier, args): |
| 414 |
svc = rscdef.getReferencedElement(args.svcId, |
| 415 |
forceType=svcs.Service) |
| 416 |
fillers = _getHipsFillers(svc) |
| 417 |
|
| 418 |
propFile = args.hipsDir/"properties" |
| 419 |
newLines = [] |
| 420 |
with open(propFile, "r", encoding="utf-8") as f: |
| 421 |
for ln in f: |
| 422 |
newLines.append(_editProp(ln, fillers)) |
| 423 |
|
| 424 |
newContent = "\n".join(newLines).encode("utf-8")+b"\n" |
| 425 |
with open(propFile, "wb") as f: |
| 426 |
f.write(newContent) |
| 427 |
|
| 428 |
|
| 429 |
def main(): |
| 430 |
with base.AdhocQuerier(lambda: base.getDBConnection("feed")) as querier: |
| 431 |
args = makeCLIParser(globals()).parse_args() |
| 432 |
retval = args.subAction(querier, args) or 0 |
| 433 |
|
| 434 |
sys.exit(retval) |