Debian Codegraph @

gavo/svcs/uploadcores.py

raw
1 """
2 Cores to alter the DB state from the Web.
3
4 Honestly: I doubt this type of http upload is a good idea in general.
5 If given the choice, I'd go for uploading through rsync and using a timed
6 job (or perhaps a trigger) any day.
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 import grp
16 import os
17
18 from gavo import base
19 from gavo import rsc
20 from gavo.svcs import core
21
22
23 MS = base.makeStruct
24
25 uploadOutputDef = """<outputTable>
26 <column name="nAffected" type="integer"
27 tablehead="Number touched" required="True"/>
28 </outputTable>"""
29
30
31 class UploadCore(core.Core):
32 """A core handling uploads of files to the database.
33
34 It allows users to upload individual files into a special staging
35 area (taken from the stagingDir property of the destination data descriptor)
36 and causes these files to be parsed using destDD. Note that destDD
37 *must* have ``updating="True"`` for this to work properly (it will otherwise
38 drop the table on each upload). If uploads are the only way updates
39 into the table occur, source management is not necessary for these, though.
40
41 You can tell UploadCores to either insert or update the incoming data using
42 the "mode" input key.
43 """
44 name_ = "uploadCore"
45
46 _destDD = base.ReferenceAttribute("destDD", default=base.Undefined,
47 description="Reference to the data we are uploading into. The"
48 " destination must be an updating data descriptor.")
49
50 inputTableXML = """
51 <inputTable id="inFields">
52 <inputKey name="File" type="file" required="True"
53 tablehead="Source to upload"/>
54 <inputKey name="Mode" type="text" tablehead="Upload mode"
55 required="True" multiplicity="forced-single">
56 <values default="i">
57 <option title="Insert">i</option>
58 <option title="Update">u</option>
59 </values>
60 </inputKey>
61 </inputTable>
62 """
63 outputTableXML = uploadOutputDef
64
65 def _fixPermissions(self, fName):
66 """tries to chmod the newly created file to 0664 and change the group
67 to config.gavoGroup.
68 """
69 try:
70 os.chmod(fName, 0o664)
71 os.chown(fName, -1, grp.getgrnam(base.getConfig("gavoGroup"))[2])
72 except (KeyError, os.error): # let someone else worry about it
73 pass
74
75 def _writeFile(self, srcFile, fName):
76 """writes the contents of srcFile to fName in destDD's staging dir.
77 """
78 try:
79 targetDir = os.path.join(self.rd.resdir,
80 self.destDD.getProperty("stagingDir"))
81 except KeyError:
82 raise base.ui.logOldExc(base.ValidationError("Uploading is only"
83 " supported for data having a staging directory.", "File"))
84 if not os.path.exists(targetDir):
85 raise base.ValidationError("Staging directory does not exist.",
86 "File")
87 targetFName = fName.split("/")[-1]
88 if not targetFName:
89 raise base.ValidationError("Bad file name", "File")
90 targetPath = os.path.join(targetDir, targetFName)
91
92 with open(targetPath, "wb") as f:
93 f.write(srcFile.read())
94
95 try:
96 self._fixPermissions(targetPath)
97 except os.error:
98 # Nothing we can do, and it may not even hurt
99 pass
100 return targetPath
101
102 def _importData(self, sourcePath, mode):
103 """parses the input file at sourcePath and writes the result to the DB.
104 """
105 base.ui.notifyInfo("Web upload ingesting %s in %s mode"%(sourcePath, mode))
106 try:
107 parseOptions = rsc.getParseOptions(
108 validateRows=True,
109 doTableUpdates=mode=="u")
110 with base.getWritableAdminConn() as conn:
111 res = rsc.makeData(self.destDD, parseOptions=parseOptions,
112 forceSource=sourcePath, connection=conn)
113 except Exception as msg:
114 raise base.ui.logOldExc(base.ValidationError("Cannot enter %s in"
115 " database: %s"%(os.path.basename(sourcePath), str(msg)), "File"))
116 return res.nAffected
117
118 def _saveData(self, srcFile, fName, mode):
119 """saves data read from srcFile to both fNames staging dir and to the
120 database table(s) described by destDD.
121
122 mode can be "u" (for update) or "i" for insert.
123
124 If parsing or the database operations fail, the saved file will be removed.
125 Errors will usually be base.ValidationErrors on either File or Mode.
126
127 The function returns the number of items modified.
128 """
129 targetPath = self._writeFile(srcFile, fName)
130 try:
131 nAffected = self._importData(targetPath, mode)
132 except:
133 os.unlink(targetPath)
134 raise
135 return nAffected
136
137 def run(self, service, inputTable, queryMeta):
138 totalAffected = 0
139 fName, srcFile = inputTable.getParam("File")
140 mode = inputTable.getParam("Mode")
141 totalAffected += self._saveData(srcFile, fName, mode)
142 return rsc.TableForDef(self.outputTable,
143 rows=[{"nAffected": totalAffected}])