19 #include "gcc-compat.h"
32 struct gengetopt_args_info conf;
33 char *dss_error_txt = NULL;
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 /* Creation time of the snapshot currently being created. */
46 int64_t current_snapshot_creation_time;
52 /* a litte cpp magic helps to DRY */
58 #define COMMAND(x) int com_ ##x(void);
61 #define COMMAND(x) if (conf.x ##_given) return com_ ##x();
62 int call_command_handler(void)
65 DSS_EMERG_LOG("BUG: did not find command handler\n");
72 * complete, not being deleted: 1204565370-1204565371.Sun_Mar_02_2008_14_33-Sun_Mar_02_2008_14_43
73 * complete, being deleted: 1204565370-1204565371.being_deleted
74 * incomplete, not being deleted: 1204565370-incomplete
75 * incomplete, being deleted: 1204565370-incomplete.being_deleted
77 enum snapshot_status_flags {
78 /** The rsync process terminated successfully. */
80 /** The rm process is running to remove this snapshot. */
86 int64_t creation_time;
87 int64_t completion_time;
88 enum snapshot_status_flags flags;
93 * An edge snapshot is either the oldest one or the newest one.
95 * We need to find either of them occasionally: The create code
96 * needs to know the newest snapshot because that is the one
97 * used as the link destination dir. The pruning code needs to
98 * find the oldest one in case disk space becomes low.
100 struct edge_snapshot_data {
102 struct snapshot snap;
105 __printf_2_3 void dss_log(int ll, const char* fmt,...)
113 if (ll < conf.loglevel_arg)
115 outfd = logfile? logfile : stderr;
118 strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
119 fprintf(outfd, "%s ", str);
120 if (conf.loglevel_arg <= INFO)
121 fprintf(outfd, "%i: ", ll);
123 vfprintf(outfd, fmt, argp);
128 * Print a message either to stdout or to the log file.
130 __printf_1_2 void dss_msg(const char* fmt,...)
132 FILE *outfd = conf.daemon_given? logfile : stdout;
135 vfprintf(outfd, fmt, argp);
140 * Return the desired number of snapshots of an interval.
142 unsigned num_snapshots(int interval)
146 assert(interval >= 0);
148 if (interval >= conf.num_intervals_arg)
150 n = conf.num_intervals_arg - interval - 1;
154 /* return: Whether dirname is a snapshot directory (0: no, 1: yes) */
155 int is_snapshot(const char *dirname, int64_t now, struct snapshot *s)
158 char *dash, *dot, *tmp;
162 dash = strchr(dirname, '-');
163 if (!dash || !dash[1] || dash == dirname)
165 for (i = 0; dirname[i] != '-'; i++)
166 if (!isdigit(dirname[i]))
168 tmp = dss_strdup(dirname);
170 ret = dss_atoi64(tmp, &num);
179 s->creation_time = num;
180 //DSS_DEBUG_LOG("%s start time: %lli\n", dirname, (long long)s->creation_time);
181 s->interval = (long long) ((now - s->creation_time)
182 / conf.unit_interval_arg / 24 / 3600);
183 if (!strcmp(dash + 1, "incomplete")) {
184 s->completion_time = -1;
185 s->flags = 0; /* neither complete, nor being deleted */
188 if (!strcmp(dash + 1, "incomplete.being_deleted")) {
189 s->completion_time = -1;
190 s->flags = SS_BEING_DELETED; /* mot cpmplete, being deleted */
194 dot = strchr(tmp, '.');
195 if (!dot || !dot[1] || dot == tmp)
197 for (i = 0; tmp[i] != '.'; i++)
198 if (!isdigit(tmp[i]))
200 tmp = dss_strdup(dash + 1);
202 ret = dss_atoi64(tmp, &num);
210 s->completion_time = num;
211 s->flags = SS_COMPLETE;
212 if (!strcmp(dot + 1, "being_deleted"))
213 s->flags |= SS_BEING_DELETED;
215 s->name = dss_strdup(dirname);
219 int64_t get_current_time(void)
223 DSS_DEBUG_LOG("now: %lli\n", (long long) now);
227 char *incomplete_name(int64_t start)
229 return make_message("%lli-incomplete", (long long)start);
232 char *being_deleted_name(struct snapshot *s)
234 if (s->flags & SS_COMPLETE)
235 return make_message("%lli-%lli.being_deleted",
236 (long long)s->creation_time,
237 (long long)s->completion_time);
238 return make_message("%lli-incomplete.being_deleted",
239 (long long)s->creation_time);
242 int complete_name(int64_t start, int64_t end, char **result)
244 struct tm start_tm, end_tm;
245 time_t *start_seconds = (time_t *) (uint64_t *)&start; /* STFU, gcc */
246 time_t *end_seconds = (time_t *) (uint64_t *)&end; /* STFU, gcc */
247 char start_str[200], end_str[200];
249 if (!localtime_r(start_seconds, &start_tm)) {
250 make_err_msg("%lli", (long long)start);
253 if (!localtime_r(end_seconds, &end_tm)) {
254 make_err_msg("%lli", (long long)end);
257 if (!strftime(start_str, sizeof(start_str), "%a_%b_%d_%Y_%H_%M_%S", &start_tm)) {
258 make_err_msg("%lli", (long long)start);
261 if (!strftime(end_str, sizeof(end_str), "%a_%b_%d_%Y_%H_%M_%S", &end_tm)) {
262 make_err_msg("%lli", (long long)end);
265 *result = make_message("%lli-%lli.%s-%s", (long long) start, (long long) end,
270 struct snapshot_list {
272 unsigned num_snapshots;
274 struct snapshot **snapshots;
276 * Array of size num_intervals + 1
278 * It contains the number of snapshots in each interval. interval_count[num_intervals]
279 * is the number of snapshots which belong to any interval greater than num_intervals.
281 unsigned *interval_count;
284 #define FOR_EACH_SNAPSHOT(s, i, sl) \
285 for ((i) = 0; (i) < (sl)->num_snapshots && ((s) = (sl)->snapshots[(i)]); (i)++)
289 #define NUM_COMPARE(x, y) ((int)((x) < (y)) - (int)((x) > (y)))
291 static int compare_snapshots(const void *a, const void *b)
293 struct snapshot *s1 = *(struct snapshot **)a;
294 struct snapshot *s2 = *(struct snapshot **)b;
295 return NUM_COMPARE(s2->creation_time, s1->creation_time);
298 /** Compute the minimum of \a a and \a b. */
299 #define DSS_MIN(a,b) ((a) < (b) ? (a) : (b))
301 int add_snapshot(const char *dirname, void *private)
303 struct snapshot_list *sl = private;
305 int ret = is_snapshot(dirname, sl->now, &s);
309 if (sl->num_snapshots >= sl->array_size) {
310 sl->array_size = 2 * sl->array_size + 1;
311 sl->snapshots = dss_realloc(sl->snapshots,
312 sl->array_size * sizeof(struct snapshot *));
314 sl->snapshots[sl->num_snapshots] = dss_malloc(sizeof(struct snapshot));
315 *(sl->snapshots[sl->num_snapshots]) = s;
316 sl->interval_count[DSS_MIN(s.interval, conf.num_intervals_arg)]++;
321 void get_snapshot_list(struct snapshot_list *sl)
323 sl->now = get_current_time();
324 sl->num_snapshots = 0;
326 sl->snapshots = NULL;
327 sl->interval_count = dss_calloc((conf.num_intervals_arg + 1) * sizeof(unsigned));
328 for_each_subdir(add_snapshot, sl);
329 qsort(sl->snapshots, sl->num_snapshots, sizeof(struct snapshot *),
333 void free_snapshot_list(struct snapshot_list *sl)
338 FOR_EACH_SNAPSHOT(s, i, sl) {
342 free(sl->interval_count);
346 void stop_rsync_process(void)
348 if (!rsync_pid || rsync_stopped)
350 kill(SIGSTOP, rsync_pid);
354 void restart_rsync_process(void)
356 if (!rsync_pid || !rsync_stopped)
358 kill (SIGCONT, rsync_pid);
363 * Print a log message about the exit status of a child.
365 void log_termination_msg(pid_t pid, int status)
367 if (WIFEXITED(status))
368 DSS_INFO_LOG("child %i exited. Exit status: %i\n", (int)pid,
369 WEXITSTATUS(status));
370 else if (WIFSIGNALED(status))
371 DSS_NOTICE_LOG("child %i was killed by signal %i\n", (int)pid,
374 DSS_WARNING_LOG("child %i terminated abormally\n", (int)pid);
377 int wait_for_process(pid_t pid, int *status)
381 DSS_DEBUG_LOG("Waiting for process %d to terminate\n", (int)pid);
389 if (ret == SIGCHLD) {
390 ret = waitpid(pid, status, 0);
393 if (errno != EINTR) { /* error */
394 ret = -ERRNO_TO_DSS_ERROR(errno);
398 /* SIGINT or SIGTERM */
399 DSS_WARNING_LOG("sending SIGTERM to pid %d\n", (int)pid);
403 make_err_msg("failed to wait for process %d", (int)pid);
405 log_termination_msg(pid, *status);
409 int remove_snapshot(struct snapshot *s)
411 int fds[3] = {0, 0, 0};
413 char *new_name = being_deleted_name(s);
414 int ret = dss_rename(s->name, new_name);
415 char *argv[] = {"rm", "-rf", new_name, NULL};
419 DSS_NOTICE_LOG("removing %s (interval = %i)\n", s->name, s->interval);
420 stop_rsync_process();
421 ret = dss_exec(&rm_pid, argv[0], argv, fds);
428 * return: 0: no redundant snapshots, 1: rm process started, negative: error
430 int remove_redundant_snapshot(struct snapshot_list *sl)
432 int ret, i, interval;
434 unsigned missing = 0;
436 DSS_INFO_LOG("looking for intervals containing too many snapshots\n");
437 for (interval = conf.num_intervals_arg - 1; interval >= 0; interval--) {
438 unsigned keep = num_snapshots(interval);
439 unsigned num = sl->interval_count[interval];
440 struct snapshot *victim = NULL, *prev = NULL;
441 int64_t score = LONG_MAX;
444 missing += keep - num;
445 DSS_DEBUG_LOG("interval %i: keep: %u, have: %u, missing: %u\n",
446 interval, keep, num, missing);
447 if (keep + missing >= num)
449 /* redundant snapshot in this interval, pick snapshot with lowest score */
450 FOR_EACH_SNAPSHOT(s, i, sl) {
453 //DSS_DEBUG_LOG("checking %s\n", s->name);
454 if (s->interval > interval) {
458 if (s->interval < interval)
466 /* check if s is a better victim */
467 this_score = s->creation_time - prev->creation_time;
468 assert(this_score >= 0);
469 //DSS_DEBUG_LOG("%s: score %lli\n", s->name, (long long)score);
470 if (this_score < score) {
477 if (conf.dry_run_given) {
478 dss_msg("%s would be removed (interval = %i)\n",
479 victim->name, victim->interval);
482 ret = remove_snapshot(victim);
483 return ret < 0? ret : 1;
488 int remove_outdated_snapshot(struct snapshot_list *sl)
493 DSS_INFO_LOG("looking for snapshots belonging to intervals greater than %d\n",
494 conf.num_intervals_arg);
495 FOR_EACH_SNAPSHOT(s, i, sl) {
496 if (s->interval <= conf.num_intervals_arg)
498 if (conf.dry_run_given) {
499 dss_msg("%s would be removed (interval = %i)\n",
500 s->name, s->interval);
503 ret = remove_snapshot(s);
511 int handle_rm_exit(int status)
515 if (!WIFEXITED(status)) {
516 make_err_msg("rm process %d died involuntary", (int)rm_pid);
517 ret = -E_INVOLUNTARY_EXIT;
520 es = WEXITSTATUS(status);
522 make_err_msg("rm process %d returned %d", (int)rm_pid, es);
523 ret = -E_BAD_EXIT_CODE;
532 int wait_for_rm_process(void)
534 int status, ret = wait_for_process(rm_pid, &status);
538 return handle_rm_exit(status);
541 void kill_process(pid_t pid)
545 DSS_WARNING_LOG("sending SIGTERM to pid %d\n", (int)pid);
551 DSS_INFO_LOG("FIXME: no sighup handling yet\n");
554 int rename_incomplete_snapshot(int64_t start)
556 char *old_name, *new_name;
559 ret = complete_name(start, get_current_time(), &new_name);
562 old_name = incomplete_name(start);
563 ret = dss_rename(old_name, new_name);
565 DSS_NOTICE_LOG("%s -> %s\n", old_name, new_name);
571 int handle_rsync_exit(int status)
575 if (!WIFEXITED(status)) {
576 make_err_msg("rsync process %d died involuntary", (int)rsync_pid);
577 ret = -E_INVOLUNTARY_EXIT;
580 es = WEXITSTATUS(status);
581 if (es != 0 && es != 23 && es != 24) {
582 make_err_msg("rsync process %d returned %d", (int)rsync_pid, es);
583 ret = -E_BAD_EXIT_CODE;
586 ret = rename_incomplete_snapshot(current_snapshot_creation_time);
589 current_snapshot_creation_time = 0;
594 int get_newest_complete(const char *dirname, void *private)
596 struct edge_snapshot_data *esd = private;
598 int ret = is_snapshot(dirname, esd->now, &s);
602 if (s.flags != SS_COMPLETE) /* incomplete or being deleted */
604 if (s.creation_time < esd->snap.creation_time)
606 free(esd->snap.name);
611 __malloc char *name_of_newest_complete_snapshot(void)
613 struct edge_snapshot_data esd = {
614 .now = get_current_time(),
615 .snap = {.creation_time = -1}
617 for_each_subdir(get_newest_complete, &esd);
618 return esd.snap.name;
621 void create_rsync_argv(char ***argv, int64_t *num)
623 char *logname, *newest = name_of_newest_complete_snapshot();
626 *argv = dss_malloc((15 + conf.rsync_option_given) * sizeof(char *));
627 (*argv)[i++] = dss_strdup("rsync");
628 (*argv)[i++] = dss_strdup("-aq");
629 (*argv)[i++] = dss_strdup("--delete");
630 for (j = 0; j < conf.rsync_option_given; j++)
631 (*argv)[i++] = dss_strdup(conf.rsync_option_arg[j]);
633 DSS_INFO_LOG("using %s as reference snapshot\n", newest);
634 (*argv)[i++] = make_message("--link-dest=../%s", newest);
637 DSS_INFO_LOG("no previous snapshot found\n");
638 if (conf.exclude_patterns_given) {
639 (*argv)[i++] = dss_strdup("--exclude-from");
640 (*argv)[i++] = dss_strdup(conf.exclude_patterns_arg);
643 logname = dss_logname();
644 if (conf.remote_user_given && !strcmp(conf.remote_user_arg, logname))
645 (*argv)[i++] = dss_strdup(conf.source_dir_arg);
647 (*argv)[i++] = make_message("%s@%s:%s/", conf.remote_user_given?
648 conf.remote_user_arg : logname,
649 conf.remote_host_arg, conf.source_dir_arg);
651 *num = get_current_time();
652 (*argv)[i++] = incomplete_name(*num);
654 for (j = 0; j < i; j++)
655 DSS_DEBUG_LOG("argv[%d] = %s\n", j, (*argv)[j]);
658 void free_rsync_argv(char **argv)
661 for (i = 0; argv[i]; i++)
666 int create_snapshot(char **argv)
668 int fds[3] = {0, 0, 0};
669 char *name = incomplete_name(current_snapshot_creation_time);
671 DSS_NOTICE_LOG("creating new snapshot %s\n", name);
673 return dss_exec(&rsync_pid, argv[0], argv, fds);
676 void compute_next_snapshot_time(struct snapshot_list *sl)
678 struct timeval now, unit_interval = {.tv_sec = 24 * 3600 * conf.unit_interval_arg},
681 unsigned wanted = num_snapshots(0), num_complete_snapshots = 0;
685 gettimeofday(&now, NULL);
686 FOR_EACH_SNAPSHOT(s, i, sl) {
687 if (!(s->flags & SS_COMPLETE))
689 num_complete_snapshots++;
690 x += s->completion_time - s->creation_time;
693 if (num_complete_snapshots)
694 x /= num_complete_snapshots; /* avg time to create one snapshot */
695 x *= wanted; /* time to create all snapshots in interval 0 */
698 ret = tv_diff(&unit_interval, &tmp, &diff); /* time between creation */
700 next_snapshot_time = now;
703 tv_divide(wanted, &diff, &tmp);
704 tv_add(&now, &tmp, &next_snapshot_time);
707 void handle_signal(struct snapshot_list *sl)
709 int sig, ret = next_signal();
719 restart_rsync_process();
720 kill_process(rsync_pid);
721 kill_process(rm_pid);
727 ret = reap_child(&pid, &status);
730 assert(pid == rsync_pid || pid == rm_pid);
731 if (pid == rsync_pid)
732 ret = handle_rsync_exit(status);
734 ret = handle_rm_exit(status);
735 free_snapshot_list(sl);
736 get_snapshot_list(sl);
737 compute_next_snapshot_time(sl);
741 log_err_msg(ERROR, -ret);
744 int get_oldest(const char *dirname, void *private)
746 struct edge_snapshot_data *esd = private;
748 int ret = is_snapshot(dirname, esd->now, &s);
752 if (s.creation_time > esd->snap.creation_time)
754 free(esd->snap.name);
759 int remove_oldest_snapshot()
762 struct edge_snapshot_data esd = {
763 .now = get_current_time(),
764 .snap = {.creation_time = LLONG_MAX}
766 for_each_subdir(get_oldest, &esd);
767 if (!esd.snap.name) /* no snapshot found */
769 DSS_INFO_LOG("oldest snapshot: %s\n", esd.snap.name);
771 if (esd.snap.creation_time == current_snapshot_creation_time)
772 goto out; /* do not remove the snapshot currently being created */
773 ret = remove_snapshot(&esd.snap);
779 /* TODO: Also consider number of inodes. */
780 int disk_space_low(void)
782 struct disk_space ds;
783 int ret = get_disk_space(".", &ds);
787 if (conf.min_free_mb_arg)
788 if (ds.free_mb < conf.min_free_mb_arg)
790 if (conf.min_free_percent_arg)
791 if (ds.percent_free < conf.min_free_percent_arg)
796 int try_to_free_disk_space(int low_disk_space, struct snapshot_list *sl)
800 ret = remove_outdated_snapshot(sl);
801 if (ret) /* error, or we are removing something */
803 /* no outdated snapshot */
804 ret = remove_redundant_snapshot(sl);
809 DSS_WARNING_LOG("disk space low and nothing obvious to remove\n");
810 ret = remove_oldest_snapshot();
813 make_err_msg("uhuhu: not enough disk space for a single snapshot");
817 int select_loop(void)
820 struct timeval tv = {.tv_sec = 0, .tv_usec = 0};
821 struct snapshot_list sl = {.num_snapshots = 0};
823 get_snapshot_list(&sl);
824 compute_next_snapshot_time(&sl);
826 struct timeval now, *tvp = &tv;
832 FD_SET(signal_pipe, &rfds);
837 ret = dss_select(signal_pipe + 1, &rfds, NULL, tvp);
840 if (FD_ISSET(signal_pipe, &rfds))
844 ret = disk_space_low();
847 low_disk_space = ret;
849 stop_rsync_process();
850 ret = try_to_free_disk_space(low_disk_space, &sl);
856 restart_rsync_process();
859 /* neither rsync nor rm are running. Start rsync? */
860 gettimeofday(&now, NULL);
861 if (tv_diff(&next_snapshot_time, &now, &tv) > 0)
863 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
864 ret = create_snapshot(rsync_argv);
865 free_rsync_argv(rsync_argv);
869 free_snapshot_list(&sl);
877 if (conf.dry_run_given) {
878 make_err_msg("dry_run not supported by this command");
881 ret = install_sighandler(SIGHUP);
884 return select_loop();
887 void log_disk_space(struct disk_space *ds)
889 DSS_INFO_LOG("free: %uM/%uM (%u%%), %u%% inodes unused\n",
890 ds->free_mb, ds->total_mb, ds->percent_free,
891 ds->percent_free_inodes);
897 struct snapshot_list sl;
898 struct disk_space ds;
900 ret = get_disk_space(".", &ds);
905 get_snapshot_list(&sl);
906 ret = remove_outdated_snapshot(&sl);
907 free_snapshot_list(&sl);
912 ret = wait_for_rm_process();
917 get_snapshot_list(&sl);
918 ret = remove_redundant_snapshot(&sl);
919 free_snapshot_list(&sl);
924 ret = wait_for_rm_process();
938 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
939 if (conf.dry_run_given) {
942 for (i = 0; rsync_argv[i]; i++) {
944 msg = make_message("%s%s%s", tmp? tmp : "",
945 tmp? " " : "", rsync_argv[i]);
948 dss_msg("%s\n", msg);
952 ret = create_snapshot(rsync_argv);
955 ret = wait_for_process(rsync_pid, &status);
958 ret = handle_rsync_exit(status);
960 free_rsync_argv(rsync_argv);
967 struct snapshot_list sl;
969 get_snapshot_list(&sl);
970 FOR_EACH_SNAPSHOT(s, i, &sl)
971 dss_msg("%u\t%s\n", s->interval, s->name);
972 free_snapshot_list(&sl);
976 __noreturn void clean_exit(int status)
982 int read_config_file(void)
988 if (conf.config_file_given)
989 config_file = dss_strdup(conf.config_file_arg);
991 char *home = get_homedir();
992 config_file = make_message("%s/.dssrc", home);
995 ret = stat(config_file, &statbuf);
996 if (ret && conf.config_file_given) {
997 ret = -ERRNO_TO_DSS_ERROR(errno);
998 make_err_msg("failed to stat config file %s", config_file);
1002 struct cmdline_parser_params params = {
1005 .check_required = 0,
1006 .check_ambiguity = 0
1008 cmdline_parser_config_file(config_file, &conf, ¶ms);
1010 if (!conf.source_dir_given || !conf.dest_dir_given) {
1012 make_err_msg("you need to specify both source_dir and dest_dir");
1021 int check_config(void)
1023 if (conf.unit_interval_arg <= 0) {
1024 make_err_msg("bad unit interval: %i", conf.unit_interval_arg);
1025 return -E_INVALID_NUMBER;
1027 DSS_DEBUG_LOG("unit interval: %i day(s)\n", conf.unit_interval_arg);
1028 if (conf.num_intervals_arg <= 0) {
1029 make_err_msg("bad number of intervals %i", conf.num_intervals_arg);
1030 return -E_INVALID_NUMBER;
1032 DSS_DEBUG_LOG("number of intervals: %i\n", conf.num_intervals_arg);
1036 static void setup_signal_handling(void)
1040 DSS_INFO_LOG("setting up signal handlers\n");
1041 signal_pipe = signal_init(); /* always successful */
1042 ret = install_sighandler(SIGINT);
1045 ret = install_sighandler(SIGTERM);
1048 ret = install_sighandler(SIGCHLD);
1053 DSS_EMERG_LOG("could not install signal handlers\n");
1057 int main(int argc, char **argv)
1061 cmdline_parser(argc, argv, &conf); /* aborts on errors */
1062 ret = read_config_file();
1065 ret = check_config();
1068 if (conf.logfile_given) {
1069 logfile = open_log(conf.logfile_arg);
1070 log_welcome(conf.loglevel_arg);
1072 ret = dss_chdir(conf.dest_dir_arg);
1075 if (conf.daemon_given)
1077 setup_signal_handling();
1078 ret = call_command_handler();
1081 log_err_msg(EMERG, -ret);
1082 clean_exit(ret >= 0? EXIT_SUCCESS : EXIT_FAILURE);