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