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 ret = kill(pid, sig);
300 return -ERRNO_TO_DSS_ERROR(errno);
305 const char * const name;
310 * The table below was taken 2016 from proc/sig.c of procps-3.2.8. Copyright
311 * 1998-2003 by Albert Cahalan, GPLv2.
313 static const struct signal_info signal_table[] = {
314 {"ABRT", SIGABRT}, /* IOT */
317 {"CHLD", SIGCHLD}, /* CLD */
326 {"POLL", SIGPOLL}, /* IO */
335 {"STKFLT", SIGSTKFLT},
338 {"SYS", SIGSYS}, /* UNUSED */
347 {"VTALRM", SIGVTALRM},
353 #define SIGNAL_TABLE_SIZE (sizeof(signal_table) / sizeof(signal_table[0]))
358 static int com_kill(void)
360 const char *arg = OPT_STRING_VAL(KILL, SIGNAL);
363 if (*arg >= '0' && *arg <= '9') {
365 ret = dss_atoi64(arg, &val);
368 if (val < 0 || val > SIGRTMAX)
369 return -ERRNO_TO_DSS_ERROR(EINVAL);
370 return send_signal(val);
372 if (strncasecmp(arg, "sig", 3) == 0)
374 if (strcasecmp(arg, "CLD") == 0)
375 return send_signal(SIGCHLD);
376 if (strcasecmp(arg, "IOT") == 0)
377 return send_signal(SIGABRT);
378 for (i = 0; i < SIGNAL_TABLE_SIZE; i++)
379 if (strcasecmp(arg, signal_table[i].name) == 0)
380 return send_signal(signal_table[i].num);
381 DSS_ERROR_LOG(("invalid sigspec: %s\n", arg));
382 return -ERRNO_TO_DSS_ERROR(EINVAL);
384 EXPORT_CMD_HANDLER(kill);
386 static void dss_get_snapshot_list(struct snapshot_list *sl)
388 get_snapshot_list(sl, OPT_UINT32_VAL(DSS, UNIT_INTERVAL),
389 OPT_UINT32_VAL(DSS, NUM_INTERVALS));
392 static int64_t compute_next_snapshot_time(void)
394 int64_t x = 0, now = get_current_time(), unit_interval
395 = 24 * 3600 * OPT_UINT32_VAL(DSS, UNIT_INTERVAL), ret;
396 unsigned wanted = desired_number_of_snapshots(0,
397 OPT_UINT32_VAL(DSS, NUM_INTERVALS)),
400 struct snapshot *s = NULL;
401 struct snapshot_list sl;
403 dss_get_snapshot_list(&sl);
404 FOR_EACH_SNAPSHOT(s, i, &sl) {
405 if (!(s->flags & SS_COMPLETE))
408 x += s->completion_time - s->creation_time;
413 if (num_complete == 0)
415 x /= num_complete; /* avg time to create one snapshot */
416 if (unit_interval < x * wanted) /* oops, no sleep at all */
418 ret = s->completion_time + unit_interval / wanted - x;
420 free_snapshot_list(&sl);
424 static inline void invalidate_next_snapshot_time(void)
426 next_snapshot_time = 0;
429 static inline int next_snapshot_time_is_valid(void)
431 return next_snapshot_time != 0;
434 static int next_snapshot_is_due(void)
436 int64_t now = get_current_time();
438 if (!next_snapshot_time_is_valid())
439 next_snapshot_time = compute_next_snapshot_time();
440 if (next_snapshot_time <= now) {
441 DSS_DEBUG_LOG(("next snapshot: now\n"));
444 DSS_DEBUG_LOG(("next snapshot due in %" PRId64 " seconds\n",
445 next_snapshot_time - now));
449 static void pre_create_hook(void)
451 assert(snapshot_creation_status == HS_READY);
452 /* make sure that the next snapshot time will be recomputed */
453 invalidate_next_snapshot_time();
454 DSS_DEBUG_LOG(("executing %s\n", OPT_STRING_VAL(DSS, PRE_CREATE_HOOK)));
455 dss_exec_cmdline_pid(&create_pid, OPT_STRING_VAL(DSS, PRE_CREATE_HOOK));
456 snapshot_creation_status = HS_PRE_RUNNING;
459 static void pre_remove_hook(struct snapshot *s, const char *why)
465 DSS_DEBUG_LOG(("%s snapshot %s\n", why, s->name));
466 assert(snapshot_removal_status == HS_READY);
467 assert(remove_pid == 0);
468 assert(!snapshot_currently_being_removed);
470 snapshot_currently_being_removed = dss_malloc(sizeof(struct snapshot));
471 *snapshot_currently_being_removed = *s;
472 snapshot_currently_being_removed->name = dss_strdup(s->name);
474 cmd = make_message("%s %s/%s", OPT_STRING_VAL(DSS, PRE_REMOVE_HOOK),
475 OPT_STRING_VAL(DSS, DEST_DIR), s->name);
476 DSS_DEBUG_LOG(("executing %s\n", cmd));
477 dss_exec_cmdline_pid(&remove_pid, cmd);
479 snapshot_removal_status = HS_PRE_RUNNING;
482 static int exec_rm(void)
484 struct snapshot *s = snapshot_currently_being_removed;
485 char *new_name = being_deleted_name(s);
494 assert(snapshot_removal_status == HS_PRE_SUCCESS);
495 assert(remove_pid == 0);
497 DSS_NOTICE_LOG(("removing %s (interval = %i)\n", s->name, s->interval));
498 ret = dss_rename(s->name, new_name);
501 dss_exec(&remove_pid, argv[0], argv);
502 snapshot_removal_status = HS_RUNNING;
508 static int snapshot_is_being_created(struct snapshot *s)
510 return s->creation_time == current_snapshot_creation_time;
513 static struct snapshot *find_orphaned_snapshot(struct snapshot_list *sl)
518 DSS_DEBUG_LOG(("looking for orphaned snapshots\n"));
519 FOR_EACH_SNAPSHOT(s, i, sl) {
520 if (snapshot_is_being_created(s))
523 * We know that no rm is currently running, so if s is marked
524 * as being deleted, a previously started rm must have failed.
526 if (s->flags & SS_BEING_DELETED)
529 if (s->flags & SS_COMPLETE) /* good snapshot */
532 * This snapshot is incomplete and it is not the snapshot
533 * currently being created. However, we must not remove it if
534 * rsync is about to be restarted. As only the newest snapshot
535 * can be restarted, this snapshot is orphaned if it is not the
536 * newest snapshot or if we are not about to restart rsync.
538 if (get_newest_snapshot(sl) != s)
540 if (snapshot_creation_status != HS_NEEDS_RESTART)
543 /* no orphaned snapshots */
547 static int is_reference_snapshot(struct snapshot *s)
549 if (!name_of_reference_snapshot)
551 return strcmp(s->name, name_of_reference_snapshot)? 0 : 1;
555 * return: 0: no redundant snapshots, 1: rm process started, negative: error
557 static struct snapshot *find_redundant_snapshot(struct snapshot_list *sl)
561 unsigned missing = 0;
562 uint32_t N = OPT_UINT32_VAL(DSS, NUM_INTERVALS);
564 DSS_DEBUG_LOG(("looking for intervals containing too many snapshots\n"));
565 for (interval = N - 1; interval >= 0; interval--) {
566 unsigned keep = desired_number_of_snapshots(interval, N);
567 unsigned num = sl->interval_count[interval];
568 struct snapshot *victim = NULL, *prev = NULL;
569 int64_t score = LONG_MAX;
572 missing += keep - num;
573 if (keep + missing >= num)
575 /* redundant snapshot in this interval, pick snapshot with lowest score */
576 FOR_EACH_SNAPSHOT(s, i, sl) {
579 if (snapshot_is_being_created(s))
581 if (is_reference_snapshot(s))
583 if (s->interval > interval) {
587 if (s->interval < interval)
595 /* check if s is a better victim */
596 this_score = s->creation_time - prev->creation_time;
597 assert(this_score >= 0);
598 if (this_score < score) {
610 static struct snapshot *find_outdated_snapshot(struct snapshot_list *sl)
615 DSS_DEBUG_LOG(("looking for snapshots belonging to intervals >= %d\n",
616 OPT_UINT32_VAL(DSS, NUM_INTERVALS)));
617 FOR_EACH_SNAPSHOT(s, i, sl) {
618 if (snapshot_is_being_created(s))
620 if (is_reference_snapshot(s))
622 if (s->interval < OPT_UINT32_VAL(DSS, NUM_INTERVALS))
629 static struct snapshot *find_oldest_removable_snapshot(struct snapshot_list *sl)
632 struct snapshot *s, *ref = NULL;
634 num_complete = num_complete_snapshots(sl);
635 if (num_complete <= OPT_UINT32_VAL(DSS, MIN_COMPLETE))
637 FOR_EACH_SNAPSHOT(s, i, sl) {
638 if (snapshot_is_being_created(s))
640 if (is_reference_snapshot(s)) { /* avoid this one */
644 DSS_INFO_LOG(("oldest removable snapshot: %s\n", s->name));
648 DSS_WARNING_LOG(("removing reference snapshot %s\n", ref->name));
652 static int rename_incomplete_snapshot(int64_t start)
659 * We don't want the dss_rename() below to fail with EEXIST because the
660 * last complete snapshot was created (and completed) in the same
661 * second as this one.
663 while ((now = get_current_time()) == start)
665 free(path_to_last_complete_snapshot);
666 ret = complete_name(start, now, &path_to_last_complete_snapshot);
669 old_name = incomplete_name(start);
670 ret = dss_rename(old_name, path_to_last_complete_snapshot);
672 DSS_NOTICE_LOG(("%s -> %s\n", old_name,
673 path_to_last_complete_snapshot));
678 static int try_to_free_disk_space(void)
681 struct snapshot_list sl;
682 struct snapshot *victim;
687 ret = disk_space_low(NULL);
690 low_disk_space = ret;
691 gettimeofday(&now, NULL);
692 if (tv_diff(&next_removal_check, &now, NULL) > 0)
694 if (!low_disk_space) {
695 if (OPT_GIVEN(DSS, KEEP_REDUNDANT))
697 if (snapshot_creation_status != HS_READY)
699 if (next_snapshot_is_due())
703 * Idle and --keep_redundant not given, or low disk space. Look at
704 * existing snapshots.
706 dss_get_snapshot_list(&sl);
709 * Don't remove anything if there is free space and we have fewer
710 * snapshots than configured, plus one. This way there is always one
711 * snapshot that can be recycled.
713 if (!low_disk_space && sl.num_snapshots <=
714 1 << OPT_UINT32_VAL(DSS, NUM_INTERVALS))
717 victim = find_outdated_snapshot(&sl);
721 victim = find_redundant_snapshot(&sl);
725 victim = find_orphaned_snapshot(&sl);
728 /* try harder only if disk space is low */
731 DSS_WARNING_LOG(("disk space low and nothing obvious to remove\n"));
733 victim = find_oldest_removable_snapshot(&sl);
736 DSS_CRIT_LOG(("uhuhu: disk space low and nothing to remove\n"));
737 ret = -ERRNO_TO_DSS_ERROR(ENOSPC);
740 pre_remove_hook(victim, why);
742 free_snapshot_list(&sl);
746 static void post_create_hook(void)
748 char *cmd = make_message("%s %s/%s",
749 OPT_STRING_VAL(DSS, POST_CREATE_HOOK),
750 OPT_STRING_VAL(DSS, DEST_DIR), path_to_last_complete_snapshot);
751 DSS_NOTICE_LOG(("executing %s\n", cmd));
752 dss_exec_cmdline_pid(&create_pid, cmd);
754 snapshot_creation_status = HS_POST_RUNNING;
757 static void post_remove_hook(void)
760 struct snapshot *s = snapshot_currently_being_removed;
764 cmd = make_message("%s %s/%s", OPT_STRING_VAL(DSS, POST_REMOVE_HOOK),
765 OPT_STRING_VAL(DSS, DEST_DIR), s->name);
766 DSS_NOTICE_LOG(("executing %s\n", cmd));
767 dss_exec_cmdline_pid(&remove_pid, cmd);
769 snapshot_removal_status = HS_POST_RUNNING;
772 static void dss_kill(pid_t pid, int sig, const char *msg)
774 const char *signame, *process_name;
779 case SIGTERM: signame = "TERM"; break;
780 case SIGSTOP: signame = "STOP"; break;
781 case SIGCONT: signame = "CONT"; break;
782 default: signame = "????";
785 if (pid == create_pid)
786 process_name = "create";
787 else if (pid == remove_pid)
788 process_name = "remove";
789 else process_name = "??????";
792 DSS_INFO_LOG(("%s\n", msg));
793 DSS_DEBUG_LOG(("sending signal %d (%s) to pid %d (%s process)\n",
794 sig, signame, (int)pid, process_name));
795 if (kill(pid, sig) >= 0)
797 DSS_INFO_LOG(("failed to send signal %d (%s) to pid %d (%s process)\n",
798 sig, signame, (int)pid, process_name));
801 static void stop_create_process(void)
803 if (create_process_stopped)
805 dss_kill(create_pid, SIGSTOP, "suspending create process");
806 create_process_stopped = 1;
809 static void restart_create_process(void)
811 if (!create_process_stopped)
813 dss_kill(create_pid, SIGCONT, "resuming create process");
814 create_process_stopped = 0;
818 * Print a log message about the exit status of a child.
820 static void log_termination_msg(pid_t pid, int status)
822 if (WIFEXITED(status))
823 DSS_INFO_LOG(("child %i exited. Exit status: %i\n", (int)pid,
824 WEXITSTATUS(status)));
825 else if (WIFSIGNALED(status))
826 DSS_NOTICE_LOG(("child %i was killed by signal %i\n", (int)pid,
829 DSS_WARNING_LOG(("child %i terminated abormally\n", (int)pid));
832 static int wait_for_process(pid_t pid, int *status)
836 DSS_DEBUG_LOG(("Waiting for process %d to terminate\n", (int)pid));
841 FD_SET(signal_pipe, &rfds);
842 ret = dss_select(signal_pipe + 1, &rfds, NULL, NULL);
848 if (ret == SIGCHLD) {
849 ret = waitpid(pid, status, 0);
852 if (errno != EINTR) { /* error */
853 ret = -ERRNO_TO_DSS_ERROR(errno);
857 /* SIGINT or SIGTERM */
858 dss_kill(pid, SIGTERM, "killing child process");
861 DSS_ERROR_LOG(("failed to wait for process %d\n", (int)pid));
863 log_termination_msg(pid, *status);
867 static void handle_pre_remove_exit(int status)
869 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
870 snapshot_removal_status = HS_READY;
871 gettimeofday(&next_removal_check, NULL);
872 next_removal_check.tv_sec += 60;
875 snapshot_removal_status = HS_PRE_SUCCESS;
878 static int handle_rm_exit(int status)
880 if (!WIFEXITED(status)) {
881 snapshot_removal_status = HS_READY;
882 return -E_INVOLUNTARY_EXIT;
884 if (WEXITSTATUS(status)) {
885 snapshot_removal_status = HS_READY;
886 return -E_BAD_EXIT_CODE;
888 snapshot_removal_status = HS_SUCCESS;
892 static void handle_post_remove_exit(void)
894 snapshot_removal_status = HS_READY;
897 static int handle_remove_exit(int status)
900 struct snapshot *s = snapshot_currently_being_removed;
903 switch (snapshot_removal_status) {
905 handle_pre_remove_exit(status);
909 ret = handle_rm_exit(status);
911 case HS_POST_RUNNING:
912 handle_post_remove_exit();
918 if (snapshot_removal_status == HS_READY) {
921 snapshot_currently_being_removed = NULL;
927 static int wait_for_remove_process(void)
933 snapshot_removal_status == HS_PRE_RUNNING ||
934 snapshot_removal_status == HS_RUNNING ||
935 snapshot_removal_status == HS_POST_RUNNING
937 ret = wait_for_process(remove_pid, &status);
940 return handle_remove_exit(status);
943 static int handle_rsync_exit(int status)
947 if (!WIFEXITED(status)) {
948 DSS_ERROR_LOG(("rsync process %d died involuntary\n", (int)create_pid));
949 ret = -E_INVOLUNTARY_EXIT;
950 snapshot_creation_status = HS_READY;
953 es = WEXITSTATUS(status);
955 * Restart rsync on non-fatal errors:
956 * 24: Partial transfer due to vanished source files
958 if (es != 0 && es != 24) {
959 DSS_WARNING_LOG(("rsync exit code %d, error count %d\n",
960 es, ++num_consecutive_rsync_errors));
961 if (!logfile) { /* called by com_run() */
962 ret = -E_BAD_EXIT_CODE;
965 if (num_consecutive_rsync_errors >
966 OPT_UINT32_VAL(RUN, MAX_RSYNC_ERRORS)) {
967 ret = -E_TOO_MANY_RSYNC_ERRORS;
968 snapshot_creation_status = HS_READY;
971 DSS_WARNING_LOG(("restarting rsync process\n"));
972 snapshot_creation_status = HS_NEEDS_RESTART;
973 next_snapshot_time = get_current_time() + 60;
977 num_consecutive_rsync_errors = 0;
978 ret = rename_incomplete_snapshot(current_snapshot_creation_time);
981 snapshot_creation_status = HS_SUCCESS;
982 free(name_of_reference_snapshot);
983 name_of_reference_snapshot = NULL;
985 create_process_stopped = 0;
989 static int handle_pre_create_hook_exit(int status)
992 static int warn_count;
994 if (!WIFEXITED(status)) {
995 snapshot_creation_status = HS_READY;
996 ret = -E_INVOLUNTARY_EXIT;
999 es = WEXITSTATUS(status);
1001 if (!warn_count--) {
1002 DSS_NOTICE_LOG(("pre_create_hook %s returned %d\n",
1003 OPT_STRING_VAL(DSS, PRE_CREATE_HOOK), es));
1004 DSS_NOTICE_LOG(("deferring snapshot creation...\n"));
1005 warn_count = 60; /* warn only once per hour */
1007 next_snapshot_time = get_current_time() + 60;
1008 snapshot_creation_status = HS_READY;
1013 snapshot_creation_status = HS_PRE_SUCCESS;
1019 static int handle_sigchld(void)
1022 int status, ret = reap_child(&pid, &status);
1027 if (pid == create_pid) {
1028 switch (snapshot_creation_status) {
1029 case HS_PRE_RUNNING:
1030 ret = handle_pre_create_hook_exit(status);
1033 ret = handle_rsync_exit(status);
1035 case HS_POST_RUNNING:
1036 snapshot_creation_status = HS_READY;
1040 DSS_EMERG_LOG(("BUG: create can't die in status %d\n",
1041 snapshot_creation_status));
1047 if (pid == remove_pid) {
1048 ret = handle_remove_exit(status);
1053 DSS_EMERG_LOG(("BUG: unknown process %d died\n", (int)pid));
1057 static int change_to_dest_dir(void)
1060 const char *dd = OPT_STRING_VAL(DSS, DEST_DIR);
1062 DSS_INFO_LOG(("changing cwd to %s\n", dd));
1065 ret = -ERRNO_TO_DSS_ERROR(errno);
1066 DSS_ERROR_LOG(("could not change cwd to %s\n", dd));
1070 static int check_config(const struct lls_command *cmd)
1073 uint32_t unit_interval = OPT_UINT32_VAL(DSS, UNIT_INTERVAL);
1074 uint32_t num_intervals = OPT_UINT32_VAL(DSS, NUM_INTERVALS);
1076 if (unit_interval == 0) {
1077 DSS_ERROR_LOG(("bad unit interval: %i\n", unit_interval));
1078 return -E_INVALID_NUMBER;
1080 DSS_DEBUG_LOG(("unit interval: %i day(s)\n", unit_interval));
1082 if (num_intervals == 0 || num_intervals > 30) {
1083 DSS_ERROR_LOG(("bad number of intervals: %i\n", num_intervals));
1084 return -E_INVALID_NUMBER;
1086 if (cmd == CMD_PTR(RUN) || cmd == CMD_PTR(CREATE))
1087 if (!OPT_GIVEN(DSS, SOURCE_DIR)) {
1088 DSS_ERROR_LOG(("--source-dir required\n"));
1091 if (cmd == CMD_PTR(RUN) || cmd == CMD_PTR(CREATE)
1092 || cmd == CMD_PTR(LS) || cmd == CMD_PTR(PRUNE)) {
1093 if (!OPT_GIVEN(DSS, DEST_DIR)) {
1094 DSS_ERROR_LOG(("--dest-dir required\n"));
1097 ret = change_to_dest_dir();
1101 DSS_DEBUG_LOG(("number of intervals: %i\n", num_intervals));
1105 static int lopsub_error(int lopsub_ret, char **errctx)
1107 const char *msg = lls_strerror(-lopsub_ret);
1109 DSS_ERROR_LOG(("%s: %s\n", *errctx, msg));
1111 DSS_ERROR_LOG(("%s\n", msg));
1117 static int parse_config_file(bool sighup, const struct lls_command *cmd)
1120 char *config_file = get_config_file_name();
1121 struct stat statbuf;
1125 char **cf_argv, *errctx = NULL;
1126 struct lls_parse_result *cf_lpr, *merged_lpr, *clpr;
1127 const char *subcmd_name;
1129 ret = open(config_file, O_RDONLY);
1131 if (errno != ENOENT || OPT_GIVEN(DSS, CONFIG_FILE)) {
1132 ret = -ERRNO_TO_DSS_ERROR(errno);
1133 DSS_ERROR_LOG(("config file %s can not be opened\n",
1137 /* no config file -- nothing to do */
1142 ret = fstat(fd, &statbuf);
1144 ret = -ERRNO_TO_DSS_ERROR(errno);
1145 DSS_ERROR_LOG(("failed to stat config file %s\n", config_file));
1148 sz = statbuf.st_size;
1149 if (sz == 0) { /* config file is empty -- nothing to do */
1153 map = mmap(NULL, sz, PROT_READ, MAP_PRIVATE, fd, 0);
1154 if (map == MAP_FAILED) {
1155 ret = -ERRNO_TO_DSS_ERROR(errno);
1156 DSS_ERROR_LOG(("failed to mmap config file %s\n",
1160 if (cmd == CMD_PTR(DSS))
1163 subcmd_name = lls_command_name(cmd);
1164 ret = lls_convert_config(map, sz, subcmd_name, &cf_argv, &errctx);
1167 DSS_ERROR_LOG(("failed to convert config file %s\n",
1169 ret = lopsub_error(ret, &errctx);
1173 ret = lls_parse(cf_argc, cf_argv, cmd, &cf_lpr, &errctx);
1174 lls_free_argv(cf_argv);
1176 ret = lopsub_error(ret, &errctx);
1179 clpr = cmd == CMD_PTR(DSS)? cmdline_lpr : cmdline_sublpr;
1180 if (sighup) /* config file overrides command line */
1181 ret = lls_merge(cf_lpr, clpr, cmd, &merged_lpr, &errctx);
1182 else /* command line options overrride config file options */
1183 ret = lls_merge(clpr, cf_lpr, cmd, &merged_lpr, &errctx);
1184 lls_free_parse_result(cf_lpr, cmd);
1186 ret = lopsub_error(ret, &errctx);
1192 DSS_DEBUG_LOG(("loglevel: %d\n", OPT_UINT32_VAL(DSS, LOGLEVEL)));
1193 if (cmd != CMD_PTR(DSS)) {
1195 if (sublpr != cmdline_sublpr)
1196 lls_free_parse_result(sublpr, cmd);
1197 sublpr = merged_lpr;
1199 sublpr = cmdline_sublpr;
1202 if (lpr != cmdline_lpr)
1203 lls_free_parse_result(lpr, cmd);
1214 DSS_EMERG_LOG(("%s\n", dss_strerror(-ret)));
1218 static int handle_sighup(void)
1222 DSS_NOTICE_LOG(("SIGHUP, re-reading config\n"));
1223 dump_dss_config("old");
1224 ret = parse_config_file(true /* SIGHUP */, CMD_PTR(DSS));
1227 ret = parse_config_file(true /* SIGHUP */, CMD_PTR(RUN));
1230 ret = check_config(CMD_PTR(RUN));
1235 if (OPT_GIVEN(RUN, DAEMON) || daemonized) {
1236 logfile = open_log(OPT_STRING_VAL(RUN, LOGFILE));
1237 log_welcome(OPT_UINT32_VAL(DSS, LOGLEVEL));
1240 dump_dss_config("reloaded");
1241 invalidate_next_snapshot_time();
1245 static void kill_children(void)
1247 restart_create_process();
1248 dss_kill(create_pid, SIGTERM, NULL);
1249 dss_kill(remove_pid, SIGTERM, NULL);
1252 static int handle_signal(void)
1254 int sig, ret = next_signal();
1266 ret = handle_sighup();
1269 ret = handle_sigchld();
1274 DSS_ERROR_LOG(("%s\n", dss_strerror(-ret)));
1279 * We can not use rsync locally if the local user is different from the remote
1280 * user or if the src dir is not on the local host (or both).
1282 static int use_rsync_locally(char *logname)
1284 const char *h = OPT_STRING_VAL(DSS, REMOTE_HOST);
1286 if (strcmp(h, "localhost") && strcmp(h, "127.0.0.1"))
1288 if (OPT_GIVEN(DSS, REMOTE_USER) &&
1289 strcmp(OPT_STRING_VAL(DSS, REMOTE_USER), logname))
1294 static int rename_resume_snap(int64_t creation_time)
1296 struct snapshot_list sl;
1297 struct snapshot *s = NULL;
1298 char *new_name = incomplete_name(creation_time);
1302 sl.num_snapshots = 0;
1305 dss_get_snapshot_list(&sl);
1307 * Snapshot recycling: We first look at the newest snapshot. If this
1308 * snapshot happens to be incomplete, the last rsync process was
1309 * aborted and we reuse this one. Otherwise we look at snapshots which
1310 * could be removed (outdated and redundant snapshots) as candidates
1311 * for recycling. If no outdated/redundant snapshot exists, we check if
1312 * there is an orphaned snapshot, which likely is useless anyway.
1314 * Only if no existing snapshot is suitable for recycling, we bite the
1315 * bullet and create a new one.
1317 s = get_newest_snapshot(&sl);
1318 if (!s) /* no snapshots at all */
1320 /* re-use last snapshot if it is incomplete */
1322 if ((s->flags & SS_COMPLETE) == 0)
1325 s = find_outdated_snapshot(&sl);
1329 s = find_redundant_snapshot(&sl);
1333 s = find_orphaned_snapshot(&sl);
1336 DSS_NOTICE_LOG(("recycling %s snapshot %s\n", why, s->name));
1337 ret = dss_rename(s->name, new_name);
1340 DSS_NOTICE_LOG(("creating %s\n", new_name));
1342 free_snapshot_list(&sl);
1346 static void create_rsync_argv(char ***argv, int64_t *num)
1349 int i = 0, j, N = OPT_GIVEN(DSS, RSYNC_OPTION);
1350 struct snapshot_list sl;
1353 dss_get_snapshot_list(&sl);
1354 assert(!name_of_reference_snapshot);
1355 name_of_reference_snapshot = name_of_newest_complete_snapshot(&sl);
1356 free_snapshot_list(&sl);
1358 *argv = dss_malloc((15 + N) * sizeof(char *));
1359 (*argv)[i++] = dss_strdup("rsync");
1360 (*argv)[i++] = dss_strdup("-a");
1361 (*argv)[i++] = dss_strdup("--delete");
1363 srandom((unsigned)time(NULL)); /* no need to be fancy here */
1366 if (1000 * (random() / (RAND_MAX + 1.0)) < OPT_UINT32_VAL(DSS, CHECKSUM)) {
1367 DSS_NOTICE_LOG(("adding --checksum to rsync options\n"));
1368 (*argv)[i++] = dss_strdup("--checksum");
1370 for (j = 0; j < N; j++)
1371 (*argv)[i++] = dss_strdup(lls_string_val(j,
1372 OPT_RESULT(DSS, RSYNC_OPTION)));
1373 if (name_of_reference_snapshot) {
1374 DSS_INFO_LOG(("using %s as reference\n", name_of_reference_snapshot));
1375 (*argv)[i++] = make_message("--link-dest=../%s",
1376 name_of_reference_snapshot);
1378 DSS_INFO_LOG(("no suitable reference snapshot found\n"));
1379 logname = dss_logname();
1380 if (use_rsync_locally(logname))
1381 (*argv)[i++] = dss_strdup(OPT_STRING_VAL(DSS, SOURCE_DIR));
1383 (*argv)[i++] = make_message("%s@%s:%s/",
1384 OPT_GIVEN(DSS, REMOTE_USER)?
1385 OPT_STRING_VAL(DSS, REMOTE_USER) : logname,
1386 OPT_STRING_VAL(DSS, REMOTE_HOST),
1387 OPT_STRING_VAL(DSS, SOURCE_DIR));
1389 *num = get_current_time();
1390 (*argv)[i++] = incomplete_name(*num);
1391 (*argv)[i++] = NULL;
1392 for (j = 0; j < i; j++)
1393 DSS_DEBUG_LOG(("argv[%d] = %s\n", j, (*argv)[j]));
1396 static void free_rsync_argv(char **argv)
1402 for (i = 0; argv[i]; i++)
1407 static int create_snapshot(char **argv)
1411 ret = rename_resume_snap(current_snapshot_creation_time);
1414 dss_exec(&create_pid, argv[0], argv);
1415 snapshot_creation_status = HS_RUNNING;
1419 static int select_loop(void)
1422 /* check every 60 seconds for free disk space */
1424 char **rsync_argv = NULL;
1428 struct timeval *tvp;
1431 tvp = NULL; /* sleep until rm hook/process dies */
1432 else { /* sleep one minute */
1438 FD_SET(signal_pipe, &rfds);
1439 ret = dss_select(signal_pipe + 1, &rfds, NULL, tvp);
1442 if (FD_ISSET(signal_pipe, &rfds)) {
1443 ret = handle_signal();
1449 if (snapshot_removal_status == HS_PRE_SUCCESS) {
1455 if (snapshot_removal_status == HS_SUCCESS) {
1459 ret = try_to_free_disk_space();
1462 if (snapshot_removal_status != HS_READY) {
1463 stop_create_process();
1466 restart_create_process();
1467 switch (snapshot_creation_status) {
1469 if (!next_snapshot_is_due())
1473 case HS_PRE_RUNNING:
1475 case HS_POST_RUNNING:
1477 case HS_PRE_SUCCESS:
1478 if (!name_of_reference_snapshot) {
1479 free_rsync_argv(rsync_argv);
1480 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
1482 ret = create_snapshot(rsync_argv);
1486 case HS_NEEDS_RESTART:
1487 if (!next_snapshot_is_due())
1489 ret = create_snapshot(rsync_argv);
1502 static void exit_hook(int exit_code)
1504 const char *argv[3];
1507 argv[0] = OPT_STRING_VAL(DSS, EXIT_HOOK);
1508 argv[1] = dss_strerror(-exit_code);
1511 DSS_NOTICE_LOG(("executing %s %s\n", argv[0], argv[1]));
1512 dss_exec(&pid, argv[0], (char **)argv);
1515 static void lock_dss_or_die(void)
1517 char *config_file = get_config_file_name();
1518 int ret = lock_dss(config_file);
1522 DSS_EMERG_LOG(("failed to lock: %s\n", dss_strerror(-ret)));
1527 static int com_run(void)
1533 if (OPT_GIVEN(DSS, DRY_RUN)) {
1534 DSS_ERROR_LOG(("dry run not supported by this command\n"));
1537 config_file = get_config_file_name();
1538 ret = get_dss_pid(config_file, &pid);
1541 DSS_ERROR_LOG(("pid %d\n", (int)pid));
1542 return -E_ALREADY_RUNNING;
1544 if (OPT_GIVEN(RUN, DAEMON)) {
1547 logfile = open_log(OPT_STRING_VAL(RUN, LOGFILE));
1550 dump_dss_config("startup");
1551 ret = install_sighandler(SIGHUP);
1555 ret = write(fd, "\0", 1);
1557 DSS_ERROR_LOG(("write to daemon pipe returned %d\n",
1560 return -ERRNO_TO_DSS_ERROR(errno);
1564 ret = select_loop();
1565 if (ret >= 0) /* impossible */
1571 EXPORT_CMD_HANDLER(run);
1573 static int com_prune(void)
1576 struct snapshot_list sl;
1577 struct snapshot *victim;
1578 struct disk_space ds;
1582 ret = get_disk_space(".", &ds);
1585 log_disk_space(&ds);
1586 dss_get_snapshot_list(&sl);
1588 victim = find_outdated_snapshot(&sl);
1592 victim = find_redundant_snapshot(&sl);
1598 if (OPT_GIVEN(DSS, DRY_RUN)) {
1599 dss_msg("%s snapshot %s (interval = %i)\n",
1600 why, victim->name, victim->interval);
1604 pre_remove_hook(victim, why);
1605 if (snapshot_removal_status == HS_PRE_RUNNING) {
1606 ret = wait_for_remove_process();
1609 if (snapshot_removal_status != HS_PRE_SUCCESS)
1615 ret = wait_for_remove_process();
1618 if (snapshot_removal_status != HS_SUCCESS)
1621 if (snapshot_removal_status != HS_POST_RUNNING)
1623 ret = wait_for_remove_process();
1628 free_snapshot_list(&sl);
1631 EXPORT_CMD_HANDLER(prune);
1633 static int com_create(void)
1639 if (OPT_GIVEN(DSS, DRY_RUN)) {
1642 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
1643 for (i = 0; rsync_argv[i]; i++) {
1645 msg = make_message("%s%s%s", tmp? tmp : "",
1646 tmp? " " : "", rsync_argv[i]);
1649 free_rsync_argv(rsync_argv);
1650 dss_msg("%s\n", msg);
1656 ret = wait_for_process(create_pid, &status);
1659 ret = handle_pre_create_hook_exit(status);
1660 if (ret <= 0) /* error, or pre-create failed */
1663 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
1664 ret = create_snapshot(rsync_argv);
1667 ret = wait_for_process(create_pid, &status);
1670 ret = handle_rsync_exit(status);
1675 ret = wait_for_process(create_pid, &status);
1677 free_rsync_argv(rsync_argv);
1680 EXPORT_CMD_HANDLER(create);
1682 static int com_ls(void)
1685 struct snapshot_list sl;
1688 dss_get_snapshot_list(&sl);
1689 FOR_EACH_SNAPSHOT(s, i, &sl) {
1691 if (s->flags & SS_COMPLETE)
1692 d = (s->completion_time - s->creation_time) / 60;
1693 dss_msg("%u\t%s\t%3" PRId64 ":%02" PRId64 "\n", s->interval, s->name, d/60, d%60);
1695 free_snapshot_list(&sl);
1698 EXPORT_CMD_HANDLER(ls);
1700 static int setup_signal_handling(void)
1704 DSS_INFO_LOG(("setting up signal handlers\n"));
1705 signal_pipe = signal_init(); /* always successful */
1706 ret = install_sighandler(SIGINT);
1709 ret = install_sighandler(SIGTERM);
1712 return install_sighandler(SIGCHLD);
1715 static void handle_version_and_help(void)
1719 if (OPT_GIVEN(DSS, DETAILED_HELP))
1720 txt = lls_long_help(CMD_PTR(DSS));
1721 else if (OPT_GIVEN(DSS, HELP))
1722 txt = lls_short_help(CMD_PTR(DSS));
1723 else if (OPT_GIVEN(DSS, VERSION))
1724 txt = dss_strdup(VERSION_STRING);
1732 static void show_subcommand_summary(void)
1734 const struct lls_command *cmd;
1737 printf("Available subcommands:\n");
1738 for (i = 1; (cmd = lls_cmd(i, dss_suite)); i++) {
1739 const char *name = lls_command_name(cmd);
1740 const char *purpose = lls_purpose(cmd);
1741 printf("%-10s%s\n", name, purpose);
1746 int main(int argc, char **argv)
1749 const struct lls_command *cmd = CMD_PTR(DSS);
1750 char *errctx = NULL;
1751 unsigned num_inputs;
1752 const struct dss_user_data *ud = NULL;
1754 ret = lls_parse(argc, argv, cmd, &cmdline_lpr, &errctx);
1756 ret = lopsub_error(ret, &errctx);
1760 ret = parse_config_file(false /* no SIGHUP */, cmd);
1763 handle_version_and_help();
1764 num_inputs = lls_num_inputs(lpr);
1765 if (num_inputs == 0)
1766 show_subcommand_summary();
1767 ret = lls_lookup_subcmd(argv[argc - num_inputs], dss_suite, &errctx);
1769 ret = lopsub_error(ret, &errctx);
1772 cmd = lls_cmd(ret, dss_suite);
1773 ret = lls_parse(num_inputs, argv + argc - num_inputs, cmd,
1774 &cmdline_sublpr, &errctx);
1776 ret = lopsub_error(ret, &errctx);
1779 sublpr = cmdline_sublpr;
1780 ret = parse_config_file(false /* no SIGHUP */, cmd);
1783 ret = check_config(cmd);
1786 ret = setup_signal_handling();
1789 ud = lls_user_data(cmd);
1790 ret = ud->handler();
1795 DSS_ERROR_LOG(("%s\n", errctx));
1796 DSS_EMERG_LOG(("%s\n", dss_strerror(-ret)));
1799 lls_free_parse_result(lpr, CMD_PTR(DSS));
1800 if (lpr != cmdline_lpr)
1801 lls_free_parse_result(cmdline_lpr, CMD_PTR(DSS));
1802 lls_free_parse_result(sublpr, cmd);
1803 if (sublpr != cmdline_sublpr)
1804 lls_free_parse_result(cmdline_sublpr, cmd);
1805 exit(ret >= 0? EXIT_SUCCESS : EXIT_FAILURE);