19 #include "gcc-compat.h"
32 /** Command line and config file options. */
33 static struct gengetopt_args_info conf;
34 /** Non-NULL if we log to a file. */
36 /** The read end of the signal pipe */
37 static int signal_pipe;
38 /** Process id of current rsync process. */
39 static pid_t rsync_pid;
40 /** Whether the rsync process is currently stopped */
41 static int rsync_stopped;
42 /** Process id of current rm process. */
44 /** When the next snapshot is due. */
45 static struct timeval next_snapshot_time;
46 /** The pid of the pre-create hook. */
47 static pid_t pre_create_hook_pid;
48 /** The pid of the post-create hook. */
49 static pid_t post_create_hook_pid;
50 /** Creation time of the snapshot currently being created. */
51 static int64_t current_snapshot_creation_time;
52 /** Needed by the post-create hook. */
53 static char *path_to_last_complete_snapshot;
54 /** \sa \ref snap.h for details. */
55 static unsigned snapshot_creation_status;
61 /* a litte cpp magic helps to DRY */
67 #define COMMAND(x) static int com_ ##x(void);
70 #define COMMAND(x) if (conf.x ##_given) return com_ ##x();
71 static int call_command_handler(void)
74 DSS_EMERG_LOG("BUG: did not find command handler\n");
81 * The log function of dss.
84 * \param fml Usual format string.
86 * All DSS_XXX_LOG() macros use this function.
88 __printf_2_3 void dss_log(int ll, const char* fmt,...)
96 if (ll < conf.loglevel_arg)
98 outfd = logfile? logfile : stderr;
101 strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
102 fprintf(outfd, "%s ", str);
103 if (conf.loglevel_arg <= INFO)
104 fprintf(outfd, "%i: ", ll);
106 vfprintf(outfd, fmt, argp);
111 * Print a message either to stdout or to the log file.
113 static __printf_1_2 void dss_msg(const char* fmt,...)
115 FILE *outfd = conf.daemon_given? logfile : stdout;
118 vfprintf(outfd, fmt, argp);
122 /* TODO: Also consider number of inodes. */
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 gettimeofday(&now, NULL);
177 tv_divide(wanted, &diff, &tmp); /* sleep time betweeen two snapshots */
178 diff.tv_sec = s->completion_time;
180 tv_add(&diff, &tmp, &next_snapshot_time);
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)
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 (interval = %i)\n", s->name, s->interval);
202 ret = dss_exec(&rm_pid, argv[0], argv, fds);
209 * return: 0: no redundant snapshots, 1: rm process started, negative: error
211 static int remove_redundant_snapshot(struct snapshot_list *sl)
213 int ret, i, interval;
215 unsigned missing = 0;
217 DSS_INFO_LOG("looking for intervals containing too many snapshots\n");
218 for (interval = conf.num_intervals_arg - 1; interval >= 0; interval--) {
219 unsigned keep = desired_number_of_snapshots(interval, conf.num_intervals_arg);
220 unsigned num = sl->interval_count[interval];
221 struct snapshot *victim = NULL, *prev = NULL;
222 int64_t score = LONG_MAX;
225 missing += keep - num;
226 // DSS_DEBUG_LOG("interval %i: keep: %u, have: %u, missing: %u\n",
227 // interval, keep, num, missing);
228 if (keep + missing >= num)
230 /* redundant snapshot in this interval, pick snapshot with lowest score */
231 FOR_EACH_SNAPSHOT(s, i, sl) {
234 //DSS_DEBUG_LOG("checking %s\n", s->name);
235 if (s->interval > interval) {
239 if (s->interval < interval)
247 /* check if s is a better victim */
248 this_score = s->creation_time - prev->creation_time;
249 assert(this_score >= 0);
250 //DSS_DEBUG_LOG("%s: score %lli\n", s->name, (long long)score);
251 if (this_score < score) {
258 if (conf.dry_run_given) {
259 dss_msg("%s would be removed (interval = %i)\n",
260 victim->name, victim->interval);
263 ret = remove_snapshot(victim);
264 return ret < 0? ret : 1;
269 static int remove_outdated_snapshot(struct snapshot_list *sl)
274 DSS_INFO_LOG("looking for snapshots belonging to intervals greater than %d\n",
275 conf.num_intervals_arg);
276 FOR_EACH_SNAPSHOT(s, i, sl) {
277 if (s->interval <= conf.num_intervals_arg)
279 if (conf.dry_run_given) {
280 dss_msg("%s would be removed (interval = %i)\n",
281 s->name, s->interval);
284 ret = remove_snapshot(s);
292 static int remove_oldest_snapshot(struct snapshot_list *sl)
294 struct snapshot *s = get_oldest_snapshot(sl);
296 if (!s) /* no snapshot found */
298 DSS_INFO_LOG("oldest snapshot: %s\n", s->name);
299 if (s->creation_time == current_snapshot_creation_time)
300 return 0; /* do not remove the snapshot currently being created */
301 return remove_snapshot(s);
304 static int rename_incomplete_snapshot(int64_t start)
309 free(path_to_last_complete_snapshot);
310 ret = complete_name(start, get_current_time(),
311 &path_to_last_complete_snapshot);
314 old_name = incomplete_name(start);
315 ret = dss_rename(old_name, path_to_last_complete_snapshot);
317 DSS_NOTICE_LOG("%s -> %s\n", old_name,
318 path_to_last_complete_snapshot);
323 static int try_to_free_disk_space(int low_disk_space)
326 struct snapshot_list sl;
328 dss_get_snapshot_list(&sl);
329 ret = remove_outdated_snapshot(&sl);
330 if (ret) /* error, or we are removing something */
332 /* no outdated snapshot */
333 ret = remove_redundant_snapshot(&sl);
339 DSS_WARNING_LOG("disk space low and nothing obvious to remove\n");
340 ret = remove_oldest_snapshot(&sl);
343 DSS_CRIT_LOG("uhuhu: not enough disk space for a single snapshot\n");
346 free_snapshot_list(&sl);
350 static int pre_create_hook(void)
352 int ret, fds[3] = {0, 0, 0};
354 if (!conf.pre_create_hook_given) {
355 snapshot_creation_status = SCS_PRE_HOOK_SUCCESS;
358 DSS_NOTICE_LOG("executing %s\n", conf.pre_create_hook_arg);
359 ret = dss_exec_cmdline_pid(&pre_create_hook_pid,
360 conf.pre_create_hook_arg, fds);
363 snapshot_creation_status = SCS_PRE_HOOK_RUNNING;
367 static int post_create_hook(void)
369 int ret, fds[3] = {0, 0, 0};
372 if (!conf.post_create_hook_given) {
373 snapshot_creation_status = SCS_READY;
374 compute_next_snapshot_time();
377 cmd = make_message("%s %s", conf.post_create_hook_arg,
378 path_to_last_complete_snapshot);
379 DSS_NOTICE_LOG("executing %s\n", cmd);
380 ret = dss_exec_cmdline_pid(&post_create_hook_pid, cmd, fds);
384 snapshot_creation_status = SCS_POST_HOOK_RUNNING;
388 static void kill_process(pid_t pid)
392 DSS_WARNING_LOG("sending SIGTERM to pid %d\n", (int)pid);
396 static void stop_rsync_process(void)
398 if (!rsync_pid || rsync_stopped)
400 kill(SIGSTOP, rsync_pid);
404 static void restart_rsync_process(void)
406 if (!rsync_pid || !rsync_stopped)
408 kill (SIGCONT, rsync_pid);
414 * Print a log message about the exit status of a child.
416 static void log_termination_msg(pid_t pid, int status)
418 if (WIFEXITED(status))
419 DSS_INFO_LOG("child %i exited. Exit status: %i\n", (int)pid,
420 WEXITSTATUS(status));
421 else if (WIFSIGNALED(status))
422 DSS_NOTICE_LOG("child %i was killed by signal %i\n", (int)pid,
425 DSS_WARNING_LOG("child %i terminated abormally\n", (int)pid);
428 static int wait_for_process(pid_t pid, int *status)
432 DSS_DEBUG_LOG("Waiting for process %d to terminate\n", (int)pid);
437 FD_SET(signal_pipe, &rfds);
438 ret = dss_select(signal_pipe + 1, &rfds, NULL, NULL);
444 if (ret == SIGCHLD) {
445 ret = waitpid(pid, status, 0);
448 if (errno != EINTR) { /* error */
449 ret = -ERRNO_TO_DSS_ERROR(errno);
453 /* SIGINT or SIGTERM */
454 DSS_WARNING_LOG("sending SIGTERM to pid %d\n", (int)pid);
458 DSS_ERROR_LOG("failed to wait for process %d\n", (int)pid);
460 log_termination_msg(pid, *status);
464 static int handle_rm_exit(int status)
467 if (!WIFEXITED(status))
468 return -E_INVOLUNTARY_EXIT;
469 if (WEXITSTATUS(status))
470 return -E_BAD_EXIT_CODE;
474 static int wait_for_rm_process(void)
476 int status, ret = wait_for_process(rm_pid, &status);
480 return handle_rm_exit(status);
483 static int handle_rsync_exit(int status)
487 if (!WIFEXITED(status)) {
488 DSS_ERROR_LOG("rsync process %d died involuntary\n", (int)rsync_pid);
489 ret = -E_INVOLUNTARY_EXIT;
490 snapshot_creation_status = SCS_READY;
491 compute_next_snapshot_time();
494 es = WEXITSTATUS(status);
495 if (es != 0 && es != 23 && es != 24) {
496 DSS_ERROR_LOG("rsync process %d returned %d\n", (int)rsync_pid, es);
497 ret = -E_BAD_EXIT_CODE;
498 snapshot_creation_status = SCS_READY;
499 compute_next_snapshot_time();
502 ret = rename_incomplete_snapshot(current_snapshot_creation_time);
505 snapshot_creation_status = SCS_RSYNC_SUCCESS;
512 static int handle_pre_create_hook_exit(int status)
516 if (!WIFEXITED(status)) {
517 snapshot_creation_status = SCS_READY;
518 compute_next_snapshot_time();
519 ret = -E_INVOLUNTARY_EXIT;
522 es = WEXITSTATUS(status);
524 snapshot_creation_status = SCS_READY;
525 compute_next_snapshot_time();
526 ret = -E_BAD_EXIT_CODE;
529 snapshot_creation_status = SCS_PRE_HOOK_SUCCESS;
532 pre_create_hook_pid = 0;
536 static int handle_sigchld(void)
539 int status, ret = reap_child(&pid, &status);
543 if (pid == rsync_pid)
544 return handle_rsync_exit(status);
546 return handle_rm_exit(status);
547 if (pid == pre_create_hook_pid)
548 return handle_pre_create_hook_exit(status);
549 if (pid == post_create_hook_pid) {
550 snapshot_creation_status = SCS_READY;
551 compute_next_snapshot_time();
554 DSS_EMERG_LOG("BUG: unknown process %d died\n", (int)pid);
558 static int check_config(void)
560 if (conf.unit_interval_arg <= 0) {
561 DSS_ERROR_LOG("bad unit interval: %i\n", conf.unit_interval_arg);
562 return -E_INVALID_NUMBER;
564 DSS_DEBUG_LOG("unit interval: %i day(s)\n", conf.unit_interval_arg);
565 if (conf.num_intervals_arg <= 0) {
566 DSS_ERROR_LOG("bad number of intervals %i\n", conf.num_intervals_arg);
567 return -E_INVALID_NUMBER;
569 DSS_DEBUG_LOG("number of intervals: %i\n", conf.num_intervals_arg);
573 /* exits on errors */
574 static void parse_config_file(int override)
579 char *old_logfile_arg = NULL;
580 int old_daemon_given = 0;
582 if (conf.config_file_given)
583 config_file = dss_strdup(conf.config_file_arg);
585 char *home = get_homedir();
586 config_file = make_message("%s/.dssrc", home);
589 if (override) { /* SIGHUP */
590 if (conf.logfile_given)
591 old_logfile_arg = dss_strdup(conf.logfile_arg);
592 old_daemon_given = conf.daemon_given;
595 ret = stat(config_file, &statbuf);
596 if (ret && conf.config_file_given) {
597 ret = -ERRNO_TO_DSS_ERROR(errno);
598 DSS_ERROR_LOG("failed to stat config file %s\n", config_file);
602 struct cmdline_parser_params params = {
603 .override = override,
606 .check_ambiguity = 0,
609 cmdline_parser_config_file(config_file, &conf, ¶ms);
611 ret = check_config();
615 /* don't change daemon mode on SIGHUP */
616 conf.daemon_given = old_daemon_given;
619 if (conf.logfile_given)
620 free(old_logfile_arg);
621 else if (conf.daemon_given) { /* re-use old logfile */
622 conf.logfile_arg = old_logfile_arg;
623 conf.logfile_given = 1;
626 if (conf.logfile_given) {
627 logfile = open_log(conf.logfile_arg);
628 log_welcome(conf.loglevel_arg);
630 DSS_EMERG_LOG("loglevel: %d\n", conf.loglevel_arg);
631 // cmdline_parser_dump(logfile? logfile : stdout, &conf);
636 DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
640 static void change_to_dest_dir(void)
644 DSS_INFO_LOG("changing cwd to %s\n", conf.dest_dir_arg);
645 ret = dss_chdir(conf.dest_dir_arg);
648 DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
652 static void handle_sighup(void)
654 DSS_NOTICE_LOG("SIGHUP\n");
655 parse_config_file(1);
656 change_to_dest_dir();
659 static void handle_signal(void)
661 int sig, ret = next_signal();
669 restart_rsync_process();
670 kill_process(rsync_pid);
671 kill_process(rm_pid);
678 ret = handle_sigchld();
683 DSS_ERROR_LOG("%s\n", dss_strerror(-ret));
686 static void create_rsync_argv(char ***argv, int64_t *num)
688 char *logname, *newest;
690 struct snapshot_list sl;
692 dss_get_snapshot_list(&sl);
693 newest = name_of_newest_complete_snapshot(&sl);
694 free_snapshot_list(&sl);
696 *argv = dss_malloc((15 + conf.rsync_option_given) * sizeof(char *));
697 (*argv)[i++] = dss_strdup("rsync");
698 (*argv)[i++] = dss_strdup("-aq");
699 (*argv)[i++] = dss_strdup("--delete");
700 for (j = 0; j < conf.rsync_option_given; j++)
701 (*argv)[i++] = dss_strdup(conf.rsync_option_arg[j]);
703 DSS_INFO_LOG("using %s as reference snapshot\n", newest);
704 (*argv)[i++] = make_message("--link-dest=../%s", newest);
707 DSS_INFO_LOG("no previous snapshot found\n");
708 logname = dss_logname();
709 if (conf.remote_user_given && !strcmp(conf.remote_user_arg, logname))
710 (*argv)[i++] = dss_strdup(conf.source_dir_arg);
712 (*argv)[i++] = make_message("%s@%s:%s/", conf.remote_user_given?
713 conf.remote_user_arg : logname,
714 conf.remote_host_arg, conf.source_dir_arg);
716 *num = get_current_time();
717 (*argv)[i++] = incomplete_name(*num);
719 for (j = 0; j < i; j++)
720 DSS_DEBUG_LOG("argv[%d] = %s\n", j, (*argv)[j]);
723 static void free_rsync_argv(char **argv)
726 for (i = 0; argv[i]; i++)
731 static int create_snapshot(char **argv)
733 int ret, fds[3] = {0, 0, 0};
736 name = incomplete_name(current_snapshot_creation_time);
737 DSS_NOTICE_LOG("creating new snapshot %s\n", name);
739 ret = dss_exec(&rsync_pid, argv[0], argv, fds);
742 snapshot_creation_status = SCS_RSYNC_RUNNING;
746 static int select_loop(void)
749 /* check every 60 seconds for free disk space */
750 struct timeval tv = {.tv_sec = 60, .tv_usec = 0};
756 struct timeval now, *tvp = &tv;
759 tvp = NULL; /* sleep until rm process dies */
761 FD_SET(signal_pipe, &rfds);
762 DSS_DEBUG_LOG("tvp: %p, tv_sec: %lu\n", tvp, (long unsigned) tv.tv_sec);
763 ret = dss_select(signal_pipe + 1, &rfds, NULL, tvp);
766 if (FD_ISSET(signal_pipe, &rfds))
770 ret = disk_space_low();
773 low_disk_space = ret;
774 ret = try_to_free_disk_space(low_disk_space);
778 stop_rsync_process();
781 restart_rsync_process();
782 gettimeofday(&now, NULL);
783 if (tv_diff(&next_snapshot_time, &now, NULL) > 0)
785 switch (snapshot_creation_status) {
787 ret = pre_create_hook();
791 case SCS_PRE_HOOK_RUNNING:
793 case SCS_PRE_HOOK_SUCCESS:
794 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
795 ret = create_snapshot(rsync_argv);
796 free_rsync_argv(rsync_argv);
800 case SCS_RSYNC_RUNNING:
802 case SCS_RSYNC_SUCCESS:
803 ret = post_create_hook();
807 case SCS_POST_HOOK_RUNNING:
815 static int com_run(void)
819 if (conf.dry_run_given) {
820 DSS_ERROR_LOG("dry_run not supported by this command\n");
823 ret = install_sighandler(SIGHUP);
826 compute_next_snapshot_time();
827 return select_loop();
830 static int com_prune(void)
833 struct snapshot_list sl;
834 struct disk_space ds;
836 ret = get_disk_space(".", &ds);
841 dss_get_snapshot_list(&sl);
842 ret = remove_outdated_snapshot(&sl);
843 free_snapshot_list(&sl);
848 ret = wait_for_rm_process();
853 dss_get_snapshot_list(&sl);
854 ret = remove_redundant_snapshot(&sl);
855 free_snapshot_list(&sl);
860 ret = wait_for_rm_process();
869 static int com_create(void)
874 if (conf.dry_run_given) {
877 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
878 for (i = 0; rsync_argv[i]; i++) {
880 msg = make_message("%s%s%s", tmp? tmp : "",
881 tmp? " " : "", rsync_argv[i]);
884 free_rsync_argv(rsync_argv);
885 dss_msg("%s\n", msg);
889 ret = pre_create_hook();
892 if (pre_create_hook_pid) {
893 ret = wait_for_process(pre_create_hook_pid, &status);
896 ret = handle_pre_create_hook_exit(status);
900 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
901 ret = create_snapshot(rsync_argv);
904 ret = wait_for_process(rsync_pid, &status);
907 ret = handle_rsync_exit(status);
911 if (post_create_hook_pid)
912 ret = wait_for_process(post_create_hook_pid, &status);
914 free_rsync_argv(rsync_argv);
918 static int com_ls(void)
921 struct snapshot_list sl;
924 dss_get_snapshot_list(&sl);
925 FOR_EACH_SNAPSHOT(s, i, &sl)
926 dss_msg("%u\t%s\n", s->interval, s->name);
927 free_snapshot_list(&sl);
931 static void setup_signal_handling(void)
935 DSS_INFO_LOG("setting up signal handlers\n");
936 signal_pipe = signal_init(); /* always successful */
937 ret = install_sighandler(SIGINT);
940 ret = install_sighandler(SIGTERM);
943 ret = install_sighandler(SIGCHLD);
948 DSS_EMERG_LOG("could not install signal handlers\n");
953 * The main function of dss.
955 * \param argc Usual argument count.
956 * \param argv Usual argument vector.
958 int main(int argc, char **argv)
961 struct cmdline_parser_params params = {
965 .check_ambiguity = 0,
969 cmdline_parser_ext(argc, argv, &conf, ¶ms); /* aborts on errors */
970 parse_config_file(0);
972 if (conf.daemon_given)
974 change_to_dest_dir();
975 setup_signal_handling();
976 ret = call_command_handler();
978 DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
979 exit(ret >= 0? EXIT_SUCCESS : EXIT_FAILURE);