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