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