2 * Copyright (C) 2008-2011 Andre Noll <maan@tuebingen.mpg.de>
4 * Licensed under the GPL v2. For licencing details see COPYING.
12 #include <sys/types.h>
26 #include "gcc-compat.h"
40 /** Command line and config file options. */
41 static struct gengetopt_args_info conf;
42 /** Non-NULL if we log to a file. */
44 /** The read end of the signal pipe */
45 static int signal_pipe;
46 /** Process id of current pre-create-hook/rsync/post-create-hook process. */
47 static pid_t create_pid;
48 /** Whether the pre-create-hook/rsync/post-create-hook is currently stopped. */
49 static int create_process_stopped;
50 /** How many times in a row the rsync command failed. */
51 static int num_consecutive_rsync_errors;
52 /** Process id of current pre-remove/rm/post-remove process. */
53 static pid_t remove_pid;
54 /** When the next snapshot is due. */
55 static int64_t next_snapshot_time;
56 /** When to try to remove something. */
57 static struct timeval next_removal_check;
58 /** Creation time of the snapshot currently being created. */
59 static int64_t current_snapshot_creation_time;
60 /** The snapshot currently being removed. */
61 struct snapshot *snapshot_currently_being_removed;
62 /** Needed by the post-create hook. */
63 static char *path_to_last_complete_snapshot;
64 static char *name_of_reference_snapshot;
65 /** \sa \ref snap.h for details. */
66 enum hook_status snapshot_creation_status;
67 /** \sa \ref snap.h for details. */
68 enum hook_status snapshot_removal_status;
72 static const char *hook_status_description[] = {HOOK_STATUS_ARRAY};
74 /* may be called with ds == NULL. */
75 static int disk_space_low(struct disk_space *ds)
77 struct disk_space ds_struct;
80 int ret = get_disk_space(".", &ds_struct);
85 if (conf.min_free_mb_arg)
86 if (ds->free_mb < conf.min_free_mb_arg)
88 if (conf.min_free_percent_arg)
89 if (ds->percent_free < conf.min_free_percent_arg)
91 if (conf.min_free_percent_inodes_arg)
92 if (ds->percent_free_inodes < conf.min_free_percent_inodes_arg)
97 static void dump_dss_config(const char *msg)
99 const char dash[] = "-----------------------------";
101 FILE *log = logfile? logfile : stderr;
102 struct disk_space ds;
103 int64_t now = get_current_time();
105 if (conf.loglevel_arg > INFO)
108 fprintf(log, "%s <%s config> %s\n", dash, msg, dash);
109 fprintf(log, "\n*** disk space ***\n\n");
110 ret = get_disk_space(".", &ds);
112 DSS_INFO_LOG(("disk space low: %s\n", disk_space_low(&ds)?
116 DSS_ERROR_LOG(("can not get free disk space: %s\n",
117 dss_strerror(-ret)));
119 /* we continue on errors from get_disk_space */
121 fprintf(log, "\n*** command line and config file options ***\n\n");
122 cmdline_parser_dump(log, &conf);
123 fprintf(log, "\n*** internal state ***\n\n");
127 "snapshot_currently_being_removed: %s\n"
128 "path_to_last_complete_snapshot: %s\n"
129 "reference_snapshot: %s\n"
130 "snapshot_creation_status: %s\n"
131 "snapshot_removal_status: %s\n"
132 "num_consecutive_rsync_errors: %d\n"
135 logfile? conf.logfile_arg : "stderr",
136 snapshot_currently_being_removed?
137 snapshot_currently_being_removed->name : "(none)",
138 path_to_last_complete_snapshot?
139 path_to_last_complete_snapshot : "(none)",
140 name_of_reference_snapshot?
141 name_of_reference_snapshot : "(none)",
142 hook_status_description[snapshot_creation_status],
143 hook_status_description[snapshot_removal_status],
144 num_consecutive_rsync_errors
148 "create_pid: %" PRId32 "\n"
149 "create process is %sstopped\n"
152 create_process_stopped? "" : "not "
155 fprintf(log, "remove_pid: %" PRId32 "\n", remove_pid);
156 if (next_snapshot_time != 0)
157 fprintf(log, "next snapshot due in %" PRId64 " seconds\n",
158 next_snapshot_time - now);
159 if (current_snapshot_creation_time != 0)
160 fprintf(log, "current_snapshot_creation_time: %"
161 PRId64 " (%" PRId64 " seconds ago)\n",
162 current_snapshot_creation_time,
163 now - current_snapshot_creation_time
165 if (next_removal_check.tv_sec != 0) {
166 fprintf(log, "next removal check: %llu (%llu seconds ago)\n",
167 (long long unsigned)next_removal_check.tv_sec,
168 now - (long long unsigned)next_removal_check.tv_sec
172 fprintf(log, "%s </%s config> %s\n", dash, msg, dash);
175 /* a litte cpp magic helps to DRY */
184 #define COMMAND(x) static int com_ ##x(void);
187 #define COMMAND(x) if (conf.x ##_given) return com_ ##x();
188 static int call_command_handler(void)
191 DSS_EMERG_LOG(("BUG: did not find command handler\n"));
197 static int loglevel = -1;
198 static const char *location_file = NULL;
199 static int location_line = -1;
200 static const char *location_func = NULL;
202 void dss_log_set_params(int ll, const char *file, int line, const char *func)
205 location_file = file;
206 location_line = line;
207 location_func = func;
211 * The log function of dss.
213 * \param ll Loglevel.
214 * \param fml Usual format string.
216 * All DSS_XXX_LOG() macros use this function.
218 __printf_1_2 void dss_log(const char* fmt,...)
226 if (loglevel < conf.loglevel_arg)
228 outfd = logfile? logfile : stderr;
231 strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
232 fprintf(outfd, "%s ", str);
233 if (conf.loglevel_arg <= INFO)
234 fprintf(outfd, "%i: ", loglevel);
235 #ifdef DSS_NO_FUNC_NAMES
236 fprintf(outfd, "%s:%d: ", location_file, location_line);
238 fprintf(outfd, "%s: ", location_func);
241 vfprintf(outfd, fmt, argp);
246 * Print a message either to stdout or to the log file.
248 static __printf_1_2 void dss_msg(const char* fmt,...)
250 FILE *outfd = conf.daemon_given? logfile : stdout;
253 vfprintf(outfd, fmt, argp);
257 static char *get_config_file_name(void)
259 char *home, *config_file;
261 if (conf.config_file_given)
262 return dss_strdup(conf.config_file_arg);
263 home = get_homedir();
264 config_file = make_message("%s/.dssrc", home);
269 static int send_signal(int sig)
272 char *config_file = get_config_file_name();
273 int ret = get_dss_pid(config_file, &pid);
278 if (conf.dry_run_given) {
279 dss_msg("%d\n", (int)pid);
282 ret = kill(pid, sig);
284 return -ERRNO_TO_DSS_ERROR(errno);
288 static int com_kill(void)
290 return send_signal(SIGTERM);
293 static int com_reload(void)
295 return send_signal(SIGHUP);
298 static void dss_get_snapshot_list(struct snapshot_list *sl)
300 get_snapshot_list(sl, conf.unit_interval_arg, conf.num_intervals_arg);
303 static int64_t compute_next_snapshot_time(void)
305 int64_t x = 0, now = get_current_time(), unit_interval
306 = 24 * 3600 * conf.unit_interval_arg, ret;
307 unsigned wanted = desired_number_of_snapshots(0, conf.num_intervals_arg),
310 struct snapshot *s = NULL;
311 struct snapshot_list sl;
313 dss_get_snapshot_list(&sl);
314 FOR_EACH_SNAPSHOT(s, i, &sl) {
315 if (!(s->flags & SS_COMPLETE))
318 x += s->completion_time - s->creation_time;
323 if (num_complete == 0)
325 x /= num_complete; /* avg time to create one snapshot */
326 if (unit_interval < x * wanted) /* oops, no sleep at all */
328 ret = s->completion_time + unit_interval / wanted - x;
330 free_snapshot_list(&sl);
334 static inline void invalidate_next_snapshot_time(void)
336 next_snapshot_time = 0;
339 static inline int next_snapshot_time_is_valid(void)
341 return next_snapshot_time != 0;
344 static int next_snapshot_is_due(void)
346 int64_t now = get_current_time();
348 if (!next_snapshot_time_is_valid())
349 next_snapshot_time = compute_next_snapshot_time();
350 if (next_snapshot_time <= now) {
351 DSS_DEBUG_LOG(("next snapshot: now\n"));
354 DSS_DEBUG_LOG(("next snapshot due in %" PRId64 " seconds\n",
355 next_snapshot_time - now));
359 static void pre_create_hook(void)
361 assert(snapshot_creation_status == HS_READY);
362 /* make sure that the next snapshot time will be recomputed */
363 invalidate_next_snapshot_time();
364 DSS_DEBUG_LOG(("executing %s\n", conf.pre_create_hook_arg));
365 dss_exec_cmdline_pid(&create_pid, conf.pre_create_hook_arg);
366 snapshot_creation_status = HS_PRE_RUNNING;
369 static void pre_remove_hook(struct snapshot *s, const char *why)
375 DSS_DEBUG_LOG(("%s snapshot %s\n", why, s->name));
376 assert(snapshot_removal_status == HS_READY);
377 assert(remove_pid == 0);
378 assert(!snapshot_currently_being_removed);
380 snapshot_currently_being_removed = dss_malloc(sizeof(struct snapshot));
381 *snapshot_currently_being_removed = *s;
382 snapshot_currently_being_removed->name = dss_strdup(s->name);
384 cmd = make_message("%s %s/%s", conf.pre_remove_hook_arg,
385 conf.dest_dir_arg, s->name);
386 DSS_DEBUG_LOG(("executing %s\n", cmd));
387 dss_exec_cmdline_pid(&remove_pid, cmd);
389 snapshot_removal_status = HS_PRE_RUNNING;
392 static int exec_rm(void)
394 struct snapshot *s = snapshot_currently_being_removed;
395 char *new_name = being_deleted_name(s);
404 assert(snapshot_removal_status == HS_PRE_SUCCESS);
405 assert(remove_pid == 0);
407 DSS_NOTICE_LOG(("removing %s (interval = %i)\n", s->name, s->interval));
408 ret = dss_rename(s->name, new_name);
411 dss_exec(&remove_pid, argv[0], argv);
412 snapshot_removal_status = HS_RUNNING;
418 static int snapshot_is_being_created(struct snapshot *s)
420 return s->creation_time == current_snapshot_creation_time;
423 static struct snapshot *find_orphaned_snapshot(struct snapshot_list *sl)
428 DSS_DEBUG_LOG(("looking for orphaned snapshots\n"));
429 FOR_EACH_SNAPSHOT(s, i, sl) {
430 if (snapshot_is_being_created(s))
433 * We know that no rm is currently running, so if s is marked
434 * as being deleted, a previously started rm must have failed.
436 if (s->flags & SS_BEING_DELETED)
439 if (s->flags & SS_COMPLETE) /* good snapshot */
442 * This snapshot is incomplete and it is not the snapshot
443 * currently being created. However, we must not remove it if
444 * rsync is about to be restarted. As only the newest snapshot
445 * can be restarted, this snapshot is orphaned if it is not the
446 * newest snapshot or if we are not about to restart rsync.
448 if (get_newest_snapshot(sl) != s)
450 if (snapshot_creation_status != HS_NEEDS_RESTART)
453 /* no orphaned snapshots */
457 static int is_reference_snapshot(struct snapshot *s)
459 if (!name_of_reference_snapshot)
461 return strcmp(s->name, name_of_reference_snapshot)? 0 : 1;
465 * return: 0: no redundant snapshots, 1: rm process started, negative: error
467 static struct snapshot *find_redundant_snapshot(struct snapshot_list *sl)
471 unsigned missing = 0;
473 DSS_DEBUG_LOG(("looking for intervals containing too many snapshots\n"));
474 for (interval = conf.num_intervals_arg - 1; interval >= 0; interval--) {
475 unsigned keep = desired_number_of_snapshots(interval, conf.num_intervals_arg);
476 unsigned num = sl->interval_count[interval];
477 struct snapshot *victim = NULL, *prev = NULL;
478 int64_t score = LONG_MAX;
481 missing += keep - num;
482 if (keep + missing >= num)
484 /* redundant snapshot in this interval, pick snapshot with lowest score */
485 FOR_EACH_SNAPSHOT(s, i, sl) {
488 if (snapshot_is_being_created(s))
490 if (is_reference_snapshot(s))
492 if (s->interval > interval) {
496 if (s->interval < interval)
504 /* check if s is a better victim */
505 this_score = s->creation_time - prev->creation_time;
506 assert(this_score >= 0);
507 if (this_score < score) {
519 static struct snapshot *find_outdated_snapshot(struct snapshot_list *sl)
524 DSS_DEBUG_LOG(("looking for snapshots belonging to intervals >= %d\n",
525 conf.num_intervals_arg));
526 FOR_EACH_SNAPSHOT(s, i, sl) {
527 if (snapshot_is_being_created(s))
529 if (is_reference_snapshot(s))
531 if (s->interval < conf.num_intervals_arg)
538 static struct snapshot *find_oldest_removable_snapshot(struct snapshot_list *sl)
541 struct snapshot *s, *ref = NULL;
543 num_complete = num_complete_snapshots(sl);
544 if (num_complete <= conf.min_complete_arg)
546 FOR_EACH_SNAPSHOT(s, i, sl) {
547 if (snapshot_is_being_created(s))
549 if (is_reference_snapshot(s)) { /* avoid this one */
553 DSS_INFO_LOG(("oldest removable snapshot: %s\n", s->name));
557 DSS_WARNING_LOG(("removing reference snapshot %s\n", ref->name));
561 static int rename_incomplete_snapshot(int64_t start)
568 * We don't want the dss_rename() below to fail with EEXIST because the
569 * last complete snapshot was created (and completed) in the same
570 * second as this one.
572 while ((now = get_current_time()) == start)
574 free(path_to_last_complete_snapshot);
575 ret = complete_name(start, now, &path_to_last_complete_snapshot);
578 old_name = incomplete_name(start);
579 ret = dss_rename(old_name, path_to_last_complete_snapshot);
581 DSS_NOTICE_LOG(("%s -> %s\n", old_name,
582 path_to_last_complete_snapshot));
587 static int try_to_free_disk_space(void)
590 struct snapshot_list sl;
591 struct snapshot *victim;
596 ret = disk_space_low(NULL);
599 low_disk_space = ret;
600 gettimeofday(&now, NULL);
601 if (tv_diff(&next_removal_check, &now, NULL) > 0)
603 if (!low_disk_space) {
604 if (conf.keep_redundant_given)
606 if (snapshot_creation_status != HS_READY)
608 if (next_snapshot_is_due())
612 * Idle and --keep_redundant not given, or low disk space. Look at
613 * existing snapshots.
615 dss_get_snapshot_list(&sl);
618 * Don't remove anything if there is free space and we have fewer
619 * snapshots than configured, plus one. This way there is always one
620 * snapshot that can be recycled.
622 if (!low_disk_space && sl.num_snapshots <= 1 << conf.num_intervals_arg)
625 victim = find_outdated_snapshot(&sl);
629 victim = find_redundant_snapshot(&sl);
633 victim = find_orphaned_snapshot(&sl);
636 /* try harder only if disk space is low */
639 DSS_WARNING_LOG(("disk space low and nothing obvious to remove\n"));
641 victim = find_oldest_removable_snapshot(&sl);
644 DSS_CRIT_LOG(("uhuhu: disk space low and nothing to remove\n"));
645 ret = -ERRNO_TO_DSS_ERROR(ENOSPC);
648 pre_remove_hook(victim, why);
650 free_snapshot_list(&sl);
654 static void post_create_hook(void)
656 char *cmd = make_message("%s %s/%s", conf.post_create_hook_arg,
657 conf.dest_dir_arg, path_to_last_complete_snapshot);
658 DSS_NOTICE_LOG(("executing %s\n", cmd));
659 dss_exec_cmdline_pid(&create_pid, cmd);
661 snapshot_creation_status = HS_POST_RUNNING;
664 static void post_remove_hook(void)
667 struct snapshot *s = snapshot_currently_being_removed;
671 cmd = make_message("%s %s/%s", conf.post_remove_hook_arg,
672 conf.dest_dir_arg, s->name);
673 DSS_NOTICE_LOG(("executing %s\n", cmd));
674 dss_exec_cmdline_pid(&remove_pid, cmd);
676 snapshot_removal_status = HS_POST_RUNNING;
679 static void dss_kill(pid_t pid, int sig, const char *msg)
681 const char *signame, *process_name;
686 case SIGTERM: signame = "TERM"; break;
687 case SIGSTOP: signame = "STOP"; break;
688 case SIGCONT: signame = "CONT"; break;
689 default: signame = "????";
692 if (pid == create_pid)
693 process_name = "create";
694 else if (pid == remove_pid)
695 process_name = "remove";
696 else process_name = "??????";
699 DSS_INFO_LOG(("%s\n", msg));
700 DSS_DEBUG_LOG(("sending signal %d (%s) to pid %d (%s process)\n",
701 sig, signame, (int)pid, process_name));
702 if (kill(pid, sig) >= 0)
704 DSS_INFO_LOG(("failed to send signal %d (%s) to pid %d (%s process)\n",
705 sig, signame, (int)pid, process_name));
708 static void stop_create_process(void)
710 if (create_process_stopped)
712 dss_kill(create_pid, SIGSTOP, "suspending create process");
713 create_process_stopped = 1;
716 static void restart_create_process(void)
718 if (!create_process_stopped)
720 dss_kill(create_pid, SIGCONT, "resuming create process");
721 create_process_stopped = 0;
725 * Print a log message about the exit status of a child.
727 static void log_termination_msg(pid_t pid, int status)
729 if (WIFEXITED(status))
730 DSS_INFO_LOG(("child %i exited. Exit status: %i\n", (int)pid,
731 WEXITSTATUS(status)));
732 else if (WIFSIGNALED(status))
733 DSS_NOTICE_LOG(("child %i was killed by signal %i\n", (int)pid,
736 DSS_WARNING_LOG(("child %i terminated abormally\n", (int)pid));
739 static int wait_for_process(pid_t pid, int *status)
743 DSS_DEBUG_LOG(("Waiting for process %d to terminate\n", (int)pid));
748 FD_SET(signal_pipe, &rfds);
749 ret = dss_select(signal_pipe + 1, &rfds, NULL, NULL);
755 if (ret == SIGCHLD) {
756 ret = waitpid(pid, status, 0);
759 if (errno != EINTR) { /* error */
760 ret = -ERRNO_TO_DSS_ERROR(errno);
764 /* SIGINT or SIGTERM */
765 dss_kill(pid, SIGTERM, "killing child process");
768 DSS_ERROR_LOG(("failed to wait for process %d\n", (int)pid));
770 log_termination_msg(pid, *status);
774 static void handle_pre_remove_exit(int status)
776 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
777 snapshot_removal_status = HS_READY;
778 gettimeofday(&next_removal_check, NULL);
779 next_removal_check.tv_sec += 60;
782 snapshot_removal_status = HS_PRE_SUCCESS;
785 static int handle_rm_exit(int status)
787 if (!WIFEXITED(status)) {
788 snapshot_removal_status = HS_READY;
789 return -E_INVOLUNTARY_EXIT;
791 if (WEXITSTATUS(status)) {
792 snapshot_removal_status = HS_READY;
793 return -E_BAD_EXIT_CODE;
795 snapshot_removal_status = HS_SUCCESS;
799 static void handle_post_remove_exit(void)
801 snapshot_removal_status = HS_READY;
804 static int handle_remove_exit(int status)
807 struct snapshot *s = snapshot_currently_being_removed;
810 switch (snapshot_removal_status) {
812 handle_pre_remove_exit(status);
816 ret = handle_rm_exit(status);
818 case HS_POST_RUNNING:
819 handle_post_remove_exit();
825 if (snapshot_removal_status == HS_READY) {
828 snapshot_currently_being_removed = NULL;
834 static int wait_for_remove_process(void)
840 snapshot_removal_status == HS_PRE_RUNNING ||
841 snapshot_removal_status == HS_RUNNING ||
842 snapshot_removal_status == HS_POST_RUNNING
844 ret = wait_for_process(remove_pid, &status);
847 return handle_remove_exit(status);
850 static int handle_rsync_exit(int status)
854 if (!WIFEXITED(status)) {
855 DSS_ERROR_LOG(("rsync process %d died involuntary\n", (int)create_pid));
856 ret = -E_INVOLUNTARY_EXIT;
857 snapshot_creation_status = HS_READY;
860 es = WEXITSTATUS(status);
862 * Restart rsync on non-fatal errors:
863 * 24: Partial transfer due to vanished source files
865 if (es != 0 && es != 24) {
866 DSS_WARNING_LOG(("rsync exit code %d, error count %d\n",
867 es, ++num_consecutive_rsync_errors));
868 if (conf.create_given) {
869 ret = -E_BAD_EXIT_CODE;
872 if (num_consecutive_rsync_errors > conf.max_rsync_errors_arg) {
873 ret = -E_TOO_MANY_RSYNC_ERRORS;
874 snapshot_creation_status = HS_READY;
877 DSS_WARNING_LOG(("restarting rsync process\n"));
878 snapshot_creation_status = HS_NEEDS_RESTART;
879 next_snapshot_time = get_current_time() + 60;
883 num_consecutive_rsync_errors = 0;
884 ret = rename_incomplete_snapshot(current_snapshot_creation_time);
887 snapshot_creation_status = HS_SUCCESS;
888 free(name_of_reference_snapshot);
889 name_of_reference_snapshot = NULL;
891 create_process_stopped = 0;
895 static int handle_pre_create_hook_exit(int status)
898 static int warn_count;
900 if (!WIFEXITED(status)) {
901 snapshot_creation_status = HS_READY;
902 ret = -E_INVOLUNTARY_EXIT;
905 es = WEXITSTATUS(status);
908 DSS_NOTICE_LOG(("pre_create_hook %s returned %d\n",
909 conf.pre_create_hook_arg, es));
910 DSS_NOTICE_LOG(("deferring snapshot creation...\n"));
911 warn_count = 60; /* warn only once per hour */
913 next_snapshot_time = get_current_time() + 60;
914 snapshot_creation_status = HS_READY;
919 snapshot_creation_status = HS_PRE_SUCCESS;
925 static int handle_sigchld(void)
928 int status, ret = reap_child(&pid, &status);
933 if (pid == create_pid) {
934 switch (snapshot_creation_status) {
936 ret = handle_pre_create_hook_exit(status);
939 ret = handle_rsync_exit(status);
941 case HS_POST_RUNNING:
942 snapshot_creation_status = HS_READY;
946 DSS_EMERG_LOG(("BUG: create can't die in status %d\n",
947 snapshot_creation_status));
953 if (pid == remove_pid) {
954 ret = handle_remove_exit(status);
959 DSS_EMERG_LOG(("BUG: unknown process %d died\n", (int)pid));
963 static int check_config(void)
965 if (conf.unit_interval_arg <= 0) {
966 DSS_ERROR_LOG(("bad unit interval: %i\n", conf.unit_interval_arg));
967 return -E_INVALID_NUMBER;
969 DSS_DEBUG_LOG(("unit interval: %i day(s)\n", conf.unit_interval_arg));
970 if (conf.num_intervals_arg <= 0 || conf.num_intervals_arg > 30) {
971 DSS_ERROR_LOG(("bad number of intervals: %i\n",
972 conf.num_intervals_arg));
973 return -E_INVALID_NUMBER;
975 DSS_DEBUG_LOG(("number of intervals: %i\n", conf.num_intervals_arg));
980 * Returns < 0 on errors, 0 if no config file is given and > 0 if the config
981 * file was read successfully.
983 static int parse_config_file(bool sighup)
985 int ret, config_file_exists;
986 char *config_file = get_config_file_name();
988 char *old_logfile_arg = NULL;
989 int old_daemon_given = 0;
992 if (conf.logfile_given)
993 old_logfile_arg = dss_strdup(conf.logfile_arg);
994 old_daemon_given = conf.daemon_given;
997 config_file_exists = !stat(config_file, &statbuf);
998 if (!config_file_exists && conf.config_file_given) {
999 ret = -ERRNO_TO_DSS_ERROR(errno);
1000 DSS_ERROR_LOG(("failed to stat config file %s\n", config_file));
1003 if (config_file_exists) {
1004 struct cmdline_parser_params params;
1005 params.override = sighup;
1006 params.initialize = 0;
1007 params.check_required = 1;
1008 params.check_ambiguity = 0;
1009 params.print_errors = 1;
1010 if (sighup) { /* invalidate all rsync options */
1013 for (i = 0; i < conf.rsync_option_given; i++) {
1014 free(conf.rsync_option_arg[i]);
1015 conf.rsync_option_arg[i] = NULL;
1017 conf.rsync_option_given = 0;
1019 cmdline_parser_config_file(config_file, &conf, ¶ms);
1021 ret = check_config();
1025 /* don't change daemon mode on SIGHUP */
1026 conf.daemon_given = old_daemon_given;
1029 if (conf.logfile_given)
1030 free(old_logfile_arg);
1031 else if (conf.daemon_given) { /* re-use old logfile */
1032 conf.logfile_arg = old_logfile_arg;
1033 conf.logfile_given = 1;
1036 if (conf.logfile_given && conf.run_given && conf.daemon_given) {
1037 logfile = open_log(conf.logfile_arg);
1038 log_welcome(conf.loglevel_arg);
1040 DSS_DEBUG_LOG(("loglevel: %d\n", conf.loglevel_arg));
1041 ret = config_file_exists;
1045 DSS_EMERG_LOG(("%s\n", dss_strerror(-ret)));
1049 static int change_to_dest_dir(void)
1051 DSS_INFO_LOG(("changing cwd to %s\n", conf.dest_dir_arg));
1052 return dss_chdir(conf.dest_dir_arg);
1055 static int handle_sighup(void)
1059 DSS_NOTICE_LOG(("SIGHUP, re-reading config\n"));
1060 dump_dss_config("old");
1061 ret = parse_config_file(true /* SIGHUP */);
1064 dump_dss_config("reloaded");
1065 invalidate_next_snapshot_time();
1066 return change_to_dest_dir();
1069 static void kill_children(void)
1071 restart_create_process();
1072 dss_kill(create_pid, SIGTERM, NULL);
1073 dss_kill(remove_pid, SIGTERM, NULL);
1076 static int handle_signal(void)
1078 int sig, ret = next_signal();
1090 ret = handle_sighup();
1093 ret = handle_sigchld();
1098 DSS_ERROR_LOG(("%s\n", dss_strerror(-ret)));
1103 * We can not use rsync locally if the local user is different from the remote
1104 * user or if the src dir is not on the local host (or both).
1106 static int use_rsync_locally(char *logname)
1108 char *h = conf.remote_host_arg;
1110 if (strcmp(h, "localhost") && strcmp(h, "127.0.0.1"))
1112 if (conf.remote_user_given && strcmp(conf.remote_user_arg, logname))
1117 static int rename_resume_snap(int64_t creation_time)
1119 struct snapshot_list sl;
1120 struct snapshot *s = NULL;
1121 char *new_name = incomplete_name(creation_time);
1125 sl.num_snapshots = 0;
1128 if (conf.no_resume_given)
1130 dss_get_snapshot_list(&sl);
1132 * Snapshot recycling: We first look at the newest snapshot. If this
1133 * snapshot happens to be incomplete, the last rsync process was
1134 * aborted and we reuse this one. Otherwise we look at snapshots which
1135 * could be removed (outdated and redundant snapshots) as candidates
1136 * for recycling. If no outdated/redundant snapshot exists, we check if
1137 * there is an orphaned snapshot, which likely is useless anyway.
1139 * Only if no existing snapshot is suitable for recycling, we bite the
1140 * bullet and create a new one.
1142 s = get_newest_snapshot(&sl);
1143 if (!s) /* no snapshots at all */
1145 /* re-use last snapshot if it is incomplete */
1147 if ((s->flags & SS_COMPLETE) == 0)
1150 s = find_outdated_snapshot(&sl);
1154 s = find_redundant_snapshot(&sl);
1158 s = find_orphaned_snapshot(&sl);
1161 DSS_NOTICE_LOG(("recycling %s snapshot %s\n", why, s->name));
1162 ret = dss_rename(s->name, new_name);
1165 DSS_NOTICE_LOG(("creating %s\n", new_name));
1167 free_snapshot_list(&sl);
1171 static void create_rsync_argv(char ***argv, int64_t *num)
1175 struct snapshot_list sl;
1177 dss_get_snapshot_list(&sl);
1178 assert(!name_of_reference_snapshot);
1179 name_of_reference_snapshot = name_of_newest_complete_snapshot(&sl);
1180 free_snapshot_list(&sl);
1182 *argv = dss_malloc((15 + conf.rsync_option_given) * sizeof(char *));
1183 (*argv)[i++] = dss_strdup("rsync");
1184 (*argv)[i++] = dss_strdup("-a");
1185 (*argv)[i++] = dss_strdup("--delete");
1186 for (j = 0; j < conf.rsync_option_given; j++)
1187 (*argv)[i++] = dss_strdup(conf.rsync_option_arg[j]);
1188 if (name_of_reference_snapshot) {
1189 DSS_INFO_LOG(("using %s as reference\n", name_of_reference_snapshot));
1190 (*argv)[i++] = make_message("--link-dest=../%s",
1191 name_of_reference_snapshot);
1193 DSS_INFO_LOG(("no suitable reference snapshot found\n"));
1194 logname = dss_logname();
1195 if (use_rsync_locally(logname))
1196 (*argv)[i++] = dss_strdup(conf.source_dir_arg);
1198 (*argv)[i++] = make_message("%s@%s:%s/", conf.remote_user_given?
1199 conf.remote_user_arg : logname,
1200 conf.remote_host_arg, conf.source_dir_arg);
1202 *num = get_current_time();
1203 (*argv)[i++] = incomplete_name(*num);
1204 (*argv)[i++] = NULL;
1205 for (j = 0; j < i; j++)
1206 DSS_DEBUG_LOG(("argv[%d] = %s\n", j, (*argv)[j]));
1209 static void free_rsync_argv(char **argv)
1215 for (i = 0; argv[i]; i++)
1220 static int create_snapshot(char **argv)
1224 ret = rename_resume_snap(current_snapshot_creation_time);
1227 dss_exec(&create_pid, argv[0], argv);
1228 snapshot_creation_status = HS_RUNNING;
1232 static int select_loop(void)
1235 /* check every 60 seconds for free disk space */
1237 char **rsync_argv = NULL;
1241 struct timeval *tvp;
1244 tvp = NULL; /* sleep until rm hook/process dies */
1245 else { /* sleep one minute */
1251 FD_SET(signal_pipe, &rfds);
1252 ret = dss_select(signal_pipe + 1, &rfds, NULL, tvp);
1255 if (FD_ISSET(signal_pipe, &rfds)) {
1256 ret = handle_signal();
1262 if (snapshot_removal_status == HS_PRE_SUCCESS) {
1268 if (snapshot_removal_status == HS_SUCCESS) {
1272 ret = try_to_free_disk_space();
1275 if (snapshot_removal_status != HS_READY) {
1276 stop_create_process();
1279 restart_create_process();
1280 switch (snapshot_creation_status) {
1282 if (!next_snapshot_is_due())
1286 case HS_PRE_RUNNING:
1288 case HS_POST_RUNNING:
1290 case HS_PRE_SUCCESS:
1291 if (!name_of_reference_snapshot) {
1292 free_rsync_argv(rsync_argv);
1293 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
1295 ret = create_snapshot(rsync_argv);
1299 case HS_NEEDS_RESTART:
1300 if (!next_snapshot_is_due())
1302 ret = create_snapshot(rsync_argv);
1315 static void exit_hook(int exit_code)
1320 argv[0] = conf.exit_hook_arg;
1321 argv[1] = dss_strerror(-exit_code);
1324 DSS_NOTICE_LOG(("executing %s %s\n", argv[0], argv[1]));
1325 dss_exec(&pid, conf.exit_hook_arg, argv);
1328 static void lock_dss_or_die(void)
1330 char *config_file = get_config_file_name();
1331 int ret = lock_dss(config_file);
1335 DSS_EMERG_LOG(("failed to lock: %s\n", dss_strerror(-ret)));
1340 static int com_run(void)
1345 if (conf.dry_run_given) {
1346 DSS_ERROR_LOG(("dry_run not supported by this command\n"));
1349 ret = install_sighandler(SIGHUP);
1352 ret = select_loop();
1353 if (ret >= 0) /* impossible */
1360 static int com_prune(void)
1363 struct snapshot_list sl;
1364 struct snapshot *victim;
1365 struct disk_space ds;
1369 ret = get_disk_space(".", &ds);
1372 log_disk_space(&ds);
1373 dss_get_snapshot_list(&sl);
1375 victim = find_outdated_snapshot(&sl);
1379 victim = find_redundant_snapshot(&sl);
1385 if (conf.dry_run_given) {
1386 dss_msg("%s snapshot %s (interval = %i)\n",
1387 why, victim->name, victim->interval);
1391 pre_remove_hook(victim, why);
1392 if (snapshot_removal_status == HS_PRE_RUNNING) {
1393 ret = wait_for_remove_process();
1396 if (snapshot_removal_status != HS_PRE_SUCCESS)
1402 ret = wait_for_remove_process();
1405 if (snapshot_removal_status != HS_SUCCESS)
1408 if (snapshot_removal_status != HS_POST_RUNNING)
1410 ret = wait_for_remove_process();
1415 free_snapshot_list(&sl);
1419 static int com_create(void)
1425 if (conf.dry_run_given) {
1428 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
1429 for (i = 0; rsync_argv[i]; i++) {
1431 msg = make_message("%s%s%s", tmp? tmp : "",
1432 tmp? " " : "", rsync_argv[i]);
1435 free_rsync_argv(rsync_argv);
1436 dss_msg("%s\n", msg);
1442 ret = wait_for_process(create_pid, &status);
1445 ret = handle_pre_create_hook_exit(status);
1446 if (ret <= 0) /* error, or pre-create failed */
1449 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
1450 ret = create_snapshot(rsync_argv);
1453 ret = wait_for_process(create_pid, &status);
1456 ret = handle_rsync_exit(status);
1461 ret = wait_for_process(create_pid, &status);
1463 free_rsync_argv(rsync_argv);
1467 static int com_ls(void)
1470 struct snapshot_list sl;
1473 dss_get_snapshot_list(&sl);
1474 FOR_EACH_SNAPSHOT(s, i, &sl) {
1476 if (s->flags & SS_COMPLETE)
1477 d = (s->completion_time - s->creation_time) / 60;
1478 dss_msg("%u\t%s\t%3" PRId64 ":%02" PRId64 "\n", s->interval, s->name, d/60, d%60);
1480 free_snapshot_list(&sl);
1484 static int setup_signal_handling(void)
1488 DSS_INFO_LOG(("setting up signal handlers\n"));
1489 signal_pipe = signal_init(); /* always successful */
1490 ret = install_sighandler(SIGINT);
1493 ret = install_sighandler(SIGTERM);
1496 return install_sighandler(SIGCHLD);
1499 int main(int argc, char **argv)
1502 struct cmdline_parser_params params;
1504 params.override = 0;
1505 params.initialize = 1;
1506 params.check_required = 0;
1507 params.check_ambiguity = 0;
1508 params.print_errors = 1;
1510 cmdline_parser_ext(argc, argv, &conf, ¶ms); /* aborts on errors */
1511 ret = parse_config_file(0);
1512 ret = parse_config_file(false /* no SIGHUP */);
1515 if (ret == 0) { /* no config file given */
1517 * Parse the command line options again, but this time check
1518 * that all required options are given.
1520 params.override = 1;
1521 params.initialize = 1;
1522 params.check_required = 1;
1523 params.check_ambiguity = 1;
1524 params.print_errors = 1;
1525 cmdline_parser_ext(argc, argv, &conf, ¶ms); /* aborts on errors */
1527 if (conf.daemon_given)
1529 ret = change_to_dest_dir();
1532 dump_dss_config("startup");
1533 ret = setup_signal_handling();
1536 ret = call_command_handler();
1540 DSS_EMERG_LOG(("%s\n", dss_strerror(-ret)));
1541 exit(ret >= 0? EXIT_SUCCESS : EXIT_FAILURE);