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