chiark / gitweb /
fa424ee42066b219d1283d0e5eef06d0eb6c7f5a
[disorder] / server / choose.c
1 /*
2  * This file is part of DisOrder 
3  * Copyright (C) 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 /** @file choose.c
21  * @brief Random track chooser
22  *
23  * Picks a track at random and writes it to standard output.  If for
24  * any reason no track can be picked - even a trivial reason like a
25  * deadlock - it just exits and expects the server to try again.
26  */
27
28 #include <config.h>
29 #include "types.h"
30
31 #include <getopt.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <db.h>
35 #include <locale.h>
36 #include <errno.h>
37 #include <sys/types.h>
38 #include <unistd.h>
39 #include <pcre.h>
40 #include <string.h>
41 #include <fcntl.h>
42 #include <syslog.h>
43
44 #include "configuration.h"
45 #include "log.h"
46 #include "defs.h"
47 #include "mem.h"
48 #include "kvp.h"
49 #include "syscalls.h"
50 #include "printf.h"
51 #include "trackdb.h"
52 #include "trackdb-int.h"
53 #include "version.h"
54
55 static DB_TXN *global_tid;
56
57 static const struct option options[] = {
58   { "help", no_argument, 0, 'h' },
59   { "version", no_argument, 0, 'V' },
60   { "config", required_argument, 0, 'c' },
61   { "debug", no_argument, 0, 'd' },
62   { "no-debug", no_argument, 0, 'D' },
63   { "syslog", no_argument, 0, 's' },
64   { "no-syslog", no_argument, 0, 'S' },
65   { 0, 0, 0, 0 }
66 };
67
68 /* display usage message and terminate */
69 static void help(void) {
70   xprintf("Usage:\n"
71           "  disorder-choose [OPTIONS]\n"
72           "Options:\n"
73           "  --help, -h              Display usage message\n"
74           "  --version, -V           Display version number\n"
75           "  --config PATH, -c PATH  Set configuration file\n"
76           "  --debug, -d             Turn on debugging\n"
77           "  --[no-]syslog           Enable/disable logging to syslog\n"
78           "\n"
79           "Track choose for DisOrder.  Not intended to be run\n"
80           "directly.\n");
81   xfclose(stdout);
82   exit(0);
83 }
84
85 /** @brief Weighted track record */
86 struct weighted_track {
87   /** @brief Next track in the list */
88   struct weighted_track *next;
89   /** @brief Track name */
90   const char *track;
91   /** @brief Weight for this track (always positive) */
92   unsigned long weight;
93 };
94
95 /** @brief List of tracks with nonzero weight */
96 static struct weighted_track *tracks;
97
98 /** @brief Sum of all weights */
99 static unsigned long long total_weight;
100
101 /** @brief Count of tracks */
102 static long ntracks;
103
104 /** @brief Compute the weight of a track
105  * @param track Track name (UTF-8)
106  * @param data Track data
107  * @param prefs Track preferences
108  * @return Track weight (non-negative)
109  *
110  * Tracks to be excluded entirely are given a weight of 0.
111  */
112 static unsigned long compute_weight(const char attribute((unused)) *track,
113                                     struct kvp attribute((unused)) *data,
114                                     struct kvp *prefs) {
115   const char *s;
116
117   /* Firstly, tracks with random play disabled always have weight 0 and that's
118    * that */
119   if((s = kvp_get(prefs, "pick_at_random"))
120      && !strcmp(s, "0"))
121     return 0;
122   return 90000;
123 }
124
125 /** @brief Called for each track */
126 static int collect_tracks_callback(const char *track,
127                                    struct kvp *data,
128                                    struct kvp *prefs,
129                                    void attribute((unused)) *u,
130                                    DB_TXN attribute((unused)) *tid) {
131   const unsigned long weight = compute_weight(track, data, prefs);
132
133   if(weight) {
134     struct weighted_track *const t = xmalloc(sizeof *t);
135
136     t->next = tracks;
137     t->track = track;
138     t->weight = weight;
139     tracks = t;
140     total_weight += weight;
141     ++ntracks;
142   }
143   return 0;
144 }
145
146 /** @brief Pick a random integer uniformly from [0, limit) */
147 static unsigned long long pick_weight(unsigned long long limit) {
148   unsigned long long n;
149   static int fd = -1;
150   int r;
151
152   if(fd < 0) {
153     if((fd = open("/dev/urandom", O_RDONLY)) < 0)
154       fatal(errno, "opening /dev/urandom");
155   }
156   if((r = read(fd, &n, sizeof n)) < 0)
157     fatal(errno, "reading /dev/urandom");
158   if((size_t)r < sizeof n)
159     fatal(0, "short read from /dev/urandom");
160   return n % limit;
161 }
162
163 /** @brief Pick a track at random and write it to stdout */
164 static void pick_track(void) {
165   long long w;
166   struct weighted_track *t;
167
168   w = pick_weight(total_weight);
169   t = tracks;
170   while(t && w >= t->weight) {
171     w -= t->weight;
172     t = t->next;
173   }
174   if(!t)
175     fatal(0, "ran out of tracks but %lld weighting left", w);
176   xprintf("%s", t->track);
177 }
178
179 int main(int argc, char **argv) {
180   int n, logsyslog = !isatty(2);
181   
182   set_progname(argv);
183   mem_init();
184   if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
185   while((n = getopt_long(argc, argv, "hVc:dDSs", options, 0)) >= 0) {
186     switch(n) {
187     case 'h': help();
188     case 'V': version("disorder-choose");
189     case 'c': configfile = optarg; break;
190     case 'd': debugging = 1; break;
191     case 'D': debugging = 0; break;
192     case 'S': logsyslog = 0; break;
193     case 's': logsyslog = 1; break;
194     default: fatal(0, "invalid option");
195     }
196   }
197   if(logsyslog) {
198     openlog(progname, LOG_PID, LOG_DAEMON);
199     log_default = &log_syslog;
200   }
201   if(config_read(0)) fatal(0, "cannot read configuration");
202   /* Generate the candidate track list */
203   trackdb_init(TRACKDB_NO_RECOVER);
204   trackdb_open(TRACKDB_NO_UPGRADE|TRACKDB_READ_ONLY);
205   global_tid = trackdb_begin_transaction();
206   if(trackdb_scan(0, collect_tracks_callback, 0, global_tid))
207     exit(1);
208   trackdb_commit_transaction(global_tid);
209   trackdb_close();
210   trackdb_deinit();
211   //info("ntracks=%ld total_weight=%lld", ntracks, total_weight);
212   if(!total_weight)
213     fatal(0, "no tracks match random choice criteria");
214   /* Pick a track */
215   pick_track();
216   xfclose(stdout);
217   return 0;
218 }
219
220 /*
221 Local Variables:
222 c-basic-offset:2
223 comment-column:40
224 fill-column:79
225 indent-tabs-mode:nil
226 End:
227 */