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 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 rm process. */
49 /** When the next snapshot is due. */
50 static struct timeval next_snapshot_time;
51 /** Creation time of the snapshot currently being created. */
52 static int64_t current_snapshot_creation_time;
53 /** Needed by the post-create hook. */
54 static char *path_to_last_complete_snapshot;
55 /** \sa \ref snap.h for details. */
56 static unsigned snapshot_creation_status;
62 /* a litte cpp magic helps to DRY */
68 #define COMMAND(x) static int com_ ##x(void);
71 #define COMMAND(x) if (conf.x ##_given) return com_ ##x();
72 static int call_command_handler(void)
75 DSS_EMERG_LOG("BUG: did not find command handler\n");
82 * The log function of dss.
85 * \param fml Usual format string.
87 * All DSS_XXX_LOG() macros use this function.
89 __printf_2_3 void dss_log(int ll, const char* fmt,...)
97 if (ll < conf.loglevel_arg)
99 outfd = logfile? logfile : stderr;
102 strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
103 fprintf(outfd, "%s ", str);
104 if (conf.loglevel_arg <= INFO)
105 fprintf(outfd, "%i: ", ll);
107 vfprintf(outfd, fmt, argp);
112 * Print a message either to stdout or to the log file.
114 static __printf_1_2 void dss_msg(const char* fmt,...)
116 FILE *outfd = conf.daemon_given? logfile : stdout;
119 vfprintf(outfd, fmt, argp);
123 static int disk_space_low(void)
125 struct disk_space ds;
126 int ret = get_disk_space(".", &ds);
130 if (conf.min_free_mb_arg)
131 if (ds.free_mb < conf.min_free_mb_arg)
133 if (conf.min_free_percent_arg)
134 if (ds.percent_free < conf.min_free_percent_arg)
136 if (conf.min_free_percent_inodes_arg)
137 if (ds.percent_free_inodes < conf.min_free_percent_inodes_arg)
142 static void dss_get_snapshot_list(struct snapshot_list *sl)
144 get_snapshot_list(sl, conf.unit_interval_arg, conf.num_intervals_arg);
147 static void compute_next_snapshot_time(void)
149 struct timeval now, unit_interval = {.tv_sec = 24 * 3600 * conf.unit_interval_arg},
152 unsigned wanted = desired_number_of_snapshots(0, conf.num_intervals_arg),
153 num_complete_snapshots = 0;
155 struct snapshot *s = NULL;
156 struct snapshot_list sl;
158 assert(snapshot_creation_status == SCS_READY);
159 current_snapshot_creation_time = 0;
160 dss_get_snapshot_list(&sl);
161 FOR_EACH_SNAPSHOT(s, i, &sl) {
162 if (!(s->flags & SS_COMPLETE))
164 num_complete_snapshots++;
165 x += s->completion_time - s->creation_time;
168 if (num_complete_snapshots)
169 x /= num_complete_snapshots; /* avg time to create one snapshot */
170 x *= wanted; /* time to create all snapshots in interval 0 */
173 ret = tv_diff(&unit_interval, &tmp, &diff); /* total sleep time per unit interval */
174 if (ret < 0 || !s) /* unit_interval < tmp or no snapshot */
176 tv_divide(wanted, &diff, &tmp); /* sleep time betweeen two snapshots */
177 diff.tv_sec = s->completion_time; /* completion time of the the latest snaphot */
179 tv_add(&diff, &tmp, &next_snapshot_time);
180 gettimeofday(&now, NULL);
181 if (tv_diff(&now, &next_snapshot_time, NULL) < 0)
184 next_snapshot_time = now;
185 next_snapshot_time.tv_sec += 60;
187 free_snapshot_list(&sl);
191 static int remove_snapshot(struct snapshot *s, char *why)
193 int fds[3] = {0, 0, 0};
195 char *new_name = being_deleted_name(s);
196 int ret = dss_rename(s->name, new_name);
197 char *argv[] = {"rm", "-rf", new_name, NULL};
201 DSS_NOTICE_LOG("removing %s snapshot %s (interval = %i)\n",
202 why, s->name, s->interval);
203 ret = dss_exec(&rm_pid, argv[0], argv, fds);
209 static int snapshot_is_being_created(struct snapshot *s)
211 return s->creation_time == current_snapshot_creation_time;
215 * return: 0: no redundant snapshots, 1: rm process started, negative: error
217 static int remove_redundant_snapshot(struct snapshot_list *sl)
219 int ret, i, interval;
221 unsigned missing = 0;
223 DSS_DEBUG_LOG("looking for intervals containing too many snapshots\n");
224 for (interval = conf.num_intervals_arg - 1; interval >= 0; interval--) {
225 unsigned keep = desired_number_of_snapshots(interval, conf.num_intervals_arg);
226 unsigned num = sl->interval_count[interval];
227 struct snapshot *victim = NULL, *prev = NULL;
228 int64_t score = LONG_MAX;
231 missing += keep - num;
232 // DSS_DEBUG_LOG("interval %i: keep: %u, have: %u, missing: %u\n",
233 // interval, keep, num, missing);
234 if (keep + missing >= num)
236 /* redundant snapshot in this interval, pick snapshot with lowest score */
237 FOR_EACH_SNAPSHOT(s, i, sl) {
240 if (snapshot_is_being_created(s))
242 //DSS_DEBUG_LOG("checking %s\n", s->name);
243 if (s->interval > interval) {
247 if (s->interval < interval)
255 /* check if s is a better victim */
256 this_score = s->creation_time - prev->creation_time;
257 assert(this_score >= 0);
258 //DSS_DEBUG_LOG("%s: score %lli\n", s->name, (long long)score);
259 if (this_score < score) {
266 if (conf.dry_run_given) {
267 dss_msg("%s would be removed (interval = %i)\n",
268 victim->name, victim->interval);
271 ret = remove_snapshot(victim, "redundant");
272 return ret < 0? ret : 1;
277 static int remove_outdated_snapshot(struct snapshot_list *sl)
282 DSS_DEBUG_LOG("looking for snapshots belonging to intervals greater than %d\n",
283 conf.num_intervals_arg);
284 FOR_EACH_SNAPSHOT(s, i, sl) {
285 if (snapshot_is_being_created(s))
287 if (s->interval <= conf.num_intervals_arg)
289 if (conf.dry_run_given) {
290 dss_msg("%s would be removed (interval = %i)\n",
291 s->name, s->interval);
294 ret = remove_snapshot(s, "outdated");
302 static int remove_oldest_snapshot(struct snapshot_list *sl)
304 struct snapshot *s = get_oldest_snapshot(sl);
306 if (!s) /* no snapshot found */
308 DSS_INFO_LOG("oldest snapshot: %s\n", s->name);
309 if (snapshot_is_being_created(s))
311 return remove_snapshot(s, "oldest");
314 static int rename_incomplete_snapshot(int64_t start)
319 free(path_to_last_complete_snapshot);
320 ret = complete_name(start, get_current_time(),
321 &path_to_last_complete_snapshot);
324 old_name = incomplete_name(start);
325 ret = dss_rename(old_name, path_to_last_complete_snapshot);
327 DSS_NOTICE_LOG("%s -> %s\n", old_name,
328 path_to_last_complete_snapshot);
333 static int try_to_free_disk_space(int low_disk_space)
336 struct snapshot_list sl;
338 if (!low_disk_space && conf.keep_redundant_given)
340 dss_get_snapshot_list(&sl);
341 ret = remove_outdated_snapshot(&sl);
342 if (ret) /* error, or we are removing something */
344 /* no outdated snapshot */
345 ret = remove_redundant_snapshot(&sl);
351 DSS_WARNING_LOG("disk space low and nothing obvious to remove\n");
352 ret = remove_oldest_snapshot(&sl);
355 DSS_CRIT_LOG("uhuhu: not enough disk space for a single snapshot\n");
356 ret = -ERRNO_TO_DSS_ERROR(ENOSPC);
358 free_snapshot_list(&sl);
362 static int pre_create_hook(void)
364 int ret, fds[3] = {0, 0, 0};
366 if (!conf.pre_create_hook_given) {
367 snapshot_creation_status = SCS_PRE_HOOK_SUCCESS;
370 DSS_NOTICE_LOG("executing %s\n", conf.pre_create_hook_arg);
371 ret = dss_exec_cmdline_pid(&create_pid,
372 conf.pre_create_hook_arg, fds);
375 snapshot_creation_status = SCS_PRE_HOOK_RUNNING;
379 static int post_create_hook(void)
381 int ret, fds[3] = {0, 0, 0};
384 if (!conf.post_create_hook_given) {
385 snapshot_creation_status = SCS_READY;
386 compute_next_snapshot_time();
389 cmd = make_message("%s %s/%s", conf.post_create_hook_arg,
390 conf.dest_dir_arg, path_to_last_complete_snapshot);
391 DSS_NOTICE_LOG("executing %s\n", cmd);
392 ret = dss_exec_cmdline_pid(&create_pid, cmd, fds);
396 snapshot_creation_status = SCS_POST_HOOK_RUNNING;
400 static void kill_process(pid_t pid)
404 DSS_WARNING_LOG("sending SIGTERM to pid %d\n", (int)pid);
408 static void stop_create_process(void)
410 if (!create_pid || create_process_stopped)
412 kill(SIGSTOP, create_pid);
413 create_process_stopped = 1;
416 static void restart_create_process(void)
418 if (!create_pid || !create_process_stopped)
420 kill (SIGCONT, create_pid);
421 create_process_stopped = 0;
425 * Print a log message about the exit status of a child.
427 static void log_termination_msg(pid_t pid, int status)
429 if (WIFEXITED(status))
430 DSS_INFO_LOG("child %i exited. Exit status: %i\n", (int)pid,
431 WEXITSTATUS(status));
432 else if (WIFSIGNALED(status))
433 DSS_NOTICE_LOG("child %i was killed by signal %i\n", (int)pid,
436 DSS_WARNING_LOG("child %i terminated abormally\n", (int)pid);
439 static int wait_for_process(pid_t pid, int *status)
443 DSS_DEBUG_LOG("Waiting for process %d to terminate\n", (int)pid);
448 FD_SET(signal_pipe, &rfds);
449 ret = dss_select(signal_pipe + 1, &rfds, NULL, NULL);
455 if (ret == SIGCHLD) {
456 ret = waitpid(pid, status, 0);
459 if (errno != EINTR) { /* error */
460 ret = -ERRNO_TO_DSS_ERROR(errno);
464 /* SIGINT or SIGTERM */
465 DSS_WARNING_LOG("sending SIGTERM to pid %d\n", (int)pid);
469 DSS_ERROR_LOG("failed to wait for process %d\n", (int)pid);
471 log_termination_msg(pid, *status);
475 static int handle_rm_exit(int status)
478 if (!WIFEXITED(status))
479 return -E_INVOLUNTARY_EXIT;
480 if (WEXITSTATUS(status))
481 return -E_BAD_EXIT_CODE;
485 static int wait_for_rm_process(void)
487 int status, ret = wait_for_process(rm_pid, &status);
491 return handle_rm_exit(status);
494 static int handle_rsync_exit(int status)
498 if (!WIFEXITED(status)) {
499 DSS_ERROR_LOG("rsync process %d died involuntary\n", (int)create_pid);
500 ret = -E_INVOLUNTARY_EXIT;
501 snapshot_creation_status = SCS_READY;
502 compute_next_snapshot_time();
505 es = WEXITSTATUS(status);
506 if (es == 13) { /* Errors with program diagnostics */
507 DSS_WARNING_LOG("rsync process %d returned %d -- restarting\n",
508 (int)create_pid, es);
509 snapshot_creation_status = SCS_RSYNC_NEEDS_RESTART;
510 gettimeofday(&next_snapshot_time, NULL);
511 next_snapshot_time.tv_sec += 60;
515 if (es != 0 && es != 23 && es != 24) {
516 DSS_ERROR_LOG("rsync process %d returned %d\n", (int)create_pid, es);
517 ret = -E_BAD_EXIT_CODE;
518 snapshot_creation_status = SCS_READY;
519 compute_next_snapshot_time();
522 ret = rename_incomplete_snapshot(current_snapshot_creation_time);
525 snapshot_creation_status = SCS_RSYNC_SUCCESS;
528 create_process_stopped = 0;
532 static int handle_pre_create_hook_exit(int status)
536 if (!WIFEXITED(status)) {
537 snapshot_creation_status = SCS_READY;
538 compute_next_snapshot_time();
539 ret = -E_INVOLUNTARY_EXIT;
542 es = WEXITSTATUS(status);
544 snapshot_creation_status = SCS_READY;
545 compute_next_snapshot_time();
546 ret = -E_BAD_EXIT_CODE;
549 snapshot_creation_status = SCS_PRE_HOOK_SUCCESS;
556 static int handle_sigchld(void)
559 int status, ret = reap_child(&pid, &status);
564 if (pid == create_pid) {
565 switch (snapshot_creation_status) {
566 case SCS_PRE_HOOK_RUNNING:
567 return handle_pre_create_hook_exit(status);
568 case SCS_RSYNC_RUNNING:
569 return handle_rsync_exit(status);
570 case SCS_POST_HOOK_RUNNING:
571 snapshot_creation_status = SCS_READY;
572 compute_next_snapshot_time();
575 DSS_EMERG_LOG("BUG: create can't die in status %d\n",
576 snapshot_creation_status);
581 return handle_rm_exit(status);
582 DSS_EMERG_LOG("BUG: unknown process %d died\n", (int)pid);
586 static int check_config(void)
588 if (conf.unit_interval_arg <= 0) {
589 DSS_ERROR_LOG("bad unit interval: %i\n", conf.unit_interval_arg);
590 return -E_INVALID_NUMBER;
592 DSS_DEBUG_LOG("unit interval: %i day(s)\n", conf.unit_interval_arg);
593 if (conf.num_intervals_arg <= 0) {
594 DSS_ERROR_LOG("bad number of intervals %i\n", conf.num_intervals_arg);
595 return -E_INVALID_NUMBER;
597 DSS_DEBUG_LOG("number of intervals: %i\n", conf.num_intervals_arg);
601 static int parse_config_file(int override)
606 char *old_logfile_arg = NULL;
607 int old_daemon_given = 0;
609 if (conf.config_file_given)
610 config_file = dss_strdup(conf.config_file_arg);
612 char *home = get_homedir();
613 config_file = make_message("%s/.dssrc", home);
616 if (override) { /* SIGHUP */
617 if (conf.logfile_given)
618 old_logfile_arg = dss_strdup(conf.logfile_arg);
619 old_daemon_given = conf.daemon_given;
622 ret = stat(config_file, &statbuf);
623 if (ret && conf.config_file_given) {
624 ret = -ERRNO_TO_DSS_ERROR(errno);
625 DSS_ERROR_LOG("failed to stat config file %s\n", config_file);
629 struct cmdline_parser_params params = {
630 .override = override,
633 .check_ambiguity = 0,
636 if (override) { /* invalidate all rsync options */
639 for (i = 0; i < conf.rsync_option_given; i++) {
640 free(conf.rsync_option_arg[i]);
641 conf.rsync_option_arg[i] = NULL;
643 conf.rsync_option_given = 0;
645 cmdline_parser_config_file(config_file, &conf, ¶ms);
647 ret = check_config();
651 /* don't change daemon mode on SIGHUP */
652 conf.daemon_given = old_daemon_given;
655 if (conf.logfile_given)
656 free(old_logfile_arg);
657 else if (conf.daemon_given) { /* re-use old logfile */
658 conf.logfile_arg = old_logfile_arg;
659 conf.logfile_given = 1;
662 if (conf.logfile_given) {
663 logfile = open_log(conf.logfile_arg);
664 log_welcome(conf.loglevel_arg);
666 DSS_DEBUG_LOG("loglevel: %d\n", conf.loglevel_arg);
667 // cmdline_parser_dump(logfile? logfile : stdout, &conf);
671 DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
675 static int change_to_dest_dir(void)
677 DSS_INFO_LOG("changing cwd to %s\n", conf.dest_dir_arg);
678 return dss_chdir(conf.dest_dir_arg);
681 static int handle_sighup(void)
685 DSS_NOTICE_LOG("SIGHUP\n");
686 ret = parse_config_file(1);
689 return change_to_dest_dir();
692 static int handle_signal(void)
694 int sig, ret = next_signal();
702 restart_create_process();
703 kill_process(create_pid);
704 kill_process(rm_pid);
708 ret = handle_sighup();
711 ret = handle_sigchld();
716 DSS_ERROR_LOG("%s\n", dss_strerror(-ret));
721 * We can not use rsync locally if the local user is different from the remote
722 * user or if the src dir is not on the local host (or both).
724 static int use_rsync_locally(char *logname)
726 char *h = conf.remote_host_arg;
728 if (strcmp(h, "localhost") && strcmp(h, "127.0.0.1"))
730 if (conf.remote_user_given && strcmp(conf.remote_user_arg, logname))
735 static void create_rsync_argv(char ***argv, int64_t *num)
737 char *logname, *newest;
739 struct snapshot_list sl;
741 dss_get_snapshot_list(&sl);
742 newest = name_of_newest_complete_snapshot(&sl);
743 free_snapshot_list(&sl);
745 *argv = dss_malloc((15 + conf.rsync_option_given) * sizeof(char *));
746 (*argv)[i++] = dss_strdup("rsync");
747 (*argv)[i++] = dss_strdup("-aq");
748 (*argv)[i++] = dss_strdup("--delete");
749 for (j = 0; j < conf.rsync_option_given; j++)
750 (*argv)[i++] = dss_strdup(conf.rsync_option_arg[j]);
752 DSS_INFO_LOG("using %s as reference snapshot\n", newest);
753 (*argv)[i++] = make_message("--link-dest=../%s", newest);
756 DSS_INFO_LOG("no previous snapshot found\n");
757 logname = dss_logname();
758 if (use_rsync_locally(logname))
759 (*argv)[i++] = dss_strdup(conf.source_dir_arg);
761 (*argv)[i++] = make_message("%s@%s:%s/", conf.remote_user_given?
762 conf.remote_user_arg : logname,
763 conf.remote_host_arg, conf.source_dir_arg);
765 *num = get_current_time();
766 (*argv)[i++] = incomplete_name(*num);
768 for (j = 0; j < i; j++)
769 DSS_DEBUG_LOG("argv[%d] = %s\n", j, (*argv)[j]);
772 static void free_rsync_argv(char **argv)
778 for (i = 0; argv[i]; i++)
783 static int create_snapshot(char **argv)
785 int ret, fds[3] = {0, 0, 0};
788 name = incomplete_name(current_snapshot_creation_time);
789 DSS_NOTICE_LOG("creating new snapshot %s\n", name);
791 ret = dss_exec(&create_pid, argv[0], argv, fds);
794 snapshot_creation_status = SCS_RSYNC_RUNNING;
798 static int select_loop(void)
801 /* check every 60 seconds for free disk space */
803 char **rsync_argv = NULL;
808 struct timeval now, *tvp;
811 tvp = NULL; /* sleep until rm process dies */
812 else { /* sleep one minute */
818 FD_SET(signal_pipe, &rfds);
819 DSS_DEBUG_LOG("tvp: %p, tv_sec : %lu\n", tvp, (long unsigned) tv.tv_sec);
820 ret = dss_select(signal_pipe + 1, &rfds, NULL, tvp);
823 if (FD_ISSET(signal_pipe, &rfds)) {
824 ret = handle_signal();
830 ret = disk_space_low();
833 low_disk_space = ret;
834 ret = try_to_free_disk_space(low_disk_space);
838 stop_create_process();
841 restart_create_process();
842 gettimeofday(&now, NULL);
843 if (tv_diff(&next_snapshot_time, &now, NULL) > 0)
845 switch (snapshot_creation_status) {
847 ret = pre_create_hook();
851 case SCS_PRE_HOOK_RUNNING:
853 case SCS_RSYNC_NEEDS_RESTART:
854 ret = create_snapshot(rsync_argv);
858 case SCS_PRE_HOOK_SUCCESS:
859 free_rsync_argv(rsync_argv);
860 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
861 ret = create_snapshot(rsync_argv);
865 case SCS_RSYNC_RUNNING:
867 case SCS_RSYNC_SUCCESS:
868 ret = post_create_hook();
872 case SCS_POST_HOOK_RUNNING:
880 static void exit_hook(int exit_code)
882 int fds[3] = {0, 0, 0};
883 char *argv[] = {conf.exit_hook_arg, dss_strerror(-exit_code), NULL};
886 if (!conf.exit_hook_given)
888 DSS_NOTICE_LOG("executing %s %s\n", argv[0], argv[1]);
889 dss_exec(&pid, conf.exit_hook_arg, argv, fds);
892 static int com_run(void)
896 if (conf.dry_run_given) {
897 DSS_ERROR_LOG("dry_run not supported by this command\n");
900 ret = install_sighandler(SIGHUP);
903 compute_next_snapshot_time();
905 if (ret >= 0) /* impossible */
911 static int com_prune(void)
914 struct snapshot_list sl;
915 struct disk_space ds;
917 ret = get_disk_space(".", &ds);
922 dss_get_snapshot_list(&sl);
923 ret = remove_outdated_snapshot(&sl);
924 free_snapshot_list(&sl);
929 ret = wait_for_rm_process();
934 dss_get_snapshot_list(&sl);
935 ret = remove_redundant_snapshot(&sl);
936 free_snapshot_list(&sl);
941 ret = wait_for_rm_process();
950 static int com_create(void)
955 if (conf.dry_run_given) {
958 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
959 for (i = 0; rsync_argv[i]; i++) {
961 msg = make_message("%s%s%s", tmp? tmp : "",
962 tmp? " " : "", rsync_argv[i]);
965 free_rsync_argv(rsync_argv);
966 dss_msg("%s\n", msg);
970 ret = pre_create_hook();
974 ret = wait_for_process(create_pid, &status);
977 ret = handle_pre_create_hook_exit(status);
981 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
982 ret = create_snapshot(rsync_argv);
985 ret = wait_for_process(create_pid, &status);
988 ret = handle_rsync_exit(status);
993 ret = wait_for_process(create_pid, &status);
995 free_rsync_argv(rsync_argv);
999 static int com_ls(void)
1002 struct snapshot_list sl;
1005 dss_get_snapshot_list(&sl);
1006 FOR_EACH_SNAPSHOT(s, i, &sl) {
1008 if (s->flags & SS_COMPLETE)
1009 d = (s->completion_time - s->creation_time) / 60;
1010 dss_msg("%u\t%s\t%3" PRId64 ":%02" PRId64 "\n", s->interval, s->name, d/60, d%60);
1012 free_snapshot_list(&sl);
1016 static int setup_signal_handling(void)
1020 DSS_INFO_LOG("setting up signal handlers\n");
1021 signal_pipe = signal_init(); /* always successful */
1022 ret = install_sighandler(SIGINT);
1025 ret = install_sighandler(SIGTERM);
1028 return install_sighandler(SIGCHLD);
1032 * The main function of dss.
1034 * \param argc Usual argument count.
1035 * \param argv Usual argument vector.
1037 int main(int argc, char **argv)
1040 struct cmdline_parser_params params = {
1043 .check_required = 0,
1044 .check_ambiguity = 0,
1048 cmdline_parser_ext(argc, argv, &conf, ¶ms); /* aborts on errors */
1049 ret = parse_config_file(0);
1052 if (conf.daemon_given)
1054 ret = change_to_dest_dir();
1057 ret = setup_signal_handling();
1060 ret = call_command_handler();
1063 DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
1064 exit(ret >= 0? EXIT_SUCCESS : EXIT_FAILURE);