2 * Copyright (C) 2008-2011 Andre Noll <maan@tuebingen.mpg.de>
4 * Licensed under the GPL v2. For licencing details see COPYING.
11 #include <sys/types.h>
24 #include "gcc-compat.h"
38 /** Command line and config file options. */
39 static struct gengetopt_args_info conf;
40 /** Non-NULL if we log to a file. */
42 /** The read end of the signal pipe */
43 static int signal_pipe;
44 /** Process id of current pre-create-hook/rsync/post-create-hook process. */
45 static pid_t create_pid;
46 /** Whether the pre-create-hook/rsync/post-create-hook is currently stopped. */
47 static int create_process_stopped;
48 /** How many times in a row the rsync command failed. */
49 static int num_consecutive_rsync_errors;
50 /** Process id of current pre-remove/rm/post-remove process. */
51 static pid_t remove_pid;
52 /** When the next snapshot is due. */
53 static int64_t next_snapshot_time;
54 /** When to try to remove something. */
55 static struct timeval next_removal_check;
56 /** Creation time of the snapshot currently being created. */
57 static int64_t current_snapshot_creation_time;
58 /** The snapshot currently being removed. */
59 struct snapshot *snapshot_currently_being_removed;
60 /** Needed by the post-create hook. */
61 static char *path_to_last_complete_snapshot;
62 static char *name_of_reference_snapshot;
63 /** \sa \ref snap.h for details. */
64 enum hook_status snapshot_creation_status;
65 /** \sa \ref snap.h for details. */
66 enum hook_status snapshot_removal_status;
70 static const char *hook_status_description[] = {HOOK_STATUS_ARRAY};
72 /* may be called with ds == NULL. */
73 static int disk_space_low(struct disk_space *ds)
75 struct disk_space ds_struct;
78 int ret = get_disk_space(".", &ds_struct);
83 if (conf.min_free_mb_arg)
84 if (ds->free_mb < conf.min_free_mb_arg)
86 if (conf.min_free_percent_arg)
87 if (ds->percent_free < conf.min_free_percent_arg)
89 if (conf.min_free_percent_inodes_arg)
90 if (ds->percent_free_inodes < conf.min_free_percent_inodes_arg)
95 static void dump_dss_config(const char *msg)
97 const char dash[] = "-----------------------------";
99 FILE *log = logfile? logfile : stderr;
100 struct disk_space ds;
101 int64_t now = get_current_time();
103 if (conf.loglevel_arg > INFO)
106 fprintf(log, "%s <%s config> %s\n", dash, msg, dash);
107 fprintf(log, "\n*** disk space ***\n\n");
108 ret = get_disk_space(".", &ds);
110 DSS_INFO_LOG(("disk space low: %s\n", disk_space_low(&ds)?
114 DSS_ERROR_LOG(("can not get free disk space: %s\n",
115 dss_strerror(-ret)));
117 /* we continue on errors from get_disk_space */
119 fprintf(log, "\n*** command line and config file options ***\n\n");
120 cmdline_parser_dump(log, &conf);
121 fprintf(log, "\n*** internal state ***\n\n");
125 "snapshot_currently_being_removed: %s\n"
126 "path_to_last_complete_snapshot: %s\n"
127 "reference_snapshot: %s\n"
128 "snapshot_creation_status: %s\n"
129 "snapshot_removal_status: %s\n"
130 "num_consecutive_rsync_errors: %d\n"
133 logfile? conf.logfile_arg : "stderr",
134 snapshot_currently_being_removed?
135 snapshot_currently_being_removed->name : "(none)",
136 path_to_last_complete_snapshot?
137 path_to_last_complete_snapshot : "(none)",
138 name_of_reference_snapshot?
139 name_of_reference_snapshot : "(none)",
140 hook_status_description[snapshot_creation_status],
141 hook_status_description[snapshot_removal_status],
142 num_consecutive_rsync_errors
146 "create_pid: %" PRId32 "\n"
147 "create process is %sstopped\n"
150 create_process_stopped? "" : "not "
153 fprintf(log, "remove_pid: %" PRId32 "\n", remove_pid);
154 if (next_snapshot_time != 0)
155 fprintf(log, "next snapshot due in %" PRId64 " seconds\n",
156 next_snapshot_time - now);
157 if (current_snapshot_creation_time != 0)
158 fprintf(log, "current_snapshot_creation_time: %"
159 PRId64 " (%" PRId64 " seconds ago)\n",
160 current_snapshot_creation_time,
161 now - current_snapshot_creation_time
163 if (next_removal_check.tv_sec != 0) {
164 fprintf(log, "next removal check: %llu (%llu seconds ago)\n",
165 (long long unsigned)next_removal_check.tv_sec,
166 now - (long long unsigned)next_removal_check.tv_sec
170 fprintf(log, "%s </%s config> %s\n", dash, msg, dash);
173 /* a litte cpp magic helps to DRY */
182 #define COMMAND(x) static int com_ ##x(void);
185 #define COMMAND(x) if (conf.x ##_given) return com_ ##x();
186 static int call_command_handler(void)
189 DSS_EMERG_LOG(("BUG: did not find command handler\n"));
195 static int loglevel = -1;
196 static const char *location_file = NULL;
197 static int location_line = -1;
198 static const char *location_func = NULL;
200 void dss_log_set_params(int ll, const char *file, int line, const char *func)
203 location_file = file;
204 location_line = line;
205 location_func = func;
209 * The log function of dss.
211 * \param ll Loglevel.
212 * \param fml Usual format string.
214 * All DSS_XXX_LOG() macros use this function.
216 __printf_1_2 void dss_log(const char* fmt,...)
224 if (loglevel < conf.loglevel_arg)
226 outfd = logfile? logfile : stderr;
229 strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
230 fprintf(outfd, "%s ", str);
231 if (conf.loglevel_arg <= INFO)
232 fprintf(outfd, "%i: ", loglevel);
233 #ifdef DSS_NO_FUNC_NAMES
234 fprintf(outfd, "%s:%d: ", location_file, location_line);
236 fprintf(outfd, "%s: ", location_func);
239 vfprintf(outfd, fmt, argp);
244 * Print a message either to stdout or to the log file.
246 static __printf_1_2 void dss_msg(const char* fmt,...)
248 FILE *outfd = conf.daemon_given? logfile : stdout;
251 vfprintf(outfd, fmt, argp);
255 static char *get_config_file_name(void)
257 char *home, *config_file;
259 if (conf.config_file_given)
260 return dss_strdup(conf.config_file_arg);
261 home = get_homedir();
262 config_file = make_message("%s/.dssrc", home);
267 static int send_signal(int sig)
270 char *config_file = get_config_file_name();
271 int ret = get_dss_pid(config_file, &pid);
276 if (conf.dry_run_given) {
277 dss_msg("%d\n", (int)pid);
280 ret = kill(pid, sig);
282 return -ERRNO_TO_DSS_ERROR(errno);
286 static int com_kill(void)
288 return send_signal(SIGTERM);
291 static int com_reload(void)
293 return send_signal(SIGHUP);
296 static void dss_get_snapshot_list(struct snapshot_list *sl)
298 get_snapshot_list(sl, conf.unit_interval_arg, conf.num_intervals_arg);
301 static int64_t compute_next_snapshot_time(void)
303 int64_t x = 0, now = get_current_time(), unit_interval
304 = 24 * 3600 * conf.unit_interval_arg, ret;
305 unsigned wanted = desired_number_of_snapshots(0, conf.num_intervals_arg),
306 num_complete_snapshots = 0;
308 struct snapshot *s = NULL;
309 struct snapshot_list sl;
311 dss_get_snapshot_list(&sl);
312 FOR_EACH_SNAPSHOT(s, i, &sl) {
313 if (!(s->flags & SS_COMPLETE))
315 num_complete_snapshots++;
316 x += s->completion_time - s->creation_time;
321 if (num_complete_snapshots == 0)
323 x /= num_complete_snapshots; /* avg time to create one snapshot */
324 if (unit_interval < x * wanted) /* oops, no sleep at all */
326 ret = s->completion_time + unit_interval / wanted - x;
328 free_snapshot_list(&sl);
332 static inline void invalidate_next_snapshot_time(void)
334 next_snapshot_time = 0;
337 static inline int next_snapshot_time_is_valid(void)
339 return next_snapshot_time != 0;
342 static int next_snapshot_is_due(void)
344 int64_t now = get_current_time();
346 if (!next_snapshot_time_is_valid())
347 next_snapshot_time = compute_next_snapshot_time();
348 if (next_snapshot_time <= now) {
349 DSS_DEBUG_LOG(("next snapshot: now\n"));
352 DSS_DEBUG_LOG(("next snapshot due in %" PRId64 " seconds\n",
353 next_snapshot_time - now));
357 static void pre_create_hook(void)
359 assert(snapshot_creation_status == HS_READY);
360 /* make sure that the next snapshot time will be recomputed */
361 invalidate_next_snapshot_time();
362 DSS_DEBUG_LOG(("executing %s\n", conf.pre_create_hook_arg));
363 dss_exec_cmdline_pid(&create_pid, conf.pre_create_hook_arg);
364 snapshot_creation_status = HS_PRE_RUNNING;
367 static void pre_remove_hook(struct snapshot *s, const char *why)
373 DSS_DEBUG_LOG(("%s snapshot %s\n", why, s->name));
374 assert(snapshot_removal_status == HS_READY);
375 assert(remove_pid == 0);
376 assert(!snapshot_currently_being_removed);
378 snapshot_currently_being_removed = dss_malloc(sizeof(struct snapshot));
379 *snapshot_currently_being_removed = *s;
380 snapshot_currently_being_removed->name = dss_strdup(s->name);
382 cmd = make_message("%s %s/%s", conf.pre_remove_hook_arg,
383 conf.dest_dir_arg, s->name);
384 DSS_DEBUG_LOG(("executing %s\n", cmd));
385 dss_exec_cmdline_pid(&remove_pid, cmd);
387 snapshot_removal_status = HS_PRE_RUNNING;
390 static int exec_rm(void)
392 struct snapshot *s = snapshot_currently_being_removed;
393 char *new_name = being_deleted_name(s);
402 assert(snapshot_removal_status == HS_PRE_SUCCESS);
403 assert(remove_pid == 0);
405 DSS_NOTICE_LOG(("removing %s (interval = %i)\n", s->name, s->interval));
406 ret = dss_rename(s->name, new_name);
409 dss_exec(&remove_pid, argv[0], argv);
410 snapshot_removal_status = HS_RUNNING;
416 static int snapshot_is_being_created(struct snapshot *s)
418 return s->creation_time == current_snapshot_creation_time;
421 static struct snapshot *find_orphaned_snapshot(struct snapshot_list *sl)
426 DSS_DEBUG_LOG(("looking for orphaned snapshots\n"));
427 FOR_EACH_SNAPSHOT(s, i, sl) {
428 if (snapshot_is_being_created(s))
431 * We know that no rm is currently running, so if s is marked
432 * as being deleted, a previously started rm must have failed.
434 if (s->flags & SS_BEING_DELETED)
437 if (s->flags & SS_COMPLETE) /* good snapshot */
440 * This snapshot is incomplete and it is not the snapshot
441 * currently being created. However, we must not remove it if
442 * rsync is about to be restarted. As only the newest snapshot
443 * can be restarted, this snapshot is orphaned if it is not the
444 * newest snapshot or if we are not about to restart rsync.
446 if (get_newest_snapshot(sl) != s)
448 if (snapshot_creation_status != HS_NEEDS_RESTART)
451 /* no orphaned snapshots */
455 static int is_reference_snapshot(struct snapshot *s)
457 if (!name_of_reference_snapshot)
459 return strcmp(s->name, name_of_reference_snapshot)? 0 : 1;
463 * return: 0: no redundant snapshots, 1: rm process started, negative: error
465 static struct snapshot *find_redundant_snapshot(struct snapshot_list *sl)
469 unsigned missing = 0;
471 DSS_DEBUG_LOG(("looking for intervals containing too many snapshots\n"));
472 for (interval = conf.num_intervals_arg - 1; interval >= 0; interval--) {
473 unsigned keep = desired_number_of_snapshots(interval, conf.num_intervals_arg);
474 unsigned num = sl->interval_count[interval];
475 struct snapshot *victim = NULL, *prev = NULL;
476 int64_t score = LONG_MAX;
479 missing += keep - num;
480 if (keep + missing >= num)
482 /* redundant snapshot in this interval, pick snapshot with lowest score */
483 FOR_EACH_SNAPSHOT(s, i, sl) {
486 if (snapshot_is_being_created(s))
488 if (is_reference_snapshot(s))
490 if (s->interval > interval) {
494 if (s->interval < interval)
502 /* check if s is a better victim */
503 this_score = s->creation_time - prev->creation_time;
504 assert(this_score >= 0);
505 if (this_score < score) {
517 static struct snapshot *find_outdated_snapshot(struct snapshot_list *sl)
522 DSS_DEBUG_LOG(("looking for snapshots belonging to intervals >= %d\n",
523 conf.num_intervals_arg));
524 FOR_EACH_SNAPSHOT(s, i, sl) {
525 if (snapshot_is_being_created(s))
527 if (is_reference_snapshot(s))
529 if (s->interval < conf.num_intervals_arg)
536 static struct snapshot *find_oldest_removable_snapshot(struct snapshot_list *sl)
539 struct snapshot *s, *ref = NULL;
541 num_complete = num_complete_snapshots(sl);
542 if (num_complete <= conf.min_complete_arg)
544 FOR_EACH_SNAPSHOT(s, i, sl) {
545 if (snapshot_is_being_created(s))
547 if (is_reference_snapshot(s)) { /* avoid this one */
551 DSS_INFO_LOG(("oldest removable snapshot: %s\n", s->name));
555 DSS_WARNING_LOG(("removing reference snapshot %s\n", ref->name));
559 static int rename_incomplete_snapshot(int64_t start)
566 * We don't want the dss_rename() below to fail with EEXIST because the
567 * last complete snapshot was created (and completed) in the same
568 * second as this one.
570 while ((now = get_current_time()) == start)
572 free(path_to_last_complete_snapshot);
573 ret = complete_name(start, now, &path_to_last_complete_snapshot);
576 old_name = incomplete_name(start);
577 ret = dss_rename(old_name, path_to_last_complete_snapshot);
579 DSS_NOTICE_LOG(("%s -> %s\n", old_name,
580 path_to_last_complete_snapshot));
585 static int try_to_free_disk_space(void)
588 struct snapshot_list sl;
589 struct snapshot *victim;
594 ret = disk_space_low(NULL);
597 low_disk_space = ret;
598 gettimeofday(&now, NULL);
599 if (tv_diff(&next_removal_check, &now, NULL) > 0)
601 if (!low_disk_space) {
602 if (conf.keep_redundant_given)
604 if (snapshot_creation_status != HS_READY)
606 if (next_snapshot_is_due())
609 dss_get_snapshot_list(&sl);
611 if (!low_disk_space && sl.num_snapshots <= 1)
614 victim = find_outdated_snapshot(&sl);
618 victim = find_redundant_snapshot(&sl);
621 /* try harder only if disk space is low */
625 victim = find_orphaned_snapshot(&sl);
628 DSS_WARNING_LOG(("disk space low and nothing obvious to remove\n"));
629 victim = find_oldest_removable_snapshot(&sl);
632 DSS_CRIT_LOG(("uhuhu: disk space low and nothing to remove\n"));
633 ret = -ERRNO_TO_DSS_ERROR(ENOSPC);
636 pre_remove_hook(victim, why);
638 free_snapshot_list(&sl);
642 static void post_create_hook(void)
644 char *cmd = make_message("%s %s/%s", conf.post_create_hook_arg,
645 conf.dest_dir_arg, path_to_last_complete_snapshot);
646 DSS_NOTICE_LOG(("executing %s\n", cmd));
647 dss_exec_cmdline_pid(&create_pid, cmd);
649 snapshot_creation_status = HS_POST_RUNNING;
652 static void post_remove_hook(void)
655 struct snapshot *s = snapshot_currently_being_removed;
659 cmd = make_message("%s %s/%s", conf.post_remove_hook_arg,
660 conf.dest_dir_arg, s->name);
661 DSS_NOTICE_LOG(("executing %s\n", cmd));
662 dss_exec_cmdline_pid(&remove_pid, cmd);
664 snapshot_removal_status = HS_POST_RUNNING;
667 static void dss_kill(pid_t pid, int sig, const char *msg)
669 const char *signame, *process_name;
674 case SIGTERM: signame = "TERM"; break;
675 case SIGSTOP: signame = "STOP"; break;
676 case SIGCONT: signame = "CONT"; break;
677 default: signame = "????";
680 if (pid == create_pid)
681 process_name = "create";
682 else if (pid == remove_pid)
683 process_name = "remove";
684 else process_name = "??????";
687 DSS_INFO_LOG(("%s\n", msg));
688 DSS_DEBUG_LOG(("sending signal %d (%s) to pid %d (%s process)\n",
689 sig, signame, (int)pid, process_name));
690 if (kill(pid, sig) >= 0)
692 DSS_INFO_LOG(("failed to send signal %d (%s) to pid %d (%s process)\n",
693 sig, signame, (int)pid, process_name));
696 static void stop_create_process(void)
698 if (create_process_stopped)
700 dss_kill(create_pid, SIGSTOP, "suspending create process");
701 create_process_stopped = 1;
704 static void restart_create_process(void)
706 if (!create_process_stopped)
708 dss_kill(create_pid, SIGCONT, "resuming create process");
709 create_process_stopped = 0;
713 * Print a log message about the exit status of a child.
715 static void log_termination_msg(pid_t pid, int status)
717 if (WIFEXITED(status))
718 DSS_INFO_LOG(("child %i exited. Exit status: %i\n", (int)pid,
719 WEXITSTATUS(status)));
720 else if (WIFSIGNALED(status))
721 DSS_NOTICE_LOG(("child %i was killed by signal %i\n", (int)pid,
724 DSS_WARNING_LOG(("child %i terminated abormally\n", (int)pid));
727 static int wait_for_process(pid_t pid, int *status)
731 DSS_DEBUG_LOG(("Waiting for process %d to terminate\n", (int)pid));
736 FD_SET(signal_pipe, &rfds);
737 ret = dss_select(signal_pipe + 1, &rfds, NULL, NULL);
743 if (ret == SIGCHLD) {
744 ret = waitpid(pid, status, 0);
747 if (errno != EINTR) { /* error */
748 ret = -ERRNO_TO_DSS_ERROR(errno);
752 /* SIGINT or SIGTERM */
753 dss_kill(pid, SIGTERM, "killing child process");
756 DSS_ERROR_LOG(("failed to wait for process %d\n", (int)pid));
758 log_termination_msg(pid, *status);
762 static void handle_pre_remove_exit(int status)
764 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
765 snapshot_removal_status = HS_READY;
766 gettimeofday(&next_removal_check, NULL);
767 next_removal_check.tv_sec += 60;
770 snapshot_removal_status = HS_PRE_SUCCESS;
773 static int handle_rm_exit(int status)
775 if (!WIFEXITED(status)) {
776 snapshot_removal_status = HS_READY;
777 return -E_INVOLUNTARY_EXIT;
779 if (WEXITSTATUS(status)) {
780 snapshot_removal_status = HS_READY;
781 return -E_BAD_EXIT_CODE;
783 snapshot_removal_status = HS_SUCCESS;
787 static void handle_post_remove_exit(void)
789 snapshot_removal_status = HS_READY;
792 static int handle_remove_exit(int status)
795 struct snapshot *s = snapshot_currently_being_removed;
798 switch (snapshot_removal_status) {
800 handle_pre_remove_exit(status);
804 ret = handle_rm_exit(status);
806 case HS_POST_RUNNING:
807 handle_post_remove_exit();
813 if (snapshot_removal_status == HS_READY) {
816 snapshot_currently_being_removed = NULL;
822 static int wait_for_remove_process(void)
828 snapshot_removal_status == HS_PRE_RUNNING ||
829 snapshot_removal_status == HS_RUNNING ||
830 snapshot_removal_status == HS_POST_RUNNING
832 ret = wait_for_process(remove_pid, &status);
835 return handle_remove_exit(status);
838 static int handle_rsync_exit(int status)
842 if (!WIFEXITED(status)) {
843 DSS_ERROR_LOG(("rsync process %d died involuntary\n", (int)create_pid));
844 ret = -E_INVOLUNTARY_EXIT;
845 snapshot_creation_status = HS_READY;
848 es = WEXITSTATUS(status);
850 * Restart rsync on non-fatal errors:
851 * 24: Partial transfer due to vanished source files
853 if (es != 0 && es != 24) {
854 DSS_WARNING_LOG(("rsync exit code %d, error count %d\n",
855 es, ++num_consecutive_rsync_errors));
856 if (num_consecutive_rsync_errors > conf.max_rsync_errors_arg) {
857 ret = -E_TOO_MANY_RSYNC_ERRORS;
858 snapshot_creation_status = HS_READY;
861 DSS_WARNING_LOG(("restarting rsync process\n"));
862 snapshot_creation_status = HS_NEEDS_RESTART;
863 next_snapshot_time = get_current_time() + 60;
867 num_consecutive_rsync_errors = 0;
868 ret = rename_incomplete_snapshot(current_snapshot_creation_time);
871 snapshot_creation_status = HS_SUCCESS;
872 free(name_of_reference_snapshot);
873 name_of_reference_snapshot = NULL;
875 create_process_stopped = 0;
879 static int handle_pre_create_hook_exit(int status)
882 static int warn_count;
884 if (!WIFEXITED(status)) {
885 snapshot_creation_status = HS_READY;
886 ret = -E_INVOLUNTARY_EXIT;
889 es = WEXITSTATUS(status);
892 DSS_NOTICE_LOG(("pre_create_hook %s returned %d\n",
893 conf.pre_create_hook_arg, es));
894 DSS_NOTICE_LOG(("deferring snapshot creation...\n"));
895 warn_count = 60; /* warn only once per hour */
897 next_snapshot_time = get_current_time() + 60;
898 snapshot_creation_status = HS_READY;
903 snapshot_creation_status = HS_PRE_SUCCESS;
909 static int handle_sigchld(void)
912 int status, ret = reap_child(&pid, &status);
917 if (pid == create_pid) {
918 switch (snapshot_creation_status) {
920 ret = handle_pre_create_hook_exit(status);
923 ret = handle_rsync_exit(status);
925 case HS_POST_RUNNING:
926 snapshot_creation_status = HS_READY;
930 DSS_EMERG_LOG(("BUG: create can't die in status %d\n",
931 snapshot_creation_status));
937 if (pid == remove_pid) {
938 ret = handle_remove_exit(status);
943 DSS_EMERG_LOG(("BUG: unknown process %d died\n", (int)pid));
947 static int check_config(void)
949 if (conf.unit_interval_arg <= 0) {
950 DSS_ERROR_LOG(("bad unit interval: %i\n", conf.unit_interval_arg));
951 return -E_INVALID_NUMBER;
953 DSS_DEBUG_LOG(("unit interval: %i day(s)\n", conf.unit_interval_arg));
954 if (conf.num_intervals_arg <= 0 || conf.num_intervals_arg > 30) {
955 DSS_ERROR_LOG(("bad number of intervals: %i\n",
956 conf.num_intervals_arg));
957 return -E_INVALID_NUMBER;
959 DSS_DEBUG_LOG(("number of intervals: %i\n", conf.num_intervals_arg));
964 * Returns < 0 on errors, 0 if no config file is given and > 0 if the config
965 * file was read successfully.
967 static int parse_config_file(int override)
969 int ret, config_file_exists;
970 char *config_file = get_config_file_name();
972 char *old_logfile_arg = NULL;
973 int old_daemon_given = 0;
975 if (override) { /* SIGHUP */
976 if (conf.logfile_given)
977 old_logfile_arg = dss_strdup(conf.logfile_arg);
978 old_daemon_given = conf.daemon_given;
981 config_file_exists = !stat(config_file, &statbuf);
982 if (!config_file_exists && conf.config_file_given) {
983 ret = -ERRNO_TO_DSS_ERROR(errno);
984 DSS_ERROR_LOG(("failed to stat config file %s\n", config_file));
987 if (config_file_exists) {
988 struct cmdline_parser_params params;
989 params.override = override;
990 params.initialize = 0;
991 params.check_required = 1;
992 params.check_ambiguity = 0;
993 params.print_errors = 1;
994 if (override) { /* invalidate all rsync options */
997 for (i = 0; i < conf.rsync_option_given; i++) {
998 free(conf.rsync_option_arg[i]);
999 conf.rsync_option_arg[i] = NULL;
1001 conf.rsync_option_given = 0;
1003 cmdline_parser_config_file(config_file, &conf, ¶ms);
1005 ret = check_config();
1009 /* don't change daemon mode on SIGHUP */
1010 conf.daemon_given = old_daemon_given;
1013 if (conf.logfile_given)
1014 free(old_logfile_arg);
1015 else if (conf.daemon_given) { /* re-use old logfile */
1016 conf.logfile_arg = old_logfile_arg;
1017 conf.logfile_given = 1;
1020 if (conf.logfile_given && conf.run_given && conf.daemon_given) {
1021 logfile = open_log(conf.logfile_arg);
1022 log_welcome(conf.loglevel_arg);
1024 DSS_DEBUG_LOG(("loglevel: %d\n", conf.loglevel_arg));
1025 ret = config_file_exists;
1029 DSS_EMERG_LOG(("%s\n", dss_strerror(-ret)));
1033 static int change_to_dest_dir(void)
1035 DSS_INFO_LOG(("changing cwd to %s\n", conf.dest_dir_arg));
1036 return dss_chdir(conf.dest_dir_arg);
1039 static int handle_sighup(void)
1043 DSS_NOTICE_LOG(("SIGHUP, re-reading config\n"));
1044 dump_dss_config("old");
1045 ret = parse_config_file(1);
1048 dump_dss_config("reloaded");
1049 invalidate_next_snapshot_time();
1050 return change_to_dest_dir();
1053 static void kill_children(void)
1055 restart_create_process();
1056 dss_kill(create_pid, SIGTERM, NULL);
1057 dss_kill(remove_pid, SIGTERM, NULL);
1060 static int handle_signal(void)
1062 int sig, ret = next_signal();
1074 ret = handle_sighup();
1077 ret = handle_sigchld();
1082 DSS_ERROR_LOG(("%s\n", dss_strerror(-ret)));
1087 * We can not use rsync locally if the local user is different from the remote
1088 * user or if the src dir is not on the local host (or both).
1090 static int use_rsync_locally(char *logname)
1092 char *h = conf.remote_host_arg;
1094 if (strcmp(h, "localhost") && strcmp(h, "127.0.0.1"))
1096 if (conf.remote_user_given && strcmp(conf.remote_user_arg, logname))
1101 static int rename_resume_snap(int64_t creation_time)
1103 struct snapshot_list sl;
1104 struct snapshot *s = NULL;
1105 char *new_name = incomplete_name(creation_time);
1109 sl.num_snapshots = 0;
1112 if (conf.no_resume_given)
1114 dss_get_snapshot_list(&sl);
1116 * Snapshot recycling: We first look at the newest snapshot. If this
1117 * snapshot happens to be incomplete, the last rsync process was
1118 * aborted and we reuse this one. Otherwise we look at snapshots which
1119 * could be removed (outdated and redundant snapshots) as candidates
1120 * for recycling. If no outdated/redundant snapshot exists, we check if
1121 * there is an orphaned snapshot, which likely is useless anyway.
1123 * Only if no existing snapshot is suitable for recycling, we bite the
1124 * bullet and create a new one.
1126 s = get_newest_snapshot(&sl);
1127 if (!s) /* no snapshots at all */
1129 /* re-use last snapshot if it is incomplete */
1131 if ((s->flags & SS_COMPLETE) == 0)
1134 s = find_outdated_snapshot(&sl);
1138 s = find_redundant_snapshot(&sl);
1142 s = find_orphaned_snapshot(&sl);
1145 DSS_INFO_LOG(("reusing %s snapshot %s\n", why, s->name));
1146 ret = dss_rename(s->name, new_name);
1149 DSS_NOTICE_LOG(("creating new snapshot %s\n", new_name));
1151 free_snapshot_list(&sl);
1155 static void create_rsync_argv(char ***argv, int64_t *num)
1159 struct snapshot_list sl;
1161 dss_get_snapshot_list(&sl);
1162 assert(!name_of_reference_snapshot);
1163 name_of_reference_snapshot = name_of_newest_complete_snapshot(&sl);
1164 free_snapshot_list(&sl);
1166 *argv = dss_malloc((15 + conf.rsync_option_given) * sizeof(char *));
1167 (*argv)[i++] = dss_strdup("rsync");
1168 (*argv)[i++] = dss_strdup("-a");
1169 (*argv)[i++] = dss_strdup("--delete");
1170 for (j = 0; j < conf.rsync_option_given; j++)
1171 (*argv)[i++] = dss_strdup(conf.rsync_option_arg[j]);
1172 if (name_of_reference_snapshot) {
1173 DSS_INFO_LOG(("using %s as reference\n", name_of_reference_snapshot));
1174 (*argv)[i++] = make_message("--link-dest=../%s",
1175 name_of_reference_snapshot);
1177 DSS_INFO_LOG(("no suitable reference snapshot found\n"));
1178 logname = dss_logname();
1179 if (use_rsync_locally(logname))
1180 (*argv)[i++] = dss_strdup(conf.source_dir_arg);
1182 (*argv)[i++] = make_message("%s@%s:%s/", conf.remote_user_given?
1183 conf.remote_user_arg : logname,
1184 conf.remote_host_arg, conf.source_dir_arg);
1186 *num = get_current_time();
1187 (*argv)[i++] = incomplete_name(*num);
1188 (*argv)[i++] = NULL;
1189 for (j = 0; j < i; j++)
1190 DSS_DEBUG_LOG(("argv[%d] = %s\n", j, (*argv)[j]));
1193 static void free_rsync_argv(char **argv)
1199 for (i = 0; argv[i]; i++)
1204 static int create_snapshot(char **argv)
1208 ret = rename_resume_snap(current_snapshot_creation_time);
1211 dss_exec(&create_pid, argv[0], argv);
1212 snapshot_creation_status = HS_RUNNING;
1216 static int select_loop(void)
1219 /* check every 60 seconds for free disk space */
1221 char **rsync_argv = NULL;
1225 struct timeval *tvp;
1228 tvp = NULL; /* sleep until rm hook/process dies */
1229 else { /* sleep one minute */
1235 FD_SET(signal_pipe, &rfds);
1236 ret = dss_select(signal_pipe + 1, &rfds, NULL, tvp);
1239 if (FD_ISSET(signal_pipe, &rfds)) {
1240 ret = handle_signal();
1246 if (snapshot_removal_status == HS_PRE_SUCCESS) {
1252 if (snapshot_removal_status == HS_SUCCESS) {
1256 ret = try_to_free_disk_space();
1259 if (snapshot_removal_status != HS_READY) {
1260 stop_create_process();
1263 restart_create_process();
1264 switch (snapshot_creation_status) {
1266 if (!next_snapshot_is_due())
1270 case HS_PRE_RUNNING:
1272 case HS_POST_RUNNING:
1274 case HS_PRE_SUCCESS:
1275 if (!name_of_reference_snapshot) {
1276 free_rsync_argv(rsync_argv);
1277 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
1279 ret = create_snapshot(rsync_argv);
1283 case HS_NEEDS_RESTART:
1284 if (!next_snapshot_is_due())
1286 ret = create_snapshot(rsync_argv);
1299 static void exit_hook(int exit_code)
1304 argv[0] = conf.exit_hook_arg;
1305 argv[1] = dss_strerror(-exit_code);
1308 DSS_NOTICE_LOG(("executing %s %s\n", argv[0], argv[1]));
1309 dss_exec(&pid, conf.exit_hook_arg, argv);
1312 static void lock_dss_or_die(void)
1314 char *config_file = get_config_file_name();
1315 int ret = lock_dss(config_file);
1319 DSS_EMERG_LOG(("failed to lock: %s\n", dss_strerror(-ret)));
1324 static int com_run(void)
1329 if (conf.dry_run_given) {
1330 DSS_ERROR_LOG(("dry_run not supported by this command\n"));
1333 ret = install_sighandler(SIGHUP);
1336 ret = select_loop();
1337 if (ret >= 0) /* impossible */
1344 static int com_prune(void)
1347 struct snapshot_list sl;
1348 struct snapshot *victim;
1349 struct disk_space ds;
1353 ret = get_disk_space(".", &ds);
1356 log_disk_space(&ds);
1357 dss_get_snapshot_list(&sl);
1359 victim = find_outdated_snapshot(&sl);
1363 victim = find_redundant_snapshot(&sl);
1369 if (conf.dry_run_given) {
1370 dss_msg("%s snapshot %s (interval = %i)\n",
1371 why, victim->name, victim->interval);
1375 pre_remove_hook(victim, why);
1376 if (snapshot_removal_status == HS_PRE_RUNNING) {
1377 ret = wait_for_remove_process();
1380 if (snapshot_removal_status != HS_PRE_SUCCESS)
1386 ret = wait_for_remove_process();
1389 if (snapshot_removal_status != HS_SUCCESS)
1392 if (snapshot_removal_status != HS_POST_RUNNING)
1394 ret = wait_for_remove_process();
1399 free_snapshot_list(&sl);
1403 static int com_create(void)
1409 if (conf.dry_run_given) {
1412 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
1413 for (i = 0; rsync_argv[i]; i++) {
1415 msg = make_message("%s%s%s", tmp? tmp : "",
1416 tmp? " " : "", rsync_argv[i]);
1419 free_rsync_argv(rsync_argv);
1420 dss_msg("%s\n", msg);
1426 ret = wait_for_process(create_pid, &status);
1429 ret = handle_pre_create_hook_exit(status);
1430 if (ret <= 0) /* error, or pre-create failed */
1433 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
1434 ret = create_snapshot(rsync_argv);
1437 ret = wait_for_process(create_pid, &status);
1440 ret = handle_rsync_exit(status);
1445 ret = wait_for_process(create_pid, &status);
1447 free_rsync_argv(rsync_argv);
1451 static int com_ls(void)
1454 struct snapshot_list sl;
1457 dss_get_snapshot_list(&sl);
1458 FOR_EACH_SNAPSHOT(s, i, &sl) {
1460 if (s->flags & SS_COMPLETE)
1461 d = (s->completion_time - s->creation_time) / 60;
1462 dss_msg("%u\t%s\t%3" PRId64 ":%02" PRId64 "\n", s->interval, s->name, d/60, d%60);
1464 free_snapshot_list(&sl);
1468 static int setup_signal_handling(void)
1472 DSS_INFO_LOG(("setting up signal handlers\n"));
1473 signal_pipe = signal_init(); /* always successful */
1474 ret = install_sighandler(SIGINT);
1477 ret = install_sighandler(SIGTERM);
1480 return install_sighandler(SIGCHLD);
1484 * The main function of dss.
1486 * \param argc Usual argument count.
1487 * \param argv Usual argument vector.
1489 int main(int argc, char **argv)
1492 struct cmdline_parser_params params;
1494 params.override = 0;
1495 params.initialize = 1;
1496 params.check_required = 0;
1497 params.check_ambiguity = 0;
1498 params.print_errors = 1;
1500 cmdline_parser_ext(argc, argv, &conf, ¶ms); /* aborts on errors */
1501 ret = parse_config_file(0);
1504 if (ret == 0) { /* no config file given */
1506 * Parse the command line options again, but this time check
1507 * that all required options are given.
1509 struct cmdline_parser_params params;
1510 params.override = 1;
1511 params.initialize = 1;
1512 params.check_required = 1;
1513 params.check_ambiguity = 1;
1514 params.print_errors = 1;
1515 cmdline_parser_ext(argc, argv, &conf, ¶ms); /* aborts on errors */
1517 if (conf.daemon_given)
1519 ret = change_to_dest_dir();
1522 dump_dss_config("startup");
1523 ret = setup_signal_handling();
1526 ret = call_command_handler();
1530 DSS_EMERG_LOG(("%s\n", dss_strerror(-ret)));
1531 exit(ret >= 0? EXIT_SUCCESS : EXIT_FAILURE);