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)
139 static void dss_get_snapshot_list(struct snapshot_list *sl)
141 get_snapshot_list(sl, conf.unit_interval_arg, conf.num_intervals_arg);
144 static void compute_next_snapshot_time(void)
146 struct timeval now, unit_interval = {.tv_sec = 24 * 3600 * conf.unit_interval_arg},
149 unsigned wanted = desired_number_of_snapshots(0, conf.num_intervals_arg),
150 num_complete_snapshots = 0;
152 struct snapshot *s = NULL;
153 struct snapshot_list sl;
155 assert(snapshot_creation_status == SCS_READY);
156 current_snapshot_creation_time = 0;
157 dss_get_snapshot_list(&sl);
158 FOR_EACH_SNAPSHOT(s, i, &sl) {
159 if (!(s->flags & SS_COMPLETE))
161 num_complete_snapshots++;
162 x += s->completion_time - s->creation_time;
165 if (num_complete_snapshots)
166 x /= num_complete_snapshots; /* avg time to create one snapshot */
167 x *= wanted; /* time to create all snapshots in interval 0 */
170 ret = tv_diff(&unit_interval, &tmp, &diff); /* total sleep time per unit interval */
171 gettimeofday(&now, NULL);
174 tv_divide(wanted, &diff, &tmp); /* sleep time betweeen two snapshots */
175 diff.tv_sec = s->completion_time;
177 tv_add(&diff, &tmp, &next_snapshot_time);
178 if (tv_diff(&now, &next_snapshot_time, NULL) < 0)
181 next_snapshot_time = now;
182 next_snapshot_time.tv_sec += 60;
184 free_snapshot_list(&sl);
188 static int remove_snapshot(struct snapshot *s)
190 int fds[3] = {0, 0, 0};
192 char *new_name = being_deleted_name(s);
193 int ret = dss_rename(s->name, new_name);
194 char *argv[] = {"rm", "-rf", new_name, NULL};
198 DSS_NOTICE_LOG("removing %s (interval = %i)\n", s->name, s->interval);
199 ret = dss_exec(&rm_pid, argv[0], argv, fds);
206 * return: 0: no redundant snapshots, 1: rm process started, negative: error
208 static int remove_redundant_snapshot(struct snapshot_list *sl)
210 int ret, i, interval;
212 unsigned missing = 0;
214 DSS_INFO_LOG("looking for intervals containing too many snapshots\n");
215 for (interval = conf.num_intervals_arg - 1; interval >= 0; interval--) {
216 unsigned keep = desired_number_of_snapshots(interval, conf.num_intervals_arg);
217 unsigned num = sl->interval_count[interval];
218 struct snapshot *victim = NULL, *prev = NULL;
219 int64_t score = LONG_MAX;
222 missing += keep - num;
223 // DSS_DEBUG_LOG("interval %i: keep: %u, have: %u, missing: %u\n",
224 // interval, keep, num, missing);
225 if (keep + missing >= num)
227 /* redundant snapshot in this interval, pick snapshot with lowest score */
228 FOR_EACH_SNAPSHOT(s, i, sl) {
231 //DSS_DEBUG_LOG("checking %s\n", s->name);
232 if (s->interval > interval) {
236 if (s->interval < interval)
244 /* check if s is a better victim */
245 this_score = s->creation_time - prev->creation_time;
246 assert(this_score >= 0);
247 //DSS_DEBUG_LOG("%s: score %lli\n", s->name, (long long)score);
248 if (this_score < score) {
255 if (conf.dry_run_given) {
256 dss_msg("%s would be removed (interval = %i)\n",
257 victim->name, victim->interval);
260 ret = remove_snapshot(victim);
261 return ret < 0? ret : 1;
266 static int remove_outdated_snapshot(struct snapshot_list *sl)
271 DSS_INFO_LOG("looking for snapshots belonging to intervals greater than %d\n",
272 conf.num_intervals_arg);
273 FOR_EACH_SNAPSHOT(s, i, sl) {
274 if (s->interval <= conf.num_intervals_arg)
276 if (conf.dry_run_given) {
277 dss_msg("%s would be removed (interval = %i)\n",
278 s->name, s->interval);
281 ret = remove_snapshot(s);
289 static int remove_oldest_snapshot(struct snapshot_list *sl)
291 struct snapshot *s = get_oldest_snapshot(sl);
293 if (!s) /* no snapshot found */
295 DSS_INFO_LOG("oldest snapshot: %s\n", s->name);
296 if (s->creation_time == current_snapshot_creation_time)
297 return 0; /* do not remove the snapshot currently being created */
298 return remove_snapshot(s);
301 static int rename_incomplete_snapshot(int64_t start)
306 free(path_to_last_complete_snapshot);
307 ret = complete_name(start, get_current_time(),
308 &path_to_last_complete_snapshot);
311 old_name = incomplete_name(start);
312 ret = dss_rename(old_name, path_to_last_complete_snapshot);
314 DSS_NOTICE_LOG("%s -> %s\n", old_name,
315 path_to_last_complete_snapshot);
320 static int try_to_free_disk_space(int low_disk_space)
323 struct snapshot_list sl;
325 dss_get_snapshot_list(&sl);
326 ret = remove_outdated_snapshot(&sl);
327 if (ret) /* error, or we are removing something */
329 /* no outdated snapshot */
330 ret = remove_redundant_snapshot(&sl);
336 DSS_WARNING_LOG("disk space low and nothing obvious to remove\n");
337 ret = remove_oldest_snapshot(&sl);
340 DSS_CRIT_LOG("uhuhu: not enough disk space for a single snapshot\n");
343 free_snapshot_list(&sl);
347 static int pre_create_hook(void)
349 int ret, fds[3] = {0, 0, 0};
351 if (!conf.pre_create_hook_given) {
352 snapshot_creation_status = SCS_PRE_HOOK_SUCCESS;
355 DSS_NOTICE_LOG("executing %s\n", conf.pre_create_hook_arg);
356 ret = dss_exec_cmdline_pid(&pre_create_hook_pid,
357 conf.pre_create_hook_arg, fds);
360 snapshot_creation_status = SCS_PRE_HOOK_RUNNING;
364 static int post_create_hook(void)
366 int ret, fds[3] = {0, 0, 0};
369 if (!conf.post_create_hook_given) {
370 snapshot_creation_status = SCS_READY;
371 compute_next_snapshot_time();
374 cmd = make_message("%s %s", conf.post_create_hook_arg,
375 path_to_last_complete_snapshot);
376 DSS_NOTICE_LOG("executing %s\n", cmd);
377 ret = dss_exec_cmdline_pid(&post_create_hook_pid, cmd, fds);
381 snapshot_creation_status = SCS_POST_HOOK_RUNNING;
385 static void kill_process(pid_t pid)
389 DSS_WARNING_LOG("sending SIGTERM to pid %d\n", (int)pid);
393 static void stop_rsync_process(void)
395 if (!rsync_pid || rsync_stopped)
397 kill(SIGSTOP, rsync_pid);
401 static void restart_rsync_process(void)
403 if (!rsync_pid || !rsync_stopped)
405 kill (SIGCONT, rsync_pid);
411 * Print a log message about the exit status of a child.
413 static void log_termination_msg(pid_t pid, int status)
415 if (WIFEXITED(status))
416 DSS_INFO_LOG("child %i exited. Exit status: %i\n", (int)pid,
417 WEXITSTATUS(status));
418 else if (WIFSIGNALED(status))
419 DSS_NOTICE_LOG("child %i was killed by signal %i\n", (int)pid,
422 DSS_WARNING_LOG("child %i terminated abormally\n", (int)pid);
425 static int wait_for_process(pid_t pid, int *status)
429 DSS_DEBUG_LOG("Waiting for process %d to terminate\n", (int)pid);
434 FD_SET(signal_pipe, &rfds);
435 ret = dss_select(signal_pipe + 1, &rfds, NULL, NULL);
441 if (ret == SIGCHLD) {
442 ret = waitpid(pid, status, 0);
445 if (errno != EINTR) { /* error */
446 ret = -ERRNO_TO_DSS_ERROR(errno);
450 /* SIGINT or SIGTERM */
451 DSS_WARNING_LOG("sending SIGTERM to pid %d\n", (int)pid);
455 DSS_ERROR_LOG("failed to wait for process %d\n", (int)pid);
457 log_termination_msg(pid, *status);
461 static int handle_rm_exit(int status)
464 if (!WIFEXITED(status))
465 return -E_INVOLUNTARY_EXIT;
466 if (WEXITSTATUS(status))
467 return -E_BAD_EXIT_CODE;
471 static int wait_for_rm_process(void)
473 int status, ret = wait_for_process(rm_pid, &status);
477 return handle_rm_exit(status);
480 static int handle_rsync_exit(int status)
484 if (!WIFEXITED(status)) {
485 DSS_ERROR_LOG("rsync process %d died involuntary\n", (int)rsync_pid);
486 ret = -E_INVOLUNTARY_EXIT;
487 snapshot_creation_status = SCS_READY;
488 compute_next_snapshot_time();
491 es = WEXITSTATUS(status);
492 if (es != 0 && es != 23 && es != 24) {
493 DSS_ERROR_LOG("rsync process %d returned %d\n", (int)rsync_pid, es);
494 ret = -E_BAD_EXIT_CODE;
495 snapshot_creation_status = SCS_READY;
496 compute_next_snapshot_time();
499 ret = rename_incomplete_snapshot(current_snapshot_creation_time);
502 snapshot_creation_status = SCS_RSYNC_SUCCESS;
509 static int handle_pre_create_hook_exit(int status)
513 if (!WIFEXITED(status)) {
514 snapshot_creation_status = SCS_READY;
515 compute_next_snapshot_time();
516 ret = -E_INVOLUNTARY_EXIT;
519 es = WEXITSTATUS(status);
521 snapshot_creation_status = SCS_READY;
522 compute_next_snapshot_time();
523 ret = -E_BAD_EXIT_CODE;
526 snapshot_creation_status = SCS_PRE_HOOK_SUCCESS;
529 pre_create_hook_pid = 0;
533 static int handle_sigchld(void)
536 int status, ret = reap_child(&pid, &status);
540 if (pid == rsync_pid)
541 return handle_rsync_exit(status);
543 return handle_rm_exit(status);
544 if (pid == pre_create_hook_pid)
545 return handle_pre_create_hook_exit(status);
546 if (pid == post_create_hook_pid) {
547 snapshot_creation_status = SCS_READY;
548 compute_next_snapshot_time();
551 DSS_EMERG_LOG("BUG: unknown process %d died\n", (int)pid);
555 static int check_config(void)
557 if (conf.unit_interval_arg <= 0) {
558 DSS_ERROR_LOG("bad unit interval: %i\n", conf.unit_interval_arg);
559 return -E_INVALID_NUMBER;
561 DSS_DEBUG_LOG("unit interval: %i day(s)\n", conf.unit_interval_arg);
562 if (conf.num_intervals_arg <= 0) {
563 DSS_ERROR_LOG("bad number of intervals %i\n", conf.num_intervals_arg);
564 return -E_INVALID_NUMBER;
566 DSS_DEBUG_LOG("number of intervals: %i\n", conf.num_intervals_arg);
570 /* exits on errors */
571 static void parse_config_file(int override)
576 char *old_logfile_arg = NULL;
577 int old_daemon_given = 0;
579 if (conf.config_file_given)
580 config_file = dss_strdup(conf.config_file_arg);
582 char *home = get_homedir();
583 config_file = make_message("%s/.dssrc", home);
586 if (override) { /* SIGHUP */
587 if (conf.logfile_given)
588 old_logfile_arg = dss_strdup(conf.logfile_arg);
589 old_daemon_given = conf.daemon_given;
592 ret = stat(config_file, &statbuf);
593 if (ret && conf.config_file_given) {
594 ret = -ERRNO_TO_DSS_ERROR(errno);
595 DSS_ERROR_LOG("failed to stat config file %s\n", config_file);
599 struct cmdline_parser_params params = {
600 .override = override,
605 cmdline_parser_config_file(config_file, &conf, ¶ms);
607 ret = check_config();
611 /* don't change daemon mode on SIGHUP */
612 conf.daemon_given = old_daemon_given;
615 if (conf.logfile_given)
616 free(old_logfile_arg);
617 else if (conf.daemon_given) { /* re-use old logfile */
618 conf.logfile_arg = old_logfile_arg;
619 conf.logfile_given = 1;
622 if (conf.logfile_given) {
623 logfile = open_log(conf.logfile_arg);
624 log_welcome(conf.loglevel_arg);
626 DSS_EMERG_LOG("loglevel: %d\n", conf.loglevel_arg);
627 // cmdline_parser_dump(logfile? logfile : stdout, &conf);
628 ret = dss_chdir(conf.dest_dir_arg);
633 DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
637 static void handle_sighup(void)
639 DSS_NOTICE_LOG("SIGHUP\n");
640 parse_config_file(1);
643 static void handle_signal(void)
645 int sig, ret = next_signal();
653 restart_rsync_process();
654 kill_process(rsync_pid);
655 kill_process(rm_pid);
662 ret = handle_sigchld();
667 DSS_ERROR_LOG("%s\n", dss_strerror(-ret));
670 static void create_rsync_argv(char ***argv, int64_t *num)
672 char *logname, *newest;
674 struct snapshot_list sl;
676 dss_get_snapshot_list(&sl);
677 newest = name_of_newest_complete_snapshot(&sl);
678 free_snapshot_list(&sl);
680 *argv = dss_malloc((15 + conf.rsync_option_given) * sizeof(char *));
681 (*argv)[i++] = dss_strdup("rsync");
682 (*argv)[i++] = dss_strdup("-aq");
683 (*argv)[i++] = dss_strdup("--delete");
684 for (j = 0; j < conf.rsync_option_given; j++)
685 (*argv)[i++] = dss_strdup(conf.rsync_option_arg[j]);
687 DSS_INFO_LOG("using %s as reference snapshot\n", newest);
688 (*argv)[i++] = make_message("--link-dest=../%s", newest);
691 DSS_INFO_LOG("no previous snapshot found\n");
692 if (conf.exclude_patterns_given) {
693 (*argv)[i++] = dss_strdup("--exclude-from");
694 (*argv)[i++] = dss_strdup(conf.exclude_patterns_arg);
697 logname = dss_logname();
698 if (conf.remote_user_given && !strcmp(conf.remote_user_arg, logname))
699 (*argv)[i++] = dss_strdup(conf.source_dir_arg);
701 (*argv)[i++] = make_message("%s@%s:%s/", conf.remote_user_given?
702 conf.remote_user_arg : logname,
703 conf.remote_host_arg, conf.source_dir_arg);
705 *num = get_current_time();
706 (*argv)[i++] = incomplete_name(*num);
708 for (j = 0; j < i; j++)
709 DSS_DEBUG_LOG("argv[%d] = %s\n", j, (*argv)[j]);
712 static void free_rsync_argv(char **argv)
715 for (i = 0; argv[i]; i++)
720 static int create_snapshot(char **argv)
722 int ret, fds[3] = {0, 0, 0};
725 name = incomplete_name(current_snapshot_creation_time);
726 DSS_NOTICE_LOG("creating new snapshot %s\n", name);
728 ret = dss_exec(&rsync_pid, argv[0], argv, fds);
731 snapshot_creation_status = SCS_RSYNC_RUNNING;
735 static int select_loop(void)
738 struct timeval tv = {.tv_sec = 0, .tv_usec = 0};
744 struct timeval now, *tvp = &tv;
747 tv.tv_sec = 60; /* check every 60 seconds for free disk space */
749 tvp = NULL; /* sleep until rm process dies */
751 FD_SET(signal_pipe, &rfds);
752 DSS_DEBUG_LOG("tvp: %p, tv_sec: %lu\n", tvp, (long unsigned) tv.tv_sec);
753 ret = dss_select(signal_pipe + 1, &rfds, NULL, tvp);
756 if (FD_ISSET(signal_pipe, &rfds))
760 ret = disk_space_low();
763 low_disk_space = ret;
764 ret = try_to_free_disk_space(low_disk_space);
768 stop_rsync_process();
771 restart_rsync_process();
772 gettimeofday(&now, NULL);
773 if (tv_diff(&next_snapshot_time, &now, &tv) > 0)
775 switch (snapshot_creation_status) {
777 ret = pre_create_hook();
781 case SCS_PRE_HOOK_RUNNING:
783 case SCS_PRE_HOOK_SUCCESS:
784 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
785 ret = create_snapshot(rsync_argv);
786 free_rsync_argv(rsync_argv);
790 case SCS_RSYNC_RUNNING:
792 case SCS_RSYNC_SUCCESS:
793 ret = post_create_hook();
797 case SCS_POST_HOOK_RUNNING:
805 static int com_run(void)
809 if (conf.dry_run_given) {
810 DSS_ERROR_LOG("dry_run not supported by this command\n");
813 ret = install_sighandler(SIGHUP);
816 compute_next_snapshot_time();
817 return select_loop();
820 static int com_prune(void)
823 struct snapshot_list sl;
824 struct disk_space ds;
826 ret = get_disk_space(".", &ds);
831 dss_get_snapshot_list(&sl);
832 ret = remove_outdated_snapshot(&sl);
833 free_snapshot_list(&sl);
838 ret = wait_for_rm_process();
843 dss_get_snapshot_list(&sl);
844 ret = remove_redundant_snapshot(&sl);
845 free_snapshot_list(&sl);
850 ret = wait_for_rm_process();
859 static int com_create(void)
864 if (conf.dry_run_given) {
867 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
868 for (i = 0; rsync_argv[i]; i++) {
870 msg = make_message("%s%s%s", tmp? tmp : "",
871 tmp? " " : "", rsync_argv[i]);
874 free_rsync_argv(rsync_argv);
875 dss_msg("%s\n", msg);
879 ret = pre_create_hook();
882 if (pre_create_hook_pid) {
883 ret = wait_for_process(pre_create_hook_pid, &status);
886 ret = handle_pre_create_hook_exit(status);
890 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
891 ret = create_snapshot(rsync_argv);
894 ret = wait_for_process(rsync_pid, &status);
897 ret = handle_rsync_exit(status);
901 if (post_create_hook_pid)
902 ret = wait_for_process(post_create_hook_pid, &status);
904 free_rsync_argv(rsync_argv);
908 static int com_ls(void)
911 struct snapshot_list sl;
914 dss_get_snapshot_list(&sl);
915 FOR_EACH_SNAPSHOT(s, i, &sl)
916 dss_msg("%u\t%s\n", s->interval, s->name);
917 free_snapshot_list(&sl);
921 static void setup_signal_handling(void)
925 DSS_INFO_LOG("setting up signal handlers\n");
926 signal_pipe = signal_init(); /* always successful */
927 ret = install_sighandler(SIGINT);
930 ret = install_sighandler(SIGTERM);
933 ret = install_sighandler(SIGCHLD);
938 DSS_EMERG_LOG("could not install signal handlers\n");
943 * The main function of dss.
945 * \param argc Usual argument count.
946 * \param argv Usual argument vector.
948 int main(int argc, char **argv)
951 struct cmdline_parser_params params = {
958 cmdline_parser_ext(argc, argv, &conf, ¶ms); /* aborts on errors */
959 parse_config_file(0);
961 if (conf.daemon_given)
963 setup_signal_handling();
964 ret = call_command_handler();
966 DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
967 exit(ret >= 0? EXIT_SUCCESS : EXIT_FAILURE);