1 /* SPDX-License-Identifier: GPL-2.0 */
24 #include "gcc-compat.h"
38 #define CMD_PTR(_cname) lls_cmd(LSG_DSS_CMD_ ## _cname, dss_suite)
39 #define OPT_RESULT(_cname, _oname) (lls_opt_result(\
40 LSG_DSS_ ## _cname ## _OPT_ ## _oname, (CMD_PTR(_cname) == CMD_PTR(DSS))? lpr : sublpr))
41 #define OPT_GIVEN(_cname, _oname) (lls_opt_given(OPT_RESULT(_cname, _oname)))
42 #define OPT_STRING_VAL(_cname, _oname) (lls_string_val(0, \
43 OPT_RESULT(_cname, _oname)))
44 #define OPT_UINT32_VAL(_cname, _oname) (lls_uint32_val(0, \
45 OPT_RESULT(_cname, _oname)))
47 struct dss_user_data {int (*handler)(void);};
48 #define EXPORT_CMD_HANDLER(_cmd) const struct dss_user_data \
49 lsg_dss_com_ ## _cmd ## _user_data = { \
50 .handler = com_ ## _cmd \
54 * Command line and active options. We need to keep a copy of the parsed
55 * command line options for the SIGHUP case where we merge the command line
56 * options and the new config file options.
58 static struct lls_parse_result *cmdline_lpr, *lpr;
60 /** Parsed subcommand options. */
61 static struct lls_parse_result *cmdline_sublpr, *sublpr;
62 /* The executing subcommand (NULL at startup). */
63 static const struct lls_command *subcmd;
64 /** Wether daemon_init() was called. */
65 static bool daemonized;
66 /** Non-NULL if we log to a file. */
68 /** The read end of the signal pipe */
69 static int signal_pipe;
70 /** Process id of current pre-create-hook/rsync/post-create-hook process. */
71 static pid_t create_pid;
72 /** Whether the pre-create-hook/rsync/post-create-hook is currently stopped. */
73 static int create_process_stopped;
74 /** How many times in a row the rsync command failed. */
75 static int num_consecutive_rsync_errors;
76 /** Process id of current pre-remove/rm/post-remove process. */
77 static pid_t remove_pid;
78 /** When the next snapshot is due. */
79 static int64_t next_snapshot_time;
80 /** When to try to remove something. */
81 static struct timeval next_removal_check;
82 /** Creation time of the snapshot currently being created. */
83 static int64_t current_snapshot_creation_time;
84 /** The snapshot currently being removed. */
85 struct snapshot *snapshot_currently_being_removed;
86 /** Needed by the post-create hook. */
87 static char *path_to_last_complete_snapshot;
88 static char *name_of_reference_snapshot;
89 /** \sa \ref snap.h for details. */
90 enum hook_status snapshot_creation_status;
91 /** \sa \ref snap.h for details. */
92 enum hook_status snapshot_removal_status;
96 static const char *hook_status_description[] = {HOOK_STATUS_ARRAY};
98 /* may be called with ds == NULL. */
99 static int disk_space_low(struct disk_space *ds)
101 struct disk_space ds_struct;
105 int ret = get_disk_space(".", &ds_struct);
110 val = OPT_UINT32_VAL(DSS, MIN_FREE_MB);
112 if (ds->free_mb < val)
114 val = OPT_UINT32_VAL(DSS, MIN_FREE_PERCENT);
116 if (ds->percent_free < val)
118 val = OPT_UINT32_VAL(DSS, MIN_FREE_PERCENT_INODES);
120 if (ds->percent_free_inodes < val)
125 static void dump_dss_config(const char *msg)
127 const char dash[] = "-----------------------------";
130 FILE *log = logfile? logfile : stderr;
131 struct disk_space ds;
132 int64_t now = get_current_time();
134 if (OPT_UINT32_VAL(DSS, LOGLEVEL) > INFO)
137 fprintf(log, "%s <%s config> %s\n", dash, msg, dash);
138 fprintf(log, "\n*** disk space ***\n\n");
139 ret = get_disk_space(".", &ds);
141 DSS_INFO_LOG(("disk space low: %s\n", disk_space_low(&ds)?
145 DSS_ERROR_LOG(("can not get free disk space: %s\n",
146 dss_strerror(-ret)));
148 /* we continue on errors from get_disk_space */
150 fprintf(log, "\n*** non-default options ***\n\n");
151 lopsub_dump = lls_dump_parse_result(lpr, CMD_PTR(DSS), true);
152 fprintf(log, "%s", lopsub_dump);
154 fprintf(log, "\n*** non-default options for \"run\" ***\n\n");
155 lopsub_dump = lls_dump_parse_result(lpr, CMD_PTR(RUN), true);
156 fprintf(log, "%s", lopsub_dump);
158 fprintf(log, "\n*** internal state ***\n\n");
162 "snapshot_currently_being_removed: %s\n"
163 "path_to_last_complete_snapshot: %s\n"
164 "reference_snapshot: %s\n"
165 "snapshot_creation_status: %s\n"
166 "snapshot_removal_status: %s\n"
167 "num_consecutive_rsync_errors: %d\n"
170 logfile? OPT_STRING_VAL(RUN, LOGFILE) : "stderr",
171 snapshot_currently_being_removed?
172 snapshot_currently_being_removed->name : "(none)",
173 path_to_last_complete_snapshot?
174 path_to_last_complete_snapshot : "(none)",
175 name_of_reference_snapshot?
176 name_of_reference_snapshot : "(none)",
177 hook_status_description[snapshot_creation_status],
178 hook_status_description[snapshot_removal_status],
179 num_consecutive_rsync_errors
183 "create_pid: %" PRId32 "\n"
184 "create process is %sstopped\n"
187 create_process_stopped? "" : "not "
190 fprintf(log, "remove_pid: %" PRId32 "\n", remove_pid);
191 if (next_snapshot_time != 0)
192 fprintf(log, "next snapshot due in %" PRId64 " seconds\n",
193 next_snapshot_time - now);
194 if (current_snapshot_creation_time != 0)
195 fprintf(log, "current_snapshot_creation_time: %"
196 PRId64 " (%" PRId64 " seconds ago)\n",
197 current_snapshot_creation_time,
198 now - current_snapshot_creation_time
200 if (next_removal_check.tv_sec != 0) {
201 fprintf(log, "next removal check: %llu (%llu seconds ago)\n",
202 (long long unsigned)next_removal_check.tv_sec,
203 now - (long long unsigned)next_removal_check.tv_sec
207 fprintf(log, "%s </%s config> %s\n", dash, msg, dash);
210 static int loglevel = -1;
211 static const char *location_file = NULL;
212 static int location_line = -1;
213 static const char *location_func = NULL;
215 void dss_log_set_params(int ll, const char *file, int line, const char *func)
218 location_file = file;
219 location_line = line;
220 location_func = func;
224 * The log function of dss.
226 * \param ll Loglevel.
227 * \param fml Usual format string.
229 * All DSS_XXX_LOG() macros use this function.
231 __printf_1_2 void dss_log(const char* fmt,...)
238 int lpr_ll = lpr? OPT_UINT32_VAL(DSS, LOGLEVEL) : WARNING;
240 if (loglevel < lpr_ll)
242 outfd = logfile? logfile : stderr;
243 if (subcmd == CMD_PTR(RUN)) {
246 strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
247 fprintf(outfd, "%s ", str);
249 fprintf(outfd, "%i: ", loglevel);
251 if (subcmd == CMD_PTR(RUN))
252 #ifdef DSS_NO_FUNC_NAMES
253 fprintf(outfd, "%s:%d: ", location_file, location_line);
255 fprintf(outfd, "%s: ", location_func);
258 vfprintf(outfd, fmt, argp);
263 * Print a message either to stdout or to the log file.
265 static __printf_1_2 void dss_msg(const char* fmt,...)
267 FILE *outfd = logfile? logfile : stdout;
270 vfprintf(outfd, fmt, argp);
274 static char *get_config_file_name(void)
276 char *home, *config_file;
278 if (OPT_GIVEN(DSS, CONFIG_FILE))
279 return dss_strdup(OPT_STRING_VAL(DSS, CONFIG_FILE));
280 home = get_homedir();
281 config_file = make_message("%s/.dssrc", home);
286 static int send_signal(int sig, bool wait)
289 char *config_file = get_config_file_name();
290 int ret = get_dss_pid(config_file, &pid);
297 if (OPT_GIVEN(DSS, DRY_RUN)) {
298 dss_msg("%d\n", (int)pid);
301 DSS_NOTICE_LOG(("sending signal %d to pid %d\n", sig, (int)pid));
302 ret = kill(pid, sig);
304 return -ERRNO_TO_DSS_ERROR(errno);
308 ts.tv_sec = ms / 1000;
309 ts.tv_nsec = (ms % 1000) * 1000 * 1000;
310 ret = nanosleep(&ts, NULL);
312 return -ERRNO_TO_DSS_ERROR(errno);
316 return -ERRNO_TO_DSS_ERROR(errno);
321 return -E_KILL_TIMEOUT;
325 const char * const name;
330 * The table below was taken 2016 from proc/sig.c of procps-3.2.8. Copyright
331 * 1998-2003 by Albert Cahalan, GPLv2.
333 static const struct signal_info signal_table[] = {
334 {"ABRT", SIGABRT}, /* IOT */
337 {"CHLD", SIGCHLD}, /* CLD */
346 {"POLL", SIGPOLL}, /* IO */
355 {"STKFLT", SIGSTKFLT},
358 {"SYS", SIGSYS}, /* UNUSED */
367 {"VTALRM", SIGVTALRM},
373 #define SIGNAL_TABLE_SIZE (sizeof(signal_table) / sizeof(signal_table[0]))
378 static int com_kill(void)
380 bool w_given = OPT_GIVEN(KILL, WAIT);
381 const char *arg = OPT_STRING_VAL(KILL, SIGNAL);
384 if (*arg >= '0' && *arg <= '9') {
386 ret = dss_atoi64(arg, &val);
389 if (val < 0 || val > SIGRTMAX)
390 return -ERRNO_TO_DSS_ERROR(EINVAL);
391 return send_signal(val, w_given);
393 if (strncasecmp(arg, "sig", 3) == 0)
395 if (strcasecmp(arg, "CLD") == 0)
396 return send_signal(SIGCHLD, w_given);
397 if (strcasecmp(arg, "IOT") == 0)
398 return send_signal(SIGABRT, w_given);
399 for (i = 0; i < SIGNAL_TABLE_SIZE; i++)
400 if (strcasecmp(arg, signal_table[i].name) == 0)
401 return send_signal(signal_table[i].num, w_given);
402 DSS_ERROR_LOG(("invalid sigspec: %s\n", arg));
403 return -ERRNO_TO_DSS_ERROR(EINVAL);
405 EXPORT_CMD_HANDLER(kill);
407 static void dss_get_snapshot_list(struct snapshot_list *sl)
409 get_snapshot_list(sl, OPT_UINT32_VAL(DSS, UNIT_INTERVAL),
410 OPT_UINT32_VAL(DSS, NUM_INTERVALS));
413 static int64_t compute_next_snapshot_time(void)
415 int64_t x = 0, now = get_current_time(), unit_interval
416 = 24 * 3600 * OPT_UINT32_VAL(DSS, UNIT_INTERVAL), ret,
417 last_completion_time;
418 unsigned wanted = desired_number_of_snapshots(0,
419 OPT_UINT32_VAL(DSS, NUM_INTERVALS)),
422 struct snapshot *s = NULL;
423 struct snapshot_list sl;
425 dss_get_snapshot_list(&sl);
426 FOR_EACH_SNAPSHOT(s, i, &sl) {
427 if (!(s->flags & SS_COMPLETE))
430 x += s->completion_time - s->creation_time;
431 last_completion_time = s->completion_time;
436 if (num_complete == 0)
438 x /= num_complete; /* avg time to create one snapshot */
439 if (unit_interval < x * wanted) /* oops, no sleep at all */
441 ret = last_completion_time + unit_interval / wanted - x;
443 free_snapshot_list(&sl);
447 static inline void invalidate_next_snapshot_time(void)
449 next_snapshot_time = 0;
452 static inline int next_snapshot_time_is_valid(void)
454 return next_snapshot_time != 0;
457 static int next_snapshot_is_due(void)
459 int64_t now = get_current_time();
461 if (!next_snapshot_time_is_valid())
462 next_snapshot_time = compute_next_snapshot_time();
463 if (next_snapshot_time <= now) {
464 DSS_DEBUG_LOG(("next snapshot: now\n"));
467 DSS_DEBUG_LOG(("next snapshot due in %" PRId64 " seconds\n",
468 next_snapshot_time - now));
472 static void pre_create_hook(void)
474 assert(snapshot_creation_status == HS_READY);
475 /* make sure that the next snapshot time will be recomputed */
476 invalidate_next_snapshot_time();
477 DSS_DEBUG_LOG(("executing %s\n", OPT_STRING_VAL(DSS, PRE_CREATE_HOOK)));
478 dss_exec_cmdline_pid(&create_pid, OPT_STRING_VAL(DSS, PRE_CREATE_HOOK));
479 snapshot_creation_status = HS_PRE_RUNNING;
482 static void pre_remove_hook(struct snapshot *s, const char *why)
488 DSS_DEBUG_LOG(("%s snapshot %s\n", why, s->name));
489 assert(snapshot_removal_status == HS_READY);
490 assert(remove_pid == 0);
491 assert(!snapshot_currently_being_removed);
493 snapshot_currently_being_removed = dss_malloc(sizeof(struct snapshot));
494 *snapshot_currently_being_removed = *s;
495 snapshot_currently_being_removed->name = dss_strdup(s->name);
497 cmd = make_message("%s %s/%s", OPT_STRING_VAL(DSS, PRE_REMOVE_HOOK),
498 OPT_STRING_VAL(DSS, DEST_DIR), s->name);
499 DSS_DEBUG_LOG(("executing %s\n", cmd));
500 dss_exec_cmdline_pid(&remove_pid, cmd);
502 snapshot_removal_status = HS_PRE_RUNNING;
505 static int exec_rm(void)
507 struct snapshot *s = snapshot_currently_being_removed;
508 char *new_name = being_deleted_name(s);
517 assert(snapshot_removal_status == HS_PRE_SUCCESS);
518 assert(remove_pid == 0);
520 DSS_NOTICE_LOG(("removing %s (interval = %i)\n", s->name, s->interval));
521 ret = dss_rename(s->name, new_name);
524 dss_exec(&remove_pid, argv[0], argv);
525 snapshot_removal_status = HS_RUNNING;
531 static int snapshot_is_being_created(struct snapshot *s)
533 return s->creation_time == current_snapshot_creation_time;
536 static struct snapshot *find_orphaned_snapshot(struct snapshot_list *sl)
541 DSS_DEBUG_LOG(("looking for old incomplete snapshots\n"));
542 FOR_EACH_SNAPSHOT(s, i, sl) {
543 if (snapshot_is_being_created(s))
546 * We know that no rm is currently running, so if s is marked
547 * as being deleted, a previously started rm must have failed.
549 if (s->flags & SS_BEING_DELETED)
552 if (s->flags & SS_COMPLETE) /* good snapshot */
555 * This snapshot is incomplete and it is not the snapshot
556 * currently being created. However, we must not remove it if
557 * rsync is about to be restarted. As only the newest snapshot
558 * can be restarted, this snapshot is orphaned if it is not the
559 * newest snapshot or if we are not about to restart rsync.
561 if (get_newest_snapshot(sl) != s)
563 if (snapshot_creation_status != HS_NEEDS_RESTART)
566 /* no orphaned snapshots */
570 static int is_reference_snapshot(struct snapshot *s)
572 if (!name_of_reference_snapshot)
574 return strcmp(s->name, name_of_reference_snapshot)? 0 : 1;
578 * return: 0: no redundant snapshots, 1: rm process started, negative: error
580 static struct snapshot *find_redundant_snapshot(struct snapshot_list *sl)
584 unsigned missing = 0;
585 uint32_t N = OPT_UINT32_VAL(DSS, NUM_INTERVALS);
587 DSS_DEBUG_LOG(("looking for intervals containing too many snapshots\n"));
588 for (interval = N - 1; interval >= 0; interval--) {
589 unsigned keep = desired_number_of_snapshots(interval, N);
590 unsigned num = sl->interval_count[interval];
591 struct snapshot *victim = NULL, *prev = NULL;
592 int64_t score = LONG_MAX;
595 missing += keep - num;
596 if (keep + missing >= num)
598 /* redundant snapshot in this interval, pick snapshot with lowest score */
599 FOR_EACH_SNAPSHOT(s, i, sl) {
602 if (snapshot_is_being_created(s))
604 if (is_reference_snapshot(s))
606 if (s->interval > interval) {
610 if (s->interval < interval)
618 /* check if s is a better victim */
619 this_score = s->creation_time - prev->creation_time;
620 assert(this_score >= 0);
621 if (this_score < score) {
633 static struct snapshot *find_outdated_snapshot(struct snapshot_list *sl)
638 DSS_DEBUG_LOG(("looking for snapshots belonging to intervals >= %d\n",
639 OPT_UINT32_VAL(DSS, NUM_INTERVALS)));
640 FOR_EACH_SNAPSHOT(s, i, sl) {
641 if (snapshot_is_being_created(s))
643 if (is_reference_snapshot(s))
645 if (s->interval < OPT_UINT32_VAL(DSS, NUM_INTERVALS))
652 static struct snapshot *find_oldest_removable_snapshot(struct snapshot_list *sl)
655 struct snapshot *s, *ref = NULL;
657 num_complete = num_complete_snapshots(sl);
658 if (num_complete <= OPT_UINT32_VAL(DSS, MIN_COMPLETE))
660 FOR_EACH_SNAPSHOT(s, i, sl) {
661 if (snapshot_is_being_created(s))
663 if (is_reference_snapshot(s)) { /* avoid this one */
667 DSS_INFO_LOG(("oldest removable snapshot: %s\n", s->name));
671 DSS_WARNING_LOG(("removing reference snapshot %s\n", ref->name));
675 static int rename_incomplete_snapshot(int64_t start)
682 * We don't want the dss_rename() below to fail with EEXIST because the
683 * last complete snapshot was created (and completed) in the same
684 * second as this one.
686 while ((now = get_current_time()) == start)
688 free(path_to_last_complete_snapshot);
689 ret = complete_name(start, now, &path_to_last_complete_snapshot);
692 old_name = incomplete_name(start);
693 ret = dss_rename(old_name, path_to_last_complete_snapshot);
695 DSS_NOTICE_LOG(("%s -> %s\n", old_name,
696 path_to_last_complete_snapshot));
701 static int try_to_free_disk_space(void)
704 struct snapshot_list sl;
705 struct snapshot *victim;
710 ret = disk_space_low(NULL);
713 low_disk_space = ret;
714 gettimeofday(&now, NULL);
715 if (tv_diff(&next_removal_check, &now, NULL) > 0)
717 if (!low_disk_space) {
718 if (OPT_GIVEN(DSS, KEEP_REDUNDANT))
720 if (snapshot_creation_status != HS_READY)
722 if (next_snapshot_is_due())
726 * Idle and --keep_redundant not given, or low disk space. Look at
727 * existing snapshots.
729 dss_get_snapshot_list(&sl);
732 * Don't remove anything if there is free space and we have fewer
733 * snapshots than configured, plus one. This way there is always one
734 * snapshot that can be recycled.
736 if (!low_disk_space && sl.num_snapshots <=
737 1 << OPT_UINT32_VAL(DSS, NUM_INTERVALS))
740 victim = find_outdated_snapshot(&sl);
744 victim = find_redundant_snapshot(&sl);
748 victim = find_orphaned_snapshot(&sl);
751 /* try harder only if disk space is low */
754 DSS_WARNING_LOG(("disk space low and nothing obvious to remove\n"));
756 victim = find_oldest_removable_snapshot(&sl);
759 DSS_CRIT_LOG(("uhuhu: disk space low and nothing to remove\n"));
760 ret = -ERRNO_TO_DSS_ERROR(ENOSPC);
763 pre_remove_hook(victim, why);
765 free_snapshot_list(&sl);
769 static void post_create_hook(void)
771 char *cmd = make_message("%s %s/%s",
772 OPT_STRING_VAL(DSS, POST_CREATE_HOOK),
773 OPT_STRING_VAL(DSS, DEST_DIR), path_to_last_complete_snapshot);
774 DSS_NOTICE_LOG(("executing %s\n", cmd));
775 dss_exec_cmdline_pid(&create_pid, cmd);
777 snapshot_creation_status = HS_POST_RUNNING;
780 static void post_remove_hook(void)
783 struct snapshot *s = snapshot_currently_being_removed;
787 cmd = make_message("%s %s/%s", OPT_STRING_VAL(DSS, POST_REMOVE_HOOK),
788 OPT_STRING_VAL(DSS, DEST_DIR), s->name);
789 DSS_NOTICE_LOG(("executing %s\n", cmd));
790 dss_exec_cmdline_pid(&remove_pid, cmd);
792 snapshot_removal_status = HS_POST_RUNNING;
795 static void dss_kill(pid_t pid, int sig, const char *msg)
797 const char *signame, *process_name;
802 case SIGTERM: signame = "TERM"; break;
803 case SIGSTOP: signame = "STOP"; break;
804 case SIGCONT: signame = "CONT"; break;
805 default: signame = "????";
808 if (pid == create_pid)
809 process_name = "create";
810 else if (pid == remove_pid)
811 process_name = "remove";
812 else process_name = "??????";
815 DSS_INFO_LOG(("%s\n", msg));
816 DSS_DEBUG_LOG(("sending signal %d (%s) to pid %d (%s process)\n",
817 sig, signame, (int)pid, process_name));
818 if (kill(pid, sig) >= 0)
820 DSS_INFO_LOG(("failed to send signal %d (%s) to pid %d (%s process)\n",
821 sig, signame, (int)pid, process_name));
824 static void stop_create_process(void)
826 if (create_process_stopped)
828 dss_kill(create_pid, SIGSTOP, "suspending create process");
829 create_process_stopped = 1;
832 static void restart_create_process(void)
834 if (!create_process_stopped)
836 dss_kill(create_pid, SIGCONT, "resuming create process");
837 create_process_stopped = 0;
841 * Print a log message about the exit status of a child.
843 static void log_termination_msg(pid_t pid, int status)
845 if (WIFEXITED(status))
846 DSS_INFO_LOG(("child %i exited. Exit status: %i\n", (int)pid,
847 WEXITSTATUS(status)));
848 else if (WIFSIGNALED(status))
849 DSS_NOTICE_LOG(("child %i was killed by signal %i\n", (int)pid,
852 DSS_WARNING_LOG(("child %i terminated abormally\n", (int)pid));
855 static int wait_for_process(pid_t pid, int *status)
859 DSS_DEBUG_LOG(("Waiting for process %d to terminate\n", (int)pid));
864 FD_SET(signal_pipe, &rfds);
865 ret = dss_select(signal_pipe + 1, &rfds, NULL, NULL);
871 if (ret == SIGCHLD) {
872 ret = waitpid(pid, status, 0);
875 if (errno != EINTR) { /* error */
876 ret = -ERRNO_TO_DSS_ERROR(errno);
880 /* SIGINT or SIGTERM */
881 dss_kill(pid, SIGTERM, "killing child process");
884 DSS_ERROR_LOG(("failed to wait for process %d\n", (int)pid));
886 log_termination_msg(pid, *status);
890 static void handle_pre_remove_exit(int status)
892 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
893 snapshot_removal_status = HS_READY;
894 gettimeofday(&next_removal_check, NULL);
895 next_removal_check.tv_sec += 60;
898 snapshot_removal_status = HS_PRE_SUCCESS;
901 static int handle_rm_exit(int status)
903 if (!WIFEXITED(status)) {
904 snapshot_removal_status = HS_READY;
905 return -E_INVOLUNTARY_EXIT;
907 if (WEXITSTATUS(status)) {
908 snapshot_removal_status = HS_READY;
909 return -E_BAD_EXIT_CODE;
911 snapshot_removal_status = HS_SUCCESS;
915 static void handle_post_remove_exit(void)
917 snapshot_removal_status = HS_READY;
920 static int handle_remove_exit(int status)
923 struct snapshot *s = snapshot_currently_being_removed;
926 switch (snapshot_removal_status) {
928 handle_pre_remove_exit(status);
932 ret = handle_rm_exit(status);
934 case HS_POST_RUNNING:
935 handle_post_remove_exit();
941 if (snapshot_removal_status == HS_READY) {
944 snapshot_currently_being_removed = NULL;
950 static int wait_for_remove_process(void)
956 snapshot_removal_status == HS_PRE_RUNNING ||
957 snapshot_removal_status == HS_RUNNING ||
958 snapshot_removal_status == HS_POST_RUNNING
960 ret = wait_for_process(remove_pid, &status);
963 return handle_remove_exit(status);
966 static int handle_rsync_exit(int status)
970 if (!WIFEXITED(status)) {
971 DSS_ERROR_LOG(("rsync process %d died involuntary\n", (int)create_pid));
972 ret = -E_INVOLUNTARY_EXIT;
973 snapshot_creation_status = HS_READY;
976 es = WEXITSTATUS(status);
978 * Restart rsync on non-fatal errors:
979 * 24: Partial transfer due to vanished source files
981 if (es != 0 && es != 24) {
982 DSS_WARNING_LOG(("rsync exit code %d, error count %d\n",
983 es, ++num_consecutive_rsync_errors));
984 if (!logfile) { /* called by com_run() */
985 ret = -E_BAD_EXIT_CODE;
988 if (num_consecutive_rsync_errors >
989 OPT_UINT32_VAL(RUN, MAX_RSYNC_ERRORS)) {
990 ret = -E_TOO_MANY_RSYNC_ERRORS;
991 snapshot_creation_status = HS_READY;
994 DSS_WARNING_LOG(("restarting rsync process\n"));
995 snapshot_creation_status = HS_NEEDS_RESTART;
996 next_snapshot_time = get_current_time() + 60;
1000 num_consecutive_rsync_errors = 0;
1001 ret = rename_incomplete_snapshot(current_snapshot_creation_time);
1004 snapshot_creation_status = HS_SUCCESS;
1005 free(name_of_reference_snapshot);
1006 name_of_reference_snapshot = NULL;
1008 create_process_stopped = 0;
1012 static int handle_pre_create_hook_exit(int status)
1015 static int warn_count;
1017 if (!WIFEXITED(status)) {
1018 snapshot_creation_status = HS_READY;
1019 ret = -E_INVOLUNTARY_EXIT;
1022 es = WEXITSTATUS(status);
1024 if (!warn_count--) {
1025 DSS_NOTICE_LOG(("pre_create_hook %s returned %d\n",
1026 OPT_STRING_VAL(DSS, PRE_CREATE_HOOK), es));
1027 DSS_NOTICE_LOG(("deferring snapshot creation...\n"));
1028 warn_count = 60; /* warn only once per hour */
1030 next_snapshot_time = get_current_time() + 60;
1031 snapshot_creation_status = HS_READY;
1036 snapshot_creation_status = HS_PRE_SUCCESS;
1042 static int handle_sigchld(void)
1045 int status, ret = reap_child(&pid, &status);
1050 if (pid == create_pid) {
1051 switch (snapshot_creation_status) {
1052 case HS_PRE_RUNNING:
1053 ret = handle_pre_create_hook_exit(status);
1056 ret = handle_rsync_exit(status);
1058 case HS_POST_RUNNING:
1059 snapshot_creation_status = HS_READY;
1063 DSS_EMERG_LOG(("BUG: create can't die in status %d\n",
1064 snapshot_creation_status));
1070 if (pid == remove_pid) {
1071 ret = handle_remove_exit(status);
1076 DSS_EMERG_LOG(("BUG: unknown process %d died\n", (int)pid));
1080 /* also checks if . is a mountpoint, if --mountpoint was given */
1081 static int change_to_dest_dir(void)
1084 const char *dd = OPT_STRING_VAL(DSS, DEST_DIR);
1085 struct stat dot, dotdot;
1087 DSS_INFO_LOG(("changing cwd to %s\n", dd));
1088 if (chdir(dd) < 0) {
1089 ret = -ERRNO_TO_DSS_ERROR(errno);
1090 DSS_ERROR_LOG(("could not change cwd to %s\n", dd));
1093 if (!OPT_GIVEN(DSS, MOUNTPOINT))
1095 if (stat(".", &dot) < 0) {
1096 ret = -ERRNO_TO_DSS_ERROR(errno);
1097 DSS_ERROR_LOG(("could not stat .\n"));
1100 if (stat("..", &dotdot) < 0) {
1101 ret = -ERRNO_TO_DSS_ERROR(errno);
1102 DSS_ERROR_LOG(("could not stat ..\n"));
1105 if (dot.st_dev == dotdot.st_dev && dot.st_ino != dotdot.st_ino) {
1106 DSS_ERROR_LOG(("mountpoint check failed for %s\n", dd));
1107 return -E_MOUNTPOINT;
1112 static int check_config(void)
1115 uint32_t unit_interval = OPT_UINT32_VAL(DSS, UNIT_INTERVAL);
1116 uint32_t num_intervals = OPT_UINT32_VAL(DSS, NUM_INTERVALS);
1118 if (unit_interval == 0) {
1119 DSS_ERROR_LOG(("bad unit interval: %i\n", unit_interval));
1120 return -E_INVALID_NUMBER;
1122 DSS_DEBUG_LOG(("unit interval: %i day(s)\n", unit_interval));
1124 if (num_intervals == 0 || num_intervals > 30) {
1125 DSS_ERROR_LOG(("bad number of intervals: %i\n", num_intervals));
1126 return -E_INVALID_NUMBER;
1128 if (subcmd == CMD_PTR(RUN) || subcmd == CMD_PTR(CREATE))
1129 if (!OPT_GIVEN(DSS, SOURCE_DIR)) {
1130 DSS_ERROR_LOG(("--source-dir required\n"));
1133 if (subcmd == CMD_PTR(RUN) || subcmd == CMD_PTR(CREATE)
1134 || subcmd == CMD_PTR(LS) || subcmd == CMD_PTR(PRUNE)) {
1135 if (!OPT_GIVEN(DSS, DEST_DIR)) {
1136 DSS_ERROR_LOG(("--dest-dir required\n"));
1139 ret = change_to_dest_dir();
1143 DSS_DEBUG_LOG(("number of intervals: %i\n", num_intervals));
1147 static int lopsub_error(int lopsub_ret, char **errctx)
1149 const char *msg = lls_strerror(-lopsub_ret);
1151 DSS_ERROR_LOG(("%s: %s\n", *errctx, msg));
1153 DSS_ERROR_LOG(("%s\n", msg));
1159 static int parse_config_file(bool sighup, const struct lls_command *cmd)
1162 char *config_file = get_config_file_name();
1163 struct stat statbuf;
1167 char **cf_argv, *errctx = NULL;
1168 struct lls_parse_result *cf_lpr, *merged_lpr, *clpr;
1169 const char *subcmd_name;
1171 ret = open(config_file, O_RDONLY);
1173 if (errno != ENOENT || OPT_GIVEN(DSS, CONFIG_FILE)) {
1174 ret = -ERRNO_TO_DSS_ERROR(errno);
1175 DSS_ERROR_LOG(("config file %s can not be opened\n",
1179 /* no config file -- nothing to do */
1184 ret = fstat(fd, &statbuf);
1186 ret = -ERRNO_TO_DSS_ERROR(errno);
1187 DSS_ERROR_LOG(("failed to stat config file %s\n", config_file));
1190 sz = statbuf.st_size;
1191 if (sz == 0) { /* config file is empty -- nothing to do */
1195 map = mmap(NULL, sz, PROT_READ, MAP_PRIVATE, fd, 0);
1196 if (map == MAP_FAILED) {
1197 ret = -ERRNO_TO_DSS_ERROR(errno);
1198 DSS_ERROR_LOG(("failed to mmap config file %s\n",
1202 if (cmd == CMD_PTR(DSS))
1205 subcmd_name = lls_command_name(cmd);
1206 ret = lls_convert_config(map, sz, subcmd_name, &cf_argv, &errctx);
1209 DSS_ERROR_LOG(("failed to convert config file %s\n",
1211 ret = lopsub_error(ret, &errctx);
1215 ret = lls_parse(cf_argc, cf_argv, cmd, &cf_lpr, &errctx);
1216 lls_free_argv(cf_argv);
1218 ret = lopsub_error(ret, &errctx);
1221 clpr = cmd == CMD_PTR(DSS)? cmdline_lpr : cmdline_sublpr;
1222 if (sighup) /* config file overrides command line */
1223 ret = lls_merge(cf_lpr, clpr, cmd, &merged_lpr, &errctx);
1224 else /* command line options overrride config file options */
1225 ret = lls_merge(clpr, cf_lpr, cmd, &merged_lpr, &errctx);
1226 lls_free_parse_result(cf_lpr, cmd);
1228 ret = lopsub_error(ret, &errctx);
1234 DSS_DEBUG_LOG(("loglevel: %d\n", OPT_UINT32_VAL(DSS, LOGLEVEL)));
1235 if (cmd != CMD_PTR(DSS)) {
1237 if (sublpr != cmdline_sublpr)
1238 lls_free_parse_result(sublpr, cmd);
1239 sublpr = merged_lpr;
1241 sublpr = cmdline_sublpr;
1244 if (lpr != cmdline_lpr)
1245 lls_free_parse_result(lpr, cmd);
1256 DSS_EMERG_LOG(("%s\n", dss_strerror(-ret)));
1260 static int handle_sighup(void)
1264 DSS_NOTICE_LOG(("SIGHUP, re-reading config\n"));
1265 dump_dss_config("old");
1266 ret = parse_config_file(true /* SIGHUP */, CMD_PTR(DSS));
1269 ret = parse_config_file(true /* SIGHUP */, CMD_PTR(RUN));
1272 ret = check_config();
1277 if (OPT_GIVEN(RUN, DAEMON) || daemonized) {
1278 logfile = open_log(OPT_STRING_VAL(RUN, LOGFILE));
1279 log_welcome(OPT_UINT32_VAL(DSS, LOGLEVEL));
1282 dump_dss_config("reloaded");
1283 invalidate_next_snapshot_time();
1287 static void kill_children(void)
1289 restart_create_process();
1290 dss_kill(create_pid, SIGTERM, NULL);
1291 dss_kill(remove_pid, SIGTERM, NULL);
1294 static int handle_signal(void)
1296 int sig, ret = next_signal();
1306 ret = handle_sighup();
1309 ret = handle_sigchld();
1314 DSS_ERROR_LOG(("%s\n", dss_strerror(-ret)));
1319 * We can not use rsync locally if the local user is different from the remote
1320 * user or if the src dir is not on the local host (or both).
1322 static int use_rsync_locally(char *logname)
1324 const char *h = OPT_STRING_VAL(DSS, REMOTE_HOST);
1326 if (strcmp(h, "localhost") && strcmp(h, "127.0.0.1"))
1328 if (OPT_GIVEN(DSS, REMOTE_USER) &&
1329 strcmp(OPT_STRING_VAL(DSS, REMOTE_USER), logname))
1334 static int rename_resume_snap(int64_t creation_time)
1336 struct snapshot_list sl;
1337 struct snapshot *s = NULL;
1338 char *new_name = incomplete_name(creation_time);
1342 sl.num_snapshots = 0;
1345 dss_get_snapshot_list(&sl);
1347 * Snapshot recycling: We first look at the newest snapshot. If this
1348 * snapshot happens to be incomplete, the last rsync process was
1349 * aborted and we reuse this one. Otherwise we look at snapshots which
1350 * could be removed (outdated and redundant snapshots) as candidates
1351 * for recycling. If no outdated/redundant snapshot exists, we check if
1352 * there is an orphaned snapshot, which likely is useless anyway.
1354 * Only if no existing snapshot is suitable for recycling, we bite the
1355 * bullet and create a new one.
1357 s = get_newest_snapshot(&sl);
1358 if (!s) /* no snapshots at all */
1360 /* re-use last snapshot if it is incomplete */
1362 if ((s->flags & SS_COMPLETE) == 0)
1365 s = find_outdated_snapshot(&sl);
1369 s = find_redundant_snapshot(&sl);
1373 s = find_orphaned_snapshot(&sl);
1376 DSS_NOTICE_LOG(("recycling %s snapshot %s\n", why, s->name));
1377 ret = dss_rename(s->name, new_name);
1380 DSS_NOTICE_LOG(("creating %s\n", new_name));
1382 free_snapshot_list(&sl);
1386 static void create_rsync_argv(char ***argv, int64_t *num)
1390 struct snapshot_list sl;
1393 dss_get_snapshot_list(&sl);
1394 assert(!name_of_reference_snapshot);
1395 name_of_reference_snapshot = name_of_newest_complete_snapshot(&sl);
1396 free_snapshot_list(&sl);
1399 * We specify up to 6 arguments, one argument per given rsync option
1400 * and one argument per given source dir. We also need space for the
1401 * terminating NULL pointer.
1403 N = OPT_GIVEN(DSS, RSYNC_OPTION) + OPT_GIVEN(DSS, SOURCE_DIR);
1404 *argv = dss_malloc((7 + N) * sizeof(char *));
1405 (*argv)[i++] = dss_strdup("rsync");
1406 (*argv)[i++] = dss_strdup("-a");
1407 (*argv)[i++] = dss_strdup("--delete");
1409 srandom((unsigned)time(NULL)); /* no need to be fancy here */
1412 if (1000 * (random() / (RAND_MAX + 1.0)) < OPT_UINT32_VAL(DSS, CHECKSUM)) {
1413 DSS_NOTICE_LOG(("adding --checksum to rsync options\n"));
1414 (*argv)[i++] = dss_strdup("--checksum");
1416 for (j = 0; j < OPT_GIVEN(DSS, RSYNC_OPTION); j++)
1417 (*argv)[i++] = dss_strdup(lls_string_val(j,
1418 OPT_RESULT(DSS, RSYNC_OPTION)));
1419 if (name_of_reference_snapshot) {
1420 DSS_INFO_LOG(("using %s as reference\n", name_of_reference_snapshot));
1421 (*argv)[i++] = make_message("--link-dest=../%s",
1422 name_of_reference_snapshot);
1424 DSS_INFO_LOG(("no suitable reference snapshot found\n"));
1425 logname = dss_logname();
1426 if (use_rsync_locally(logname)) {
1427 for (j = 0; j < OPT_GIVEN(DSS, SOURCE_DIR); j++)
1428 (*argv)[i++] = dss_strdup(lls_string_val(j,
1429 OPT_RESULT(DSS, SOURCE_DIR)));
1432 * dss-1.0 and earlier did not support multiple source
1433 * directories. These versions appended a slash to the end of
1434 * the source directory to make sure that only the contents of
1435 * the single source directory, but not the directory itself,
1436 * are copied to the destination. For multiple source
1437 * directories, however, this is not a good idea because the
1438 * source directories may well contain identical file names,
1439 * which would then be copied to the same location on the
1440 * destination, overwriting each other. Moreover, we want the
1441 * directory on the destination match the source. To preserve
1442 * the old behaviour, we thus have to special-case N=1.
1444 for (j = 0; j < OPT_GIVEN(DSS, SOURCE_DIR); j++) {
1445 (*argv)[i++] = make_message("%s@%s:%s%s",
1446 OPT_GIVEN(DSS, REMOTE_USER)?
1447 OPT_STRING_VAL(DSS, REMOTE_USER) : logname,
1448 OPT_STRING_VAL(DSS, REMOTE_HOST),
1449 lls_string_val(j, OPT_RESULT(DSS, SOURCE_DIR)),
1455 *num = get_current_time();
1456 (*argv)[i++] = incomplete_name(*num);
1457 (*argv)[i++] = NULL;
1458 for (j = 0; j < i; j++)
1459 DSS_DEBUG_LOG(("argv[%d] = %s\n", j, (*argv)[j]));
1462 static void free_rsync_argv(char **argv)
1468 for (i = 0; argv[i]; i++)
1473 static int create_snapshot(char **argv)
1478 ret = rename_resume_snap(current_snapshot_creation_time);
1481 dss_exec(&create_pid, argv[0], argv);
1482 snapshot_creation_status = HS_RUNNING;
1486 static int select_loop(void)
1489 /* check every 60 seconds for free disk space */
1491 char **rsync_argv = NULL;
1495 struct timeval *tvp;
1498 tvp = NULL; /* sleep until rm hook/process dies */
1499 else { /* sleep one minute */
1505 FD_SET(signal_pipe, &rfds);
1506 ret = dss_select(signal_pipe + 1, &rfds, NULL, tvp);
1509 if (FD_ISSET(signal_pipe, &rfds)) {
1510 ret = handle_signal();
1516 if (snapshot_removal_status == HS_PRE_SUCCESS) {
1522 if (snapshot_removal_status == HS_SUCCESS) {
1526 ret = try_to_free_disk_space();
1529 if (snapshot_removal_status != HS_READY) {
1530 stop_create_process();
1533 restart_create_process();
1534 switch (snapshot_creation_status) {
1536 if (!next_snapshot_is_due())
1540 case HS_PRE_RUNNING:
1542 case HS_POST_RUNNING:
1544 case HS_PRE_SUCCESS:
1545 if (!name_of_reference_snapshot) {
1546 free_rsync_argv(rsync_argv);
1547 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
1549 ret = create_snapshot(rsync_argv);
1553 case HS_NEEDS_RESTART:
1554 if (!next_snapshot_is_due())
1556 ret = create_snapshot(rsync_argv);
1569 static void exit_hook(int exit_code)
1572 char **argv, *tmp = dss_strdup(OPT_STRING_VAL(DSS, EXIT_HOOK));
1573 unsigned n = split_args(tmp, &argv, " \t");
1576 argv = dss_realloc(argv, (n + 1) * sizeof(char *));
1577 argv[n - 1] = dss_strdup(dss_strerror(-exit_code));
1579 dss_exec(&pid, argv[0], argv);
1585 static void lock_dss_or_die(void)
1587 char *config_file = get_config_file_name();
1588 int ret = lock_dss(config_file);
1592 DSS_EMERG_LOG(("failed to lock: %s\n", dss_strerror(-ret)));
1597 static int com_run(void)
1603 if (OPT_GIVEN(DSS, DRY_RUN)) {
1604 DSS_ERROR_LOG(("dry run not supported by this command\n"));
1607 config_file = get_config_file_name();
1608 ret = get_dss_pid(config_file, &pid);
1611 DSS_ERROR_LOG(("pid %d\n", (int)pid));
1612 return -E_ALREADY_RUNNING;
1614 if (OPT_GIVEN(RUN, DAEMON)) {
1617 logfile = open_log(OPT_STRING_VAL(RUN, LOGFILE));
1620 dump_dss_config("startup");
1621 ret = install_sighandler(SIGHUP);
1625 ret = write(fd, "\0", 1);
1627 DSS_ERROR_LOG(("write to daemon pipe returned %d\n",
1630 return -ERRNO_TO_DSS_ERROR(errno);
1634 ret = select_loop();
1635 if (ret >= 0) /* impossible */
1639 while (wait(NULL) >= 0 || errno != ECHILD)
1640 ; /* still have children to wait for */
1643 EXPORT_CMD_HANDLER(run);
1645 static int com_prune(void)
1648 struct snapshot_list sl;
1649 struct snapshot *victim;
1650 struct disk_space ds;
1654 ret = get_disk_space(".", &ds);
1657 log_disk_space(&ds);
1658 dss_get_snapshot_list(&sl);
1660 victim = find_outdated_snapshot(&sl);
1664 victim = find_redundant_snapshot(&sl);
1670 if (OPT_GIVEN(DSS, DRY_RUN)) {
1671 dss_msg("%s snapshot %s (interval = %i)\n",
1672 why, victim->name, victim->interval);
1676 pre_remove_hook(victim, why);
1677 if (snapshot_removal_status == HS_PRE_RUNNING) {
1678 ret = wait_for_remove_process();
1681 if (snapshot_removal_status != HS_PRE_SUCCESS)
1687 ret = wait_for_remove_process();
1690 if (snapshot_removal_status != HS_SUCCESS)
1693 if (snapshot_removal_status != HS_POST_RUNNING)
1695 ret = wait_for_remove_process();
1700 free_snapshot_list(&sl);
1703 EXPORT_CMD_HANDLER(prune);
1705 static int com_create(void)
1711 if (OPT_GIVEN(DSS, DRY_RUN)) {
1714 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
1715 for (i = 0; rsync_argv[i]; i++) {
1717 msg = make_message("%s%s%s", tmp? tmp : "",
1718 tmp? " " : "", rsync_argv[i]);
1721 free_rsync_argv(rsync_argv);
1722 dss_msg("%s\n", msg);
1728 ret = wait_for_process(create_pid, &status);
1731 ret = handle_pre_create_hook_exit(status);
1732 if (ret <= 0) /* error, or pre-create failed */
1735 create_rsync_argv(&rsync_argv, ¤t_snapshot_creation_time);
1736 ret = create_snapshot(rsync_argv);
1739 ret = wait_for_process(create_pid, &status);
1742 ret = handle_rsync_exit(status);
1747 ret = wait_for_process(create_pid, &status);
1749 free_rsync_argv(rsync_argv);
1752 EXPORT_CMD_HANDLER(create);
1754 static int com_ls(void)
1757 struct snapshot_list sl;
1759 int64_t now = get_current_time();
1761 dss_get_snapshot_list(&sl);
1762 FOR_EACH_SNAPSHOT(s, i, &sl) {
1764 if (s->flags & SS_COMPLETE)
1765 d = (s->completion_time - s->creation_time) / 60;
1767 d = (now - s->creation_time) / 60;
1768 dss_msg("%u\t%s\t%3" PRId64 ":%02" PRId64 "\n", s->interval,
1769 s->name, d / 60, d % 60);
1771 free_snapshot_list(&sl);
1774 EXPORT_CMD_HANDLER(ls);
1776 static int com_configtest(void)
1778 printf("Syntax Ok\n");
1781 EXPORT_CMD_HANDLER(configtest);
1783 static int setup_signal_handling(void)
1787 DSS_INFO_LOG(("setting up signal handlers\n"));
1788 signal_pipe = signal_init(); /* always successful */
1789 ret = install_sighandler(SIGINT);
1792 ret = install_sighandler(SIGTERM);
1795 return install_sighandler(SIGCHLD);
1798 static void handle_version_and_help(void)
1802 if (OPT_GIVEN(DSS, DETAILED_HELP))
1803 txt = lls_long_help(CMD_PTR(DSS));
1804 else if (OPT_GIVEN(DSS, HELP))
1805 txt = lls_short_help(CMD_PTR(DSS));
1806 else if (OPT_GIVEN(DSS, VERSION))
1807 txt = make_message("%s\n", VERSION_STRING);
1815 static void show_subcommand_summary(void)
1817 const struct lls_command *cmd;
1820 printf("Available subcommands:\n");
1821 for (i = 1; (cmd = lls_cmd(i, dss_suite)); i++) {
1822 const char *name = lls_command_name(cmd);
1823 const char *purpose = lls_purpose(cmd);
1824 printf("%-11s%s\n", name, purpose);
1829 int main(int argc, char **argv)
1832 char *errctx = NULL;
1833 unsigned num_inputs;
1834 const struct dss_user_data *ud;
1836 ret = lls_parse(argc, argv, CMD_PTR(DSS), &cmdline_lpr, &errctx);
1838 ret = lopsub_error(ret, &errctx);
1842 ret = parse_config_file(false /* no SIGHUP */, CMD_PTR(DSS));
1845 handle_version_and_help();
1846 num_inputs = lls_num_inputs(lpr);
1847 if (num_inputs == 0)
1848 show_subcommand_summary();
1849 ret = lls_lookup_subcmd(argv[argc - num_inputs], dss_suite, &errctx);
1851 ret = lopsub_error(ret, &errctx);
1854 subcmd = lls_cmd(ret, dss_suite);
1855 ret = lls_parse(num_inputs, argv + argc - num_inputs, subcmd,
1856 &cmdline_sublpr, &errctx);
1858 ret = lopsub_error(ret, &errctx);
1861 sublpr = cmdline_sublpr;
1862 ret = parse_config_file(false /* no SIGHUP */, subcmd);
1865 ret = check_config();
1868 ret = setup_signal_handling();
1871 ud = lls_user_data(subcmd);
1872 ret = ud->handler();
1877 DSS_ERROR_LOG(("%s\n", errctx));
1878 DSS_EMERG_LOG(("%s\n", dss_strerror(-ret)));
1881 lls_free_parse_result(lpr, CMD_PTR(DSS));
1882 if (lpr != cmdline_lpr)
1883 lls_free_parse_result(cmdline_lpr, CMD_PTR(DSS));
1884 lls_free_parse_result(sublpr, subcmd);
1885 if (sublpr != cmdline_sublpr)
1886 lls_free_parse_result(cmdline_sublpr, subcmd);
1887 exit(ret >= 0? EXIT_SUCCESS : EXIT_FAILURE);