Coverage for dak/show_deferred.py: 22%

174 statements  

« prev     ^ index     » next       coverage.py v7.6.0, created at 2026-11-21 08:51 +0000

1"""Overview of the DEFERRED queue, based on queue-report""" 

2 

3# Copyright (C) 2001, 2002, 2003, 2005, 2006 James Troup <james@nocrew.org> 

4# Copyright (C) 2008 Thomas Viehmann <tv@beamnet.de> 

5 

6# This program is free software; you can redistribute it and/or modify 

7# it under the terms of the GNU General Public License as published by 

8# the Free Software Foundation; either version 2 of the License, or 

9# (at your option) any later version. 

10 

11# This program is distributed in the hope that it will be useful, 

12# but WITHOUT ANY WARRANTY; without even the implied warranty of 

13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

14# GNU General Public License for more details. 

15 

16# You should have received a copy of the GNU General Public License 

17# along with this program; if not, write to the Free Software 

18# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 

19 

20################################################################################ 

21 

22import errno 

23import html 

24import os 

25import re 

26import stat 

27import sys 

28import time 

29 

30import apt_pkg 

31import rrdtool 

32 

33from daklib import utils 

34from daklib.dbconn import DBConn, get_active_keyring_paths, get_suites_source_in 

35from daklib.gpg import SignedFile 

36from daklib.regexes import re_file_safe 

37from debian import deb822 

38 

39Cnf: apt_pkg.Configuration 

40Options: apt_pkg.Configuration 

41 

42################################################################################ 

43 

44 

45def header(): 

46 return """<!DOCTYPE html> 

47 <html lang="en"><head><meta charset="utf-8"> 

48 <title>Deferred uploads to Debian</title> 

49 <link rel="stylesheet" href="style.css"> 

50 <link rel="shortcut icon" href="https://www.debian.org/favicon.ico"> 

51 </head> 

52 <body> 

53 <div align="center"> 

54 <a href="https://www.debian.org/"> 

55 <img src="https://www.debian.org/logos/openlogo-nd-50.png" border="0" hspace="0" vspace="0" alt=""></a> 

56 <a href="https://www.debian.org/"> 

57 <img src="https://www.debian.org/Pics/debian.png" border="0" hspace="0" vspace="0" alt="Debian Project"></a> 

58 </div> 

59 <br> 

60 <table class="reddy" width="100%"> 

61 <tr> 

62 <td class="reddy"> 

63 <img src="https://www.debian.org/Pics/red-upperleft.png" align="left" border="0" hspace="0" vspace="0" 

64 alt="" width="15" height="16"></td> 

65 <td rowspan="2" class="reddy">Deferred uploads to Debian</td> 

66 <td class="reddy"> 

67 <img src="https://www.debian.org/Pics/red-upperright.png" align="right" border="0" hspace="0" vspace="0" 

68 alt="" width="16" height="16"></td> 

69 </tr> 

70 <tr> 

71 <td class="reddy"> 

72 <img src="https://www.debian.org/Pics/red-lowerleft.png" align="left" border="0" hspace="0" vspace="0" 

73 alt="" width="16" height="16"></td> 

74 <td class="reddy"> 

75 <img src="https://www.debian.org/Pics/red-lowerright.png" align="right" border="0" hspace="0" vspace="0" 

76 alt="" width="15" height="16"></td> 

77 </tr> 

78 </table> 

79 """ 

80 

81 

82def footer(): 

83 res = '<p class="validate">Timestamp: %s (UTC)</p>' % ( 

84 time.strftime("%d.%m.%Y / %H:%M:%S", time.gmtime()) 

85 ) 

86 res += '<p class="timestamp">There are <a href="/stat.html">graphs about the queues</a> available.</p>' 

87 res += "</body></html>" 

88 return res 

89 

90 

91def table_header(): 

92 return """<h1>Deferred uploads</h1> 

93 <center><table border="0"> 

94 <tr> 

95 <th align="center">Change</th> 

96 <th align="center">Time remaining</th> 

97 <th align="center">Uploader</th> 

98 <th align="center">Closes</th> 

99 </tr> 

100 """ 

101 

102 

103def table_footer(): 

104 return '</table><br><p>non-NEW uploads are <a href="/deferred/">available</a> (<a href="/deferred/status">machine readable version</a>), see the <a href="https://www.debian.org/doc/manuals/developers-reference/ch05.en.html#delayed-incoming">Developer\'s reference</a> for more information on the DELAYED queue.</p></center><br>\n' 

105 

106 

107def table_row(changesname, delay, changed_by, closes, fingerprint): 

108 res = "<tr>" 

109 res += (2 * '<td valign="top">%s</td>') % tuple( 

110 html.escape(x, quote=False) for x in (changesname, delay) 

111 ) 

112 res += ( 

113 '<td valign="top">%s<br><span class="deferredfp">Fingerprint: %s</span></td>' 

114 % (html.escape(changed_by or "Unknown", quote=False), fingerprint) 

115 ) 

116 res += '<td valign="top">%s</td>' % "".join( 

117 [ 

118 '<a href="https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=%s">#%s</a><br>' 

119 % (close, close) 

120 for close in closes 

121 ] 

122 ) 

123 res += "</tr>\n" 

124 return res 

125 

126 

127def update_graph_database(rrd_dir, *counts): 

128 if not rrd_dir: 

129 return 

130 

131 rrd_file = os.path.join(rrd_dir, "deferred.rrd") 

132 update = [rrd_file, "N:" + ":".join(str(count) for count in counts)] 

133 

134 try: 

135 rrdtool.update(*update) 

136 except rrdtool.error: 

137 create = ( 

138 [rrd_file] 

139 + """ 

140--step 

141300 

142--start 

1430 

144DS:day0:GAUGE:7200:0:1000 

145DS:day1:GAUGE:7200:0:1000 

146DS:day2:GAUGE:7200:0:1000 

147DS:day3:GAUGE:7200:0:1000 

148DS:day4:GAUGE:7200:0:1000 

149DS:day5:GAUGE:7200:0:1000 

150DS:day6:GAUGE:7200:0:1000 

151DS:day7:GAUGE:7200:0:1000 

152DS:day8:GAUGE:7200:0:1000 

153DS:day9:GAUGE:7200:0:1000 

154DS:day10:GAUGE:7200:0:1000 

155DS:day11:GAUGE:7200:0:1000 

156DS:day12:GAUGE:7200:0:1000 

157DS:day13:GAUGE:7200:0:1000 

158DS:day14:GAUGE:7200:0:1000 

159DS:day15:GAUGE:7200:0:1000 

160RRA:AVERAGE:0.5:1:599 

161RRA:AVERAGE:0.5:6:700 

162RRA:AVERAGE:0.5:24:775 

163RRA:AVERAGE:0.5:288:795 

164RRA:MIN:0.5:1:600 

165RRA:MIN:0.5:6:700 

166RRA:MIN:0.5:24:775 

167RRA:MIN:0.5:288:795 

168RRA:MAX:0.5:1:600 

169RRA:MAX:0.5:6:700 

170RRA:MAX:0.5:24:775 

171RRA:MAX:0.5:288:795 

172""".strip().split( 

173 "\n" 

174 ) 

175 ) 

176 try: 

177 rrdtool.create(*create) 

178 rrdtool.update(*update) 

179 except rrdtool.error as e: 

180 print( 

181 "warning: queue_report: rrdtool error, skipping %s.rrd: %s" % (type, e) 

182 ) 

183 except NameError: 

184 pass 

185 

186 

187def is_linkable_name(name: str) -> bool: 

188 """Check a name from the Files field of a deferred .changes 

189 

190 The name is joined to the deferred directory and to the link 

191 directory, so only plain file names are allowed. We don't link 

192 .changes because we don't want other people to upload it with the 

193 existing signature, and `status` is written by list_uploads(). 

194 """ 

195 return ( 

196 re_file_safe.fullmatch(name) is not None 

197 and not name.endswith(".changes") 

198 and name != "status" 

199 ) 

200 

201 

202def link_deferred_file(qfn: str, lfn: str) -> None: 

203 """Make `qfn` world-readable and create the symlink `lfn` to it 

204 

205 Nothing is done unless `qfn` is a regular file. It is opened without 

206 following symlinks and its mode is changed through the descriptor. 

207 """ 

208 try: 

209 # O_NONBLOCK so that opening a FIFO does not wait for a writer 

210 fd = os.open(qfn, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) 

211 except FileNotFoundError: 

212 return 

213 except OSError as e: 

214 # O_NOFOLLOW gives ELOOP for a symlink 

215 if e.errno != errno.ELOOP: 

216 raise 

217 utils.warn(f"{qfn} is a symlink, not linking it") 

218 return 

219 try: 

220 if not stat.S_ISREG(os.fstat(fd).st_mode): 

221 utils.warn(f"{qfn} is not a regular file, not linking it") 

222 return 

223 os.fchmod(fd, 0o644) 

224 finally: 

225 os.close(fd) 

226 os.symlink(qfn, lfn) 

227 

228 

229def get_upload_data(changesfn): 

230 with open(changesfn) as fd: 

231 achanges = deb822.Changes(fd) 

232 changesname = os.path.basename(changesfn) 

233 delay = os.path.basename(os.path.dirname(changesfn)) 

234 m = re.match(r"([0-9]+)-day", delay) 

235 if m: 

236 delaydays = int(m.group(1)) 

237 remainingtime = (delaydays > 0) * max( 

238 0, 24 * 60 * 60 + os.stat(changesfn).st_mtime - time.time() 

239 ) 

240 delay = "%d days %02d:%02d" % ( 

241 max(delaydays - 1, 0), 

242 int(remainingtime / 3600), 

243 int(remainingtime / 60) % 60, 

244 ) 

245 else: 

246 delaydays = 0 

247 remainingtime = 0 

248 

249 uploader = achanges.get("changed-by") 

250 if uploader is not None: 

251 uploader = re.sub(r"^\s*(\S.*)\s+<.*>", r"\1", uploader) 

252 

253 with open(changesfn, "rb") as f: 

254 fingerprint = SignedFile( 

255 f.read(), keyrings=get_active_keyring_paths(), require_signature=False 

256 ).fingerprint 

257 if "Show-Deferred::LinkPath" in Cnf: 

258 isnew = False 

259 suites = get_suites_source_in(achanges["source"]) 

260 if "unstable" not in suites and "experimental" not in suites: 

261 isnew = True 

262 

263 if not isnew: 

264 names = [x["name"] for x in achanges["files"]] 

265 if not all(is_linkable_name(name) for name in names): 

266 utils.warn(f"{changesfn}: unsafe name in Files, not linking any files") 

267 else: 

268 for afn in names: 

269 lfn = os.path.join(Cnf["Show-Deferred::LinkPath"], afn) 

270 qfn = os.path.join(os.path.dirname(changesfn), afn) 

271 if os.path.islink(lfn): 

272 os.unlink(lfn) 

273 link_deferred_file(qfn, lfn) 

274 return ( 

275 max(delaydays - 1, 0) * 24 * 60 * 60 + remainingtime, 

276 changesname, 

277 delay, 

278 uploader, 

279 achanges.get("closes", "").split(), 

280 fingerprint, 

281 achanges, 

282 delaydays, 

283 ) 

284 

285 

286def list_uploads(filelist, rrd_dir): 

287 uploads = sorted(get_upload_data(x) for x in filelist) 

288 # print the summary page 

289 print(header()) 

290 if uploads: 

291 print(table_header()) 

292 print("".join(table_row(*x[1:6]) for x in uploads)) 

293 print(table_footer()) 

294 else: 

295 print("<h1>Currently no deferred uploads to Debian</h1>") 

296 print(footer()) 

297 # machine readable summary 

298 if "Show-Deferred::LinkPath" in Cnf: 

299 fn = os.path.join(Cnf["Show-Deferred::LinkPath"], ".status.tmp") 

300 f = open(fn, "w") 

301 try: 

302 counts = [0] * 16 

303 for u in uploads: 

304 counts[u[7]] += 1 

305 print("Changes-file: %s" % u[1], file=f) 

306 fields = """Location: DEFERRED 

307Delayed-Until: %s 

308Delay-Remaining: %s 

309Fingerprint: %s""" % ( 

310 time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(time.time() + u[0])), 

311 u[2], 

312 u[5], 

313 ) 

314 print(fields, file=f) 

315 encoded = u[6].dump() 

316 print(encoded.rstrip(), file=f) 

317 open(os.path.join(Cnf["Show-Deferred::LinkPath"], u[1]), "w").write( 

318 encoded + fields + "\n" 

319 ) 

320 print(file=f) 

321 f.close() 

322 os.rename( 

323 os.path.join(Cnf["Show-Deferred::LinkPath"], ".status.tmp"), 

324 os.path.join(Cnf["Show-Deferred::LinkPath"], "status"), 

325 ) 

326 update_graph_database(rrd_dir, *counts) 

327 except: 

328 os.unlink(fn) 

329 raise 

330 

331 

332def usage(exit_code=0): 

333 if exit_code: 333 ↛ 334line 333 didn't jump to line 334 because the condition on line 333 was never true

334 f = sys.stderr 

335 else: 

336 f = sys.stdout 

337 print( 

338 """Usage: dak show-deferred 

339 -h, --help show this help and exit. 

340 -p, --link-path [path] override output directory. 

341 -d, --deferred-queue [path] path to the deferred queue 

342 -r, --rrd=key Directory where rrd files to be updated are stored 

343 """, 

344 file=f, 

345 ) 

346 sys.exit(exit_code) 

347 

348 

349def init(): 

350 global Cnf, Options 

351 Cnf = utils.get_conf() 

352 Arguments = [ 

353 ("h", "help", "Show-Deferred::Options::Help"), 

354 ("p", "link-path", "Show-Deferred::LinkPath", "HasArg"), 

355 ("d", "deferred-queue", "Show-Deferred::DeferredQueue", "HasArg"), 

356 ("r", "rrd", "Show-Deferred::Options::Rrd", "HasArg"), 

357 ] 

358 args = apt_pkg.parse_commandline(Cnf, Arguments, sys.argv) # type: ignore[attr-defined] 

359 for i in ["help"]: 

360 key = "Show-Deferred::Options::%s" % i 

361 if key not in Cnf: 361 ↛ 362line 361 didn't jump to line 362 because the condition on line 361 was never true

362 Cnf[key] = "" # type: ignore[index] 

363 for i, j in [("DeferredQueue", "--deferred-queue")]: 

364 key = "Show-Deferred::%s" % i 

365 if key not in Cnf: 365 ↛ 363line 365 didn't jump to line 363 because the condition on line 365 was always true

366 print( 

367 """%s is mandatory. 

368 set via config file or command-line option %s""" 

369 % (key, j), 

370 file=sys.stderr, 

371 ) 

372 

373 Options = Cnf.subtree("Show-Deferred::Options") # type: ignore[attr-defined] 

374 if Options["help"]: 374 ↛ 378line 374 didn't jump to line 378 because the condition on line 374 was always true

375 usage() 

376 

377 # Initialise database connection 

378 DBConn() 

379 

380 return args 

381 

382 

383def main(): 

384 args = init() 

385 if len(args) != 0: 

386 usage(1) 

387 

388 if "Show-Deferred::Options::Rrd" in Cnf: 

389 rrd_dir = Cnf["Show-Deferred::Options::Rrd"] 

390 elif "Dir::Rrd" in Cnf: 

391 rrd_dir = Cnf["Dir::Rrd"] 

392 else: 

393 rrd_dir = None 

394 

395 filelist: list[str] = [] 

396 for r, d, f in os.walk(Cnf["Show-Deferred::DeferredQueue"]): 

397 filelist.extend(os.path.join(r, x) for x in f if x.endswith(".changes")) 

398 list_uploads(filelist, rrd_dir) 

399 

400 available_changes = {os.path.basename(x) for x in filelist} 

401 if "Show-Deferred::LinkPath" in Cnf: 

402 # remove dead links 

403 for r, d, f in os.walk(Cnf["Show-Deferred::LinkPath"]): 

404 for af in f: 

405 afp = os.path.join(r, af) 

406 if not os.path.exists(afp) or ( 

407 af.endswith(".changes") and af not in available_changes 

408 ): 

409 os.unlink(afp)