19 #include "gcc-compat.h"
33 static struct gengetopt_args_info conf;
35 static int signal_pipe;
37 /** Process id of current rsync process. */
38 static pid_t rsync_pid;
39 /** Whether the rsync process is currently stopped */
40 static int rsync_stopped;
41 /** Process id of current rm process. */
43 /** When the next snapshot is due. */
44 struct timeval next_snapshot_time;
45 /** The pid of the pre-create hook. */
46 pid_t pre_create_hook_pid;
47 /** The pid of the post-create hook. */
48 pid_t post_create_hook_pid;
49 /* Creation time of the snapshot currently being created. */
50 int64_t current_snapshot_creation_time;
52 static char *path_to_last_complete_snapshot;
54 static unsigned snapshot_creation_status;
60 /* a litte cpp magic helps to DRY */
66 #define COMMAND(x) int com_ ##x(void);
69 #define COMMAND(x) if (conf.x ##_given) return com_ ##x();
70 int call_command_handler(void)
73 DSS_EMERG_LOG("BUG: did not find command handler\n");
79 __printf_2_3 void dss_log(int ll, const char* fmt,...)
87 if (ll < conf.loglevel_arg)
89 outfd = logfile? logfile : stderr;
92 strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
93 fprintf(outfd, "%s ", str);
94 if (conf.loglevel_arg <= INFO)
95 fprintf(outfd, "%i: ", ll);
97 vfprintf(outfd, fmt, argp);
102 * Print a message either to stdout or to the log file.
104 __printf_1_2 void dss_msg(const char* fmt,...)
106 FILE *outfd = conf.daemon_given? logfile : stdout;
109 vfprintf(outfd, fmt, argp);
113 /* TODO: Also consider number of inodes. */
114 int disk_space_low(void)
116 struct disk_space ds;
117 int ret = get_disk_space(".", &ds);
121 if (conf.min_free_mb_arg)
122 if (ds.free_mb < conf.min_free_mb_arg)
124 if (conf.min_free_percent_arg)
125 if (ds.percent_free < conf.min_free_percent_arg)
130 void dss_get_snapshot_list(struct snapshot_list *sl)
132 get_snapshot_list(sl, conf.unit_interval_arg, conf.num_intervals_arg);
135 void compute_next_snapshot_time(void)
137 struct timeval now, unit_interval = {.tv_sec = 24 * 3600 * conf.unit_interval_arg},
140 unsigned wanted = desired_number_of_snapshots(0, conf.num_intervals_arg),
141 num_complete_snapshots = 0;
143 struct snapshot *s = NULL;
144 struct snapshot_list sl;
146 assert(snapshot_creation_status == SCS_READY);
147 current_snapshot_creation_time = 0;
148 dss_get_snapshot_list(&sl);
149 FOR_EACH_SNAPSHOT(s, i, &sl) {
150 if (!(s->flags & SS_COMPLETE))
152 num_complete_snapshots++;
153 x += s->completion_time - s->creation_time;
156 if (num_complete_snapshots)
157 x /= num_complete_snapshots; /* avg time to create one snapshot */
158 x *= wanted; /* time to create all snapshots in interval 0 */
161 ret = tv_diff(&unit_interval, &tmp, &diff); /* total sleep time per unit interval */
162 gettimeofday(&now, NULL);
165 tv_divide(wanted, &diff, &tmp); /* sleep time betweeen two snapshots */
166 diff.tv_sec = s->completion_time;
168 tv_add(&diff, &tmp, &next_snapshot_time);
169 if (tv_diff(&now, &next_snapshot_time, NULL) < 0)
172 next_snapshot_time = now;
173 next_snapshot_time.tv_sec += 60;
175 free_snapshot_list(&sl);
179 int remove_snapshot(struct snapshot *s)
181 int fds[3] = {0, 0, 0};
183 char *new_name = being_deleted_name(s);
184 int ret = dss_rename(s->name, new_name);
185 char *argv[] = {"rm", "-rf", new_name, NULL};
189 DSS_NOTICE_LOG("removing %s (interval = %i)\n", s->name, s->interval);
190 ret = dss_exec(&rm_pid, argv[0], argv, fds);
197 * return: 0: no redundant snapshots, 1: rm process started, negative: error
199 int remove_redundant_snapshot(struct snapshot_list *sl)
201 int ret, i, interval;
203 unsigned missing = 0;
205 DSS_INFO_LOG("looking for intervals containing too many snapshots\n");
206 for (interval = conf.num_intervals_arg - 1; interval >= 0; interval--) {
207 unsigned keep = desired_number_of_snapshots(interval, conf.num_intervals_arg);
208 unsigned num = sl->interval_count[interval];
209 struct snapshot *victim = NULL, *prev = NULL;
210 int64_t score = LONG_MAX;
213 missing += keep - num;
214 // DSS_DEBUG_LOG("interval %i: keep: %u, have: %u, missing: %u\n",
215 // interval, keep, num, missing);
216 if (keep + missing >= num)
218 /* redundant snapshot in this interval, pick snapshot with lowest score */
219 FOR_EACH_SNAPSHOT(s, i, sl) {
222 //DSS_DEBUG_LOG("checking %s\n", s->name);
223 if (s->interval > interval) {
227 if (s->interval < interval)
235 /* check if s is a better victim */
236 this_score = s->creation_time - prev->creation_time;
237 assert(this_score >= 0);
238 //DSS_DEBUG_LOG("%s: score %lli\n", s->name, (long long)score);
239 if (this_score < score) {
246 if (conf.dry_run_given) {
247 dss_msg("%s would be removed (interval = %i)\n",
248 victim->name, victim->interval);
251 ret = remove_snapshot(victim);
252 return ret < 0? ret : 1;
257 int remove_outdated_snapshot(struct snapshot_list *sl)
262 DSS_INFO_LOG("looking for snapshots belonging to intervals greater than %d\n",
263 conf.num_intervals_arg);
264 FOR_EACH_SNAPSHOT(s, i, sl) {
265 if (s->interval <= conf.num_intervals_arg)
267 if (conf.dry_run_given) {
268 dss_msg("%s would be removed (interval = %i)\n",
269 s->name, s->interval);
272 ret = remove_snapshot(s);
280 int remove_oldest_snapshot(struct snapshot_list *sl)
282 struct snapshot *s = get_oldest_snapshot(sl);
284 if (!s) /* no snapshot found */
286 DSS_INFO_LOG("oldest snapshot: %s\n", s->name);
287 if (s->creation_time == current_snapshot_creation_time)
288 return 0; /* do not remove the snapshot currently being created */
289 return remove_snapshot(s);
292 int rename_incomplete_snapshot(int64_t start)
297 free(path_to_last_complete_snapshot);
298 ret = complete_name(start, get_current_time(),
299 &path_to_last_complete_snapshot);
302 old_name = incomplete_name(start);
303 ret = dss_rename(old_name, path_to_last_complete_snapshot);
305 DSS_NOTICE_LOG("%s -> %s\n", old_name,
306 path_to_last_complete_snapshot);
311 int try_to_free_disk_space(int low_disk_space)
314 struct snapshot_list sl;
316 dss_get_snapshot_list(&sl);
317 ret = remove_outdated_snapshot(&sl);
318 if (ret) /* error, or we are removing something */
320 /* no outdated snapshot */
321 ret = remove_redundant_snapshot(&sl);
327 DSS_WARNING_LOG("disk space low and nothing obvious to remove\n");
328 ret = remove_oldest_snapshot(&sl);
331 DSS_CRIT_LOG("uhuhu: not enough disk space for a single snapshot\n");
334 free_snapshot_list(&sl);
338 int pre_create_hook(void)
340 int ret, fds[3] = {0, 0, 0};
342 if (!conf.pre_create_hook_given) {
343 snapshot_creation_status = SCS_PRE_HOOK_SUCCESS;
346 DSS_NOTICE_LOG("executing %s\n", conf.pre_create_hook_arg);
347 ret = dss_exec_cmdline_pid(&pre_create_hook_pid,
348 conf.pre_create_hook_arg, fds);
351 snapshot_creation_status = SCS_PRE_HOOK_RUNNING;
355 int post_create_hook(void)
357 int ret, fds[3] = {0, 0, 0};
360 if (!conf.post_create_hook_given) {
361 snapshot_creation_status = SCS_READY;
362 compute_next_snapshot_time();
365 cmd = make_message("%s %s", conf.post_create_hook_arg,
366 path_to_last_complete_snapshot);
367 DSS_NOTICE_LOG("executing %s\n", cmd);
368 ret = dss_exec_cmdline_pid(&post_create_hook_pid, cmd, fds);
372 snapshot_creation_status = SCS_POST_HOOK_RUNNING;
376 void kill_process(pid_t pid)
380 DSS_WARNING_LOG("sending SIGTERM to pid %d\n", (int)pid);
384 void stop_rsync_process(void)
386 if (!rsync_pid || rsync_stopped)
388 kill(SIGSTOP, rsync_pid);
392 void restart_rsync_process(void)
394 if (!rsync_pid || !rsync_stopped)
396 kill (SIGCONT, rsync_pid);
402 * Print a log message about the exit status of a child.
404 void log_termination_msg(pid_t pid, int status)
406 if (WIFEXITED(status))
407 DSS_INFO_LOG("child %i exited. Exit status: %i\n", (int)pid,
408 WEXITSTATUS(status));
409 else if (WIFSIGNALED(status))
410 DSS_NOTICE_LOG("child %i was killed by signal %i\n", (int)pid,
413 DSS_WARNING_LOG("child %i terminated abormally\n", (int)pid);
416 int wait_for_process(pid_t pid, int *status)
420 DSS_DEBUG_LOG("Waiting for process %d to terminate\n", (int)pid);
425 FD_SET(signal_pipe, &rfds);
426 ret = dss_select(signal_pipe + 1, &rfds, NULL, NULL);
432 if (ret == SIGCHLD) {
433 ret = waitpid(pid, status, 0);
436 if (errno != EINTR) { /* error */
437 ret = -ERRNO_TO_DSS_ERROR(errno);
441 /* SIGINT or SIGTERM */
442 DSS_WARNING_LOG("sending SIGTERM to pid %d\n", (int)pid);
446 DSS_ERROR_LOG("failed to wait for process %d\n", (int)pid);
448 log_termination_msg(pid, *status);
451 int handle_rm_exit(int status)
454 if (!WIFEXITED(status))
455 return -E_INVOLUNTARY_EXIT;
456 if (WEXITSTATUS(status))
457 return -E_BAD_EXIT_CODE;
461 int wait_for_rm_process(void)
463 int status, ret = wait_for_process(rm_pid, &status);
467 return handle_rm_exit(status);
470 int handle_rsync_exit(int status)
474 if (!WIFEXITED(status)) {
475 DSS_ERROR_LOG("rsync process %d died involuntary\n", (int)rsync_pid);
476 ret = -E_INVOLUNTARY_EXIT;
477 snapshot_creation_status = SCS_READY;
478 compute_next_snapshot_time();
481 es = WEXITSTATUS(status);
482 if (es != 0 && es != 23 && es != 24) {
483 DSS_ERROR_LOG("rsync process %d returned %d\n", (int)rsync_pid, es);
484 ret = -E_BAD_EXIT_CODE;
485 snapshot_creation_status = SCS_READY;
486 compute_next_snapshot_time();
489 ret = rename_incomplete_snapshot(current_snapshot_creation_time);
492 snapshot_creation_status = SCS_RSYNC_SUCCESS;
499 int handle_pre_create_hook_exit(int status)
503 if (!WIFEXITED(status)) {
504 snapshot_creation_status = SCS_READY;
505 compute_next_snapshot_time();
506 ret = -E_INVOLUNTARY_EXIT;
509 es = WEXITSTATUS(status);
511 snapshot_creation_status = SCS_READY;
512 compute_next_snapshot_time();
513 ret = -E_BAD_EXIT_CODE;
516 snapshot_creation_status = SCS_PRE_HOOK_SUCCESS;
519 pre_create_hook_pid = 0;
523 int handle_sigchld(void)
526 int status, ret = reap_child(&pid, &status);
530 if (pid == rsync_pid)
531 return handle_rsync_exit(status);
533 return handle_rm_exit(status);
534 if (pid == pre_create_hook_pid)
535 return handle_pre_create_hook_exit(status);
536 if (pid == post_create_hook_pid) {
537 snapshot_creation_status = SCS_READY;
538 compute_next_snapshot_time();
541 DSS_EMERG_LOG("BUG: unknown process %d died\n", (int)pid);
546 int check_config(void)
548 if (conf.unit_interval_arg <= 0) {
549 DSS_ERROR_LOG("bad unit interval: %i\n", conf.unit_interval_arg);
550 return -E_INVALID_NUMBER;
552 DSS_DEBUG_LOG("unit interval: %i day(s)\n", conf.unit_interval_arg);
553 if (conf.num_intervals_arg <= 0) {
554 DSS_ERROR_LOG("bad number of intervals %i\n", conf.num_intervals_arg);
555 return -E_INVALID_NUMBER;
557 DSS_DEBUG_LOG("number of intervals: %i\n", conf.num_intervals_arg);
561 /* exits on errors */
562 void parse_config_file(int override)
567 char *old_logfile_arg = NULL;
568 int old_daemon_given = 0;
570 if (conf.config_file_given)
571 config_file = dss_strdup(conf.config_file_arg);
573 char *home = get_homedir();
574 config_file = make_message("%s/.dssrc", home);
577 if (override) { /* SIGHUP */
578 if (conf.logfile_given)
579 old_logfile_arg = dss_strdup(conf.logfile_arg);
580 old_daemon_given = conf.daemon_given;
583 ret = stat(config_file, &statbuf);
584 if (ret && conf.config_file_given) {
585 ret = -ERRNO_TO_DSS_ERROR(errno);
586 DSS_ERROR_LOG("failed to stat config file %s\n", config_file);
590 struct cmdline_parser_params params = {
591 .override = override,
596 cmdline_parser_config_file(config_file, &conf, ¶ms);
598 ret = check_config();
602 /* don't change daemon mode on SIGHUP */
603 conf.daemon_given = old_daemon_given;
606 if (conf.logfile_given)
607 free(old_logfile_arg);
608 else if (conf.daemon_given) { /* re-use old logfile */
609 conf.logfile_arg = old_logfile_arg;
610 conf.logfile_given = 1;
613 if (conf.logfile_given) {
614 logfile = open_log(conf.logfile_arg);
615 log_welcome(conf.loglevel_arg);
617 DSS_EMERG_LOG("loglevel: %d\n", conf.loglevel_arg);
618 // cmdline_parser_dump(logfile? logfile : stdout, &conf);
619 ret = dss_chdir(conf.dest_dir_arg);
624 DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
628 void handle_sighup(void)
630 DSS_NOTICE_LOG("SIGHUP\n");
631 parse_config_file(1);
634 void handle_signal(void)
636 int sig, ret = next_signal();
644 restart_rsync_process();
645 kill_process(rsync_pid);
646 kill_process(rm_pid);
653 ret = handle_sigchld();
658 DSS_ERROR_LOG("%s\n", dss_strerror(-ret));
661 void create_rsync_argv(char ***argv, int64_t *num)
663 char *logname, *newest;
665 struct snapshot_list sl;
667 dss_get_snapshot_list(&sl);
668 newest = name_of_newest_complete_snapshot(&sl);
669 free_snapshot_list(&sl);
671 *argv = dss_malloc((15 + conf.rsync_option_given) * sizeof(char *));
672 (*argv)[i++] = dss_strdup("rsync");
673 (*argv)[i++] = dss_strdup("-aq");
674 (*argv)[i++] = dss_strdup("--delete");
675 for (j = 0; j < conf.rsync_option_given; j++)
676 (*argv)[i++] = dss_strdup(conf.rsync_option_arg[j]);
678 DSS_INFO_LOG("using %s as reference snapshot\n", newest);
679 (*argv)[i++] = make_message("--link-dest=../%s", newest);
682 DSS_INFO_LOG("no previous snapshot found\n");
683 if (conf.exclude_patterns_given) {
684 (*argv)[i++] = dss_strdup("--exclude-from");
685 (*argv)[i++] = dss_strdup(conf.exclude_patterns_arg);
688 logname = dss_logname();
689 if (conf.remote_user_given && !strcmp(conf.remote_user_arg, logname))
690 (*argv)[i++] = dss_strdup(conf.source_dir_arg);
692 (*argv)[i++] = make_message("%s@%s:%s/", conf.remote_user_given?
693 conf.remote_user_arg : logname,
694 conf.remote_host_arg, conf.source_dir_arg);
696 *num = get_current_time();
697 (*argv)[i++] = incomplete_name(*num);
699 for (j = 0; j < i; j++)
700 DSS_DEBUG_LOG("argv[%d] = %s\n", j, (*argv)[j]);
703 void free_rsync_argv(char **argv)
706 for (i = 0; argv[i]; i++)
711 int create_snapshot(char **argv)
713 int ret, fds[3] = {0, 0, 0};
716 name = incomplete_name(current_snapshot_creation_time);
717 DSS_NOTICE_LOG("creating new snapshot %s\n", name);
719 ret = dss_exec(&rsync_pid, argv[0], argv, fds);
722 snapshot_creation_status = SCS_RSYNC_RUNNING;
726 int select_loop(void)
729 struct timeval tv = {.tv_sec = 0, .tv_usec = 0};
735 struct timeval now, *tvp = &tv;
738 tv.tv_sec = 60; /* check every 60 seconds for free disk space */
740 tvp = NULL; /* sleep until rm process dies */
742 FD_SET(signal_pipe, &rfds);
743 DSS_DEBUG_LOG("tvp: %p, tv_sec: %lu\n", tvp, (long unsigned) tv.tv_sec);
744 ret = dss_select(signal_pipe + 1, &rfds, NULL, tvp);
747 if (FD_ISSET(signal_pipe, &rfds))
751 ret = disk_space_low();
754 low_disk_space = ret;
755 ret = try_to_free_disk_space(low_disk_space);
759 stop_rsync_process();
762 restart_rsync_process();
763 gettimeofday(&now, NULL);
764 if (tv_diff(&next_snapshot_time, &now, &tv) > 0)
766 switch (snapshot_creation_status) {
768 ret = pre_create_hook();
772 case SCS_PRE_HOOK_RUNNING:
774 case SCS_PRE_HOOK_SUCCESS:
775 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
776 ret = create_snapshot(rsync_argv);
777 free_rsync_argv(rsync_argv);
781 case SCS_RSYNC_RUNNING:
783 case SCS_RSYNC_SUCCESS:
784 ret = post_create_hook();
788 case SCS_POST_HOOK_RUNNING:
800 if (conf.dry_run_given) {
801 DSS_ERROR_LOG("dry_run not supported by this command\n");
804 ret = install_sighandler(SIGHUP);
807 compute_next_snapshot_time();
808 return select_loop();
814 struct snapshot_list sl;
815 struct disk_space ds;
817 ret = get_disk_space(".", &ds);
822 dss_get_snapshot_list(&sl);
823 ret = remove_outdated_snapshot(&sl);
824 free_snapshot_list(&sl);
829 ret = wait_for_rm_process();
834 dss_get_snapshot_list(&sl);
835 ret = remove_redundant_snapshot(&sl);
836 free_snapshot_list(&sl);
841 ret = wait_for_rm_process();
855 if (conf.dry_run_given) {
858 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
859 for (i = 0; rsync_argv[i]; i++) {
861 msg = make_message("%s%s%s", tmp? tmp : "",
862 tmp? " " : "", rsync_argv[i]);
865 free_rsync_argv(rsync_argv);
866 dss_msg("%s\n", msg);
870 ret = pre_create_hook();
873 if (pre_create_hook_pid) {
874 ret = wait_for_process(pre_create_hook_pid, &status);
877 ret = handle_pre_create_hook_exit(status);
881 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
882 ret = create_snapshot(rsync_argv);
885 ret = wait_for_process(rsync_pid, &status);
888 ret = handle_rsync_exit(status);
892 if (post_create_hook_pid)
893 ret = wait_for_process(post_create_hook_pid, &status);
895 free_rsync_argv(rsync_argv);
902 struct snapshot_list sl;
905 dss_get_snapshot_list(&sl);
906 FOR_EACH_SNAPSHOT(s, i, &sl)
907 dss_msg("%u\t%s\n", s->interval, s->name);
908 free_snapshot_list(&sl);
912 static void setup_signal_handling(void)
916 DSS_INFO_LOG("setting up signal handlers\n");
917 signal_pipe = signal_init(); /* always successful */
918 ret = install_sighandler(SIGINT);
921 ret = install_sighandler(SIGTERM);
924 ret = install_sighandler(SIGCHLD);
929 DSS_EMERG_LOG("could not install signal handlers\n");
934 int main(int argc, char **argv)
937 struct cmdline_parser_params params = {
944 cmdline_parser_ext(argc, argv, &conf, ¶ms); /* aborts on errors */
945 parse_config_file(0);
947 if (conf.daemon_given)
949 setup_signal_handling();
950 ret = call_command_handler();
952 DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
953 exit(ret >= 0? EXIT_SUCCESS : EXIT_FAILURE);