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>
28 #include "gcc-compat.h"
42 #define CMD_PTR(_cname) lls_cmd(LSG_DSS_CMD_ ## _cname, dss_suite)
43 #define OPT_RESULT(_cname, _oname) (lls_opt_result(\
44 LSG_DSS_ ## _cname ## _OPT_ ## _oname, (CMD_PTR(_cname) == CMD_PTR(DSS))? lpr : sublpr))
45 #define OPT_GIVEN(_cname, _oname) (lls_opt_given(OPT_RESULT(_cname, _oname)))
46 #define OPT_STRING_VAL(_cname, _oname) (lls_string_val(0, \
47 OPT_RESULT(_cname, _oname)))
48 #define OPT_UINT32_VAL(_cname, _oname) (lls_uint32_val(0, \
49 OPT_RESULT(_cname, _oname)))
51 struct dss_user_data {int (*handler)(void);};
52 #define EXPORT_CMD_HANDLER(_cmd) const struct dss_user_data \
53 lsg_dss_com_ ## _cmd ## _user_data = { \
54 .handler = com_ ## _cmd \
58 * Command line and active options. We need to keep a copy of the parsed
59 * command line options for the SIGHUP case where we merge the command line
60 * options and the new config file options.
62 static struct lls_parse_result *cmdline_lpr, *lpr;
64 /** Parsed subcommand options. */
65 static struct lls_parse_result *cmdline_sublpr, *sublpr;
66 /** Wether daemon_init() was called. */
67 static bool daemonized;
68 /** Non-NULL if we log to a file. */
70 /** The read end of the signal pipe */
71 static int signal_pipe;
72 /** Process id of current pre-create-hook/rsync/post-create-hook process. */
73 static pid_t create_pid;
74 /** Whether the pre-create-hook/rsync/post-create-hook is currently stopped. */
75 static int create_process_stopped;
76 /** How many times in a row the rsync command failed. */
77 static int num_consecutive_rsync_errors;
78 /** Process id of current pre-remove/rm/post-remove process. */
79 static pid_t remove_pid;
80 /** When the next snapshot is due. */
81 static int64_t next_snapshot_time;
82 /** When to try to remove something. */
83 static struct timeval next_removal_check;
84 /** Creation time of the snapshot currently being created. */
85 static int64_t current_snapshot_creation_time;
86 /** The snapshot currently being removed. */
87 struct snapshot *snapshot_currently_being_removed;
88 /** Needed by the post-create hook. */
89 static char *path_to_last_complete_snapshot;
90 static char *name_of_reference_snapshot;
91 /** \sa \ref snap.h for details. */
92 enum hook_status snapshot_creation_status;
93 /** \sa \ref snap.h for details. */
94 enum hook_status snapshot_removal_status;
98 static const char *hook_status_description[] = {HOOK_STATUS_ARRAY};
100 /* may be called with ds == NULL. */
101 static int disk_space_low(struct disk_space *ds)
103 struct disk_space ds_struct;
107 int ret = get_disk_space(".", &ds_struct);
112 val = OPT_UINT32_VAL(DSS, MIN_FREE_MB);
114 if (ds->free_mb < val)
116 val = OPT_UINT32_VAL(DSS, MIN_FREE_PERCENT);
118 if (ds->percent_free < val)
120 val = OPT_UINT32_VAL(DSS, MIN_FREE_PERCENT_INODES);
122 if (ds->percent_free_inodes < val)
127 static void dump_dss_config(const char *msg)
129 const char dash[] = "-----------------------------";
132 FILE *log = logfile? logfile : stderr;
133 struct disk_space ds;
134 int64_t now = get_current_time();
136 if (OPT_UINT32_VAL(DSS, LOGLEVEL) > INFO)
139 fprintf(log, "%s <%s config> %s\n", dash, msg, dash);
140 fprintf(log, "\n*** disk space ***\n\n");
141 ret = get_disk_space(".", &ds);
143 DSS_INFO_LOG(("disk space low: %s\n", disk_space_low(&ds)?
147 DSS_ERROR_LOG(("can not get free disk space: %s\n",
148 dss_strerror(-ret)));
150 /* we continue on errors from get_disk_space */
152 fprintf(log, "\n*** non-default options ***\n\n");
153 lopsub_dump = lls_dump_parse_result(lpr, CMD_PTR(DSS), true);
154 fprintf(log, "%s", lopsub_dump);
156 fprintf(log, "\n*** non-default options for \"run\" ***\n\n");
157 lopsub_dump = lls_dump_parse_result(lpr, CMD_PTR(RUN), true);
158 fprintf(log, "%s", lopsub_dump);
160 fprintf(log, "\n*** internal state ***\n\n");
164 "snapshot_currently_being_removed: %s\n"
165 "path_to_last_complete_snapshot: %s\n"
166 "reference_snapshot: %s\n"
167 "snapshot_creation_status: %s\n"
168 "snapshot_removal_status: %s\n"
169 "num_consecutive_rsync_errors: %d\n"
172 logfile? OPT_STRING_VAL(RUN, LOGFILE) : "stderr",
173 snapshot_currently_being_removed?
174 snapshot_currently_being_removed->name : "(none)",
175 path_to_last_complete_snapshot?
176 path_to_last_complete_snapshot : "(none)",
177 name_of_reference_snapshot?
178 name_of_reference_snapshot : "(none)",
179 hook_status_description[snapshot_creation_status],
180 hook_status_description[snapshot_removal_status],
181 num_consecutive_rsync_errors
185 "create_pid: %" PRId32 "\n"
186 "create process is %sstopped\n"
189 create_process_stopped? "" : "not "
192 fprintf(log, "remove_pid: %" PRId32 "\n", remove_pid);
193 if (next_snapshot_time != 0)
194 fprintf(log, "next snapshot due in %" PRId64 " seconds\n",
195 next_snapshot_time - now);
196 if (current_snapshot_creation_time != 0)
197 fprintf(log, "current_snapshot_creation_time: %"
198 PRId64 " (%" PRId64 " seconds ago)\n",
199 current_snapshot_creation_time,
200 now - current_snapshot_creation_time
202 if (next_removal_check.tv_sec != 0) {
203 fprintf(log, "next removal check: %llu (%llu seconds ago)\n",
204 (long long unsigned)next_removal_check.tv_sec,
205 now - (long long unsigned)next_removal_check.tv_sec
209 fprintf(log, "%s </%s config> %s\n", dash, msg, dash);
212 static int loglevel = -1;
213 static const char *location_file = NULL;
214 static int location_line = -1;
215 static const char *location_func = NULL;
217 void dss_log_set_params(int ll, const char *file, int line, const char *func)
220 location_file = file;
221 location_line = line;
222 location_func = func;
226 * The log function of dss.
228 * \param ll Loglevel.
229 * \param fml Usual format string.
231 * All DSS_XXX_LOG() macros use this function.
233 __printf_1_2 void dss_log(const char* fmt,...)
240 int lpr_ll = lpr? OPT_UINT32_VAL(DSS, LOGLEVEL) : WARNING;
242 if (loglevel < lpr_ll)
244 outfd = logfile? logfile : stderr;
247 strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
248 fprintf(outfd, "%s ", str);
250 fprintf(outfd, "%i: ", loglevel);
251 #ifdef DSS_NO_FUNC_NAMES
252 fprintf(outfd, "%s:%d: ", location_file, location_line);
254 fprintf(outfd, "%s: ", location_func);
257 vfprintf(outfd, fmt, argp);
262 * Print a message either to stdout or to the log file.
264 static __printf_1_2 void dss_msg(const char* fmt,...)
266 FILE *outfd = logfile? logfile : stdout;
269 vfprintf(outfd, fmt, argp);
273 static char *get_config_file_name(void)
275 char *home, *config_file;
277 if (OPT_GIVEN(DSS, CONFIG_FILE))
278 return dss_strdup(OPT_STRING_VAL(DSS, CONFIG_FILE));
279 home = get_homedir();
280 config_file = make_message("%s/.dssrc", home);
285 static int send_signal(int sig)
288 char *config_file = get_config_file_name();
289 int ret = get_dss_pid(config_file, &pid);
294 if (OPT_GIVEN(DSS, DRY_RUN)) {
295 dss_msg("%d\n", (int)pid);
298 DSS_NOTICE_LOG(("sending signal %d to pid %d\n", sig, (int)pid));
299 ret = kill(pid, sig);
301 return -ERRNO_TO_DSS_ERROR(errno);
306 const char * const name;
311 * The table below was taken 2016 from proc/sig.c of procps-3.2.8. Copyright
312 * 1998-2003 by Albert Cahalan, GPLv2.
314 static const struct signal_info signal_table[] = {
315 {"ABRT", SIGABRT}, /* IOT */
318 {"CHLD", SIGCHLD}, /* CLD */
327 {"POLL", SIGPOLL}, /* IO */
336 {"STKFLT", SIGSTKFLT},
339 {"SYS", SIGSYS}, /* UNUSED */
348 {"VTALRM", SIGVTALRM},
354 #define SIGNAL_TABLE_SIZE (sizeof(signal_table) / sizeof(signal_table[0]))
359 static int com_kill(void)
361 const char *arg = OPT_STRING_VAL(KILL, SIGNAL);
364 if (*arg >= '0' && *arg <= '9') {
366 ret = dss_atoi64(arg, &val);
369 if (val < 0 || val > SIGRTMAX)
370 return -ERRNO_TO_DSS_ERROR(EINVAL);
371 return send_signal(val);
373 if (strncasecmp(arg, "sig", 3) == 0)
375 if (strcasecmp(arg, "CLD") == 0)
376 return send_signal(SIGCHLD);
377 if (strcasecmp(arg, "IOT") == 0)
378 return send_signal(SIGABRT);
379 for (i = 0; i < SIGNAL_TABLE_SIZE; i++)
380 if (strcasecmp(arg, signal_table[i].name) == 0)
381 return send_signal(signal_table[i].num);
382 DSS_ERROR_LOG(("invalid sigspec: %s\n", arg));
383 return -ERRNO_TO_DSS_ERROR(EINVAL);
385 EXPORT_CMD_HANDLER(kill);
387 static void dss_get_snapshot_list(struct snapshot_list *sl)
389 get_snapshot_list(sl, OPT_UINT32_VAL(DSS, UNIT_INTERVAL),
390 OPT_UINT32_VAL(DSS, NUM_INTERVALS));
393 static int64_t compute_next_snapshot_time(void)
395 int64_t x = 0, now = get_current_time(), unit_interval
396 = 24 * 3600 * OPT_UINT32_VAL(DSS, UNIT_INTERVAL), ret;
397 unsigned wanted = desired_number_of_snapshots(0,
398 OPT_UINT32_VAL(DSS, NUM_INTERVALS)),
401 struct snapshot *s = NULL;
402 struct snapshot_list sl;
404 dss_get_snapshot_list(&sl);
405 FOR_EACH_SNAPSHOT(s, i, &sl) {
406 if (!(s->flags & SS_COMPLETE))
409 x += s->completion_time - s->creation_time;
414 if (num_complete == 0)
416 x /= num_complete; /* avg time to create one snapshot */
417 if (unit_interval < x * wanted) /* oops, no sleep at all */
419 ret = s->completion_time + unit_interval / wanted - x;
421 free_snapshot_list(&sl);
425 static inline void invalidate_next_snapshot_time(void)
427 next_snapshot_time = 0;
430 static inline int next_snapshot_time_is_valid(void)
432 return next_snapshot_time != 0;
435 static int next_snapshot_is_due(void)
437 int64_t now = get_current_time();
439 if (!next_snapshot_time_is_valid())
440 next_snapshot_time = compute_next_snapshot_time();
441 if (next_snapshot_time <= now) {
442 DSS_DEBUG_LOG(("next snapshot: now\n"));
445 DSS_DEBUG_LOG(("next snapshot due in %" PRId64 " seconds\n",
446 next_snapshot_time - now));
450 static void pre_create_hook(void)
452 assert(snapshot_creation_status == HS_READY);
453 /* make sure that the next snapshot time will be recomputed */
454 invalidate_next_snapshot_time();
455 DSS_DEBUG_LOG(("executing %s\n", OPT_STRING_VAL(DSS, PRE_CREATE_HOOK)));
456 dss_exec_cmdline_pid(&create_pid, OPT_STRING_VAL(DSS, PRE_CREATE_HOOK));
457 snapshot_creation_status = HS_PRE_RUNNING;
460 static void pre_remove_hook(struct snapshot *s, const char *why)
466 DSS_DEBUG_LOG(("%s snapshot %s\n", why, s->name));
467 assert(snapshot_removal_status == HS_READY);
468 assert(remove_pid == 0);
469 assert(!snapshot_currently_being_removed);
471 snapshot_currently_being_removed = dss_malloc(sizeof(struct snapshot));
472 *snapshot_currently_being_removed = *s;
473 snapshot_currently_being_removed->name = dss_strdup(s->name);
475 cmd = make_message("%s %s/%s", OPT_STRING_VAL(DSS, PRE_REMOVE_HOOK),
476 OPT_STRING_VAL(DSS, DEST_DIR), s->name);
477 DSS_DEBUG_LOG(("executing %s\n", cmd));
478 dss_exec_cmdline_pid(&remove_pid, cmd);
480 snapshot_removal_status = HS_PRE_RUNNING;
483 static int exec_rm(void)
485 struct snapshot *s = snapshot_currently_being_removed;
486 char *new_name = being_deleted_name(s);
495 assert(snapshot_removal_status == HS_PRE_SUCCESS);
496 assert(remove_pid == 0);
498 DSS_NOTICE_LOG(("removing %s (interval = %i)\n", s->name, s->interval));
499 ret = dss_rename(s->name, new_name);
502 dss_exec(&remove_pid, argv[0], argv);
503 snapshot_removal_status = HS_RUNNING;
509 static int snapshot_is_being_created(struct snapshot *s)
511 return s->creation_time == current_snapshot_creation_time;
514 static struct snapshot *find_orphaned_snapshot(struct snapshot_list *sl)
519 DSS_DEBUG_LOG(("looking for orphaned snapshots\n"));
520 FOR_EACH_SNAPSHOT(s, i, sl) {
521 if (snapshot_is_being_created(s))
524 * We know that no rm is currently running, so if s is marked
525 * as being deleted, a previously started rm must have failed.
527 if (s->flags & SS_BEING_DELETED)
530 if (s->flags & SS_COMPLETE) /* good snapshot */
533 * This snapshot is incomplete and it is not the snapshot
534 * currently being created. However, we must not remove it if
535 * rsync is about to be restarted. As only the newest snapshot
536 * can be restarted, this snapshot is orphaned if it is not the
537 * newest snapshot or if we are not about to restart rsync.
539 if (get_newest_snapshot(sl) != s)
541 if (snapshot_creation_status != HS_NEEDS_RESTART)
544 /* no orphaned snapshots */
548 static int is_reference_snapshot(struct snapshot *s)
550 if (!name_of_reference_snapshot)
552 return strcmp(s->name, name_of_reference_snapshot)? 0 : 1;
556 * return: 0: no redundant snapshots, 1: rm process started, negative: error
558 static struct snapshot *find_redundant_snapshot(struct snapshot_list *sl)
562 unsigned missing = 0;
563 uint32_t N = OPT_UINT32_VAL(DSS, NUM_INTERVALS);
565 DSS_DEBUG_LOG(("looking for intervals containing too many snapshots\n"));
566 for (interval = N - 1; interval >= 0; interval--) {
567 unsigned keep = desired_number_of_snapshots(interval, N);
568 unsigned num = sl->interval_count[interval];
569 struct snapshot *victim = NULL, *prev = NULL;
570 int64_t score = LONG_MAX;
573 missing += keep - num;
574 if (keep + missing >= num)
576 /* redundant snapshot in this interval, pick snapshot with lowest score */
577 FOR_EACH_SNAPSHOT(s, i, sl) {
580 if (snapshot_is_being_created(s))
582 if (is_reference_snapshot(s))
584 if (s->interval > interval) {
588 if (s->interval < interval)
596 /* check if s is a better victim */
597 this_score = s->creation_time - prev->creation_time;
598 assert(this_score >= 0);
599 if (this_score < score) {
611 static struct snapshot *find_outdated_snapshot(struct snapshot_list *sl)
616 DSS_DEBUG_LOG(("looking for snapshots belonging to intervals >= %d\n",
617 OPT_UINT32_VAL(DSS, NUM_INTERVALS)));
618 FOR_EACH_SNAPSHOT(s, i, sl) {
619 if (snapshot_is_being_created(s))
621 if (is_reference_snapshot(s))
623 if (s->interval < OPT_UINT32_VAL(DSS, NUM_INTERVALS))
630 static struct snapshot *find_oldest_removable_snapshot(struct snapshot_list *sl)
633 struct snapshot *s, *ref = NULL;
635 num_complete = num_complete_snapshots(sl);
636 if (num_complete <= OPT_UINT32_VAL(DSS, MIN_COMPLETE))
638 FOR_EACH_SNAPSHOT(s, i, sl) {
639 if (snapshot_is_being_created(s))
641 if (is_reference_snapshot(s)) { /* avoid this one */
645 DSS_INFO_LOG(("oldest removable snapshot: %s\n", s->name));
649 DSS_WARNING_LOG(("removing reference snapshot %s\n", ref->name));
653 static int rename_incomplete_snapshot(int64_t start)
660 * We don't want the dss_rename() below to fail with EEXIST because the
661 * last complete snapshot was created (and completed) in the same
662 * second as this one.
664 while ((now = get_current_time()) == start)
666 free(path_to_last_complete_snapshot);
667 ret = complete_name(start, now, &path_to_last_complete_snapshot);
670 old_name = incomplete_name(start);
671 ret = dss_rename(old_name, path_to_last_complete_snapshot);
673 DSS_NOTICE_LOG(("%s -> %s\n", old_name,
674 path_to_last_complete_snapshot));
679 static int try_to_free_disk_space(void)
682 struct snapshot_list sl;
683 struct snapshot *victim;
688 ret = disk_space_low(NULL);
691 low_disk_space = ret;
692 gettimeofday(&now, NULL);
693 if (tv_diff(&next_removal_check, &now, NULL) > 0)
695 if (!low_disk_space) {
696 if (OPT_GIVEN(DSS, KEEP_REDUNDANT))
698 if (snapshot_creation_status != HS_READY)
700 if (next_snapshot_is_due())
704 * Idle and --keep_redundant not given, or low disk space. Look at
705 * existing snapshots.
707 dss_get_snapshot_list(&sl);
710 * Don't remove anything if there is free space and we have fewer
711 * snapshots than configured, plus one. This way there is always one
712 * snapshot that can be recycled.
714 if (!low_disk_space && sl.num_snapshots <=
715 1 << OPT_UINT32_VAL(DSS, NUM_INTERVALS))
718 victim = find_outdated_snapshot(&sl);
722 victim = find_redundant_snapshot(&sl);
726 victim = find_orphaned_snapshot(&sl);
729 /* try harder only if disk space is low */
732 DSS_WARNING_LOG(("disk space low and nothing obvious to remove\n"));
734 victim = find_oldest_removable_snapshot(&sl);
737 DSS_CRIT_LOG(("uhuhu: disk space low and nothing to remove\n"));
738 ret = -ERRNO_TO_DSS_ERROR(ENOSPC);
741 pre_remove_hook(victim, why);
743 free_snapshot_list(&sl);
747 static void post_create_hook(void)
749 char *cmd = make_message("%s %s/%s",
750 OPT_STRING_VAL(DSS, POST_CREATE_HOOK),
751 OPT_STRING_VAL(DSS, DEST_DIR), path_to_last_complete_snapshot);
752 DSS_NOTICE_LOG(("executing %s\n", cmd));
753 dss_exec_cmdline_pid(&create_pid, cmd);
755 snapshot_creation_status = HS_POST_RUNNING;
758 static void post_remove_hook(void)
761 struct snapshot *s = snapshot_currently_being_removed;
765 cmd = make_message("%s %s/%s", OPT_STRING_VAL(DSS, POST_REMOVE_HOOK),
766 OPT_STRING_VAL(DSS, DEST_DIR), s->name);
767 DSS_NOTICE_LOG(("executing %s\n", cmd));
768 dss_exec_cmdline_pid(&remove_pid, cmd);
770 snapshot_removal_status = HS_POST_RUNNING;
773 static void dss_kill(pid_t pid, int sig, const char *msg)
775 const char *signame, *process_name;
780 case SIGTERM: signame = "TERM"; break;
781 case SIGSTOP: signame = "STOP"; break;
782 case SIGCONT: signame = "CONT"; break;
783 default: signame = "????";
786 if (pid == create_pid)
787 process_name = "create";
788 else if (pid == remove_pid)
789 process_name = "remove";
790 else process_name = "??????";
793 DSS_INFO_LOG(("%s\n", msg));
794 DSS_DEBUG_LOG(("sending signal %d (%s) to pid %d (%s process)\n",
795 sig, signame, (int)pid, process_name));
796 if (kill(pid, sig) >= 0)
798 DSS_INFO_LOG(("failed to send signal %d (%s) to pid %d (%s process)\n",
799 sig, signame, (int)pid, process_name));
802 static void stop_create_process(void)
804 if (create_process_stopped)
806 dss_kill(create_pid, SIGSTOP, "suspending create process");
807 create_process_stopped = 1;
810 static void restart_create_process(void)
812 if (!create_process_stopped)
814 dss_kill(create_pid, SIGCONT, "resuming create process");
815 create_process_stopped = 0;
819 * Print a log message about the exit status of a child.
821 static void log_termination_msg(pid_t pid, int status)
823 if (WIFEXITED(status))
824 DSS_INFO_LOG(("child %i exited. Exit status: %i\n", (int)pid,
825 WEXITSTATUS(status)));
826 else if (WIFSIGNALED(status))
827 DSS_NOTICE_LOG(("child %i was killed by signal %i\n", (int)pid,
830 DSS_WARNING_LOG(("child %i terminated abormally\n", (int)pid));
833 static int wait_for_process(pid_t pid, int *status)
837 DSS_DEBUG_LOG(("Waiting for process %d to terminate\n", (int)pid));
842 FD_SET(signal_pipe, &rfds);
843 ret = dss_select(signal_pipe + 1, &rfds, NULL, NULL);
849 if (ret == SIGCHLD) {
850 ret = waitpid(pid, status, 0);
853 if (errno != EINTR) { /* error */
854 ret = -ERRNO_TO_DSS_ERROR(errno);
858 /* SIGINT or SIGTERM */
859 dss_kill(pid, SIGTERM, "killing child process");
862 DSS_ERROR_LOG(("failed to wait for process %d\n", (int)pid));
864 log_termination_msg(pid, *status);
868 static void handle_pre_remove_exit(int status)
870 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
871 snapshot_removal_status = HS_READY;
872 gettimeofday(&next_removal_check, NULL);
873 next_removal_check.tv_sec += 60;
876 snapshot_removal_status = HS_PRE_SUCCESS;
879 static int handle_rm_exit(int status)
881 if (!WIFEXITED(status)) {
882 snapshot_removal_status = HS_READY;
883 return -E_INVOLUNTARY_EXIT;
885 if (WEXITSTATUS(status)) {
886 snapshot_removal_status = HS_READY;
887 return -E_BAD_EXIT_CODE;
889 snapshot_removal_status = HS_SUCCESS;
893 static void handle_post_remove_exit(void)
895 snapshot_removal_status = HS_READY;
898 static int handle_remove_exit(int status)
901 struct snapshot *s = snapshot_currently_being_removed;
904 switch (snapshot_removal_status) {
906 handle_pre_remove_exit(status);
910 ret = handle_rm_exit(status);
912 case HS_POST_RUNNING:
913 handle_post_remove_exit();
919 if (snapshot_removal_status == HS_READY) {
922 snapshot_currently_being_removed = NULL;
928 static int wait_for_remove_process(void)
934 snapshot_removal_status == HS_PRE_RUNNING ||
935 snapshot_removal_status == HS_RUNNING ||
936 snapshot_removal_status == HS_POST_RUNNING
938 ret = wait_for_process(remove_pid, &status);
941 return handle_remove_exit(status);
944 static int handle_rsync_exit(int status)
948 if (!WIFEXITED(status)) {
949 DSS_ERROR_LOG(("rsync process %d died involuntary\n", (int)create_pid));
950 ret = -E_INVOLUNTARY_EXIT;
951 snapshot_creation_status = HS_READY;
954 es = WEXITSTATUS(status);
956 * Restart rsync on non-fatal errors:
957 * 24: Partial transfer due to vanished source files
959 if (es != 0 && es != 24) {
960 DSS_WARNING_LOG(("rsync exit code %d, error count %d\n",
961 es, ++num_consecutive_rsync_errors));
962 if (!logfile) { /* called by com_run() */
963 ret = -E_BAD_EXIT_CODE;
966 if (num_consecutive_rsync_errors >
967 OPT_UINT32_VAL(RUN, MAX_RSYNC_ERRORS)) {
968 ret = -E_TOO_MANY_RSYNC_ERRORS;
969 snapshot_creation_status = HS_READY;
972 DSS_WARNING_LOG(("restarting rsync process\n"));
973 snapshot_creation_status = HS_NEEDS_RESTART;
974 next_snapshot_time = get_current_time() + 60;
978 num_consecutive_rsync_errors = 0;
979 ret = rename_incomplete_snapshot(current_snapshot_creation_time);
982 snapshot_creation_status = HS_SUCCESS;
983 free(name_of_reference_snapshot);
984 name_of_reference_snapshot = NULL;
986 create_process_stopped = 0;
990 static int handle_pre_create_hook_exit(int status)
993 static int warn_count;
995 if (!WIFEXITED(status)) {
996 snapshot_creation_status = HS_READY;
997 ret = -E_INVOLUNTARY_EXIT;
1000 es = WEXITSTATUS(status);
1002 if (!warn_count--) {
1003 DSS_NOTICE_LOG(("pre_create_hook %s returned %d\n",
1004 OPT_STRING_VAL(DSS, PRE_CREATE_HOOK), es));
1005 DSS_NOTICE_LOG(("deferring snapshot creation...\n"));
1006 warn_count = 60; /* warn only once per hour */
1008 next_snapshot_time = get_current_time() + 60;
1009 snapshot_creation_status = HS_READY;
1014 snapshot_creation_status = HS_PRE_SUCCESS;
1020 static int handle_sigchld(void)
1023 int status, ret = reap_child(&pid, &status);
1028 if (pid == create_pid) {
1029 switch (snapshot_creation_status) {
1030 case HS_PRE_RUNNING:
1031 ret = handle_pre_create_hook_exit(status);
1034 ret = handle_rsync_exit(status);
1036 case HS_POST_RUNNING:
1037 snapshot_creation_status = HS_READY;
1041 DSS_EMERG_LOG(("BUG: create can't die in status %d\n",
1042 snapshot_creation_status));
1048 if (pid == remove_pid) {
1049 ret = handle_remove_exit(status);
1054 DSS_EMERG_LOG(("BUG: unknown process %d died\n", (int)pid));
1058 static int change_to_dest_dir(void)
1061 const char *dd = OPT_STRING_VAL(DSS, DEST_DIR);
1063 DSS_INFO_LOG(("changing cwd to %s\n", dd));
1066 ret = -ERRNO_TO_DSS_ERROR(errno);
1067 DSS_ERROR_LOG(("could not change cwd to %s\n", dd));
1071 static int check_config(const struct lls_command *cmd)
1074 uint32_t unit_interval = OPT_UINT32_VAL(DSS, UNIT_INTERVAL);
1075 uint32_t num_intervals = OPT_UINT32_VAL(DSS, NUM_INTERVALS);
1077 if (unit_interval == 0) {
1078 DSS_ERROR_LOG(("bad unit interval: %i\n", unit_interval));
1079 return -E_INVALID_NUMBER;
1081 DSS_DEBUG_LOG(("unit interval: %i day(s)\n", unit_interval));
1083 if (num_intervals == 0 || num_intervals > 30) {
1084 DSS_ERROR_LOG(("bad number of intervals: %i\n", num_intervals));
1085 return -E_INVALID_NUMBER;
1087 if (cmd == CMD_PTR(RUN) || cmd == CMD_PTR(CREATE))
1088 if (!OPT_GIVEN(DSS, SOURCE_DIR)) {
1089 DSS_ERROR_LOG(("--source-dir required\n"));
1092 if (cmd == CMD_PTR(RUN) || cmd == CMD_PTR(CREATE)
1093 || cmd == CMD_PTR(LS) || cmd == CMD_PTR(PRUNE)) {
1094 if (!OPT_GIVEN(DSS, DEST_DIR)) {
1095 DSS_ERROR_LOG(("--dest-dir required\n"));
1098 ret = change_to_dest_dir();
1102 DSS_DEBUG_LOG(("number of intervals: %i\n", num_intervals));
1106 static int lopsub_error(int lopsub_ret, char **errctx)
1108 const char *msg = lls_strerror(-lopsub_ret);
1110 DSS_ERROR_LOG(("%s: %s\n", *errctx, msg));
1112 DSS_ERROR_LOG(("%s\n", msg));
1118 static int parse_config_file(bool sighup, const struct lls_command *cmd)
1121 char *config_file = get_config_file_name();
1122 struct stat statbuf;
1126 char **cf_argv, *errctx = NULL;
1127 struct lls_parse_result *cf_lpr, *merged_lpr, *clpr;
1128 const char *subcmd_name;
1130 ret = open(config_file, O_RDONLY);
1132 if (errno != ENOENT || OPT_GIVEN(DSS, CONFIG_FILE)) {
1133 ret = -ERRNO_TO_DSS_ERROR(errno);
1134 DSS_ERROR_LOG(("config file %s can not be opened\n",
1138 /* no config file -- nothing to do */
1143 ret = fstat(fd, &statbuf);
1145 ret = -ERRNO_TO_DSS_ERROR(errno);
1146 DSS_ERROR_LOG(("failed to stat config file %s\n", config_file));
1149 sz = statbuf.st_size;
1150 if (sz == 0) { /* config file is empty -- nothing to do */
1154 map = mmap(NULL, sz, PROT_READ, MAP_PRIVATE, fd, 0);
1155 if (map == MAP_FAILED) {
1156 ret = -ERRNO_TO_DSS_ERROR(errno);
1157 DSS_ERROR_LOG(("failed to mmap config file %s\n",
1161 if (cmd == CMD_PTR(DSS))
1164 subcmd_name = lls_command_name(cmd);
1165 ret = lls_convert_config(map, sz, subcmd_name, &cf_argv, &errctx);
1168 DSS_ERROR_LOG(("failed to convert config file %s\n",
1170 ret = lopsub_error(ret, &errctx);
1174 ret = lls_parse(cf_argc, cf_argv, cmd, &cf_lpr, &errctx);
1175 lls_free_argv(cf_argv);
1177 ret = lopsub_error(ret, &errctx);
1180 clpr = cmd == CMD_PTR(DSS)? cmdline_lpr : cmdline_sublpr;
1181 if (sighup) /* config file overrides command line */
1182 ret = lls_merge(cf_lpr, clpr, cmd, &merged_lpr, &errctx);
1183 else /* command line options overrride config file options */
1184 ret = lls_merge(clpr, cf_lpr, cmd, &merged_lpr, &errctx);
1185 lls_free_parse_result(cf_lpr, cmd);
1187 ret = lopsub_error(ret, &errctx);
1193 DSS_DEBUG_LOG(("loglevel: %d\n", OPT_UINT32_VAL(DSS, LOGLEVEL)));
1194 if (cmd != CMD_PTR(DSS)) {
1196 if (sublpr != cmdline_sublpr)
1197 lls_free_parse_result(sublpr, cmd);
1198 sublpr = merged_lpr;
1200 sublpr = cmdline_sublpr;
1203 if (lpr != cmdline_lpr)
1204 lls_free_parse_result(lpr, cmd);
1215 DSS_EMERG_LOG(("%s\n", dss_strerror(-ret)));
1219 static int handle_sighup(void)
1223 DSS_NOTICE_LOG(("SIGHUP, re-reading config\n"));
1224 dump_dss_config("old");
1225 ret = parse_config_file(true /* SIGHUP */, CMD_PTR(DSS));
1228 ret = parse_config_file(true /* SIGHUP */, CMD_PTR(RUN));
1231 ret = check_config(CMD_PTR(RUN));
1236 if (OPT_GIVEN(RUN, DAEMON) || daemonized) {
1237 logfile = open_log(OPT_STRING_VAL(RUN, LOGFILE));
1238 log_welcome(OPT_UINT32_VAL(DSS, LOGLEVEL));
1241 dump_dss_config("reloaded");
1242 invalidate_next_snapshot_time();
1246 static void kill_children(void)
1248 restart_create_process();
1249 dss_kill(create_pid, SIGTERM, NULL);
1250 dss_kill(remove_pid, SIGTERM, NULL);
1253 static int handle_signal(void)
1255 int sig, ret = next_signal();
1267 ret = handle_sighup();
1270 ret = handle_sigchld();
1275 DSS_ERROR_LOG(("%s\n", dss_strerror(-ret)));
1280 * We can not use rsync locally if the local user is different from the remote
1281 * user or if the src dir is not on the local host (or both).
1283 static int use_rsync_locally(char *logname)
1285 const char *h = OPT_STRING_VAL(DSS, REMOTE_HOST);
1287 if (strcmp(h, "localhost") && strcmp(h, "127.0.0.1"))
1289 if (OPT_GIVEN(DSS, REMOTE_USER) &&
1290 strcmp(OPT_STRING_VAL(DSS, REMOTE_USER), logname))
1295 static int rename_resume_snap(int64_t creation_time)
1297 struct snapshot_list sl;
1298 struct snapshot *s = NULL;
1299 char *new_name = incomplete_name(creation_time);
1303 sl.num_snapshots = 0;
1306 dss_get_snapshot_list(&sl);
1308 * Snapshot recycling: We first look at the newest snapshot. If this
1309 * snapshot happens to be incomplete, the last rsync process was
1310 * aborted and we reuse this one. Otherwise we look at snapshots which
1311 * could be removed (outdated and redundant snapshots) as candidates
1312 * for recycling. If no outdated/redundant snapshot exists, we check if
1313 * there is an orphaned snapshot, which likely is useless anyway.
1315 * Only if no existing snapshot is suitable for recycling, we bite the
1316 * bullet and create a new one.
1318 s = get_newest_snapshot(&sl);
1319 if (!s) /* no snapshots at all */
1321 /* re-use last snapshot if it is incomplete */
1323 if ((s->flags & SS_COMPLETE) == 0)
1326 s = find_outdated_snapshot(&sl);
1330 s = find_redundant_snapshot(&sl);
1334 s = find_orphaned_snapshot(&sl);
1337 DSS_NOTICE_LOG(("recycling %s snapshot %s\n", why, s->name));
1338 ret = dss_rename(s->name, new_name);
1341 DSS_NOTICE_LOG(("creating %s\n", new_name));
1343 free_snapshot_list(&sl);
1347 static void create_rsync_argv(char ***argv, int64_t *num)
1350 int i = 0, j, N = OPT_GIVEN(DSS, RSYNC_OPTION);
1351 struct snapshot_list sl;
1354 dss_get_snapshot_list(&sl);
1355 assert(!name_of_reference_snapshot);
1356 name_of_reference_snapshot = name_of_newest_complete_snapshot(&sl);
1357 free_snapshot_list(&sl);
1359 *argv = dss_malloc((15 + N) * sizeof(char *));
1360 (*argv)[i++] = dss_strdup("rsync");
1361 (*argv)[i++] = dss_strdup("-a");
1362 (*argv)[i++] = dss_strdup("--delete");
1364 srandom((unsigned)time(NULL)); /* no need to be fancy here */
1367 if (1000 * (random() / (RAND_MAX + 1.0)) < OPT_UINT32_VAL(DSS, CHECKSUM)) {
1368 DSS_NOTICE_LOG(("adding --checksum to rsync options\n"));
1369 (*argv)[i++] = dss_strdup("--checksum");
1371 for (j = 0; j < N; j++)
1372 (*argv)[i++] = dss_strdup(lls_string_val(j,
1373 OPT_RESULT(DSS, RSYNC_OPTION)));
1374 if (name_of_reference_snapshot) {
1375 DSS_INFO_LOG(("using %s as reference\n", name_of_reference_snapshot));
1376 (*argv)[i++] = make_message("--link-dest=../%s",
1377 name_of_reference_snapshot);
1379 DSS_INFO_LOG(("no suitable reference snapshot found\n"));
1380 logname = dss_logname();
1381 if (use_rsync_locally(logname))
1382 (*argv)[i++] = dss_strdup(OPT_STRING_VAL(DSS, SOURCE_DIR));
1384 (*argv)[i++] = make_message("%s@%s:%s/",
1385 OPT_GIVEN(DSS, REMOTE_USER)?
1386 OPT_STRING_VAL(DSS, REMOTE_USER) : logname,
1387 OPT_STRING_VAL(DSS, REMOTE_HOST),
1388 OPT_STRING_VAL(DSS, SOURCE_DIR));
1390 *num = get_current_time();
1391 (*argv)[i++] = incomplete_name(*num);
1392 (*argv)[i++] = NULL;
1393 for (j = 0; j < i; j++)
1394 DSS_DEBUG_LOG(("argv[%d] = %s\n", j, (*argv)[j]));
1397 static void free_rsync_argv(char **argv)
1403 for (i = 0; argv[i]; i++)
1408 static int create_snapshot(char **argv)
1412 ret = rename_resume_snap(current_snapshot_creation_time);
1415 dss_exec(&create_pid, argv[0], argv);
1416 snapshot_creation_status = HS_RUNNING;
1420 static int select_loop(void)
1423 /* check every 60 seconds for free disk space */
1425 char **rsync_argv = NULL;
1429 struct timeval *tvp;
1432 tvp = NULL; /* sleep until rm hook/process dies */
1433 else { /* sleep one minute */
1439 FD_SET(signal_pipe, &rfds);
1440 ret = dss_select(signal_pipe + 1, &rfds, NULL, tvp);
1443 if (FD_ISSET(signal_pipe, &rfds)) {
1444 ret = handle_signal();
1450 if (snapshot_removal_status == HS_PRE_SUCCESS) {
1456 if (snapshot_removal_status == HS_SUCCESS) {
1460 ret = try_to_free_disk_space();
1463 if (snapshot_removal_status != HS_READY) {
1464 stop_create_process();
1467 restart_create_process();
1468 switch (snapshot_creation_status) {
1470 if (!next_snapshot_is_due())
1474 case HS_PRE_RUNNING:
1476 case HS_POST_RUNNING:
1478 case HS_PRE_SUCCESS:
1479 if (!name_of_reference_snapshot) {
1480 free_rsync_argv(rsync_argv);
1481 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
1483 ret = create_snapshot(rsync_argv);
1487 case HS_NEEDS_RESTART:
1488 if (!next_snapshot_is_due())
1490 ret = create_snapshot(rsync_argv);
1503 static void exit_hook(int exit_code)
1505 const char *argv[3];
1508 argv[0] = OPT_STRING_VAL(DSS, EXIT_HOOK);
1509 argv[1] = dss_strerror(-exit_code);
1512 DSS_NOTICE_LOG(("executing %s %s\n", argv[0], argv[1]));
1513 dss_exec(&pid, argv[0], (char **)argv);
1516 static void lock_dss_or_die(void)
1518 char *config_file = get_config_file_name();
1519 int ret = lock_dss(config_file);
1523 DSS_EMERG_LOG(("failed to lock: %s\n", dss_strerror(-ret)));
1528 static int com_run(void)
1534 if (OPT_GIVEN(DSS, DRY_RUN)) {
1535 DSS_ERROR_LOG(("dry run not supported by this command\n"));
1538 config_file = get_config_file_name();
1539 ret = get_dss_pid(config_file, &pid);
1542 DSS_ERROR_LOG(("pid %d\n", (int)pid));
1543 return -E_ALREADY_RUNNING;
1545 if (OPT_GIVEN(RUN, DAEMON)) {
1548 logfile = open_log(OPT_STRING_VAL(RUN, LOGFILE));
1551 dump_dss_config("startup");
1552 ret = install_sighandler(SIGHUP);
1556 ret = write(fd, "\0", 1);
1558 DSS_ERROR_LOG(("write to daemon pipe returned %d\n",
1561 return -ERRNO_TO_DSS_ERROR(errno);
1565 ret = select_loop();
1566 if (ret >= 0) /* impossible */
1572 EXPORT_CMD_HANDLER(run);
1574 static int com_prune(void)
1577 struct snapshot_list sl;
1578 struct snapshot *victim;
1579 struct disk_space ds;
1583 ret = get_disk_space(".", &ds);
1586 log_disk_space(&ds);
1587 dss_get_snapshot_list(&sl);
1589 victim = find_outdated_snapshot(&sl);
1593 victim = find_redundant_snapshot(&sl);
1599 if (OPT_GIVEN(DSS, DRY_RUN)) {
1600 dss_msg("%s snapshot %s (interval = %i)\n",
1601 why, victim->name, victim->interval);
1605 pre_remove_hook(victim, why);
1606 if (snapshot_removal_status == HS_PRE_RUNNING) {
1607 ret = wait_for_remove_process();
1610 if (snapshot_removal_status != HS_PRE_SUCCESS)
1616 ret = wait_for_remove_process();
1619 if (snapshot_removal_status != HS_SUCCESS)
1622 if (snapshot_removal_status != HS_POST_RUNNING)
1624 ret = wait_for_remove_process();
1629 free_snapshot_list(&sl);
1632 EXPORT_CMD_HANDLER(prune);
1634 static int com_create(void)
1640 if (OPT_GIVEN(DSS, DRY_RUN)) {
1643 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
1644 for (i = 0; rsync_argv[i]; i++) {
1646 msg = make_message("%s%s%s", tmp? tmp : "",
1647 tmp? " " : "", rsync_argv[i]);
1650 free_rsync_argv(rsync_argv);
1651 dss_msg("%s\n", msg);
1657 ret = wait_for_process(create_pid, &status);
1660 ret = handle_pre_create_hook_exit(status);
1661 if (ret <= 0) /* error, or pre-create failed */
1664 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
1665 ret = create_snapshot(rsync_argv);
1668 ret = wait_for_process(create_pid, &status);
1671 ret = handle_rsync_exit(status);
1676 ret = wait_for_process(create_pid, &status);
1678 free_rsync_argv(rsync_argv);
1681 EXPORT_CMD_HANDLER(create);
1683 static int com_ls(void)
1686 struct snapshot_list sl;
1689 dss_get_snapshot_list(&sl);
1690 FOR_EACH_SNAPSHOT(s, i, &sl) {
1692 if (s->flags & SS_COMPLETE)
1693 d = (s->completion_time - s->creation_time) / 60;
1694 dss_msg("%u\t%s\t%3" PRId64 ":%02" PRId64 "\n", s->interval, s->name, d/60, d%60);
1696 free_snapshot_list(&sl);
1699 EXPORT_CMD_HANDLER(ls);
1701 static int com_configtest(void)
1703 printf("Syntax Ok\n");
1706 EXPORT_CMD_HANDLER(configtest);
1708 static int setup_signal_handling(void)
1712 DSS_INFO_LOG(("setting up signal handlers\n"));
1713 signal_pipe = signal_init(); /* always successful */
1714 ret = install_sighandler(SIGINT);
1717 ret = install_sighandler(SIGTERM);
1720 return install_sighandler(SIGCHLD);
1723 static void handle_version_and_help(void)
1727 if (OPT_GIVEN(DSS, DETAILED_HELP))
1728 txt = lls_long_help(CMD_PTR(DSS));
1729 else if (OPT_GIVEN(DSS, HELP))
1730 txt = lls_short_help(CMD_PTR(DSS));
1731 else if (OPT_GIVEN(DSS, VERSION))
1732 txt = dss_strdup(VERSION_STRING);
1740 static void show_subcommand_summary(void)
1742 const struct lls_command *cmd;
1745 printf("Available subcommands:\n");
1746 for (i = 1; (cmd = lls_cmd(i, dss_suite)); i++) {
1747 const char *name = lls_command_name(cmd);
1748 const char *purpose = lls_purpose(cmd);
1749 printf("%-11s%s\n", name, purpose);
1754 int main(int argc, char **argv)
1757 const struct lls_command *cmd = CMD_PTR(DSS);
1758 char *errctx = NULL;
1759 unsigned num_inputs;
1760 const struct dss_user_data *ud = NULL;
1762 ret = lls_parse(argc, argv, cmd, &cmdline_lpr, &errctx);
1764 ret = lopsub_error(ret, &errctx);
1768 ret = parse_config_file(false /* no SIGHUP */, cmd);
1771 handle_version_and_help();
1772 num_inputs = lls_num_inputs(lpr);
1773 if (num_inputs == 0)
1774 show_subcommand_summary();
1775 ret = lls_lookup_subcmd(argv[argc - num_inputs], dss_suite, &errctx);
1777 ret = lopsub_error(ret, &errctx);
1780 cmd = lls_cmd(ret, dss_suite);
1781 ret = lls_parse(num_inputs, argv + argc - num_inputs, cmd,
1782 &cmdline_sublpr, &errctx);
1784 ret = lopsub_error(ret, &errctx);
1787 sublpr = cmdline_sublpr;
1788 ret = parse_config_file(false /* no SIGHUP */, cmd);
1791 ret = check_config(cmd);
1794 ret = setup_signal_handling();
1797 ud = lls_user_data(cmd);
1798 ret = ud->handler();
1803 DSS_ERROR_LOG(("%s\n", errctx));
1804 DSS_EMERG_LOG(("%s\n", dss_strerror(-ret)));
1807 lls_free_parse_result(lpr, CMD_PTR(DSS));
1808 if (lpr != cmdline_lpr)
1809 lls_free_parse_result(cmdline_lpr, CMD_PTR(DSS));
1810 lls_free_parse_result(sublpr, cmd);
1811 if (sublpr != cmdline_sublpr)
1812 lls_free_parse_result(cmdline_sublpr, cmd);
1813 exit(ret >= 0? EXIT_SUCCESS : EXIT_FAILURE);