2 * Copyright (C) 2008 Andre Noll <maan@systemlinux.org>
4 * Licensed under the GPL v2. For licencing details see COPYING.
11 #include <sys/types.h>
24 #include "gcc-compat.h"
37 /** Command line and config file options. */
38 static struct gengetopt_args_info conf;
39 /** Non-NULL if we log to a file. */
41 /** The read end of the signal pipe */
42 static int signal_pipe;
43 /** Process id of current rsync process. */
44 static pid_t rsync_pid;
45 /** Whether the rsync process is currently stopped */
46 static int rsync_stopped;
47 /** Process id of current rm process. */
49 /** When the next snapshot is due. */
50 static struct timeval next_snapshot_time;
51 /** The pid of the pre-create hook. */
52 static pid_t pre_create_hook_pid;
53 /** The pid of the post-create hook. */
54 static pid_t post_create_hook_pid;
55 /** Creation time of the snapshot currently being created. */
56 static int64_t current_snapshot_creation_time;
57 /** Needed by the post-create hook. */
58 static char *path_to_last_complete_snapshot;
59 /** \sa \ref snap.h for details. */
60 static unsigned snapshot_creation_status;
66 /* a litte cpp magic helps to DRY */
72 #define COMMAND(x) static int com_ ##x(void);
75 #define COMMAND(x) if (conf.x ##_given) return com_ ##x();
76 static int call_command_handler(void)
79 DSS_EMERG_LOG("BUG: did not find command handler\n");
86 * The log function of dss.
89 * \param fml Usual format string.
91 * All DSS_XXX_LOG() macros use this function.
93 __printf_2_3 void dss_log(int ll, const char* fmt,...)
101 if (ll < conf.loglevel_arg)
103 outfd = logfile? logfile : stderr;
106 strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
107 fprintf(outfd, "%s ", str);
108 if (conf.loglevel_arg <= INFO)
109 fprintf(outfd, "%i: ", ll);
111 vfprintf(outfd, fmt, argp);
116 * Print a message either to stdout or to the log file.
118 static __printf_1_2 void dss_msg(const char* fmt,...)
120 FILE *outfd = conf.daemon_given? logfile : stdout;
123 vfprintf(outfd, fmt, argp);
127 static int disk_space_low(void)
129 struct disk_space ds;
130 int ret = get_disk_space(".", &ds);
134 if (conf.min_free_mb_arg)
135 if (ds.free_mb < conf.min_free_mb_arg)
137 if (conf.min_free_percent_arg)
138 if (ds.percent_free < conf.min_free_percent_arg)
140 if (conf.min_free_percent_inodes_arg)
141 if (ds.percent_free_inodes < conf.min_free_percent_inodes_arg)
146 static void dss_get_snapshot_list(struct snapshot_list *sl)
148 get_snapshot_list(sl, conf.unit_interval_arg, conf.num_intervals_arg);
151 static void compute_next_snapshot_time(void)
153 struct timeval now, unit_interval = {.tv_sec = 24 * 3600 * conf.unit_interval_arg},
156 unsigned wanted = desired_number_of_snapshots(0, conf.num_intervals_arg),
157 num_complete_snapshots = 0;
159 struct snapshot *s = NULL;
160 struct snapshot_list sl;
162 assert(snapshot_creation_status == SCS_READY);
163 current_snapshot_creation_time = 0;
164 dss_get_snapshot_list(&sl);
165 FOR_EACH_SNAPSHOT(s, i, &sl) {
166 if (!(s->flags & SS_COMPLETE))
168 num_complete_snapshots++;
169 x += s->completion_time - s->creation_time;
172 if (num_complete_snapshots)
173 x /= num_complete_snapshots; /* avg time to create one snapshot */
174 x *= wanted; /* time to create all snapshots in interval 0 */
177 ret = tv_diff(&unit_interval, &tmp, &diff); /* total sleep time per unit interval */
178 if (ret < 0 || !s) /* unit_interval < tmp or no snapshot */
180 tv_divide(wanted, &diff, &tmp); /* sleep time betweeen two snapshots */
181 diff.tv_sec = s->completion_time; /* completion time of the the latest snaphot */
183 tv_add(&diff, &tmp, &next_snapshot_time);
184 gettimeofday(&now, NULL);
185 if (tv_diff(&now, &next_snapshot_time, NULL) < 0)
188 next_snapshot_time = now;
189 next_snapshot_time.tv_sec += 60;
191 free_snapshot_list(&sl);
195 static int remove_snapshot(struct snapshot *s)
197 int fds[3] = {0, 0, 0};
199 char *new_name = being_deleted_name(s);
200 int ret = dss_rename(s->name, new_name);
201 char *argv[] = {"rm", "-rf", new_name, NULL};
205 DSS_NOTICE_LOG("removing %s (interval = %i)\n", s->name, s->interval);
206 ret = dss_exec(&rm_pid, argv[0], argv, fds);
213 * return: 0: no redundant snapshots, 1: rm process started, negative: error
215 static int remove_redundant_snapshot(struct snapshot_list *sl)
217 int ret, i, interval;
219 unsigned missing = 0;
221 DSS_DEBUG_LOG("looking for intervals containing too many snapshots\n");
222 for (interval = conf.num_intervals_arg - 1; interval >= 0; interval--) {
223 unsigned keep = desired_number_of_snapshots(interval, conf.num_intervals_arg);
224 unsigned num = sl->interval_count[interval];
225 struct snapshot *victim = NULL, *prev = NULL;
226 int64_t score = LONG_MAX;
229 missing += keep - num;
230 // DSS_DEBUG_LOG("interval %i: keep: %u, have: %u, missing: %u\n",
231 // interval, keep, num, missing);
232 if (keep + missing >= num)
234 /* redundant snapshot in this interval, pick snapshot with lowest score */
235 FOR_EACH_SNAPSHOT(s, i, sl) {
238 //DSS_DEBUG_LOG("checking %s\n", s->name);
239 if (s->interval > interval) {
243 if (s->interval < interval)
251 /* check if s is a better victim */
252 this_score = s->creation_time - prev->creation_time;
253 assert(this_score >= 0);
254 //DSS_DEBUG_LOG("%s: score %lli\n", s->name, (long long)score);
255 if (this_score < score) {
262 if (conf.dry_run_given) {
263 dss_msg("%s would be removed (interval = %i)\n",
264 victim->name, victim->interval);
267 ret = remove_snapshot(victim);
268 return ret < 0? ret : 1;
273 static int remove_outdated_snapshot(struct snapshot_list *sl)
278 DSS_DEBUG_LOG("looking for snapshots belonging to intervals greater than %d\n",
279 conf.num_intervals_arg);
280 FOR_EACH_SNAPSHOT(s, i, sl) {
281 if (s->interval <= conf.num_intervals_arg)
283 if (conf.dry_run_given) {
284 dss_msg("%s would be removed (interval = %i)\n",
285 s->name, s->interval);
288 ret = remove_snapshot(s);
296 static int remove_oldest_snapshot(struct snapshot_list *sl)
298 struct snapshot *s = get_oldest_snapshot(sl);
300 if (!s) /* no snapshot found */
302 DSS_INFO_LOG("oldest snapshot: %s\n", s->name);
303 if (s->creation_time == current_snapshot_creation_time)
304 return 0; /* do not remove the snapshot currently being created */
305 return remove_snapshot(s);
308 static int rename_incomplete_snapshot(int64_t start)
313 free(path_to_last_complete_snapshot);
314 ret = complete_name(start, get_current_time(),
315 &path_to_last_complete_snapshot);
318 old_name = incomplete_name(start);
319 ret = dss_rename(old_name, path_to_last_complete_snapshot);
321 DSS_NOTICE_LOG("%s -> %s\n", old_name,
322 path_to_last_complete_snapshot);
327 static int try_to_free_disk_space(int low_disk_space)
330 struct snapshot_list sl;
332 if (!low_disk_space && conf.keep_redundant_given)
334 dss_get_snapshot_list(&sl);
335 ret = remove_outdated_snapshot(&sl);
336 if (ret) /* error, or we are removing something */
338 /* no outdated snapshot */
339 ret = remove_redundant_snapshot(&sl);
345 DSS_WARNING_LOG("disk space low and nothing obvious to remove\n");
346 ret = remove_oldest_snapshot(&sl);
349 DSS_CRIT_LOG("uhuhu: not enough disk space for a single snapshot\n");
350 ret = -ERRNO_TO_DSS_ERROR(ENOSPC);
352 free_snapshot_list(&sl);
356 static int pre_create_hook(void)
358 int ret, fds[3] = {0, 0, 0};
360 if (!conf.pre_create_hook_given) {
361 snapshot_creation_status = SCS_PRE_HOOK_SUCCESS;
364 DSS_NOTICE_LOG("executing %s\n", conf.pre_create_hook_arg);
365 ret = dss_exec_cmdline_pid(&pre_create_hook_pid,
366 conf.pre_create_hook_arg, fds);
369 snapshot_creation_status = SCS_PRE_HOOK_RUNNING;
373 static int post_create_hook(void)
375 int ret, fds[3] = {0, 0, 0};
378 if (!conf.post_create_hook_given) {
379 snapshot_creation_status = SCS_READY;
380 compute_next_snapshot_time();
383 cmd = make_message("%s %s/%s", conf.post_create_hook_arg,
384 conf.dest_dir_arg, path_to_last_complete_snapshot);
385 DSS_NOTICE_LOG("executing %s\n", cmd);
386 ret = dss_exec_cmdline_pid(&post_create_hook_pid, cmd, fds);
390 snapshot_creation_status = SCS_POST_HOOK_RUNNING;
394 static void kill_process(pid_t pid)
398 DSS_WARNING_LOG("sending SIGTERM to pid %d\n", (int)pid);
402 static void stop_rsync_process(void)
404 if (!rsync_pid || rsync_stopped)
406 kill(SIGSTOP, rsync_pid);
410 static void restart_rsync_process(void)
412 if (!rsync_pid || !rsync_stopped)
414 kill (SIGCONT, rsync_pid);
420 * Print a log message about the exit status of a child.
422 static void log_termination_msg(pid_t pid, int status)
424 if (WIFEXITED(status))
425 DSS_INFO_LOG("child %i exited. Exit status: %i\n", (int)pid,
426 WEXITSTATUS(status));
427 else if (WIFSIGNALED(status))
428 DSS_NOTICE_LOG("child %i was killed by signal %i\n", (int)pid,
431 DSS_WARNING_LOG("child %i terminated abormally\n", (int)pid);
434 static int wait_for_process(pid_t pid, int *status)
438 DSS_DEBUG_LOG("Waiting for process %d to terminate\n", (int)pid);
443 FD_SET(signal_pipe, &rfds);
444 ret = dss_select(signal_pipe + 1, &rfds, NULL, NULL);
450 if (ret == SIGCHLD) {
451 ret = waitpid(pid, status, 0);
454 if (errno != EINTR) { /* error */
455 ret = -ERRNO_TO_DSS_ERROR(errno);
459 /* SIGINT or SIGTERM */
460 DSS_WARNING_LOG("sending SIGTERM to pid %d\n", (int)pid);
464 DSS_ERROR_LOG("failed to wait for process %d\n", (int)pid);
466 log_termination_msg(pid, *status);
470 static int handle_rm_exit(int status)
473 if (!WIFEXITED(status))
474 return -E_INVOLUNTARY_EXIT;
475 if (WEXITSTATUS(status))
476 return -E_BAD_EXIT_CODE;
480 static int wait_for_rm_process(void)
482 int status, ret = wait_for_process(rm_pid, &status);
486 return handle_rm_exit(status);
489 static int handle_rsync_exit(int status)
493 if (!WIFEXITED(status)) {
494 DSS_ERROR_LOG("rsync process %d died involuntary\n", (int)rsync_pid);
495 ret = -E_INVOLUNTARY_EXIT;
496 snapshot_creation_status = SCS_READY;
497 compute_next_snapshot_time();
500 es = WEXITSTATUS(status);
501 if (es == 13) { /* Errors with program diagnostics */
502 DSS_WARNING_LOG("rsync process %d returned %d -- restarting\n",
504 snapshot_creation_status = SCS_RSYNC_NEEDS_RESTART;
505 gettimeofday(&next_snapshot_time, NULL);
506 next_snapshot_time.tv_sec += 60;
510 if (es != 0 && es != 23 && es != 24) {
511 DSS_ERROR_LOG("rsync process %d returned %d\n", (int)rsync_pid, es);
512 ret = -E_BAD_EXIT_CODE;
513 snapshot_creation_status = SCS_READY;
514 compute_next_snapshot_time();
517 ret = rename_incomplete_snapshot(current_snapshot_creation_time);
520 snapshot_creation_status = SCS_RSYNC_SUCCESS;
527 static int handle_pre_create_hook_exit(int status)
531 if (!WIFEXITED(status)) {
532 snapshot_creation_status = SCS_READY;
533 compute_next_snapshot_time();
534 ret = -E_INVOLUNTARY_EXIT;
537 es = WEXITSTATUS(status);
539 snapshot_creation_status = SCS_READY;
540 compute_next_snapshot_time();
541 ret = -E_BAD_EXIT_CODE;
544 snapshot_creation_status = SCS_PRE_HOOK_SUCCESS;
547 pre_create_hook_pid = 0;
551 static int handle_sigchld(void)
554 int status, ret = reap_child(&pid, &status);
558 if (pid == rsync_pid)
559 return handle_rsync_exit(status);
561 return handle_rm_exit(status);
562 if (pid == pre_create_hook_pid)
563 return handle_pre_create_hook_exit(status);
564 if (pid == post_create_hook_pid) {
565 snapshot_creation_status = SCS_READY;
566 compute_next_snapshot_time();
569 DSS_EMERG_LOG("BUG: unknown process %d died\n", (int)pid);
573 static int check_config(void)
575 if (conf.unit_interval_arg <= 0) {
576 DSS_ERROR_LOG("bad unit interval: %i\n", conf.unit_interval_arg);
577 return -E_INVALID_NUMBER;
579 DSS_DEBUG_LOG("unit interval: %i day(s)\n", conf.unit_interval_arg);
580 if (conf.num_intervals_arg <= 0) {
581 DSS_ERROR_LOG("bad number of intervals %i\n", conf.num_intervals_arg);
582 return -E_INVALID_NUMBER;
584 DSS_DEBUG_LOG("number of intervals: %i\n", conf.num_intervals_arg);
588 static int parse_config_file(int override)
593 char *old_logfile_arg = NULL;
594 int old_daemon_given = 0;
596 if (conf.config_file_given)
597 config_file = dss_strdup(conf.config_file_arg);
599 char *home = get_homedir();
600 config_file = make_message("%s/.dssrc", home);
603 if (override) { /* SIGHUP */
604 if (conf.logfile_given)
605 old_logfile_arg = dss_strdup(conf.logfile_arg);
606 old_daemon_given = conf.daemon_given;
609 ret = stat(config_file, &statbuf);
610 if (ret && conf.config_file_given) {
611 ret = -ERRNO_TO_DSS_ERROR(errno);
612 DSS_ERROR_LOG("failed to stat config file %s\n", config_file);
616 struct cmdline_parser_params params = {
617 .override = override,
620 .check_ambiguity = 0,
623 if (override) { /* invalidate all rsync options */
626 for (i = 0; i < conf.rsync_option_given; i++) {
627 free(conf.rsync_option_arg[i]);
628 conf.rsync_option_arg[i] = NULL;
630 conf.rsync_option_given = 0;
632 cmdline_parser_config_file(config_file, &conf, ¶ms);
634 ret = check_config();
638 /* don't change daemon mode on SIGHUP */
639 conf.daemon_given = old_daemon_given;
642 if (conf.logfile_given)
643 free(old_logfile_arg);
644 else if (conf.daemon_given) { /* re-use old logfile */
645 conf.logfile_arg = old_logfile_arg;
646 conf.logfile_given = 1;
649 if (conf.logfile_given) {
650 logfile = open_log(conf.logfile_arg);
651 log_welcome(conf.loglevel_arg);
653 DSS_DEBUG_LOG("loglevel: %d\n", conf.loglevel_arg);
654 // cmdline_parser_dump(logfile? logfile : stdout, &conf);
658 DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
662 static int change_to_dest_dir(void)
664 DSS_INFO_LOG("changing cwd to %s\n", conf.dest_dir_arg);
665 return dss_chdir(conf.dest_dir_arg);
668 static int handle_sighup(void)
672 DSS_NOTICE_LOG("SIGHUP\n");
673 ret = parse_config_file(1);
676 return change_to_dest_dir();
679 static int handle_signal(void)
681 int sig, ret = next_signal();
689 restart_rsync_process();
690 kill_process(rsync_pid);
691 kill_process(rm_pid);
695 ret = handle_sighup();
698 ret = handle_sigchld();
703 DSS_ERROR_LOG("%s\n", dss_strerror(-ret));
708 * We can not use rsync locally if the local user is different from the remote
709 * user or if the src dir is not on the local host (or both).
711 static int use_rsync_locally(char *logname)
713 char *h = conf.remote_host_arg;
715 if (strcmp(h, "localhost") && strcmp(h, "127.0.0.1"))
717 if (conf.remote_user_given && strcmp(conf.remote_user_arg, logname))
722 static void create_rsync_argv(char ***argv, int64_t *num)
724 char *logname, *newest;
726 struct snapshot_list sl;
728 dss_get_snapshot_list(&sl);
729 newest = name_of_newest_complete_snapshot(&sl);
730 free_snapshot_list(&sl);
732 *argv = dss_malloc((15 + conf.rsync_option_given) * sizeof(char *));
733 (*argv)[i++] = dss_strdup("rsync");
734 (*argv)[i++] = dss_strdup("-aq");
735 (*argv)[i++] = dss_strdup("--delete");
736 for (j = 0; j < conf.rsync_option_given; j++)
737 (*argv)[i++] = dss_strdup(conf.rsync_option_arg[j]);
739 DSS_INFO_LOG("using %s as reference snapshot\n", newest);
740 (*argv)[i++] = make_message("--link-dest=../%s", newest);
743 DSS_INFO_LOG("no previous snapshot found\n");
744 logname = dss_logname();
745 if (use_rsync_locally(logname))
746 (*argv)[i++] = dss_strdup(conf.source_dir_arg);
748 (*argv)[i++] = make_message("%s@%s:%s/", conf.remote_user_given?
749 conf.remote_user_arg : logname,
750 conf.remote_host_arg, conf.source_dir_arg);
752 *num = get_current_time();
753 (*argv)[i++] = incomplete_name(*num);
755 for (j = 0; j < i; j++)
756 DSS_DEBUG_LOG("argv[%d] = %s\n", j, (*argv)[j]);
759 static void free_rsync_argv(char **argv)
765 for (i = 0; argv[i]; i++)
770 static int create_snapshot(char **argv)
772 int ret, fds[3] = {0, 0, 0};
775 name = incomplete_name(current_snapshot_creation_time);
776 DSS_NOTICE_LOG("creating new snapshot %s\n", name);
778 ret = dss_exec(&rsync_pid, argv[0], argv, fds);
781 snapshot_creation_status = SCS_RSYNC_RUNNING;
785 static int select_loop(void)
788 /* check every 60 seconds for free disk space */
790 char **rsync_argv = NULL;
795 struct timeval now, *tvp;
798 tvp = NULL; /* sleep until rm process dies */
799 else { /* sleep one minute */
805 FD_SET(signal_pipe, &rfds);
806 DSS_DEBUG_LOG("tvp: %p, tv_sec : %lu\n", tvp, (long unsigned) tv.tv_sec);
807 ret = dss_select(signal_pipe + 1, &rfds, NULL, tvp);
810 if (FD_ISSET(signal_pipe, &rfds)) {
811 ret = handle_signal();
817 ret = disk_space_low();
820 low_disk_space = ret;
821 ret = try_to_free_disk_space(low_disk_space);
825 stop_rsync_process();
828 restart_rsync_process();
829 gettimeofday(&now, NULL);
830 if (tv_diff(&next_snapshot_time, &now, NULL) > 0)
832 switch (snapshot_creation_status) {
834 ret = pre_create_hook();
838 case SCS_PRE_HOOK_RUNNING:
840 case SCS_RSYNC_NEEDS_RESTART:
841 ret = create_snapshot(rsync_argv);
845 case SCS_PRE_HOOK_SUCCESS:
846 free_rsync_argv(rsync_argv);
847 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
848 ret = create_snapshot(rsync_argv);
852 case SCS_RSYNC_RUNNING:
854 case SCS_RSYNC_SUCCESS:
855 ret = post_create_hook();
859 case SCS_POST_HOOK_RUNNING:
867 static void exit_hook(int exit_code)
869 int fds[3] = {0, 0, 0};
870 char *argv[] = {conf.exit_hook_arg, dss_strerror(-exit_code), NULL};
873 if (!conf.exit_hook_given)
875 DSS_NOTICE_LOG("executing %s %s\n", argv[0], argv[1]);
876 dss_exec(&pid, conf.exit_hook_arg, argv, fds);
879 static int com_run(void)
883 if (conf.dry_run_given) {
884 DSS_ERROR_LOG("dry_run not supported by this command\n");
887 ret = install_sighandler(SIGHUP);
890 compute_next_snapshot_time();
892 if (ret >= 0) /* impossible */
898 static int com_prune(void)
901 struct snapshot_list sl;
902 struct disk_space ds;
904 ret = get_disk_space(".", &ds);
909 dss_get_snapshot_list(&sl);
910 ret = remove_outdated_snapshot(&sl);
911 free_snapshot_list(&sl);
916 ret = wait_for_rm_process();
921 dss_get_snapshot_list(&sl);
922 ret = remove_redundant_snapshot(&sl);
923 free_snapshot_list(&sl);
928 ret = wait_for_rm_process();
937 static int com_create(void)
942 if (conf.dry_run_given) {
945 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
946 for (i = 0; rsync_argv[i]; i++) {
948 msg = make_message("%s%s%s", tmp? tmp : "",
949 tmp? " " : "", rsync_argv[i]);
952 free_rsync_argv(rsync_argv);
953 dss_msg("%s\n", msg);
957 ret = pre_create_hook();
960 if (pre_create_hook_pid) {
961 ret = wait_for_process(pre_create_hook_pid, &status);
964 ret = handle_pre_create_hook_exit(status);
968 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
969 ret = create_snapshot(rsync_argv);
972 ret = wait_for_process(rsync_pid, &status);
975 ret = handle_rsync_exit(status);
979 if (post_create_hook_pid)
980 ret = wait_for_process(post_create_hook_pid, &status);
982 free_rsync_argv(rsync_argv);
986 static int com_ls(void)
989 struct snapshot_list sl;
992 dss_get_snapshot_list(&sl);
993 FOR_EACH_SNAPSHOT(s, i, &sl) {
995 if (s->flags & SS_COMPLETE)
996 d = (s->completion_time - s->creation_time) / 60;
997 dss_msg("%u\t%s\t%3" PRId64 ":%02" PRId64 "\n", s->interval, s->name, d/60, d%60);
999 free_snapshot_list(&sl);
1003 static int setup_signal_handling(void)
1007 DSS_INFO_LOG("setting up signal handlers\n");
1008 signal_pipe = signal_init(); /* always successful */
1009 ret = install_sighandler(SIGINT);
1012 ret = install_sighandler(SIGTERM);
1015 return install_sighandler(SIGCHLD);
1019 * The main function of dss.
1021 * \param argc Usual argument count.
1022 * \param argv Usual argument vector.
1024 int main(int argc, char **argv)
1027 struct cmdline_parser_params params = {
1030 .check_required = 0,
1031 .check_ambiguity = 0,
1035 cmdline_parser_ext(argc, argv, &conf, ¶ms); /* aborts on errors */
1036 ret = parse_config_file(0);
1039 if (conf.daemon_given)
1041 ret = change_to_dest_dir();
1044 ret = setup_signal_handling();
1047 ret = call_command_handler();
1050 DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
1051 exit(ret >= 0? EXIT_SUCCESS : EXIT_FAILURE);