chiark / gitweb /
Switch to GPL v3
[disorder] / server / schedule.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 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 /** @file server/schedule.c
20  * @brief Scheduled events
21  *
22  * @ref trackdb_scheduledb is a mapping from ID strings to encoded
23  * key-value pairs called 'actiondata'.
24  *
25  * Possible actiondata keys are:
26  * - @b when: when to perform this action (required)
27  * - @b who: originator for action (required)
28  * - @b action: action to perform (required)
29  * - @b track: for @c action=play, the track to play
30  * - @b key: for @c action=set-global, the global pref to set
31  * - @b value: for @c action=set-global, the value to set (omit to unset)
32  * - @b priority: the importance of this action
33  * - @b recurs: how the event recurs; NOT IMPLEMENTED
34  * - ...others to be defined
35  *
36  * Possible actions are:
37  * - @b play: play a track
38  * - @b set-global: set or unset a global pref
39  * - ...others to be defined
40  *
41  * Possible priorities are:
42  * - @b junk: junk actions that are in the past at startup are discarded
43  * - @b normal: normal actions that are in the past at startup are run
44  *   immediately.  (This the default.)
45  * - ...others to be defined
46  *
47  * On startup the schedule database is read and a timeout set on the event loop
48  * for each action.  Similarly when an action is added, a timeout is set on the
49  * event loop.  The timeout has the ID attached as user data so that the action
50  * can easily be found again.
51  *
52  * Recurring events are NOT IMPLEMENTED yet but this is the proposed
53  * interface:
54  *
55  * Recurring events are updated with a new 'when' field when they are processed
56  * (event on error).  Non-recurring events are just deleted after processing.
57  *
58  * The recurs field is a whitespace-delimited list of criteria:
59  * - nn:nn or nn:nn:nn define a time of day, in local time.  There must be
60  *   at least one of these but can be more than one.
61  * - a day name (monday, tuesday, ...) defines the days of the week on
62  *   which the event will recur.  There can be more than one.
63  * - a day number and month name (1 january, 5 february, ...) defines
64  *   the days of the year on which the event will recur.  There can be
65  *   more than one of these.
66  *
67  * Day and month names are case insensitive.  Multiple languages are
68  * likely to be supported, especially if people send me pointers to
69  * their month and day names.  Abbreviations are NOT supported, as
70  * there is more of a risk of a clash between different languages that
71  * way.
72  *
73  * If there are no week or year days then the event recurs every day.
74  *
75  * If there are both week and year days then the union of them is
76  * taken, rather than the intersection.
77  *
78  * TODO: support recurring events.
79  *
80  * TODO: add disorder-dump support
81  */
82 #include "disorder-server.h"
83
84 static int schedule_trigger(ev_source *ev,
85                             const struct timeval *now,
86                             void *u);
87 static int schedule_lookup(const char *id,
88                            struct kvp *actiondata);
89
90 /** @brief List of required fields in a scheduled event */
91 static const char *const schedule_required[] = {"when", "who", "action"};
92
93 /** @brief Number of elements in @ref schedule_required */
94 #define NREQUIRED (int)(sizeof schedule_required / sizeof *schedule_required)
95
96 /** @brief Parse a scheduled event key and data
97  * @param k Pointer to key
98  * @param whenp Where to store timestamp
99  * @return 0 on success, non-0 on error
100  *
101  * Rejects entries that are invalid in various ways.
102  */
103 static int schedule_parse(const DBT *k,
104                           const DBT *d,
105                           char **idp,
106                           struct kvp **actiondatap,
107                           time_t *whenp) {
108   char *id;
109   struct kvp *actiondata;
110   int n;
111
112   /* Reject bogus keys */
113   if(!k->size || k->size > 128) {
114     error(0, "bogus schedule.db key (%lu bytes)", (unsigned long)k->size);
115     return -1;
116   }
117   id = xstrndup(k->data, k->size);
118   actiondata = kvp_urldecode(d->data, d->size);
119   /* Reject items without the required fields */
120   for(n = 0; n < NREQUIRED; ++n) {
121     if(!kvp_get(actiondata, schedule_required[n])) {
122       error(0, "scheduled event %s: missing required field '%s'",
123             id, schedule_required[n]);
124       return -1;
125     }
126   }
127   /* Return the results */
128   if(idp)
129     *idp = id;
130   if(actiondatap)
131     *actiondatap = actiondata;
132   if(whenp)
133     *whenp = (time_t)atoll(kvp_get(actiondata, "when"));
134   return 0;
135 }
136
137 /** @brief Delete via a cursor
138  * @return 0 or @c DB_LOCK_DEADLOCK */
139 static int cdel(DBC *cursor) {
140   int err;
141
142   switch(err = cursor->c_del(cursor, 0)) {
143   case 0:
144     break;
145   case DB_LOCK_DEADLOCK:
146     error(0, "error deleting from schedule.db: %s", db_strerror(err));
147     break;
148   default:
149     fatal(0, "error deleting from schedule.db: %s", db_strerror(err));
150   }
151   return err;
152 }
153
154 /** @brief Initialize the schedule
155  * @param ev Event loop
156  * @param tid Transaction ID
157  *
158  * Sets a callback for all action times except for junk actions that are
159  * already in the past, which are discarded.
160  */
161 static int schedule_init_tid(ev_source *ev,
162                              DB_TXN *tid) {
163   DBC *cursor;
164   DBT k, d;
165   int err;
166
167   cursor = trackdb_opencursor(trackdb_scheduledb, tid);
168   while(!(err = cursor->c_get(cursor, prepare_data(&k),  prepare_data(&d),
169                               DB_NEXT))) {
170     struct timeval when;
171     struct kvp *actiondata;
172     char *id;
173
174     /* Parse the key.  We destroy bogus entries on sight. */
175     if(schedule_parse(&k, &d, &id, &actiondata, &when.tv_sec)) {
176       if((err = cdel(cursor)))
177         goto deadlocked;
178       continue;
179     }
180     when.tv_usec = 0;
181     /* The action might be in the past */
182     if(when.tv_sec < time(0)) {
183       const char *priority = kvp_get(actiondata, "priority");
184
185       if(priority && !strcmp(priority, "junk")) {
186         /* Junk actions that are in the past are discarded during startup */
187         /* TODO recurring events should be handled differently here */
188         info("junk event %s is in the past, discarding", id);
189         if(cdel(cursor))
190           goto deadlocked;
191         /* Skip this time */
192         continue;
193       }
194     }
195     /* Arrange a callback when the scheduled event is due */
196     ev_timeout(ev, 0/*handlep*/, &when, schedule_trigger, id);
197   }
198   switch(err) {
199   case DB_NOTFOUND:
200     err = 0;
201     break;
202   case DB_LOCK_DEADLOCK:
203     error(0, "error querying schedule.db: %s", db_strerror(err));
204     break;
205   default:
206     fatal(0, "error querying schedule.db: %s", db_strerror(err));
207   }
208 deadlocked:
209   if(trackdb_closecursor(cursor))
210     err = DB_LOCK_DEADLOCK;
211   return err;
212 }
213
214 /** @brief Initialize the schedule
215  * @param ev Event loop
216  *
217  * Sets a callback for all action times except for junk actions that are
218  * already in the past, which are discarded.
219  */
220 void schedule_init(ev_source *ev) {
221   int e;
222   WITH_TRANSACTION(schedule_init_tid(ev, tid));
223 }
224
225 /******************************************************************************/
226
227 /** @brief Create a scheduled event
228  * @param ev Event loop
229  * @param actiondata Action data
230  */
231 static int schedule_add_tid(const char *id,
232                             struct kvp *actiondata,
233                             DB_TXN *tid) {
234   int err;
235   DBT k, d;
236
237   memset(&k, 0, sizeof k);
238   k.data = (void *)id;
239   k.size = strlen(id);
240   switch(err = trackdb_scheduledb->put(trackdb_scheduledb, tid, &k,
241                                        encode_data(&d, actiondata),
242                                        DB_NOOVERWRITE)) {
243   case 0:
244     break;
245   case DB_LOCK_DEADLOCK:
246     error(0, "error updating schedule.db: %s", db_strerror(err));
247     return err;
248   case DB_KEYEXIST:
249     return err;
250   default:
251     fatal(0, "error updating schedule.db: %s", db_strerror(err));
252   }
253   return 0;
254 }
255
256 /** @brief Create a scheduled event
257  * @param ev Event loop
258  * @param actiondata Action actiondata
259  * @return Scheduled event ID or NULL on error
260  *
261  * Events are rejected if they lack the required fields, if the user
262  * is not allowed to perform them or if they are scheduled for a time
263  * in the past.
264  */
265 const char *schedule_add(ev_source *ev,
266                          struct kvp *actiondata) {
267   int e, n;
268   const char *id;
269   struct timeval when;
270
271   /* TODO: handle recurring events */
272   /* Check that the required field are present */
273   for(n = 0; n < NREQUIRED; ++n) {
274     if(!kvp_get(actiondata, schedule_required[n])) {
275       error(0, "new scheduled event is missing required field '%s'",
276             schedule_required[n]);
277       return 0;
278     }
279   }
280   /* Check that the user is allowed to do whatever it is */
281   if(schedule_lookup("[new]", actiondata) < 0)
282     return 0;
283   when.tv_sec = atoll(kvp_get(actiondata, "when"));
284   when.tv_usec = 0;
285   /* Reject events in the past */
286   if(when.tv_sec <= time(0)) {
287     error(0, "new scheduled event is in the past");
288     return 0;
289   }
290   do {
291     id = random_id();
292     WITH_TRANSACTION(schedule_add_tid(id, actiondata, tid));
293   } while(e == DB_KEYEXIST);
294   ev_timeout(ev, 0/*handlep*/, &when, schedule_trigger, (void *)id);
295   return id;
296 }
297
298 /******************************************************************************/
299
300 /** @brief Get the action data for a scheduled event
301  * @param id Event ID
302  * @return Event data or NULL
303  */
304 struct kvp *schedule_get(const char *id) {
305   int e, n;
306   struct kvp *actiondata;
307   
308   WITH_TRANSACTION(trackdb_getdata(trackdb_scheduledb, id, &actiondata, tid));
309   /* Check that the required field are present */
310   for(n = 0; n < NREQUIRED; ++n) {
311     if(!kvp_get(actiondata, schedule_required[n])) {
312       error(0, "scheduled event %s is missing required field '%s'",
313             id, schedule_required[n]);
314       return 0;
315     }
316   }
317   return actiondata;
318 }
319
320 /******************************************************************************/
321
322 /** @brief Delete a scheduled event
323  * @param id Event to delete
324  * @return 0 on success, non-0 if it did not exist
325  */
326 int schedule_del(const char *id) {
327   int e;
328
329   WITH_TRANSACTION(trackdb_delkey(trackdb_scheduledb, id, tid));
330   return e == 0 ? 0 : -1;
331 }
332
333 /******************************************************************************/
334
335 /** @brief Get a list of scheduled events
336  * @param neventsp Where to put count of events (or NULL)
337  * @return 0-terminate list of ID strings
338  */
339 char **schedule_list(int *neventsp) {
340   int e;
341   struct vector v[1];
342
343   vector_init(v);
344   WITH_TRANSACTION(trackdb_listkeys(trackdb_scheduledb, v, tid));
345   if(neventsp)
346     *neventsp = v->nvec;
347   return v->vec;
348 }
349
350 /******************************************************************************/
351
352 static void schedule_play(ev_source *ev,
353                           const char *id,
354                           const char *who,
355                           struct kvp *actiondata) {
356   const char *track = kvp_get(actiondata, "track");
357   struct queue_entry *q;
358
359   /* This stuff has rather a lot in common with c_play() */
360   if(!track) {
361     error(0, "scheduled event %s: no track field", id);
362     return;
363   }
364   if(!trackdb_exists(track)) {
365     error(0, "scheduled event %s: no such track as %s", id, track);
366     return;
367   }
368   if(!(track = trackdb_resolve(track))) {
369     error(0, "scheduled event %s: cannot resolve track %s", id, track);
370     return;
371   }
372   info("scheduled event %s: %s play %s", id,  who, track);
373   q = queue_add(track, who, WHERE_START);
374   queue_write();
375   if(q == qhead.next && playing)
376     prepare(ev, q);
377   play(ev);
378 }
379
380 static void schedule_set_global(ev_source attribute((unused)) *ev,
381                                 const char *id,
382                                 const char *who,
383                                 struct kvp *actiondata) {
384   const char *key = kvp_get(actiondata, "key");
385   const char *value = kvp_get(actiondata, "value");
386
387   if(!key) {
388     error(0, "scheduled event %s: no key field", id);
389     return;
390   }
391   if(key[0] == '_') {
392     error(0, "scheduled event %s: cannot set internal global preferences (%s)",
393           id, key);
394     return;
395   }
396   if(value)
397     info("scheduled event %s: %s set-global %s=%s", id, who, key, value);
398   else
399     info("scheduled event %s: %s set-global %s unset", id,  who, key);
400   trackdb_set_global(key, value, who);
401 }
402
403 /** @brief Table of schedule actions
404  *
405  * Must be kept sorted.
406  */
407 static struct {
408   const char *name;
409   void (*callback)(ev_source *ev,
410                    const char *id, const char *who,
411                    struct kvp *actiondata);
412   rights_type right;
413 } schedule_actions[] = {
414   { "play", schedule_play, RIGHT_PLAY },
415   { "set-global", schedule_set_global, RIGHT_GLOBAL_PREFS },
416 };
417
418 /** @brief Look up a scheduled event
419  * @param actiondata Event description
420  * @return index in schedule_actions[] on success, -1 on error
421  *
422  * Unknown events are rejected as are those that the user is not allowed to do.
423  */
424 static int schedule_lookup(const char *id,
425                            struct kvp *actiondata) {
426   const char *who = kvp_get(actiondata, "who");
427   const char *action = kvp_get(actiondata, "action");
428   const char *rights;
429   struct kvp *userinfo;
430   rights_type r;
431   int n;
432
433   /* Look up the action */
434   n = TABLE_FIND(schedule_actions, name, action);
435   if(n < 0) {
436     error(0, "scheduled event %s: unrecognized action '%s'", id, action);
437     return -1;
438   }
439   /* Find the user */
440   if(!(userinfo = trackdb_getuserinfo(who))) {
441     error(0, "scheduled event %s: user '%s' does not exist", id, who);
442     return -1;
443   }
444   /* Check that they have suitable rights */
445   if(!(rights = kvp_get(userinfo, "rights"))) {
446     error(0, "scheduled event %s: user %s' has no rights???", id, who);
447     return -1;
448   }
449   if(parse_rights(rights, &r, 1)) {
450     error(0, "scheduled event %s: user %s has invalid rights '%s'",
451           id, who, rights);
452     return -1;
453   }
454   if(!(r & schedule_actions[n].right)) {
455     error(0, "scheduled event %s: user %s lacks rights for action %s",
456           id, who, action);
457     return -1;
458   }
459   return n;
460 }
461
462 /** @brief Called when an action is due */
463 static int schedule_trigger(ev_source *ev,
464                             const struct timeval attribute((unused)) *now,
465                             void *u) {
466   const char *action, *id = u;
467   struct kvp *actiondata = schedule_get(id);
468   int n;
469
470   if(!actiondata)
471     return 0;
472   /* schedule_get() enforces these being present */
473   action = kvp_get(actiondata, "action");
474   /* Look up the action */
475   n = schedule_lookup(id, actiondata);
476   if(n < 0)
477     goto done;
478   /* Go ahead and do it */
479   schedule_actions[n].callback(ev, id, kvp_get(actiondata, "who"), actiondata);
480 done:
481   /* TODO: rewrite recurring events for their next trigger time,
482    * rather than deleting them */
483   schedule_del(id);
484   return 0;
485 }
486
487 /*
488 Local Variables:
489 c-basic-offset:2
490 comment-column:40
491 fill-column:79
492 indent-tabs-mode:nil
493 End:
494 */