]> git.tuebingen.mpg.de Git - dss.git/blob - dss.c
089f954da86ceeb9997420300e466c0a45a619b8
[dss.git] / dss.c
1 /*
2  * Copyright (C) 2008 Andre Noll <maan@systemlinux.org>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6 #include <string.h>
7 #include <stdlib.h>
8 #include <stdarg.h>
9 #include <assert.h>
10 #include <errno.h>
11 #include <sys/types.h>
12 #include <signal.h>
13 #include <ctype.h>
14 #include <sys/stat.h>
15 #include <unistd.h>
16 #include <inttypes.h>
17 #include <sys/time.h>
18 #include <time.h>
19 #include <sys/wait.h>
20 #include <fnmatch.h>
21 #include <limits.h>
22
23
24 #include "gcc-compat.h"
25 #include "cmdline.h"
26 #include "log.h"
27 #include "string.h"
28 #include "error.h"
29 #include "fd.h"
30 #include "exec.h"
31 #include "daemon.h"
32 #include "signal.h"
33 #include "df.h"
34 #include "time.h"
35 #include "snap.h"
36
37 /** Command line and config file options. */
38 static struct gengetopt_args_info conf;
39 /** Non-NULL if we log to a file. */
40 static FILE *logfile;
41 /** The read end of the signal pipe */
42 static int signal_pipe;
43 /** Process id of current pre-create-hook/rsync/post-create-hook process. */
44 static pid_t create_pid;
45 /** Whether the pre-create-hook/rsync/post-create-hook is currently stopped. */
46 static int create_process_stopped;
47 /** Process id of current pre-remove/rm/post-remove process. */
48 static pid_t remove_pid;
49 /** When the next snapshot is due. */
50 static struct timeval next_snapshot_time;
51 /** When to try to remove something. */
52 static struct timeval next_removal_check;
53 /** Creation time of the snapshot currently being created. */
54 static int64_t current_snapshot_creation_time;
55 /* The snapshot currently being removed. */
56 struct snapshot *snapshot_currently_being_removed;
57 /** Needed by the post-create hook. */
58 static char *path_to_last_complete_snapshot;
59 /** \sa \ref snap.h for details. */
60 enum hook_status snapshot_creation_status;
61 /** \sa \ref snap.h for details. */
62 enum hook_status snapshot_removal_status;
63
64
65 DEFINE_DSS_ERRLIST;
66
67
68 /* a litte cpp magic helps to DRY */
69 #define COMMANDS \
70         COMMAND(ls) \
71         COMMAND(create) \
72         COMMAND(prune) \
73         COMMAND(run)
74 #define COMMAND(x) static int com_ ##x(void);
75 COMMANDS
76 #undef COMMAND
77 #define COMMAND(x) if (conf.x ##_given) return com_ ##x();
78 static int call_command_handler(void)
79 {
80         COMMANDS
81         DSS_EMERG_LOG("BUG: did not find command handler\n");
82         return -E_BUG;
83 }
84 #undef COMMAND
85 #undef COMMANDS
86
87 /**
88  * The log function of dss.
89  *
90  * \param ll Loglevel.
91  * \param fml Usual format string.
92  *
93  * All DSS_XXX_LOG() macros use this function.
94  */
95 __printf_2_3 void dss_log(int ll, const char* fmt,...)
96 {
97         va_list argp;
98         FILE *outfd;
99         struct tm *tm;
100         time_t t1;
101         char str[255] = "";
102
103         if (ll < conf.loglevel_arg)
104                 return;
105         outfd = logfile? logfile : stderr;
106         time(&t1);
107         tm = localtime(&t1);
108         strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
109         fprintf(outfd, "%s ", str);
110         if (conf.loglevel_arg <= INFO)
111                 fprintf(outfd, "%i: ", ll);
112         va_start(argp, fmt);
113         vfprintf(outfd, fmt, argp);
114         va_end(argp);
115 }
116
117 /**
118  * Print a message either to stdout or to the log file.
119  */
120 static __printf_1_2 void dss_msg(const char* fmt,...)
121 {
122         FILE *outfd = conf.daemon_given? logfile : stdout;
123         va_list argp;
124         va_start(argp, fmt);
125         vfprintf(outfd, fmt, argp);
126         va_end(argp);
127 }
128
129 static int disk_space_low(void)
130 {
131         struct disk_space ds;
132         int ret = get_disk_space(".", &ds);
133
134         if (ret < 0)
135                 return ret;
136         if (conf.min_free_mb_arg)
137                 if (ds.free_mb < conf.min_free_mb_arg)
138                         return 1;
139         if (conf.min_free_percent_arg)
140                 if (ds.percent_free < conf.min_free_percent_arg)
141                         return 1;
142         if (conf.min_free_percent_inodes_arg)
143                 if (ds.percent_free_inodes < conf.min_free_percent_inodes_arg)
144                         return 1;
145         return 0;
146 }
147
148 static void dss_get_snapshot_list(struct snapshot_list *sl)
149 {
150         get_snapshot_list(sl, conf.unit_interval_arg, conf.num_intervals_arg);
151 }
152
153 static int next_snapshot_is_due(void)
154 {
155         struct timeval now, unit_interval = {.tv_sec = 24 * 3600 * conf.unit_interval_arg},
156                 tmp, diff;
157         int64_t x = 0;
158         unsigned wanted = desired_number_of_snapshots(0, conf.num_intervals_arg),
159                 num_complete_snapshots = 0;
160         int i, ret;
161         struct snapshot *s = NULL;
162         struct snapshot_list sl;
163
164         gettimeofday(&now, NULL);
165         if (tv_diff(&next_snapshot_time, &now, NULL) > 0)
166                 return 0;
167         assert(snapshot_creation_status == HS_READY);
168         current_snapshot_creation_time = 0;
169         dss_get_snapshot_list(&sl);
170         FOR_EACH_SNAPSHOT(s, i, &sl) {
171                 if (!(s->flags & SS_COMPLETE))
172                         continue;
173                 num_complete_snapshots++;
174                 x += s->completion_time - s->creation_time;
175         }
176         assert(x >= 0);
177         if (num_complete_snapshots)
178                 x /= num_complete_snapshots; /* avg time to create one snapshot */
179         x *= wanted; /* time to create all snapshots in interval 0 */
180         tmp.tv_sec = x;
181         tmp.tv_usec = 0;
182         ret = tv_diff(&unit_interval, &tmp, &diff); /* total sleep time per unit interval */
183         if (ret < 0 || !s) { /* unit_interval < tmp or no snapshot */
184                 ret = 1;
185                 goto out;
186         }
187
188         tv_divide(wanted, &diff, &tmp); /* sleep time between two snapshots */
189         diff.tv_sec = s->completion_time; /* completion time of the latest snapshot */
190         diff.tv_usec = 0;
191         tv_add(&diff, &tmp, &next_snapshot_time);
192         ret = (tv_diff(&now, &next_snapshot_time, &diff) < 0)? 0 : 1;
193 out:
194         free_snapshot_list(&sl);
195         if (ret == 0)
196                 DSS_DEBUG_LOG("next snapshot due in %lu seconds\n",
197                         tv2ms(&diff) / 1000);
198         else
199                 DSS_DEBUG_LOG("next snapshot: now\n");
200         return ret;
201 }
202
203 static int pre_create_hook(void)
204 {
205         int ret, fds[3] = {0, 0, 0};
206
207         assert(snapshot_creation_status == HS_READY);
208         if (!conf.pre_create_hook_given) {
209                 snapshot_creation_status = HS_PRE_SUCCESS;
210                 return 0;
211         }
212         DSS_DEBUG_LOG("executing %s\n", conf.pre_create_hook_arg);
213         ret = dss_exec_cmdline_pid(&create_pid,
214                 conf.pre_create_hook_arg, fds);
215         if (ret < 0)
216                 return ret;
217         snapshot_creation_status = HS_PRE_RUNNING;
218         return ret;
219 }
220
221 static int pre_remove_hook(struct snapshot *s, const char *why)
222 {
223         int ret, fds[3] = {0, 0, 0};
224         char *cmd;
225
226         if (!s)
227                 return 0;
228         DSS_DEBUG_LOG("%s snapshot %s\n", why, s->name);
229         assert(snapshot_removal_status == HS_READY);
230         assert(remove_pid == 0);
231         assert(!snapshot_currently_being_removed);
232
233         snapshot_currently_being_removed = dss_malloc(sizeof(struct snapshot));
234         *snapshot_currently_being_removed = *s;
235         snapshot_currently_being_removed->name = dss_strdup(s->name);
236
237         if (!conf.pre_remove_hook_given) {
238                 snapshot_removal_status = HS_PRE_SUCCESS;
239                 return 0;
240         }
241         cmd = make_message("%s %s/%s", conf.pre_remove_hook_arg,
242                 conf.dest_dir_arg, s->name);
243         DSS_DEBUG_LOG("executing %s\n", cmd);
244         ret = dss_exec_cmdline_pid(&remove_pid,
245                 conf.pre_remove_hook_arg, fds);
246         free(cmd);
247         if (ret < 0)
248                 return ret;
249         snapshot_removal_status = HS_PRE_RUNNING;
250         return ret;
251 }
252
253 static int exec_rm(void)
254 {
255         struct snapshot *s = snapshot_currently_being_removed;
256         int fds[3] = {0, 0, 0};
257         char *new_name = being_deleted_name(s);
258         char *argv[] = {"rm", "-rf", new_name, NULL};
259         int ret;
260
261         assert(snapshot_removal_status == HS_PRE_SUCCESS);
262         assert(remove_pid == 0);
263
264         DSS_NOTICE_LOG("removing %s (interval = %i)\n", s->name, s->interval);
265         ret = dss_rename(s->name, new_name);
266         if (ret < 0)
267                 goto out;
268         ret = dss_exec(&remove_pid, argv[0], argv, fds);
269         if (ret < 0)
270                 goto out;
271         snapshot_removal_status = HS_RUNNING;
272 out:
273         free(new_name);
274         return ret;
275 }
276
277 static int snapshot_is_being_created(struct snapshot *s)
278 {
279         return s->creation_time == current_snapshot_creation_time;
280 }
281
282 static struct snapshot *find_orphaned_snapshot(struct snapshot_list *sl)
283 {
284         struct snapshot *s;
285         int i;
286
287         DSS_DEBUG_LOG("looking for orphaned snapshots\n");
288         FOR_EACH_SNAPSHOT(s, i, sl) {
289                 if (snapshot_is_being_created(s))
290                         continue;
291                 /*
292                  * We know that no rm is currently running, so if s is marked
293                  * as being deleted, a previously started rm must have failed.
294                  */
295                 if (s->flags & SS_BEING_DELETED)
296                         return s;
297
298                 if (s->flags & SS_COMPLETE) /* good snapshot */
299                         continue;
300                 /*
301                  * This snapshot is incomplete and it is not the snapshot
302                  * currently being created. However, we must not remove it if
303                  * rsync is about to be restarted. As only the newest snapshot
304                  * can be restarted, this snapshot is orphaned if it is not the
305                  * newest snapshot or if we are not about to restart rsync.
306                  */
307                 if (get_newest_snapshot(sl) != s)
308                         return s;
309                 if (snapshot_creation_status != HS_NEEDS_RESTART)
310                         return s;
311         }
312         /* no orphaned snapshots */
313         return NULL;
314 }
315
316 /*
317  * return: 0: no redundant snapshots, 1: rm process started, negative: error
318  */
319 static struct snapshot *find_redundant_snapshot(struct snapshot_list *sl)
320 {
321         int i, interval;
322         struct snapshot *s;
323         unsigned missing = 0;
324
325         DSS_DEBUG_LOG("looking for intervals containing too many snapshots\n");
326         for (interval = conf.num_intervals_arg - 1; interval >= 0; interval--) {
327                 unsigned keep = desired_number_of_snapshots(interval, conf.num_intervals_arg);
328                 unsigned num = sl->interval_count[interval];
329                 struct snapshot *victim = NULL, *prev = NULL;
330                 int64_t score = LONG_MAX;
331
332                 if (keep >= num)
333                         missing += keep - num;
334 //              DSS_DEBUG_LOG("interval %i: keep: %u, have: %u, missing: %u\n",
335 //                      interval, keep, num, missing);
336                 if (keep + missing >= num)
337                         continue;
338                 /* redundant snapshot in this interval, pick snapshot with lowest score */
339                 FOR_EACH_SNAPSHOT(s, i, sl) {
340                         int64_t this_score;
341
342                         if (snapshot_is_being_created(s))
343                                 continue;
344                         //DSS_DEBUG_LOG("checking %s\n", s->name);
345                         if (s->interval > interval) {
346                                 prev = s;
347                                 continue;
348                         }
349                         if (s->interval < interval)
350                                 break;
351                         if (!victim) {
352                                 victim = s;
353                                 prev = s;
354                                 continue;
355                         }
356                         assert(prev);
357                         /* check if s is a better victim */
358                         this_score = s->creation_time - prev->creation_time;
359                         assert(this_score >= 0);
360                         //DSS_DEBUG_LOG("%s: score %lli\n", s->name, (long long)score);
361                         if (this_score < score) {
362                                 score = this_score;
363                                 victim = s;
364                         }
365                         prev = s;
366                 }
367                 assert(victim);
368                 return victim;
369         }
370         return NULL;
371 }
372
373 static struct snapshot *find_outdated_snapshot(struct snapshot_list *sl)
374 {
375         int i;
376         struct snapshot *s;
377
378         DSS_DEBUG_LOG("looking for snapshots belonging to intervals greater than %d\n",
379                 conf.num_intervals_arg);
380         FOR_EACH_SNAPSHOT(s, i, sl) {
381                 if (snapshot_is_being_created(s))
382                         continue;
383                 if (s->interval <= conf.num_intervals_arg)
384                         continue;
385                 return s;
386         }
387         return NULL;
388 }
389
390 struct snapshot *find_oldest_removable_snapshot(struct snapshot_list *sl)
391 {
392         struct snapshot *s = get_oldest_snapshot(sl);
393
394         if (!s) /* no snapshot found */
395                 return NULL;
396         DSS_INFO_LOG("oldest snapshot: %s\n", s->name);
397         if (snapshot_is_being_created(s))
398                 return NULL;
399         return s;
400 }
401
402 static int rename_incomplete_snapshot(int64_t start)
403 {
404         char *old_name;
405         int ret;
406
407         free(path_to_last_complete_snapshot);
408         ret = complete_name(start, get_current_time(),
409                 &path_to_last_complete_snapshot);
410         if (ret < 0)
411                 return ret;
412         old_name = incomplete_name(start);
413         ret = dss_rename(old_name, path_to_last_complete_snapshot);
414         if (ret >= 0)
415                 DSS_NOTICE_LOG("%s -> %s\n", old_name,
416                         path_to_last_complete_snapshot);
417         free(old_name);
418         return ret;
419 }
420
421 static int try_to_free_disk_space(int low_disk_space)
422 {
423         int ret;
424         struct snapshot_list sl;
425         struct snapshot *victim;
426         struct timeval now;
427         const char *why;
428
429         gettimeofday(&now, NULL);
430         if (tv_diff(&next_removal_check, &now, NULL) > 0)
431                 return 0;
432         if (!low_disk_space && conf.keep_redundant_given)
433                 return 0;
434         dss_get_snapshot_list(&sl);
435         ret = 0;
436         if (!low_disk_space && sl.num_snapshots <= 1)
437                 goto out;
438         why = "outdated";
439         victim = find_outdated_snapshot(&sl);
440         if (victim)
441                 goto remove;
442         why = "redundant";
443         victim = find_redundant_snapshot(&sl);
444         if (victim)
445                 goto remove;
446         /* try harder only if disk space is low */
447         if (!low_disk_space)
448                 goto out;
449         why = "orphaned";
450         victim = find_orphaned_snapshot(&sl);
451         if (victim)
452                 goto remove;
453         DSS_WARNING_LOG("disk space low and nothing obvious to remove\n");
454         victim = find_oldest_removable_snapshot(&sl);
455         if (victim)
456                 goto remove;
457         DSS_CRIT_LOG("uhuhu: not enough disk space for a single snapshot\n");
458         ret = -ERRNO_TO_DSS_ERROR(ENOSPC);
459         goto out;
460 remove:
461         ret = pre_remove_hook(victim, why);
462 out:
463         free_snapshot_list(&sl);
464         return ret;
465 }
466
467 static int post_create_hook(void)
468 {
469         int ret, fds[3] = {0, 0, 0};
470         char *cmd;
471
472         if (!conf.post_create_hook_given) {
473                 snapshot_creation_status = HS_READY;
474                 return 0;
475         }
476         cmd = make_message("%s %s/%s", conf.post_create_hook_arg,
477                 conf.dest_dir_arg, path_to_last_complete_snapshot);
478         DSS_NOTICE_LOG("executing %s\n", cmd);
479         ret = dss_exec_cmdline_pid(&create_pid, cmd, fds);
480         free(cmd);
481         if (ret < 0)
482                 return ret;
483         snapshot_creation_status = HS_POST_RUNNING;
484         return ret;
485 }
486
487 static int post_remove_hook(void)
488 {
489         int ret, fds[3] = {0, 0, 0};
490         char *cmd;
491         struct snapshot *s = snapshot_currently_being_removed;
492
493         assert(s);
494
495         if (!conf.post_remove_hook_given) {
496                 snapshot_removal_status = HS_READY;
497                 return 0;
498         }
499         cmd = make_message("%s %s/%s", conf.post_remove_hook_arg,
500                 conf.dest_dir_arg, s->name);
501         DSS_NOTICE_LOG("executing %s\n", cmd);
502         ret = dss_exec_cmdline_pid(&remove_pid, cmd, fds);
503         free(cmd);
504         if (ret < 0)
505                 return ret;
506         snapshot_removal_status = HS_POST_RUNNING;
507         return ret;
508 }
509
510 static void kill_process(pid_t pid)
511 {
512         if (!pid)
513                 return;
514         DSS_WARNING_LOG("sending SIGTERM to pid %d\n", (int)pid);
515         kill(pid, SIGTERM);
516 }
517
518 static void stop_create_process(void)
519 {
520         if (!create_pid || create_process_stopped)
521                 return;
522         kill(SIGSTOP, create_pid);
523         create_process_stopped = 1;
524 }
525
526 static void restart_create_process(void)
527 {
528         if (!create_pid || !create_process_stopped)
529                 return;
530         kill (SIGCONT, create_pid);
531         create_process_stopped = 0;
532 }
533
534 /**
535  * Print a log message about the exit status of a child.
536  */
537 static void log_termination_msg(pid_t pid, int status)
538 {
539         if (WIFEXITED(status))
540                 DSS_INFO_LOG("child %i exited. Exit status: %i\n", (int)pid,
541                         WEXITSTATUS(status));
542         else if (WIFSIGNALED(status))
543                 DSS_NOTICE_LOG("child %i was killed by signal %i\n", (int)pid,
544                         WTERMSIG(status));
545         else
546                 DSS_WARNING_LOG("child %i terminated abormally\n", (int)pid);
547 }
548
549 static int wait_for_process(pid_t pid, int *status)
550 {
551         int ret;
552
553         DSS_DEBUG_LOG("Waiting for process %d to terminate\n", (int)pid);
554         for (;;) {
555                 fd_set rfds;
556
557                 FD_ZERO(&rfds);
558                 FD_SET(signal_pipe, &rfds);
559                 ret = dss_select(signal_pipe + 1, &rfds, NULL, NULL);
560                 if (ret < 0)
561                         break;
562                 ret = next_signal();
563                 if (!ret)
564                         continue;
565                 if (ret == SIGCHLD) {
566                         ret = waitpid(pid, status, 0);
567                         if (ret >= 0)
568                                 break;
569                         if (errno != EINTR) { /* error */
570                                 ret = -ERRNO_TO_DSS_ERROR(errno);
571                                 break;
572                         }
573                 }
574                 /* SIGINT or SIGTERM */
575                 DSS_WARNING_LOG("sending SIGTERM to pid %d\n", (int)pid);
576                 kill(pid, SIGTERM);
577         }
578         if (ret < 0)
579                 DSS_ERROR_LOG("failed to wait for process %d\n", (int)pid);
580         else
581                 log_termination_msg(pid, *status);
582         return ret;
583 }
584
585 static void handle_pre_remove_exit(int status)
586 {
587         if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
588                 snapshot_removal_status = HS_READY;
589                 gettimeofday(&next_removal_check, NULL);
590                 next_removal_check.tv_sec += 60;
591                 return;
592         }
593         snapshot_removal_status = HS_PRE_SUCCESS;
594 }
595
596 static int handle_rm_exit(int status)
597 {
598         if (!WIFEXITED(status)) {
599                 snapshot_removal_status = HS_READY;
600                 return -E_INVOLUNTARY_EXIT;
601         }
602         if (WEXITSTATUS(status)) {
603                 snapshot_removal_status = HS_READY;
604                 return -E_BAD_EXIT_CODE;
605         }
606         if (conf.post_remove_hook_given)
607                 snapshot_removal_status = HS_SUCCESS;
608         else
609                 snapshot_removal_status = HS_READY;
610         return 1;
611 }
612
613 static void handle_post_remove_exit(void)
614 {
615         snapshot_removal_status = HS_READY;
616 }
617
618 static int handle_remove_exit(int status)
619 {
620         int ret;
621         struct snapshot *s = snapshot_currently_being_removed;
622
623         assert(s);
624         switch (snapshot_removal_status) {
625         case HS_PRE_RUNNING:
626                 handle_pre_remove_exit(status);
627                 ret = 1;
628                 break;
629         case HS_RUNNING:
630                 ret = handle_rm_exit(status);
631                 break;
632         case HS_POST_RUNNING:
633                 handle_post_remove_exit();
634                 ret = 1;
635                 break;
636         default:
637                 ret = -E_BUG;
638         }
639         if (snapshot_removal_status == HS_READY) {
640                 free(s->name);
641                 free(s);
642                 snapshot_currently_being_removed = NULL;
643         }
644         remove_pid = 0;
645         return ret;
646 }
647
648 static int wait_for_remove_process(void)
649 {
650         int status, ret;
651
652         assert(remove_pid);
653         assert(
654                 snapshot_removal_status == HS_PRE_RUNNING ||
655                 snapshot_removal_status == HS_RUNNING ||
656                 snapshot_removal_status == HS_POST_RUNNING
657         );
658         ret = wait_for_process(remove_pid, &status);
659         if (ret < 0)
660                 return ret;
661         return handle_remove_exit(status);
662 }
663
664 static int handle_rsync_exit(int status)
665 {
666         int es, ret;
667
668         if (!WIFEXITED(status)) {
669                 DSS_ERROR_LOG("rsync process %d died involuntary\n", (int)create_pid);
670                 ret = -E_INVOLUNTARY_EXIT;
671                 snapshot_creation_status = HS_READY;
672                 goto out;
673         }
674         es = WEXITSTATUS(status);
675         /*
676          * Restart rsync on non-fatal errors:
677          * 12: Error in rsync protocol data stream
678          * 13: Errors with program diagnostics
679          */
680         if (es == 12 || es == 13) {
681                 DSS_WARNING_LOG("rsync process %d returned %d -- restarting\n",
682                         (int)create_pid, es);
683                 snapshot_creation_status = HS_NEEDS_RESTART;
684                 gettimeofday(&next_snapshot_time, NULL);
685                 next_snapshot_time.tv_sec += 60;
686                 ret = 1;
687                 goto out;
688         }
689         if (es != 0 && es != 23 && es != 24) {
690                 DSS_ERROR_LOG("rsync process %d returned %d\n", (int)create_pid, es);
691                 ret = -E_BAD_EXIT_CODE;
692                 snapshot_creation_status = HS_READY;
693                 goto out;
694         }
695         ret = rename_incomplete_snapshot(current_snapshot_creation_time);
696         if (ret < 0)
697                 goto out;
698         snapshot_creation_status = HS_SUCCESS;
699 out:
700         create_pid = 0;
701         create_process_stopped = 0;
702         return ret;
703 }
704
705 static int handle_pre_create_hook_exit(int status)
706 {
707         int es, ret;
708         static int warn_count;
709
710         if (!WIFEXITED(status)) {
711                 snapshot_creation_status = HS_READY;
712                 ret = -E_INVOLUNTARY_EXIT;
713                 goto out;
714         }
715         es = WEXITSTATUS(status);
716         if (es) {
717                 if (!warn_count--) {
718                         DSS_NOTICE_LOG("pre_create_hook %s returned %d\n",
719                                 conf.pre_create_hook_arg, es);
720                         DSS_NOTICE_LOG("deferring snapshot creation...\n");
721                         warn_count = 60; /* warn only once per hour */
722                 }
723                 gettimeofday(&next_snapshot_time, NULL);
724                 next_snapshot_time.tv_sec += 60;
725                 snapshot_creation_status = HS_READY;
726                 ret = 0;
727                 goto out;
728         }
729         warn_count = 0;
730         snapshot_creation_status = HS_PRE_SUCCESS;
731         ret = 1;
732 out:
733         create_pid = 0;
734         return ret;
735 }
736
737 static int handle_sigchld(void)
738 {
739         pid_t pid;
740         int status, ret = reap_child(&pid, &status);
741
742         if (ret <= 0)
743                 return ret;
744
745         if (pid == create_pid) {
746                 switch (snapshot_creation_status) {
747                 case HS_PRE_RUNNING:
748                         return handle_pre_create_hook_exit(status);
749                 case HS_RUNNING:
750                         return handle_rsync_exit(status);
751                 case HS_POST_RUNNING:
752                         snapshot_creation_status = HS_READY;
753                         return 1;
754                 default:
755                         DSS_EMERG_LOG("BUG: create can't die in status %d\n",
756                                 snapshot_creation_status);
757                         return -E_BUG;
758                 }
759         }
760         if (pid == remove_pid) {
761                 ret = handle_remove_exit(status);
762                 if (ret < 0)
763                         return ret;
764                 return ret;
765         }
766         DSS_EMERG_LOG("BUG: unknown process %d died\n", (int)pid);
767         return -E_BUG;
768 }
769
770 static int check_config(void)
771 {
772         if (conf.unit_interval_arg <= 0) {
773                 DSS_ERROR_LOG("bad unit interval: %i\n", conf.unit_interval_arg);
774                 return -E_INVALID_NUMBER;
775         }
776         DSS_DEBUG_LOG("unit interval: %i day(s)\n", conf.unit_interval_arg);
777         if (conf.num_intervals_arg <= 0) {
778                 DSS_ERROR_LOG("bad number of intervals  %i\n", conf.num_intervals_arg);
779                 return -E_INVALID_NUMBER;
780         }
781         DSS_DEBUG_LOG("number of intervals: %i\n", conf.num_intervals_arg);
782         return 1;
783 }
784
785 static int parse_config_file(int override)
786 {
787         int ret;
788         char *config_file;
789         struct stat statbuf;
790         char *old_logfile_arg = NULL;
791         int old_daemon_given = 0;
792
793         if (conf.config_file_given)
794                 config_file = dss_strdup(conf.config_file_arg);
795         else {
796                 char *home = get_homedir();
797                 config_file = make_message("%s/.dssrc", home);
798                 free(home);
799         }
800         if (override) { /* SIGHUP */
801                 if (conf.logfile_given)
802                         old_logfile_arg = dss_strdup(conf.logfile_arg);
803                 old_daemon_given = conf.daemon_given;
804         }
805
806         ret = stat(config_file, &statbuf);
807         if (ret && conf.config_file_given) {
808                 ret = -ERRNO_TO_DSS_ERROR(errno);
809                 DSS_ERROR_LOG("failed to stat config file %s\n", config_file);
810                 goto out;
811         }
812         if (!ret) {
813                 struct cmdline_parser_params params = {
814                         .override = override,
815                         .initialize = 0,
816                         .check_required = 1,
817                         .check_ambiguity = 0,
818                         .print_errors = 1
819                 };
820                 if (override) { /* invalidate all rsync options */
821                         int i;
822
823                         for (i = 0; i < conf.rsync_option_given; i++) {
824                                 free(conf.rsync_option_arg[i]);
825                                 conf.rsync_option_arg[i] = NULL;
826                         }
827                         conf.rsync_option_given = 0;
828                 }
829                 cmdline_parser_config_file(config_file, &conf, &params);
830         }
831         ret = check_config();
832         if (ret < 0)
833                 goto out;
834         if (override) {
835                 /* don't change daemon mode on SIGHUP */
836                 conf.daemon_given = old_daemon_given;
837                 close_log(logfile);
838                 logfile = NULL;
839                 if (conf.logfile_given)
840                         free(old_logfile_arg);
841                 else if (conf.daemon_given) { /* re-use old logfile */
842                         conf.logfile_arg = old_logfile_arg;
843                         conf.logfile_given = 1;
844                 }
845         }
846         if (conf.logfile_given) {
847                 logfile = open_log(conf.logfile_arg);
848                 log_welcome(conf.loglevel_arg);
849         }
850         DSS_DEBUG_LOG("loglevel: %d\n", conf.loglevel_arg);
851 //      cmdline_parser_dump(logfile? logfile : stdout, &conf);
852 out:
853         free(config_file);
854         if (ret < 0)
855                 DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
856         return ret;
857 }
858
859 static int change_to_dest_dir(void)
860 {
861         DSS_INFO_LOG("changing cwd to %s\n", conf.dest_dir_arg);
862         return dss_chdir(conf.dest_dir_arg);
863 }
864
865 static int handle_sighup(void)
866 {
867         int ret;
868
869         DSS_NOTICE_LOG("SIGHUP\n");
870         ret = parse_config_file(1);
871         if (ret < 0)
872                 return ret;
873         return change_to_dest_dir();
874 }
875
876 static int handle_signal(void)
877 {
878         int sig, ret = next_signal();
879
880         if (ret <= 0)
881                 goto out;
882         sig = ret;
883         switch (sig) {
884         case SIGINT:
885         case SIGTERM:
886                 restart_create_process();
887                 kill_process(create_pid);
888                 kill_process(remove_pid);
889                 ret = -E_SIGNAL;
890                 break;
891         case SIGHUP:
892                 ret = handle_sighup();
893                 break;
894         case SIGCHLD:
895                 ret = handle_sigchld();
896                 break;
897         }
898 out:
899         if (ret < 0)
900                 DSS_ERROR_LOG("%s\n", dss_strerror(-ret));
901         return ret;
902 }
903
904 /*
905  * We can not use rsync locally if the local user is different from the remote
906  * user or if the src dir is not on the local host (or both).
907  */
908 static int use_rsync_locally(char *logname)
909 {
910         char *h = conf.remote_host_arg;
911
912         if (strcmp(h, "localhost") && strcmp(h, "127.0.0.1"))
913                 return 0;
914         if (conf.remote_user_given && strcmp(conf.remote_user_arg, logname))
915                 return 0;
916         return 1;
917 }
918
919 static void create_rsync_argv(char ***argv, int64_t *num)
920 {
921         char *logname, *newest;
922         int i = 0, j;
923         struct snapshot_list sl;
924
925         dss_get_snapshot_list(&sl);
926         newest = name_of_newest_complete_snapshot(&sl);
927         free_snapshot_list(&sl);
928
929         *argv = dss_malloc((15 + conf.rsync_option_given) * sizeof(char *));
930         (*argv)[i++] = dss_strdup("rsync");
931         (*argv)[i++] = dss_strdup("-aq");
932         (*argv)[i++] = dss_strdup("--delete");
933         for (j = 0; j < conf.rsync_option_given; j++)
934                 (*argv)[i++] = dss_strdup(conf.rsync_option_arg[j]);
935         if (newest) {
936                 DSS_INFO_LOG("using %s as reference snapshot\n", newest);
937                 (*argv)[i++] = make_message("--link-dest=../%s", newest);
938                 free(newest);
939         } else
940                 DSS_INFO_LOG("no previous snapshot found\n");
941         logname = dss_logname();
942         if (use_rsync_locally(logname))
943                 (*argv)[i++] = dss_strdup(conf.source_dir_arg);
944         else
945                 (*argv)[i++] = make_message("%s@%s:%s/", conf.remote_user_given?
946                         conf.remote_user_arg : logname,
947                         conf.remote_host_arg, conf.source_dir_arg);
948         free(logname);
949         *num = get_current_time();
950         (*argv)[i++] = incomplete_name(*num);
951         (*argv)[i++] = NULL;
952         for (j = 0; j < i; j++)
953                 DSS_DEBUG_LOG("argv[%d] = %s\n", j, (*argv)[j]);
954 }
955
956 static void free_rsync_argv(char **argv)
957 {
958         int i;
959
960         if (!argv)
961                 return;
962         for (i = 0; argv[i]; i++)
963                 free(argv[i]);
964         free(argv);
965 }
966
967 static int create_snapshot(char **argv)
968 {
969         int ret, fds[3] = {0, 0, 0};
970         char *name;
971
972         name = incomplete_name(current_snapshot_creation_time);
973         DSS_NOTICE_LOG("creating new snapshot %s\n", name);
974         free(name);
975         ret = dss_exec(&create_pid, argv[0], argv, fds);
976         if (ret < 0)
977                 return ret;
978         snapshot_creation_status = HS_RUNNING;
979         return ret;
980 }
981
982 static int select_loop(void)
983 {
984         int ret;
985         /* check every 60 seconds for free disk space */
986         struct timeval tv;
987         char **rsync_argv = NULL;
988
989         for (;;) {
990                 fd_set rfds;
991                 int low_disk_space;
992                 struct timeval *tvp;
993
994                 if (remove_pid)
995                         tvp = NULL; /* sleep until rm hook/process dies */
996                 else { /* sleep one minute */
997                         tv.tv_sec = 60;
998                         tv.tv_usec = 0;
999                         tvp = &tv;
1000                 }
1001                 FD_ZERO(&rfds);
1002                 FD_SET(signal_pipe, &rfds);
1003                 DSS_DEBUG_LOG("tvp: %p, tv_sec : %lu\n", tvp, (long unsigned) tv.tv_sec);
1004                 ret = dss_select(signal_pipe + 1, &rfds, NULL, tvp);
1005                 if (ret < 0)
1006                         goto out;
1007                 if (FD_ISSET(signal_pipe, &rfds)) {
1008                         ret = handle_signal();
1009                         if (ret < 0)
1010                                 goto out;
1011                 }
1012                 if (remove_pid)
1013                         continue;
1014                 if (snapshot_removal_status == HS_PRE_SUCCESS) {
1015                         ret = exec_rm();
1016                         if (ret < 0)
1017                                 goto out;
1018                         continue;
1019                 }
1020                 if (snapshot_removal_status == HS_SUCCESS) {
1021                         ret = post_remove_hook();
1022                         if (ret < 0)
1023                                 goto out;
1024                         continue;
1025                 }
1026                 ret = disk_space_low();
1027                 if (ret < 0)
1028                         goto out;
1029                 low_disk_space = ret;
1030                 ret = try_to_free_disk_space(low_disk_space);
1031                 if (ret < 0)
1032                         goto out;
1033                 if (snapshot_removal_status != HS_READY) {
1034                         stop_create_process();
1035                         continue;
1036                 }
1037                 restart_create_process();
1038                 switch (snapshot_creation_status) {
1039                 case HS_READY:
1040                         if (!next_snapshot_is_due())
1041                                 continue;
1042                         ret = pre_create_hook();
1043                         if (ret < 0)
1044                                 goto out;
1045                         continue;
1046                 case HS_PRE_RUNNING:
1047                 case HS_RUNNING:
1048                 case HS_POST_RUNNING:
1049                         continue;
1050                 case HS_PRE_SUCCESS:
1051                         free_rsync_argv(rsync_argv);
1052                         create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
1053                         /* fall through */
1054                 case HS_NEEDS_RESTART:
1055                         ret = create_snapshot(rsync_argv);
1056                         if (ret < 0)
1057                                 goto out;
1058                         continue;
1059                 case HS_SUCCESS:
1060                         ret = post_create_hook();
1061                         if (ret < 0)
1062                                 goto out;
1063                         continue;
1064                 }
1065         }
1066 out:
1067         return ret;
1068 }
1069
1070 static void exit_hook(int exit_code)
1071 {
1072         int fds[3] = {0, 0, 0};
1073         char *argv[] = {conf.exit_hook_arg, dss_strerror(-exit_code), NULL};
1074         pid_t pid;
1075
1076         if (!conf.exit_hook_given)
1077                 return;
1078         DSS_NOTICE_LOG("executing %s %s\n", argv[0], argv[1]);
1079         dss_exec(&pid, conf.exit_hook_arg, argv, fds);
1080 }
1081
1082 static int com_run(void)
1083 {
1084         int ret;
1085
1086         if (conf.dry_run_given) {
1087                 DSS_ERROR_LOG("dry_run not supported by this command\n");
1088                 return -E_SYNTAX;
1089         }
1090         ret = install_sighandler(SIGHUP);
1091         if (ret < 0)
1092                 return ret;
1093         ret = select_loop();
1094         if (ret >= 0) /* impossible */
1095                 ret = -E_BUG;
1096         exit_hook(ret);
1097         return ret;
1098 }
1099
1100 static int com_prune(void)
1101 {
1102         int ret;
1103         struct snapshot_list sl;
1104         struct snapshot *victim;
1105         struct disk_space ds;
1106         const char *why;
1107
1108         ret = get_disk_space(".", &ds);
1109         if (ret < 0)
1110                 return ret;
1111         log_disk_space(&ds);
1112         dss_get_snapshot_list(&sl);
1113         why = "outdated";
1114         victim = find_outdated_snapshot(&sl);
1115         if (victim)
1116                 goto rm;
1117         why = "redundant";
1118         victim = find_redundant_snapshot(&sl);
1119         if (victim)
1120                 goto rm;
1121         ret = 0;
1122         goto out;
1123 rm:
1124         if (conf.dry_run_given) {
1125                 dss_msg("%s snapshot %s (interval = %i)\n",
1126                         why, victim->name, victim->interval);
1127                 ret = 0;
1128                 goto out;
1129         }
1130         ret = pre_remove_hook(victim, why);
1131         if (ret < 0)
1132                 goto out;
1133         if (snapshot_removal_status == HS_PRE_RUNNING) {
1134                 ret = wait_for_remove_process();
1135                 if (ret < 0)
1136                         goto out;
1137                 if (snapshot_removal_status != HS_PRE_SUCCESS)
1138                         goto out;
1139         }
1140         ret = exec_rm();
1141         if (ret < 0)
1142                 goto out;
1143         ret = wait_for_remove_process();
1144         if (ret < 0)
1145                 goto out;
1146         if (snapshot_removal_status != HS_SUCCESS)
1147                 goto out;
1148         ret = post_remove_hook();
1149         if (ret < 0)
1150                 goto out;
1151         if (snapshot_removal_status != HS_POST_RUNNING)
1152                 goto out;
1153         ret = wait_for_remove_process();
1154         if (ret < 0)
1155                 goto out;
1156         ret = 1;
1157 out:
1158         free_snapshot_list(&sl);
1159         return ret;
1160 }
1161
1162 static int com_create(void)
1163 {
1164         int ret, status;
1165         char **rsync_argv;
1166
1167         if (conf.dry_run_given) {
1168                 int i;
1169                 char *msg = NULL;
1170                 create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
1171                 for (i = 0; rsync_argv[i]; i++) {
1172                         char *tmp = msg;
1173                         msg = make_message("%s%s%s", tmp? tmp : "",
1174                                 tmp? " " : "", rsync_argv[i]);
1175                         free(tmp);
1176                 }
1177                 free_rsync_argv(rsync_argv);
1178                 dss_msg("%s\n", msg);
1179                 free(msg);
1180                 return 1;
1181         }
1182         ret = pre_create_hook();
1183         if (ret < 0)
1184                 return ret;
1185         if (create_pid) {
1186                 ret = wait_for_process(create_pid, &status);
1187                 if (ret < 0)
1188                         return ret;
1189                 ret = handle_pre_create_hook_exit(status);
1190                 if (ret <= 0) /* error, or pre-create failed */
1191                         return ret;
1192         }
1193         create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
1194         ret = create_snapshot(rsync_argv);
1195         if (ret < 0)
1196                 goto out;
1197         ret = wait_for_process(create_pid, &status);
1198         if (ret < 0)
1199                 goto out;
1200         ret = handle_rsync_exit(status);
1201         if (ret < 0)
1202                 goto out;
1203         post_create_hook();
1204         if (create_pid)
1205                 ret = wait_for_process(create_pid, &status);
1206 out:
1207         free_rsync_argv(rsync_argv);
1208         return ret;
1209 }
1210
1211 static int com_ls(void)
1212 {
1213         int i;
1214         struct snapshot_list sl;
1215         struct snapshot *s;
1216
1217         dss_get_snapshot_list(&sl);
1218         FOR_EACH_SNAPSHOT(s, i, &sl) {
1219                 int64_t d = 0;
1220                 if (s->flags & SS_COMPLETE)
1221                         d = (s->completion_time - s->creation_time) / 60;
1222                 dss_msg("%u\t%s\t%3" PRId64 ":%02" PRId64 "\n", s->interval, s->name, d/60, d%60);
1223         };
1224         free_snapshot_list(&sl);
1225         return 1;
1226 }
1227
1228 static int setup_signal_handling(void)
1229 {
1230         int ret;
1231
1232         DSS_INFO_LOG("setting up signal handlers\n");
1233         signal_pipe = signal_init(); /* always successful */
1234         ret = install_sighandler(SIGINT);
1235         if (ret < 0)
1236                 return ret;
1237         ret = install_sighandler(SIGTERM);
1238         if (ret < 0)
1239                 return ret;
1240         return install_sighandler(SIGCHLD);
1241 }
1242
1243 /**
1244  * The main function of dss.
1245  *
1246  * \param argc Usual argument count.
1247  * \param argv Usual argument vector.
1248  */
1249 int main(int argc, char **argv)
1250 {
1251         int ret;
1252         struct cmdline_parser_params params = {
1253                 .override = 0,
1254                 .initialize = 1,
1255                 .check_required = 0,
1256                 .check_ambiguity = 0,
1257                 .print_errors = 1
1258         };
1259
1260         cmdline_parser_ext(argc, argv, &conf, &params); /* aborts on errors */
1261         ret = parse_config_file(0);
1262         if (ret < 0)
1263                 goto out;
1264         if (conf.daemon_given)
1265                 daemon_init();
1266         ret = change_to_dest_dir();
1267         if (ret < 0)
1268                 goto out;
1269         ret = setup_signal_handling();
1270         if (ret < 0)
1271                 goto out;
1272         ret = call_command_handler();
1273 out:
1274         if (ret < 0)
1275                 DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
1276         exit(ret >= 0? EXIT_SUCCESS : EXIT_FAILURE);
1277 }