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 static struct timeval next_snapshot_time;
45 /** The pid of the pre-create hook. */
46 static pid_t pre_create_hook_pid;
47 /** The pid of the post-create hook. */
48 static pid_t post_create_hook_pid;
49 /* Creation time of the snapshot currently being created. */
50 static 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) static int com_ ##x(void);
69 #define COMMAND(x) if (conf.x ##_given) return com_ ##x();
70 static 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 static __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 static 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 static void dss_get_snapshot_list(struct snapshot_list *sl)
132 get_snapshot_list(sl, conf.unit_interval_arg, conf.num_intervals_arg);
135 static 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 static 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 static 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 static 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 static 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 static 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 static 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 static 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 static 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 static void kill_process(pid_t pid)
380 DSS_WARNING_LOG("sending SIGTERM to pid %d\n", (int)pid);
384 static void stop_rsync_process(void)
386 if (!rsync_pid || rsync_stopped)
388 kill(SIGSTOP, rsync_pid);
392 static 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 static 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 static 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);
452 static int handle_rm_exit(int status)
455 if (!WIFEXITED(status))
456 return -E_INVOLUNTARY_EXIT;
457 if (WEXITSTATUS(status))
458 return -E_BAD_EXIT_CODE;
462 static int wait_for_rm_process(void)
464 int status, ret = wait_for_process(rm_pid, &status);
468 return handle_rm_exit(status);
471 static int handle_rsync_exit(int status)
475 if (!WIFEXITED(status)) {
476 DSS_ERROR_LOG("rsync process %d died involuntary\n", (int)rsync_pid);
477 ret = -E_INVOLUNTARY_EXIT;
478 snapshot_creation_status = SCS_READY;
479 compute_next_snapshot_time();
482 es = WEXITSTATUS(status);
483 if (es != 0 && es != 23 && es != 24) {
484 DSS_ERROR_LOG("rsync process %d returned %d\n", (int)rsync_pid, es);
485 ret = -E_BAD_EXIT_CODE;
486 snapshot_creation_status = SCS_READY;
487 compute_next_snapshot_time();
490 ret = rename_incomplete_snapshot(current_snapshot_creation_time);
493 snapshot_creation_status = SCS_RSYNC_SUCCESS;
500 static int handle_pre_create_hook_exit(int status)
504 if (!WIFEXITED(status)) {
505 snapshot_creation_status = SCS_READY;
506 compute_next_snapshot_time();
507 ret = -E_INVOLUNTARY_EXIT;
510 es = WEXITSTATUS(status);
512 snapshot_creation_status = SCS_READY;
513 compute_next_snapshot_time();
514 ret = -E_BAD_EXIT_CODE;
517 snapshot_creation_status = SCS_PRE_HOOK_SUCCESS;
520 pre_create_hook_pid = 0;
524 static int handle_sigchld(void)
527 int status, ret = reap_child(&pid, &status);
531 if (pid == rsync_pid)
532 return handle_rsync_exit(status);
534 return handle_rm_exit(status);
535 if (pid == pre_create_hook_pid)
536 return handle_pre_create_hook_exit(status);
537 if (pid == post_create_hook_pid) {
538 snapshot_creation_status = SCS_READY;
539 compute_next_snapshot_time();
542 DSS_EMERG_LOG("BUG: unknown process %d died\n", (int)pid);
547 static int check_config(void)
549 if (conf.unit_interval_arg <= 0) {
550 DSS_ERROR_LOG("bad unit interval: %i\n", conf.unit_interval_arg);
551 return -E_INVALID_NUMBER;
553 DSS_DEBUG_LOG("unit interval: %i day(s)\n", conf.unit_interval_arg);
554 if (conf.num_intervals_arg <= 0) {
555 DSS_ERROR_LOG("bad number of intervals %i\n", conf.num_intervals_arg);
556 return -E_INVALID_NUMBER;
558 DSS_DEBUG_LOG("number of intervals: %i\n", conf.num_intervals_arg);
562 /* exits on errors */
563 static void parse_config_file(int override)
568 char *old_logfile_arg = NULL;
569 int old_daemon_given = 0;
571 if (conf.config_file_given)
572 config_file = dss_strdup(conf.config_file_arg);
574 char *home = get_homedir();
575 config_file = make_message("%s/.dssrc", home);
578 if (override) { /* SIGHUP */
579 if (conf.logfile_given)
580 old_logfile_arg = dss_strdup(conf.logfile_arg);
581 old_daemon_given = conf.daemon_given;
584 ret = stat(config_file, &statbuf);
585 if (ret && conf.config_file_given) {
586 ret = -ERRNO_TO_DSS_ERROR(errno);
587 DSS_ERROR_LOG("failed to stat config file %s\n", config_file);
591 struct cmdline_parser_params params = {
592 .override = override,
597 cmdline_parser_config_file(config_file, &conf, ¶ms);
599 ret = check_config();
603 /* don't change daemon mode on SIGHUP */
604 conf.daemon_given = old_daemon_given;
607 if (conf.logfile_given)
608 free(old_logfile_arg);
609 else if (conf.daemon_given) { /* re-use old logfile */
610 conf.logfile_arg = old_logfile_arg;
611 conf.logfile_given = 1;
614 if (conf.logfile_given) {
615 logfile = open_log(conf.logfile_arg);
616 log_welcome(conf.loglevel_arg);
618 DSS_EMERG_LOG("loglevel: %d\n", conf.loglevel_arg);
619 // cmdline_parser_dump(logfile? logfile : stdout, &conf);
620 ret = dss_chdir(conf.dest_dir_arg);
625 DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
629 static void handle_sighup(void)
631 DSS_NOTICE_LOG("SIGHUP\n");
632 parse_config_file(1);
635 static void handle_signal(void)
637 int sig, ret = next_signal();
645 restart_rsync_process();
646 kill_process(rsync_pid);
647 kill_process(rm_pid);
654 ret = handle_sigchld();
659 DSS_ERROR_LOG("%s\n", dss_strerror(-ret));
662 static void create_rsync_argv(char ***argv, int64_t *num)
664 char *logname, *newest;
666 struct snapshot_list sl;
668 dss_get_snapshot_list(&sl);
669 newest = name_of_newest_complete_snapshot(&sl);
670 free_snapshot_list(&sl);
672 *argv = dss_malloc((15 + conf.rsync_option_given) * sizeof(char *));
673 (*argv)[i++] = dss_strdup("rsync");
674 (*argv)[i++] = dss_strdup("-aq");
675 (*argv)[i++] = dss_strdup("--delete");
676 for (j = 0; j < conf.rsync_option_given; j++)
677 (*argv)[i++] = dss_strdup(conf.rsync_option_arg[j]);
679 DSS_INFO_LOG("using %s as reference snapshot\n", newest);
680 (*argv)[i++] = make_message("--link-dest=../%s", newest);
683 DSS_INFO_LOG("no previous snapshot found\n");
684 if (conf.exclude_patterns_given) {
685 (*argv)[i++] = dss_strdup("--exclude-from");
686 (*argv)[i++] = dss_strdup(conf.exclude_patterns_arg);
689 logname = dss_logname();
690 if (conf.remote_user_given && !strcmp(conf.remote_user_arg, logname))
691 (*argv)[i++] = dss_strdup(conf.source_dir_arg);
693 (*argv)[i++] = make_message("%s@%s:%s/", conf.remote_user_given?
694 conf.remote_user_arg : logname,
695 conf.remote_host_arg, conf.source_dir_arg);
697 *num = get_current_time();
698 (*argv)[i++] = incomplete_name(*num);
700 for (j = 0; j < i; j++)
701 DSS_DEBUG_LOG("argv[%d] = %s\n", j, (*argv)[j]);
704 static void free_rsync_argv(char **argv)
707 for (i = 0; argv[i]; i++)
712 static int create_snapshot(char **argv)
714 int ret, fds[3] = {0, 0, 0};
717 name = incomplete_name(current_snapshot_creation_time);
718 DSS_NOTICE_LOG("creating new snapshot %s\n", name);
720 ret = dss_exec(&rsync_pid, argv[0], argv, fds);
723 snapshot_creation_status = SCS_RSYNC_RUNNING;
727 static int select_loop(void)
730 struct timeval tv = {.tv_sec = 0, .tv_usec = 0};
736 struct timeval now, *tvp = &tv;
739 tv.tv_sec = 60; /* check every 60 seconds for free disk space */
741 tvp = NULL; /* sleep until rm process dies */
743 FD_SET(signal_pipe, &rfds);
744 DSS_DEBUG_LOG("tvp: %p, tv_sec: %lu\n", tvp, (long unsigned) tv.tv_sec);
745 ret = dss_select(signal_pipe + 1, &rfds, NULL, tvp);
748 if (FD_ISSET(signal_pipe, &rfds))
752 ret = disk_space_low();
755 low_disk_space = ret;
756 ret = try_to_free_disk_space(low_disk_space);
760 stop_rsync_process();
763 restart_rsync_process();
764 gettimeofday(&now, NULL);
765 if (tv_diff(&next_snapshot_time, &now, &tv) > 0)
767 switch (snapshot_creation_status) {
769 ret = pre_create_hook();
773 case SCS_PRE_HOOK_RUNNING:
775 case SCS_PRE_HOOK_SUCCESS:
776 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
777 ret = create_snapshot(rsync_argv);
778 free_rsync_argv(rsync_argv);
782 case SCS_RSYNC_RUNNING:
784 case SCS_RSYNC_SUCCESS:
785 ret = post_create_hook();
789 case SCS_POST_HOOK_RUNNING:
797 static int com_run(void)
801 if (conf.dry_run_given) {
802 DSS_ERROR_LOG("dry_run not supported by this command\n");
805 ret = install_sighandler(SIGHUP);
808 compute_next_snapshot_time();
809 return select_loop();
812 static int com_prune(void)
815 struct snapshot_list sl;
816 struct disk_space ds;
818 ret = get_disk_space(".", &ds);
823 dss_get_snapshot_list(&sl);
824 ret = remove_outdated_snapshot(&sl);
825 free_snapshot_list(&sl);
830 ret = wait_for_rm_process();
835 dss_get_snapshot_list(&sl);
836 ret = remove_redundant_snapshot(&sl);
837 free_snapshot_list(&sl);
842 ret = wait_for_rm_process();
851 static int com_create(void)
856 if (conf.dry_run_given) {
859 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
860 for (i = 0; rsync_argv[i]; i++) {
862 msg = make_message("%s%s%s", tmp? tmp : "",
863 tmp? " " : "", rsync_argv[i]);
866 free_rsync_argv(rsync_argv);
867 dss_msg("%s\n", msg);
871 ret = pre_create_hook();
874 if (pre_create_hook_pid) {
875 ret = wait_for_process(pre_create_hook_pid, &status);
878 ret = handle_pre_create_hook_exit(status);
882 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
883 ret = create_snapshot(rsync_argv);
886 ret = wait_for_process(rsync_pid, &status);
889 ret = handle_rsync_exit(status);
893 if (post_create_hook_pid)
894 ret = wait_for_process(post_create_hook_pid, &status);
896 free_rsync_argv(rsync_argv);
900 static int com_ls(void)
903 struct snapshot_list sl;
906 dss_get_snapshot_list(&sl);
907 FOR_EACH_SNAPSHOT(s, i, &sl)
908 dss_msg("%u\t%s\n", s->interval, s->name);
909 free_snapshot_list(&sl);
913 static void setup_signal_handling(void)
917 DSS_INFO_LOG("setting up signal handlers\n");
918 signal_pipe = signal_init(); /* always successful */
919 ret = install_sighandler(SIGINT);
922 ret = install_sighandler(SIGTERM);
925 ret = install_sighandler(SIGCHLD);
930 DSS_EMERG_LOG("could not install signal handlers\n");
935 int main(int argc, char **argv)
938 struct cmdline_parser_params params = {
945 cmdline_parser_ext(argc, argv, &conf, ¶ms); /* aborts on errors */
946 parse_config_file(0);
948 if (conf.daemon_given)
950 setup_signal_handling();
951 ret = call_command_handler();
953 DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
954 exit(ret >= 0? EXIT_SUCCESS : EXIT_FAILURE);