Branch data Line data Source code
1 : : /* Debuginfo-over-http server.
2 : : Copyright (C) 2019-2024 Red Hat, Inc.
3 : : Copyright (C) 2021, 2022 Mark J. Wielaard <mark@klomp.org>
4 : : This file is part of elfutils.
5 : :
6 : : This file 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 3 of the License, or
9 : : (at your option) any later version.
10 : :
11 : : elfutils is distributed in the hope that it will be useful, but
12 : : 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, see <http://www.gnu.org/licenses/>. */
18 : :
19 : :
20 : : /* cargo-cult from libdwfl linux-kernel-modules.c */
21 : : /* In case we have a bad fts we include this before config.h because it
22 : : can't handle _FILE_OFFSET_BITS.
23 : : Everything we need here is fine if its declarations just come first.
24 : : Also, include sys/types.h before fts. On some systems fts.h is not self
25 : : contained. */
26 : : #ifdef BAD_FTS
27 : : #include <sys/types.h>
28 : : #include <fts.h>
29 : : #endif
30 : :
31 : : #ifdef HAVE_CONFIG_H
32 : : #include "config.h"
33 : : #endif
34 : :
35 : : // #define _GNU_SOURCE
36 : : #ifdef HAVE_SCHED_H
37 : : extern "C" {
38 : : #include <sched.h>
39 : : }
40 : : #endif
41 : : #ifdef HAVE_SYS_RESOURCE_H
42 : : extern "C" {
43 : : #include <sys/resource.h>
44 : : }
45 : : #endif
46 : :
47 : : #ifdef HAVE_EXECINFO_H
48 : : extern "C" {
49 : : #include <execinfo.h>
50 : : }
51 : : #endif
52 : :
53 : : #include "debuginfod.h"
54 : : #include <dwarf.h>
55 : :
56 : : #include <argp.h>
57 : : #ifdef __GNUC__
58 : : #undef __attribute__ /* glibc bug - rhbz 1763325 */
59 : : #endif
60 : :
61 : : #include <unistd.h>
62 : : #include <stdlib.h>
63 : : #include <locale.h>
64 : : #include <pthread.h>
65 : : #include <signal.h>
66 : : #include <sys/stat.h>
67 : : #include <sys/time.h>
68 : : #include <sys/vfs.h>
69 : : #include <unistd.h>
70 : : #include <fcntl.h>
71 : : #include <netdb.h>
72 : : #include <math.h>
73 : : #include <float.h>
74 : :
75 : :
76 : : /* If fts.h is included before config.h, its indirect inclusions may not
77 : : give us the right LFS aliases of these functions, so map them manually. */
78 : : #ifdef BAD_FTS
79 : : #ifdef _FILE_OFFSET_BITS
80 : : #define open open64
81 : : #define fopen fopen64
82 : : #endif
83 : : #else
84 : : #include <sys/types.h>
85 : : #include <fts.h>
86 : : #endif
87 : :
88 : : #include <cstring>
89 : : #include <vector>
90 : : #include <set>
91 : : #include <unordered_set>
92 : : #include <map>
93 : : #include <string>
94 : : #include <iostream>
95 : : #include <iomanip>
96 : : #include <ostream>
97 : : #include <sstream>
98 : : #include <mutex>
99 : : #include <deque>
100 : : #include <condition_variable>
101 : : #include <exception>
102 : : #include <thread>
103 : : // #include <regex> // on rhel7 gcc 4.8, not competent
104 : : #include <regex.h>
105 : : // #include <algorithm>
106 : : using namespace std;
107 : :
108 : : #include <gelf.h>
109 : : #include <libdwelf.h>
110 : :
111 : : #include <microhttpd.h>
112 : :
113 : : #if MHD_VERSION >= 0x00097002
114 : : // libmicrohttpd 0.9.71 broke API
115 : : #define MHD_RESULT enum MHD_Result
116 : : #else
117 : : #define MHD_RESULT int
118 : : #endif
119 : :
120 : : #include <curl/curl.h>
121 : : #include <archive.h>
122 : : #include <archive_entry.h>
123 : : #include <sqlite3.h>
124 : :
125 : : #ifdef __linux__
126 : : #include <sys/syscall.h>
127 : : #endif
128 : :
129 : : #ifdef __linux__
130 : : #define tid() syscall(SYS_gettid)
131 : : #else
132 : : #define tid() pthread_self()
133 : : #endif
134 : :
135 : : extern "C" {
136 : : #include "printversion.h"
137 : : #include "system.h"
138 : : }
139 : :
140 : :
141 : : inline bool
142 : 2022 : string_endswith(const string& haystack, const string& needle)
143 : : {
144 [ + # ]: 2022 : return (haystack.size() >= needle.size() &&
145 : 2024 : equal(haystack.end()-needle.size(), haystack.end(),
146 : 2022 : needle.begin()));
147 : : }
148 : :
149 : :
150 : : // Roll this identifier for every sqlite schema incompatibility.
151 : : #define BUILDIDS "buildids10"
152 : :
153 : : #if SQLITE_VERSION_NUMBER >= 3008000
154 : : #define WITHOUT_ROWID "without rowid"
155 : : #else
156 : : #define WITHOUT_ROWID ""
157 : : #endif
158 : :
159 : : static const char DEBUGINFOD_SQLITE_DDL[] =
160 : : "pragma foreign_keys = on;\n"
161 : : "pragma synchronous = 0;\n" // disable fsync()s - this cache is disposable across a machine crash
162 : : "pragma journal_mode = wal;\n" // https://sqlite.org/wal.html
163 : : "pragma wal_checkpoint = truncate;\n" // clean out any preexisting wal file
164 : : "pragma journal_size_limit = 0;\n" // limit steady state file (between grooming, which also =truncate's)
165 : : "pragma auto_vacuum = incremental;\n" // https://sqlite.org/pragma.html
166 : : "pragma busy_timeout = 1000;\n" // https://sqlite.org/pragma.html
167 : : // NB: all these are overridable with -D option
168 : :
169 : : // Normalization table for interning file names
170 : : "create table if not exists " BUILDIDS "_fileparts (\n"
171 : : " id integer primary key not null,\n"
172 : : " name text unique not null\n"
173 : : " );\n"
174 : : "create table if not exists " BUILDIDS "_files (\n"
175 : : " id integer primary key not null,\n"
176 : : " dirname integer not null,\n"
177 : : " basename integer not null,\n"
178 : : " unique (dirname, basename),\n"
179 : : " foreign key (dirname) references " BUILDIDS "_fileparts(id) on delete cascade,\n"
180 : : " foreign key (basename) references " BUILDIDS "_fileparts(id) on delete cascade\n"
181 : : " );\n"
182 : : "create view if not exists " BUILDIDS "_files_v as\n" // a
183 : : " select f.id, n1.name || '/' || n2.name as name\n"
184 : : " from " BUILDIDS "_files f, " BUILDIDS "_fileparts n1, " BUILDIDS "_fileparts n2\n"
185 : : " where f.dirname = n1.id and f.basename = n2.id;\n"
186 : :
187 : : // Normalization table for interning buildids
188 : : "create table if not exists " BUILDIDS "_buildids (\n"
189 : : " id integer primary key not null,\n"
190 : : " hex text unique not null);\n"
191 : : // Track the completion of scanning of a given file & sourcetype at given time
192 : : "create table if not exists " BUILDIDS "_file_mtime_scanned (\n"
193 : : " mtime integer not null,\n"
194 : : " file integer not null,\n"
195 : : " size integer not null,\n" // in bytes
196 : : " sourcetype text(1) not null\n"
197 : : " check (sourcetype IN ('F', 'R')),\n"
198 : : " foreign key (file) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
199 : : " primary key (file, mtime, sourcetype)\n"
200 : : " ) " WITHOUT_ROWID ";\n"
201 : : "create table if not exists " BUILDIDS "_f_de (\n"
202 : : " buildid integer not null,\n"
203 : : " debuginfo_p integer not null,\n"
204 : : " executable_p integer not null,\n"
205 : : " file integer not null,\n"
206 : : " mtime integer not null,\n"
207 : : " foreign key (file) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
208 : : " foreign key (buildid) references " BUILDIDS "_buildids(id) on update cascade on delete cascade,\n"
209 : : " primary key (buildid, file, mtime)\n"
210 : : " ) " WITHOUT_ROWID ";\n"
211 : : // Index for faster delete by file identifier
212 : : "create index if not exists " BUILDIDS "_f_de_idx on " BUILDIDS "_f_de (file, mtime);\n"
213 : : "create table if not exists " BUILDIDS "_f_s (\n"
214 : : " buildid integer not null,\n"
215 : : " artifactsrc integer not null,\n"
216 : : " file integer not null,\n" // NB: not necessarily entered into _mtime_scanned
217 : : " mtime integer not null,\n"
218 : : " foreign key (file) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
219 : : " foreign key (artifactsrc) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
220 : : " foreign key (buildid) references " BUILDIDS "_buildids(id) on update cascade on delete cascade,\n"
221 : : " primary key (buildid, artifactsrc, file, mtime)\n"
222 : : " ) " WITHOUT_ROWID ";\n"
223 : : "create table if not exists " BUILDIDS "_r_de (\n"
224 : : " buildid integer not null,\n"
225 : : " debuginfo_p integer not null,\n"
226 : : " executable_p integer not null,\n"
227 : : " file integer not null,\n"
228 : : " mtime integer not null,\n"
229 : : " content integer not null,\n"
230 : : " foreign key (file) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
231 : : " foreign key (content) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
232 : : " foreign key (buildid) references " BUILDIDS "_buildids(id) on update cascade on delete cascade,\n"
233 : : " primary key (buildid, debuginfo_p, executable_p, file, content, mtime)\n"
234 : : " ) " WITHOUT_ROWID ";\n"
235 : : // Index for faster delete by archive file identifier
236 : : "create index if not exists " BUILDIDS "_r_de_idx on " BUILDIDS "_r_de (file, mtime);\n"
237 : : "create table if not exists " BUILDIDS "_r_sref (\n" // outgoing dwarf sourcefile references from rpm
238 : : " buildid integer not null,\n"
239 : : " artifactsrc integer not null,\n"
240 : : " foreign key (artifactsrc) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
241 : : " foreign key (buildid) references " BUILDIDS "_buildids(id) on update cascade on delete cascade,\n"
242 : : " primary key (buildid, artifactsrc)\n"
243 : : " ) " WITHOUT_ROWID ";\n"
244 : : "create table if not exists " BUILDIDS "_r_sdef (\n" // rpm contents that may satisfy sref
245 : : " file integer not null,\n"
246 : : " mtime integer not null,\n"
247 : : " content integer not null,\n"
248 : : " foreign key (file) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
249 : : " foreign key (content) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
250 : : " primary key (content, file, mtime)\n"
251 : : " ) " WITHOUT_ROWID ";\n"
252 : : // create views to glue together some of the above tables, for webapi D queries
253 : : "create view if not exists " BUILDIDS "_query_d as \n"
254 : : "select\n"
255 : : " b.hex as buildid, n.mtime, 'F' as sourcetype, f0.name as source0, n.mtime as mtime, null as source1\n"
256 : : " from " BUILDIDS "_buildids b, " BUILDIDS "_files_v f0, " BUILDIDS "_f_de n\n"
257 : : " where b.id = n.buildid and f0.id = n.file and n.debuginfo_p = 1\n"
258 : : "union all select\n"
259 : : " b.hex as buildid, n.mtime, 'R' as sourcetype, f0.name as source0, n.mtime as mtime, f1.name as source1\n"
260 : : " from " BUILDIDS "_buildids b, " BUILDIDS "_files_v f0, " BUILDIDS "_files_v f1, " BUILDIDS "_r_de n\n"
261 : : " where b.id = n.buildid and f0.id = n.file and f1.id = n.content and n.debuginfo_p = 1\n"
262 : : ";"
263 : : // ... and for E queries
264 : : "create view if not exists " BUILDIDS "_query_e as \n"
265 : : "select\n"
266 : : " b.hex as buildid, n.mtime, 'F' as sourcetype, f0.name as source0, n.mtime as mtime, null as source1\n"
267 : : " from " BUILDIDS "_buildids b, " BUILDIDS "_files_v f0, " BUILDIDS "_f_de n\n"
268 : : " where b.id = n.buildid and f0.id = n.file and n.executable_p = 1\n"
269 : : "union all select\n"
270 : : " b.hex as buildid, n.mtime, 'R' as sourcetype, f0.name as source0, n.mtime as mtime, f1.name as source1\n"
271 : : " from " BUILDIDS "_buildids b, " BUILDIDS "_files_v f0, " BUILDIDS "_files_v f1, " BUILDIDS "_r_de n\n"
272 : : " where b.id = n.buildid and f0.id = n.file and f1.id = n.content and n.executable_p = 1\n"
273 : : ";"
274 : : // ... and for S queries
275 : : "create view if not exists " BUILDIDS "_query_s as \n"
276 : : "select\n"
277 : : " b.hex as buildid, fs.name as artifactsrc, 'F' as sourcetype, f0.name as source0, n.mtime as mtime, null as source1, null as source0ref\n"
278 : : " from " BUILDIDS "_buildids b, " BUILDIDS "_files_v f0, " BUILDIDS "_files_v fs, " BUILDIDS "_f_s n\n"
279 : : " where b.id = n.buildid and f0.id = n.file and fs.id = n.artifactsrc\n"
280 : : "union all select\n"
281 : : " b.hex as buildid, f1.name as artifactsrc, 'R' as sourcetype, f0.name as source0, sd.mtime as mtime, f1.name as source1, fsref.name as source0ref\n"
282 : : " from " BUILDIDS "_buildids b, " BUILDIDS "_files_v f0, " BUILDIDS "_files_v f1, " BUILDIDS "_files_v fsref, "
283 : : " " BUILDIDS "_r_sdef sd, " BUILDIDS "_r_sref sr, " BUILDIDS "_r_de sde\n"
284 : : " where b.id = sr.buildid and f0.id = sd.file and fsref.id = sde.file and f1.id = sd.content\n"
285 : : " and sr.artifactsrc = sd.content and sde.buildid = sr.buildid\n"
286 : : ";"
287 : : // and for startup overview counts
288 : : "drop view if exists " BUILDIDS "_stats;\n"
289 : : "create view if not exists " BUILDIDS "_stats as\n"
290 : : " select 'file d/e' as label,count(*) as quantity from " BUILDIDS "_f_de\n"
291 : : "union all select 'file s',count(*) from " BUILDIDS "_f_s\n"
292 : : "union all select 'archive d/e',count(*) from " BUILDIDS "_r_de\n"
293 : : "union all select 'archive sref',count(*) from " BUILDIDS "_r_sref\n"
294 : : "union all select 'archive sdef',count(*) from " BUILDIDS "_r_sdef\n"
295 : : "union all select 'buildids',count(*) from " BUILDIDS "_buildids\n"
296 : : "union all select 'filenames',count(*) from " BUILDIDS "_files\n"
297 : : "union all select 'fileparts',count(*) from " BUILDIDS "_fileparts\n"
298 : : "union all select 'files scanned (#)',count(*) from " BUILDIDS "_file_mtime_scanned\n"
299 : : "union all select 'files scanned (mb)',coalesce(sum(size)/1024/1024,0) from " BUILDIDS "_file_mtime_scanned\n"
300 : : #if SQLITE_VERSION_NUMBER >= 3016000
301 : : "union all select 'index db size (mb)',page_count*page_size/1024/1024 as size FROM pragma_page_count(), pragma_page_size()\n"
302 : : #endif
303 : : ";\n"
304 : :
305 : : // schema change history & garbage collection
306 : : //
307 : : // XXX: we could have migration queries here to bring prior-schema
308 : : // data over instead of just dropping it. But that could incur
309 : : // doubled storage costs.
310 : : //
311 : : // buildids10: split the _files table into _parts
312 : : "" // <<< we are here
313 : : // buildids9: widen the mtime_scanned table
314 : : "DROP VIEW IF EXISTS buildids9_stats;\n"
315 : : "DROP INDEX IF EXISTS buildids9_r_de_idx;\n"
316 : : "DROP INDEX IF EXISTS buildids9_f_de_idx;\n"
317 : : "DROP VIEW IF EXISTS buildids9_query_s;\n"
318 : : "DROP VIEW IF EXISTS buildids9_query_e;\n"
319 : : "DROP VIEW IF EXISTS buildids9_query_d;\n"
320 : : "DROP TABLE IF EXISTS buildids9_r_sdef;\n"
321 : : "DROP TABLE IF EXISTS buildids9_r_sref;\n"
322 : : "DROP TABLE IF EXISTS buildids9_r_de;\n"
323 : : "DROP TABLE IF EXISTS buildids9_f_s;\n"
324 : : "DROP TABLE IF EXISTS buildids9_f_de;\n"
325 : : "DROP TABLE IF EXISTS buildids9_file_mtime_scanned;\n"
326 : : "DROP TABLE IF EXISTS buildids9_buildids;\n"
327 : : "DROP TABLE IF EXISTS buildids9_files;\n"
328 : : // buildids8: slim the sref table
329 : : "drop table if exists buildids8_f_de;\n"
330 : : "drop table if exists buildids8_f_s;\n"
331 : : "drop table if exists buildids8_r_de;\n"
332 : : "drop table if exists buildids8_r_sref;\n"
333 : : "drop table if exists buildids8_r_sdef;\n"
334 : : "drop table if exists buildids8_file_mtime_scanned;\n"
335 : : "drop table if exists buildids8_files;\n"
336 : : "drop table if exists buildids8_buildids;\n"
337 : : // buildids7: separate _norm table into dense subtype tables
338 : : "drop table if exists buildids7_f_de;\n"
339 : : "drop table if exists buildids7_f_s;\n"
340 : : "drop table if exists buildids7_r_de;\n"
341 : : "drop table if exists buildids7_r_sref;\n"
342 : : "drop table if exists buildids7_r_sdef;\n"
343 : : "drop table if exists buildids7_file_mtime_scanned;\n"
344 : : "drop table if exists buildids7_files;\n"
345 : : "drop table if exists buildids7_buildids;\n"
346 : : // buildids6: drop bolo/rfolo again, represent sources / rpmcontents in main table
347 : : "drop table if exists buildids6_norm;\n"
348 : : "drop table if exists buildids6_files;\n"
349 : : "drop table if exists buildids6_buildids;\n"
350 : : "drop view if exists buildids6;\n"
351 : : // buildids5: redefine srcfile1 column to be '.'-less (for rpms)
352 : : "drop table if exists buildids5_norm;\n"
353 : : "drop table if exists buildids5_files;\n"
354 : : "drop table if exists buildids5_buildids;\n"
355 : : "drop table if exists buildids5_bolo;\n"
356 : : "drop table if exists buildids5_rfolo;\n"
357 : : "drop view if exists buildids5;\n"
358 : : // buildids4: introduce rpmfile RFOLO
359 : : "drop table if exists buildids4_norm;\n"
360 : : "drop table if exists buildids4_files;\n"
361 : : "drop table if exists buildids4_buildids;\n"
362 : : "drop table if exists buildids4_bolo;\n"
363 : : "drop table if exists buildids4_rfolo;\n"
364 : : "drop view if exists buildids4;\n"
365 : : // buildids3*: split out srcfile BOLO
366 : : "drop table if exists buildids3_norm;\n"
367 : : "drop table if exists buildids3_files;\n"
368 : : "drop table if exists buildids3_buildids;\n"
369 : : "drop table if exists buildids3_bolo;\n"
370 : : "drop view if exists buildids3;\n"
371 : : // buildids2: normalized buildid and filenames into interning tables;
372 : : "drop table if exists buildids2_norm;\n"
373 : : "drop table if exists buildids2_files;\n"
374 : : "drop table if exists buildids2_buildids;\n"
375 : : "drop view if exists buildids2;\n"
376 : : // buildids1: made buildid and artifacttype NULLable, to represent cached-negative
377 : : // lookups from sources, e.g. files or rpms that contain no buildid-indexable content
378 : : "drop table if exists buildids1;\n"
379 : : // buildids: original
380 : : "drop table if exists buildids;\n"
381 : : ;
382 : :
383 : : static const char DEBUGINFOD_SQLITE_CLEANUP_DDL[] =
384 : : "pragma wal_checkpoint = truncate;\n" // clean out any preexisting wal file
385 : : ;
386 : :
387 : :
388 : :
389 : :
390 : : /* Name and version of program. */
391 : : ARGP_PROGRAM_VERSION_HOOK_DEF = print_version;
392 : :
393 : : /* Bug report address. */
394 : : ARGP_PROGRAM_BUG_ADDRESS_DEF = PACKAGE_BUGREPORT;
395 : :
396 : : /* Definitions of arguments for argp functions. */
397 : : static const struct argp_option options[] =
398 : : {
399 : : { NULL, 0, NULL, 0, "Scanners:", 1 },
400 : : { "scan-file-dir", 'F', NULL, 0, "Enable ELF/DWARF file scanning.", 0 },
401 : : { "scan-rpm-dir", 'R', NULL, 0, "Enable RPM scanning.", 0 },
402 : : { "scan-deb-dir", 'U', NULL, 0, "Enable DEB scanning.", 0 },
403 : : { "scan-archive", 'Z', "EXT=CMD", 0, "Enable arbitrary archive scanning.", 0 },
404 : : // "source-oci-imageregistry" ...
405 : :
406 : : { NULL, 0, NULL, 0, "Options:", 2 },
407 : : { "logical", 'L', NULL, 0, "Follow symlinks, default=ignore.", 0 },
408 : : { "rescan-time", 't', "SECONDS", 0, "Number of seconds to wait between rescans, 0=disable.", 0 },
409 : : { "groom-time", 'g', "SECONDS", 0, "Number of seconds to wait between database grooming, 0=disable.", 0 },
410 : : { "maxigroom", 'G', NULL, 0, "Run a complete database groom/shrink pass at startup.", 0 },
411 : : { "concurrency", 'c', "NUM", 0, "Limit scanning thread concurrency to NUM, default=#CPUs.", 0 },
412 : : { "connection-pool", 'C', "NUM", OPTION_ARG_OPTIONAL,
413 : : "Use webapi connection pool with NUM threads, default=unlim.", 0 },
414 : : { "include", 'I', "REGEX", 0, "Include files matching REGEX, default=all.", 0 },
415 : : { "exclude", 'X', "REGEX", 0, "Exclude files matching REGEX, default=none.", 0 },
416 : : { "port", 'p', "NUM", 0, "HTTP port to listen on, default 8002.", 0 },
417 : : { "database", 'd', "FILE", 0, "Path to sqlite database.", 0 },
418 : : { "ddl", 'D', "SQL", 0, "Apply extra sqlite ddl/pragma to connection.", 0 },
419 : : { "verbose", 'v', NULL, 0, "Increase verbosity.", 0 },
420 : : { "regex-groom", 'r', NULL, 0,"Uses regexes from -I and -X arguments to groom the database.",0},
421 : : #define ARGP_KEY_FDCACHE_FDS 0x1001
422 : : { "fdcache-fds", ARGP_KEY_FDCACHE_FDS, "NUM", OPTION_HIDDEN, NULL, 0 },
423 : : #define ARGP_KEY_FDCACHE_MBS 0x1002
424 : : { "fdcache-mbs", ARGP_KEY_FDCACHE_MBS, "MB", 0, "Maximum total size of archive file fdcache.", 0 },
425 : : #define ARGP_KEY_FDCACHE_PREFETCH 0x1003
426 : : { "fdcache-prefetch", ARGP_KEY_FDCACHE_PREFETCH, "NUM", 0, "Number of archive files to prefetch into fdcache.", 0 },
427 : : #define ARGP_KEY_FDCACHE_MINTMP 0x1004
428 : : { "fdcache-mintmp", ARGP_KEY_FDCACHE_MINTMP, "NUM", 0, "Minimum free space% on tmpdir.", 0 },
429 : : #define ARGP_KEY_FDCACHE_PREFETCH_MBS 0x1005
430 : : { "fdcache-prefetch-mbs", ARGP_KEY_FDCACHE_PREFETCH_MBS, "MB", OPTION_HIDDEN, NULL, 0},
431 : : #define ARGP_KEY_FDCACHE_PREFETCH_FDS 0x1006
432 : : { "fdcache-prefetch-fds", ARGP_KEY_FDCACHE_PREFETCH_FDS, "NUM", OPTION_HIDDEN, NULL, 0},
433 : : #define ARGP_KEY_FORWARDED_TTL_LIMIT 0x1007
434 : : {"forwarded-ttl-limit", ARGP_KEY_FORWARDED_TTL_LIMIT, "NUM", 0, "Limit of X-Forwarded-For hops, default 8.", 0},
435 : : #define ARGP_KEY_PASSIVE 0x1008
436 : : { "passive", ARGP_KEY_PASSIVE, NULL, 0, "Do not scan or groom, read-only database.", 0 },
437 : : #define ARGP_KEY_DISABLE_SOURCE_SCAN 0x1009
438 : : { "disable-source-scan", ARGP_KEY_DISABLE_SOURCE_SCAN, NULL, 0, "Do not scan dwarf source info.", 0 },
439 : : #define ARGP_SCAN_CHECKPOINT 0x100A
440 : : { "scan-checkpoint", ARGP_SCAN_CHECKPOINT, "NUM", 0, "Number of files scanned before a WAL checkpoint.", 0 },
441 : : { NULL, 0, NULL, 0, NULL, 0 },
442 : : };
443 : :
444 : : /* Short description of program. */
445 : : static const char doc[] = "Serve debuginfo-related content across HTTP from files under PATHs.";
446 : :
447 : : /* Strings for arguments in help texts. */
448 : : static const char args_doc[] = "[PATH ...]";
449 : :
450 : : /* Prototype for option handler. */
451 : : static error_t parse_opt (int key, char *arg, struct argp_state *state);
452 : :
453 : : static unsigned default_concurrency();
454 : :
455 : : /* Data structure to communicate with argp functions. */
456 : : static struct argp argp =
457 : : {
458 : : options, parse_opt, args_doc, doc, NULL, NULL, NULL
459 : : };
460 : :
461 : :
462 : : static string db_path;
463 : : static sqlite3 *db; // single connection, serialized across all our threads!
464 : : static sqlite3 *dbq; // webapi query-servicing readonly connection, serialized ditto!
465 : : static unsigned verbose;
466 : : static volatile sig_atomic_t interrupted = 0;
467 : : static volatile sig_atomic_t forced_rescan_count = 0;
468 : : static volatile sig_atomic_t sigusr1 = 0;
469 : : static volatile sig_atomic_t forced_groom_count = 0;
470 : : static volatile sig_atomic_t sigusr2 = 0;
471 : : static unsigned http_port = 8002;
472 : : static unsigned rescan_s = 300;
473 : : static unsigned groom_s = 86400;
474 : : static bool maxigroom = false;
475 : : static unsigned concurrency = default_concurrency();
476 : : static int connection_pool = 0;
477 : : static set<string> source_paths;
478 : : static bool scan_files = false;
479 : : static map<string,string> scan_archives;
480 : : static vector<string> extra_ddl;
481 : : static regex_t file_include_regex;
482 : : static regex_t file_exclude_regex;
483 : : static bool regex_groom = false;
484 : : static bool traverse_logical;
485 : : static long fdcache_mbs;
486 : : static long fdcache_prefetch;
487 : : static long fdcache_mintmp;
488 : : static unsigned forwarded_ttl_limit = 8;
489 : : static bool scan_source_info = true;
490 : : static string tmpdir;
491 : : static bool passive_p = false;
492 : : static long scan_checkpoint = 256;
493 : :
494 : : static void set_metric(const string& key, double value);
495 : : static void inc_metric(const string& key);
496 : : static void add_metric(const string& metric,
497 : : double value);
498 : : static void set_metric(const string& metric,
499 : : const string& lname, const string& lvalue,
500 : : double value);
501 : : static void inc_metric(const string& metric,
502 : : const string& lname, const string& lvalue);
503 : : static void add_metric(const string& metric,
504 : : const string& lname, const string& lvalue,
505 : : double value);
506 : : static void inc_metric(const string& metric,
507 : : const string& lname, const string& lvalue,
508 : : const string& rname, const string& rvalue);
509 : : static void add_metric(const string& metric,
510 : : const string& lname, const string& lvalue,
511 : : const string& rname, const string& rvalue,
512 : : double value);
513 : :
514 : :
515 : : class tmp_inc_metric { // a RAII style wrapper for exception-safe scoped increment & decrement
516 : : string m, n, v;
517 : : public:
518 : 2615 : tmp_inc_metric(const string& mname, const string& lname, const string& lvalue):
519 [ + - + - ]: 2615 : m(mname), n(lname), v(lvalue)
520 : : {
521 [ + - ]: 2615 : add_metric (m, n, v, 1);
522 [ - - - - : 2615 : }
- - ]
523 : 2615 : ~tmp_inc_metric()
524 : : {
525 : 2615 : add_metric (m, n, v, -1);
526 [ - + - + : 2615 : }
- + ]
527 : : };
528 : :
529 : : class tmp_ms_metric { // a RAII style wrapper for exception-safe scoped timing
530 : : string m, n, v;
531 : : struct timespec ts_start;
532 : : public:
533 : 322195 : tmp_ms_metric(const string& mname, const string& lname, const string& lvalue):
534 [ + - + - ]: 322195 : m(mname), n(lname), v(lvalue)
535 : : {
536 : 322184 : clock_gettime (CLOCK_MONOTONIC, & ts_start);
537 [ - - - - ]: 322348 : }
538 : 322452 : ~tmp_ms_metric()
539 : : {
540 : 322452 : struct timespec ts_end;
541 : 322452 : clock_gettime (CLOCK_MONOTONIC, & ts_end);
542 : 322425 : double deltas = (ts_end.tv_sec - ts_start.tv_sec)
543 : 322425 : + (ts_end.tv_nsec - ts_start.tv_nsec)/1.e9;
544 : :
545 [ + - ]: 322425 : add_metric (m + "_milliseconds_sum", n, v, (deltas*1000.0));
546 [ + + ]: 322466 : inc_metric (m + "_milliseconds_count", n, v);
547 [ + + - + : 597975 : }
- + ]
548 : : };
549 : :
550 : :
551 : : /* Handle program arguments. */
552 : : static error_t
553 : 1148 : parse_opt (int key, char *arg,
554 : : struct argp_state *state __attribute__ ((unused)))
555 : : {
556 : 1148 : int rc;
557 [ + + + + : 1148 : switch (key)
+ + + + +
- + + - -
+ + + + +
+ + + + +
- + + ]
558 : : {
559 : 286 : case 'v': verbose ++; break;
560 : 74 : case 'd':
561 : : /* When using the in-memory database make sure it is shareable,
562 : : so we can open it twice as read/write and read-only. */
563 [ + + ]: 74 : if (strcmp (arg, ":memory:") == 0)
564 : 1162 : db_path = "file::memory:?cache=shared";
565 : : else
566 [ + - ]: 120 : db_path = string(arg);
567 : : break;
568 : 74 : case 'p': http_port = (unsigned) atoi(arg);
569 [ + - ]: 74 : if (http_port == 0 || http_port > 65535)
570 : 0 : argp_failure(state, 1, EINVAL, "port number");
571 : : break;
572 : 50 : case 'F': scan_files = true; break;
573 : 22 : case 'R':
574 [ + - + - : 22 : scan_archives[".rpm"]="cat"; // libarchive groks rpm natively
- + ]
575 : 22 : break;
576 : 14 : case 'U':
577 [ + - + - : 14 : scan_archives[".deb"]="(bsdtar -O -x -f - data.tar\\*)<";
- + ]
578 [ + - + - : 14 : scan_archives[".ddeb"]="(bsdtar -O -x -f - data.tar\\*)<";
- + ]
579 [ + - + - : 14 : scan_archives[".ipk"]="(bsdtar -O -x -f - data.tar\\*)<";
- + ]
580 : : // .udeb too?
581 : 14 : break;
582 : 38 : case 'Z':
583 : 38 : {
584 [ - + ]: 38 : char* extension = strchr(arg, '=');
585 [ - + ]: 38 : if (arg[0] == '\0')
586 : 0 : argp_failure(state, 1, EINVAL, "missing EXT");
587 [ + + ]: 38 : else if (extension)
588 [ + - + - : 20 : scan_archives[string(arg, (extension-arg))]=string(extension+1);
- + - + -
- ]
589 : : else
590 [ + - + - : 18 : scan_archives[string(arg)]=string("cat");
- + - + -
- ]
591 : : }
592 : : break;
593 : 8 : case 'L':
594 [ - + ]: 8 : if (passive_p)
595 : 0 : argp_failure(state, 1, EINVAL, "-L option inconsistent with passive mode");
596 : 8 : traverse_logical = true;
597 : 8 : break;
598 : 0 : case 'D':
599 [ # # ]: 0 : if (passive_p)
600 : 0 : argp_failure(state, 1, EINVAL, "-D option inconsistent with passive mode");
601 [ # # ]: 0 : extra_ddl.push_back(string(arg));
602 : 0 : break;
603 : 58 : case 't':
604 [ - + ]: 58 : if (passive_p)
605 : 0 : argp_failure(state, 1, EINVAL, "-t option inconsistent with passive mode");
606 : 58 : rescan_s = (unsigned) atoi(arg);
607 : 58 : break;
608 : 58 : case 'g':
609 [ - + ]: 58 : if (passive_p)
610 : 0 : argp_failure(state, 1, EINVAL, "-g option inconsistent with passive mode");
611 : 58 : groom_s = (unsigned) atoi(arg);
612 : 58 : break;
613 : 0 : case 'G':
614 [ # # ]: 0 : if (passive_p)
615 : 0 : argp_failure(state, 1, EINVAL, "-G option inconsistent with passive mode");
616 : 0 : maxigroom = true;
617 : 0 : break;
618 : 0 : case 'c':
619 [ # # ]: 0 : if (passive_p)
620 : 0 : argp_failure(state, 1, EINVAL, "-c option inconsistent with passive mode");
621 : 0 : concurrency = (unsigned) atoi(arg);
622 [ # # ]: 0 : if (concurrency < 1) concurrency = 1;
623 : : break;
624 : 6 : case 'C':
625 [ + + ]: 6 : if (arg)
626 : : {
627 : 4 : connection_pool = atoi(arg);
628 [ + - ]: 4 : if (connection_pool < 2)
629 : 0 : argp_failure(state, 1, EINVAL, "-C NUM minimum 2");
630 : : }
631 : : break;
632 : 4 : case 'I':
633 : : // NB: no problem with unconditional free here - an earlier failed regcomp would exit program
634 [ - + ]: 4 : if (passive_p)
635 : 0 : argp_failure(state, 1, EINVAL, "-I option inconsistent with passive mode");
636 : 4 : regfree (&file_include_regex);
637 : 4 : rc = regcomp (&file_include_regex, arg, REG_EXTENDED|REG_NOSUB);
638 [ + - ]: 4 : if (rc != 0)
639 : 0 : argp_failure(state, 1, EINVAL, "regular expression");
640 : : break;
641 : 6 : case 'X':
642 [ - + ]: 6 : if (passive_p)
643 : 0 : argp_failure(state, 1, EINVAL, "-X option inconsistent with passive mode");
644 : 6 : regfree (&file_exclude_regex);
645 : 6 : rc = regcomp (&file_exclude_regex, arg, REG_EXTENDED|REG_NOSUB);
646 [ + - ]: 6 : if (rc != 0)
647 : 0 : argp_failure(state, 1, EINVAL, "regular expression");
648 : : break;
649 : 4 : case 'r':
650 [ - + ]: 4 : if (passive_p)
651 : 0 : argp_failure(state, 1, EINVAL, "-r option inconsistent with passive mode");
652 : 4 : regex_groom = true;
653 : 4 : break;
654 : : case ARGP_KEY_FDCACHE_FDS:
655 : : // deprecated
656 : : break;
657 : 4 : case ARGP_KEY_FDCACHE_MBS:
658 : 4 : fdcache_mbs = atol (arg);
659 : 4 : break;
660 : 2 : case ARGP_KEY_FDCACHE_PREFETCH:
661 : 2 : fdcache_prefetch = atol (arg);
662 : 2 : break;
663 : 2 : case ARGP_KEY_FDCACHE_MINTMP:
664 : 2 : fdcache_mintmp = atol (arg);
665 [ + - ]: 2 : if( fdcache_mintmp > 100 || fdcache_mintmp < 0 )
666 : 0 : argp_failure(state, 1, EINVAL, "fdcache mintmp percent");
667 : : break;
668 : 4 : case ARGP_KEY_FORWARDED_TTL_LIMIT:
669 : 4 : forwarded_ttl_limit = (unsigned) atoi(arg);
670 : 4 : break;
671 : 102 : case ARGP_KEY_ARG:
672 [ + - ]: 102 : source_paths.insert(string(arg));
673 : 102 : break;
674 : : case ARGP_KEY_FDCACHE_PREFETCH_FDS:
675 : : // deprecated
676 : : break;
677 : : case ARGP_KEY_FDCACHE_PREFETCH_MBS:
678 : : // deprecated
679 : : break;
680 : 2 : case ARGP_KEY_PASSIVE:
681 : 2 : passive_p = true;
682 [ + - ]: 2 : if (source_paths.size() > 0
683 [ + - ]: 2 : || maxigroom
684 [ + - ]: 2 : || extra_ddl.size() > 0
685 [ + - + - ]: 4 : || traverse_logical)
686 : : // other conflicting options tricky to check
687 : 0 : argp_failure(state, 1, EINVAL, "inconsistent options with passive mode");
688 : : break;
689 : 0 : case ARGP_KEY_DISABLE_SOURCE_SCAN:
690 : 0 : scan_source_info = false;
691 : 0 : break;
692 : 2 : case ARGP_SCAN_CHECKPOINT:
693 : 2 : scan_checkpoint = atol (arg);
694 [ + - ]: 2 : if (scan_checkpoint < 0)
695 : 0 : argp_failure(state, 1, EINVAL, "scan checkpoint");
696 : : break;
697 : : // case 'h': argp_state_help (state, stderr, ARGP_HELP_LONG|ARGP_HELP_EXIT_OK);
698 : : default: return ARGP_ERR_UNKNOWN;
699 : : }
700 : :
701 : : return 0;
702 : : }
703 : :
704 : :
705 : : ////////////////////////////////////////////////////////////////////////
706 : :
707 : :
708 : : static void add_mhd_response_header (struct MHD_Response *r,
709 : : const char *h, const char *v);
710 : :
711 : : // represent errors that may get reported to an ostream and/or a libmicrohttpd connection
712 : :
713 : 8 : struct reportable_exception
714 : : {
715 : : int code;
716 : : string message;
717 : :
718 [ - - + - : 86 : reportable_exception(int c, const string& m): code(c), message(m) {}
- - + - +
- ]
719 [ - - - - : 604 : reportable_exception(const string& m): code(503), message(m) {}
- - - - +
- - - - -
+ - - - -
- - - + -
- - ]
720 : : reportable_exception(): code(503), message() {}
721 : :
722 : : void report(ostream& o) const; // defined under obatched() class below
723 : :
724 : 634 : MHD_RESULT mhd_send_response(MHD_Connection* c) const {
725 : 1268 : MHD_Response* r = MHD_create_response_from_buffer (message.size(),
726 : 634 : (void*) message.c_str(),
727 : : MHD_RESPMEM_MUST_COPY);
728 : 634 : add_mhd_response_header (r, "Content-Type", "text/plain");
729 : 634 : MHD_RESULT rc = MHD_queue_response (c, code, r);
730 : 634 : MHD_destroy_response (r);
731 : 634 : return rc;
732 : : }
733 : : };
734 : :
735 : :
736 : : struct sqlite_exception: public reportable_exception
737 : : {
738 : 0 : sqlite_exception(int rc, const string& msg):
739 [ # # # # : 0 : reportable_exception(string("sqlite3 error: ") + msg + ": " + string(sqlite3_errstr(rc) ?: "?")) {
# # # # #
# # # # #
# # # # #
# ]
740 [ # # # # : 0 : inc_metric("error_count","sqlite3",sqlite3_errstr(rc));
# # # # #
# # # # #
# # # # ]
741 [ # # ]: 0 : }
742 : : };
743 : :
744 [ + - - - ]: 4 : struct libc_exception: public reportable_exception
745 : : {
746 : 594 : libc_exception(int rc, const string& msg):
747 [ - + + - : 2376 : reportable_exception(string("libc error: ") + msg + ": " + string(strerror(rc) ?: "?")) {
+ - + - +
- - + - +
- + + - -
- ]
748 [ + - + - : 1188 : inc_metric("error_count","libc",strerror(rc));
+ - + - -
+ + - - -
- - ]
749 [ - - ]: 594 : }
750 : : };
751 : :
752 : :
753 : : struct archive_exception: public reportable_exception
754 : : {
755 : 0 : archive_exception(const string& msg):
756 [ # # # # : 0 : reportable_exception(string("libarchive error: ") + msg) {
# # ]
757 [ # # # # : 0 : inc_metric("error_count","libarchive",msg);
# # # # #
# ]
758 [ # # ]: 0 : }
759 : 0 : archive_exception(struct archive* a, const string& msg):
760 [ # # # # : 0 : reportable_exception(string("libarchive error: ") + msg + ": " + string(archive_error_string(a) ?: "?")) {
# # # # #
# # # # #
# # # # #
# ]
761 [ # # # # : 0 : inc_metric("error_count","libarchive",msg + ": " + string(archive_error_string(a) ?: "?"));
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# ]
762 [ # # ]: 0 : }
763 : : };
764 : :
765 : :
766 : : struct elfutils_exception: public reportable_exception
767 : : {
768 : 0 : elfutils_exception(int rc, const string& msg):
769 [ # # # # : 0 : reportable_exception(string("elfutils error: ") + msg + ": " + string(elf_errmsg(rc) ?: "?")) {
# # # # #
# # # # #
# # # # #
# ]
770 [ # # # # : 0 : inc_metric("error_count","elfutils",elf_errmsg(rc));
# # # # #
# # # # #
# # # # ]
771 [ # # ]: 0 : }
772 : : };
773 : :
774 : :
775 : : ////////////////////////////////////////////////////////////////////////
776 : :
777 : : template <typename Payload>
778 : : class workq
779 : : {
780 : : unordered_set<Payload> q; // eliminate duplicates
781 : : mutex mtx;
782 : : condition_variable cv;
783 : : bool dead;
784 : : unsigned idlers; // number of threads busy with wait_idle / done_idle
785 : : unsigned fronters; // number of threads busy with wait_front / done_front
786 : :
787 : : public:
788 : 74 : workq() { dead = false; idlers = 0; fronters = 0; }
789 : 74 : ~workq() {}
790 : :
791 : 1186 : void push_back(const Payload& p)
792 : : {
793 : 1186 : unique_lock<mutex> lock(mtx);
794 [ + - ]: 1186 : q.insert (p);
795 [ + - + - : 2372 : set_metric("thread_work_pending","role","scan", q.size());
+ - + - -
+ - + - -
- - ]
796 : 1186 : cv.notify_all();
797 : 1186 : }
798 : :
799 : : // kill this workqueue, wake up all idlers / scanners
800 : 74 : void nuke() {
801 : 74 : unique_lock<mutex> lock(mtx);
802 : : // optional: q.clear();
803 : 74 : dead = true;
804 : 74 : cv.notify_all();
805 : 74 : }
806 : :
807 : : // clear the workqueue, when scanning is interrupted with USR2
808 : 0 : void clear() {
809 : 0 : unique_lock<mutex> lock(mtx);
810 : 0 : q.clear();
811 [ # # # # : 0 : set_metric("thread_work_pending","role","scan", q.size());
# # # # #
# # # # #
# # ]
812 : : // NB: there may still be some live fronters
813 : 0 : cv.notify_all(); // maybe wake up waiting idlers
814 : 0 : }
815 : :
816 : : // block this scanner thread until there is work to do and no active idler
817 : 1450 : bool wait_front (Payload& p)
818 : : {
819 : 1450 : unique_lock<mutex> lock(mtx);
820 [ + + + + : 4932 : while (!dead && (q.size() == 0 || idlers > 0))
+ + ]
821 [ + - ]: 3482 : cv.wait(lock);
822 [ + + ]: 1450 : if (dead)
823 : : return false;
824 : : else
825 : : {
826 [ + - ]: 1186 : p = * q.begin();
827 : 1186 : q.erase (q.begin());
828 : 1186 : fronters ++; // prevent idlers from starting awhile, even if empty q
829 [ + - + - : 2372 : set_metric("thread_work_pending","role","scan", q.size());
+ - + - -
+ - + - -
- - - - ]
830 : : // NB: don't wake up idlers yet! The consumer is busy
831 : : // processing this element until it calls done_front().
832 : 1186 : return true;
833 : : }
834 : 1450 : }
835 : :
836 : : // notify waitq that scanner thread is done with that last item
837 : 1186 : void done_front ()
838 : : {
839 : 1186 : unique_lock<mutex> lock(mtx);
840 : 1186 : fronters --;
841 [ + + + + ]: 1186 : if (q.size() == 0 && fronters == 0)
842 : 93 : cv.notify_all(); // maybe wake up waiting idlers
843 : 1186 : }
844 : :
845 : : // block this idler thread until there is no work to do
846 : 599 : void wait_idle ()
847 : : {
848 : 599 : unique_lock<mutex> lock(mtx);
849 : 599 : cv.notify_all(); // maybe wake up waiting scanners
850 [ + + + + : 657 : while (!dead && ((q.size() != 0) || fronters > 0))
+ + ]
851 [ + - ]: 58 : cv.wait(lock);
852 [ + - ]: 599 : idlers ++;
853 : 599 : }
854 : :
855 : 527 : void done_idle ()
856 : : {
857 : 527 : unique_lock<mutex> lock(mtx);
858 : 527 : idlers --;
859 : 527 : cv.notify_all(); // maybe wake up waiting scanners, but probably not (shutting down)
860 : 527 : }
861 : : };
862 : :
863 : : typedef struct stat stat_t;
864 : : typedef pair<string,stat_t> scan_payload;
865 : : inline bool operator< (const scan_payload& a, const scan_payload& b)
866 : : {
867 : : return a.first < b.first; // don't bother compare the stat fields
868 : : }
869 : :
870 : : namespace std { // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=56480
871 : : template<> struct hash<::scan_payload>
872 : : {
873 : 4914 : std::size_t operator() (const ::scan_payload& p) const noexcept
874 : : {
875 [ + + + + ]: 4914 : return hash<string>()(p.first);
876 : : }
877 : : };
878 : : template<> struct equal_to<::scan_payload>
879 : : {
880 : 486 : std::size_t operator() (const ::scan_payload& a, const ::scan_payload& b) const noexcept
881 : : {
882 [ - + - - ]: 486 : return a.first == b.first;
883 : : }
884 : : };
885 : : }
886 : :
887 : : static workq<scan_payload> scanq; // just a single one
888 : : // producer & idler: thread_main_fts_source_paths()
889 : : // consumer: thread_main_scanner()
890 : : // idler: thread_main_groom()
891 : :
892 : :
893 : : ////////////////////////////////////////////////////////////////////////
894 : :
895 : : // Unique set is a thread-safe structure that lends 'ownership' of a value
896 : : // to a thread. Other threads requesting the same thing are made to wait.
897 : : // It's like a semaphore-on-demand.
898 : : template <typename T>
899 : : class unique_set
900 : : {
901 : : private:
902 : : set<T> values;
903 : : mutex mtx;
904 : : condition_variable cv;
905 : : public:
906 : 57 : unique_set() {}
907 : 57 : ~unique_set() {}
908 : :
909 : 1897 : void acquire(const T& value)
910 : : {
911 : 1897 : unique_lock<mutex> lock(mtx);
912 [ + + ]: 2596 : while (values.find(value) != values.end())
913 [ + - ]: 699 : cv.wait(lock);
914 [ + - ]: 1897 : values.insert(value);
915 : 1897 : }
916 : :
917 : 1897 : void release(const T& value)
918 : : {
919 : 1897 : unique_lock<mutex> lock(mtx);
920 : : // assert (values.find(value) != values.end());
921 : 1897 : values.erase(value);
922 : 1897 : cv.notify_all();
923 : 1897 : }
924 : : };
925 : :
926 : :
927 : : // This is the object that's instantiate to uniquely hold a value in a
928 : : // RAII-pattern way.
929 : : template <typename T>
930 : : class unique_set_reserver
931 : : {
932 : : private:
933 : : unique_set<T>& please_hold;
934 : : T mine;
935 : : public:
936 : 1897 : unique_set_reserver(unique_set<T>& t, const T& value):
937 [ + - - - ]: 1897 : please_hold(t), mine(value) { please_hold.acquire(mine); }
938 [ + - ]: 1897 : ~unique_set_reserver() { please_hold.release(mine); }
939 : : };
940 : :
941 : :
942 : : ////////////////////////////////////////////////////////////////////////
943 : :
944 : : // periodic_barrier is a concurrency control object that lets N threads
945 : : // periodically (based on counter value) agree to wait at a barrier,
946 : : // let one of them carry out some work, then be set free
947 : :
948 : : class periodic_barrier
949 : : {
950 : : private:
951 : : unsigned period; // number of count() reports to trigger barrier activation
952 : : unsigned threads; // number of threads participating
953 : : mutex mtx; // protects all the following fields
954 : : unsigned counter; // count of count() reports in the current generation
955 : : unsigned generation; // barrier activation generation
956 : : unsigned waiting; // number of threads waiting for barrier
957 : : bool dead; // bring out your
958 : : condition_variable cv;
959 : : public:
960 : 66 : periodic_barrier(unsigned t, unsigned p):
961 : 66 : period(p), threads(t), counter(0), generation(0), waiting(0), dead(false) { }
962 : : virtual ~periodic_barrier() {}
963 : :
964 : : virtual void periodic_barrier_work() noexcept = 0;
965 : 66 : void nuke() {
966 : 66 : unique_lock<mutex> lock(mtx);
967 : 66 : dead = true;
968 : 66 : cv.notify_all();
969 : 66 : }
970 : :
971 : 1450 : void count()
972 : : {
973 : 1450 : unique_lock<mutex> lock(mtx);
974 : 1450 : unsigned prev_generation = this->generation;
975 [ + + ]: 1450 : if (counter < period-1) // normal case: counter just freely running
976 : : {
977 : 1334 : counter ++;
978 : 1334 : return;
979 : : }
980 [ + + ]: 116 : else if (counter == period-1) // we're the doer
981 : : {
982 : 30 : counter = period; // entering barrier holding phase
983 : 30 : cv.notify_all();
984 [ + + + + ]: 146 : while (waiting < threads-1 && !dead)
985 [ + - ]: 86 : cv.wait(lock);
986 : : // all other threads are now stuck in the barrier
987 : 30 : this->periodic_barrier_work(); // NB: we're holding the mutex the whole time
988 : : // reset for next barrier, releasing other waiters
989 : 30 : counter = 0;
990 : 30 : generation ++;
991 : 30 : cv.notify_all();
992 : 30 : return;
993 : : }
994 [ + - ]: 86 : else if (counter == period) // we're a waiter, in holding phase
995 : : {
996 : 86 : waiting ++;
997 : 86 : cv.notify_all();
998 [ + + + + : 315 : while (counter == period && generation == prev_generation && !dead)
+ - ]
999 [ + - ]: 143 : cv.wait(lock);
1000 : 86 : waiting --;
1001 : 86 : return;
1002 : : }
1003 : 1450 : }
1004 : : };
1005 : :
1006 : :
1007 : :
1008 : : ////////////////////////////////////////////////////////////////////////
1009 : :
1010 : :
1011 : : // Print a standard timestamp.
1012 : : static ostream&
1013 : 41534 : timestamp (ostream &o)
1014 : : {
1015 : 41534 : char datebuf[80];
1016 : 41534 : char *now2 = NULL;
1017 : 41534 : time_t now_t = time(NULL);
1018 : 41534 : struct tm now;
1019 : 41534 : struct tm *nowp = gmtime_r (&now_t, &now);
1020 [ + - ]: 41534 : if (nowp)
1021 : : {
1022 : 41534 : (void) strftime (datebuf, sizeof (datebuf), "%c", nowp);
1023 : 41534 : now2 = datebuf;
1024 : : }
1025 : :
1026 : 41534 : return o << "[" << (now2 ? now2 : "") << "] "
1027 [ - + ]: 41534 : << "(" << getpid () << "/" << tid() << "): ";
1028 : : }
1029 : :
1030 : :
1031 : : // A little class that impersonates an ostream to the extent that it can
1032 : : // take << streaming operations. It batches up the bits into an internal
1033 : : // stringstream until it is destroyed; then flushes to the original ostream.
1034 : : // It adds a timestamp
1035 : : class obatched
1036 : : {
1037 : : private:
1038 : : ostream& o;
1039 : : stringstream stro;
1040 : : static mutex lock;
1041 : : public:
1042 : 41533 : obatched(ostream& oo, bool timestamp_p = true): o(oo)
1043 : : {
1044 [ + - ]: 41534 : if (timestamp_p)
1045 [ + - ]: 41534 : timestamp(stro);
1046 : 41534 : }
1047 : 41533 : ~obatched()
1048 : : {
1049 : 41533 : unique_lock<mutex> do_not_cross_the_streams(obatched::lock);
1050 [ + - ]: 41534 : o << stro.str();
1051 : 41534 : o.flush();
1052 : 41534 : }
1053 : : operator ostream& () { return stro; }
1054 [ - - + - : 29822 : template <typename T> ostream& operator << (const T& t) { stro << t; return stro; }
+ - + - +
- + - + -
- - - - -
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
- - + - +
- + - + -
+ - + - +
- + - - -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - -
- - - - -
+ - - - +
- - - - -
- - + - -
- + - - -
+ - - - -
- + - + -
+ - + - +
- + - - -
- - ]
1055 : : };
1056 : : mutex obatched::lock; // just the one, since cout/cerr iostreams are not thread-safe
1057 : :
1058 : :
1059 : 696 : void reportable_exception::report(ostream& o) const {
1060 [ + - + - ]: 696 : obatched(o) << message << endl;
1061 : 696 : }
1062 : :
1063 : :
1064 : : ////////////////////////////////////////////////////////////////////////
1065 : :
1066 : :
1067 : : // RAII style sqlite prepared-statement holder that matches { } block lifetime
1068 : :
1069 : : struct sqlite_ps
1070 : : {
1071 : : private:
1072 : : sqlite3* db;
1073 : : const string nickname;
1074 : : const string sql;
1075 : : sqlite3_stmt *pp;
1076 : :
1077 : : sqlite_ps(const sqlite_ps&); // make uncopyable
1078 : : sqlite_ps& operator=(const sqlite_ps &); // make unassignable
1079 : :
1080 : : public:
1081 [ + - - - ]: 7063 : sqlite_ps (sqlite3* d, const string& n, const string& s): db(d), nickname(n), sql(s) {
1082 : : // tmp_ms_metric tick("sqlite3","prep",nickname);
1083 [ + + ]: 7063 : if (verbose > 4)
1084 [ + - + - : 348 : obatched(clog) << nickname << " prep " << sql << endl;
+ - + - +
- - - ]
1085 [ + - ]: 7063 : int rc = sqlite3_prepare_v2 (db, sql.c_str(), -1 /* to \0 */, & this->pp, NULL);
1086 [ - + ]: 7063 : if (rc != SQLITE_OK)
1087 [ # # # # ]: 0 : throw sqlite_exception(rc, "prepare " + sql);
1088 : 7063 : }
1089 : :
1090 : 177317 : sqlite_ps& reset()
1091 : : {
1092 [ + - + - : 354611 : tmp_ms_metric tick("sqlite3","reset",nickname);
- + - - ]
1093 [ + - ]: 177294 : sqlite3_reset(this->pp);
1094 : 177314 : return *this;
1095 : 177310 : }
1096 : :
1097 : 203530 : sqlite_ps& bind(int parameter, const string& str)
1098 : : {
1099 [ + + ]: 203530 : if (verbose > 4)
1100 [ + - + - : 1418 : obatched(clog) << nickname << " bind " << parameter << "=" << str << endl;
+ - + - +
- + - ]
1101 : 203530 : int rc = sqlite3_bind_text (this->pp, parameter, str.c_str(), -1, SQLITE_TRANSIENT);
1102 [ - + ]: 203531 : if (rc != SQLITE_OK)
1103 [ # # # # ]: 0 : throw sqlite_exception(rc, "sqlite3 bind");
1104 : 203531 : return *this;
1105 : : }
1106 : :
1107 : 52024 : sqlite_ps& bind(int parameter, int64_t value)
1108 : : {
1109 [ + + ]: 52024 : if (verbose > 4)
1110 [ + - + - : 636 : obatched(clog) << nickname << " bind " << parameter << "=" << value << endl;
+ - + - +
- + - ]
1111 : 52024 : int rc = sqlite3_bind_int64 (this->pp, parameter, value);
1112 [ - + ]: 52026 : if (rc != SQLITE_OK)
1113 [ # # # # ]: 0 : throw sqlite_exception(rc, "sqlite3 bind");
1114 : 52026 : return *this;
1115 : : }
1116 : :
1117 : : sqlite_ps& bind(int parameter)
1118 : : {
1119 : : if (verbose > 4)
1120 : : obatched(clog) << nickname << " bind " << parameter << "=" << "NULL" << endl;
1121 : : int rc = sqlite3_bind_null (this->pp, parameter);
1122 : : if (rc != SQLITE_OK)
1123 : : throw sqlite_exception(rc, "sqlite3 bind");
1124 : : return *this;
1125 : : }
1126 : :
1127 : :
1128 : 109565 : void step_ok_done() {
1129 [ + - + - : 219106 : tmp_ms_metric tick("sqlite3","step_done",nickname);
- + - - ]
1130 [ + - ]: 109541 : int rc = sqlite3_step (this->pp);
1131 [ + + ]: 109578 : if (verbose > 4)
1132 [ + - + - : 832 : obatched(clog) << nickname << " step-ok-done(" << sqlite3_errstr(rc) << ") " << sql << endl;
+ - + - +
- + - + -
+ - ]
1133 [ + + - + ]: 109578 : if (rc != SQLITE_OK && rc != SQLITE_DONE && rc != SQLITE_ROW)
1134 [ # # # # ]: 0 : throw sqlite_exception(rc, "sqlite3 step");
1135 [ + - ]: 109578 : (void) sqlite3_reset (this->pp);
1136 : 109578 : }
1137 : :
1138 : :
1139 : 35566 : int step() {
1140 [ + - + - : 71133 : tmp_ms_metric tick("sqlite3","step",nickname);
- + - - ]
1141 [ + - ]: 35567 : int rc = sqlite3_step (this->pp);
1142 [ + + ]: 35567 : if (verbose > 4)
1143 [ + - + - : 378 : obatched(clog) << nickname << " step(" << sqlite3_errstr(rc) << ") " << sql << endl;
+ - + - +
- + - + -
+ - ]
1144 : 35567 : return rc;
1145 : 35567 : }
1146 : :
1147 [ + + + + ]: 14048 : ~sqlite_ps () { sqlite3_finalize (this->pp); }
1148 [ + - + - : 4107 : operator sqlite3_stmt* () { return this->pp; }
+ - ]
1149 : : };
1150 : :
1151 : :
1152 : : ////////////////////////////////////////////////////////////////////////
1153 : :
1154 : :
1155 : : struct sqlite_checkpoint_pb: public periodic_barrier
1156 : : {
1157 : : // NB: don't use sqlite_ps since it can throw exceptions during ctor etc.
1158 : 66 : sqlite_checkpoint_pb(unsigned t, unsigned p):
1159 : 132 : periodic_barrier(t, p) { }
1160 : :
1161 : 30 : void periodic_barrier_work() noexcept
1162 : : {
1163 : 30 : (void) sqlite3_exec (db, "pragma wal_checkpoint(truncate);", NULL, NULL, NULL);
1164 : 30 : }
1165 : : };
1166 : :
1167 : : static periodic_barrier* scan_barrier = 0; // initialized in main()
1168 : :
1169 : :
1170 : : ////////////////////////////////////////////////////////////////////////
1171 : :
1172 : : // RAII style templated autocloser
1173 : :
1174 : : template <class Payload, class Ignore>
1175 : : struct defer_dtor
1176 : : {
1177 : : public:
1178 : : typedef Ignore (*dtor_fn) (Payload);
1179 : :
1180 : : private:
1181 : : Payload p;
1182 : : dtor_fn fn;
1183 : :
1184 : : public:
1185 : 3322 : defer_dtor(Payload _p, dtor_fn _fn): p(_p), fn(_fn) {}
1186 : 714 : ~defer_dtor() { (void) (*fn)(p); }
1187 : :
1188 : : private:
1189 : : defer_dtor(const defer_dtor<Payload,Ignore>&); // make uncopyable
1190 : : defer_dtor& operator=(const defer_dtor<Payload,Ignore> &); // make unassignable
1191 : : };
1192 : :
1193 : :
1194 : :
1195 : : ////////////////////////////////////////////////////////////////////////
1196 : :
1197 : :
1198 : : static string
1199 : 5242 : header_censor(const string& str)
1200 : : {
1201 : 5242 : string y;
1202 [ + + ]: 55467 : for (auto&& x : str)
1203 : : {
1204 [ + + ]: 50225 : if (isalnum(x) || x == '/' || x == '.' || x == ',' || x == '_' || x == ':')
1205 [ + - ]: 100444 : y += x;
1206 : : }
1207 : 5242 : return y;
1208 : 0 : }
1209 : :
1210 : :
1211 : : static string
1212 : 2621 : conninfo (struct MHD_Connection * conn)
1213 : : {
1214 : 2621 : char hostname[256]; // RFC1035
1215 : 2621 : char servname[256];
1216 : 2621 : int sts = -1;
1217 : :
1218 [ - + ]: 2621 : if (conn == 0)
1219 : 0 : return "internal";
1220 : :
1221 : : /* Look up client address data. */
1222 : 2621 : const union MHD_ConnectionInfo *u = MHD_get_connection_info (conn,
1223 : : MHD_CONNECTION_INFO_CLIENT_ADDRESS);
1224 [ + - ]: 2621 : struct sockaddr *so = u ? u->client_addr : 0;
1225 : :
1226 [ + - - + ]: 2621 : if (so && so->sa_family == AF_INET) {
1227 : 0 : sts = getnameinfo (so, sizeof (struct sockaddr_in),
1228 : : hostname, sizeof (hostname),
1229 : : servname, sizeof (servname),
1230 : : NI_NUMERICHOST | NI_NUMERICSERV);
1231 [ + - ]: 2621 : } else if (so && so->sa_family == AF_INET6) {
1232 : 2621 : struct sockaddr_in6* addr6 = (struct sockaddr_in6*) so;
1233 [ + - + - : 2621 : if (IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr)) {
- + ]
1234 : 2621 : struct sockaddr_in addr4;
1235 : 2621 : memset (&addr4, 0, sizeof(addr4));
1236 : 2621 : addr4.sin_family = AF_INET;
1237 : 2621 : addr4.sin_port = addr6->sin6_port;
1238 : 2621 : memcpy (&addr4.sin_addr.s_addr, addr6->sin6_addr.s6_addr+12, sizeof(addr4.sin_addr.s_addr));
1239 : 2621 : sts = getnameinfo ((struct sockaddr*) &addr4, sizeof (addr4),
1240 : : hostname, sizeof (hostname),
1241 : : servname, sizeof (servname),
1242 : : NI_NUMERICHOST | NI_NUMERICSERV);
1243 : : } else {
1244 : 0 : sts = getnameinfo (so, sizeof (struct sockaddr_in6),
1245 : : hostname, sizeof (hostname),
1246 : : servname, sizeof (servname),
1247 : : NI_NUMERICHOST | NI_NUMERICSERV);
1248 : : }
1249 : : }
1250 : :
1251 [ - + ]: 2621 : if (sts != 0) {
1252 : 0 : hostname[0] = servname[0] = '\0';
1253 : : }
1254 : :
1255 : : // extract headers relevant to administration
1256 [ - + ]: 2621 : const char* user_agent = MHD_lookup_connection_value (conn, MHD_HEADER_KIND, "User-Agent") ?: "";
1257 [ + + ]: 2621 : const char* x_forwarded_for = MHD_lookup_connection_value (conn, MHD_HEADER_KIND, "X-Forwarded-For") ?: "";
1258 : : // NB: these are untrustworthy, beware if machine-processing log files
1259 : :
1260 [ + - + - : 7863 : return string(hostname) + string(":") + string(servname) +
+ - + - +
- + - - +
- + - + -
+ - + - +
- - - - -
- ]
1261 [ + - + - : 11299 : string(" UA:") + header_censor(string(user_agent)) +
+ - + - +
- - + + +
- + + + -
+ - - -
- ]
1262 [ + - + - : 7875 : string(" XFF:") + header_censor(string(x_forwarded_for));
+ - + + +
+ - - ]
1263 : : }
1264 : :
1265 : :
1266 : :
1267 : : ////////////////////////////////////////////////////////////////////////
1268 : :
1269 : : /* Wrapper for MHD_add_response_header that logs an error if we
1270 : : couldn't add the specified header. */
1271 : : static void
1272 : 8633 : add_mhd_response_header (struct MHD_Response *r,
1273 : : const char *h, const char *v)
1274 : : {
1275 [ - + ]: 8633 : if (MHD_add_response_header (r, h, v) == MHD_NO)
1276 [ # # # # : 0 : obatched(clog) << "Error: couldn't add '" << h << "' header" << endl;
# # ]
1277 : 8633 : }
1278 : :
1279 : : static void
1280 : 1311 : add_mhd_last_modified (struct MHD_Response *resp, time_t mtime)
1281 : : {
1282 : 1311 : struct tm now;
1283 : 1311 : struct tm *nowp = gmtime_r (&mtime, &now);
1284 [ + - ]: 1311 : if (nowp != NULL)
1285 : : {
1286 : 1311 : char datebuf[80];
1287 : 1311 : size_t rc = strftime (datebuf, sizeof (datebuf), "%a, %d %b %Y %T GMT",
1288 : : nowp);
1289 [ + - ]: 1311 : if (rc > 0 && rc < sizeof (datebuf))
1290 : 1311 : add_mhd_response_header (resp, "Last-Modified", datebuf);
1291 : : }
1292 : :
1293 : 1311 : add_mhd_response_header (resp, "Cache-Control", "public");
1294 : 1311 : }
1295 : :
1296 : : // quote all questionable characters of str for safe passage through a sh -c expansion.
1297 : : static string
1298 : 56 : shell_escape(const string& str)
1299 : : {
1300 : 56 : string y;
1301 [ + + ]: 7308 : for (auto&& x : str)
1302 : : {
1303 [ + + + + ]: 7252 : if (! isalnum(x) && x != '/')
1304 [ + - ]: 574 : y += "\\";
1305 [ + - ]: 14504 : y += x;
1306 : : }
1307 : 56 : return y;
1308 : 0 : }
1309 : :
1310 : :
1311 : : // PR25548: Perform POSIX / RFC3986 style path canonicalization on the input string.
1312 : : //
1313 : : // Namely:
1314 : : // // -> /
1315 : : // /foo/../ -> /
1316 : : // /./ -> /
1317 : : //
1318 : : // This mapping is done on dwarf-side source path names, which may
1319 : : // include these constructs, so we can deal with debuginfod clients
1320 : : // that accidentally canonicalize the paths.
1321 : : //
1322 : : // realpath(3) is close but not quite right, because it also resolves
1323 : : // symbolic links. Symlinks at the debuginfod server have nothing to
1324 : : // do with the build-time symlinks, thus they must not be considered.
1325 : : //
1326 : : // see also curl Curl_dedotdotify() aka RFC3986, which we mostly follow here
1327 : : // see also libc __realpath()
1328 : : // see also llvm llvm::sys::path::remove_dots()
1329 : : static string
1330 : 15047 : canon_pathname (const string& input)
1331 : : {
1332 : 15047 : string i = input; // 5.2.4 (1)
1333 : 15047 : string o;
1334 : :
1335 : 143354 : while (i.size() != 0)
1336 : : {
1337 : : // 5.2.4 (2) A
1338 [ + - - + : 256614 : if (i.substr(0,3) == "../")
- + ]
1339 [ # # # # ]: 0 : i = i.substr(3);
1340 [ + - - + : 256614 : else if(i.substr(0,2) == "./")
- + ]
1341 [ # # # # ]: 0 : i = i.substr(2);
1342 : :
1343 : : // 5.2.4 (2) B
1344 [ + - - + : 256614 : else if (i.substr(0,3) == "/./")
+ + ]
1345 [ + - + + ]: 2826 : i = i.substr(2);
1346 [ - + ]: 126659 : else if (i == "/.")
1347 [ # # ]: 0 : i = ""; // no need to handle "/." complete-path-segment case; we're dealing with file names
1348 : :
1349 : : // 5.2.4 (2) C
1350 [ + - - + : 253318 : else if (i.substr(0,4) == "/../") {
+ + ]
1351 [ + - + + ]: 2016 : i = i.substr(3);
1352 : 2016 : string::size_type sl = o.rfind("/");
1353 [ + - ]: 2016 : if (sl != string::npos)
1354 [ + - + - ]: 4032 : o = o.substr(0, sl);
1355 : : else
1356 [ # # ]: 0 : o = "";
1357 [ - + ]: 124643 : } else if (i == "/..")
1358 [ # # ]: 0 : i = ""; // no need to handle "/.." complete-path-segment case; we're dealing with file names
1359 : :
1360 : : // 5.2.4 (2) D
1361 : : // no need to handle these cases; we're dealing with file names
1362 [ - + ]: 124643 : else if (i == ".")
1363 [ # # ]: 0 : i = "";
1364 [ - + ]: 124643 : else if (i == "..")
1365 [ # # ]: 0 : i = "";
1366 : :
1367 : : // POSIX special: map // to /
1368 [ + - - + : 249286 : else if (i.substr(0,2) == "//")
+ + ]
1369 [ + - + + ]: 152 : i = i.substr(1);
1370 : :
1371 : : // 5.2.4 (2) E
1372 : : else {
1373 [ - + ]: 124507 : string::size_type next_slash = i.find("/", (i[0]=='/' ? 1 : 0)); // skip first slash
1374 [ + - + + ]: 249014 : o += i.substr(0, next_slash);
1375 [ + + ]: 124507 : if (next_slash == string::npos)
1376 [ + - + + ]: 158401 : i = "";
1377 : : else
1378 [ + - + + : 206808 : i = i.substr(next_slash);
- - ]
1379 : : }
1380 : : }
1381 : :
1382 [ + - ]: 15047 : return o;
1383 : 15047 : }
1384 : :
1385 : :
1386 : : // Estimate available free space for a given filesystem via statfs(2).
1387 : : // Return true if the free fraction is known to be smaller than the
1388 : : // given minimum percentage. Also update a related metric.
1389 : 2652 : bool statfs_free_enough_p(const string& path, const string& label, long minfree = 0)
1390 : : {
1391 : 2652 : struct statfs sfs;
1392 : 2652 : int rc = statfs(path.c_str(), &sfs);
1393 [ + + ]: 2652 : if (rc == 0)
1394 : : {
1395 : 2602 : double s = (double) sfs.f_bavail / (double) sfs.f_blocks;
1396 [ + - + - : 5204 : set_metric("filesys_free_ratio","purpose",label, s);
- + - - ]
1397 : 2602 : return ((s * 100.0) < minfree);
1398 : : }
1399 : : return false;
1400 : : }
1401 : :
1402 : :
1403 : :
1404 : : // A map-like class that owns a cache of file descriptors (indexed by
1405 : : // file / content names).
1406 : : //
1407 : : // If only it could use fd's instead of file names ... but we can't
1408 : : // dup(2) to create independent descriptors for the same unlinked
1409 : : // files, so would have to use some goofy linux /proc/self/fd/%d
1410 : : // hack such as the following
1411 : :
1412 : : #if 0
1413 : : int superdup(int fd)
1414 : : {
1415 : : #ifdef __linux__
1416 : : char *fdpath = NULL;
1417 : : int rc = asprintf(& fdpath, "/proc/self/fd/%d", fd);
1418 : : int newfd;
1419 : : if (rc >= 0)
1420 : : newfd = open(fdpath, O_RDONLY);
1421 : : else
1422 : : newfd = -1;
1423 : : free (fdpath);
1424 : : return newfd;
1425 : : #else
1426 : : return -1;
1427 : : #endif
1428 : : }
1429 : : #endif
1430 : :
1431 : : class libarchive_fdcache
1432 : : {
1433 : : private:
1434 : : mutex fdcache_lock;
1435 : :
1436 : : typedef pair<string,string> key; // archive, entry
1437 [ + - ]: 208 : struct fdcache_entry
1438 : : {
1439 : : string fd; // file name (probably in $TMPDIR), not an actual open fd (EMFILE)
1440 : : double fd_size_mb; // slightly rounded up megabytes
1441 : : time_t freshness; // when was this entry created or requested last
1442 : : unsigned request_count; // how many requests were made; or 0=prefetch only
1443 : : double latency; // how many seconds it took to extract the file
1444 : : };
1445 : :
1446 : : map<key,fdcache_entry> entries; // optimized for lookup
1447 : : time_t last_cleaning;
1448 : : long max_mbs;
1449 : :
1450 : : public:
1451 : 282 : void set_metrics()
1452 : : {
1453 : 282 : double fdcache_mb = 0.0;
1454 : 282 : double prefetch_mb = 0.0;
1455 : 282 : unsigned fdcache_count = 0;
1456 : 282 : unsigned prefetch_count = 0;
1457 [ + + ]: 1730 : for (auto &i : entries) {
1458 [ + + ]: 1448 : if (i.second.request_count) {
1459 : 1354 : fdcache_mb += i.second.fd_size_mb;
1460 : 1354 : fdcache_count ++;
1461 : : } else {
1462 : 94 : prefetch_mb += i.second.fd_size_mb;
1463 : 94 : prefetch_count ++;
1464 : : }
1465 : : }
1466 [ + - ]: 282 : set_metric("fdcache_bytes", fdcache_mb*1024.0*1024.0);
1467 [ + - ]: 282 : set_metric("fdcache_count", fdcache_count);
1468 [ + - ]: 282 : set_metric("fdcache_prefetch_bytes", prefetch_mb*1024.0*1024.0);
1469 [ + - ]: 282 : set_metric("fdcache_prefetch_count", prefetch_count);
1470 : 282 : }
1471 : :
1472 : 208 : void intern(const string& a, const string& b, string fd, off_t sz,
1473 : : bool requested_p, double lat)
1474 : : {
1475 : 208 : {
1476 : 208 : unique_lock<mutex> lock(fdcache_lock);
1477 : 208 : time_t now = time(NULL);
1478 : : // there is a chance it's already in here, just wasn't found last time
1479 : : // if so, there's nothing to do but count our luck
1480 [ + - ]: 208 : auto i = entries.find(make_pair(a,b));
1481 [ - + ]: 208 : if (i != entries.end())
1482 : : {
1483 [ # # # # : 0 : inc_metric("fdcache_op_count","op","redundant_intern");
# # # # #
# # # # #
# # ]
1484 [ # # ]: 0 : if (requested_p) i->second.request_count ++; // repeat prefetch doesn't count
1485 : 0 : i->second.freshness = now;
1486 : : // We need to nuke the temp file, since interning passes
1487 : : // responsibility over the path to this structure. It is
1488 : : // possible that the caller still has an fd open, but that's
1489 : : // OK.
1490 : 0 : unlink (fd.c_str());
1491 : 0 : return;
1492 : : }
1493 : 208 : double mb = (sz+65535)/1048576.0; // round up to 64K block
1494 : 208 : fdcache_entry n = { .fd=fd, .fd_size_mb=mb,
1495 : 208 : .freshness=now, .request_count = requested_p?1U:0U,
1496 [ + - + + ]: 208 : .latency=lat};
1497 [ + - + - : 208 : entries.insert(make_pair(make_pair(a,b),n));
+ - ]
1498 : :
1499 [ + + ]: 208 : if (requested_p)
1500 [ + - + - : 320 : inc_metric("fdcache_op_count","op","enqueue");
+ - + - -
+ - + - -
- - ]
1501 : : else
1502 [ + - + - : 144 : inc_metric("fdcache_op_count","op","prefetch_enqueue");
+ - + - -
+ + - - -
- - ]
1503 : :
1504 [ + + ]: 208 : if (verbose > 3)
1505 [ + - + - : 534 : obatched(clog) << "fdcache interned a=" << a << " b=" << b
- - ]
1506 [ + - + - : 178 : << " fd=" << fd << " mb=" << mb << " front=" << requested_p
+ - + - +
- + - + -
+ - ]
1507 [ + - + - : 178 : << " latency=" << lat << endl;
+ - ]
1508 : :
1509 [ + - ]: 208 : set_metrics();
1510 : 208 : }
1511 : :
1512 : : // NB: we age the cache at lookup time too
1513 [ + - - + : 208 : if (statfs_free_enough_p(tmpdir, "tmpdir", fdcache_mintmp))
- + ]
1514 : : {
1515 [ # # # # : 0 : inc_metric("fdcache_op_count","op","emerg-flush");
# # # # #
# # # #
# ]
1516 [ # # ]: 0 : obatched(clog) << "fdcache emergency flush for filling tmpdir" << endl;
1517 : 0 : this->limit(0); // emergency flush
1518 : : }
1519 : : else // age cache normally
1520 : 208 : this->limit(max_mbs);
1521 : : }
1522 : :
1523 : 740 : int lookup(const string& a, const string& b)
1524 : : {
1525 : 740 : int fd = -1;
1526 : 740 : {
1527 : 740 : unique_lock<mutex> lock(fdcache_lock);
1528 [ + - ]: 740 : auto i = entries.find(make_pair(a,b));
1529 [ + + ]: 740 : if (i != entries.end())
1530 : : {
1531 [ + + ]: 576 : if (i->second.request_count == 0) // was a prefetch!
1532 : : {
1533 [ + - + - ]: 16 : inc_metric("fdcache_prefetch_saved_milliseconds_count");
1534 [ + - + - ]: 32 : add_metric("fdcache_prefetch_saved_milliseconds_sum", i->second.latency*1000.);
1535 : : }
1536 : 576 : i->second.request_count ++;
1537 : 576 : i->second.freshness = time(NULL);
1538 : : // brag about our success
1539 [ + - + - : 1152 : inc_metric("fdcache_op_count","op","prefetch_access"); // backward compat
+ - + - -
+ - + - -
- - ]
1540 [ + - + - ]: 576 : inc_metric("fdcache_saved_milliseconds_count");
1541 [ + - + - ]: 576 : add_metric("fdcache_saved_milliseconds_sum", i->second.latency*1000.);
1542 [ + - ]: 740 : fd = open(i->second.fd.c_str(), O_RDONLY);
1543 : : }
1544 : 0 : }
1545 : :
1546 [ + + ]: 740 : if (fd >= 0)
1547 [ + - + - : 1152 : inc_metric("fdcache_op_count","op","lookup_hit");
+ - - + -
+ - - -
- ]
1548 : : else
1549 [ + - + - : 328 : inc_metric("fdcache_op_count","op","lookup_miss");
+ - - + -
+ - - -
- ]
1550 : :
1551 : : // NB: no need to age the cache after just a lookup
1552 : :
1553 : 740 : return fd;
1554 : : }
1555 : :
1556 : 226 : int probe(const string& a, const string& b) // just a cache residency check - don't modify state, don't open
1557 : : {
1558 : 226 : unique_lock<mutex> lock(fdcache_lock);
1559 [ + - ]: 226 : auto i = entries.find(make_pair(a,b));
1560 [ + + ]: 226 : if (i != entries.end()) {
1561 [ + - + - : 52 : inc_metric("fdcache_op_count","op","probe_hit");
+ - + - -
+ - + - -
- - ]
1562 : 26 : return true;
1563 : : } else {
1564 [ + - + - : 400 : inc_metric("fdcache_op_count","op","probe_miss");
+ - + - -
+ - + - -
- - ]
1565 : 200 : return false;
1566 : : }
1567 : 226 : }
1568 : :
1569 : 0 : void clear(const string& a, const string& b)
1570 : : {
1571 : 0 : unique_lock<mutex> lock(fdcache_lock);
1572 [ # # ]: 0 : auto i = entries.find(make_pair(a,b));
1573 [ # # ]: 0 : if (i != entries.end()) {
1574 [ # # # # : 0 : inc_metric("fdcache_op_count","op",
# # # # #
# # # # #
# # # # ]
1575 [ # # ]: 0 : i->second.request_count > 0 ? "clear" : "prefetch_clear");
1576 : 0 : unlink (i->second.fd.c_str());
1577 : 0 : entries.erase(i);
1578 [ # # ]: 0 : set_metrics();
1579 : 0 : return;
1580 : : }
1581 : 0 : }
1582 : :
1583 : 356 : void limit(long maxmbs, bool metrics_p = true)
1584 : : {
1585 : 356 : time_t now = time(NULL);
1586 : :
1587 : : // avoid overly frequent limit operations
1588 [ + + + + ]: 356 : if (maxmbs > 0 && (now - this->last_cleaning) < 10) // probably not worth parametrizing
1589 : 208 : return;
1590 : 148 : this->last_cleaning = now;
1591 : :
1592 [ + + + - ]: 148 : if (verbose > 3 && (this->max_mbs != maxmbs))
1593 [ + - + - ]: 192 : obatched(clog) << "fdcache limited to maxmbs=" << maxmbs << endl;
1594 : :
1595 : 148 : unique_lock<mutex> lock(fdcache_lock);
1596 : :
1597 : 148 : this->max_mbs = maxmbs;
1598 : 148 : double total_mb = 0.0;
1599 : :
1600 : 148 : map<double, pair<string,string>> sorted_entries;
1601 [ + + ]: 356 : for (auto &i: entries)
1602 : : {
1603 : 208 : total_mb += i.second.fd_size_mb;
1604 : :
1605 : : // need a scalar quantity that combines these inputs in a sensible way:
1606 : : //
1607 : : // 1) freshness of this entry (last time it was accessed)
1608 : : // 2) size of this entry
1609 : : // 3) number of times it has been accessed (or if just prefetched with 0 accesses)
1610 : : // 4) latency it required to extract
1611 : : //
1612 : : // The lower the "score", the earlier garbage collection will
1613 : : // nuke it, so to prioritize entries for preservation, the
1614 : : // score should be higher, and vice versa.
1615 : 208 : time_t factor_1_freshness = (now - i.second.freshness); // seconds
1616 : 208 : double factor_2_size = i.second.fd_size_mb; // megabytes
1617 : 208 : unsigned factor_3_accesscount = i.second.request_count; // units
1618 : 208 : double factor_4_latency = i.second.latency; // seconds
1619 : :
1620 : : #if 0
1621 : : double score = - factor_1_freshness; // simple LRU
1622 : : #endif
1623 : :
1624 [ + + ]: 208 : double score = 0.
1625 : 208 : - log1p(factor_1_freshness) // penalize old file
1626 : 208 : - log1p(factor_2_size) // penalize large file
1627 : 208 : + factor_4_latency * factor_3_accesscount; // reward slow + repeatedly read files
1628 : :
1629 [ + + ]: 208 : if (verbose > 4)
1630 [ + - ]: 64 : obatched(clog) << "fdcache scored score=" << score
1631 [ + - + - ]: 64 : << " a=" << i.first.first << " b=" << i.first.second
1632 [ + - + - : 96 : << " f1=" << factor_1_freshness << " f2=" << factor_2_size
+ - + - +
- + - +
- ]
1633 [ + - + - : 32 : << " f3=" << factor_3_accesscount << " f4=" << factor_4_latency
+ - + - +
- ]
1634 : 32 : << endl;
1635 : :
1636 [ + - + - ]: 416 : sorted_entries.insert(make_pair(score, i.first));
1637 : : }
1638 : :
1639 : 148 : unsigned cleaned = 0;
1640 : 148 : unsigned entries_original = entries.size();
1641 : 148 : double cleaned_score_min = DBL_MAX;
1642 : 148 : double cleaned_score_max = DBL_MIN;
1643 : :
1644 : : // drop as many entries[] as needed to bring total mb down to the threshold
1645 [ + + ]: 356 : for (auto &i: sorted_entries) // in increasing score order!
1646 : : {
1647 [ - + ]: 208 : if (this->max_mbs > 0 // if this is not a "clear entire table"
1648 [ # # ]: 0 : && total_mb < this->max_mbs) // we've cleared enough to meet threshold
1649 : : break; // stop clearing
1650 : :
1651 [ - + ]: 208 : auto j = entries.find(i.second);
1652 [ - + ]: 208 : if (j == entries.end())
1653 : 0 : continue; // should not happen
1654 : :
1655 [ + + ]: 208 : if (cleaned == 0)
1656 : 32 : cleaned_score_min = i.first;
1657 : 208 : cleaned++;
1658 : 208 : cleaned_score_max = i.first;
1659 : :
1660 [ + + ]: 208 : if (verbose > 3)
1661 [ + - + - ]: 534 : obatched(clog) << "fdcache evicted score=" << i.first
1662 [ + - + - ]: 356 : << " a=" << i.second.first << " b=" << i.second.second
1663 [ + - + - : 534 : << " fd=" << j->second.fd << " mb=" << j->second.fd_size_mb
+ - + - +
- + - ]
1664 [ + - + - : 178 : << " rq=" << j->second.request_count << " lat=" << j->second.latency
+ - + - ]
1665 [ + - + - : 178 : << " fr=" << (now - j->second.freshness)
+ - ]
1666 : 178 : << endl;
1667 [ - + ]: 208 : if (metrics_p)
1668 [ # # # # : 0 : inc_metric("fdcache_op_count","op","evict");
# # # # #
# # # # #
# # ]
1669 : :
1670 : 208 : total_mb -= j->second.fd_size_mb;
1671 : 208 : unlink (j->second.fd.c_str());
1672 : 208 : entries.erase(j);
1673 : : }
1674 : :
1675 [ + + ]: 148 : if (metrics_p)
1676 [ + - + - : 148 : inc_metric("fdcache_op_count","op","evict_cycle");
+ - + - -
+ - + - -
- - ]
1677 : :
1678 [ + - + + ]: 148 : if (verbose > 1 && cleaned > 0)
1679 : : {
1680 [ + - + - : 96 : obatched(clog) << "fdcache evicted num=" << cleaned << " of=" << entries_original
+ - + - ]
1681 [ + - + - : 32 : << " min=" << cleaned_score_min << " max=" << cleaned_score_max
+ - + - +
- ]
1682 : 32 : << endl;
1683 : : }
1684 : :
1685 [ + + + - ]: 148 : if (metrics_p) set_metrics();
1686 : 148 : }
1687 : :
1688 : :
1689 : 74 : ~libarchive_fdcache()
1690 : : {
1691 : : // unlink any fdcache entries in $TMPDIR
1692 : : // don't update metrics; those globals may be already destroyed
1693 : 74 : limit(0, false);
1694 : 74 : }
1695 : : };
1696 : : static libarchive_fdcache fdcache;
1697 : :
1698 : : /* Search ELF_FD for an ELF/DWARF section with name SECTION.
1699 : : If found copy the section to a temporary file and return
1700 : : its file descriptor, otherwise return -1.
1701 : :
1702 : : The temporary file's mtime will be set to PARENT_MTIME.
1703 : : B_SOURCE should be a description of the parent file suitable
1704 : : for printing to the log. */
1705 : :
1706 : : static int
1707 : 12 : extract_section (int elf_fd, int64_t parent_mtime,
1708 : : const string& b_source, const string& section,
1709 : : const timespec& extract_begin)
1710 : : {
1711 : : /* Search the fdcache. */
1712 : 12 : struct stat fs;
1713 : 12 : int fd = fdcache.lookup (b_source, section);
1714 [ - + ]: 12 : if (fd >= 0)
1715 : : {
1716 [ # # ]: 0 : if (fstat (fd, &fs) != 0)
1717 : : {
1718 [ # # ]: 0 : if (verbose)
1719 [ # # ]: 0 : obatched (clog) << "cannot fstate fdcache "
1720 [ # # # # : 0 : << b_source << " " << section << endl;
# # ]
1721 : 0 : close (fd);
1722 : 0 : return -1;
1723 : : }
1724 [ # # ]: 0 : if ((int64_t) fs.st_mtime != parent_mtime)
1725 : : {
1726 [ # # ]: 0 : if (verbose)
1727 [ # # ]: 0 : obatched(clog) << "mtime mismatch for "
1728 [ # # # # : 0 : << b_source << " " << section << endl;
# # ]
1729 : 0 : close (fd);
1730 : 0 : return -1;
1731 : : }
1732 : : /* Success. */
1733 : : return fd;
1734 : : }
1735 : :
1736 : 12 : Elf *elf = elf_begin (elf_fd, ELF_C_READ_MMAP_PRIVATE, NULL);
1737 [ - + ]: 12 : if (elf == NULL)
1738 : : return -1;
1739 : :
1740 : : /* Try to find the section and copy the contents into a separate file. */
1741 : 12 : try
1742 : : {
1743 : 12 : size_t shstrndx;
1744 [ + - ]: 12 : int rc = elf_getshdrstrndx (elf, &shstrndx);
1745 [ - + ]: 12 : if (rc < 0)
1746 [ # # # # ]: 0 : throw elfutils_exception (rc, "getshdrstrndx");
1747 : :
1748 : : Elf_Scn *scn = NULL;
1749 : 432 : while (true)
1750 : : {
1751 [ + - ]: 222 : scn = elf_nextscn (elf, scn);
1752 [ + - ]: 222 : if (scn == NULL)
1753 : : break;
1754 : 222 : GElf_Shdr shdr_storage;
1755 [ + - ]: 222 : GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_storage);
1756 [ + - ]: 222 : if (shdr == NULL)
1757 : : break;
1758 : :
1759 [ + - ]: 222 : const char *scn_name = elf_strptr (elf, shstrndx, shdr->sh_name);
1760 [ + - ]: 222 : if (scn_name == NULL)
1761 : : break;
1762 [ + + ]: 222 : if (scn_name == section)
1763 : : {
1764 : 12 : Elf_Data *data = NULL;
1765 : :
1766 : : /* We found the desired section. */
1767 [ + - ]: 12 : data = elf_rawdata (scn, NULL);
1768 [ - + ]: 12 : if (data == NULL)
1769 [ # # # # : 0 : throw elfutils_exception (elf_errno (), "elfraw_data");
# # ]
1770 [ + + ]: 12 : if (data->d_buf == NULL)
1771 : : {
1772 [ + - + - ]: 8 : obatched(clog) << "section " << section
1773 [ + - + - ]: 4 : << " is empty" << endl;
1774 : 4 : break;
1775 : : }
1776 : :
1777 : : /* Create temporary file containing the section. */
1778 : 8 : char *tmppath = NULL;
1779 : 8 : rc = asprintf (&tmppath, "%s/debuginfod-section.XXXXXX", tmpdir.c_str());
1780 [ - + ]: 8 : if (rc < 0)
1781 [ # # # # ]: 0 : throw libc_exception (ENOMEM, "cannot allocate tmppath");
1782 : 8 : defer_dtor<void*,void> tmmpath_freer (tmppath, free);
1783 [ + - ]: 8 : fd = mkstemp (tmppath);
1784 [ - + ]: 8 : if (fd < 0)
1785 [ # # # # ]: 0 : throw libc_exception (errno, "cannot create temporary file");
1786 : :
1787 [ + - ]: 8 : ssize_t res = write_retry (fd, data->d_buf, data->d_size);
1788 [ + - - + ]: 8 : if (res < 0 || (size_t) res != data->d_size) {
1789 [ # # ]: 0 : close (fd);
1790 : 0 : unlink (tmppath);
1791 [ # # # # ]: 0 : throw libc_exception (errno, "cannot write to temporary file");
1792 : : }
1793 : :
1794 : : /* Set mtime to be the same as the parent file's mtime. */
1795 : 8 : struct timespec tvs[2];
1796 [ - + ]: 8 : if (fstat (elf_fd, &fs) != 0) {
1797 [ # # ]: 0 : close (fd);
1798 : 0 : unlink (tmppath);
1799 [ # # # # ]: 0 : throw libc_exception (errno, "cannot fstat file");
1800 : : }
1801 : :
1802 : 8 : tvs[0].tv_sec = 0;
1803 : 8 : tvs[0].tv_nsec = UTIME_OMIT;
1804 : 8 : tvs[1] = fs.st_mtim;
1805 : 8 : (void) futimens (fd, tvs);
1806 : :
1807 : 8 : struct timespec extract_end;
1808 : 8 : clock_gettime (CLOCK_MONOTONIC, &extract_end);
1809 : 8 : double extract_time = (extract_end.tv_sec - extract_begin.tv_sec)
1810 : 8 : + (extract_end.tv_nsec - extract_begin.tv_nsec)/1.e9;
1811 : :
1812 : : /* Add to fdcache. */
1813 [ + - + - ]: 8 : fdcache.intern (b_source, section, tmppath, data->d_size, true, extract_time);
1814 : 8 : break;
1815 : 12 : }
1816 : 210 : }
1817 : : }
1818 [ - - ]: 0 : catch (const reportable_exception &e)
1819 : : {
1820 [ - - ]: 0 : e.report (clog);
1821 [ - - ]: 0 : close (fd);
1822 : 0 : fd = -1;
1823 : 0 : }
1824 : :
1825 : 12 : elf_end (elf);
1826 : : return fd;
1827 : : }
1828 : :
1829 : : static struct MHD_Response*
1830 : 583 : handle_buildid_f_match (bool internal_req_t,
1831 : : int64_t b_mtime,
1832 : : const string& b_source0,
1833 : : const string& section,
1834 : : int *result_fd)
1835 : : {
1836 : 583 : (void) internal_req_t; // ignored
1837 : :
1838 : 583 : struct timespec extract_begin;
1839 : 583 : clock_gettime (CLOCK_MONOTONIC, &extract_begin);
1840 : :
1841 : 583 : int fd = open(b_source0.c_str(), O_RDONLY);
1842 [ - + ]: 583 : if (fd < 0)
1843 [ # # # # : 0 : throw libc_exception (errno, string("open ") + b_source0);
# # # # ]
1844 : :
1845 : : // NB: use manual close(2) in error case instead of defer_dtor, because
1846 : : // in the normal case, we want to hand the fd over to libmicrohttpd for
1847 : : // file transfer.
1848 : :
1849 : 583 : struct stat s;
1850 : 583 : int rc = fstat(fd, &s);
1851 [ - + ]: 583 : if (rc < 0)
1852 : : {
1853 : 0 : close(fd);
1854 [ # # # # : 0 : throw libc_exception (errno, string("fstat ") + b_source0);
# # # # ]
1855 : : }
1856 : :
1857 [ - + ]: 583 : if ((int64_t) s.st_mtime != b_mtime)
1858 : : {
1859 [ # # ]: 0 : if (verbose)
1860 [ # # # # ]: 0 : obatched(clog) << "mtime mismatch for " << b_source0 << endl;
1861 : 0 : close(fd);
1862 : 0 : return 0;
1863 : : }
1864 : :
1865 [ + + ]: 583 : if (!section.empty ())
1866 : : {
1867 : 6 : int scn_fd = extract_section (fd, s.st_mtime, b_source0, section, extract_begin);
1868 : 6 : close (fd);
1869 : :
1870 [ + + ]: 6 : if (scn_fd >= 0)
1871 : 4 : fd = scn_fd;
1872 : : else
1873 : : {
1874 [ + - ]: 2 : if (verbose)
1875 [ + - ]: 6 : obatched (clog) << "cannot find section " << section
1876 [ + - + - : 2 : << " for " << b_source0 << endl;
+ - ]
1877 : 2 : return 0;
1878 : : }
1879 : :
1880 : 4 : rc = fstat(fd, &s);
1881 [ - + ]: 4 : if (rc < 0)
1882 : : {
1883 : 0 : close (fd);
1884 [ # # # # : 0 : throw libc_exception (errno, string ("fstat ") + b_source0
# # # # #
# # # #
# ]
1885 [ # # # # : 0 : + string (" ") + section);
# # # # #
# ]
1886 : : }
1887 : : }
1888 : :
1889 : 581 : struct MHD_Response* r = MHD_create_response_from_fd ((uint64_t) s.st_size, fd);
1890 [ + - + - : 1162 : inc_metric ("http_responses_total","result","file");
+ - - + -
+ - - -
- ]
1891 [ - + ]: 581 : if (r == 0)
1892 : : {
1893 [ # # ]: 0 : if (verbose)
1894 [ # # ]: 0 : obatched(clog) << "cannot create fd-response for " << b_source0
1895 [ # # # # : 0 : << " section=" << section << endl;
# # ]
1896 : 0 : close(fd);
1897 : : }
1898 : : else
1899 : : {
1900 : 581 : add_mhd_response_header (r, "Content-Type", "application/octet-stream");
1901 [ + - ]: 581 : add_mhd_response_header (r, "X-DEBUGINFOD-SIZE",
1902 : 581 : to_string(s.st_size).c_str());
1903 : 581 : add_mhd_response_header (r, "X-DEBUGINFOD-FILE", b_source0.c_str());
1904 : 581 : add_mhd_last_modified (r, s.st_mtime);
1905 [ + - ]: 581 : if (verbose > 1)
1906 [ + - + - : 1162 : obatched(clog) << "serving file " << b_source0 << " section=" << section << endl;
+ - + - ]
1907 : : /* libmicrohttpd will close it. */
1908 [ - + ]: 581 : if (result_fd)
1909 : 581 : *result_fd = fd;
1910 : : }
1911 : :
1912 : : return r;
1913 : : }
1914 : :
1915 : : // For security/portability reasons, many distro-package archives have
1916 : : // a "./" in front of path names; others have nothing, others have
1917 : : // "/". Canonicalize them all to a single leading "/", with the
1918 : : // assumption that this matches the dwarf-derived file names too.
1919 : 974 : string canonicalized_archive_entry_pathname(struct archive_entry *e)
1920 : : {
1921 : 974 : string fn = archive_entry_pathname(e);
1922 [ - + ]: 974 : if (fn.size() == 0)
1923 : 0 : return fn;
1924 [ - + ]: 974 : if (fn[0] == '/')
1925 : 0 : return fn;
1926 [ + + ]: 974 : if (fn[0] == '.')
1927 [ + - ]: 776 : return fn.substr(1);
1928 : : else
1929 [ + - + - : 396 : return string("/")+fn;
- - ]
1930 : 974 : }
1931 : :
1932 : :
1933 : :
1934 : : static struct MHD_Response*
1935 : 786 : handle_buildid_r_match (bool internal_req_p,
1936 : : int64_t b_mtime,
1937 : : const string& b_source0,
1938 : : const string& b_source1,
1939 : : const string& section,
1940 : : int *result_fd)
1941 : : {
1942 : 786 : struct timespec extract_begin;
1943 : 786 : clock_gettime (CLOCK_MONOTONIC, &extract_begin);
1944 : :
1945 : 786 : struct stat fs;
1946 : 786 : int rc = stat (b_source0.c_str(), &fs);
1947 [ + + ]: 786 : if (rc != 0)
1948 [ + - + - : 116 : throw libc_exception (errno, string("stat ") + b_source0);
+ - - + ]
1949 : :
1950 [ - + ]: 728 : if ((int64_t) fs.st_mtime != b_mtime)
1951 : : {
1952 [ # # ]: 0 : if (verbose)
1953 [ # # # # ]: 0 : obatched(clog) << "mtime mismatch for " << b_source0 << endl;
1954 : 0 : return 0;
1955 : : }
1956 : :
1957 : : // check for a match in the fdcache first
1958 : 728 : int fd = fdcache.lookup(b_source0, b_source1);
1959 [ + + ]: 728 : while (fd >= 0) // got one!; NB: this is really an if() with a possible branch out to the end
1960 : : {
1961 : 576 : rc = fstat(fd, &fs);
1962 [ - + ]: 576 : if (rc < 0) // disappeared?
1963 : : {
1964 [ # # ]: 0 : if (verbose)
1965 [ # # # # ]: 0 : obatched(clog) << "cannot fstat fdcache " << b_source0 << endl;
1966 : 0 : close(fd);
1967 : 0 : fdcache.clear(b_source0, b_source1);
1968 : : break; // branch out of if "loop", to try new libarchive fetch attempt
1969 : : }
1970 : :
1971 [ + + ]: 576 : if (!section.empty ())
1972 : : {
1973 [ + - + - ]: 2 : int scn_fd = extract_section (fd, fs.st_mtime,
1974 [ + - - + ]: 4 : b_source0 + ":" + b_source1,
1975 : : section, extract_begin);
1976 : 2 : close (fd);
1977 [ - + ]: 2 : if (scn_fd >= 0)
1978 : 0 : fd = scn_fd;
1979 : : else
1980 : : {
1981 [ + - ]: 2 : if (verbose)
1982 [ + - ]: 6 : obatched (clog) << "cannot find section " << section
1983 : : << " for archive " << b_source0
1984 [ + - + - : 2 : << " file " << b_source1 << endl;
+ - + - +
- ]
1985 : 2 : return 0;
1986 : : }
1987 : :
1988 : 0 : rc = fstat(fd, &fs);
1989 [ # # ]: 0 : if (rc < 0)
1990 : : {
1991 : 0 : close (fd);
1992 [ # # # # ]: 0 : throw libc_exception (errno,
1993 [ # # # # : 0 : string ("fstat archive ") + b_source0 + string (" file ") + b_source1
# # # # #
# # # # #
# # # # #
# # # #
# ]
1994 [ # # # # : 0 : + string (" section ") + section);
# # # # #
# ]
1995 : : }
1996 : : }
1997 : :
1998 : 574 : struct MHD_Response* r = MHD_create_response_from_fd (fs.st_size, fd);
1999 [ - + ]: 574 : if (r == 0)
2000 : : {
2001 [ # # ]: 0 : if (verbose)
2002 [ # # # # ]: 0 : obatched(clog) << "cannot create fd-response for " << b_source0 << endl;
2003 : 0 : close(fd);
2004 : : break; // branch out of if "loop", to try new libarchive fetch attempt
2005 : : }
2006 : :
2007 [ + - + - : 1148 : inc_metric ("http_responses_total","result","archive fdcache");
+ - - + -
+ - - -
- ]
2008 : :
2009 : 574 : add_mhd_response_header (r, "Content-Type", "application/octet-stream");
2010 [ + - ]: 574 : add_mhd_response_header (r, "X-DEBUGINFOD-SIZE",
2011 : 574 : to_string(fs.st_size).c_str());
2012 : 574 : add_mhd_response_header (r, "X-DEBUGINFOD-ARCHIVE", b_source0.c_str());
2013 : 574 : add_mhd_response_header (r, "X-DEBUGINFOD-FILE", b_source1.c_str());
2014 : 574 : add_mhd_last_modified (r, fs.st_mtime);
2015 [ + - ]: 574 : if (verbose > 1)
2016 [ + - ]: 1722 : obatched(clog) << "serving fdcache archive " << b_source0
2017 : : << " file " << b_source1
2018 [ + - + - : 574 : << " section=" << section << endl;
+ - + - +
- ]
2019 : : /* libmicrohttpd will close it. */
2020 [ + - ]: 574 : if (result_fd)
2021 : 574 : *result_fd = fd;
2022 : : return r;
2023 : : // NB: see, we never go around the 'loop' more than once
2024 : : }
2025 : :
2026 : : // no match ... grumble, must process the archive
2027 : 152 : string archive_decoder = "/dev/null";
2028 [ + - - - ]: 152 : string archive_extension = "";
2029 [ + + ]: 342 : for (auto&& arch : scan_archives)
2030 [ + + ]: 190 : if (string_endswith(b_source0, arch.first))
2031 : : {
2032 [ + - ]: 152 : archive_extension = arch.first;
2033 [ + - ]: 342 : archive_decoder = arch.second;
2034 : : }
2035 : 152 : FILE* fp;
2036 : :
2037 : 152 : defer_dtor<FILE*,int>::dtor_fn dfn;
2038 [ + + ]: 152 : if (archive_decoder != "cat")
2039 : : {
2040 [ + - + - : 48 : string popen_cmd = archive_decoder + " " + shell_escape(b_source0);
+ - - + -
- - - ]
2041 [ + - ]: 24 : fp = popen (popen_cmd.c_str(), "r"); // "e" O_CLOEXEC?
2042 : 24 : dfn = pclose;
2043 [ - + ]: 24 : if (fp == NULL)
2044 [ # # # # : 0 : throw libc_exception (errno, string("popen ") + popen_cmd);
# # # # ]
2045 : 24 : }
2046 : : else
2047 : : {
2048 [ + - ]: 128 : fp = fopen (b_source0.c_str(), "r");
2049 : 128 : dfn = fclose;
2050 [ - + ]: 128 : if (fp == NULL)
2051 [ # # # # : 0 : throw libc_exception (errno, string("fopen ") + b_source0);
# # # # ]
2052 : : }
2053 : 152 : defer_dtor<FILE*,int> fp_closer (fp, dfn);
2054 : :
2055 : 152 : struct archive *a;
2056 [ + - ]: 152 : a = archive_read_new();
2057 [ - + ]: 152 : if (a == NULL)
2058 [ # # # # ]: 0 : throw archive_exception("cannot create archive reader");
2059 : 152 : defer_dtor<struct archive*,int> archive_closer (a, archive_read_free);
2060 : :
2061 [ + - ]: 152 : rc = archive_read_support_format_all(a);
2062 [ - + ]: 152 : if (rc != ARCHIVE_OK)
2063 [ # # # # ]: 0 : throw archive_exception(a, "cannot select all format");
2064 [ + - ]: 152 : rc = archive_read_support_filter_all(a);
2065 [ - + ]: 152 : if (rc != ARCHIVE_OK)
2066 [ # # # # ]: 0 : throw archive_exception(a, "cannot select all filters");
2067 : :
2068 [ + - ]: 152 : rc = archive_read_open_FILE (a, fp);
2069 [ - + ]: 152 : if (rc != ARCHIVE_OK)
2070 : : {
2071 [ # # # # : 0 : obatched(clog) << "cannot open archive from pipe " << b_source0 << endl;
# # ]
2072 [ # # # # ]: 0 : throw archive_exception(a, "cannot open archive from pipe");
2073 : : }
2074 : :
2075 : : // archive traversal is in three stages, no, four stages:
2076 : : // 1) skip entries whose names do not match the requested one
2077 : : // 2) extract the matching entry name (set r = result)
2078 : : // 3) extract some number of prefetched entries (just into fdcache)
2079 : : // 4) abort any further processing
2080 : 152 : struct MHD_Response* r = 0; // will set in stage 2
2081 [ + + ]: 152 : unsigned prefetch_count =
2082 : : internal_req_p ? 0 : fdcache_prefetch; // will decrement in stage 3
2083 : :
2084 [ + + ]: 1536 : while(r == 0 || prefetch_count > 0) // stage 1, 2, or 3
2085 : : {
2086 [ + - ]: 1516 : if (interrupted)
2087 : : break;
2088 : :
2089 : 1516 : struct archive_entry *e;
2090 [ + - ]: 1516 : rc = archive_read_next_header (a, &e);
2091 [ + + ]: 1516 : if (rc != ARCHIVE_OK)
2092 : : break;
2093 : :
2094 [ + - + + ]: 1384 : if (! S_ISREG(archive_entry_mode (e))) // skip non-files completely
2095 : 1084 : continue;
2096 : :
2097 [ + - ]: 300 : string fn = canonicalized_archive_entry_pathname (e);
2098 [ + + + + ]: 300 : if ((r == 0) && (fn != b_source1)) // stage 1
2099 : 76 : continue;
2100 : :
2101 [ + - + + ]: 224 : if (fdcache.probe (b_source0, fn) && // skip if already interned
2102 [ - + ]: 24 : fn != b_source1) // but only if we'd just be prefetching, PR29474
2103 : 24 : continue;
2104 : :
2105 : : // extract this file to a temporary file
2106 : 200 : char* tmppath = NULL;
2107 : 200 : rc = asprintf (&tmppath, "%s/debuginfod-fdcache.XXXXXX", tmpdir.c_str());
2108 [ - + ]: 200 : if (rc < 0)
2109 [ # # # # ]: 0 : throw libc_exception (ENOMEM, "cannot allocate tmppath");
2110 : 200 : defer_dtor<void*,void> tmmpath_freer (tmppath, free);
2111 [ + - ]: 200 : fd = mkstemp (tmppath);
2112 [ - + ]: 200 : if (fd < 0)
2113 [ # # # # ]: 0 : throw libc_exception (errno, "cannot create temporary file");
2114 : : // NB: don't unlink (tmppath), as fdcache will take charge of it.
2115 : :
2116 : : // NB: this can take many uninterruptible seconds for a huge file
2117 [ + - ]: 200 : rc = archive_read_data_into_fd (a, fd);
2118 [ - + ]: 200 : if (rc != ARCHIVE_OK) // e.g. ENOSPC!
2119 : : {
2120 [ # # ]: 0 : close (fd);
2121 : 0 : unlink (tmppath);
2122 [ # # # # ]: 0 : throw archive_exception(a, "cannot extract file");
2123 : : }
2124 : :
2125 : : // Set the mtime so the fdcache file mtimes, even prefetched ones,
2126 : : // propagate to future webapi clients.
2127 : 200 : struct timespec tvs[2];
2128 : 200 : tvs[0].tv_sec = 0;
2129 : 200 : tvs[0].tv_nsec = UTIME_OMIT;
2130 [ + - ]: 200 : tvs[1].tv_sec = archive_entry_mtime(e);
2131 [ + - ]: 200 : tvs[1].tv_nsec = archive_entry_mtime_nsec(e);
2132 : 200 : (void) futimens (fd, tvs); /* best effort */
2133 : :
2134 : 200 : struct timespec extract_end;
2135 : 200 : clock_gettime (CLOCK_MONOTONIC, &extract_end);
2136 : 200 : double extract_time = (extract_end.tv_sec - extract_begin.tv_sec)
2137 : 200 : + (extract_end.tv_nsec - extract_begin.tv_nsec)/1.e9;
2138 : :
2139 [ + + ]: 200 : if (r != 0) // stage 3
2140 : : {
2141 : : // NB: now we know we have a complete reusable file; make fdcache
2142 : : // responsible for unlinking it later.
2143 [ + - + - : 48 : fdcache.intern(b_source0, fn,
+ - ]
2144 : : tmppath, archive_entry_size(e),
2145 : : false, extract_time); // prefetched ones go to the prefetch cache
2146 : 48 : prefetch_count --;
2147 [ + - ]: 48 : close (fd); // we're not saving this fd to make a mhd-response from!
2148 : 48 : continue;
2149 : : }
2150 : :
2151 : : // NB: now we know we have a complete reusable file; make fdcache
2152 : : // responsible for unlinking it later.
2153 [ + - + - : 152 : fdcache.intern(b_source0, b_source1,
+ - ]
2154 : : tmppath, archive_entry_size(e),
2155 : : true, extract_time); // requested ones go to the front of the line
2156 : :
2157 [ + + ]: 152 : if (!section.empty ())
2158 : : {
2159 [ + - + - ]: 4 : int scn_fd = extract_section (fd, b_mtime,
2160 [ + - + - : 8 : b_source0 + ":" + b_source1,
- + ]
2161 : : section, extract_begin);
2162 [ + - ]: 4 : close (fd);
2163 [ + - ]: 4 : if (scn_fd >= 0)
2164 : 4 : fd = scn_fd;
2165 : : else
2166 : : {
2167 [ # # ]: 0 : if (verbose)
2168 [ # # # # ]: 0 : obatched (clog) << "cannot find section " << section
2169 : : << " for archive " << b_source0
2170 [ # # # # : 0 : << " file " << b_source1 << endl;
# # # # #
# ]
2171 : 0 : return 0;
2172 : : }
2173 : :
2174 : 4 : rc = fstat(fd, &fs);
2175 [ - + ]: 4 : if (rc < 0)
2176 : : {
2177 [ # # ]: 0 : close (fd);
2178 [ # # # # ]: 0 : throw libc_exception (errno,
2179 [ # # # # : 0 : string ("fstat ") + b_source0 + string (" ") + section);
# # # # #
# # # # #
# # # # #
# ]
2180 : : }
2181 [ + - ]: 4 : r = MHD_create_response_from_fd (fs.st_size, fd);
2182 : : }
2183 : : else
2184 [ + - + - ]: 148 : r = MHD_create_response_from_fd (archive_entry_size(e), fd);
2185 : :
2186 [ + - + - : 304 : inc_metric ("http_responses_total","result",archive_extension + " archive");
+ - + - -
+ + + - -
- - ]
2187 [ - + ]: 152 : if (r == 0)
2188 : : {
2189 [ # # ]: 0 : if (verbose)
2190 [ # # # # : 0 : obatched(clog) << "cannot create fd-response for " << b_source0 << endl;
# # ]
2191 [ # # ]: 0 : close(fd);
2192 : 0 : break; // assume no chance of better luck around another iteration; no other copies of same file
2193 : : }
2194 : : else
2195 : : {
2196 [ + - ]: 152 : add_mhd_response_header (r, "Content-Type",
2197 : : "application/octet-stream");
2198 [ + - ]: 152 : add_mhd_response_header (r, "X-DEBUGINFOD-SIZE",
2199 [ + - + - ]: 152 : to_string(archive_entry_size(e)).c_str());
2200 [ + - ]: 152 : add_mhd_response_header (r, "X-DEBUGINFOD-ARCHIVE", b_source0.c_str());
2201 [ + - ]: 152 : add_mhd_response_header (r, "X-DEBUGINFOD-FILE", b_source1.c_str());
2202 [ + - + - ]: 152 : add_mhd_last_modified (r, archive_entry_mtime(e));
2203 [ + - ]: 152 : if (verbose > 1)
2204 [ + - + - ]: 456 : obatched(clog) << "serving archive " << b_source0
2205 : : << " file " << b_source1
2206 [ + - + - : 152 : << " section=" << section << endl;
+ - + - +
- ]
2207 : : /* libmicrohttpd will close it. */
2208 [ + - ]: 152 : if (result_fd)
2209 : 152 : *result_fd = fd;
2210 : 152 : continue;
2211 : : }
2212 [ - - - - : 1816 : }
+ + ]
2213 : :
2214 : : // XXX: rpm/file not found: delete this R entry?
2215 : : return r;
2216 [ - + + + ]: 880 : }
2217 : :
2218 : :
2219 : : static struct MHD_Response*
2220 : 1369 : handle_buildid_match (bool internal_req_p,
2221 : : int64_t b_mtime,
2222 : : const string& b_stype,
2223 : : const string& b_source0,
2224 : : const string& b_source1,
2225 : : const string& section,
2226 : : int *result_fd)
2227 : : {
2228 : 1369 : try
2229 : : {
2230 [ + + ]: 1369 : if (b_stype == "F")
2231 [ + - ]: 583 : return handle_buildid_f_match(internal_req_p, b_mtime, b_source0,
2232 : : section, result_fd);
2233 [ + - ]: 786 : else if (b_stype == "R")
2234 [ + + ]: 786 : return handle_buildid_r_match(internal_req_p, b_mtime, b_source0,
2235 : : b_source1, section, result_fd);
2236 : : }
2237 [ - + ]: 58 : catch (const reportable_exception &e)
2238 : : {
2239 [ + - ]: 58 : e.report(clog);
2240 : : // Report but swallow libc etc. errors here; let the caller
2241 : : // iterate to other matches of the content.
2242 : 58 : }
2243 : :
2244 : : return 0;
2245 : : }
2246 : :
2247 : :
2248 : : static int
2249 : 3236 : debuginfod_find_progress (debuginfod_client *, long a, long b)
2250 : : {
2251 [ - + ]: 3236 : if (verbose > 4)
2252 [ # # # # : 0 : obatched(clog) << "federated debuginfod progress=" << a << "/" << b << endl;
# # # # ]
2253 : :
2254 : 3236 : return interrupted;
2255 : : }
2256 : :
2257 : :
2258 : : // a little lru pool of debuginfod_client*s for reuse between query threads
2259 : :
2260 : : mutex dc_pool_lock;
2261 : : deque<debuginfod_client*> dc_pool;
2262 : :
2263 : 620 : debuginfod_client* debuginfod_pool_begin()
2264 : : {
2265 : 620 : unique_lock<mutex> lock(dc_pool_lock);
2266 [ + + ]: 620 : if (dc_pool.size() > 0)
2267 : : {
2268 [ + - + - : 1188 : inc_metric("dc_pool_op_count","op","begin-reuse");
+ - + - -
+ - + - -
- - ]
2269 : 594 : debuginfod_client *c = dc_pool.front();
2270 : 594 : dc_pool.pop_front();
2271 : 594 : return c;
2272 : : }
2273 [ + - + - : 52 : inc_metric("dc_pool_op_count","op","begin-new");
+ - + - -
+ - + - -
- - ]
2274 [ + - ]: 26 : return debuginfod_begin();
2275 : 620 : }
2276 : :
2277 : :
2278 : 146 : void debuginfod_pool_groom()
2279 : : {
2280 : 146 : unique_lock<mutex> lock(dc_pool_lock);
2281 [ + + ]: 172 : while (dc_pool.size() > 0)
2282 : : {
2283 [ + - + - : 52 : inc_metric("dc_pool_op_count","op","end");
+ - + - -
+ - + - -
- - ]
2284 [ + - ]: 26 : debuginfod_end(dc_pool.front());
2285 : 26 : dc_pool.pop_front();
2286 : : }
2287 : 146 : }
2288 : :
2289 : :
2290 : 620 : void debuginfod_pool_end(debuginfod_client* c)
2291 : : {
2292 : 620 : unique_lock<mutex> lock(dc_pool_lock);
2293 [ + - + - : 1240 : inc_metric("dc_pool_op_count","op","end-save");
+ - + - -
+ - + - -
- - ]
2294 [ + - ]: 620 : dc_pool.push_front(c); // accelerate reuse, vs. push_back
2295 : 620 : }
2296 : :
2297 : :
2298 : : static struct MHD_Response*
2299 : 1937 : handle_buildid (MHD_Connection* conn,
2300 : : const string& buildid /* unsafe */,
2301 : : string& artifacttype /* unsafe, cleanse on exception/return */,
2302 : : const string& suffix /* unsafe */,
2303 : : int *result_fd)
2304 : : {
2305 : : // validate artifacttype
2306 : 1937 : string atype_code;
2307 [ + + + - ]: 1937 : if (artifacttype == "debuginfo") atype_code = "D";
2308 [ + + + - ]: 1199 : else if (artifacttype == "executable") atype_code = "E";
2309 [ + + + - ]: 577 : else if (artifacttype == "source") atype_code = "S";
2310 [ + + + - ]: 12 : else if (artifacttype == "section") atype_code = "I";
2311 : : else {
2312 [ + - ]: 4 : artifacttype = "invalid"; // PR28242 ensure http_resposes metrics don't propagate unclean user data
2313 [ + - + - ]: 12 : throw reportable_exception("invalid artifacttype");
2314 : : }
2315 : :
2316 [ + + ]: 1933 : if (conn != 0)
2317 [ + - + - : 4412 : inc_metric("http_requests_total", "type", artifacttype);
+ - - + -
- - + ]
2318 : :
2319 : 1933 : string section;
2320 [ + + ]: 1933 : if (atype_code == "I")
2321 : : {
2322 [ - + ]: 8 : if (suffix.size () < 2)
2323 [ # # # # ]: 0 : throw reportable_exception ("invalid section suffix");
2324 : :
2325 : : // Remove leading '/'
2326 [ + - - + ]: 8 : section = suffix.substr(1);
2327 : : }
2328 : :
2329 [ + + - + ]: 2498 : if (atype_code == "S" && suffix == "")
2330 [ # # # # ]: 0 : throw reportable_exception("invalid source suffix");
2331 : :
2332 : : // validate buildid
2333 [ + + ]: 1933 : if ((buildid.size() < 2) || // not empty
2334 [ + + + - : 3860 : (buildid.size() % 2) || // even number
+ - ]
2335 : 1927 : (buildid.find_first_not_of("0123456789abcdef") != string::npos)) // pure tasty lowercase hex
2336 [ + - - + ]: 12 : throw reportable_exception("invalid buildid");
2337 : :
2338 [ + - ]: 1927 : if (verbose > 1)
2339 [ + - + - ]: 5781 : obatched(clog) << "searching for buildid=" << buildid << " artifacttype=" << artifacttype
2340 [ + - + - : 1927 : << " suffix=" << suffix << endl;
+ - + - +
- ]
2341 : :
2342 : : // If invoked from the scanner threads, use the scanners' read-write
2343 : : // connection. Otherwise use the web query threads' read-only connection.
2344 [ + + ]: 1927 : sqlite3 *thisdb = (conn == 0) ? db : dbq;
2345 : :
2346 : 1927 : sqlite_ps *pp = 0;
2347 : :
2348 [ + + ]: 1927 : if (atype_code == "D")
2349 : : {
2350 [ - + ]: 738 : pp = new sqlite_ps (thisdb, "mhd-query-d",
2351 : : "select mtime, sourcetype, source0, source1 from " BUILDIDS "_query_d where buildid = ? "
2352 [ + - + - : 1476 : "order by mtime desc");
+ - + - +
- - - ]
2353 [ + - ]: 738 : pp->reset();
2354 [ + - ]: 738 : pp->bind(1, buildid);
2355 : : }
2356 [ + + ]: 1189 : else if (atype_code == "E")
2357 : : {
2358 [ - + ]: 616 : pp = new sqlite_ps (thisdb, "mhd-query-e",
2359 : : "select mtime, sourcetype, source0, source1 from " BUILDIDS "_query_e where buildid = ? "
2360 [ + - + - : 1232 : "order by mtime desc");
+ - + - +
- - - ]
2361 [ + - ]: 616 : pp->reset();
2362 [ + - ]: 616 : pp->bind(1, buildid);
2363 : : }
2364 [ + + ]: 573 : else if (atype_code == "S")
2365 : : {
2366 : : // PR25548
2367 : : // Incoming source queries may come in with either dwarf-level OR canonicalized paths.
2368 : : // We let the query pass with either one.
2369 : :
2370 [ - + ]: 565 : pp = new sqlite_ps (thisdb, "mhd-query-s",
2371 : : "select mtime, sourcetype, source0, source1 from " BUILDIDS "_query_s where buildid = ? and artifactsrc in (?,?) "
2372 [ + - + - : 1130 : "order by sharedprefix(source0,source0ref) desc, mtime desc");
+ - + - +
- - - ]
2373 [ + - ]: 565 : pp->reset();
2374 [ + - ]: 565 : pp->bind(1, buildid);
2375 : : // NB: we don't store the non-canonicalized path names any more, but old databases
2376 : : // might have them (and no canon ones), so we keep searching for both.
2377 [ + - ]: 565 : pp->bind(2, suffix);
2378 [ + - + - : 1752 : pp->bind(3, canon_pathname(suffix));
- + ]
2379 : : }
2380 [ + - ]: 8 : else if (atype_code == "I")
2381 : : {
2382 [ - + ]: 8 : pp = new sqlite_ps (thisdb, "mhd-query-i",
2383 : : "select mtime, sourcetype, source0, source1, 1 as debug_p from " BUILDIDS "_query_d where buildid = ? "
2384 : : "union all "
2385 : : "select mtime, sourcetype, source0, source1, 0 as debug_p from " BUILDIDS "_query_e where buildid = ? "
2386 [ + - + - : 16 : "order by debug_p desc, mtime desc");
+ - + - +
- - - ]
2387 [ + - ]: 8 : pp->reset();
2388 [ + - ]: 8 : pp->bind(1, buildid);
2389 [ + - ]: 8 : pp->bind(2, buildid);
2390 : : }
2391 : 1927 : unique_ptr<sqlite_ps> ps_closer(pp); // release pp if exception or return
2392 : :
2393 : 1927 : bool do_upstream_section_query = true;
2394 : :
2395 : : // consume all the rows
2396 : 1989 : while (1)
2397 : : {
2398 [ + - ]: 1989 : int rc = pp->step();
2399 [ + + ]: 1989 : if (rc == SQLITE_DONE) break;
2400 [ - + ]: 1369 : if (rc != SQLITE_ROW)
2401 [ # # # # ]: 0 : throw sqlite_exception(rc, "step");
2402 : :
2403 [ + - ]: 1369 : int64_t b_mtime = sqlite3_column_int64 (*pp, 0);
2404 [ + - - + : 1369 : string b_stype = string((const char*) sqlite3_column_text (*pp, 1) ?: ""); /* by DDL may not be NULL */
+ - ]
2405 [ + - - + : 1369 : string b_source0 = string((const char*) sqlite3_column_text (*pp, 2) ?: ""); /* may be NULL */
+ - - - ]
2406 [ + - + + : 1952 : string b_source1 = string((const char*) sqlite3_column_text (*pp, 3) ?: ""); /* may be NULL */
+ - - - ]
2407 : :
2408 [ + - ]: 1369 : if (verbose > 1)
2409 [ + - + - : 4107 : obatched(clog) << "found mtime=" << b_mtime << " stype=" << b_stype
- - ]
2410 [ + - + - : 1369 : << " source0=" << b_source0 << " source1=" << b_source1 << endl;
+ - + - +
- + - +
- ]
2411 : :
2412 : : // Try accessing the located match.
2413 : : // XXX: in case of multiple matches, attempt them in parallel?
2414 [ + - ]: 1369 : auto r = handle_buildid_match (conn ? false : true,
2415 : : b_mtime, b_stype, b_source0, b_source1,
2416 : : section, result_fd);
2417 [ + + ]: 1369 : if (r)
2418 [ + + ]: 1307 : return r;
2419 : :
2420 : : // If a debuginfo file matching BUILDID was found but didn't contain
2421 : : // the desired section, then the section should not exist. Don't
2422 : : // bother querying upstream servers.
2423 [ + + + - : 62 : if (!section.empty () && (sqlite3_column_int (*pp, 4) == 1))
- + ]
2424 : : {
2425 : 4 : struct stat st;
2426 : :
2427 : : // For "F" sourcetype, check if the debuginfo exists. For "R"
2428 : : // sourcetype, check if the debuginfo was interned into the fdcache.
2429 [ - + ]: 6 : if ((b_stype == "F" && (stat (b_source0.c_str (), &st) == 0))
2430 [ + + + - : 6 : || (b_stype == "R" && fdcache.probe (b_source0, b_source1)))
+ - - + ]
2431 : : do_upstream_section_query = false;
2432 : : }
2433 [ + - - + : 2738 : }
+ - - + ]
2434 [ + - ]: 620 : pp->reset();
2435 : :
2436 [ - + ]: 620 : if (!do_upstream_section_query)
2437 [ # # # # ]: 0 : throw reportable_exception(MHD_HTTP_NOT_FOUND, "not found");
2438 : :
2439 : : // We couldn't find it in the database. Last ditch effort
2440 : : // is to defer to other debuginfo servers.
2441 : :
2442 : 620 : int fd = -1;
2443 [ + - ]: 620 : debuginfod_client *client = debuginfod_pool_begin ();
2444 [ - + ]: 620 : if (client == NULL)
2445 [ # # # # ]: 0 : throw libc_exception(errno, "debuginfod client pool alloc");
2446 : 620 : defer_dtor<debuginfod_client*,void> client_closer (client, debuginfod_pool_end);
2447 : :
2448 [ + - ]: 620 : debuginfod_set_progressfn (client, & debuginfod_find_progress);
2449 : :
2450 [ + - ]: 620 : if (conn)
2451 : : {
2452 : : // Transcribe incoming User-Agent:
2453 [ + - - + : 620 : string ua = MHD_lookup_connection_value (conn, MHD_HEADER_KIND, "User-Agent") ?: "";
+ - ]
2454 [ + - + - : 624 : string ua_complete = string("User-Agent: ") + ua;
+ - ]
2455 [ + - ]: 620 : debuginfod_add_http_header (client, ua_complete.c_str());
2456 : :
2457 : : // Compute larger XFF:, for avoiding info loss during
2458 : : // federation, and for future cyclicity detection.
2459 [ + - + + : 1226 : string xff = MHD_lookup_connection_value (conn, MHD_HEADER_KIND, "X-Forwarded-For") ?: "";
+ - + - ]
2460 [ + + ]: 620 : if (xff != "")
2461 [ + - - + ]: 36 : xff += string(", "); // comma separated list
2462 : :
2463 : 620 : unsigned int xff_count = 0;
2464 [ + + ]: 860 : for (auto&& i : xff){
2465 [ + + ]: 240 : if (i == ',') xff_count++;
2466 : : }
2467 : :
2468 : : // if X-Forwarded-For: exceeds N hops,
2469 : : // do not delegate a local lookup miss to upstream debuginfods.
2470 [ + + ]: 620 : if (xff_count >= forwarded_ttl_limit)
2471 [ + - + - ]: 8 : throw reportable_exception(MHD_HTTP_NOT_FOUND, "not found, --forwared-ttl-limit reached \
2472 : 8 : and will not query the upstream servers");
2473 : :
2474 : : // Compute the client's numeric IP address only - so can't merge with conninfo()
2475 [ + - ]: 616 : const union MHD_ConnectionInfo *u = MHD_get_connection_info (conn,
2476 : : MHD_CONNECTION_INFO_CLIENT_ADDRESS);
2477 [ + - ]: 616 : struct sockaddr *so = u ? u->client_addr : 0;
2478 : 616 : char hostname[256] = ""; // RFC1035
2479 [ + - - + ]: 616 : if (so && so->sa_family == AF_INET) {
2480 [ # # ]: 0 : (void) getnameinfo (so, sizeof (struct sockaddr_in), hostname, sizeof (hostname), NULL, 0,
2481 : : NI_NUMERICHOST);
2482 [ + - ]: 616 : } else if (so && so->sa_family == AF_INET6) {
2483 : 616 : struct sockaddr_in6* addr6 = (struct sockaddr_in6*) so;
2484 [ + - + - : 616 : if (IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr)) {
- + ]
2485 : 616 : struct sockaddr_in addr4;
2486 [ + - ]: 616 : memset (&addr4, 0, sizeof(addr4));
2487 : 616 : addr4.sin_family = AF_INET;
2488 : 616 : addr4.sin_port = addr6->sin6_port;
2489 [ + - ]: 616 : memcpy (&addr4.sin_addr.s_addr, addr6->sin6_addr.s6_addr+12, sizeof(addr4.sin_addr.s_addr));
2490 [ + - ]: 616 : (void) getnameinfo ((struct sockaddr*) &addr4, sizeof (addr4),
2491 : : hostname, sizeof (hostname), NULL, 0,
2492 : : NI_NUMERICHOST);
2493 : : } else {
2494 [ # # ]: 0 : (void) getnameinfo (so, sizeof (struct sockaddr_in6), hostname, sizeof (hostname), NULL, 0,
2495 : : NI_NUMERICHOST);
2496 : : }
2497 : : }
2498 : :
2499 [ + - + - : 1236 : string xff_complete = string("X-Forwarded-For: ")+xff+string(hostname);
+ - + - -
+ - + - -
- + ]
2500 [ + - ]: 616 : debuginfod_add_http_header (client, xff_complete.c_str());
2501 [ + + + - : 1300 : }
+ + ]
2502 : :
2503 [ + + ]: 616 : if (artifacttype == "debuginfo")
2504 [ + - ]: 68 : fd = debuginfod_find_debuginfo (client,
2505 [ + - ]: 68 : (const unsigned char*) buildid.c_str(),
2506 : : 0, NULL);
2507 [ + + ]: 548 : else if (artifacttype == "executable")
2508 [ + - ]: 546 : fd = debuginfod_find_executable (client,
2509 [ + - ]: 546 : (const unsigned char*) buildid.c_str(),
2510 : : 0, NULL);
2511 [ + - ]: 2 : else if (artifacttype == "source")
2512 [ + - ]: 2 : fd = debuginfod_find_source (client,
2513 [ + - ]: 2 : (const unsigned char*) buildid.c_str(),
2514 : : 0, suffix.c_str(), NULL);
2515 [ # # ]: 0 : else if (artifacttype == "section")
2516 [ # # ]: 0 : fd = debuginfod_find_section (client,
2517 [ # # ]: 0 : (const unsigned char*) buildid.c_str(),
2518 : : 0, section.c_str(), NULL);
2519 : :
2520 [ + + ]: 616 : if (fd >= 0)
2521 : : {
2522 [ + - ]: 4 : if (conn != 0)
2523 [ + - + - : 624 : inc_metric ("http_responses_total","result","upstream");
+ - + - -
+ - + - -
- - ]
2524 : 4 : struct stat s;
2525 : 4 : int rc = fstat (fd, &s);
2526 [ + - ]: 4 : if (rc == 0)
2527 : : {
2528 [ + - ]: 4 : auto r = MHD_create_response_from_fd ((uint64_t) s.st_size, fd);
2529 [ + - ]: 4 : if (r)
2530 : : {
2531 [ + - ]: 4 : add_mhd_response_header (r, "Content-Type",
2532 : : "application/octet-stream");
2533 : : // Copy the incoming headers
2534 [ + - ]: 4 : const char * hdrs = debuginfod_get_headers(client);
2535 [ + - ]: 4 : string header_dup;
2536 [ + - ]: 4 : if (hdrs)
2537 [ + - - + ]: 4 : header_dup = string(hdrs);
2538 : : // Parse the "header: value\n" lines into (h,v) tuples and pass on
2539 : 20 : while(1)
2540 : : {
2541 : 12 : size_t newline = header_dup.find('\n');
2542 [ + + ]: 12 : if (newline == string::npos) break;
2543 : 8 : size_t colon = header_dup.find(':');
2544 [ + - ]: 8 : if (colon == string::npos) break;
2545 [ + - ]: 8 : string header = header_dup.substr(0,colon);
2546 [ + - ]: 8 : string value = header_dup.substr(colon+1,newline-colon-1);
2547 : : // strip leading spaces from value
2548 : 8 : size_t nonspace = value.find_first_not_of(" ");
2549 [ + - ]: 8 : if (nonspace != string::npos)
2550 [ + - + + ]: 12 : value = value.substr(nonspace);
2551 [ + - ]: 8 : add_mhd_response_header(r, header.c_str(), value.c_str());
2552 [ + - + + : 12 : header_dup = header_dup.substr(newline+1);
+ + - - ]
2553 [ + - ]: 16 : }
2554 : :
2555 [ + - ]: 4 : add_mhd_last_modified (r, s.st_mtime);
2556 [ + - ]: 4 : if (verbose > 1)
2557 [ + - + - : 8 : obatched(clog) << "serving file from upstream debuginfod/cache" << endl;
- - ]
2558 [ + - ]: 4 : if (result_fd)
2559 : 4 : *result_fd = fd;
2560 [ + - ]: 4 : return r; // NB: don't close fd; libmicrohttpd will
2561 : 4 : }
2562 : : }
2563 [ # # ]: 0 : close (fd);
2564 : : }
2565 : : else
2566 [ + + ]: 612 : switch(fd)
2567 : : {
2568 : : case -ENOSYS:
2569 : : break;
2570 : : case -ENOENT:
2571 : : break;
2572 : 532 : default: // some more tricky error
2573 [ + - + - ]: 1064 : throw libc_exception(-fd, "upstream debuginfod query failed");
2574 : : }
2575 : :
2576 [ + - - + ]: 160 : throw reportable_exception(MHD_HTTP_NOT_FOUND, "not found");
2577 [ - + - + ]: 2549 : }
2578 : :
2579 : :
2580 : : ////////////////////////////////////////////////////////////////////////
2581 : :
2582 : : static map<string,double> metrics; // arbitrary data for /metrics query
2583 : : // NB: store int64_t since all our metrics are integers; prometheus accepts double
2584 : : static mutex metrics_lock;
2585 : : // NB: these objects get released during the process exit via global dtors
2586 : : // do not call them from within other global dtors
2587 : :
2588 : : // utility function for assembling prometheus-compatible
2589 : : // name="escaped-value" strings
2590 : : // https://prometheus.io/docs/instrumenting/exposition_formats/
2591 : : static string
2592 : 724615 : metric_label(const string& name, const string& value)
2593 : : {
2594 : 724615 : string x = name + "=\"";
2595 [ + + ]: 12611091 : for (auto&& c : value)
2596 [ - - - + ]: 11886922 : switch(c)
2597 : : {
2598 [ # # ]: 0 : case '\\': x += "\\\\"; break;
2599 [ # # ]: 0 : case '\"': x += "\\\""; break;
2600 [ # # ]: 0 : case '\n': x += "\\n"; break;
2601 [ + - ]: 23773662 : default: x += c; break;
2602 : : }
2603 [ + - ]: 724169 : x += "\"";
2604 : 724258 : return x;
2605 : 0 : }
2606 : :
2607 : :
2608 : : // add prometheus-format metric name + label tuple (if any) + value
2609 : :
2610 : : static void
2611 : 1276 : set_metric(const string& metric, double value)
2612 : : {
2613 : 1276 : unique_lock<mutex> lock(metrics_lock);
2614 [ + - ]: 1276 : metrics[metric] = value;
2615 : 1276 : }
2616 : : static void
2617 : 592 : inc_metric(const string& metric)
2618 : : {
2619 : 592 : unique_lock<mutex> lock(metrics_lock);
2620 [ + - ]: 592 : metrics[metric] ++;
2621 : 592 : }
2622 : : static void
2623 : 6408 : set_metric(const string& metric,
2624 : : const string& lname, const string& lvalue,
2625 : : double value)
2626 : : {
2627 [ + - + - : 12815 : string key = (metric + "{" + metric_label(lname, lvalue) + "}");
- + - + +
+ - - ]
2628 [ + - ]: 6408 : unique_lock<mutex> lock(metrics_lock);
2629 [ + - ]: 6408 : metrics[key] = value;
2630 [ + - ]: 12816 : }
2631 : :
2632 : : static void
2633 : 349486 : inc_metric(const string& metric,
2634 : : const string& lname, const string& lvalue)
2635 : : {
2636 [ + - + - : 760838 : string key = (metric + "{" + metric_label(lname, lvalue) + "}");
- + + + +
+ - - ]
2637 [ + - ]: 349485 : unique_lock<mutex> lock(metrics_lock);
2638 [ + - ]: 349492 : metrics[key] ++;
2639 [ + - ]: 698975 : }
2640 : : static void
2641 : 337331 : add_metric(const string& metric,
2642 : : const string& lname, const string& lvalue,
2643 : : double value)
2644 : : {
2645 [ + - + - : 736526 : string key = (metric + "{" + metric_label(lname, lvalue) + "}");
- + + + +
+ - - ]
2646 [ + - ]: 337340 : unique_lock<mutex> lock(metrics_lock);
2647 [ + - ]: 337374 : metrics[key] += value;
2648 [ + - ]: 674746 : }
2649 : : static void
2650 : 592 : add_metric(const string& metric,
2651 : : double value)
2652 : : {
2653 : 592 : unique_lock<mutex> lock(metrics_lock);
2654 [ + - ]: 592 : metrics[metric] += value;
2655 : 592 : }
2656 : :
2657 : :
2658 : : // and more for higher arity labels if needed
2659 : :
2660 : : static void
2661 : 7863 : inc_metric(const string& metric,
2662 : : const string& lname, const string& lvalue,
2663 : : const string& rname, const string& rvalue)
2664 : : {
2665 [ + - - + : 15726 : string key = (metric + "{"
- - ]
2666 [ + - + - : 31452 : + metric_label(lname, lvalue) + ","
- + - + +
+ - - ]
2667 [ + - - + : 23589 : + metric_label(rname, rvalue) + "}");
- + ]
2668 [ + - ]: 7863 : unique_lock<mutex> lock(metrics_lock);
2669 [ + - ]: 7863 : metrics[key] ++;
2670 [ + - ]: 15726 : }
2671 : : static void
2672 : 7863 : add_metric(const string& metric,
2673 : : const string& lname, const string& lvalue,
2674 : : const string& rname, const string& rvalue,
2675 : : double value)
2676 : : {
2677 [ + - - + : 15726 : string key = (metric + "{"
- - ]
2678 [ + - + - : 31452 : + metric_label(lname, lvalue) + ","
- + - + +
+ - - ]
2679 [ + - - + : 23589 : + metric_label(rname, rvalue) + "}");
- + ]
2680 [ + - ]: 7863 : unique_lock<mutex> lock(metrics_lock);
2681 [ + - ]: 7863 : metrics[key] += value;
2682 [ + - ]: 15726 : }
2683 : :
2684 : : static struct MHD_Response*
2685 : 718 : handle_metrics (off_t* size)
2686 : : {
2687 : 718 : stringstream o;
2688 : 718 : {
2689 [ + - ]: 718 : unique_lock<mutex> lock(metrics_lock);
2690 [ + + ]: 68407 : for (auto&& i : metrics)
2691 [ + - ]: 67689 : o << i.first
2692 : : << " "
2693 [ + - + - ]: 67689 : << std::setprecision(std::numeric_limits<double>::digits10 + 1)
2694 [ + - + - ]: 67689 : << i.second
2695 : 67689 : << endl;
2696 : 0 : }
2697 [ + - ]: 718 : const string& os = o.str();
2698 [ + - ]: 718 : MHD_Response* r = MHD_create_response_from_buffer (os.size(),
2699 [ + - ]: 718 : (void*) os.c_str(),
2700 : : MHD_RESPMEM_MUST_COPY);
2701 [ + - ]: 718 : if (r != NULL)
2702 : : {
2703 [ + - ]: 718 : *size = os.size();
2704 [ + - ]: 718 : add_mhd_response_header (r, "Content-Type", "text/plain");
2705 : : }
2706 [ + - ]: 1436 : return r;
2707 : 718 : }
2708 : :
2709 : : static struct MHD_Response*
2710 : 0 : handle_root (off_t* size)
2711 : : {
2712 [ # # # # : 0 : static string version = "debuginfod (" + string (PACKAGE_NAME) + ") "
# # # # #
# # # ]
2713 [ # # # # : 0 : + string (PACKAGE_VERSION);
# # # # #
# ]
2714 : 0 : MHD_Response* r = MHD_create_response_from_buffer (version.size (),
2715 : 0 : (void *) version.c_str (),
2716 : : MHD_RESPMEM_PERSISTENT);
2717 [ # # ]: 0 : if (r != NULL)
2718 : : {
2719 : 0 : *size = version.size ();
2720 : 0 : add_mhd_response_header (r, "Content-Type", "text/plain");
2721 : : }
2722 : 0 : return r;
2723 : : }
2724 : :
2725 : :
2726 : : ////////////////////////////////////////////////////////////////////////
2727 : :
2728 : :
2729 : : /* libmicrohttpd callback */
2730 : : static MHD_RESULT
2731 : 5242 : handler_cb (void * /*cls*/,
2732 : : struct MHD_Connection *connection,
2733 : : const char *url,
2734 : : const char *method,
2735 : : const char * /*version*/,
2736 : : const char * /*upload_data*/,
2737 : : size_t * /*upload_data_size*/,
2738 : : void ** ptr)
2739 : : {
2740 : 5242 : struct MHD_Response *r = NULL;
2741 : 5242 : string url_copy = url;
2742 : :
2743 : : /* libmicrohttpd always makes (at least) two callbacks: once just
2744 : : past the headers, and one after the request body is finished
2745 : : being received. If we process things early (first callback) and
2746 : : queue a response, libmicrohttpd would suppress http keep-alive
2747 : : (via connection->read_closed = true). */
2748 : 5242 : static int aptr; /* just some random object to use as a flag */
2749 [ + + ]: 5242 : if (&aptr != *ptr)
2750 : : {
2751 : : /* do never respond on first call */
2752 : 2621 : *ptr = &aptr;
2753 : 2621 : return MHD_YES;
2754 : : }
2755 : 2621 : *ptr = NULL; /* reset when done */
2756 : :
2757 [ + - ]: 2621 : const char *maxsize_string = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, "X-DEBUGINFOD-MAXSIZE");
2758 : 2621 : long maxsize = 0;
2759 [ + + + - ]: 2621 : if (maxsize_string != NULL && maxsize_string[0] != '\0')
2760 : 2 : maxsize = atol(maxsize_string);
2761 : : else
2762 : : maxsize = 0;
2763 : :
2764 : : #if MHD_VERSION >= 0x00097002
2765 : 2621 : enum MHD_Result rc;
2766 : : #else
2767 : : int rc = MHD_NO; // mhd
2768 : : #endif
2769 : 2621 : int http_code = 500;
2770 : 2621 : off_t http_size = -1;
2771 : 2621 : struct timespec ts_start, ts_end;
2772 : 2621 : clock_gettime (CLOCK_MONOTONIC, &ts_start);
2773 : 2621 : double afteryou = 0.0;
2774 [ + - ]: 2621 : string artifacttype, suffix;
2775 : :
2776 : 2621 : try
2777 : : {
2778 [ + - - + : 5876 : if (string(method) != "GET")
- + ]
2779 [ # # # # ]: 0 : throw reportable_exception(400, "we support GET only");
2780 : :
2781 : : /* Start decoding the URL. */
2782 : 2621 : size_t slash1 = url_copy.find('/', 1);
2783 [ + - ]: 2621 : string url1 = url_copy.substr(0, slash1); // ok even if slash1 not found
2784 : :
2785 [ + + + - ]: 4518 : if (slash1 != string::npos && url1 == "/buildid")
2786 : : {
2787 : : // PR27863: block this thread awhile if another thread is already busy
2788 : : // fetching the exact same thing. This is better for Everyone.
2789 : : // The latecomer says "... after you!" and waits.
2790 [ + - + - : 4420 : add_metric ("thread_busy", "role", "http-buildid-after-you", 1);
+ - + - -
+ + - - -
- - ]
2791 : : #ifdef HAVE_PTHREAD_SETNAME_NP
2792 : 1897 : (void) pthread_setname_np (pthread_self(), "mhd-buildid-after-you");
2793 : : #endif
2794 : 1897 : struct timespec tsay_start, tsay_end;
2795 : 1897 : clock_gettime (CLOCK_MONOTONIC, &tsay_start);
2796 [ + + + - ]: 1897 : static unique_set<string> busy_urls;
2797 [ + - ]: 1897 : unique_set_reserver<string> after_you(busy_urls, url_copy);
2798 : 1897 : clock_gettime (CLOCK_MONOTONIC, &tsay_end);
2799 : 1897 : afteryou = (tsay_end.tv_sec - tsay_start.tv_sec) + (tsay_end.tv_nsec - tsay_start.tv_nsec)/1.e9;
2800 [ + - + - : 3794 : add_metric ("thread_busy", "role", "http-buildid-after-you", -1);
+ - + - -
+ + - - -
- - ]
2801 : :
2802 [ + - + - : 3794 : tmp_inc_metric m ("thread_busy", "role", "http-buildid");
+ - + - -
+ - + - -
- - ]
2803 : : #ifdef HAVE_PTHREAD_SETNAME_NP
2804 : 1897 : (void) pthread_setname_np (pthread_self(), "mhd-buildid");
2805 : : #endif
2806 : 1897 : size_t slash2 = url_copy.find('/', slash1+1);
2807 [ - + ]: 1897 : if (slash2 == string::npos)
2808 [ # # # # ]: 0 : throw reportable_exception("/buildid/ webapi error, need buildid");
2809 : :
2810 [ + - ]: 1897 : string buildid = url_copy.substr(slash1+1, slash2-slash1-1);
2811 : :
2812 : 1897 : size_t slash3 = url_copy.find('/', slash2+1);
2813 : :
2814 [ + + ]: 1897 : if (slash3 == string::npos)
2815 : : {
2816 [ + - - + ]: 1324 : artifacttype = url_copy.substr(slash2+1);
2817 [ + - ]: 1324 : suffix = "";
2818 : : }
2819 : : else
2820 : : {
2821 [ + - - + ]: 573 : artifacttype = url_copy.substr(slash2+1, slash3-slash2-1);
2822 [ + - - + : 1199 : suffix = url_copy.substr(slash3); // include the slash in the suffix
+ + ]
2823 : : }
2824 : :
2825 : : // get the resulting fd so we can report its size
2826 : 1897 : int fd;
2827 [ + + ]: 1897 : r = handle_buildid(connection, buildid, artifacttype, suffix, &fd);
2828 [ + - ]: 1271 : if (r)
2829 : : {
2830 : 1271 : struct stat fs;
2831 [ + - ]: 1271 : if (fstat(fd, &fs) == 0)
2832 : 1271 : http_size = fs.st_size;
2833 : : // libmicrohttpd will close (fd);
2834 : : }
2835 : 2523 : }
2836 [ + + ]: 724 : else if (url1 == "/metrics")
2837 : : {
2838 [ + - + - : 1436 : tmp_inc_metric m ("thread_busy", "role", "http-metrics");
+ - + - -
+ - + - -
- - ]
2839 [ + - ]: 718 : artifacttype = "metrics";
2840 [ + - + - : 1436 : inc_metric("http_requests_total", "type", artifacttype);
+ - - + -
- ]
2841 [ + - ]: 718 : r = handle_metrics(& http_size);
2842 : 718 : }
2843 [ - + ]: 6 : else if (url1 == "/")
2844 : : {
2845 [ # # ]: 0 : artifacttype = "/";
2846 [ - - - - : 634 : inc_metric("http_requests_total", "type", artifacttype);
- - - - -
- - + ]
2847 [ # # ]: 0 : r = handle_root(& http_size);
2848 : : }
2849 : : else
2850 [ + - + - : 18 : throw reportable_exception("webapi error, unrecognized '" + url1 + "'");
+ - - + ]
2851 : :
2852 [ - + ]: 1989 : if (r == 0)
2853 [ # # # # ]: 0 : throw reportable_exception("internal error, missing response");
2854 : :
2855 [ + + + - ]: 1989 : if (maxsize > 0 && http_size > maxsize)
2856 : : {
2857 [ + - ]: 2 : MHD_destroy_response(r);
2858 [ + - + - : 6 : throw reportable_exception(406, "File too large, max size=" + std::to_string(maxsize));
+ - - + ]
2859 : : }
2860 : :
2861 [ + - ]: 1987 : rc = MHD_queue_response (connection, MHD_HTTP_OK, r);
2862 : 1987 : http_code = MHD_HTTP_OK;
2863 [ + - ]: 1987 : MHD_destroy_response (r);
2864 : 2621 : }
2865 [ - + ]: 634 : catch (const reportable_exception& e)
2866 : : {
2867 [ + - + - : 1268 : inc_metric("http_responses_total","result","error");
+ - + - -
+ - + - -
- - ]
2868 [ + - ]: 634 : e.report(clog);
2869 : 634 : http_code = e.code;
2870 [ + - ]: 634 : http_size = e.message.size();
2871 [ + - ]: 634 : rc = e.mhd_send_response (connection);
2872 : 634 : }
2873 : :
2874 : 2621 : clock_gettime (CLOCK_MONOTONIC, &ts_end);
2875 : 2621 : double deltas = (ts_end.tv_sec - ts_start.tv_sec) + (ts_end.tv_nsec - ts_start.tv_nsec)/1.e9;
2876 : : // afteryou: delay waiting for other client's identical query to complete
2877 : : // deltas: total latency, including afteryou waiting
2878 [ + - + - : 5242 : obatched(clog) << conninfo(connection)
- - ]
2879 : : << ' ' << method << ' ' << url
2880 [ + - + - : 2621 : << ' ' << http_code << ' ' << http_size
+ - + - +
- + - +
- ]
2881 [ + - + - : 2621 : << ' ' << (int)(afteryou*1000) << '+' << (int)((deltas-afteryou)*1000) << "ms"
+ - + - +
- + - +
- ]
2882 [ + - ]: 2621 : << endl;
2883 : :
2884 : : // related prometheus metrics
2885 : 2621 : string http_code_str = to_string(http_code);
2886 [ + - + - : 5242 : add_metric("http_responses_transfer_bytes_sum",
+ - + - -
+ - + - -
- - ]
2887 : : "code", http_code_str, "type", artifacttype, http_size);
2888 [ + - + - : 5242 : inc_metric("http_responses_transfer_bytes_count",
+ - + - -
+ - + - -
- - ]
2889 : : "code", http_code_str, "type", artifacttype);
2890 : :
2891 [ + - + - : 5242 : add_metric("http_responses_duration_milliseconds_sum",
+ - + - -
+ - + - -
- - ]
2892 : : "code", http_code_str, "type", artifacttype, deltas*1000); // prometheus prefers _seconds and floating point
2893 [ + - + - : 5242 : inc_metric("http_responses_duration_milliseconds_count",
+ - + - -
+ - + - -
- - ]
2894 : : "code", http_code_str, "type", artifacttype);
2895 : :
2896 [ + - + - : 5242 : add_metric("http_responses_after_you_milliseconds_sum",
+ - + - -
+ - + - -
- - ]
2897 : : "code", http_code_str, "type", artifacttype, afteryou*1000);
2898 [ + - + - : 5242 : inc_metric("http_responses_after_you_milliseconds_count",
+ - + - -
+ - + - -
- - - - ]
2899 : : "code", http_code_str, "type", artifacttype);
2900 : :
2901 [ - + ]: 2621 : return rc;
2902 [ + + - + : 12222 : }
+ + ]
2903 : :
2904 : :
2905 : : ////////////////////////////////////////////////////////////////////////
2906 : : // borrowed originally from src/nm.c get_local_names()
2907 : :
2908 : : static void
2909 : 244 : dwarf_extract_source_paths (Elf *elf, set<string>& debug_sourcefiles)
2910 : : noexcept // no exceptions - so we can simplify the altdbg resource release at end
2911 : : {
2912 : 244 : Dwarf* dbg = dwarf_begin_elf (elf, DWARF_C_READ, NULL);
2913 [ - + ]: 244 : if (dbg == NULL)
2914 : 0 : return;
2915 : :
2916 : 244 : Dwarf* altdbg = NULL;
2917 : 244 : int altdbg_fd = -1;
2918 : :
2919 : : // DWZ handling: if we have an unsatisfied debug-alt-link, add an
2920 : : // empty string into the outgoing sourcefiles set, so the caller
2921 : : // should know that our data is incomplete.
2922 : 244 : const char *alt_name_p;
2923 : 244 : const void *alt_build_id; // elfutils-owned memory
2924 : 244 : ssize_t sz = dwelf_dwarf_gnu_debugaltlink (dbg, &alt_name_p, &alt_build_id);
2925 [ + + ]: 244 : if (sz > 0) // got one!
2926 : : {
2927 : 40 : string buildid;
2928 : 40 : unsigned char* build_id_bytes = (unsigned char*) alt_build_id;
2929 [ + + ]: 840 : for (ssize_t idx=0; idx<sz; idx++)
2930 : : {
2931 : 800 : buildid += "0123456789abcdef"[build_id_bytes[idx] >> 4];
2932 : 800 : buildid += "0123456789abcdef"[build_id_bytes[idx] & 0xf];
2933 : : }
2934 : :
2935 [ + - ]: 40 : if (verbose > 3)
2936 : 40 : obatched(clog) << "Need altdebug buildid=" << buildid << endl;
2937 : :
2938 : : // but is it unsatisfied the normal elfutils ways?
2939 : 40 : Dwarf* alt = dwarf_getalt (dbg);
2940 [ + - ]: 40 : if (alt == NULL)
2941 : : {
2942 : : // Yup, unsatisfied the normal way. Maybe we can satisfy it
2943 : : // from our own debuginfod database.
2944 : 40 : int alt_fd;
2945 : 40 : struct MHD_Response *r = 0;
2946 : 40 : try
2947 : : {
2948 [ + - ]: 40 : string artifacttype = "debuginfo";
2949 [ + - + - : 40 : r = handle_buildid (0, buildid, artifacttype, "", &alt_fd);
- + - + -
- ]
2950 : 0 : }
2951 [ - - ]: 0 : catch (const reportable_exception& e)
2952 : : {
2953 : : // swallow exceptions
2954 : 0 : }
2955 : :
2956 : : // NB: this is not actually recursive! This invokes the web-query
2957 : : // path, which cannot get back into the scan code paths.
2958 [ + - ]: 40 : if (r)
2959 : : {
2960 : : // Found it!
2961 : 40 : altdbg_fd = dup(alt_fd); // ok if this fails, downstream failures ok
2962 : 40 : alt = altdbg = dwarf_begin (altdbg_fd, DWARF_C_READ);
2963 : : // NB: must close this dwarf and this fd at the bottom of the function!
2964 : 40 : MHD_destroy_response (r); // will close alt_fd
2965 [ + - ]: 40 : if (alt)
2966 : 40 : dwarf_setalt (dbg, alt);
2967 : : }
2968 : : }
2969 : : else
2970 : : {
2971 : : // NB: dwarf_setalt(alt) inappropriate - already done!
2972 : : // NB: altdbg will stay 0 so nothing tries to redundantly dealloc.
2973 : : }
2974 : :
2975 [ + - ]: 40 : if (alt)
2976 : : {
2977 [ + - ]: 40 : if (verbose > 3)
2978 : 40 : obatched(clog) << "Resolved altdebug buildid=" << buildid << endl;
2979 : : }
2980 : : else // (alt == NULL) - signal possible presence of poor debuginfo
2981 : : {
2982 [ # # ]: 0 : debug_sourcefiles.insert("");
2983 [ # # ]: 0 : if (verbose > 3)
2984 : 0 : obatched(clog) << "Unresolved altdebug buildid=" << buildid << endl;
2985 : : }
2986 : 40 : }
2987 : :
2988 : 244 : Dwarf_Off offset = 0;
2989 : 244 : Dwarf_Off old_offset;
2990 : 244 : size_t hsize;
2991 : :
2992 [ + + ]: 8618 : while (dwarf_nextcu (dbg, old_offset = offset, &offset, &hsize, NULL, NULL, NULL) == 0)
2993 : : {
2994 : 8374 : Dwarf_Die cudie_mem;
2995 : 8374 : Dwarf_Die *cudie = dwarf_offdie (dbg, old_offset + hsize, &cudie_mem);
2996 : :
2997 [ - + ]: 8374 : if (cudie == NULL)
2998 : 20 : continue;
2999 [ + + ]: 8374 : if (dwarf_tag (cudie) != DW_TAG_compile_unit)
3000 : 20 : continue;
3001 : :
3002 [ - + ]: 8354 : const char *cuname = dwarf_diename(cudie) ?: "unknown";
3003 : :
3004 : 8354 : Dwarf_Files *files;
3005 : 8354 : size_t nfiles;
3006 [ - + ]: 8354 : if (dwarf_getsrcfiles (cudie, &files, &nfiles) != 0)
3007 : 0 : continue;
3008 : :
3009 : : // extract DW_AT_comp_dir to resolve relative file names
3010 : 8354 : const char *comp_dir = "";
3011 : 8354 : const char *const *dirs;
3012 : 8354 : size_t ndirs;
3013 [ - + ]: 8354 : if (dwarf_getsrcdirs (files, &dirs, &ndirs) == 0 &&
3014 [ - + ]: 8354 : dirs[0] != NULL)
3015 : : comp_dir = dirs[0];
3016 : : if (comp_dir == NULL)
3017 : : comp_dir = "";
3018 : :
3019 [ + + ]: 8354 : if (verbose > 3)
3020 : 12864 : obatched(clog) << "searching for sources for cu=" << cuname << " comp_dir=" << comp_dir
3021 : 6431 : << " #files=" << nfiles << " #dirs=" << ndirs << endl;
3022 : :
3023 [ + - - - ]: 8354 : if (comp_dir[0] == '\0' && cuname[0] != '/')
3024 : : {
3025 [ # # ]: 0 : if (verbose > 3)
3026 : 0 : obatched(clog) << "skipping cu=" << cuname << " due to empty comp_dir" << endl;
3027 : 0 : continue;
3028 : : }
3029 : :
3030 [ + + ]: 134853 : for (size_t f = 1; f < nfiles; f++)
3031 : : {
3032 : 126499 : const char *hat = dwarf_filesrc (files, f, NULL, NULL);
3033 [ - + ]: 126504 : if (hat == NULL)
3034 : 0 : continue;
3035 : :
3036 [ + + - + ]: 240256 : if (string(hat) == "<built-in>") // gcc intrinsics, don't bother record
3037 : 0 : continue;
3038 : :
3039 [ + + ]: 126503 : string waldo;
3040 [ + + ]: 126503 : if (hat[0] == '/') // absolute
3041 [ - + ]: 81145 : waldo = (string (hat));
3042 [ + - ]: 45358 : else if (comp_dir[0] != '\0') // comp_dir relative
3043 [ - + - + : 77968 : waldo = (string (comp_dir) + string("/") + string (hat));
- + - + +
+ ]
3044 : : else
3045 : : {
3046 [ # # ]: 0 : if (verbose > 3)
3047 : 0 : obatched(clog) << "skipping hat=" << hat << " due to empty comp_dir" << endl;
3048 [ # # ]: 0 : continue;
3049 : : }
3050 : :
3051 : : // NB: this is the 'waldo' that a dbginfo client will have
3052 : : // to supply for us to give them the file The comp_dir
3053 : : // prefixing is a definite complication. Otherwise we'd
3054 : : // have to return a setof comp_dirs (one per CU!) with
3055 : : // corresponding filesrc[] names, instead of one absolute
3056 : : // resoved set. Maybe we'll have to do that anyway. XXX
3057 : :
3058 [ + + ]: 126504 : if (verbose > 4)
3059 [ - + ]: 100 : obatched(clog) << waldo
3060 [ - + ]: 50 : << (debug_sourcefiles.find(waldo)==debug_sourcefiles.end() ? " new" : " dup") << endl;
3061 : :
3062 [ + - ]: 126504 : debug_sourcefiles.insert (waldo);
3063 : 126499 : }
3064 : : }
3065 : :
3066 : 244 : dwarf_end(dbg);
3067 [ + + ]: 244 : if (altdbg)
3068 : 40 : dwarf_end(altdbg);
3069 [ + + ]: 244 : if (altdbg_fd >= 0)
3070 : 40 : close(altdbg_fd);
3071 : : }
3072 : :
3073 : :
3074 : :
3075 : : static void
3076 : 1280 : elf_classify (int fd, bool &executable_p, bool &debuginfo_p, string &buildid, set<string>& debug_sourcefiles)
3077 : : {
3078 : 1280 : Elf *elf = elf_begin (fd, ELF_C_READ_MMAP_PRIVATE, NULL);
3079 [ + - ]: 1280 : if (elf == NULL)
3080 : : return;
3081 : :
3082 : 1280 : try // catch our types of errors and clean up the Elf* object
3083 : : {
3084 [ + - + + ]: 1280 : if (elf_kind (elf) != ELF_K_ELF)
3085 : : {
3086 [ + - ]: 792 : elf_end (elf);
3087 : 832 : return;
3088 : : }
3089 : :
3090 : 488 : GElf_Ehdr ehdr_storage;
3091 [ + - ]: 488 : GElf_Ehdr *ehdr = gelf_getehdr (elf, &ehdr_storage);
3092 [ - + ]: 488 : if (ehdr == NULL)
3093 : : {
3094 [ # # ]: 0 : elf_end (elf);
3095 : : return;
3096 : : }
3097 : 488 : auto elf_type = ehdr->e_type;
3098 : :
3099 : 488 : const void *build_id; // elfutils-owned memory
3100 [ + - ]: 488 : ssize_t sz = dwelf_elf_gnu_build_id (elf, & build_id);
3101 [ + + ]: 487 : if (sz <= 0)
3102 : : {
3103 : : // It's not a diagnostic-worthy error for an elf file to lack build-id.
3104 : : // It might just be very old.
3105 [ + - ]: 40 : elf_end (elf);
3106 : : return;
3107 : : }
3108 : :
3109 : : // build_id is a raw byte array; convert to hexadecimal *lowercase*
3110 : 447 : unsigned char* build_id_bytes = (unsigned char*) build_id;
3111 [ + + ]: 9399 : for (ssize_t idx=0; idx<sz; idx++)
3112 : : {
3113 [ + - ]: 8951 : buildid += "0123456789abcdef"[build_id_bytes[idx] >> 4];
3114 [ + - ]: 17908 : buildid += "0123456789abcdef"[build_id_bytes[idx] & 0xf];
3115 : : }
3116 : :
3117 : : // now decide whether it's an executable - namely, any allocatable section has
3118 : : // PROGBITS;
3119 [ + + ]: 448 : if (elf_type == ET_EXEC || elf_type == ET_DYN)
3120 : : {
3121 : 398 : size_t shnum;
3122 [ + - ]: 398 : int rc = elf_getshdrnum (elf, &shnum);
3123 [ - + ]: 396 : if (rc < 0)
3124 [ # # # # ]: 0 : throw elfutils_exception(rc, "getshdrnum");
3125 : :
3126 : 396 : executable_p = false;
3127 [ + + ]: 7051 : for (size_t sc = 0; sc < shnum; sc++)
3128 : : {
3129 [ + - ]: 6875 : Elf_Scn *scn = elf_getscn (elf, sc);
3130 [ - + ]: 6875 : if (scn == NULL)
3131 : 0 : continue;
3132 : :
3133 : 6875 : GElf_Shdr shdr_mem;
3134 [ + - ]: 6875 : GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
3135 [ - + ]: 6877 : if (shdr == NULL)
3136 : 0 : continue;
3137 : :
3138 : : // allocated (loadable / vm-addr-assigned) section with available content?
3139 [ + + + + ]: 6877 : if ((shdr->sh_type == SHT_PROGBITS) && (shdr->sh_flags & SHF_ALLOC))
3140 : : {
3141 [ + + ]: 222 : if (verbose > 4)
3142 [ + - + - : 32 : obatched(clog) << "executable due to SHF_ALLOC SHT_PROGBITS sc=" << sc << endl;
+ - ]
3143 : 222 : executable_p = true;
3144 : 222 : break; // no need to keep looking for others
3145 : : }
3146 : : } // iterate over sections
3147 : : } // executable_p classification
3148 : :
3149 : : // now decide whether it's a debuginfo - namely, if it has any .debug* or .zdebug* sections
3150 : : // logic mostly stolen from fweimer@redhat.com's elfclassify drafts
3151 : 448 : size_t shstrndx;
3152 [ + - ]: 448 : int rc = elf_getshdrstrndx (elf, &shstrndx);
3153 [ - + ]: 448 : if (rc < 0)
3154 [ # # # # ]: 0 : throw elfutils_exception(rc, "getshdrstrndx");
3155 : :
3156 : : Elf_Scn *scn = NULL;
3157 : : bool symtab_p = false;
3158 : : bool bits_alloc_p = false;
3159 : 23586 : while (true)
3160 : : {
3161 [ + - ]: 12017 : scn = elf_nextscn (elf, scn);
3162 [ + + ]: 11970 : if (scn == NULL)
3163 : : break;
3164 : 11766 : GElf_Shdr shdr_storage;
3165 [ + - ]: 11766 : GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_storage);
3166 [ - + ]: 11766 : if (shdr == NULL)
3167 : : break;
3168 [ + - ]: 11766 : const char *section_name = elf_strptr (elf, shstrndx, shdr->sh_name);
3169 [ - + ]: 11813 : if (section_name == NULL)
3170 : : break;
3171 [ + + ]: 11813 : if (startswith (section_name, ".debug_line") ||
3172 [ - + ]: 11569 : startswith (section_name, ".zdebug_line"))
3173 : : {
3174 : 244 : debuginfo_p = true;
3175 [ + - ]: 244 : if (scan_source_info)
3176 : 244 : dwarf_extract_source_paths (elf, debug_sourcefiles);
3177 : : break; // expecting only one .*debug_line, so no need to look for others
3178 : : }
3179 [ + + ]: 11569 : else if (startswith (section_name, ".debug_") ||
3180 [ + # ]: 10759 : startswith (section_name, ".zdebug_"))
3181 : : {
3182 : 770 : debuginfo_p = true;
3183 : : // NB: don't break; need to parse .debug_line for sources
3184 : : }
3185 [ + + ]: 10799 : else if (shdr->sh_type == SHT_SYMTAB)
3186 : : {
3187 : : symtab_p = true;
3188 : : }
3189 : 10775 : else if (shdr->sh_type != SHT_NOBITS
3190 [ + + ]: 10775 : && shdr->sh_type != SHT_NOTE
3191 [ + + ]: 5538 : && (shdr->sh_flags & SHF_ALLOC) != 0)
3192 : : {
3193 : 11569 : bits_alloc_p = true;
3194 : : }
3195 : 11569 : }
3196 : :
3197 : : // For more expansive elf/split-debuginfo classification, we
3198 : : // want to identify as debuginfo "strip -s"-produced files
3199 : : // without .debug_info* (like libicudata), but we don't want to
3200 : : // identify "strip -g" executables (with .symtab left there).
3201 [ - + ]: 448 : if (symtab_p && !bits_alloc_p)
3202 : 0 : debuginfo_p = true;
3203 : : }
3204 [ # # ]: 0 : catch (const reportable_exception& e)
3205 : : {
3206 [ # # ]: 0 : e.report(clog);
3207 : 0 : }
3208 : 448 : elf_end (elf);
3209 : : }
3210 : :
3211 : :
3212 : : // Intern the given file name in two parts (dirname & basename) and
3213 : : // return the resulting file's id.
3214 : : static int64_t
3215 : 30848 : register_file_name(sqlite_ps& ps_upsert_fileparts,
3216 : : sqlite_ps& ps_upsert_file,
3217 : : sqlite_ps& ps_lookup_file,
3218 : : const string& name)
3219 : : {
3220 : 30848 : std::size_t slash = name.rfind('/');
3221 [ + + ]: 30847 : string dirname, filename;
3222 [ + + ]: 30847 : if (slash == std::string::npos)
3223 : : {
3224 [ + - ]: 90 : dirname = "";
3225 [ + - ]: 90 : filename = name;
3226 : : }
3227 : : else
3228 : : {
3229 [ + - - + ]: 30757 : dirname = name.substr(0, slash);
3230 [ + - - + : 30757 : filename = name.substr(slash+1);
- - ]
3231 : : }
3232 : :
3233 : : // intern the two substrings
3234 : 30849 : ps_upsert_fileparts
3235 [ + - ]: 30849 : .reset()
3236 [ + - ]: 30850 : .bind(1, dirname)
3237 [ + - ]: 30849 : .step_ok_done();
3238 : 30850 : ps_upsert_fileparts
3239 [ + - ]: 30850 : .reset()
3240 [ + - ]: 30850 : .bind(1, filename)
3241 [ + - ]: 30848 : .step_ok_done();
3242 : :
3243 : : // intern the tuple
3244 : 30850 : ps_upsert_file
3245 [ + - ]: 30850 : .reset()
3246 [ + - ]: 30850 : .bind(1, dirname)
3247 [ + - ]: 30849 : .bind(2, filename)
3248 [ + - ]: 30850 : .step_ok_done();
3249 : :
3250 : : // look up the tuple's id
3251 : 30850 : ps_lookup_file
3252 [ + - ]: 30850 : .reset()
3253 [ + - ]: 30850 : .bind(1, dirname)
3254 [ + - ]: 30849 : .bind(2, filename);
3255 [ + - ]: 30850 : int rc = ps_lookup_file.step();
3256 [ - + - - : 30850 : if (rc != SQLITE_ROW) throw sqlite_exception(rc, "step");
- - ]
3257 : :
3258 [ + - ]: 30850 : int64_t id = sqlite3_column_int64 (ps_lookup_file, 0);
3259 [ + - ]: 30850 : ps_lookup_file.reset();
3260 [ + + ]: 30850 : return id;
3261 [ + + ]: 59528 : }
3262 : :
3263 : :
3264 : :
3265 : : static void
3266 : 974 : scan_source_file (const string& rps, const stat_t& st,
3267 : : sqlite_ps& ps_upsert_buildids,
3268 : : sqlite_ps& ps_upsert_fileparts,
3269 : : sqlite_ps& ps_upsert_file,
3270 : : sqlite_ps& ps_lookup_file,
3271 : : sqlite_ps& ps_upsert_de,
3272 : : sqlite_ps& ps_upsert_s,
3273 : : sqlite_ps& ps_query,
3274 : : sqlite_ps& ps_scan_done,
3275 : : unsigned& fts_cached,
3276 : : unsigned& fts_executable,
3277 : : unsigned& fts_debuginfo,
3278 : : unsigned& fts_sourcefiles)
3279 : : {
3280 : 974 : int64_t fileid = register_file_name(ps_upsert_fileparts, ps_upsert_file, ps_lookup_file, rps);
3281 : :
3282 : : /* See if we know of it already. */
3283 : 974 : int rc = ps_query
3284 : 974 : .reset()
3285 : 974 : .bind(1, fileid)
3286 : 974 : .bind(2, st.st_mtime)
3287 : 974 : .step();
3288 : 974 : ps_query.reset();
3289 [ + + ]: 974 : if (rc == SQLITE_ROW) // i.e., a result, as opposed to DONE (no results)
3290 : : // no need to recheck a file/version we already know
3291 : : // specifically, no need to elf-begin a file we already determined is non-elf
3292 : : // (so is stored with buildid=NULL)
3293 : : {
3294 : 368 : fts_cached++;
3295 : 368 : return;
3296 : : }
3297 : :
3298 : 606 : bool executable_p = false, debuginfo_p = false; // E and/or D
3299 [ + - ]: 606 : string buildid;
3300 [ + - ]: 606 : set<string> sourcefiles;
3301 : :
3302 [ + - ]: 606 : int fd = open (rps.c_str(), O_RDONLY);
3303 : 606 : try
3304 : : {
3305 [ + - ]: 606 : if (fd >= 0)
3306 [ + - ]: 606 : elf_classify (fd, executable_p, debuginfo_p, buildid, sourcefiles);
3307 : : else
3308 [ # # # # : 0 : throw libc_exception(errno, string("open ") + rps);
# # # # ]
3309 [ + - + - : 1212 : add_metric ("scanned_bytes_total","source","file",
+ - - + -
+ - - -
- ]
3310 [ + - ]: 606 : st.st_size);
3311 [ + - + - : 1212 : inc_metric ("scanned_files_total","source","file");
+ - + - -
+ - + - -
- - ]
3312 : : }
3313 : : // NB: we catch exceptions here too, so that we can
3314 : : // cache the corrupt-elf case (!executable_p &&
3315 : : // !debuginfo_p) just below, just as if we had an
3316 : : // EPERM error from open(2).
3317 [ - - ]: 0 : catch (const reportable_exception& e)
3318 : : {
3319 [ - - ]: 0 : e.report(clog);
3320 : 0 : }
3321 : :
3322 [ + - ]: 606 : if (fd >= 0)
3323 [ + - ]: 606 : close (fd);
3324 : :
3325 [ + + ]: 606 : if (buildid == "")
3326 : : {
3327 : : // no point storing an elf file without buildid
3328 : 510 : executable_p = false;
3329 : 510 : debuginfo_p = false;
3330 : : }
3331 : : else
3332 : : {
3333 : : // register this build-id in the interning table
3334 : 96 : ps_upsert_buildids
3335 [ + - ]: 96 : .reset()
3336 [ + - ]: 96 : .bind(1, buildid)
3337 [ + - ]: 96 : .step_ok_done();
3338 : : }
3339 : :
3340 [ + + ]: 606 : if (executable_p)
3341 : 72 : fts_executable ++;
3342 [ + + ]: 606 : if (debuginfo_p)
3343 : 72 : fts_debuginfo ++;
3344 [ + + + + ]: 606 : if (executable_p || debuginfo_p)
3345 : : {
3346 : 96 : ps_upsert_de
3347 [ + - ]: 96 : .reset()
3348 [ + - ]: 96 : .bind(1, buildid)
3349 [ + + + - ]: 120 : .bind(2, debuginfo_p ? 1 : 0)
3350 [ + + + - ]: 120 : .bind(3, executable_p ? 1 : 0)
3351 [ + - ]: 96 : .bind(4, fileid)
3352 [ + - ]: 96 : .bind(5, st.st_mtime)
3353 [ + - ]: 96 : .step_ok_done();
3354 : : }
3355 [ + + ]: 606 : if (executable_p)
3356 [ + - + - : 144 : inc_metric("found_executable_total","source","files");
+ - + - -
+ - + - -
- - ]
3357 [ + + ]: 606 : if (debuginfo_p)
3358 [ + - + - : 144 : inc_metric("found_debuginfo_total","source","files");
+ - + - -
+ - + - -
- - ]
3359 : :
3360 [ + + + - ]: 678 : if (sourcefiles.size() && buildid != "")
3361 : : {
3362 : 72 : fts_sourcefiles += sourcefiles.size();
3363 : :
3364 [ + + ]: 14310 : for (auto&& dwarfsrc : sourcefiles)
3365 : : {
3366 [ + - ]: 14238 : char *srp = realpath(dwarfsrc.c_str(), NULL);
3367 [ + + ]: 14238 : if (srp == NULL) // also if DWZ unresolved dwarfsrc=""
3368 : 220 : continue; // unresolvable files are not a serious problem
3369 : : // throw libc_exception(errno, "fts/file realpath " + srcpath);
3370 [ + - ]: 14018 : string srps = string(srp);
3371 : 14018 : free (srp);
3372 : :
3373 : 14018 : struct stat sfs;
3374 : 14018 : rc = stat(srps.c_str(), &sfs);
3375 [ - + ]: 14018 : if (rc != 0)
3376 [ # # ]: 0 : continue;
3377 : :
3378 [ + - ]: 14018 : if (verbose > 2)
3379 [ + - + - : 42054 : obatched(clog) << "recorded buildid=" << buildid << " file=" << srps
- - ]
3380 [ + - + - : 14018 : << " mtime=" << sfs.st_mtime
+ - + - ]
3381 [ + - + - : 14018 : << " as source " << dwarfsrc << endl;
+ - ]
3382 : :
3383 : : // PR25548: store canonicalized dwarfsrc path
3384 [ + - ]: 14018 : string dwarfsrc_canon = canon_pathname (dwarfsrc);
3385 [ + + ]: 14018 : if (dwarfsrc_canon != dwarfsrc)
3386 : : {
3387 [ + + ]: 2382 : if (verbose > 3)
3388 [ + - + - : 3768 : obatched(clog) << "canonicalized src=" << dwarfsrc << " alias=" << dwarfsrc_canon << endl;
+ - + - +
- ]
3389 : : }
3390 : :
3391 [ + - ]: 14018 : int64_t fileid1 = register_file_name (ps_upsert_fileparts, ps_upsert_file, ps_lookup_file, dwarfsrc_canon);
3392 [ + - ]: 14018 : int64_t fileid2 = register_file_name (ps_upsert_fileparts, ps_upsert_file, ps_lookup_file, srps);
3393 : :
3394 : 14018 : ps_upsert_s
3395 [ + - ]: 14018 : .reset()
3396 [ + - ]: 14018 : .bind(1, buildid)
3397 [ + - ]: 14018 : .bind(2, fileid1)
3398 [ + - ]: 14016 : .bind(3, fileid2)
3399 [ + - ]: 14017 : .bind(4, sfs.st_mtime)
3400 [ + - ]: 14018 : .step_ok_done();
3401 : :
3402 [ + - + - : 28036 : inc_metric("found_sourcerefs_total","source","files");
+ - + - -
+ - + + -
- - - - -
- ]
3403 [ + - ]: 28256 : }
3404 : : }
3405 : :
3406 : 606 : ps_scan_done
3407 [ + - ]: 606 : .reset()
3408 [ + - ]: 606 : .bind(1, fileid)
3409 [ + - ]: 606 : .bind(2, st.st_mtime)
3410 [ + - ]: 606 : .bind(3, st.st_size)
3411 [ + - ]: 606 : .step_ok_done();
3412 : :
3413 [ + - ]: 606 : if (verbose > 2)
3414 [ + - + - ]: 1818 : obatched(clog) << "recorded buildid=" << buildid << " file=" << rps
3415 [ + - + - : 606 : << " mtime=" << st.st_mtime << " atype="
+ - + - ]
3416 : : << (executable_p ? "E" : "")
3417 [ + - + + : 1674 : << (debuginfo_p ? "D" : "") << endl;
+ - + + +
- + - ]
3418 [ + + ]: 702 : }
3419 : :
3420 : :
3421 : :
3422 : :
3423 : :
3424 : : // Analyze given archive file of given age; record buildids / exec/debuginfo-ness of its
3425 : : // constituent files with given upsert statements.
3426 : : static void
3427 : 362 : archive_classify (const string& rps, string& archive_extension, int64_t archiveid,
3428 : : sqlite_ps& ps_upsert_buildids, sqlite_ps& ps_upsert_fileparts, sqlite_ps& ps_upsert_file,
3429 : : sqlite_ps& ps_lookup_file,
3430 : : sqlite_ps& ps_upsert_de, sqlite_ps& ps_upsert_sref, sqlite_ps& ps_upsert_sdef,
3431 : : time_t mtime,
3432 : : unsigned& fts_executable, unsigned& fts_debuginfo, unsigned& fts_sref, unsigned& fts_sdef,
3433 : : bool& fts_sref_complete_p)
3434 : : {
3435 : 362 : string archive_decoder = "/dev/null";
3436 [ + + ]: 896 : for (auto&& arch : scan_archives)
3437 [ + + ]: 534 : if (string_endswith(rps, arch.first))
3438 : : {
3439 [ + - ]: 362 : archive_extension = arch.first;
3440 [ + - ]: 896 : archive_decoder = arch.second;
3441 : : }
3442 : :
3443 : 362 : FILE* fp;
3444 : 362 : defer_dtor<FILE*,int>::dtor_fn dfn;
3445 [ + + ]: 362 : if (archive_decoder != "cat")
3446 : : {
3447 [ + - + - : 64 : string popen_cmd = archive_decoder + " " + shell_escape(rps);
+ - - + -
- - - ]
3448 [ + - ]: 32 : fp = popen (popen_cmd.c_str(), "r"); // "e" O_CLOEXEC?
3449 : 32 : dfn = pclose;
3450 [ - + ]: 32 : if (fp == NULL)
3451 [ # # # # : 0 : throw libc_exception (errno, string("popen ") + popen_cmd);
# # # # ]
3452 : 32 : }
3453 : : else
3454 : : {
3455 [ + - ]: 330 : fp = fopen (rps.c_str(), "r");
3456 : 330 : dfn = fclose;
3457 [ - + ]: 330 : if (fp == NULL)
3458 [ # # # # : 0 : throw libc_exception (errno, string("fopen ") + rps);
# # # # ]
3459 : : }
3460 : 362 : defer_dtor<FILE*,int> fp_closer (fp, dfn);
3461 : :
3462 : 362 : struct archive *a;
3463 [ + - ]: 362 : a = archive_read_new();
3464 [ - + ]: 362 : if (a == NULL)
3465 [ # # # # ]: 0 : throw archive_exception("cannot create archive reader");
3466 : 362 : defer_dtor<struct archive*,int> archive_closer (a, archive_read_free);
3467 : :
3468 [ + - ]: 362 : int rc = archive_read_support_format_all(a);
3469 [ - + ]: 362 : if (rc != ARCHIVE_OK)
3470 [ # # # # ]: 0 : throw archive_exception(a, "cannot select all formats");
3471 [ + - ]: 362 : rc = archive_read_support_filter_all(a);
3472 [ - + ]: 362 : if (rc != ARCHIVE_OK)
3473 [ # # # # ]: 0 : throw archive_exception(a, "cannot select all filters");
3474 : :
3475 [ + - ]: 362 : rc = archive_read_open_FILE (a, fp);
3476 [ - + ]: 362 : if (rc != ARCHIVE_OK)
3477 : : {
3478 [ # # # # : 0 : obatched(clog) << "cannot open archive from pipe " << rps << endl;
# # ]
3479 [ # # # # ]: 0 : throw archive_exception(a, "cannot open archive from pipe");
3480 : : }
3481 : :
3482 [ + + ]: 362 : if (verbose > 3)
3483 [ + - + - : 692 : obatched(clog) << "libarchive scanning " << rps << " id " << archiveid << endl;
+ - + - +
- ]
3484 : :
3485 : : bool any_exceptions = false;
3486 : 2564 : while(1) // parse archive entries
3487 : : {
3488 [ + - ]: 2564 : if (interrupted)
3489 : : break;
3490 : :
3491 : 2564 : try
3492 : : {
3493 : 2564 : struct archive_entry *e;
3494 [ + - ]: 2564 : rc = archive_read_next_header (a, &e);
3495 [ + + ]: 2564 : if (rc != ARCHIVE_OK)
3496 : : break;
3497 : :
3498 [ + - + + ]: 2202 : if (! S_ISREG(archive_entry_mode (e))) // skip non-files completely
3499 : 1528 : continue;
3500 : :
3501 [ + - ]: 674 : string fn = canonicalized_archive_entry_pathname (e);
3502 : :
3503 [ + + ]: 674 : if (verbose > 3)
3504 [ + - + - : 1268 : obatched(clog) << "libarchive checking " << fn << endl;
+ - - - ]
3505 : :
3506 : : // extract this file to a temporary file
3507 : 674 : char* tmppath = NULL;
3508 : 674 : rc = asprintf (&tmppath, "%s/debuginfod-classify.XXXXXX", tmpdir.c_str());
3509 [ - + ]: 674 : if (rc < 0)
3510 [ # # # # ]: 0 : throw libc_exception (ENOMEM, "cannot allocate tmppath");
3511 : 674 : defer_dtor<void*,void> tmmpath_freer (tmppath, free);
3512 [ + - ]: 674 : int fd = mkstemp (tmppath);
3513 [ - + ]: 674 : if (fd < 0)
3514 [ # # # # ]: 0 : throw libc_exception (errno, "cannot create temporary file");
3515 : 674 : unlink (tmppath); // unlink now so OS will release the file as soon as we close the fd
3516 : 674 : defer_dtor<int,int> minifd_closer (fd, close);
3517 : :
3518 [ + - ]: 674 : rc = archive_read_data_into_fd (a, fd);
3519 [ - + ]: 674 : if (rc != ARCHIVE_OK) {
3520 [ # # ]: 0 : close (fd);
3521 [ # # # # ]: 0 : throw archive_exception(a, "cannot extract file");
3522 : : }
3523 : :
3524 : : // finally ... time to run elf_classify on this bad boy and update the database
3525 : 674 : bool executable_p = false, debuginfo_p = false;
3526 [ + - ]: 674 : string buildid;
3527 [ + - ]: 674 : set<string> sourcefiles;
3528 [ + - ]: 674 : elf_classify (fd, executable_p, debuginfo_p, buildid, sourcefiles);
3529 : : // NB: might throw
3530 : :
3531 [ + + ]: 674 : if (buildid != "") // intern buildid
3532 : : {
3533 : 352 : ps_upsert_buildids
3534 [ + - ]: 352 : .reset()
3535 [ + - ]: 352 : .bind(1, buildid)
3536 [ + - ]: 352 : .step_ok_done();
3537 : : }
3538 : :
3539 [ + - ]: 674 : int64_t fileid = register_file_name (ps_upsert_fileparts, ps_upsert_file, ps_lookup_file, fn);
3540 : :
3541 [ + + ]: 674 : if (sourcefiles.size() > 0) // sref records needed
3542 : : {
3543 : : // NB: we intern each source file once. Once raw, as it
3544 : : // appears in the DWARF file list coming back from
3545 : : // elf_classify() - because it'll end up in the
3546 : : // _norm.artifactsrc column. We don't also put another
3547 : : // version with a '.' at the front, even though that's
3548 : : // how rpm/cpio packs names, because we hide that from
3549 : : // the database for storage efficiency.
3550 : :
3551 [ + + ]: 616 : for (auto&& s : sourcefiles)
3552 : : {
3553 [ - + ]: 464 : if (s == "")
3554 : : {
3555 : 0 : fts_sref_complete_p = false;
3556 : 0 : continue;
3557 : : }
3558 : :
3559 : : // PR25548: store canonicalized source path
3560 : 464 : const string& dwarfsrc = s;
3561 [ + - ]: 464 : string dwarfsrc_canon = canon_pathname (dwarfsrc);
3562 [ + + ]: 464 : if (dwarfsrc_canon != dwarfsrc)
3563 : : {
3564 [ + - ]: 32 : if (verbose > 3)
3565 [ + - + - : 64 : obatched(clog) << "canonicalized src=" << dwarfsrc << " alias=" << dwarfsrc_canon << endl;
+ - + - +
- - - ]
3566 : : }
3567 : :
3568 [ + - ]: 464 : int64_t srcfileid = register_file_name(ps_upsert_fileparts, ps_upsert_file, ps_lookup_file,
3569 : : dwarfsrc_canon);
3570 : :
3571 : 464 : ps_upsert_sref
3572 [ + - ]: 464 : .reset()
3573 [ + - ]: 464 : .bind(1, buildid)
3574 [ + - ]: 464 : .bind(2, srcfileid)
3575 [ + - ]: 464 : .step_ok_done();
3576 : :
3577 [ + - ]: 464 : fts_sref ++;
3578 : 464 : }
3579 : : }
3580 : :
3581 [ + + ]: 674 : if (executable_p)
3582 : 150 : fts_executable ++;
3583 [ + + ]: 674 : if (debuginfo_p)
3584 : 202 : fts_debuginfo ++;
3585 : :
3586 [ + + + + ]: 674 : if (executable_p || debuginfo_p)
3587 : : {
3588 : 352 : ps_upsert_de
3589 [ + - ]: 352 : .reset()
3590 [ + - ]: 352 : .bind(1, buildid)
3591 [ + + + - ]: 502 : .bind(2, debuginfo_p ? 1 : 0)
3592 [ + + + - ]: 554 : .bind(3, executable_p ? 1 : 0)
3593 [ + - ]: 352 : .bind(4, archiveid)
3594 [ + - ]: 352 : .bind(5, mtime)
3595 [ + - ]: 352 : .bind(6, fileid)
3596 [ + - ]: 352 : .step_ok_done();
3597 : : }
3598 : : else // potential source - sdef record
3599 : : {
3600 : 322 : fts_sdef ++;
3601 : 322 : ps_upsert_sdef
3602 [ + - ]: 322 : .reset()
3603 [ + - ]: 322 : .bind(1, archiveid)
3604 [ + - ]: 322 : .bind(2, mtime)
3605 [ + - ]: 322 : .bind(3, fileid)
3606 [ + - ]: 322 : .step_ok_done();
3607 : : }
3608 : :
3609 [ + - + + : 674 : if ((verbose > 2) && (executable_p || debuginfo_p))
+ + ]
3610 [ + - + - ]: 1056 : obatched(clog) << "recorded buildid=" << buildid << " rpm=" << rps << " file=" << fn
3611 [ + - + - : 352 : << " mtime=" << mtime << " atype="
+ - + - +
- + - ]
3612 : : << (executable_p ? "E" : "")
3613 : : << (debuginfo_p ? "D" : "")
3614 [ + - + + : 704 : << " sourcefiles=" << sourcefiles.size() << endl;
+ - + + +
- + - + -
+ - ]
3615 : :
3616 [ + + + + ]: 1532 : }
3617 [ - - ]: 0 : catch (const reportable_exception& e)
3618 : : {
3619 [ - - ]: 0 : e.report(clog);
3620 : 0 : any_exceptions = true;
3621 : : // NB: but we allow the libarchive iteration to continue, in
3622 : : // case we can still gather some useful information. That
3623 : : // would allow some webapi queries to work, until later when
3624 : : // this archive is rescanned. (Its vitals won't go into the
3625 : : // _file_mtime_scanned table until after a successful scan.)
3626 : 0 : }
3627 : : }
3628 : :
3629 [ - + ]: 362 : if (any_exceptions)
3630 [ # # # # ]: 0 : throw reportable_exception("exceptions encountered during archive scan");
3631 [ + + ]: 378 : }
3632 : :
3633 : :
3634 : :
3635 : : // scan for archive files such as .rpm
3636 : : static void
3637 : 702 : scan_archive_file (const string& rps, const stat_t& st,
3638 : : sqlite_ps& ps_upsert_buildids,
3639 : : sqlite_ps& ps_upsert_fileparts,
3640 : : sqlite_ps& ps_upsert_file,
3641 : : sqlite_ps& ps_lookup_file,
3642 : : sqlite_ps& ps_upsert_de,
3643 : : sqlite_ps& ps_upsert_sref,
3644 : : sqlite_ps& ps_upsert_sdef,
3645 : : sqlite_ps& ps_query,
3646 : : sqlite_ps& ps_scan_done,
3647 : : unsigned& fts_cached,
3648 : : unsigned& fts_executable,
3649 : : unsigned& fts_debuginfo,
3650 : : unsigned& fts_sref,
3651 : : unsigned& fts_sdef)
3652 : : {
3653 : : // intern the archive file name
3654 : 702 : int64_t archiveid = register_file_name (ps_upsert_fileparts, ps_upsert_file, ps_lookup_file, rps);
3655 : :
3656 : : /* See if we know of it already. */
3657 : 702 : int rc = ps_query
3658 : 702 : .reset()
3659 : 702 : .bind(1, archiveid)
3660 : 702 : .bind(2, st.st_mtime)
3661 : 702 : .step();
3662 : 702 : ps_query.reset();
3663 [ + + ]: 702 : if (rc == SQLITE_ROW) // i.e., a result, as opposed to DONE (no results)
3664 : : // no need to recheck a file/version we already know
3665 : : // specifically, no need to parse this archive again, since we already have
3666 : : // it as a D or E or S record,
3667 : : // (so is stored with buildid=NULL)
3668 : : {
3669 : 340 : fts_cached ++;
3670 : 340 : return;
3671 : : }
3672 : :
3673 : : // extract the archive contents
3674 : 362 : unsigned my_fts_executable = 0, my_fts_debuginfo = 0, my_fts_sref = 0, my_fts_sdef = 0;
3675 : 362 : bool my_fts_sref_complete_p = true;
3676 : 362 : bool any_exceptions = false;
3677 : 362 : try
3678 : : {
3679 [ + - ]: 362 : string archive_extension;
3680 : 362 : archive_classify (rps, archive_extension, archiveid,
3681 : : ps_upsert_buildids, ps_upsert_fileparts, ps_upsert_file, ps_lookup_file,
3682 : : ps_upsert_de, ps_upsert_sref, ps_upsert_sdef, // dalt
3683 [ + - ]: 362 : st.st_mtime,
3684 : : my_fts_executable, my_fts_debuginfo, my_fts_sref, my_fts_sdef,
3685 : : my_fts_sref_complete_p);
3686 [ + - + - : 724 : add_metric ("scanned_bytes_total","source",archive_extension + " archive",
+ - - + +
+ - - -
- ]
3687 [ + - ]: 362 : st.st_size);
3688 [ + - + - : 724 : inc_metric ("scanned_files_total","source",archive_extension + " archive");
+ - + - -
+ + + - -
- - ]
3689 [ + - + - : 724 : add_metric("found_debuginfo_total","source",archive_extension + " archive",
+ - + - -
+ + + - -
- - ]
3690 : : my_fts_debuginfo);
3691 [ + - + - : 724 : add_metric("found_executable_total","source",archive_extension + " archive",
+ - + - -
+ + + - -
- - ]
3692 : : my_fts_executable);
3693 [ + - + - : 740 : add_metric("found_sourcerefs_total","source",archive_extension + " archive",
+ - + - -
+ + + - +
- - - - -
- ]
3694 : : my_fts_sref);
3695 : 362 : }
3696 [ - - ]: 0 : catch (const reportable_exception& e)
3697 : : {
3698 [ - - ]: 0 : e.report(clog);
3699 : 0 : any_exceptions = true;
3700 : 0 : }
3701 : :
3702 [ + - ]: 362 : if (verbose > 2)
3703 [ + - ]: 1086 : obatched(clog) << "scanned archive=" << rps
3704 [ + - + - ]: 362 : << " mtime=" << st.st_mtime
3705 [ + - ]: 362 : << " executables=" << my_fts_executable
3706 [ + - + - ]: 362 : << " debuginfos=" << my_fts_debuginfo
3707 [ + - + - ]: 362 : << " srefs=" << my_fts_sref
3708 [ + - + - ]: 362 : << " sdefs=" << my_fts_sdef
3709 [ + - + - : 362 : << " exceptions=" << any_exceptions
+ - + - ]
3710 : 362 : << endl;
3711 : :
3712 : 362 : fts_executable += my_fts_executable;
3713 : 362 : fts_debuginfo += my_fts_debuginfo;
3714 : 362 : fts_sref += my_fts_sref;
3715 : 362 : fts_sdef += my_fts_sdef;
3716 : :
3717 [ - + ]: 362 : if (any_exceptions)
3718 [ # # # # ]: 0 : throw reportable_exception("exceptions encountered during archive scan");
3719 : :
3720 [ + - ]: 362 : if (my_fts_sref_complete_p) // leave incomplete?
3721 : 362 : ps_scan_done
3722 : 362 : .reset()
3723 : 362 : .bind(1, archiveid)
3724 : 362 : .bind(2, st.st_mtime)
3725 : 362 : .bind(3, st.st_size)
3726 : 362 : .step_ok_done();
3727 : : }
3728 : :
3729 : :
3730 : :
3731 : : ////////////////////////////////////////////////////////////////////////
3732 : :
3733 : :
3734 : :
3735 : : // The thread that consumes file names off of the scanq. We hold
3736 : : // the persistent sqlite_ps's at this level and delegate file/archive
3737 : : // scanning to other functions.
3738 : : static void
3739 : 264 : scan ()
3740 : : {
3741 : : // all the prepared statements fit to use, the _f_ set:
3742 [ + - + - : 528 : sqlite_ps ps_f_upsert_buildids (db, "file-buildids-intern", "insert or ignore into " BUILDIDS "_buildids VALUES (NULL, ?);");
+ - - - ]
3743 [ + - + - : 528 : sqlite_ps ps_f_upsert_fileparts (db, "file-fileparts-intern", "insert or ignore into " BUILDIDS "_fileparts VALUES (NULL, ?);");
+ - + - -
- ]
3744 [ + - ]: 264 : sqlite_ps ps_f_upsert_file (db, "file-file-intern", "insert or ignore into " BUILDIDS "_files VALUES (NULL, \n"
3745 : : "(select id from " BUILDIDS "_fileparts where name = ?),\n"
3746 [ + - + - : 528 : "(select id from " BUILDIDS "_fileparts where name = ?));");
+ - + - -
- ]
3747 [ + - ]: 264 : sqlite_ps ps_f_lookup_file (db, "file-file-lookup",
3748 : : "select f.id\n"
3749 : : " from " BUILDIDS "_files f, " BUILDIDS "_fileparts p1, " BUILDIDS "_fileparts p2 \n"
3750 [ + - + - : 528 : " where f.dirname = p1.id and f.basename = p2.id and p1.name = ? and p2.name = ?;\n");
+ - + - -
- ]
3751 [ + - ]: 264 : sqlite_ps ps_f_upsert_de (db, "file-de-upsert",
3752 : : "insert or ignore into " BUILDIDS "_f_de "
3753 : : "(buildid, debuginfo_p, executable_p, file, mtime) "
3754 : : "values ((select id from " BUILDIDS "_buildids where hex = ?),"
3755 [ + - + - : 528 : " ?,?,?,?);");
+ - + - -
- ]
3756 [ + - ]: 264 : sqlite_ps ps_f_upsert_s (db, "file-s-upsert",
3757 : : "insert or ignore into " BUILDIDS "_f_s "
3758 : : "(buildid, artifactsrc, file, mtime) "
3759 : : "values ((select id from " BUILDIDS "_buildids where hex = ?),"
3760 [ + - + - : 528 : " ?,?,?);");
+ - + - -
- ]
3761 [ + - ]: 264 : sqlite_ps ps_f_query (db, "file-negativehit-find",
3762 : : "select 1 from " BUILDIDS "_file_mtime_scanned where sourcetype = 'F' "
3763 [ + - + - : 528 : "and file = ? and mtime = ?;");
+ - + - -
- ]
3764 [ + - ]: 264 : sqlite_ps ps_f_scan_done (db, "file-scanned",
3765 : : "insert or ignore into " BUILDIDS "_file_mtime_scanned (sourcetype, file, mtime, size)"
3766 [ + - + - : 528 : "values ('F', ?,?,?);");
+ - + - -
- ]
3767 : :
3768 : : // and now for the _r_ set
3769 [ + - + - : 528 : sqlite_ps ps_r_upsert_buildids (db, "rpm-buildid-intern", "insert or ignore into " BUILDIDS "_buildids VALUES (NULL, ?);");
+ - + - -
- ]
3770 [ + - + - : 528 : sqlite_ps ps_r_upsert_fileparts (db, "rpm-fileparts-intern", "insert or ignore into " BUILDIDS "_fileparts VALUES (NULL, ?);");
+ - + - -
- ]
3771 [ + - ]: 264 : sqlite_ps ps_r_upsert_file (db, "rpm-file-intern", "insert or ignore into " BUILDIDS "_files VALUES (NULL, \n"
3772 : : "(select id from " BUILDIDS "_fileparts where name = ?),\n"
3773 [ + - + - : 528 : "(select id from " BUILDIDS "_fileparts where name = ?));");
+ - + - -
- ]
3774 [ + - ]: 264 : sqlite_ps ps_r_lookup_file (db, "rpm-file-lookup",
3775 : : "select f.id\n"
3776 : : " from " BUILDIDS "_files f, " BUILDIDS "_fileparts p1, " BUILDIDS "_fileparts p2 \n"
3777 [ + - + - : 528 : " where f.dirname = p1.id and f.basename = p2.id and p1.name = ? and p2.name = ?;\n");
+ - + - -
- ]
3778 [ + - ]: 264 : sqlite_ps ps_r_upsert_de (db, "rpm-de-insert",
3779 : : "insert or ignore into " BUILDIDS "_r_de (buildid, debuginfo_p, executable_p, file, mtime, content) values ("
3780 [ + - + - : 528 : "(select id from " BUILDIDS "_buildids where hex = ?), ?, ?, ?, ?, ?);");
+ - + - -
- ]
3781 [ + - ]: 264 : sqlite_ps ps_r_upsert_sref (db, "rpm-sref-insert",
3782 : : "insert or ignore into " BUILDIDS "_r_sref (buildid, artifactsrc) values ("
3783 : : "(select id from " BUILDIDS "_buildids where hex = ?), "
3784 [ + - + - : 528 : "?);");
+ - + - -
- ]
3785 [ + - ]: 264 : sqlite_ps ps_r_upsert_sdef (db, "rpm-sdef-insert",
3786 : : "insert or ignore into " BUILDIDS "_r_sdef (file, mtime, content) values ("
3787 [ + - + - : 528 : "?, ?, ?);");
+ - + - -
- ]
3788 [ + - ]: 264 : sqlite_ps ps_r_query (db, "rpm-negativehit-query",
3789 : : "select 1 from " BUILDIDS "_file_mtime_scanned where "
3790 [ + - + - : 528 : "sourcetype = 'R' and file = ? and mtime = ?;");
+ - + - -
- ]
3791 [ + - ]: 264 : sqlite_ps ps_r_scan_done (db, "rpm-scanned",
3792 : : "insert or ignore into " BUILDIDS "_file_mtime_scanned (sourcetype, file, mtime, size)"
3793 [ + - + - : 528 : "values ('R', ?, ?, ?);");
+ - + - -
- ]
3794 : :
3795 : :
3796 : 264 : unsigned fts_cached = 0, fts_executable = 0, fts_debuginfo = 0, fts_sourcefiles = 0;
3797 : 264 : unsigned fts_sref = 0, fts_sdef = 0;
3798 : :
3799 [ + - + - : 528 : add_metric("thread_count", "role", "scan", 1);
+ - + - -
+ - + - -
- - ]
3800 [ + - + - : 528 : add_metric("thread_busy", "role", "scan", 1);
+ - + - -
+ - + - -
- - ]
3801 [ + + ]: 1713 : while (! interrupted)
3802 : : {
3803 [ + - ]: 1449 : scan_payload p;
3804 : :
3805 [ + - + - : 2899 : add_metric("thread_busy", "role", "scan", -1);
+ - + - -
+ - + - -
- - ]
3806 : : // NB: threads may be blocked within either of these two waiting
3807 : : // states, if the work queue happens to run dry. That's OK.
3808 [ + - + - ]: 1450 : if (scan_barrier) scan_barrier->count();
3809 [ + - ]: 1450 : bool gotone = scanq.wait_front(p);
3810 [ + - + - : 2899 : add_metric("thread_busy", "role", "scan", 1);
+ - + - -
+ - + - -
- - ]
3811 : :
3812 [ + + - + ]: 1449 : if (! gotone) continue; // go back to waiting
3813 : :
3814 : 1186 : try
3815 : : {
3816 : 1186 : bool scan_archive = false;
3817 [ + + ]: 2486 : for (auto&& arch : scan_archives)
3818 [ + + ]: 1300 : if (string_endswith(p.first, arch.first))
3819 : 702 : scan_archive = true;
3820 : :
3821 [ + + ]: 1186 : if (scan_archive)
3822 [ + - ]: 702 : scan_archive_file (p.first, p.second,
3823 : : ps_r_upsert_buildids,
3824 : : ps_r_upsert_fileparts,
3825 : : ps_r_upsert_file,
3826 : : ps_r_lookup_file,
3827 : : ps_r_upsert_de,
3828 : : ps_r_upsert_sref,
3829 : : ps_r_upsert_sdef,
3830 : : ps_r_query,
3831 : : ps_r_scan_done,
3832 : : fts_cached,
3833 : : fts_executable,
3834 : : fts_debuginfo,
3835 : : fts_sref,
3836 : : fts_sdef);
3837 : :
3838 [ + + ]: 1186 : if (scan_files) // NB: maybe "else if" ?
3839 [ + - ]: 974 : scan_source_file (p.first, p.second,
3840 : : ps_f_upsert_buildids,
3841 : : ps_f_upsert_fileparts,
3842 : : ps_f_upsert_file,
3843 : : ps_f_lookup_file,
3844 : : ps_f_upsert_de,
3845 : : ps_f_upsert_s,
3846 : : ps_f_query,
3847 : : ps_f_scan_done,
3848 : : fts_cached, fts_executable, fts_debuginfo, fts_sourcefiles);
3849 : : }
3850 [ - - ]: 0 : catch (const reportable_exception& e)
3851 : : {
3852 [ - - ]: 0 : e.report(cerr);
3853 : 0 : }
3854 : :
3855 [ + - ]: 1186 : scanq.done_front(); // let idlers run
3856 : :
3857 : 1186 : if (fts_cached || fts_executable || fts_debuginfo || fts_sourcefiles || fts_sref || fts_sdef)
3858 : : {} // NB: not just if a successful scan - we might have encountered -ENOSPC & failed
3859 [ + - + - ]: 1186 : (void) statfs_free_enough_p(db_path, "database"); // report sqlite filesystem size
3860 [ + - + - ]: 1186 : (void) statfs_free_enough_p(tmpdir, "tmpdir"); // this too, in case of fdcache/tmpfile usage
3861 : :
3862 : : // finished a scanning step -- not a "loop", because we just
3863 : : // consume the traversal loop's work, whenever
3864 [ + - + - : 2372 : inc_metric("thread_work_total","role","scan");
+ - + - -
+ - + + -
- - - - -
- ]
3865 : 1449 : }
3866 : :
3867 [ + - + - : 525 : add_metric("thread_busy", "role", "scan", -1);
+ - + - -
+ - + - -
- - ]
3868 : 261 : }
3869 : :
3870 : :
3871 : : // Use this function as the thread entry point, so it can catch our
3872 : : // fleet of exceptions (incl. the sqlite_ps ctors) and report.
3873 : : static void*
3874 : 264 : thread_main_scanner (void* arg)
3875 : : {
3876 : 264 : (void) arg;
3877 [ + + ]: 792 : while (! interrupted)
3878 : 264 : try
3879 : : {
3880 [ + - ]: 264 : scan();
3881 : : }
3882 [ - - ]: 0 : catch (const reportable_exception& e)
3883 : : {
3884 [ - - ]: 0 : e.report(cerr);
3885 : 0 : }
3886 : 264 : return 0;
3887 : : }
3888 : :
3889 : :
3890 : :
3891 : : // The thread that traverses all the source_paths and enqueues all the
3892 : : // matching files into the file/archive scan queue.
3893 : : static void
3894 : 120 : scan_source_paths()
3895 : : {
3896 : : // NB: fedora 31 glibc/fts(3) crashes inside fts_read() on empty
3897 : : // path list.
3898 [ + + ]: 120 : if (source_paths.empty())
3899 : 2 : return;
3900 : :
3901 : : // Turn the source_paths into an fts(3)-compatible char**. Since
3902 : : // source_paths[] does not change after argv processing, the
3903 : : // c_str()'s are safe to keep around awile.
3904 : 118 : vector<const char *> sps;
3905 [ + + ]: 318 : for (auto&& sp: source_paths)
3906 [ + - ]: 200 : sps.push_back(sp.c_str());
3907 [ + - - - ]: 118 : sps.push_back(NULL);
3908 : :
3909 [ + + + - ]: 222 : FTS *fts = fts_open ((char * const *)sps.data(),
3910 : : (traverse_logical ? FTS_LOGICAL : FTS_PHYSICAL|FTS_XDEV)
3911 : : | FTS_NOCHDIR /* multithreaded */,
3912 : : NULL);
3913 [ - + ]: 118 : if (fts == NULL)
3914 [ # # # # ]: 0 : throw libc_exception(errno, "cannot fts_open");
3915 : 118 : defer_dtor<FTS*,int> fts_cleanup (fts, fts_close);
3916 : :
3917 : 118 : struct timespec ts_start, ts_end;
3918 : 118 : clock_gettime (CLOCK_MONOTONIC, &ts_start);
3919 : 118 : unsigned fts_scanned = 0, fts_regex = 0;
3920 : :
3921 : 118 : FTSENT *f;
3922 [ + - + + ]: 2374 : while ((f = fts_read (fts)) != NULL)
3923 : : {
3924 [ + - ]: 2138 : if (interrupted) break;
3925 : :
3926 [ - + ]: 2138 : if (sigusr2 != forced_groom_count) // stop early if groom triggered
3927 : : {
3928 [ # # ]: 0 : scanq.clear(); // clear previously issued work for scanner threads
3929 : : break;
3930 : : }
3931 : :
3932 : 2138 : fts_scanned ++;
3933 : :
3934 [ + - ]: 2138 : if (verbose > 2)
3935 [ + - + - : 4276 : obatched(clog) << "fts traversing " << f->fts_path << endl;
+ - ]
3936 : :
3937 [ + + + + : 2138 : switch (f->fts_info)
+ ]
3938 : : {
3939 : 1274 : case FTS_F:
3940 : 1274 : {
3941 : : /* Found a file. Convert it to an absolute path, so
3942 : : the buildid database does not have relative path
3943 : : names that are unresolvable from a subsequent run
3944 : : in a different cwd. */
3945 [ + - ]: 1274 : char *rp = realpath(f->fts_path, NULL);
3946 [ - + ]: 1274 : if (rp == NULL)
3947 : 0 : continue; // ignore dangling symlink or such
3948 [ + - ]: 1274 : string rps = string(rp);
3949 : 1274 : free (rp);
3950 : :
3951 [ + - ]: 1274 : bool ri = !regexec (&file_include_regex, rps.c_str(), 0, 0, 0);
3952 [ + - ]: 1274 : bool rx = !regexec (&file_exclude_regex, rps.c_str(), 0, 0, 0);
3953 [ + + ]: 1274 : if (!ri || rx)
3954 : : {
3955 [ + - ]: 88 : if (verbose > 3)
3956 [ + - ]: 176 : obatched(clog) << "fts skipped by regex "
3957 [ + + + - : 96 : << (!ri ? "I" : "") << (rx ? "X" : "") << endl;
+ + + - +
- ]
3958 : 88 : fts_regex ++;
3959 [ + + ]: 88 : if (!ri)
3960 [ + - + - : 8 : inc_metric("traversed_total","type","file-skipped-I");
+ - + - -
+ - + - -
- - ]
3961 [ + + ]: 88 : if (rx)
3962 [ + - + - : 168 : inc_metric("traversed_total","type","file-skipped-X");
+ - + - -
+ - + - -
- - ]
3963 : : }
3964 : : else
3965 : : {
3966 [ + - + - ]: 1186 : scanq.push_back (make_pair(rps, *f->fts_statp));
3967 [ + - + - : 2372 : inc_metric("traversed_total","type","file");
+ - + - -
+ - + - -
- - - - ]
3968 : : }
3969 : 0 : }
3970 : 1274 : break;
3971 : :
3972 : 4 : case FTS_ERR:
3973 : 4 : case FTS_NS:
3974 : : // report on some types of errors because they may reflect fixable misconfiguration
3975 : 4 : {
3976 [ + - + - : 8 : auto x = libc_exception(f->fts_errno, string("fts traversal ") + string(f->fts_path));
+ - + - -
+ - + -
- ]
3977 [ + - ]: 4 : x.report(cerr);
3978 : 0 : }
3979 [ + - + - : 8 : inc_metric("traversed_total","type","error");
+ - + - -
+ - + - -
- - ]
3980 : 4 : break;
3981 : :
3982 : 12 : case FTS_SL: // ignore, but count because debuginfod -L would traverse these
3983 [ + - + - : 24 : inc_metric("traversed_total","type","symlink");
+ - + - -
+ - + - -
- - ]
3984 : 12 : break;
3985 : :
3986 : 424 : case FTS_D: // ignore
3987 [ + - + - : 848 : inc_metric("traversed_total","type","directory");
+ - + - -
+ - + - -
- - ]
3988 : 424 : break;
3989 : :
3990 : 424 : default: // ignore
3991 [ + - + - : 848 : inc_metric("traversed_total","type","other");
+ - + - -
+ - + - -
- - ]
3992 : 424 : break;
3993 : : }
3994 : : }
3995 : 118 : clock_gettime (CLOCK_MONOTONIC, &ts_end);
3996 : 118 : double deltas = (ts_end.tv_sec - ts_start.tv_sec) + (ts_end.tv_nsec - ts_start.tv_nsec)/1.e9;
3997 : :
3998 [ + - + - : 354 : obatched(clog) << "fts traversed source paths in " << deltas << "s, scanned=" << fts_scanned
+ - + - ]
3999 [ + - + - : 118 : << ", regex-skipped=" << fts_regex << endl;
+ - ]
4000 [ + - ]: 236 : }
4001 : :
4002 : :
4003 : : static void*
4004 : 66 : thread_main_fts_source_paths (void* arg)
4005 : : {
4006 : 66 : (void) arg; // ignore; we operate on global data
4007 : :
4008 [ + - + - : 132 : set_metric("thread_tid", "role","traverse", tid());
+ - - + -
+ - - -
- ]
4009 [ + - + - : 132 : add_metric("thread_count", "role", "traverse", 1);
+ - - + -
+ - - -
- ]
4010 : :
4011 : 66 : time_t last_rescan = 0;
4012 : :
4013 [ + - ]: 296 : while (! interrupted)
4014 : : {
4015 : 296 : sleep (1);
4016 : 296 : scanq.wait_idle(); // don't start a new traversal while scanners haven't finished the job
4017 : 296 : scanq.done_idle(); // release the hounds
4018 [ + + ]: 296 : if (interrupted) break;
4019 : :
4020 : 230 : time_t now = time(NULL);
4021 : 230 : bool rescan_now = false;
4022 [ + + ]: 230 : if (last_rescan == 0) // at least one initial rescan is documented even for -t0
4023 : 64 : rescan_now = true;
4024 [ + + + + ]: 230 : if (rescan_s > 0 && (long)now > (long)(last_rescan + rescan_s))
4025 : 230 : rescan_now = true;
4026 [ + + ]: 230 : if (sigusr1 != forced_rescan_count)
4027 : : {
4028 : 60 : forced_rescan_count = sigusr1;
4029 : 60 : rescan_now = true;
4030 : : }
4031 [ + + ]: 230 : if (rescan_now)
4032 : : {
4033 [ + - + - : 240 : set_metric("thread_busy", "role","traverse", 1);
+ - - + -
+ - - -
- ]
4034 : 120 : try
4035 : : {
4036 [ + - ]: 120 : scan_source_paths();
4037 : : }
4038 [ - - ]: 0 : catch (const reportable_exception& e)
4039 : : {
4040 [ - - ]: 0 : e.report(cerr);
4041 : 0 : }
4042 : 120 : last_rescan = time(NULL); // NB: now was before scanning
4043 : : // finished a traversal loop
4044 [ + - + - : 240 : inc_metric("thread_work_total", "role","traverse");
+ - - + -
+ - - -
- ]
4045 [ + - + - : 240 : set_metric("thread_busy", "role","traverse", 0);
+ - - + -
+ - - -
- ]
4046 : : }
4047 : : }
4048 : :
4049 : 66 : return 0;
4050 : : }
4051 : :
4052 : :
4053 : :
4054 : : ////////////////////////////////////////////////////////////////////////
4055 : :
4056 : : static void
4057 : 72 : database_stats_report()
4058 : : {
4059 : 72 : sqlite_ps ps_query (db, "database-overview",
4060 [ + - + - : 144 : "select label,quantity from " BUILDIDS "_stats");
+ - - - ]
4061 : :
4062 [ + - + - ]: 144 : obatched(clog) << "database record counts:" << endl;
4063 : 1656 : while (1)
4064 : : {
4065 [ + - ]: 864 : if (interrupted) break;
4066 [ + - ]: 864 : if (sigusr1 != forced_rescan_count) // stop early if scan triggered
4067 : : break;
4068 : :
4069 [ + - ]: 864 : int rc = ps_query.step();
4070 [ + + ]: 864 : if (rc == SQLITE_DONE) break;
4071 [ - + ]: 792 : if (rc != SQLITE_ROW)
4072 [ # # # # ]: 0 : throw sqlite_exception(rc, "step");
4073 : :
4074 [ + - ]: 792 : obatched(clog)
4075 [ + - - + : 792 : << ((const char*) sqlite3_column_text(ps_query, 0) ?: (const char*) "NULL")
+ - ]
4076 : : << " "
4077 [ + - + - : 1584 : << (sqlite3_column_text(ps_query, 1) ?: (const unsigned char*) "NULL")
- + + - ]
4078 : 792 : << endl;
4079 : :
4080 [ + - + - : 1584 : set_metric("groom", "statistic",
- + + - +
- + - + -
- + + + -
- - - ]
4081 [ + - ]: 792 : ((const char*) sqlite3_column_text(ps_query, 0) ?: (const char*) "NULL"),
4082 : : (sqlite3_column_double(ps_query, 1)));
4083 : 792 : }
4084 : 72 : }
4085 : :
4086 : :
4087 : : // Do a round of database grooming that might take many minutes to run.
4088 : 72 : void groom()
4089 : : {
4090 [ + - ]: 144 : obatched(clog) << "grooming database" << endl;
4091 : :
4092 : 72 : struct timespec ts_start, ts_end;
4093 : 72 : clock_gettime (CLOCK_MONOTONIC, &ts_start);
4094 : :
4095 : : // scan for files that have disappeared
4096 : 72 : sqlite_ps files (db, "check old files",
4097 : : "select distinct s.mtime, s.file, f.name from "
4098 : : BUILDIDS "_file_mtime_scanned s, " BUILDIDS "_files_v f "
4099 [ + - + - : 144 : "where f.id = s.file");
+ - - - ]
4100 : : // NB: Because _ftime_mtime_scanned can contain both F and
4101 : : // R records for the same file, this query would return duplicates if the
4102 : : // DISTINCT qualifier were not there.
4103 [ + - ]: 72 : files.reset();
4104 : :
4105 : : // DECISION TIME - we enumerate stale fileids/mtimes
4106 [ + - ]: 72 : deque<pair<int64_t,int64_t> > stale_fileid_mtime;
4107 : :
4108 : 72 : time_t time_start = time(NULL);
4109 : 304 : while(1)
4110 : : {
4111 : : // PR28514: limit grooming iteration to O(rescan time), to avoid
4112 : : // slow filesystem tests over many files locking out rescans for
4113 : : // too long.
4114 [ + + - + ]: 188 : if (rescan_s > 0 && (long)time(NULL) > (long)(time_start + rescan_s))
4115 : : {
4116 [ # # # # : 0 : inc_metric("groomed_total", "decision", "aborted");
# # # # #
# # # # #
# # ]
4117 : 0 : break;
4118 : : }
4119 : :
4120 [ + - ]: 188 : if (interrupted) break;
4121 : :
4122 [ + - ]: 188 : int rc = files.step();
4123 [ + + ]: 188 : if (rc != SQLITE_ROW)
4124 : : break;
4125 : :
4126 [ + - ]: 116 : int64_t mtime = sqlite3_column_int64 (files, 0);
4127 [ + - ]: 116 : int64_t fileid = sqlite3_column_int64 (files, 1);
4128 [ + - - + ]: 116 : const char* filename = ((const char*) sqlite3_column_text (files, 2) ?: "");
4129 : 116 : struct stat s;
4130 : 116 : bool regex_file_drop = 0;
4131 : :
4132 [ + + ]: 116 : if (regex_groom)
4133 : : {
4134 [ + - ]: 16 : bool reg_include = !regexec (&file_include_regex, filename, 0, 0, 0);
4135 [ + - ]: 16 : bool reg_exclude = !regexec (&file_exclude_regex, filename, 0, 0, 0);
4136 : 16 : regex_file_drop = !reg_include || reg_exclude; // match logic of scan_source_paths
4137 : : }
4138 : :
4139 : 116 : rc = stat(filename, &s);
4140 [ + + - + ]: 116 : if ( regex_file_drop || rc < 0 || (mtime != (int64_t) s.st_mtime) )
4141 : : {
4142 [ + - ]: 24 : if (verbose > 2)
4143 [ + - + - : 48 : obatched(clog) << "groom: stale file=" << filename << " mtime=" << mtime << endl;
+ - + - +
- ]
4144 [ + - ]: 24 : stale_fileid_mtime.push_back(make_pair(fileid,mtime));
4145 [ + - + - : 48 : inc_metric("groomed_total", "decision", "stale");
+ - + - -
+ - + - -
- - ]
4146 [ + - + - : 48 : set_metric("thread_work_pending","role","groom", stale_fileid_mtime.size());
+ - + - -
+ - + - -
- - ]
4147 : : }
4148 : : else
4149 [ + - + - : 184 : inc_metric("groomed_total", "decision", "fresh");
+ - + - -
+ - + - -
- - ]
4150 : :
4151 [ + - ]: 116 : if (sigusr1 != forced_rescan_count) // stop early if scan triggered
4152 : : break;
4153 : 116 : }
4154 [ + - ]: 72 : files.reset();
4155 : :
4156 : : // ACTION TIME
4157 : :
4158 : : // Now that we know which file/mtime tuples are stale, actually do
4159 : : // the deletion from the database. Doing this during the SELECT
4160 : : // iteration above results in undefined behaviour in sqlite, as per
4161 : : // https://www.sqlite.org/isolation.html
4162 : :
4163 : : // We could shuffle stale_fileid_mtime[] here. It'd let aborted
4164 : : // sequences of nuke operations resume at random locations, instead
4165 : : // of just starting over. But it doesn't matter much either way,
4166 : : // as long as we make progress.
4167 : :
4168 [ + - + - : 144 : sqlite_ps files_del_f_de (db, "nuke f_de", "delete from " BUILDIDS "_f_de where file = ? and mtime = ?");
+ - + - -
- ]
4169 [ + - + - : 144 : sqlite_ps files_del_r_de (db, "nuke r_de", "delete from " BUILDIDS "_r_de where file = ? and mtime = ?");
+ - + - -
- ]
4170 [ + - ]: 72 : sqlite_ps files_del_scan (db, "nuke f_m_s", "delete from " BUILDIDS "_file_mtime_scanned "
4171 [ + - + - : 144 : "where file = ? and mtime = ?");
+ - + - -
- ]
4172 : :
4173 [ + + ]: 96 : while (! stale_fileid_mtime.empty())
4174 : : {
4175 : 24 : auto stale = stale_fileid_mtime.front();
4176 : 24 : stale_fileid_mtime.pop_front();
4177 [ + - + - : 48 : set_metric("thread_work_pending","role","groom", stale_fileid_mtime.size());
+ - + - -
+ - + - -
- - ]
4178 : :
4179 : : // PR28514: limit grooming iteration to O(rescan time), to avoid
4180 : : // slow nuke_* queries over many files locking out rescans for too
4181 : : // long. We iterate over the files in random() sequence to avoid
4182 : : // partial checks going over the same set.
4183 [ - + - - ]: 24 : if (rescan_s > 0 && (long)time(NULL) > (long)(time_start + rescan_s))
4184 : : {
4185 [ # # # # : 0 : inc_metric("groomed_total", "action", "aborted");
# # # # #
# # # # #
# # ]
4186 : 0 : break;
4187 : : }
4188 : :
4189 [ + - ]: 24 : if (interrupted) break;
4190 : :
4191 : 24 : int64_t fileid = stale.first;
4192 : 24 : int64_t mtime = stale.second;
4193 [ + - + - : 24 : files_del_f_de.reset().bind(1,fileid).bind(2,mtime).step_ok_done();
+ - + - ]
4194 [ + - + - : 24 : files_del_r_de.reset().bind(1,fileid).bind(2,mtime).step_ok_done();
+ - + - ]
4195 [ + - + - : 24 : files_del_scan.reset().bind(1,fileid).bind(2,mtime).step_ok_done();
+ - + - ]
4196 [ + - + - : 48 : inc_metric("groomed_total", "action", "cleaned");
+ - + - -
+ - + - -
- - ]
4197 : :
4198 [ + - ]: 24 : if (sigusr1 != forced_rescan_count) // stop early if scan triggered
4199 : : break;
4200 : : }
4201 : 72 : stale_fileid_mtime.clear(); // no need for this any longer
4202 [ + - + - : 144 : set_metric("thread_work_pending","role","groom", stale_fileid_mtime.size());
+ - + - -
+ - + - -
- - ]
4203 : :
4204 : : // delete buildids with no references in _r_de or _f_de tables;
4205 : : // cascades to _r_sref & _f_s records
4206 [ + - ]: 72 : sqlite_ps buildids_del (db, "nuke orphan buildids",
4207 : : "delete from " BUILDIDS "_buildids "
4208 : : "where not exists (select 1 from " BUILDIDS "_f_de d where " BUILDIDS "_buildids.id = d.buildid) "
4209 [ + - + - : 144 : "and not exists (select 1 from " BUILDIDS "_r_de d where " BUILDIDS "_buildids.id = d.buildid)");
+ - + - -
- ]
4210 [ + - + - ]: 72 : buildids_del.reset().step_ok_done();
4211 : :
4212 [ - + ]: 72 : if (interrupted) return;
4213 : :
4214 : : // NB: "vacuum" is too heavy for even daily runs: it rewrites the entire db, so is done as maxigroom -G
4215 [ + - + - : 144 : sqlite_ps g1 (db, "incremental vacuum", "pragma incremental_vacuum");
+ - + - -
- ]
4216 [ + - + - ]: 72 : g1.reset().step_ok_done();
4217 [ + - + - : 144 : sqlite_ps g2 (db, "optimize", "pragma optimize");
+ - - + -
- ]
4218 [ + - + - ]: 72 : g2.reset().step_ok_done();
4219 [ + - + - : 144 : sqlite_ps g3 (db, "wal checkpoint", "pragma wal_checkpoint=truncate");
+ - + - -
- ]
4220 [ + - + - ]: 72 : g3.reset().step_ok_done();
4221 : :
4222 [ + - ]: 72 : database_stats_report();
4223 : :
4224 [ + - + - ]: 72 : (void) statfs_free_enough_p(db_path, "database"); // report sqlite filesystem size
4225 : :
4226 [ + - ]: 72 : sqlite3_db_release_memory(db); // shrink the process if possible
4227 [ + - ]: 72 : sqlite3_db_release_memory(dbq); // ... for both connections
4228 [ + - ]: 72 : debuginfod_pool_groom(); // and release any debuginfod_client objects we've been holding onto
4229 : :
4230 : : #if 0 /* PR31265: don't jettison cache unnecessarily */
4231 : :
4232 : : fdcache.limit(0); // release the fdcache contents
4233 : : fdcache.limit(fdcache_mbs); // restore status quo parameters
4234 : : #endif
4235 : :
4236 : 72 : clock_gettime (CLOCK_MONOTONIC, &ts_end);
4237 : 72 : double deltas = (ts_end.tv_sec - ts_start.tv_sec) + (ts_end.tv_nsec - ts_start.tv_nsec)/1.e9;
4238 : :
4239 [ + - + - : 144 : obatched(clog) << "groomed database in " << deltas << "s" << endl;
+ - + - ]
4240 : 72 : }
4241 : :
4242 : :
4243 : : static void*
4244 : 72 : thread_main_groom (void* /*arg*/)
4245 : : {
4246 [ + - + - : 144 : set_metric("thread_tid", "role", "groom", tid());
+ - - + -
+ - - -
- ]
4247 [ + - + - : 144 : add_metric("thread_count", "role", "groom", 1);
+ - - + -
+ - - -
- ]
4248 : :
4249 : 72 : time_t last_groom = 0;
4250 : :
4251 : 534 : while (1)
4252 : : {
4253 : 303 : sleep (1);
4254 : 303 : scanq.wait_idle(); // PR25394: block scanners during grooming!
4255 [ + + ]: 303 : if (interrupted) break;
4256 : :
4257 : 231 : time_t now = time(NULL);
4258 : 231 : bool groom_now = false;
4259 [ + + ]: 231 : if (last_groom == 0) // at least one initial groom is documented even for -g0
4260 : 66 : groom_now = true;
4261 [ + + + + ]: 231 : if (groom_s > 0 && (long)now > (long)(last_groom + groom_s))
4262 : 231 : groom_now = true;
4263 [ + + ]: 231 : if (sigusr2 != forced_groom_count)
4264 : : {
4265 : 6 : forced_groom_count = sigusr2;
4266 : 6 : groom_now = true;
4267 : : }
4268 [ + + ]: 231 : if (groom_now)
4269 : : {
4270 [ + - + - : 144 : set_metric("thread_busy", "role", "groom", 1);
+ - - + -
+ - - -
- ]
4271 : 72 : try
4272 : : {
4273 [ + - ]: 72 : groom ();
4274 : : }
4275 [ - - ]: 0 : catch (const sqlite_exception& e)
4276 : : {
4277 [ - - - - : 0 : obatched(cerr) << e.message << endl;
- - ]
4278 : 0 : }
4279 : 72 : last_groom = time(NULL); // NB: now was before grooming
4280 : : // finished a grooming loop
4281 [ + - + - : 144 : inc_metric("thread_work_total", "role", "groom");
+ - - + -
+ - - -
- ]
4282 [ + - + - : 144 : set_metric("thread_busy", "role", "groom", 0);
+ - - + -
+ - - -
- ]
4283 : : }
4284 : :
4285 : 231 : scanq.done_idle();
4286 : 231 : }
4287 : :
4288 : 72 : return 0;
4289 : : }
4290 : :
4291 : :
4292 : : ////////////////////////////////////////////////////////////////////////
4293 : :
4294 : :
4295 : : static void
4296 : 74 : signal_handler (int /* sig */)
4297 : : {
4298 : 74 : interrupted ++;
4299 : :
4300 [ + + ]: 74 : if (db)
4301 : 72 : sqlite3_interrupt (db);
4302 [ + - ]: 74 : if (dbq)
4303 : 74 : sqlite3_interrupt (dbq);
4304 : :
4305 : : // NB: don't do anything else in here
4306 : 74 : }
4307 : :
4308 : : static void
4309 : 60 : sigusr1_handler (int /* sig */)
4310 : : {
4311 : 60 : sigusr1 ++;
4312 : : // NB: don't do anything else in here
4313 : 60 : }
4314 : :
4315 : : static void
4316 : 6 : sigusr2_handler (int /* sig */)
4317 : : {
4318 : 6 : sigusr2 ++;
4319 : : // NB: don't do anything else in here
4320 : 6 : }
4321 : :
4322 : :
4323 : : static void // error logging callback from libmicrohttpd internals
4324 : 0 : error_cb (void *arg, const char *fmt, va_list ap)
4325 : : {
4326 : 0 : (void) arg;
4327 [ # # # # : 0 : inc_metric("error_count","libmicrohttpd",fmt);
# # # # #
# # # #
# ]
4328 : 0 : char errmsg[512];
4329 : 0 : (void) vsnprintf (errmsg, sizeof(errmsg), fmt, ap); // ok if slightly truncated
4330 [ # # ]: 0 : obatched(cerr) << "libmicrohttpd error: " << errmsg; // MHD_DLOG calls already include \n
4331 : 0 : }
4332 : :
4333 : :
4334 : : // A user-defined sqlite function, to score the sharedness of the
4335 : : // prefix of two strings. This is used to compare candidate debuginfo
4336 : : // / source-rpm names, so that the closest match
4337 : : // (directory-topology-wise closest) is found. This is important in
4338 : : // case the same sref (source file name) is in many -debuginfo or
4339 : : // -debugsource RPMs, such as when multiple versions/releases of the
4340 : : // same package are in the database.
4341 : :
4342 : 805 : static void sqlite3_sharedprefix_fn (sqlite3_context* c, int argc, sqlite3_value** argv)
4343 : : {
4344 [ - + ]: 805 : if (argc != 2)
4345 : 0 : sqlite3_result_error(c, "expect 2 string arguments", -1);
4346 [ + - + + ]: 1610 : else if ((sqlite3_value_type(argv[0]) != SQLITE_TEXT) ||
4347 : 805 : (sqlite3_value_type(argv[1]) != SQLITE_TEXT))
4348 : 515 : sqlite3_result_null(c);
4349 : : else
4350 : : {
4351 : 290 : const unsigned char* a = sqlite3_value_text (argv[0]);
4352 : 290 : const unsigned char* b = sqlite3_value_text (argv[1]);
4353 : 290 : int i = 0;
4354 [ + + + - : 35878 : while (*a != '\0' && *b != '\0' && *a++ == *b++)
+ + + + ]
4355 : 35048 : i++;
4356 : 290 : sqlite3_result_int (c, i);
4357 : : }
4358 : 805 : }
4359 : :
4360 : :
4361 : : static unsigned
4362 : 144 : default_concurrency() // guaranteed >= 1
4363 : : {
4364 : : // Prior to PR29975 & PR29976, we'd just use this:
4365 : 144 : unsigned sth = std::thread::hardware_concurrency();
4366 : : // ... but on many-CPU boxes, admins or distros may throttle
4367 : : // resources in such a way that debuginfod would mysteriously fail.
4368 : : // So we reduce the defaults:
4369 : :
4370 : 144 : unsigned aff = 0;
4371 : : #ifdef HAVE_SCHED_GETAFFINITY
4372 : 144 : {
4373 : 144 : int ret;
4374 : 144 : cpu_set_t mask;
4375 : 144 : CPU_ZERO(&mask);
4376 : 144 : ret = sched_getaffinity(0, sizeof(mask), &mask);
4377 [ + - ]: 144 : if (ret == 0)
4378 : 144 : aff = CPU_COUNT(&mask);
4379 : : }
4380 : : #endif
4381 : :
4382 : 144 : unsigned fn = 0;
4383 : : #ifdef HAVE_GETRLIMIT
4384 : 144 : {
4385 : 144 : struct rlimit rlim;
4386 : 144 : int rc = getrlimit(RLIMIT_NOFILE, &rlim);
4387 [ + - ]: 144 : if (rc == 0)
4388 [ + - ]: 288 : fn = max((rlim_t)1, (rlim.rlim_cur - 100) / 4);
4389 : : // at least 2 fds are used by each listener thread etc.
4390 : : // plus a bunch to account for shared libraries and such
4391 : : }
4392 : : #endif
4393 : :
4394 [ - + - + : 144 : unsigned d = min(max(sth, 1U),
- + ]
4395 [ - + ]: 144 : min(max(aff, 1U),
4396 [ - + ]: 144 : max(fn, 1U)));
4397 : 144 : return d;
4398 : : }
4399 : :
4400 : :
4401 : : // 30879: Something to help out in case of an uncaught exception.
4402 : 0 : void my_terminate_handler()
4403 : : {
4404 : : #if defined(__GLIBC__)
4405 : 0 : void *array[40];
4406 : 0 : int size = backtrace (array, 40);
4407 : 0 : backtrace_symbols_fd (array, size, STDERR_FILENO);
4408 : : #endif
4409 : : #if defined(__GLIBCXX__) || defined(__GLIBCPP__)
4410 : 0 : __gnu_cxx::__verbose_terminate_handler();
4411 : : #endif
4412 : 0 : abort();
4413 : : }
4414 : :
4415 : :
4416 : : int
4417 : 74 : main (int argc, char *argv[])
4418 : : {
4419 : 74 : (void) setlocale (LC_ALL, "");
4420 : 74 : (void) bindtextdomain (PACKAGE_TARNAME, LOCALEDIR);
4421 : 74 : (void) textdomain (PACKAGE_TARNAME);
4422 : :
4423 : 74 : std::set_terminate(& my_terminate_handler);
4424 : :
4425 : : /* Tell the library which version we are expecting. */
4426 : 74 : elf_version (EV_CURRENT);
4427 : :
4428 [ + - - + ]: 148 : tmpdir = string(getenv("TMPDIR") ?: "/tmp");
4429 : :
4430 : : /* Set computed default values. */
4431 [ - + + - : 74 : db_path = string(getenv("HOME") ?: "/") + string("/.debuginfod.sqlite"); /* XDG? */
+ - - + -
+ + - -
- ]
4432 : 74 : int rc = regcomp (& file_include_regex, ".*", REG_EXTENDED|REG_NOSUB); // match everything
4433 [ - + ]: 74 : if (rc != 0)
4434 : 0 : error (EXIT_FAILURE, 0, "regcomp failure: %d", rc);
4435 : 74 : rc = regcomp (& file_exclude_regex, "^$", REG_EXTENDED|REG_NOSUB); // match nothing
4436 [ - + ]: 74 : if (rc != 0)
4437 : 0 : error (EXIT_FAILURE, 0, "regcomp failure: %d", rc);
4438 : :
4439 : : // default parameters for fdcache are computed from system stats
4440 : 74 : struct statfs sfs;
4441 : 74 : rc = statfs(tmpdir.c_str(), &sfs);
4442 [ - + ]: 74 : if (rc < 0)
4443 : 0 : fdcache_mbs = 1024; // 1 gigabyte
4444 : : else
4445 : 74 : fdcache_mbs = sfs.f_bavail * sfs.f_bsize / 1024 / 1024 / 4; // 25% of free space
4446 : 74 : fdcache_mintmp = 25; // emergency flush at 25% remaining (75% full)
4447 : 74 : fdcache_prefetch = 64; // guesstimate storage is this much less costly than re-decompression
4448 : :
4449 : : /* Parse and process arguments. */
4450 : 74 : int remaining;
4451 : 74 : (void) argp_parse (&argp, argc, argv, ARGP_IN_ORDER, &remaining, NULL);
4452 [ - + ]: 74 : if (remaining != argc)
4453 : 0 : error (EXIT_FAILURE, 0,
4454 : 0 : "unexpected argument: %s", argv[remaining]);
4455 : :
4456 [ + + + + : 74 : if (scan_archives.size()==0 && !scan_files && source_paths.size()>0)
- + ]
4457 [ # # ]: 0 : obatched(clog) << "warning: without -F -R -U -Z, ignoring PATHs" << endl;
4458 : :
4459 : 74 : fdcache.limit(fdcache_mbs);
4460 : :
4461 : 74 : (void) signal (SIGPIPE, SIG_IGN); // microhttpd can generate it incidentally, ignore
4462 : 74 : (void) signal (SIGINT, signal_handler); // ^C
4463 : 74 : (void) signal (SIGHUP, signal_handler); // EOF
4464 : 74 : (void) signal (SIGTERM, signal_handler); // systemd
4465 : 74 : (void) signal (SIGUSR1, sigusr1_handler); // end-user
4466 : 74 : (void) signal (SIGUSR2, sigusr2_handler); // end-user
4467 : :
4468 : : /* Get database ready. */
4469 [ + + ]: 74 : if (! passive_p)
4470 : : {
4471 : 72 : rc = sqlite3_open_v2 (db_path.c_str(), &db, (SQLITE_OPEN_READWRITE
4472 : : |SQLITE_OPEN_URI
4473 : : |SQLITE_OPEN_PRIVATECACHE
4474 : : |SQLITE_OPEN_CREATE
4475 : : |SQLITE_OPEN_FULLMUTEX), /* thread-safe */
4476 : : NULL);
4477 [ - + ]: 72 : if (rc == SQLITE_CORRUPT)
4478 : : {
4479 : 0 : (void) unlink (db_path.c_str());
4480 : 0 : error (EXIT_FAILURE, 0,
4481 : : "cannot open %s, deleted database: %s", db_path.c_str(), sqlite3_errmsg(db));
4482 : : }
4483 [ - + ]: 72 : else if (rc)
4484 : : {
4485 : 0 : error (EXIT_FAILURE, 0,
4486 : : "cannot open %s, consider deleting database: %s", db_path.c_str(), sqlite3_errmsg(db));
4487 : : }
4488 : : }
4489 : :
4490 : : // open the readonly query variant
4491 : : // NB: PRIVATECACHE allows web queries to operate in parallel with
4492 : : // much other grooming/scanning operation.
4493 : 74 : rc = sqlite3_open_v2 (db_path.c_str(), &dbq, (SQLITE_OPEN_READONLY
4494 : : |SQLITE_OPEN_URI
4495 : : |SQLITE_OPEN_PRIVATECACHE
4496 : : |SQLITE_OPEN_FULLMUTEX), /* thread-safe */
4497 : : NULL);
4498 [ - + ]: 74 : if (rc)
4499 : : {
4500 : 0 : error (EXIT_FAILURE, 0,
4501 : : "cannot open %s, consider deleting database: %s", db_path.c_str(), sqlite3_errmsg(dbq));
4502 : : }
4503 : :
4504 : :
4505 [ + - ]: 148 : obatched(clog) << "opened database " << db_path
4506 [ + + + - : 76 : << (db?" rw":"") << (dbq?" ro":"") << endl;
- + + - +
- ]
4507 [ + - + - ]: 148 : obatched(clog) << "sqlite version " << sqlite3_version << endl;
4508 [ + + + - : 220 : obatched(clog) << "service mode " << (passive_p ? "passive":"active") << endl;
+ - ]
4509 : :
4510 : : // add special string-prefix-similarity function used in rpm sref/sdef resolution
4511 : 74 : rc = sqlite3_create_function(dbq, "sharedprefix", 2, SQLITE_UTF8, NULL,
4512 : : & sqlite3_sharedprefix_fn, NULL, NULL);
4513 [ - + ]: 74 : if (rc != SQLITE_OK)
4514 : 0 : error (EXIT_FAILURE, 0,
4515 : : "cannot create sharedprefix function: %s", sqlite3_errmsg(dbq));
4516 : :
4517 [ + + ]: 74 : if (! passive_p)
4518 : : {
4519 [ + + ]: 72 : if (verbose > 3)
4520 [ + - + - ]: 92 : obatched(clog) << "ddl: " << DEBUGINFOD_SQLITE_DDL << endl;
4521 : 72 : rc = sqlite3_exec (db, DEBUGINFOD_SQLITE_DDL, NULL, NULL, NULL);
4522 [ - + ]: 72 : if (rc != SQLITE_OK)
4523 : : {
4524 : 0 : error (EXIT_FAILURE, 0,
4525 : : "cannot run database schema ddl: %s", sqlite3_errmsg(db));
4526 : : }
4527 : : }
4528 : :
4529 [ + - + - : 148 : obatched(clog) << "libmicrohttpd version " << MHD_get_version() << endl;
+ - ]
4530 : :
4531 : : /* If '-C' wasn't given or was given with no arg, pick a reasonable default
4532 : : for the number of worker threads. */
4533 [ + + ]: 74 : if (connection_pool == 0)
4534 : 70 : connection_pool = default_concurrency();
4535 : :
4536 : : /* Note that MHD_USE_EPOLL and MHD_USE_THREAD_PER_CONNECTION don't
4537 : : work together. */
4538 : 74 : unsigned int use_epoll = 0;
4539 : : #if MHD_VERSION >= 0x00095100
4540 : 74 : use_epoll = MHD_USE_EPOLL;
4541 : : #endif
4542 : :
4543 : 74 : unsigned int mhd_flags = (
4544 : : #if MHD_VERSION >= 0x00095300
4545 : : MHD_USE_INTERNAL_POLLING_THREAD
4546 : : #else
4547 : : MHD_USE_SELECT_INTERNALLY
4548 : : #endif
4549 : : | MHD_USE_DUAL_STACK
4550 : : | use_epoll
4551 : : #if MHD_VERSION >= 0x00095200
4552 : : | MHD_USE_ITC
4553 : : #endif
4554 : : | MHD_USE_DEBUG); /* report errors to stderr */
4555 : :
4556 : : // Start httpd server threads. Use a single dual-homed pool.
4557 : 74 : MHD_Daemon *d46 = MHD_start_daemon (mhd_flags, http_port,
4558 : : NULL, NULL, /* default accept policy */
4559 : : handler_cb, NULL, /* handler callback */
4560 : : MHD_OPTION_EXTERNAL_LOGGER,
4561 : : error_cb, NULL,
4562 : : MHD_OPTION_THREAD_POOL_SIZE,
4563 : : (int)connection_pool,
4564 : : MHD_OPTION_END);
4565 : :
4566 : 74 : MHD_Daemon *d4 = NULL;
4567 [ - + ]: 74 : if (d46 == NULL)
4568 : : {
4569 : : // Cannot use dual_stack, use ipv4 only
4570 : 0 : mhd_flags &= ~(MHD_USE_DUAL_STACK);
4571 [ # # ]: 0 : d4 = MHD_start_daemon (mhd_flags, http_port,
4572 : : NULL, NULL, /* default accept policy */
4573 : : handler_cb, NULL, /* handler callback */
4574 : : MHD_OPTION_EXTERNAL_LOGGER,
4575 : : error_cb, NULL,
4576 : : (connection_pool
4577 : : ? MHD_OPTION_THREAD_POOL_SIZE
4578 : : : MHD_OPTION_END),
4579 : : (connection_pool
4580 : : ? (int)connection_pool
4581 : : : MHD_OPTION_END),
4582 : : MHD_OPTION_END);
4583 [ # # ]: 0 : if (d4 == NULL)
4584 : : {
4585 : 0 : sqlite3 *database = db;
4586 : 0 : sqlite3 *databaseq = dbq;
4587 : 0 : db = dbq = 0; // for signal_handler not to freak
4588 : 0 : sqlite3_close (databaseq);
4589 : 0 : sqlite3_close (database);
4590 : 0 : error (EXIT_FAILURE, 0, "cannot start http server at port %d",
4591 : : http_port);
4592 : : }
4593 : :
4594 : : }
4595 : 74 : obatched(clog) << "started http server on"
4596 : : << (d4 != NULL ? " IPv4 " : " IPv4 IPv6 ")
4597 [ + - + - : 148 : << "port=" << http_port << endl;
+ - + - +
- ]
4598 : :
4599 : : // add maxigroom sql if -G given
4600 [ - + ]: 74 : if (maxigroom)
4601 : : {
4602 [ # # ]: 0 : obatched(clog) << "maxigrooming database, please wait." << endl;
4603 [ # # ]: 0 : extra_ddl.push_back("create index if not exists " BUILDIDS "_r_sref_arc on " BUILDIDS "_r_sref(artifactsrc);");
4604 [ # # ]: 0 : extra_ddl.push_back("delete from " BUILDIDS "_r_sdef where not exists (select 1 from " BUILDIDS "_r_sref b where " BUILDIDS "_r_sdef.content = b.artifactsrc);");
4605 [ # # ]: 0 : extra_ddl.push_back("drop index if exists " BUILDIDS "_r_sref_arc;");
4606 : :
4607 : : // NB: we don't maxigroom the _files interning table. It'd require a temp index on all the
4608 : : // tables that have file foreign-keys, which is a lot.
4609 : :
4610 : : // NB: with =delete, may take up 3x disk space total during vacuum process
4611 : : // vs. =off (only 2x but may corrupt database if program dies mid-vacuum)
4612 : : // vs. =wal (>3x observed, but safe)
4613 [ # # ]: 0 : extra_ddl.push_back("pragma journal_mode=delete;");
4614 [ # # ]: 0 : extra_ddl.push_back("vacuum;");
4615 [ # # ]: 0 : extra_ddl.push_back("pragma journal_mode=wal;");
4616 : : }
4617 : :
4618 : : // run extra -D sql if given
4619 [ + + ]: 74 : if (! passive_p)
4620 [ - + ]: 72 : for (auto&& i: extra_ddl)
4621 : : {
4622 [ # # ]: 0 : if (verbose > 1)
4623 [ # # # # ]: 0 : obatched(clog) << "extra ddl:\n" << i << endl;
4624 : 0 : rc = sqlite3_exec (db, i.c_str(), NULL, NULL, NULL);
4625 [ # # # # ]: 0 : if (rc != SQLITE_OK && rc != SQLITE_DONE && rc != SQLITE_ROW)
4626 : 0 : error (0, 0,
4627 : : "warning: cannot run database extra ddl %s: %s", i.c_str(), sqlite3_errmsg(db));
4628 : :
4629 [ # # ]: 0 : if (maxigroom)
4630 [ # # ]: 0 : obatched(clog) << "maxigroomed database" << endl;
4631 : : }
4632 : :
4633 [ + + ]: 74 : if (! passive_p)
4634 [ + - + - ]: 144 : obatched(clog) << "search concurrency " << concurrency << endl;
4635 : 74 : obatched(clog) << "webapi connection pool " << connection_pool
4636 [ + - - + : 74 : << (connection_pool ? "" : " (unlimited)") << endl;
+ - + - ]
4637 [ + + ]: 74 : if (! passive_p) {
4638 [ + - + - ]: 144 : obatched(clog) << "rescan time " << rescan_s << endl;
4639 [ + - + - ]: 144 : obatched(clog) << "scan checkpoint " << scan_checkpoint << endl;
4640 : : }
4641 [ + - + - ]: 148 : obatched(clog) << "fdcache mbs " << fdcache_mbs << endl;
4642 [ + - + - ]: 148 : obatched(clog) << "fdcache prefetch " << fdcache_prefetch << endl;
4643 [ + - + - ]: 148 : obatched(clog) << "fdcache tmpdir " << tmpdir << endl;
4644 [ + - + - ]: 148 : obatched(clog) << "fdcache tmpdir min% " << fdcache_mintmp << endl;
4645 [ + + ]: 74 : if (! passive_p)
4646 [ + - + - ]: 144 : obatched(clog) << "groom time " << groom_s << endl;
4647 [ + - + - ]: 148 : obatched(clog) << "forwarded ttl limit " << forwarded_ttl_limit << endl;
4648 : :
4649 [ + + ]: 74 : if (scan_archives.size()>0)
4650 : : {
4651 : 50 : obatched ob(clog);
4652 [ + - ]: 50 : auto& o = ob << "accepting archive types ";
4653 [ + + ]: 152 : for (auto&& arch : scan_archives)
4654 [ + - + - : 102 : o << arch.first << "(" << arch.second << ") ";
+ - + - ]
4655 [ + - ]: 50 : o << endl;
4656 : 50 : }
4657 : 74 : const char* du = getenv(DEBUGINFOD_URLS_ENV_VAR);
4658 [ + + + + ]: 74 : if (du && du[0] != '\0') // set to non-empty string?
4659 [ + - + - ]: 28 : obatched(clog) << "upstream debuginfod servers: " << du << endl;
4660 : :
4661 [ + + ]: 74 : vector<pthread_t> all_threads;
4662 : :
4663 [ + + ]: 74 : if (! passive_p)
4664 : : {
4665 : 72 : pthread_t pt;
4666 : 72 : rc = pthread_create (& pt, NULL, thread_main_groom, NULL);
4667 [ - + ]: 72 : if (rc)
4668 : 0 : error (EXIT_FAILURE, rc, "cannot spawn thread to groom database\n");
4669 : : else
4670 : : {
4671 : : #ifdef HAVE_PTHREAD_SETNAME_NP
4672 : 72 : (void) pthread_setname_np (pt, "groom");
4673 : : #endif
4674 [ + - ]: 72 : all_threads.push_back(pt);
4675 : : }
4676 : :
4677 [ + + + + ]: 72 : if (scan_files || scan_archives.size() > 0)
4678 : : {
4679 [ + - ]: 66 : if (scan_checkpoint > 0)
4680 [ + - ]: 66 : scan_barrier = new sqlite_checkpoint_pb(concurrency, (unsigned) scan_checkpoint);
4681 : :
4682 : 66 : rc = pthread_create (& pt, NULL, thread_main_fts_source_paths, NULL);
4683 [ - + ]: 66 : if (rc)
4684 : 0 : error (EXIT_FAILURE, rc, "cannot spawn thread to traverse source paths\n");
4685 : : #ifdef HAVE_PTHREAD_SETNAME_NP
4686 : 66 : (void) pthread_setname_np (pt, "traverse");
4687 : : #endif
4688 [ + - ]: 66 : all_threads.push_back(pt);
4689 : :
4690 [ + + ]: 330 : for (unsigned i=0; i<concurrency; i++)
4691 : : {
4692 : 264 : rc = pthread_create (& pt, NULL, thread_main_scanner, NULL);
4693 [ - + ]: 264 : if (rc)
4694 : 0 : error (EXIT_FAILURE, rc, "cannot spawn thread to scan source files / archives\n");
4695 : : #ifdef HAVE_PTHREAD_SETNAME_NP
4696 : 264 : (void) pthread_setname_np (pt, "scan");
4697 : : #endif
4698 [ + - ]: 264 : all_threads.push_back(pt);
4699 : : }
4700 : : }
4701 : : }
4702 : :
4703 : : /* Trivial main loop! */
4704 [ + - + - ]: 74 : set_metric("ready", 1);
4705 [ + + ]: 214 : while (! interrupted)
4706 [ + - ]: 140 : pause ();
4707 [ + - ]: 74 : scanq.nuke(); // wake up any remaining scanq-related threads, let them die
4708 [ + + + - ]: 74 : if (scan_barrier) scan_barrier->nuke(); // ... in case they're stuck in a barrier
4709 [ + - + - ]: 74 : set_metric("ready", 0);
4710 : :
4711 [ + - ]: 74 : if (verbose)
4712 [ + - + - : 148 : obatched(clog) << "stopping" << endl;
- - ]
4713 : :
4714 : : /* Join all our threads. */
4715 [ + + ]: 476 : for (auto&& it : all_threads)
4716 [ + - ]: 402 : pthread_join (it, NULL);
4717 : :
4718 : : /* Stop all the web service threads. */
4719 [ + - + - ]: 74 : if (d46) MHD_stop_daemon (d46);
4720 [ - + - - ]: 74 : if (d4) MHD_stop_daemon (d4);
4721 : :
4722 [ + + ]: 74 : if (! passive_p)
4723 : : {
4724 : : /* With all threads known dead, we can clean up the global resources. */
4725 [ + - ]: 72 : rc = sqlite3_exec (db, DEBUGINFOD_SQLITE_CLEANUP_DDL, NULL, NULL, NULL);
4726 [ - + ]: 72 : if (rc != SQLITE_OK)
4727 : : {
4728 [ # # # # ]: 0 : error (0, 0,
4729 : : "warning: cannot run database cleanup ddl: %s", sqlite3_errmsg(db));
4730 : : }
4731 : : }
4732 : :
4733 [ + - ]: 74 : debuginfod_pool_groom ();
4734 [ + + ]: 74 : delete scan_barrier;
4735 : :
4736 : : // NB: no problem with unconditional free here - an earlier failed regcomp would exit program
4737 [ + - ]: 74 : (void) regfree (& file_include_regex);
4738 [ + - ]: 74 : (void) regfree (& file_exclude_regex);
4739 : :
4740 : 74 : sqlite3 *database = db;
4741 : 74 : sqlite3 *databaseq = dbq;
4742 : 74 : db = dbq = 0; // for signal_handler not to freak
4743 [ + - ]: 74 : (void) sqlite3_close (databaseq);
4744 [ + + ]: 74 : if (! passive_p)
4745 [ + - ]: 72 : (void) sqlite3_close (database);
4746 : :
4747 [ + + ]: 74 : return 0;
4748 : 74 : }
|