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