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