chiark / gitweb /
Disobedience memory/widget debugging stuff has thoroughly rotted, so
[disorder] / server / rescan.c
1 /*
2  * This file is part of DisOrder 
3  * Copyright (C) 2005-2008 Richard Kettlewell
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
18  * USA
19  */
20
21 #include "disorder-server.h"
22
23 static time_t last_report;
24 static DB_TXN *global_tid;
25
26 static const struct option options[] = {
27   { "help", no_argument, 0, 'h' },
28   { "version", no_argument, 0, 'V' },
29   { "config", required_argument, 0, 'c' },
30   { "debug", no_argument, 0, 'd' },
31   { "no-debug", no_argument, 0, 'D' },
32   { "syslog", no_argument, 0, 's' },
33   { "no-syslog", no_argument, 0, 'S' },
34   { "check", no_argument, 0, 'K' },
35   { "no-check", no_argument, 0, 'C' },
36   { 0, 0, 0, 0 }
37 };
38
39 /* display usage message and terminate */
40 static void help(void) {
41   xprintf("Usage:\n"
42           "  disorder-rescan [OPTIONS] [PATH...]\n"
43           "Options:\n"
44           "  --help, -h              Display usage message\n"
45           "  --version, -V           Display version number\n"
46           "  --config PATH, -c PATH  Set configuration file\n"
47           "  --debug, -d             Turn on debugging\n"
48           "  --[no-]syslog           Enable/disable logging to syslog\n"
49           "  --[no-]check            Enable/disable track length check\n"
50           "\n"
51           "Rescanner for DisOrder.  Not intended to be run\n"
52           "directly.\n");
53   xfclose(stdout);
54   exit(0);
55 }
56
57 static volatile sig_atomic_t signalled;
58
59 static void signal_handler(int sig) {
60   if(sig == 0) _exit(-1);               /* "Cannot happen" */
61   signalled = sig;
62 }
63
64 static int aborted(void) {
65   return signalled || getppid() == 1;
66 }
67
68 /* Exit if our parent has gone away or we have been told to stop. */
69 static void checkabort(void) {
70   if(getppid() == 1) {
71     info("parent has terminated");
72     trackdb_abort_transaction(global_tid);
73     exit(0);
74   }
75   if(signalled) {
76     info("received signal %d", signalled);
77     trackdb_abort_transaction(global_tid);
78     exit(0);
79   }
80 }
81
82 /* rescan a collection */
83 static void rescan_collection(const struct collection *c) {
84   pid_t pid, r;
85   int p[2], n, w;
86   FILE *fp = 0;
87   char *path, *track;
88   long ntracks = 0, nnew = 0;
89   
90   checkabort();
91   info("rescanning %s with %s", c->root, c->module);
92   /* plugin runs in a subprocess */
93   xpipe(p);
94   if(!(pid = xfork())) {
95     exitfn = _exit;
96     xclose(p[0]);
97     xdup2(p[1], 1);
98     xclose(p[1]);
99     scan(c->module, c->root);
100     if(fflush(stdout) < 0)
101       fatal(errno, "error writing to scanner pipe");
102     _exit(0);
103   }
104   xclose(p[1]);
105   if(!(fp = fdopen(p[0], "r")))
106     fatal(errno, "error calling fdopen");
107   /* read tracks from the plugin */
108   while(!inputline("rescanner", fp, &path, 0)) {
109     checkabort();
110     /* actually we can cope relatively well within the server, but they'll go
111      * wrong in track listings */
112     if(strchr(path, '\n')) {
113       error(0, "cannot cope with tracks with newlines in the name");
114       continue;
115     }
116     if(!(track = any2utf8(c->encoding, path))) {
117       error(0, "cannot convert track path to UTF-8: %s", path);
118       continue;
119     }
120     if(config->dbversion > 1) {
121       /* We use NFC track names */
122       if(!(track = utf8_compose_canon(track, strlen(track), 0))) {
123         error(0, "cannot convert track path to NFC: %s", path);
124         continue;
125       }
126     }
127     D(("track %s", track));
128     /* only tracks with a known player are admitted */
129     for(n = 0; (n < config->player.n
130                 && fnmatch(config->player.s[n].s[0], track, 0) != 0); ++n)
131       ;
132     if(n < config->player.n) {
133       nnew += !!trackdb_notice(track, path);
134       ++ntracks;
135       if(ntracks % 100 == 0 && time(0) > last_report + 10) {
136         info("rescanning %s, %ld tracks so far", c->root, ntracks);
137         time(&last_report);
138       }
139     }
140   }
141   /* tidy up */
142   if(ferror(fp)) {
143     error(errno, "error reading from scanner pipe");
144     goto done;
145   }
146   xfclose(fp);
147   fp = 0;
148   while((r = waitpid(pid, &w, 0)) == -1 && errno == EINTR)
149     ;
150   if(r < 0) fatal(errno, "error calling waitpid");
151   pid = 0;
152   if(w) {
153     error(0, "scanner subprocess: %s", wstat(w));
154     goto done;
155   }
156   info("rescanned %s, %ld tracks, %ld new", c->root, ntracks, nnew);
157 done:
158   if(fp)
159     xfclose(fp);
160   if(pid)
161     while((r = waitpid(pid, &w, 0)) == -1 && errno == EINTR)
162       ;
163 }
164
165 struct recheck_state {
166   const struct collection *c;
167   long nobsolete, nnocollection, nlength;
168   struct recheck_track *tracks;
169 };
170
171 struct recheck_track {
172   struct recheck_track *next;
173   const char *track;
174 };
175
176 /* called for each non-alias track */
177 static int recheck_list_callback(const char *track,
178                                  struct kvp attribute((unused)) *data,
179                                  struct kvp attribute((unused)) *prefs,
180                                  void *u,
181                                  DB_TXN attribute((unused)) *tid) {
182   struct recheck_state *cs = u;
183   struct recheck_track *t = xmalloc(sizeof *t);
184
185   t->next = cs->tracks;
186   t->track = track;
187   cs->tracks = t;
188   return 0;
189 }
190
191 static int recheck_track_tid(struct recheck_state *cs,
192                              const struct recheck_track *t,
193                              DB_TXN *tid) {
194   const struct collection *c = cs->c;
195   const char *path;
196   char buffer[20];
197   int err, n;
198   long length;
199   struct kvp *data;
200
201   if((err = trackdb_getdata(trackdb_tracksdb, t->track, &data, tid)))
202     return err;
203   path = kvp_get(data, "_path");
204   D(("rechecking %s", t->track));
205   /* if we're not checking a specific collection, find the right collection */
206   if(!c) {
207     if(!(c = find_track_collection(t->track))) {
208       D(("obsoleting %s", t->track));
209       if((err = trackdb_obsolete(t->track, tid)))
210         return err;
211       ++cs->nnocollection;
212       return 0;
213     }
214   }
215   /* see if the track has evaporated */
216   if(check(c->module, c->root, path) == 0) {
217     D(("obsoleting %s", t->track));
218     if((err = trackdb_obsolete(t->track, tid)))
219       return err;
220     ++cs->nobsolete;
221     return 0;
222   }
223   /* make sure we know the length */
224   if(!kvp_get(data, "_length")) {
225     D(("recalculating length of %s", t->track));
226     for(n = 0; n < config->tracklength.n; ++n)
227       if(fnmatch(config->tracklength.s[n].s[0], t->track, 0) == 0)
228         break;
229     if(n >= config->tracklength.n)
230       error(0, "no tracklength plugin found for %s", t->track);
231     else {
232       length = tracklength(config->tracklength.s[n].s[1], t->track, path);
233       if(length > 0) {
234         byte_snprintf(buffer, sizeof buffer, "%ld", length);
235         kvp_set(&data, "_length", buffer);
236         if((err = trackdb_putdata(trackdb_tracksdb, t->track, data, tid, 0)))
237           return err;
238         ++cs->nlength;
239       }
240     }
241   }
242   return 0;
243 }
244
245 static int recheck_track(struct recheck_state *cs,
246                          const struct recheck_track *t) {
247   int e;
248
249   WITH_TRANSACTION(recheck_track_tid(cs, t, tid));
250   return e;
251 }
252
253 /* recheck a collection */
254 static void recheck_collection(const struct collection *c) {
255   struct recheck_state cs;
256   const struct recheck_track *t;
257   long nrc;
258
259   if(c)
260     info("rechecking %s", c->root);
261   else
262     info("rechecking all tracks");
263   /* Doing the checking inside a transaction locks up the server for much too
264    * long (because it spends lots of time thinking about each track).  So we
265    * pull the full track list into memory and work from that.
266    *
267    * 100,000 tracks at, say, 80 bytes per track name, gives 8MB, which is quite
268    * reasonable.
269    */
270   for(;;) {
271     checkabort();
272     info("getting track list");
273     global_tid = trackdb_begin_transaction();
274     memset(&cs, 0, sizeof cs);
275     cs.c = c;
276     if(trackdb_scan(c ? c->root : 0, recheck_list_callback, &cs, global_tid))
277       goto fail;
278     break;
279   fail:
280     /* Maybe we need to shut down */
281     checkabort();
282     /* Abort the transaction and try again in a bit. */
283     trackdb_abort_transaction(global_tid);
284     global_tid = 0;
285     /* Let anything else that is going on get out of the way. */
286     sleep(10);
287     checkabort();
288     if(c)
289       info("resuming recheck of %s", c->root);
290     else
291       info("resuming global recheck");
292   }
293   trackdb_commit_transaction(global_tid);
294   global_tid = 0;
295   nrc = 0;
296   for(t = cs.tracks; t; t = t->next) {
297     if(aborted())
298       return;
299     recheck_track(&cs, t);
300     ++nrc;
301     if(nrc % 100 == 0 && time(0) > last_report + 10) {
302       if(c)
303         info("rechecking %s, %ld tracks so far", c->root, nrc);
304       else
305         info("rechecking all tracks, %ld tracks so far", nrc);
306       time(&last_report);
307     }
308   }
309   if(c)
310     info("rechecked %s, %ld obsoleted, %ld lengths calculated",
311          c->root, cs.nobsolete, cs.nlength);
312   else
313     info("rechecked all tracks, %ld no collection, %ld obsoleted, %ld lengths calculated",
314          cs.nnocollection, cs.nobsolete, cs.nlength);
315 }
316
317 /* rescan/recheck a collection by name */
318 static void do_directory(const char *s,
319                          void (*fn)(const struct collection *c)) {
320   int n;
321   
322   for(n = 0; (n < config->collection.n
323               && strcmp(config->collection.s[n].root, s)); ++n)
324     ;
325   if(n < config->collection.n)
326     fn(&config->collection.s[n]);
327   else
328     error(0, "no collection has root '%s'", s);
329 }
330
331 /* rescan/recheck all collections */
332 static void do_all(void (*fn)(const struct collection *c)) {
333   int n;
334
335   for(n = 0; n < config->collection.n; ++n)
336     fn(&config->collection.s[n]);
337   /* TODO: we need to tidy up tracks from collections now removed.  We could do
338    * this two ways: either remember collections we think there are and spot
339    * their disappearance, or iterate over all tracks and gc any that don't fit
340    * into some collection.
341    *
342    * Having a way to rename collections would be rather convenient too but
343    * that's another kettle of monkeys.
344    */
345 }
346
347 /** @brief Expire noticed.db */
348 static void expire_noticed(void) {
349   time_t now;
350
351   time(&now);
352   trackdb_expire_noticed(now - config->noticed_history * 86400);
353 }
354
355 int main(int argc, char **argv) {
356   int n, logsyslog = !isatty(2);
357   struct sigaction sa;
358   int do_check = 1;
359   
360   set_progname(argv);
361   mem_init();
362   if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
363   while((n = getopt_long(argc, argv, "hVc:dDSsKC", options, 0)) >= 0) {
364     switch(n) {
365     case 'h': help();
366     case 'V': version("disorder-rescan");
367     case 'c': configfile = optarg; break;
368     case 'd': debugging = 1; break;
369     case 'D': debugging = 0; break;
370     case 'S': logsyslog = 0; break;
371     case 's': logsyslog = 1; break;
372     case 'K': do_check = 1; break;
373     case 'C': do_check = 0; break;
374     default: fatal(0, "invalid option");
375     }
376   }
377   if(logsyslog) {
378     openlog(progname, LOG_PID, LOG_DAEMON);
379     log_default = &log_syslog;
380   }
381   if(config_read(0)) fatal(0, "cannot read configuration");
382   xnice(config->nice_rescan);
383   sa.sa_handler = signal_handler;
384   sa.sa_flags = SA_RESTART;
385   sigemptyset(&sa.sa_mask);
386   xsigaction(SIGTERM, &sa, 0);
387   xsigaction(SIGINT, &sa, 0);
388   info("started");
389   trackdb_init(TRACKDB_NO_RECOVER);
390   trackdb_open(TRACKDB_NO_UPGRADE);
391   if(optind == argc) {
392     /* Rescan all collections */
393     do_all(rescan_collection);
394     /* Check that every track still exists */
395     if(do_check)
396       recheck_collection(0);
397     /* Expire noticed.db */
398     expire_noticed();
399   }
400   else {
401     /* Rescan specified collections */
402     for(n = optind; n < argc; ++n)
403       do_directory(argv[n], rescan_collection);
404     /* Check specified collections for tracks that have gone */
405     if(do_check)
406       for(n = optind; n < argc; ++n)
407         do_directory(argv[n], recheck_collection);
408   }
409   trackdb_close();
410   trackdb_deinit();
411   info("completed");
412   return 0;
413 }
414
415 /*
416 Local Variables:
417 c-basic-offset:2
418 comment-column:40
419 fill-column:79
420 indent-tabs-mode:nil
421 End:
422 */