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 /* TODO: Also consider number of inodes. */
128 static int disk_space_low(void)
130 struct disk_space ds;
131 int ret = get_disk_space(".", &ds);
135 if (conf.min_free_mb_arg)
136 if (ds.free_mb < conf.min_free_mb_arg)
138 if (conf.min_free_percent_arg)
139 if (ds.percent_free < conf.min_free_percent_arg)
141 if (conf.min_free_percent_inodes_arg)
142 if (ds.percent_free_inodes < conf.min_free_percent_inodes_arg)
147 static void dss_get_snapshot_list(struct snapshot_list *sl)
149 get_snapshot_list(sl, conf.unit_interval_arg, conf.num_intervals_arg);
152 static void compute_next_snapshot_time(void)
154 struct timeval now, unit_interval = {.tv_sec = 24 * 3600 * conf.unit_interval_arg},
157 unsigned wanted = desired_number_of_snapshots(0, conf.num_intervals_arg),
158 num_complete_snapshots = 0;
160 struct snapshot *s = NULL;
161 struct snapshot_list sl;
163 assert(snapshot_creation_status == SCS_READY);
164 current_snapshot_creation_time = 0;
165 dss_get_snapshot_list(&sl);
166 FOR_EACH_SNAPSHOT(s, i, &sl) {
167 if (!(s->flags & SS_COMPLETE))
169 num_complete_snapshots++;
170 x += s->completion_time - s->creation_time;
173 if (num_complete_snapshots)
174 x /= num_complete_snapshots; /* avg time to create one snapshot */
175 x *= wanted; /* time to create all snapshots in interval 0 */
178 ret = tv_diff(&unit_interval, &tmp, &diff); /* total sleep time per unit interval */
179 gettimeofday(&now, NULL);
182 tv_divide(wanted, &diff, &tmp); /* sleep time betweeen two snapshots */
183 diff.tv_sec = s->completion_time;
185 tv_add(&diff, &tmp, &next_snapshot_time);
186 if (tv_diff(&now, &next_snapshot_time, NULL) < 0)
189 next_snapshot_time = now;
190 next_snapshot_time.tv_sec += 60;
192 free_snapshot_list(&sl);
196 static int remove_snapshot(struct snapshot *s)
198 int fds[3] = {0, 0, 0};
200 char *new_name = being_deleted_name(s);
201 int ret = dss_rename(s->name, new_name);
202 char *argv[] = {"rm", "-rf", new_name, NULL};
206 DSS_NOTICE_LOG("removing %s (interval = %i)\n", s->name, s->interval);
207 ret = dss_exec(&rm_pid, argv[0], argv, fds);
214 * return: 0: no redundant snapshots, 1: rm process started, negative: error
216 static int remove_redundant_snapshot(struct snapshot_list *sl)
218 int ret, i, interval;
220 unsigned missing = 0;
222 DSS_DEBUG_LOG("looking for intervals containing too many snapshots\n");
223 for (interval = conf.num_intervals_arg - 1; interval >= 0; interval--) {
224 unsigned keep = desired_number_of_snapshots(interval, conf.num_intervals_arg);
225 unsigned num = sl->interval_count[interval];
226 struct snapshot *victim = NULL, *prev = NULL;
227 int64_t score = LONG_MAX;
230 missing += keep - num;
231 // DSS_DEBUG_LOG("interval %i: keep: %u, have: %u, missing: %u\n",
232 // interval, keep, num, missing);
233 if (keep + missing >= num)
235 /* redundant snapshot in this interval, pick snapshot with lowest score */
236 FOR_EACH_SNAPSHOT(s, i, sl) {
239 //DSS_DEBUG_LOG("checking %s\n", s->name);
240 if (s->interval > interval) {
244 if (s->interval < interval)
252 /* check if s is a better victim */
253 this_score = s->creation_time - prev->creation_time;
254 assert(this_score >= 0);
255 //DSS_DEBUG_LOG("%s: score %lli\n", s->name, (long long)score);
256 if (this_score < score) {
263 if (conf.dry_run_given) {
264 dss_msg("%s would be removed (interval = %i)\n",
265 victim->name, victim->interval);
268 ret = remove_snapshot(victim);
269 return ret < 0? ret : 1;
274 static int remove_outdated_snapshot(struct snapshot_list *sl)
279 DSS_DEBUG_LOG("looking for snapshots belonging to intervals greater than %d\n",
280 conf.num_intervals_arg);
281 FOR_EACH_SNAPSHOT(s, i, sl) {
282 if (s->interval <= conf.num_intervals_arg)
284 if (conf.dry_run_given) {
285 dss_msg("%s would be removed (interval = %i)\n",
286 s->name, s->interval);
289 ret = remove_snapshot(s);
297 static int remove_oldest_snapshot(struct snapshot_list *sl)
299 struct snapshot *s = get_oldest_snapshot(sl);
301 if (!s) /* no snapshot found */
303 DSS_INFO_LOG("oldest snapshot: %s\n", s->name);
304 if (s->creation_time == current_snapshot_creation_time)
305 return 0; /* do not remove the snapshot currently being created */
306 return remove_snapshot(s);
309 static int rename_incomplete_snapshot(int64_t start)
314 free(path_to_last_complete_snapshot);
315 ret = complete_name(start, get_current_time(),
316 &path_to_last_complete_snapshot);
319 old_name = incomplete_name(start);
320 ret = dss_rename(old_name, path_to_last_complete_snapshot);
322 DSS_NOTICE_LOG("%s -> %s\n", old_name,
323 path_to_last_complete_snapshot);
328 static int try_to_free_disk_space(int low_disk_space)
331 struct snapshot_list sl;
333 dss_get_snapshot_list(&sl);
334 ret = remove_outdated_snapshot(&sl);
335 if (ret) /* error, or we are removing something */
337 /* no outdated snapshot */
338 ret = remove_redundant_snapshot(&sl);
344 DSS_WARNING_LOG("disk space low and nothing obvious to remove\n");
345 ret = remove_oldest_snapshot(&sl);
348 DSS_CRIT_LOG("uhuhu: not enough disk space for a single snapshot\n");
349 ret = -ERRNO_TO_DSS_ERROR(ENOSPC);
351 free_snapshot_list(&sl);
355 static int pre_create_hook(void)
357 int ret, fds[3] = {0, 0, 0};
359 if (!conf.pre_create_hook_given) {
360 snapshot_creation_status = SCS_PRE_HOOK_SUCCESS;
363 DSS_NOTICE_LOG("executing %s\n", conf.pre_create_hook_arg);
364 ret = dss_exec_cmdline_pid(&pre_create_hook_pid,
365 conf.pre_create_hook_arg, fds);
368 snapshot_creation_status = SCS_PRE_HOOK_RUNNING;
372 static int post_create_hook(void)
374 int ret, fds[3] = {0, 0, 0};
377 if (!conf.post_create_hook_given) {
378 snapshot_creation_status = SCS_READY;
379 compute_next_snapshot_time();
382 cmd = make_message("%s %s", conf.post_create_hook_arg,
383 path_to_last_complete_snapshot);
384 DSS_NOTICE_LOG("executing %s\n", cmd);
385 ret = dss_exec_cmdline_pid(&post_create_hook_pid, cmd, fds);
389 snapshot_creation_status = SCS_POST_HOOK_RUNNING;
393 static void kill_process(pid_t pid)
397 DSS_WARNING_LOG("sending SIGTERM to pid %d\n", (int)pid);
401 static void stop_rsync_process(void)
403 if (!rsync_pid || rsync_stopped)
405 kill(SIGSTOP, rsync_pid);
409 static void restart_rsync_process(void)
411 if (!rsync_pid || !rsync_stopped)
413 kill (SIGCONT, rsync_pid);
419 * Print a log message about the exit status of a child.
421 static void log_termination_msg(pid_t pid, int status)
423 if (WIFEXITED(status))
424 DSS_INFO_LOG("child %i exited. Exit status: %i\n", (int)pid,
425 WEXITSTATUS(status));
426 else if (WIFSIGNALED(status))
427 DSS_NOTICE_LOG("child %i was killed by signal %i\n", (int)pid,
430 DSS_WARNING_LOG("child %i terminated abormally\n", (int)pid);
433 static int wait_for_process(pid_t pid, int *status)
437 DSS_DEBUG_LOG("Waiting for process %d to terminate\n", (int)pid);
442 FD_SET(signal_pipe, &rfds);
443 ret = dss_select(signal_pipe + 1, &rfds, NULL, NULL);
449 if (ret == SIGCHLD) {
450 ret = waitpid(pid, status, 0);
453 if (errno != EINTR) { /* error */
454 ret = -ERRNO_TO_DSS_ERROR(errno);
458 /* SIGINT or SIGTERM */
459 DSS_WARNING_LOG("sending SIGTERM to pid %d\n", (int)pid);
463 DSS_ERROR_LOG("failed to wait for process %d\n", (int)pid);
465 log_termination_msg(pid, *status);
469 static int handle_rm_exit(int status)
472 if (!WIFEXITED(status))
473 return -E_INVOLUNTARY_EXIT;
474 if (WEXITSTATUS(status))
475 return -E_BAD_EXIT_CODE;
479 static int wait_for_rm_process(void)
481 int status, ret = wait_for_process(rm_pid, &status);
485 return handle_rm_exit(status);
488 static int handle_rsync_exit(int status)
492 if (!WIFEXITED(status)) {
493 DSS_ERROR_LOG("rsync process %d died involuntary\n", (int)rsync_pid);
494 ret = -E_INVOLUNTARY_EXIT;
495 snapshot_creation_status = SCS_READY;
496 compute_next_snapshot_time();
499 es = WEXITSTATUS(status);
500 if (es != 0 && es != 23 && es != 24) {
501 DSS_ERROR_LOG("rsync process %d returned %d\n", (int)rsync_pid, es);
502 ret = -E_BAD_EXIT_CODE;
503 snapshot_creation_status = SCS_READY;
504 compute_next_snapshot_time();
507 ret = rename_incomplete_snapshot(current_snapshot_creation_time);
510 snapshot_creation_status = SCS_RSYNC_SUCCESS;
517 static int handle_pre_create_hook_exit(int status)
521 if (!WIFEXITED(status)) {
522 snapshot_creation_status = SCS_READY;
523 compute_next_snapshot_time();
524 ret = -E_INVOLUNTARY_EXIT;
527 es = WEXITSTATUS(status);
529 snapshot_creation_status = SCS_READY;
530 compute_next_snapshot_time();
531 ret = -E_BAD_EXIT_CODE;
534 snapshot_creation_status = SCS_PRE_HOOK_SUCCESS;
537 pre_create_hook_pid = 0;
541 static int handle_sigchld(void)
544 int status, ret = reap_child(&pid, &status);
548 if (pid == rsync_pid)
549 return handle_rsync_exit(status);
551 return handle_rm_exit(status);
552 if (pid == pre_create_hook_pid)
553 return handle_pre_create_hook_exit(status);
554 if (pid == post_create_hook_pid) {
555 snapshot_creation_status = SCS_READY;
556 compute_next_snapshot_time();
559 DSS_EMERG_LOG("BUG: unknown process %d died\n", (int)pid);
563 static int check_config(void)
565 if (conf.unit_interval_arg <= 0) {
566 DSS_ERROR_LOG("bad unit interval: %i\n", conf.unit_interval_arg);
567 return -E_INVALID_NUMBER;
569 DSS_DEBUG_LOG("unit interval: %i day(s)\n", conf.unit_interval_arg);
570 if (conf.num_intervals_arg <= 0) {
571 DSS_ERROR_LOG("bad number of intervals %i\n", conf.num_intervals_arg);
572 return -E_INVALID_NUMBER;
574 DSS_DEBUG_LOG("number of intervals: %i\n", conf.num_intervals_arg);
578 /* exits on errors */
579 static void parse_config_file(int override)
584 char *old_logfile_arg = NULL;
585 int old_daemon_given = 0;
587 if (conf.config_file_given)
588 config_file = dss_strdup(conf.config_file_arg);
590 char *home = get_homedir();
591 config_file = make_message("%s/.dssrc", home);
594 if (override) { /* SIGHUP */
595 if (conf.logfile_given)
596 old_logfile_arg = dss_strdup(conf.logfile_arg);
597 old_daemon_given = conf.daemon_given;
600 ret = stat(config_file, &statbuf);
601 if (ret && conf.config_file_given) {
602 ret = -ERRNO_TO_DSS_ERROR(errno);
603 DSS_ERROR_LOG("failed to stat config file %s\n", config_file);
607 struct cmdline_parser_params params = {
608 .override = override,
611 .check_ambiguity = 0,
614 cmdline_parser_config_file(config_file, &conf, ¶ms);
616 ret = check_config();
620 /* don't change daemon mode on SIGHUP */
621 conf.daemon_given = old_daemon_given;
624 if (conf.logfile_given)
625 free(old_logfile_arg);
626 else if (conf.daemon_given) { /* re-use old logfile */
627 conf.logfile_arg = old_logfile_arg;
628 conf.logfile_given = 1;
631 if (conf.logfile_given) {
632 logfile = open_log(conf.logfile_arg);
633 log_welcome(conf.loglevel_arg);
635 DSS_EMERG_LOG("loglevel: %d\n", conf.loglevel_arg);
636 // cmdline_parser_dump(logfile? logfile : stdout, &conf);
641 DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
645 static void change_to_dest_dir(void)
649 DSS_INFO_LOG("changing cwd to %s\n", conf.dest_dir_arg);
650 ret = dss_chdir(conf.dest_dir_arg);
653 DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
657 static void handle_sighup(void)
659 DSS_NOTICE_LOG("SIGHUP\n");
660 parse_config_file(1);
661 change_to_dest_dir();
664 static void handle_signal(void)
666 int sig, ret = next_signal();
674 restart_rsync_process();
675 kill_process(rsync_pid);
676 kill_process(rm_pid);
683 ret = handle_sigchld();
688 DSS_ERROR_LOG("%s\n", dss_strerror(-ret));
691 static void create_rsync_argv(char ***argv, int64_t *num)
693 char *logname, *newest;
695 struct snapshot_list sl;
697 dss_get_snapshot_list(&sl);
698 newest = name_of_newest_complete_snapshot(&sl);
699 free_snapshot_list(&sl);
701 *argv = dss_malloc((15 + conf.rsync_option_given) * sizeof(char *));
702 (*argv)[i++] = dss_strdup("rsync");
703 (*argv)[i++] = dss_strdup("-aq");
704 (*argv)[i++] = dss_strdup("--delete");
705 for (j = 0; j < conf.rsync_option_given; j++)
706 (*argv)[i++] = dss_strdup(conf.rsync_option_arg[j]);
708 DSS_INFO_LOG("using %s as reference snapshot\n", newest);
709 (*argv)[i++] = make_message("--link-dest=../%s", newest);
712 DSS_INFO_LOG("no previous snapshot found\n");
713 logname = dss_logname();
714 if (conf.remote_user_given && !strcmp(conf.remote_user_arg, logname))
715 (*argv)[i++] = dss_strdup(conf.source_dir_arg);
717 (*argv)[i++] = make_message("%s@%s:%s/", conf.remote_user_given?
718 conf.remote_user_arg : logname,
719 conf.remote_host_arg, conf.source_dir_arg);
721 *num = get_current_time();
722 (*argv)[i++] = incomplete_name(*num);
724 for (j = 0; j < i; j++)
725 DSS_DEBUG_LOG("argv[%d] = %s\n", j, (*argv)[j]);
728 static void free_rsync_argv(char **argv)
731 for (i = 0; argv[i]; i++)
736 static int create_snapshot(char **argv)
738 int ret, fds[3] = {0, 0, 0};
741 name = incomplete_name(current_snapshot_creation_time);
742 DSS_NOTICE_LOG("creating new snapshot %s\n", name);
744 ret = dss_exec(&rsync_pid, argv[0], argv, fds);
747 snapshot_creation_status = SCS_RSYNC_RUNNING;
751 static int select_loop(void)
754 /* check every 60 seconds for free disk space */
761 struct timeval now, *tvp;
764 tvp = NULL; /* sleep until rm process dies */
765 else { /* sleep one minute */
771 FD_SET(signal_pipe, &rfds);
772 DSS_DEBUG_LOG("tvp: %p, tv_sec : %lu\n", tvp, (long unsigned) tv.tv_sec);
773 ret = dss_select(signal_pipe + 1, &rfds, NULL, tvp);
776 if (FD_ISSET(signal_pipe, &rfds))
780 ret = disk_space_low();
783 low_disk_space = ret;
784 ret = try_to_free_disk_space(low_disk_space);
788 stop_rsync_process();
791 restart_rsync_process();
792 gettimeofday(&now, NULL);
793 if (tv_diff(&next_snapshot_time, &now, NULL) > 0)
795 switch (snapshot_creation_status) {
797 ret = pre_create_hook();
801 case SCS_PRE_HOOK_RUNNING:
803 case SCS_PRE_HOOK_SUCCESS:
804 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
805 ret = create_snapshot(rsync_argv);
806 free_rsync_argv(rsync_argv);
810 case SCS_RSYNC_RUNNING:
812 case SCS_RSYNC_SUCCESS:
813 ret = post_create_hook();
817 case SCS_POST_HOOK_RUNNING:
825 static int com_run(void)
829 if (conf.dry_run_given) {
830 DSS_ERROR_LOG("dry_run not supported by this command\n");
833 ret = install_sighandler(SIGHUP);
836 compute_next_snapshot_time();
837 return select_loop();
840 static int com_prune(void)
843 struct snapshot_list sl;
844 struct disk_space ds;
846 ret = get_disk_space(".", &ds);
851 dss_get_snapshot_list(&sl);
852 ret = remove_outdated_snapshot(&sl);
853 free_snapshot_list(&sl);
858 ret = wait_for_rm_process();
863 dss_get_snapshot_list(&sl);
864 ret = remove_redundant_snapshot(&sl);
865 free_snapshot_list(&sl);
870 ret = wait_for_rm_process();
879 static int com_create(void)
884 if (conf.dry_run_given) {
887 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
888 for (i = 0; rsync_argv[i]; i++) {
890 msg = make_message("%s%s%s", tmp? tmp : "",
891 tmp? " " : "", rsync_argv[i]);
894 free_rsync_argv(rsync_argv);
895 dss_msg("%s\n", msg);
899 ret = pre_create_hook();
902 if (pre_create_hook_pid) {
903 ret = wait_for_process(pre_create_hook_pid, &status);
906 ret = handle_pre_create_hook_exit(status);
910 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
911 ret = create_snapshot(rsync_argv);
914 ret = wait_for_process(rsync_pid, &status);
917 ret = handle_rsync_exit(status);
921 if (post_create_hook_pid)
922 ret = wait_for_process(post_create_hook_pid, &status);
924 free_rsync_argv(rsync_argv);
928 static int com_ls(void)
931 struct snapshot_list sl;
934 dss_get_snapshot_list(&sl);
935 FOR_EACH_SNAPSHOT(s, i, &sl)
936 dss_msg("%u\t%s\n", s->interval, s->name);
937 free_snapshot_list(&sl);
941 static void setup_signal_handling(void)
945 DSS_INFO_LOG("setting up signal handlers\n");
946 signal_pipe = signal_init(); /* always successful */
947 ret = install_sighandler(SIGINT);
950 ret = install_sighandler(SIGTERM);
953 ret = install_sighandler(SIGCHLD);
958 DSS_EMERG_LOG("could not install signal handlers\n");
963 * The main function of dss.
965 * \param argc Usual argument count.
966 * \param argv Usual argument vector.
968 int main(int argc, char **argv)
971 struct cmdline_parser_params params = {
975 .check_ambiguity = 0,
979 cmdline_parser_ext(argc, argv, &conf, ¶ms); /* aborts on errors */
980 parse_config_file(0);
982 if (conf.daemon_given)
984 change_to_dest_dir();
985 setup_signal_handling();
986 ret = call_command_handler();
988 DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
989 exit(ret >= 0? EXIT_SUCCESS : EXIT_FAILURE);