2 * This file is part of DisOrder
3 * Copyright (C) 2005, 2006, 2007 Richard Kettlewell
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.
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.
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
27 #include <sys/socket.h>
34 #include <sys/resource.h>
43 #include "configuration.h"
49 #include "trackname.h"
50 #include "trackdb-int.h"
56 #define RESCAN "disorder-rescan"
57 #define DEADLOCK "disorder-deadlock"
59 static const char *getpart(const char *track,
64 static int trackdb_alltags_tid(DB_TXN *tid, char ***taglistp);
65 static int trackdb_get_global_tid(const char *name,
69 const struct cache_type cache_files_type = { 86400 };
70 unsigned long cache_files_hits, cache_files_misses;
72 /* setup and teardown ********************************************************/
74 static const char *home; /* home had better not change */
75 DB_ENV *trackdb_env; /* db environment */
76 DB *trackdb_tracksdb; /* the db itself */
77 DB *trackdb_prefsdb; /* preferences */
78 DB *trackdb_searchdb; /* the search database */
79 DB *trackdb_tagsdb; /* the tags database */
80 DB *trackdb_globaldb; /* global preferences */
81 static pid_t db_deadlock_pid = -1; /* deadlock manager PID */
82 static pid_t rescan_pid = -1; /* rescanner PID */
83 static int initialized, opened; /* state */
85 /* tracks matched by required_tags */
86 static char **reqtracks;
87 static size_t nreqtracks;
89 /* comparison function for keys */
90 static int compare(DB attribute((unused)) *db_,
91 const DBT *a, const DBT *b) {
92 return compare_path_raw(a->data, a->size, b->data, b->size);
95 /* open environment */
96 void trackdb_init(int recover) {
98 static int recover_type[] = { 0, DB_RECOVER, DB_RECOVER_FATAL };
101 assert(initialized == 0);
104 if(strcmp(home, config->home))
105 fatal(0, "cannot change db home without server restart");
109 /* create environment */
110 if((err = db_env_create(&trackdb_env, 0))) fatal(0, "db_env_create: %s",
112 if((err = trackdb_env->set_alloc(trackdb_env,
113 xmalloc_noptr, xrealloc_noptr, xfree)))
114 fatal(0, "trackdb_env->set_alloc: %s", db_strerror(err));
115 if((err = trackdb_env->set_lk_max_locks(trackdb_env, 10000)))
116 fatal(0, "trackdb_env->set_lk_max_locks: %s", db_strerror(err));
117 if((err = trackdb_env->set_lk_max_objects(trackdb_env, 10000)))
118 fatal(0, "trackdb_env->set_lk_max_objects: %s", db_strerror(err));
119 if((err = trackdb_env->open(trackdb_env, config->home,
125 |recover_type[recover],
127 fatal(0, "trackdb_env->open: %s", db_strerror(err));
128 trackdb_env->set_errpfx(trackdb_env, "DB");
129 trackdb_env->set_errfile(trackdb_env, stderr);
130 trackdb_env->set_verbose(trackdb_env, DB_VERB_DEADLOCK, 1);
131 trackdb_env->set_verbose(trackdb_env, DB_VERB_RECOVERY, 1);
132 trackdb_env->set_verbose(trackdb_env, DB_VERB_REPLICATION, 1);
133 D(("initialized database environment"));
136 /* called when deadlock manager terminates */
137 static int reap_db_deadlock(ev_source attribute((unused)) *ev,
138 pid_t attribute((unused)) pid,
140 const struct rusage attribute((unused)) *rusage,
141 void attribute((unused)) *u) {
142 db_deadlock_pid = -1;
144 fatal(0, "deadlock manager unexpectedly terminated: %s",
147 D(("deadlock manager terminated: %s", wstat(status)));
151 static pid_t subprogram(ev_source *ev, const char *prog) {
155 /* If we're in the background then trap subprocess stdout/stderr */
157 lfd = logfd(ev, prog);
160 if(!(pid = xfork())) {
162 ev_signal_atfork(ev);
163 signal(SIGPIPE, SIG_DFL);
168 /* If we were negatively niced, undo it. We don't bother checking for
169 * error, it's not that important. */
170 setpriority(PRIO_PROCESS, 0, 0);
171 execlp(prog, prog, "--config", configfile,
172 debugging ? "--debug" : "--no-debug",
174 fatal(errno, "error invoking %s", prog);
176 if(lfd != -1) xclose(lfd);
180 /* start deadlock manager */
181 void trackdb_master(ev_source *ev) {
182 assert(db_deadlock_pid == -1);
183 db_deadlock_pid = subprogram(ev, DEADLOCK);
184 ev_child(ev, db_deadlock_pid, 0, reap_db_deadlock, 0);
185 D(("started deadlock manager"));
188 /* close environment */
189 void trackdb_deinit(void) {
193 assert(initialized == 1);
196 /* close the environment */
197 if((err = trackdb_env->close(trackdb_env, 0)))
198 fatal(0, "trackdb_env->close: %s", db_strerror(err));
200 if(rescan_pid != -1 && kill(rescan_pid, SIGTERM) < 0)
201 fatal(errno, "error killing rescanner");
203 /* terminate the deadlock manager */
204 if(db_deadlock_pid != -1 && kill(db_deadlock_pid, SIGTERM) < 0)
205 fatal(errno, "error killing deadlock manager");
206 db_deadlock_pid = -1;
208 D(("deinitialized database environment"));
211 /* open a specific database */
212 static DB *open_db(const char *path,
220 D(("open %s", path));
221 path = config_get_file(path);
222 if((err = db_create(&db, trackdb_env, 0)))
223 fatal(0, "db_create %s: %s", path, db_strerror(err));
225 if((err = db->set_flags(db, dbflags)))
226 fatal(0, "db->set_flags %s: %s", path, db_strerror(err));
227 if(dbtype == DB_BTREE)
228 if((err = db->set_bt_compare(db, compare)))
229 fatal(0, "db->set_bt_compare %s: %s", path, db_strerror(err));
230 if((err = db->open(db, 0, path, 0, dbtype,
231 openflags | DB_AUTO_COMMIT, mode)))
232 fatal(0, "db->open %s: %s", path, db_strerror(err));
236 /* open track databases */
237 void trackdb_open(void) {
241 /* open the databases */
242 trackdb_tracksdb = open_db("tracks.db",
243 DB_RECNUM, DB_BTREE, DB_CREATE, 0666);
244 trackdb_searchdb = open_db("search.db",
245 DB_DUP|DB_DUPSORT, DB_HASH, DB_CREATE, 0666);
246 trackdb_tagsdb = open_db("tags.db",
247 DB_DUP|DB_DUPSORT, DB_HASH, DB_CREATE, 0666);
248 trackdb_prefsdb = open_db("prefs.db", 0, DB_HASH, DB_CREATE, 0666);
249 trackdb_globaldb = open_db("global.db", 0, DB_HASH, DB_CREATE, 0666);
250 D(("opened databases"));
253 /* close track databases */
254 void trackdb_close(void) {
260 if((err = trackdb_tracksdb->close(trackdb_tracksdb, 0)))
261 fatal(0, "error closing tracks.db: %s", db_strerror(err));
262 if((err = trackdb_searchdb->close(trackdb_searchdb, 0)))
263 fatal(0, "error closing search.db: %s", db_strerror(err));
264 if((err = trackdb_tagsdb->close(trackdb_tagsdb, 0)))
265 fatal(0, "error closing tags.db: %s", db_strerror(err));
266 if((err = trackdb_prefsdb->close(trackdb_prefsdb, 0)))
267 fatal(0, "error closing prefs.db: %s", db_strerror(err));
268 if((err = trackdb_globaldb->close(trackdb_globaldb, 0)))
269 fatal(0, "error closing global.db: %s", db_strerror(err));
270 trackdb_tracksdb = trackdb_searchdb = trackdb_prefsdb = 0;
271 trackdb_tagsdb = trackdb_globaldb = 0;
272 D(("closed databases"));
275 /* generic db routines *******************************************************/
277 /* fetch and decode a database entry. Returns 0, DB_NOTFOUND or
278 * DB_LOCK_DEADLOCK. */
279 int trackdb_getdata(DB *db,
286 switch(err = db->get(db, tid, make_key(&key, track),
287 prepare_data(&data), 0)) {
289 *kp = kvp_urldecode(data.data, data.size);
294 case DB_LOCK_DEADLOCK:
295 error(0, "error querying database: %s", db_strerror(err));
298 fatal(0, "error querying database: %s", db_strerror(err));
302 /* encode and store a database entry. Returns 0, DB_KEYEXIST or
303 * DB_LOCK_DEADLOCK. */
304 int trackdb_putdata(DB *db,
312 switch(err = db->put(db, tid, make_key(&key, track),
313 encode_data(&data, k), flags)) {
317 case DB_LOCK_DEADLOCK:
318 error(0, "error updating database: %s", db_strerror(err));
321 fatal(0, "error updating database: %s", db_strerror(err));
325 /* delete a database entry */
326 int trackdb_delkey(DB *db,
332 switch(err = db->del(db, tid, make_key(&key, track), 0)) {
336 case DB_LOCK_DEADLOCK:
337 error(0, "error updating database: %s", db_strerror(err));
340 fatal(0, "error updating database: %s", db_strerror(err));
344 /* open a database cursor */
345 DBC *trackdb_opencursor(DB *db, DB_TXN *tid) {
349 switch(err = db->cursor(db, tid, &c, 0)) {
351 default: fatal(0, "error creating cursor: %s", db_strerror(err));
356 /* close a database cursor; returns 0 or DB_LOCK_DEADLOCK */
357 int trackdb_closecursor(DBC *c) {
361 switch(err = c->c_close(c)) {
364 case DB_LOCK_DEADLOCK:
365 error(0, "error closing cursor: %s", db_strerror(err));
368 fatal(0, "error closing cursor: %s", db_strerror(err));
372 /* delete a (key,data) pair. Returns 0, DB_NOTFOUND or DB_LOCK_DEADLOCK. */
373 int trackdb_delkeydata(DB *db,
381 c = trackdb_opencursor(db, tid);
382 switch(err = c->c_get(c, make_key(&key, word),
383 make_key(&data, track), DB_GET_BOTH)) {
385 switch(err = c->c_del(c, 0)) {
391 case DB_LOCK_DEADLOCK:
392 error(0, "error updating database: %s", db_strerror(err));
395 fatal(0, "c->c_del: %s", db_strerror(err));
400 case DB_LOCK_DEADLOCK:
401 error(0, "error updating database: %s", db_strerror(err));
404 fatal(0, "c->c_get: %s", db_strerror(err));
406 if(trackdb_closecursor(c)) err = DB_LOCK_DEADLOCK;
410 /* start a transaction */
411 DB_TXN *trackdb_begin_transaction(void) {
415 if((err = trackdb_env->txn_begin(trackdb_env, 0, &tid, 0)))
416 fatal(0, "trackdb_env->txn_begin: %s", db_strerror(err));
420 /* abort transaction */
421 void trackdb_abort_transaction(DB_TXN *tid) {
425 if((err = tid->abort(tid)))
426 fatal(0, "tid->abort: %s", db_strerror(err));
429 /* commit transaction */
430 void trackdb_commit_transaction(DB_TXN *tid) {
433 if((err = tid->commit(tid, 0)))
434 fatal(0, "tid->commit: %s", db_strerror(err));
437 /* search/tags shared code ***************************************************/
439 /* comparison function used by dedupe() */
440 static int wordcmp(const void *a, const void *b) {
441 return strcmp(*(const char **)a, *(const char **)b);
444 /* sort and de-dupe VEC */
445 static char **dedupe(char **vec, int nvec) {
448 qsort(vec, nvec, sizeof (char *), wordcmp);
452 for(n = 1; n < nvec; ++n)
453 if(strcmp(vec[n], vec[m - 1]))
460 /* update a key/track database. Returns 0 or DB_DEADLOCK. */
461 static int register_word(DB *db, const char *what,
462 const char *track, const char *word,
467 switch(err = db->put(db, tid, make_key(&key, word),
468 make_key(&data, track), DB_NODUPDATA)) {
472 case DB_LOCK_DEADLOCK:
473 error(0, "error updating %s.db: %s", what, db_strerror(err));
476 fatal(0, "error updating %s.db: %s", what, db_strerror(err));
480 /* search primitives *********************************************************/
482 /* return true iff NAME is a trackname_display_ pref */
483 static int is_display_pref(const char *name) {
484 static const char prefix[] = "trackname_display_";
485 return !strncmp(name, prefix, (sizeof prefix) - 1);
488 /* compute the words of a track name */
489 static char **track_to_words(const char *track,
490 const struct kvp *p) {
494 const char *rootless = track_rootless(track);
497 rootless = track; /* bodge */
499 if((w = words(casefold(strip_extension(rootless)), &nw)))
500 vector_append_many(&v, w, nw);
502 for(; p; p = p->next)
503 if(is_display_pref(p->name))
504 if((w = words(casefold(p->value), &nw)))
505 vector_append_many(&v, w, nw);
506 vector_terminate(&v);
507 return dedupe(v.vec, v.nvec);
510 /* return nonzero iff WORD is a stopword */
511 static int stopword(const char *word) {
514 for(n = 0; n < config->stopword.n
515 && strcmp(word, config->stopword.s[n]); ++n)
517 return n < config->stopword.n;
520 /* record that WORD appears in TRACK. Returns 0 or DB_LOCK_DEADLOCK. */
521 static int register_search_word(const char *track, const char *word,
523 if(stopword(word)) return 0;
524 return register_word(trackdb_searchdb, "search", track, word, tid);
527 /* Tags **********************************************************************/
529 /* Return nonzero if C is a valid tag character */
530 static int tagchar(int c) {
539 /* Parse and de-dupe a tag list. If S=0 then assumes "". */
540 static char **parsetags(const char *s) {
546 /* skip initial separators */
547 while(*s && (!tagchar(*s) || *s == ' '))
550 /* find the extent of the tag */
552 while(*s && tagchar(*s))
554 /* strip trailing spaces */
555 while(s > t && s[-1] == ' ')
557 vector_append(&v, xstrndup(t, s - t));
558 /* skip intermediate and trailing separators */
559 while(*s && (!tagchar(*s) || *s == ' '))
563 vector_terminate(&v);
564 return dedupe(v.vec, v.nvec);
567 /* Record that TRACK has TAG. Returns 0 or DB_LOCK_DEADLOCK. */
568 static int register_tag(const char *track, const char *tag, DB_TXN *tid) {
569 return register_word(trackdb_tagsdb, "tags", track, tag, tid);
572 /* aliases *******************************************************************/
574 /* compute the alias and store at aliasp. Returns 0 or DB_LOCK_DEADLOCK. If
575 * there is no alias sets *aliasp to 0. */
576 static int compute_alias(char **aliasp,
581 const char *s = config->alias, *t, *expansion, *part;
582 int c, used_db = 0, slash_prefix, err;
584 const char *const root = find_track_root(track);
587 /* Bodge for tracks with no root */
592 dynstr_append_string(&d, root);
593 while((c = (unsigned char)*s++)) {
595 dynstr_append(&d, c);
598 if((slash_prefix = (*s == '/')))
601 assert(t != 0); /* validated at startup */
602 part = xstrndup(s, t - s);
603 expansion = getpart(track, "display", part, p, &used_db);
605 if(slash_prefix) dynstr_append(&d, '/');
606 dynstr_append_string(&d, expansion);
608 s = t + 1; /* skip {part} */
610 /* only admit to the alias if we used the db... */
615 dynstr_terminate(&d);
616 /* ...and the answer differs from the original... */
617 if(!strcmp(track, d.vec)) {
621 /* ...and there isn't already a different track with that name (including as
623 switch(err = trackdb_getdata(trackdb_tracksdb, d.vec, &at, tid)) {
625 if((s = kvp_get(at, "_alias_for"))
626 && !strcmp(s, track)) {
638 /* get track and prefs data (if tp/pp not null pointers). Returns 0 on
639 * success, DB_NOTFOUND if the track does not exist or DB_LOCK_DEADLOCK.
640 * Always sets the return values, even if only to null pointers. */
641 static int gettrackdata(const char *track,
644 const char **actualp,
646 #define GTD_NOALIAS 0x0001
649 const char *actual = track;
650 struct kvp *t = 0, *p = 0;
652 if((err = trackdb_getdata(trackdb_tracksdb, track, &t, tid))) goto done;
653 if((actual = kvp_get(t, "_alias_for"))) {
654 if(flags & GTD_NOALIAS) {
655 error(0, "alias passed to gettrackdata where real path required");
658 if((err = trackdb_getdata(trackdb_tracksdb, actual, &t, tid))) goto done;
663 if((err = trackdb_getdata(trackdb_prefsdb, actual, &p, tid)) == DB_LOCK_DEADLOCK)
668 if(actualp) *actualp = actual;
674 /* trackdb_notice() **********************************************************/
677 int trackdb_notice(const char *track,
683 tid = trackdb_begin_transaction();
684 err = trackdb_notice_tid(track, path, tid);
685 if((err == DB_LOCK_DEADLOCK)) goto fail;
688 trackdb_abort_transaction(tid);
690 trackdb_commit_transaction(tid);
694 int trackdb_notice_tid(const char *track,
698 struct kvp *t, *a, *p;
702 /* notice whether the tracks.db entry changes */
704 /* get any existing tracks entry */
705 if((err = gettrackdata(track, &t, &p, 0, 0, tid)) == DB_LOCK_DEADLOCK)
708 /* this is a real track */
709 t_changed += kvp_set(&t, "_alias_for", 0);
710 t_changed += kvp_set(&t, "_path", path);
711 /* if we have an alias record it in the database */
712 if((err = compute_alias(&alias, track, p, tid))) return err;
714 /* won't overwrite someone else's alias as compute_alias() checks */
715 D(("%s: alias %s", track, alias));
717 kvp_set(&a, "_alias_for", track);
718 if((err = trackdb_putdata(trackdb_tracksdb, alias, a, tid, 0))) return err;
720 /* update search.db */
721 w = track_to_words(track, p);
722 for(n = 0; w[n]; ++n)
723 if((err = register_search_word(track, w[n], tid)))
726 w = parsetags(kvp_get(p, "tags"));
727 for(n = 0; w[n]; ++n)
728 if((err = register_tag(track, w[n], tid)))
731 /* only store the tracks.db entry if it has changed */
732 if(t_changed && (err = trackdb_putdata(trackdb_tracksdb, track, t, tid, 0)))
737 /* trackdb_obsolete() ********************************************************/
739 /* obsolete a track */
740 int trackdb_obsolete(const char *track, DB_TXN *tid) {
745 if((err = gettrackdata(track, 0, &p, 0,
746 GTD_NOALIAS, tid)) == DB_LOCK_DEADLOCK)
748 else if(err == DB_NOTFOUND) return 0;
749 /* compute the alias, if any, and delete it */
750 if(compute_alias(&alias, track, p, tid)) return err;
752 /* if the alias points to some other track then compute_alias won't
754 if(trackdb_delkey(trackdb_tracksdb, alias, tid))
757 /* update search.db */
758 w = track_to_words(track, p);
759 for(n = 0; w[n]; ++n)
760 if(trackdb_delkeydata(trackdb_searchdb,
761 w[n], track, tid) == DB_LOCK_DEADLOCK)
764 w = parsetags(kvp_get(p, "tags"));
765 for(n = 0; w[n]; ++n)
766 if(trackdb_delkeydata(trackdb_tagsdb,
767 w[n], track, tid) == DB_LOCK_DEADLOCK)
770 /* update tracks.db */
771 if(trackdb_delkey(trackdb_tracksdb, track, tid) == DB_LOCK_DEADLOCK)
773 /* We don't delete the prefs, so they survive temporary outages of the
774 * (possibly virtual) track filesystem */
778 /* trackdb_stats() ***********************************************************/
780 #define H(name) { #name, offsetof(DB_HASH_STAT, name) }
781 #define B(name) { #name, offsetof(DB_BTREE_STAT, name) }
783 static const struct statinfo {
786 } statinfo_hash[] = {
802 }, statinfo_btree[] = {
823 /* look up stats for DB */
824 static int get_stats(struct vector *v,
826 const struct statinfo *si,
835 switch(err = database->stat(database, tid, &sp, 0)) {
838 case DB_LOCK_DEADLOCK:
839 error(0, "error querying database: %s", db_strerror(err));
842 fatal(0, "error querying database: %s", db_strerror(err));
844 for(n = 0; n < nsi; ++n) {
845 byte_xasprintf(&str, "%s=%"PRIuMAX, si[n].name,
846 (uintmax_t)*(u_int32_t *)((char *)sp + si[n].offset));
847 vector_append(v, str);
853 struct search_entry {
858 /* find the top COUNT words in the search database */
859 static int search_league(struct vector *v, int count, DB_TXN *tid) {
860 struct search_entry *se;
863 int err, n = 0, nse = 0, i;
868 cursor = trackdb_opencursor(trackdb_searchdb, tid);
869 se = xmalloc(count * sizeof *se);
870 while(!(err = cursor->c_get(cursor, prepare_data(&k), prepare_data(&d),
872 if(word && wl == k.size && !strncmp(word, k.data, wl))
875 #define FINALIZE() do { \
876 if(word && (nse < count || n > se[nse - 1].n)) { \
881 while(i > 0 && n > se[i - 1].n) \
883 memmove(&se[i + 1], &se[i], (nse - i) * sizeof *se); \
889 word = xstrndup(k.data, wl = k.size);
897 case DB_LOCK_DEADLOCK:
898 error(0, "error querying search database: %s", db_strerror(err));
901 fatal(0, "error querying search database: %s", db_strerror(err));
903 if(trackdb_closecursor(cursor)) err = DB_LOCK_DEADLOCK;
906 byte_xasprintf(&str, "Top %d search words:", nse);
907 vector_append(v, str);
908 for(i = 0; i < nse; ++i) {
909 byte_xasprintf(&str, "%4d: %5d %s", i + 1, se[i].n, se[i].word);
910 vector_append(v, str);
915 #define SI(what) statinfo_##what, \
916 sizeof statinfo_##what / sizeof (struct statinfo)
918 /* return a list of database stats */
919 char **trackdb_stats(int *nstatsp) {
926 tid = trackdb_begin_transaction();
928 vector_append(&v, (char *)"Tracks database stats:");
929 if(get_stats(&v, trackdb_tracksdb, SI(btree), tid)) goto fail;
930 vector_append(&v, (char *)"");
931 vector_append(&v, (char *)"Search database stats:");
932 if(get_stats(&v, trackdb_searchdb, SI(hash), tid)) goto fail;
933 vector_append(&v, (char *)"");
934 vector_append(&v, (char *)"Prefs database stats:");
935 if(get_stats(&v, trackdb_prefsdb, SI(hash), tid)) goto fail;
936 vector_append(&v, (char *)"");
937 if(search_league(&v, 10, tid)) goto fail;
938 vector_append(&v, (char *)"");
939 vector_append(&v, (char *)"Server stats:");
940 byte_xasprintf(&s, "track lookup cache hits: %lu", cache_files_hits);
941 vector_append(&v, (char *)s);
942 byte_xasprintf(&s, "track lookup cache misses: %lu", cache_files_misses);
943 vector_append(&v, (char *)s);
944 vector_terminate(&v);
947 trackdb_abort_transaction(tid);
949 trackdb_commit_transaction(tid);
950 if(nstatsp) *nstatsp = v.nvec;
954 /* set a pref (remove if value=0) */
955 int trackdb_set(const char *track,
958 struct kvp *t, *p, *a;
961 char *oldalias, *newalias, **oldtags = 0, **newtags;
964 tid = trackdb_begin_transaction();
965 if((err = gettrackdata(track, &t, &p, 0,
966 0, tid)) == DB_LOCK_DEADLOCK)
968 if(err == DB_NOTFOUND) break;
970 if(kvp_set(&t, name, value))
971 if(trackdb_putdata(trackdb_tracksdb, track, t, tid, 0))
974 /* get the old alias name */
975 if(compute_alias(&oldalias, track, p, tid)) goto fail;
976 /* get the old tags */
977 if(!strcmp(name, "tags"))
978 oldtags = parsetags(kvp_get(p, "tags"));
980 if(kvp_set(&p, name, value))
981 if(trackdb_putdata(trackdb_prefsdb, track, p, tid, 0))
983 /* compute the new alias name */
984 if((err = compute_alias(&newalias, track, p, tid))) goto fail;
985 /* check whether alias has changed */
986 if(!(oldalias == newalias
987 || (oldalias && newalias && !strcmp(oldalias, newalias)))) {
988 /* adjust alias records to fit change */
990 && trackdb_delkey(trackdb_tracksdb, oldalias, tid)) goto fail;
993 kvp_set(&a, "_alias_for", track);
994 if(trackdb_putdata(trackdb_tracksdb, newalias, a, tid, 0)) goto fail;
997 /* check whether tags have changed */
998 if(!strcmp(name, "tags")) {
999 newtags = parsetags(value);
1000 while(*oldtags || *newtags) {
1001 if(*oldtags && *newtags) {
1002 cmp = strcmp(*oldtags, *newtags);
1004 /* keeping this tag */
1008 /* old tag fits into a gap in the new list, so delete old */
1011 /* new tag fits into a gap in the old list, so insert new */
1013 } else if(*oldtags) {
1014 /* we've run out of new tags, so remaining old ones are to be
1017 if(trackdb_delkeydata(trackdb_tagsdb,
1018 *oldtags, track, tid) == DB_LOCK_DEADLOCK)
1022 /* we've run out of old tags, so remainig new ones are to be
1025 if(register_tag(track, *newtags, tid)) goto fail;
1035 trackdb_abort_transaction(tid);
1037 trackdb_commit_transaction(tid);
1038 return err == 0 ? 0 : -1;
1042 const char *trackdb_get(const char *track,
1044 return kvp_get(trackdb_get_all(track), name);
1047 /* get all prefs as a 0-terminated array */
1048 struct kvp *trackdb_get_all(const char *track) {
1049 struct kvp *t, *p, **pp;
1053 tid = trackdb_begin_transaction();
1054 if(gettrackdata(track, &t, &p, 0, 0, tid) == DB_LOCK_DEADLOCK)
1058 trackdb_abort_transaction(tid);
1060 trackdb_commit_transaction(tid);
1061 for(pp = &p; *pp; pp = &(*pp)->next)
1068 const char *trackdb_resolve(const char *track) {
1073 tid = trackdb_begin_transaction();
1074 if(gettrackdata(track, 0, 0, &actual, 0, tid) == DB_LOCK_DEADLOCK)
1078 trackdb_abort_transaction(tid);
1080 trackdb_commit_transaction(tid);
1084 int trackdb_isalias(const char *track) {
1085 const char *actual = trackdb_resolve(track);
1087 return strcmp(actual, track);
1090 /* test whether a track exists (perhaps an alias) */
1091 int trackdb_exists(const char *track) {
1096 tid = trackdb_begin_transaction();
1097 /* unusually, here we want the return value */
1098 if((err = gettrackdata(track, 0, 0, 0, 0, tid)) == DB_LOCK_DEADLOCK)
1102 trackdb_abort_transaction(tid);
1104 trackdb_commit_transaction(tid);
1108 /* return the list of tags */
1109 char **trackdb_alltags(void) {
1115 tid = trackdb_begin_transaction();
1116 err = trackdb_alltags_tid(tid, &taglist);
1118 trackdb_abort_transaction(tid);
1120 trackdb_commit_transaction(tid);
1124 static int trackdb_alltags_tid(DB_TXN *tid, char ***taglistp) {
1131 c = trackdb_opencursor(trackdb_tagsdb, tid);
1132 memset(&k, 0, sizeof k);
1133 while(!(err = c->c_get(c, &k, prepare_data(&d), DB_NEXT_NODUP)))
1134 vector_append(&v, xstrndup(k.data, k.size));
1138 case DB_LOCK_DEADLOCK:
1141 fatal(0, "c->c_get: %s", db_strerror(err));
1143 if((err = trackdb_closecursor(c))) return err;
1144 vector_terminate(&v);
1149 /* return 1 iff sorted tag lists A and B have at least one member in common */
1150 static int tag_intersection(char **a, char **b) {
1153 /* Same sort of logic as trackdb_set() above */
1155 if(!(cmp = strcmp(*a, *b))) return 1;
1156 else if(cmp < 0) ++a;
1162 /* Check whether a track is suitable for random play. Returns 0 if it is,
1163 * DB_NOTFOUND if it is not or DB_LOCK_DEADLOCK if the database gave us
1165 static int check_suitable(const char *track,
1167 char **required_tags,
1168 char **prohibited_tags) {
1172 const char *pick_at_random, *played_time;
1174 /* don't pick tracks that aren't in any surviving collection (for instance
1175 * you've edited the config but the rescan hasn't done its job yet) */
1176 if(!find_track_root(track)) {
1177 info("found track not in any collection: %s", track);
1180 /* don't pick aliases - only pick the canonical form */
1181 if(gettrackdata(track, &t, &p, 0, 0, tid) == DB_LOCK_DEADLOCK)
1182 return DB_LOCK_DEADLOCK;
1183 if(kvp_get(t, "_alias_for"))
1185 /* check that random play is not suppressed for this track */
1186 if((pick_at_random = kvp_get(p, "pick_at_random"))
1187 && !strcmp(pick_at_random, "0"))
1189 /* don't pick a track that's been played in the last 8 hours */
1190 if((played_time = kvp_get(p, "played_time"))) {
1191 last = atoll(played_time);
1193 if(now < last + 8 * 3600) /* TODO configurable */
1196 track_tags = parsetags(kvp_get(p, "tags"));
1197 /* check that no prohibited tag is present for this track */
1198 if(prohibited_tags && tag_intersection(track_tags, prohibited_tags))
1200 /* check that at least one required tags is present for this track */
1201 if(*required_tags && !tag_intersection(track_tags, required_tags))
1206 /* attempt to pick a random non-alias track */
1207 const char *trackdb_random(int tries) {
1212 const char *track, *candidate;
1215 char **required_tags, **prohibited_tags, **tp;
1220 tid = trackdb_begin_transaction();
1221 if((err = trackdb_get_global_tid("required-tags", tid, &tags)))
1223 required_tags = parsetags(tags);
1224 if((err = trackdb_get_global_tid("prohibited-tags", tid, &tags)))
1226 prohibited_tags = parsetags(tags);
1228 if(*required_tags) {
1229 /* Bung all the suitable tracks into a hash and convert to a list of keys
1230 * (to eliminate duplicates). We cache this list since it is possible
1231 * that it will be very large. */
1234 for(tp = required_tags; *tp; ++tp) {
1235 c = trackdb_opencursor(trackdb_tagsdb, tid);
1236 memset(&key, 0, sizeof key);
1238 key.size = strlen(*tp);
1240 err = c->c_get(c, &key, prepare_data(&data), DB_SET);
1242 hash_add(h, xstrndup(data.data, data.size), 0,
1243 HASH_INSERT_OR_REPLACE);
1245 err = c->c_get(c, &key, prepare_data(&data), DB_NEXT_DUP);
1251 case DB_LOCK_DEADLOCK:
1254 fatal(0, "error querying tags.db: %s", db_strerror(err));
1256 trackdb_closecursor(c);
1259 error(0, "required tag %s does not match any tracks", *tp);
1261 nreqtracks = hash_count(h);
1262 reqtracks = hash_keys(h);
1264 while(nreqtracks && !track && tries-- > 0) {
1265 r = (rand() * (double)nreqtracks / (RAND_MAX + 1.0));
1266 candidate = reqtracks[r];
1267 switch(check_suitable(candidate, tid,
1268 required_tags, prohibited_tags)) {
1274 case DB_LOCK_DEADLOCK:
1279 /* No required tags. We pick random record numbers in the database
1281 switch(err = trackdb_tracksdb->stat(trackdb_tracksdb, tid, &sp, 0)) {
1284 case DB_LOCK_DEADLOCK:
1285 error(0, "error querying tracks.db: %s", db_strerror(err));
1288 fatal(0, "error querying tracks.db: %s", db_strerror(err));
1291 error(0, "cannot pick tracks at random from an empty database");
1292 while(sp->bt_nkeys && !track && tries-- > 0) {
1293 /* record numbers count from 1 upwards */
1294 r = 1 + (rand() * (double)sp->bt_nkeys / (RAND_MAX + 1.0));
1295 memset(&key, sizeof key, 0);
1296 key.flags = DB_DBT_MALLOC;
1297 key.size = sizeof r;
1299 switch(err = trackdb_tracksdb->get(trackdb_tracksdb, tid, &key, prepare_data(&data),
1303 case DB_LOCK_DEADLOCK:
1304 error(0, "error querying tracks.db: %s", db_strerror(err));
1307 fatal(0, "error querying tracks.db: %s", db_strerror(err));
1309 candidate = xstrndup(key.data, key.size);
1310 switch(check_suitable(candidate, tid,
1311 required_tags, prohibited_tags)) {
1317 case DB_LOCK_DEADLOCK:
1324 trackdb_closecursor(c);
1326 trackdb_abort_transaction(tid);
1328 trackdb_commit_transaction(tid);
1330 error(0, "could not pick a random track");
1334 /* get a track name given the prefs. Set *used_db to 1 if we got the answer
1335 * from the prefs. */
1336 static const char *getpart(const char *track,
1337 const char *context,
1339 const struct kvp *p,
1344 byte_xasprintf(&pref, "trackname_%s_%s", context, part);
1345 if((result = kvp_get(p, pref)))
1348 result = trackname_part(track, context, part);
1349 assert(result != 0);
1353 /* get a track name part, like trackname_part(), but taking the database into
1355 const char *trackdb_getpart(const char *track,
1356 const char *context,
1364 /* construct the full pref */
1365 byte_xasprintf(&pref, "trackname_%s_%s", context, part);
1367 tid = trackdb_begin_transaction();
1368 if((err = gettrackdata(track, 0, &p, &actual, 0, tid)) == DB_LOCK_DEADLOCK)
1372 trackdb_abort_transaction(tid);
1374 trackdb_commit_transaction(tid);
1375 return getpart(actual, context, part, p, &used_db);
1378 /* get the raw path name for @track@ (might be an alias) */
1379 const char *trackdb_rawpath(const char *track) {
1385 tid = trackdb_begin_transaction();
1386 if(gettrackdata(track, &t, 0, 0, 0, tid) == DB_LOCK_DEADLOCK)
1390 trackdb_abort_transaction(tid);
1392 trackdb_commit_transaction(tid);
1393 if(!(path = kvp_get(t, "_path"))) path = track;
1397 /* trackdb_list **************************************************************/
1399 /* this is incredibly ugly, sorry, perhaps it will be rewritten to be actually
1400 * readable at some point */
1402 /* return true if the basename of TRACK[0..TL-1], as defined by DL, matches RE.
1403 * If RE is a null pointer then it matches everything. */
1404 static int track_matches(size_t dl, const char *track, size_t tl,
1412 switch(rc = pcre_exec(re, 0, track, tl, 0, 0, ovec, 3)) {
1413 case PCRE_ERROR_NOMATCH: return 0;
1416 error(0, "pcre_exec returned %d, subject '%s'", rc, track);
1423 static int do_list(struct vector *v, const char *dir,
1424 enum trackdb_listable what, const pcre *re, DB_TXN *tid) {
1430 size_t l, last_dir_len = 0;
1431 char *last_dir = 0, *track, *alias;
1435 cursor = trackdb_opencursor(trackdb_tracksdb, tid);
1438 /* find the first key >= dir */
1439 err = cursor->c_get(cursor, &k, &d, DB_SET_RANGE);
1440 /* keep going while we're dealing with <dir/anything> */
1443 && ((char *)k.data)[dl] == '/'
1444 && !memcmp(k.data, dir, dl)) {
1445 ptr = memchr((char *)k.data + dl + 1, '/', k.size - (dl + 1));
1447 /* we have <dir/component/anything>, so <dir/component> is a directory */
1448 l = ptr - (char *)k.data;
1449 if(what & trackdb_directories)
1451 && l == last_dir_len
1452 && !memcmp(last_dir, k.data, l))) {
1453 last_dir = xstrndup(k.data, last_dir_len = l);
1454 if(track_matches(dl, k.data, l, re))
1455 vector_append(v, last_dir);
1458 /* found a plain file */
1459 if((what & trackdb_files)) {
1460 track = xstrndup(k.data, k.size);
1461 if((err = trackdb_getdata(trackdb_prefsdb,
1462 track, &p, tid)) == DB_LOCK_DEADLOCK)
1464 /* if this file has an alias in the same directory then we skip it */
1465 if((err = compute_alias(&alias, track, p, tid)))
1467 if(!(alias && !strcmp(d_dirname(alias), d_dirname(track))))
1468 if(track_matches(dl, k.data, k.size, re))
1469 vector_append(v, track);
1472 err = cursor->c_get(cursor, &k, &d, DB_NEXT);
1480 case DB_LOCK_DEADLOCK:
1481 error(0, "error querying database: %s", db_strerror(err));
1484 fatal(0, "error querying database: %s", db_strerror(err));
1487 if(trackdb_closecursor(cursor)) err = DB_LOCK_DEADLOCK;
1491 /* return the directories or files below @dir@ */
1492 char **trackdb_list(const char *dir, int *np, enum trackdb_listable what,
1500 tid = trackdb_begin_transaction();
1503 if(do_list(&v, dir, what, re, tid))
1506 for(n = 0; n < config->collection.n; ++n)
1507 if(do_list(&v, config->collection.s[n].root, what, re, tid))
1512 trackdb_abort_transaction(tid);
1514 trackdb_commit_transaction(tid);
1515 vector_terminate(&v);
1521 /* If S is tag:something, return something. Else return 0. */
1522 static const char *checktag(const char *s) {
1523 if(!strncmp(s, "tag:", 4))
1529 /* return a list of tracks containing all of the words given. If you
1530 * ask for only stopwords you get no tracks. */
1531 char **trackdb_search(char **wordlist, int nwordlist, int *ntracks) {
1532 const char **w, *best = 0, *tag;
1533 char **twords, **tags;
1534 int i, j, n, err, what;
1544 *ntracks = 0; /* for early returns */
1545 /* casefold all the words */
1546 w = xmalloc(nwordlist * sizeof (char *));
1547 for(n = 0; n < nwordlist; ++n) {
1548 w[n] = casefold(wordlist[n]);
1549 if(checktag(w[n])) ++ntags; /* count up tags */
1551 /* find the longest non-stopword */
1552 for(n = 0; n < nwordlist; ++n)
1553 if(!stopword(w[n]) && !checktag(w[n]))
1554 if(!best || strlen(w[n]) > strlen(best))
1556 /* TODO: we should at least in principal be able to identify the word or tag
1557 * with the least matches in log time, and choose that as our primary search
1559 if(ntags && !best) {
1560 /* Only tags are listed. We limit to the first and narrow down with the
1562 best = checktag(w[0]);
1563 db = trackdb_tagsdb;
1566 /* We can limit to some word. */
1567 db = trackdb_searchdb;
1570 /* Only stopwords */
1576 tid = trackdb_begin_transaction();
1577 /* find all the tracks that have that word */
1582 cursor = trackdb_opencursor(db, tid);
1583 while(!(err = cursor->c_get(cursor, &k, &d, what))) {
1584 vector_append(&v, xstrndup(d.data, d.size));
1591 case DB_LOCK_DEADLOCK:
1592 error(0, "error querying %s database: %s", dbname, db_strerror(err));
1595 fatal(0, "error querying %s database: %s", dbname, db_strerror(err));
1597 if(trackdb_closecursor(cursor)) err = DB_LOCK_DEADLOCK;
1599 /* do a naive search over that (hopefuly fairly small) list of tracks */
1601 for(n = 0; n < v.nvec; ++n) {
1602 if((err = gettrackdata(v.vec[n], 0, &p, 0, 0, tid) == DB_LOCK_DEADLOCK))
1605 error(0, "track %s unexpected error: %s", v.vec[n], db_strerror(err));
1608 twords = track_to_words(v.vec[n], p);
1609 tags = parsetags(kvp_get(p, "tags"));
1610 for(i = 0; i < nwordlist; ++i) {
1611 if((tag = checktag(w[i]))) {
1612 /* Track must have this tag */
1613 for(j = 0; tags[j]; ++j)
1614 if(!strcmp(tag, tags[j])) break; /* tag found */
1615 if(!tags[j]) break; /* tag not found */
1617 /* Track must contain this word */
1618 for(j = 0; twords[j]; ++j)
1619 if(!strcmp(w[i], twords[j])) break; /* word found */
1620 if(!twords[j]) break; /* word not found */
1623 if(i >= nwordlist) /* all words found */
1624 vector_append(&u, v.vec[n]);
1628 trackdb_closecursor(cursor);
1630 trackdb_abort_transaction(tid);
1631 info("retrying search");
1633 trackdb_commit_transaction(tid);
1634 vector_terminate(&u);
1640 /* trackdb_scan **************************************************************/
1642 int trackdb_scan(const char *root,
1643 int (*callback)(const char *track,
1651 const size_t root_len = root ? strlen(root) : 0;
1656 cursor = trackdb_opencursor(trackdb_tracksdb, tid);
1658 err = cursor->c_get(cursor, make_key(&k, root), prepare_data(&d),
1661 memset(&k, 0, sizeof k);
1662 err = cursor->c_get(cursor, &k, prepare_data(&d),
1667 || (k.size > root_len
1668 && !strncmp(k.data, root, root_len)
1669 && ((char *)k.data)[root_len] == '/')) {
1670 data = kvp_urldecode(d.data, d.size);
1671 if(kvp_get(data, "_path")) {
1672 track = xstrndup(k.data, k.size);
1673 /* Advance to the next track before the callback so that the callback
1674 * may safely delete the track */
1675 err = cursor->c_get(cursor, &k, &d, DB_NEXT);
1676 if((cberr = callback(track, data, u, tid))) {
1681 err = cursor->c_get(cursor, &k, &d, DB_NEXT);
1685 trackdb_closecursor(cursor);
1692 case DB_LOCK_DEADLOCK:
1693 error(0, "c->c_get: %s", db_strerror(err));
1696 fatal(0, "c->c_get: %s", db_strerror(err));
1700 /* trackdb_rescan ************************************************************/
1702 /* called when the rescanner terminates */
1703 static int reap_rescan(ev_source attribute((unused)) *ev,
1706 const struct rusage attribute((unused)) *rusage,
1707 void attribute((unused)) *u) {
1708 if(pid == rescan_pid) rescan_pid = -1;
1710 error(0, "disorderd-rescan: %s", wstat(status));
1712 D(("disorderd-rescan terminate: %s", wstat(status)));
1713 /* Our cache of file lookups is out of date now */
1714 cache_clean(&cache_files_type);
1718 void trackdb_rescan(ev_source *ev) {
1719 if(rescan_pid != -1) {
1720 error(0, "rescan already underway");
1723 rescan_pid = subprogram(ev, RESCAN);
1724 ev_child(ev, rescan_pid, 0, reap_rescan, 0);
1725 D(("started rescanner"));
1729 int trackdb_rescan_cancel(void) {
1730 if(rescan_pid == -1) return 0;
1731 if(kill(rescan_pid, SIGTERM) < 0)
1732 fatal(errno, "error killing rescanner");
1737 /* global prefs **************************************************************/
1739 void trackdb_set_global(const char *name,
1747 memset(&k, 0, sizeof k);
1748 memset(&d, 0, sizeof d);
1749 k.data = (void *)name;
1750 k.size = strlen(name);
1752 d.data = (void *)value;
1753 d.size = strlen(value);
1756 tid = trackdb_begin_transaction();
1758 err = trackdb_globaldb->put(trackdb_globaldb, tid, &k, &d, 0);
1760 err = trackdb_globaldb->del(trackdb_globaldb, tid, &k, 0);
1761 if(!err || err == DB_NOTFOUND) break;
1762 if(err != DB_LOCK_DEADLOCK)
1763 fatal(0, "error updating database: %s", db_strerror(err));
1764 trackdb_abort_transaction(tid);
1766 trackdb_commit_transaction(tid);
1767 /* log important state changes */
1768 if(!strcmp(name, "playing")) {
1769 state = !value || !strcmp(value, "yes");
1770 info("playing %s by %s",
1771 state ? "enabled" : "disabled",
1773 eventlog("state", state ? "enable_play" : "disable_play", (char *)0);
1775 if(!strcmp(name, "random-play")) {
1776 state = !value || !strcmp(value, "yes");
1777 info("random play %s by %s",
1778 state ? "enabled" : "disabled",
1780 eventlog("state", state ? "enable_random" : "disable_random", (char *)0);
1782 if(!strcmp(name, "required-tags"))
1786 const char *trackdb_get_global(const char *name) {
1792 tid = trackdb_begin_transaction();
1793 if(!(err = trackdb_get_global_tid(name, tid, &r)))
1795 trackdb_abort_transaction(tid);
1797 trackdb_commit_transaction(tid);
1801 static int trackdb_get_global_tid(const char *name,
1807 memset(&k, 0, sizeof k);
1808 k.data = (void *)name;
1809 k.size = strlen(name);
1810 switch(err = trackdb_globaldb->get(trackdb_globaldb, tid, &k,
1811 prepare_data(&d), 0)) {
1813 *rp = xstrndup(d.data, d.size);
1818 case DB_LOCK_DEADLOCK:
1821 fatal(0, "error updating database: %s", db_strerror(err));
1825 /* tidying up ****************************************************************/
1827 void trackdb_gc(void) {
1831 if((err = trackdb_env->txn_checkpoint(trackdb_env,
1832 config->checkpoint_kbyte,
1833 config->checkpoint_min,
1835 fatal(0, "trackdb_env->txn_checkpoint: %s", db_strerror(err));
1836 if((err = trackdb_env->log_archive(trackdb_env, &logfiles, DB_ARCH_REMOVE)))
1837 fatal(0, "trackdb_env->log_archive: %s", db_strerror(err));
1838 /* This makes catastrophic recovery impossible. However, the user can still
1839 * preserve the important data by using disorder-dump to snapshot their
1840 * prefs, and later to restore it. This is likely to have much small
1841 * long-term storage requirements than record the db logfiles. */
1849 indent-tabs-mode:nil