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