2 * Copyright (C) 2008 Andre Noll <maan@systemlinux.org>
4 * Licensed under the GPL v2. For licencing details see COPYING.
11 #include <sys/types.h>
24 #include "gcc-compat.h"
37 /** Command line and config file options. */
38 static struct gengetopt_args_info conf;
39 /** Non-NULL if we log to a file. */
41 /** The read end of the signal pipe */
42 static int signal_pipe;
43 /** Process id of current rsync process. */
44 static pid_t rsync_pid;
45 /** Whether the rsync process is currently stopped */
46 static int rsync_stopped;
47 /** Process id of current rm process. */
49 /** When the next snapshot is due. */
50 static struct timeval next_snapshot_time;
51 /** The pid of the pre-create hook. */
52 static pid_t pre_create_hook_pid;
53 /** The pid of the post-create hook. */
54 static pid_t post_create_hook_pid;
55 /** Creation time of the snapshot currently being created. */
56 static int64_t current_snapshot_creation_time;
57 /** Needed by the post-create hook. */
58 static char *path_to_last_complete_snapshot;
59 /** \sa \ref snap.h for details. */
60 static unsigned snapshot_creation_status;
66 /* a litte cpp magic helps to DRY */
72 #define COMMAND(x) static int com_ ##x(void);
75 #define COMMAND(x) if (conf.x ##_given) return com_ ##x();
76 static int call_command_handler(void)
79 DSS_EMERG_LOG("BUG: did not find command handler\n");
86 * The log function of dss.
89 * \param fml Usual format string.
91 * All DSS_XXX_LOG() macros use this function.
93 __printf_2_3 void dss_log(int ll, const char* fmt,...)
101 if (ll < conf.loglevel_arg)
103 outfd = logfile? logfile : stderr;
106 strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
107 fprintf(outfd, "%s ", str);
108 if (conf.loglevel_arg <= INFO)
109 fprintf(outfd, "%i: ", ll);
111 vfprintf(outfd, fmt, argp);
116 * Print a message either to stdout or to the log file.
118 static __printf_1_2 void dss_msg(const char* fmt,...)
120 FILE *outfd = conf.daemon_given? logfile : stdout;
123 vfprintf(outfd, fmt, argp);
127 static int disk_space_low(void)
129 struct disk_space ds;
130 int ret = get_disk_space(".", &ds);
134 if (conf.min_free_mb_arg)
135 if (ds.free_mb < conf.min_free_mb_arg)
137 if (conf.min_free_percent_arg)
138 if (ds.percent_free < conf.min_free_percent_arg)
140 if (conf.min_free_percent_inodes_arg)
141 if (ds.percent_free_inodes < conf.min_free_percent_inodes_arg)
146 static void dss_get_snapshot_list(struct snapshot_list *sl)
148 get_snapshot_list(sl, conf.unit_interval_arg, conf.num_intervals_arg);
151 static void compute_next_snapshot_time(void)
153 struct timeval now, unit_interval = {.tv_sec = 24 * 3600 * conf.unit_interval_arg},
156 unsigned wanted = desired_number_of_snapshots(0, conf.num_intervals_arg),
157 num_complete_snapshots = 0;
159 struct snapshot *s = NULL;
160 struct snapshot_list sl;
162 assert(snapshot_creation_status == SCS_READY);
163 current_snapshot_creation_time = 0;
164 dss_get_snapshot_list(&sl);
165 FOR_EACH_SNAPSHOT(s, i, &sl) {
166 if (!(s->flags & SS_COMPLETE))
168 num_complete_snapshots++;
169 x += s->completion_time - s->creation_time;
172 if (num_complete_snapshots)
173 x /= num_complete_snapshots; /* avg time to create one snapshot */
174 x *= wanted; /* time to create all snapshots in interval 0 */
177 ret = tv_diff(&unit_interval, &tmp, &diff); /* total sleep time per unit interval */
178 if (ret < 0 || !s) /* unit_interval < tmp or no snapshot */
180 tv_divide(wanted, &diff, &tmp); /* sleep time betweeen two snapshots */
181 diff.tv_sec = s->completion_time; /* completion time of the the latest snaphot */
183 tv_add(&diff, &tmp, &next_snapshot_time);
184 gettimeofday(&now, NULL);
185 if (tv_diff(&now, &next_snapshot_time, NULL) < 0)
188 next_snapshot_time = now;
189 next_snapshot_time.tv_sec += 60;
191 free_snapshot_list(&sl);
195 static int remove_snapshot(struct snapshot *s)
197 int fds[3] = {0, 0, 0};
199 char *new_name = being_deleted_name(s);
200 int ret = dss_rename(s->name, new_name);
201 char *argv[] = {"rm", "-rf", new_name, NULL};
205 DSS_NOTICE_LOG("removing %s (interval = %i)\n", s->name, s->interval);
206 ret = dss_exec(&rm_pid, argv[0], argv, fds);
212 static int snapshot_is_being_created(struct snapshot *s)
214 return s->creation_time == current_snapshot_creation_time;
218 * return: 0: no redundant snapshots, 1: rm process started, negative: error
220 static int remove_redundant_snapshot(struct snapshot_list *sl)
222 int ret, i, interval;
224 unsigned missing = 0;
226 DSS_DEBUG_LOG("looking for intervals containing too many snapshots\n");
227 for (interval = conf.num_intervals_arg - 1; interval >= 0; interval--) {
228 unsigned keep = desired_number_of_snapshots(interval, conf.num_intervals_arg);
229 unsigned num = sl->interval_count[interval];
230 struct snapshot *victim = NULL, *prev = NULL;
231 int64_t score = LONG_MAX;
234 missing += keep - num;
235 // DSS_DEBUG_LOG("interval %i: keep: %u, have: %u, missing: %u\n",
236 // interval, keep, num, missing);
237 if (keep + missing >= num)
239 /* redundant snapshot in this interval, pick snapshot with lowest score */
240 FOR_EACH_SNAPSHOT(s, i, sl) {
243 if (snapshot_is_being_created(s))
245 //DSS_DEBUG_LOG("checking %s\n", s->name);
246 if (s->interval > interval) {
250 if (s->interval < interval)
258 /* check if s is a better victim */
259 this_score = s->creation_time - prev->creation_time;
260 assert(this_score >= 0);
261 //DSS_DEBUG_LOG("%s: score %lli\n", s->name, (long long)score);
262 if (this_score < score) {
269 if (conf.dry_run_given) {
270 dss_msg("%s would be removed (interval = %i)\n",
271 victim->name, victim->interval);
274 ret = remove_snapshot(victim);
275 return ret < 0? ret : 1;
280 static int remove_outdated_snapshot(struct snapshot_list *sl)
285 DSS_DEBUG_LOG("looking for snapshots belonging to intervals greater than %d\n",
286 conf.num_intervals_arg);
287 FOR_EACH_SNAPSHOT(s, i, sl) {
288 if (snapshot_is_being_created(s))
290 if (s->interval <= conf.num_intervals_arg)
292 if (conf.dry_run_given) {
293 dss_msg("%s would be removed (interval = %i)\n",
294 s->name, s->interval);
297 ret = remove_snapshot(s);
305 static int remove_oldest_snapshot(struct snapshot_list *sl)
307 struct snapshot *s = get_oldest_snapshot(sl);
309 if (!s) /* no snapshot found */
311 DSS_INFO_LOG("oldest snapshot: %s\n", s->name);
312 if (snapshot_is_being_created(s))
314 return remove_snapshot(s);
317 static int rename_incomplete_snapshot(int64_t start)
322 free(path_to_last_complete_snapshot);
323 ret = complete_name(start, get_current_time(),
324 &path_to_last_complete_snapshot);
327 old_name = incomplete_name(start);
328 ret = dss_rename(old_name, path_to_last_complete_snapshot);
330 DSS_NOTICE_LOG("%s -> %s\n", old_name,
331 path_to_last_complete_snapshot);
336 static int try_to_free_disk_space(int low_disk_space)
339 struct snapshot_list sl;
341 if (!low_disk_space && conf.keep_redundant_given)
343 dss_get_snapshot_list(&sl);
344 ret = remove_outdated_snapshot(&sl);
345 if (ret) /* error, or we are removing something */
347 /* no outdated snapshot */
348 ret = remove_redundant_snapshot(&sl);
354 DSS_WARNING_LOG("disk space low and nothing obvious to remove\n");
355 ret = remove_oldest_snapshot(&sl);
358 DSS_CRIT_LOG("uhuhu: not enough disk space for a single snapshot\n");
359 ret = -ERRNO_TO_DSS_ERROR(ENOSPC);
361 free_snapshot_list(&sl);
365 static int pre_create_hook(void)
367 int ret, fds[3] = {0, 0, 0};
369 if (!conf.pre_create_hook_given) {
370 snapshot_creation_status = SCS_PRE_HOOK_SUCCESS;
373 DSS_NOTICE_LOG("executing %s\n", conf.pre_create_hook_arg);
374 ret = dss_exec_cmdline_pid(&pre_create_hook_pid,
375 conf.pre_create_hook_arg, fds);
378 snapshot_creation_status = SCS_PRE_HOOK_RUNNING;
382 static int post_create_hook(void)
384 int ret, fds[3] = {0, 0, 0};
387 if (!conf.post_create_hook_given) {
388 snapshot_creation_status = SCS_READY;
389 compute_next_snapshot_time();
392 cmd = make_message("%s %s/%s", conf.post_create_hook_arg,
393 conf.dest_dir_arg, path_to_last_complete_snapshot);
394 DSS_NOTICE_LOG("executing %s\n", cmd);
395 ret = dss_exec_cmdline_pid(&post_create_hook_pid, cmd, fds);
399 snapshot_creation_status = SCS_POST_HOOK_RUNNING;
403 static void kill_process(pid_t pid)
407 DSS_WARNING_LOG("sending SIGTERM to pid %d\n", (int)pid);
411 static void stop_rsync_process(void)
413 if (!rsync_pid || rsync_stopped)
415 kill(SIGSTOP, rsync_pid);
419 static void restart_rsync_process(void)
421 if (!rsync_pid || !rsync_stopped)
423 kill (SIGCONT, rsync_pid);
429 * Print a log message about the exit status of a child.
431 static void log_termination_msg(pid_t pid, int status)
433 if (WIFEXITED(status))
434 DSS_INFO_LOG("child %i exited. Exit status: %i\n", (int)pid,
435 WEXITSTATUS(status));
436 else if (WIFSIGNALED(status))
437 DSS_NOTICE_LOG("child %i was killed by signal %i\n", (int)pid,
440 DSS_WARNING_LOG("child %i terminated abormally\n", (int)pid);
443 static int wait_for_process(pid_t pid, int *status)
447 DSS_DEBUG_LOG("Waiting for process %d to terminate\n", (int)pid);
452 FD_SET(signal_pipe, &rfds);
453 ret = dss_select(signal_pipe + 1, &rfds, NULL, NULL);
459 if (ret == SIGCHLD) {
460 ret = waitpid(pid, status, 0);
463 if (errno != EINTR) { /* error */
464 ret = -ERRNO_TO_DSS_ERROR(errno);
468 /* SIGINT or SIGTERM */
469 DSS_WARNING_LOG("sending SIGTERM to pid %d\n", (int)pid);
473 DSS_ERROR_LOG("failed to wait for process %d\n", (int)pid);
475 log_termination_msg(pid, *status);
479 static int handle_rm_exit(int status)
482 if (!WIFEXITED(status))
483 return -E_INVOLUNTARY_EXIT;
484 if (WEXITSTATUS(status))
485 return -E_BAD_EXIT_CODE;
489 static int wait_for_rm_process(void)
491 int status, ret = wait_for_process(rm_pid, &status);
495 return handle_rm_exit(status);
498 static int handle_rsync_exit(int status)
502 if (!WIFEXITED(status)) {
503 DSS_ERROR_LOG("rsync process %d died involuntary\n", (int)rsync_pid);
504 ret = -E_INVOLUNTARY_EXIT;
505 snapshot_creation_status = SCS_READY;
506 compute_next_snapshot_time();
509 es = WEXITSTATUS(status);
510 if (es == 13) { /* Errors with program diagnostics */
511 DSS_WARNING_LOG("rsync process %d returned %d -- restarting\n",
513 snapshot_creation_status = SCS_RSYNC_NEEDS_RESTART;
514 gettimeofday(&next_snapshot_time, NULL);
515 next_snapshot_time.tv_sec += 60;
519 if (es != 0 && es != 23 && es != 24) {
520 DSS_ERROR_LOG("rsync process %d returned %d\n", (int)rsync_pid, es);
521 ret = -E_BAD_EXIT_CODE;
522 snapshot_creation_status = SCS_READY;
523 compute_next_snapshot_time();
526 ret = rename_incomplete_snapshot(current_snapshot_creation_time);
529 snapshot_creation_status = SCS_RSYNC_SUCCESS;
536 static int handle_pre_create_hook_exit(int status)
540 if (!WIFEXITED(status)) {
541 snapshot_creation_status = SCS_READY;
542 compute_next_snapshot_time();
543 ret = -E_INVOLUNTARY_EXIT;
546 es = WEXITSTATUS(status);
548 snapshot_creation_status = SCS_READY;
549 compute_next_snapshot_time();
550 ret = -E_BAD_EXIT_CODE;
553 snapshot_creation_status = SCS_PRE_HOOK_SUCCESS;
556 pre_create_hook_pid = 0;
560 static int handle_sigchld(void)
563 int status, ret = reap_child(&pid, &status);
567 if (pid == rsync_pid)
568 return handle_rsync_exit(status);
570 return handle_rm_exit(status);
571 if (pid == pre_create_hook_pid)
572 return handle_pre_create_hook_exit(status);
573 if (pid == post_create_hook_pid) {
574 snapshot_creation_status = SCS_READY;
575 compute_next_snapshot_time();
578 DSS_EMERG_LOG("BUG: unknown process %d died\n", (int)pid);
582 static int check_config(void)
584 if (conf.unit_interval_arg <= 0) {
585 DSS_ERROR_LOG("bad unit interval: %i\n", conf.unit_interval_arg);
586 return -E_INVALID_NUMBER;
588 DSS_DEBUG_LOG("unit interval: %i day(s)\n", conf.unit_interval_arg);
589 if (conf.num_intervals_arg <= 0) {
590 DSS_ERROR_LOG("bad number of intervals %i\n", conf.num_intervals_arg);
591 return -E_INVALID_NUMBER;
593 DSS_DEBUG_LOG("number of intervals: %i\n", conf.num_intervals_arg);
597 static int parse_config_file(int override)
602 char *old_logfile_arg = NULL;
603 int old_daemon_given = 0;
605 if (conf.config_file_given)
606 config_file = dss_strdup(conf.config_file_arg);
608 char *home = get_homedir();
609 config_file = make_message("%s/.dssrc", home);
612 if (override) { /* SIGHUP */
613 if (conf.logfile_given)
614 old_logfile_arg = dss_strdup(conf.logfile_arg);
615 old_daemon_given = conf.daemon_given;
618 ret = stat(config_file, &statbuf);
619 if (ret && conf.config_file_given) {
620 ret = -ERRNO_TO_DSS_ERROR(errno);
621 DSS_ERROR_LOG("failed to stat config file %s\n", config_file);
625 struct cmdline_parser_params params = {
626 .override = override,
629 .check_ambiguity = 0,
632 if (override) { /* invalidate all rsync options */
635 for (i = 0; i < conf.rsync_option_given; i++) {
636 free(conf.rsync_option_arg[i]);
637 conf.rsync_option_arg[i] = NULL;
639 conf.rsync_option_given = 0;
641 cmdline_parser_config_file(config_file, &conf, ¶ms);
643 ret = check_config();
647 /* don't change daemon mode on SIGHUP */
648 conf.daemon_given = old_daemon_given;
651 if (conf.logfile_given)
652 free(old_logfile_arg);
653 else if (conf.daemon_given) { /* re-use old logfile */
654 conf.logfile_arg = old_logfile_arg;
655 conf.logfile_given = 1;
658 if (conf.logfile_given) {
659 logfile = open_log(conf.logfile_arg);
660 log_welcome(conf.loglevel_arg);
662 DSS_DEBUG_LOG("loglevel: %d\n", conf.loglevel_arg);
663 // cmdline_parser_dump(logfile? logfile : stdout, &conf);
667 DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
671 static int change_to_dest_dir(void)
673 DSS_INFO_LOG("changing cwd to %s\n", conf.dest_dir_arg);
674 return dss_chdir(conf.dest_dir_arg);
677 static int handle_sighup(void)
681 DSS_NOTICE_LOG("SIGHUP\n");
682 ret = parse_config_file(1);
685 return change_to_dest_dir();
688 static int handle_signal(void)
690 int sig, ret = next_signal();
698 restart_rsync_process();
699 kill_process(rsync_pid);
700 kill_process(rm_pid);
704 ret = handle_sighup();
707 ret = handle_sigchld();
712 DSS_ERROR_LOG("%s\n", dss_strerror(-ret));
717 * We can not use rsync locally if the local user is different from the remote
718 * user or if the src dir is not on the local host (or both).
720 static int use_rsync_locally(char *logname)
722 char *h = conf.remote_host_arg;
724 if (strcmp(h, "localhost") && strcmp(h, "127.0.0.1"))
726 if (conf.remote_user_given && strcmp(conf.remote_user_arg, logname))
731 static void create_rsync_argv(char ***argv, int64_t *num)
733 char *logname, *newest;
735 struct snapshot_list sl;
737 dss_get_snapshot_list(&sl);
738 newest = name_of_newest_complete_snapshot(&sl);
739 free_snapshot_list(&sl);
741 *argv = dss_malloc((15 + conf.rsync_option_given) * sizeof(char *));
742 (*argv)[i++] = dss_strdup("rsync");
743 (*argv)[i++] = dss_strdup("-aq");
744 (*argv)[i++] = dss_strdup("--delete");
745 for (j = 0; j < conf.rsync_option_given; j++)
746 (*argv)[i++] = dss_strdup(conf.rsync_option_arg[j]);
748 DSS_INFO_LOG("using %s as reference snapshot\n", newest);
749 (*argv)[i++] = make_message("--link-dest=../%s", newest);
752 DSS_INFO_LOG("no previous snapshot found\n");
753 logname = dss_logname();
754 if (use_rsync_locally(logname))
755 (*argv)[i++] = dss_strdup(conf.source_dir_arg);
757 (*argv)[i++] = make_message("%s@%s:%s/", conf.remote_user_given?
758 conf.remote_user_arg : logname,
759 conf.remote_host_arg, conf.source_dir_arg);
761 *num = get_current_time();
762 (*argv)[i++] = incomplete_name(*num);
764 for (j = 0; j < i; j++)
765 DSS_DEBUG_LOG("argv[%d] = %s\n", j, (*argv)[j]);
768 static void free_rsync_argv(char **argv)
774 for (i = 0; argv[i]; i++)
779 static int create_snapshot(char **argv)
781 int ret, fds[3] = {0, 0, 0};
784 name = incomplete_name(current_snapshot_creation_time);
785 DSS_NOTICE_LOG("creating new snapshot %s\n", name);
787 ret = dss_exec(&rsync_pid, argv[0], argv, fds);
790 snapshot_creation_status = SCS_RSYNC_RUNNING;
794 static int select_loop(void)
797 /* check every 60 seconds for free disk space */
799 char **rsync_argv = NULL;
804 struct timeval now, *tvp;
807 tvp = NULL; /* sleep until rm process dies */
808 else { /* sleep one minute */
814 FD_SET(signal_pipe, &rfds);
815 DSS_DEBUG_LOG("tvp: %p, tv_sec : %lu\n", tvp, (long unsigned) tv.tv_sec);
816 ret = dss_select(signal_pipe + 1, &rfds, NULL, tvp);
819 if (FD_ISSET(signal_pipe, &rfds)) {
820 ret = handle_signal();
826 ret = disk_space_low();
829 low_disk_space = ret;
830 ret = try_to_free_disk_space(low_disk_space);
834 stop_rsync_process();
837 restart_rsync_process();
838 gettimeofday(&now, NULL);
839 if (tv_diff(&next_snapshot_time, &now, NULL) > 0)
841 switch (snapshot_creation_status) {
843 ret = pre_create_hook();
847 case SCS_PRE_HOOK_RUNNING:
849 case SCS_RSYNC_NEEDS_RESTART:
850 ret = create_snapshot(rsync_argv);
854 case SCS_PRE_HOOK_SUCCESS:
855 free_rsync_argv(rsync_argv);
856 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
857 ret = create_snapshot(rsync_argv);
861 case SCS_RSYNC_RUNNING:
863 case SCS_RSYNC_SUCCESS:
864 ret = post_create_hook();
868 case SCS_POST_HOOK_RUNNING:
876 static void exit_hook(int exit_code)
878 int fds[3] = {0, 0, 0};
879 char *argv[] = {conf.exit_hook_arg, dss_strerror(-exit_code), NULL};
882 if (!conf.exit_hook_given)
884 DSS_NOTICE_LOG("executing %s %s\n", argv[0], argv[1]);
885 dss_exec(&pid, conf.exit_hook_arg, argv, fds);
888 static int com_run(void)
892 if (conf.dry_run_given) {
893 DSS_ERROR_LOG("dry_run not supported by this command\n");
896 ret = install_sighandler(SIGHUP);
899 compute_next_snapshot_time();
901 if (ret >= 0) /* impossible */
907 static int com_prune(void)
910 struct snapshot_list sl;
911 struct disk_space ds;
913 ret = get_disk_space(".", &ds);
918 dss_get_snapshot_list(&sl);
919 ret = remove_outdated_snapshot(&sl);
920 free_snapshot_list(&sl);
925 ret = wait_for_rm_process();
930 dss_get_snapshot_list(&sl);
931 ret = remove_redundant_snapshot(&sl);
932 free_snapshot_list(&sl);
937 ret = wait_for_rm_process();
946 static int com_create(void)
951 if (conf.dry_run_given) {
954 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
955 for (i = 0; rsync_argv[i]; i++) {
957 msg = make_message("%s%s%s", tmp? tmp : "",
958 tmp? " " : "", rsync_argv[i]);
961 free_rsync_argv(rsync_argv);
962 dss_msg("%s\n", msg);
966 ret = pre_create_hook();
969 if (pre_create_hook_pid) {
970 ret = wait_for_process(pre_create_hook_pid, &status);
973 ret = handle_pre_create_hook_exit(status);
977 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
978 ret = create_snapshot(rsync_argv);
981 ret = wait_for_process(rsync_pid, &status);
984 ret = handle_rsync_exit(status);
988 if (post_create_hook_pid)
989 ret = wait_for_process(post_create_hook_pid, &status);
991 free_rsync_argv(rsync_argv);
995 static int com_ls(void)
998 struct snapshot_list sl;
1001 dss_get_snapshot_list(&sl);
1002 FOR_EACH_SNAPSHOT(s, i, &sl) {
1004 if (s->flags & SS_COMPLETE)
1005 d = (s->completion_time - s->creation_time) / 60;
1006 dss_msg("%u\t%s\t%3" PRId64 ":%02" PRId64 "\n", s->interval, s->name, d/60, d%60);
1008 free_snapshot_list(&sl);
1012 static int setup_signal_handling(void)
1016 DSS_INFO_LOG("setting up signal handlers\n");
1017 signal_pipe = signal_init(); /* always successful */
1018 ret = install_sighandler(SIGINT);
1021 ret = install_sighandler(SIGTERM);
1024 return install_sighandler(SIGCHLD);
1028 * The main function of dss.
1030 * \param argc Usual argument count.
1031 * \param argv Usual argument vector.
1033 int main(int argc, char **argv)
1036 struct cmdline_parser_params params = {
1039 .check_required = 0,
1040 .check_ambiguity = 0,
1044 cmdline_parser_ext(argc, argv, &conf, ¶ms); /* aborts on errors */
1045 ret = parse_config_file(0);
1048 if (conf.daemon_given)
1050 ret = change_to_dest_dir();
1053 ret = setup_signal_handling();
1056 ret = call_command_handler();
1059 DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
1060 exit(ret >= 0? EXIT_SUCCESS : EXIT_FAILURE);