54d6e42be32a6b381529d0dc2b9224ce2faaf79e
[dss.git] / dss.c
1 /*
2 * Copyright (C) 2008-2011 Andre Noll <maan@tuebingen.mpg.de>
3 *
4 * Licensed under the GPL v2. For licencing details see COPYING.
5 */
6 #include <string.h>
7 #include <stdlib.h>
8 #include <stdio.h>
9 #include <stdarg.h>
10 #include <assert.h>
11 #include <errno.h>
12 #include <sys/types.h>
13 #include <signal.h>
14 #include <ctype.h>
15 #include <stdbool.h>
16 #include <sys/stat.h>
17 #include <unistd.h>
18 #include <inttypes.h>
19 #include <sys/time.h>
20 #include <time.h>
21 #include <sys/wait.h>
22 #include <fnmatch.h>
23 #include <limits.h>
24 #include <fcntl.h>
25 #include <lopsub.h>
26 #include <sys/mman.h>
27
28 #include "gcc-compat.h"
29 #include "log.h"
30 #include "str.h"
31 #include "err.h"
32 #include "file.h"
33 #include "exec.h"
34 #include "daemon.h"
35 #include "sig.h"
36 #include "df.h"
37 #include "tv.h"
38 #include "snap.h"
39 #include "ipc.h"
40 #include "dss.lsg.h"
41
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)))
50
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 \
55 };
56
57 /*
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.
61 */
62 static struct lls_parse_result *cmdline_lpr, *lpr;
63
64 /** Parsed subcommand options. */
65 static struct lls_parse_result *cmdline_sublpr, *sublpr;
66 /* The executing subcommand (NULL at startup). */
67 static const struct lls_command *subcmd;
68 /** Wether daemon_init() was called. */
69 static bool daemonized;
70 /** Non-NULL if we log to a file. */
71 static FILE *logfile;
72 /** The read end of the signal pipe */
73 static int signal_pipe;
74 /** Process id of current pre-create-hook/rsync/post-create-hook process. */
75 static pid_t create_pid;
76 /** Whether the pre-create-hook/rsync/post-create-hook is currently stopped. */
77 static int create_process_stopped;
78 /** How many times in a row the rsync command failed. */
79 static int num_consecutive_rsync_errors;
80 /** Process id of current pre-remove/rm/post-remove process. */
81 static pid_t remove_pid;
82 /** When the next snapshot is due. */
83 static int64_t next_snapshot_time;
84 /** When to try to remove something. */
85 static struct timeval next_removal_check;
86 /** Creation time of the snapshot currently being created. */
87 static int64_t current_snapshot_creation_time;
88 /** The snapshot currently being removed. */
89 struct snapshot *snapshot_currently_being_removed;
90 /** Needed by the post-create hook. */
91 static char *path_to_last_complete_snapshot;
92 static char *name_of_reference_snapshot;
93 /** \sa \ref snap.h for details. */
94 enum hook_status snapshot_creation_status;
95 /** \sa \ref snap.h for details. */
96 enum hook_status snapshot_removal_status;
97
98
99 DEFINE_DSS_ERRLIST;
100 static const char *hook_status_description[] = {HOOK_STATUS_ARRAY};
101
102 /* may be called with ds == NULL. */
103 static int disk_space_low(struct disk_space *ds)
104 {
105 struct disk_space ds_struct;
106 uint32_t val;
107
108 if (!ds) {
109 int ret = get_disk_space(".", &ds_struct);
110 if (ret < 0)
111 return ret;
112 ds = &ds_struct;
113 }
114 val = OPT_UINT32_VAL(DSS, MIN_FREE_MB);
115 if (val != 0)
116 if (ds->free_mb < val)
117 return 1;
118 val = OPT_UINT32_VAL(DSS, MIN_FREE_PERCENT);
119 if (val != 0)
120 if (ds->percent_free < val)
121 return 1;
122 val = OPT_UINT32_VAL(DSS, MIN_FREE_PERCENT_INODES);
123 if (val != 0)
124 if (ds->percent_free_inodes < val)
125 return 1;
126 return 0;
127 }
128
129 static void dump_dss_config(const char *msg)
130 {
131 const char dash[] = "-----------------------------";
132 char *lopsub_dump;
133 int ret;
134 FILE *log = logfile? logfile : stderr;
135 struct disk_space ds;
136 int64_t now = get_current_time();
137
138 if (OPT_UINT32_VAL(DSS, LOGLEVEL) > INFO)
139 return;
140
141 fprintf(log, "%s <%s config> %s\n", dash, msg, dash);
142 fprintf(log, "\n*** disk space ***\n\n");
143 ret = get_disk_space(".", &ds);
144 if (ret >= 0) {
145 DSS_INFO_LOG(("disk space low: %s\n", disk_space_low(&ds)?
146 "yes" : "no"));
147 log_disk_space(&ds);
148 } else
149 DSS_ERROR_LOG(("can not get free disk space: %s\n",
150 dss_strerror(-ret)));
151
152 /* we continue on errors from get_disk_space */
153
154 fprintf(log, "\n*** non-default options ***\n\n");
155 lopsub_dump = lls_dump_parse_result(lpr, CMD_PTR(DSS), true);
156 fprintf(log, "%s", lopsub_dump);
157 free(lopsub_dump);
158 fprintf(log, "\n*** non-default options for \"run\" ***\n\n");
159 lopsub_dump = lls_dump_parse_result(lpr, CMD_PTR(RUN), true);
160 fprintf(log, "%s", lopsub_dump);
161 free(lopsub_dump);
162 fprintf(log, "\n*** internal state ***\n\n");
163 fprintf(log,
164 "pid: %d\n"
165 "logile: %s\n"
166 "snapshot_currently_being_removed: %s\n"
167 "path_to_last_complete_snapshot: %s\n"
168 "reference_snapshot: %s\n"
169 "snapshot_creation_status: %s\n"
170 "snapshot_removal_status: %s\n"
171 "num_consecutive_rsync_errors: %d\n"
172 ,
173 (int) getpid(),
174 logfile? OPT_STRING_VAL(RUN, LOGFILE) : "stderr",
175 snapshot_currently_being_removed?
176 snapshot_currently_being_removed->name : "(none)",
177 path_to_last_complete_snapshot?
178 path_to_last_complete_snapshot : "(none)",
179 name_of_reference_snapshot?
180 name_of_reference_snapshot : "(none)",
181 hook_status_description[snapshot_creation_status],
182 hook_status_description[snapshot_removal_status],
183 num_consecutive_rsync_errors
184 );
185 if (create_pid != 0)
186 fprintf(log,
187 "create_pid: %" PRId32 "\n"
188 "create process is %sstopped\n"
189 ,
190 create_pid,
191 create_process_stopped? "" : "not "
192 );
193 if (remove_pid != 0)
194 fprintf(log, "remove_pid: %" PRId32 "\n", remove_pid);
195 if (next_snapshot_time != 0)
196 fprintf(log, "next snapshot due in %" PRId64 " seconds\n",
197 next_snapshot_time - now);
198 if (current_snapshot_creation_time != 0)
199 fprintf(log, "current_snapshot_creation_time: %"
200 PRId64 " (%" PRId64 " seconds ago)\n",
201 current_snapshot_creation_time,
202 now - current_snapshot_creation_time
203 );
204 if (next_removal_check.tv_sec != 0) {
205 fprintf(log, "next removal check: %llu (%llu seconds ago)\n",
206 (long long unsigned)next_removal_check.tv_sec,
207 now - (long long unsigned)next_removal_check.tv_sec
208 );
209
210 }
211 fprintf(log, "%s </%s config> %s\n", dash, msg, dash);
212 }
213
214 static int loglevel = -1;
215 static const char *location_file = NULL;
216 static int location_line = -1;
217 static const char *location_func = NULL;
218
219 void dss_log_set_params(int ll, const char *file, int line, const char *func)
220 {
221 loglevel = ll;
222 location_file = file;
223 location_line = line;
224 location_func = func;
225 }
226
227 /**
228 * The log function of dss.
229 *
230 * \param ll Loglevel.
231 * \param fml Usual format string.
232 *
233 * All DSS_XXX_LOG() macros use this function.
234 */
235 __printf_1_2 void dss_log(const char* fmt,...)
236 {
237 va_list argp;
238 FILE *outfd;
239 struct tm *tm;
240 time_t t1;
241 char str[255] = "";
242 int lpr_ll = lpr? OPT_UINT32_VAL(DSS, LOGLEVEL) : WARNING;
243
244 if (loglevel < lpr_ll)
245 return;
246 outfd = logfile? logfile : stderr;
247 time(&t1);
248 tm = localtime(&t1);
249 strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
250 fprintf(outfd, "%s ", str);
251 if (lpr_ll <= INFO)
252 fprintf(outfd, "%i: ", loglevel);
253 #ifdef DSS_NO_FUNC_NAMES
254 fprintf(outfd, "%s:%d: ", location_file, location_line);
255 #else
256 fprintf(outfd, "%s: ", location_func);
257 #endif
258 va_start(argp, fmt);
259 vfprintf(outfd, fmt, argp);
260 va_end(argp);
261 }
262
263 /**
264 * Print a message either to stdout or to the log file.
265 */
266 static __printf_1_2 void dss_msg(const char* fmt,...)
267 {
268 FILE *outfd = logfile? logfile : stdout;
269 va_list argp;
270 va_start(argp, fmt);
271 vfprintf(outfd, fmt, argp);
272 va_end(argp);
273 }
274
275 static char *get_config_file_name(void)
276 {
277 char *home, *config_file;
278
279 if (OPT_GIVEN(DSS, CONFIG_FILE))
280 return dss_strdup(OPT_STRING_VAL(DSS, CONFIG_FILE));
281 home = get_homedir();
282 config_file = make_message("%s/.dssrc", home);
283 free(home);
284 return config_file;
285 }
286
287 static int send_signal(int sig)
288 {
289 pid_t pid;
290 char *config_file = get_config_file_name();
291 int ret = get_dss_pid(config_file, &pid);
292
293 free(config_file);
294 if (ret < 0)
295 return ret;
296 if (OPT_GIVEN(DSS, DRY_RUN)) {
297 dss_msg("%d\n", (int)pid);
298 return 0;
299 }
300 ret = kill(pid, sig);
301 if (ret < 0)
302 return -ERRNO_TO_DSS_ERROR(errno);
303 return 1;
304 }
305
306 struct signal_info {
307 const char * const name;
308 int num;
309 };
310
311 /*
312 * The table below was taken 2016 from proc/sig.c of procps-3.2.8. Copyright
313 * 1998-2003 by Albert Cahalan, GPLv2.
314 */
315 static const struct signal_info signal_table[] = {
316 {"ABRT", SIGABRT}, /* IOT */
317 {"ALRM", SIGALRM},
318 {"BUS", SIGBUS},
319 {"CHLD", SIGCHLD}, /* CLD */
320 {"CONT", SIGCONT},
321 {"FPE", SIGFPE},
322 {"HUP", SIGHUP},
323 {"ILL", SIGILL},
324 {"INT", SIGINT},
325 {"KILL", SIGKILL},
326 {"PIPE", SIGPIPE},
327 #ifdef SIGPOLL
328 {"POLL", SIGPOLL}, /* IO */
329 #endif
330 {"PROF", SIGPROF},
331 #ifdef SIGPWR
332 {"PWR", SIGPWR},
333 #endif
334 {"QUIT", SIGQUIT},
335 {"SEGV", SIGSEGV},
336 #ifdef SIGSTKFLT
337 {"STKFLT", SIGSTKFLT},
338 #endif
339 {"STOP", SIGSTOP},
340 {"SYS", SIGSYS}, /* UNUSED */
341 {"TERM", SIGTERM},
342 {"TRAP", SIGTRAP},
343 {"TSTP", SIGTSTP},
344 {"TTIN", SIGTTIN},
345 {"TTOU", SIGTTOU},
346 {"URG", SIGURG},
347 {"USR1", SIGUSR1},
348 {"USR2", SIGUSR2},
349 {"VTALRM", SIGVTALRM},
350 {"WINCH", SIGWINCH},
351 {"XCPU", SIGXCPU},
352 {"XFSZ", SIGXFSZ}
353 };
354
355 #define SIGNAL_TABLE_SIZE (sizeof(signal_table) / sizeof(signal_table[0]))
356 #ifndef SIGRTMAX
357 #define SIGRTMAX 64
358 #endif
359
360 static int com_kill(void)
361 {
362 const char *arg = OPT_STRING_VAL(KILL, SIGNAL);
363 int ret, i;
364
365 if (*arg >= '0' && *arg <= '9') {
366 int64_t val;
367 ret = dss_atoi64(arg, &val);
368 if (ret < 0)
369 return ret;
370 if (val < 0 || val > SIGRTMAX)
371 return -ERRNO_TO_DSS_ERROR(EINVAL);
372 return send_signal(val);
373 }
374 if (strncasecmp(arg, "sig", 3) == 0)
375 arg += 3;
376 if (strcasecmp(arg, "CLD") == 0)
377 return send_signal(SIGCHLD);
378 if (strcasecmp(arg, "IOT") == 0)
379 return send_signal(SIGABRT);
380 for (i = 0; i < SIGNAL_TABLE_SIZE; i++)
381 if (strcasecmp(arg, signal_table[i].name) == 0)
382 return send_signal(signal_table[i].num);
383 DSS_ERROR_LOG(("invalid sigspec: %s\n", arg));
384 return -ERRNO_TO_DSS_ERROR(EINVAL);
385 }
386 EXPORT_CMD_HANDLER(kill);
387
388 static void dss_get_snapshot_list(struct snapshot_list *sl)
389 {
390 get_snapshot_list(sl, OPT_UINT32_VAL(DSS, UNIT_INTERVAL),
391 OPT_UINT32_VAL(DSS, NUM_INTERVALS));
392 }
393
394 static int64_t compute_next_snapshot_time(void)
395 {
396 int64_t x = 0, now = get_current_time(), unit_interval
397 = 24 * 3600 * OPT_UINT32_VAL(DSS, UNIT_INTERVAL), ret;
398 unsigned wanted = desired_number_of_snapshots(0,
399 OPT_UINT32_VAL(DSS, NUM_INTERVALS)),
400 num_complete = 0;
401 int i;
402 struct snapshot *s = NULL;
403 struct snapshot_list sl;
404
405 dss_get_snapshot_list(&sl);
406 FOR_EACH_SNAPSHOT(s, i, &sl) {
407 if (!(s->flags & SS_COMPLETE))
408 continue;
409 num_complete++;
410 x += s->completion_time - s->creation_time;
411 }
412 assert(x >= 0);
413
414 ret = now;
415 if (num_complete == 0)
416 goto out;
417 x /= num_complete; /* avg time to create one snapshot */
418 if (unit_interval < x * wanted) /* oops, no sleep at all */
419 goto out;
420 ret = s->completion_time + unit_interval / wanted - x;
421 out:
422 free_snapshot_list(&sl);
423 return ret;
424 }
425
426 static inline void invalidate_next_snapshot_time(void)
427 {
428 next_snapshot_time = 0;
429 }
430
431 static inline int next_snapshot_time_is_valid(void)
432 {
433 return next_snapshot_time != 0;
434 }
435
436 static int next_snapshot_is_due(void)
437 {
438 int64_t now = get_current_time();
439
440 if (!next_snapshot_time_is_valid())
441 next_snapshot_time = compute_next_snapshot_time();
442 if (next_snapshot_time <= now) {
443 DSS_DEBUG_LOG(("next snapshot: now\n"));
444 return 1;
445 }
446 DSS_DEBUG_LOG(("next snapshot due in %" PRId64 " seconds\n",
447 next_snapshot_time - now));
448 return 0;
449 }
450
451 static void pre_create_hook(void)
452 {
453 assert(snapshot_creation_status == HS_READY);
454 /* make sure that the next snapshot time will be recomputed */
455 invalidate_next_snapshot_time();
456 DSS_DEBUG_LOG(("executing %s\n", OPT_STRING_VAL(DSS, PRE_CREATE_HOOK)));
457 dss_exec_cmdline_pid(&create_pid, OPT_STRING_VAL(DSS, PRE_CREATE_HOOK));
458 snapshot_creation_status = HS_PRE_RUNNING;
459 }
460
461 static void pre_remove_hook(struct snapshot *s, const char *why)
462 {
463 char *cmd;
464
465 if (!s)
466 return;
467 DSS_DEBUG_LOG(("%s snapshot %s\n", why, s->name));
468 assert(snapshot_removal_status == HS_READY);
469 assert(remove_pid == 0);
470 assert(!snapshot_currently_being_removed);
471
472 snapshot_currently_being_removed = dss_malloc(sizeof(struct snapshot));
473 *snapshot_currently_being_removed = *s;
474 snapshot_currently_being_removed->name = dss_strdup(s->name);
475
476 cmd = make_message("%s %s/%s", OPT_STRING_VAL(DSS, PRE_REMOVE_HOOK),
477 OPT_STRING_VAL(DSS, DEST_DIR), s->name);
478 DSS_DEBUG_LOG(("executing %s\n", cmd));
479 dss_exec_cmdline_pid(&remove_pid, cmd);
480 free(cmd);
481 snapshot_removal_status = HS_PRE_RUNNING;
482 }
483
484 static int exec_rm(void)
485 {
486 struct snapshot *s = snapshot_currently_being_removed;
487 char *new_name = being_deleted_name(s);
488 char *argv[4];
489 int ret;
490
491 argv[0] = "rm";
492 argv[1] = "-rf";
493 argv[2] = new_name;
494 argv[3] = NULL;
495
496 assert(snapshot_removal_status == HS_PRE_SUCCESS);
497 assert(remove_pid == 0);
498
499 DSS_NOTICE_LOG(("removing %s (interval = %i)\n", s->name, s->interval));
500 ret = dss_rename(s->name, new_name);
501 if (ret < 0)
502 goto out;
503 dss_exec(&remove_pid, argv[0], argv);
504 snapshot_removal_status = HS_RUNNING;
505 out:
506 free(new_name);
507 return ret;
508 }
509
510 static int snapshot_is_being_created(struct snapshot *s)
511 {
512 return s->creation_time == current_snapshot_creation_time;
513 }
514
515 static struct snapshot *find_orphaned_snapshot(struct snapshot_list *sl)
516 {
517 struct snapshot *s;
518 int i;
519
520 DSS_DEBUG_LOG(("looking for orphaned snapshots\n"));
521 FOR_EACH_SNAPSHOT(s, i, sl) {
522 if (snapshot_is_being_created(s))
523 continue;
524 /*
525 * We know that no rm is currently running, so if s is marked
526 * as being deleted, a previously started rm must have failed.
527 */
528 if (s->flags & SS_BEING_DELETED)
529 return s;
530
531 if (s->flags & SS_COMPLETE) /* good snapshot */
532 continue;
533 /*
534 * This snapshot is incomplete and it is not the snapshot
535 * currently being created. However, we must not remove it if
536 * rsync is about to be restarted. As only the newest snapshot
537 * can be restarted, this snapshot is orphaned if it is not the
538 * newest snapshot or if we are not about to restart rsync.
539 */
540 if (get_newest_snapshot(sl) != s)
541 return s;
542 if (snapshot_creation_status != HS_NEEDS_RESTART)
543 return s;
544 }
545 /* no orphaned snapshots */
546 return NULL;
547 }
548
549 static int is_reference_snapshot(struct snapshot *s)
550 {
551 if (!name_of_reference_snapshot)
552 return 0;
553 return strcmp(s->name, name_of_reference_snapshot)? 0 : 1;
554 }
555
556 /*
557 * return: 0: no redundant snapshots, 1: rm process started, negative: error
558 */
559 static struct snapshot *find_redundant_snapshot(struct snapshot_list *sl)
560 {
561 int i, interval;
562 struct snapshot *s;
563 unsigned missing = 0;
564 uint32_t N = OPT_UINT32_VAL(DSS, NUM_INTERVALS);
565
566 DSS_DEBUG_LOG(("looking for intervals containing too many snapshots\n"));
567 for (interval = N - 1; interval >= 0; interval--) {
568 unsigned keep = desired_number_of_snapshots(interval, N);
569 unsigned num = sl->interval_count[interval];
570 struct snapshot *victim = NULL, *prev = NULL;
571 int64_t score = LONG_MAX;
572
573 if (keep >= num)
574 missing += keep - num;
575 if (keep + missing >= num)
576 continue;
577 /* redundant snapshot in this interval, pick snapshot with lowest score */
578 FOR_EACH_SNAPSHOT(s, i, sl) {
579 int64_t this_score;
580
581 if (snapshot_is_being_created(s))
582 continue;
583 if (is_reference_snapshot(s))
584 continue;
585 if (s->interval > interval) {
586 prev = s;
587 continue;
588 }
589 if (s->interval < interval)
590 break;
591 if (!victim) {
592 victim = s;
593 prev = s;
594 continue;
595 }
596 assert(prev);
597 /* check if s is a better victim */
598 this_score = s->creation_time - prev->creation_time;
599 assert(this_score >= 0);
600 if (this_score < score) {
601 score = this_score;
602 victim = s;
603 }
604 prev = s;
605 }
606 assert(victim);
607 return victim;
608 }
609 return NULL;
610 }
611
612 static struct snapshot *find_outdated_snapshot(struct snapshot_list *sl)
613 {
614 int i;
615 struct snapshot *s;
616
617 DSS_DEBUG_LOG(("looking for snapshots belonging to intervals >= %d\n",
618 OPT_UINT32_VAL(DSS, NUM_INTERVALS)));
619 FOR_EACH_SNAPSHOT(s, i, sl) {
620 if (snapshot_is_being_created(s))
621 continue;
622 if (is_reference_snapshot(s))
623 continue;
624 if (s->interval < OPT_UINT32_VAL(DSS, NUM_INTERVALS))
625 continue;
626 return s;
627 }
628 return NULL;
629 }
630
631 static struct snapshot *find_oldest_removable_snapshot(struct snapshot_list *sl)
632 {
633 int i, num_complete;
634 struct snapshot *s, *ref = NULL;
635
636 num_complete = num_complete_snapshots(sl);
637 if (num_complete <= OPT_UINT32_VAL(DSS, MIN_COMPLETE))
638 return NULL;
639 FOR_EACH_SNAPSHOT(s, i, sl) {
640 if (snapshot_is_being_created(s))
641 continue;
642 if (is_reference_snapshot(s)) { /* avoid this one */
643 ref = s;
644 continue;
645 }
646 DSS_INFO_LOG(("oldest removable snapshot: %s\n", s->name));
647 return s;
648 }
649 assert(ref);
650 DSS_WARNING_LOG(("removing reference snapshot %s\n", ref->name));
651 return ref;
652 }
653
654 static int rename_incomplete_snapshot(int64_t start)
655 {
656 char *old_name;
657 int ret;
658 int64_t now;
659
660 /*
661 * We don't want the dss_rename() below to fail with EEXIST because the
662 * last complete snapshot was created (and completed) in the same
663 * second as this one.
664 */
665 while ((now = get_current_time()) == start)
666 sleep(1);
667 free(path_to_last_complete_snapshot);
668 ret = complete_name(start, now, &path_to_last_complete_snapshot);
669 if (ret < 0)
670 return ret;
671 old_name = incomplete_name(start);
672 ret = dss_rename(old_name, path_to_last_complete_snapshot);
673 if (ret >= 0)
674 DSS_NOTICE_LOG(("%s -> %s\n", old_name,
675 path_to_last_complete_snapshot));
676 free(old_name);
677 return ret;
678 }
679
680 static int try_to_free_disk_space(void)
681 {
682 int ret;
683 struct snapshot_list sl;
684 struct snapshot *victim;
685 struct timeval now;
686 const char *why;
687 int low_disk_space;
688
689 ret = disk_space_low(NULL);
690 if (ret < 0)
691 return ret;
692 low_disk_space = ret;
693 gettimeofday(&now, NULL);
694 if (tv_diff(&next_removal_check, &now, NULL) > 0)
695 return 0;
696 if (!low_disk_space) {
697 if (OPT_GIVEN(DSS, KEEP_REDUNDANT))
698 return 0;
699 if (snapshot_creation_status != HS_READY)
700 return 0;
701 if (next_snapshot_is_due())
702 return 0;
703 }
704 /*
705 * Idle and --keep_redundant not given, or low disk space. Look at
706 * existing snapshots.
707 */
708 dss_get_snapshot_list(&sl);
709 ret = 0;
710 /*
711 * Don't remove anything if there is free space and we have fewer
712 * snapshots than configured, plus one. This way there is always one
713 * snapshot that can be recycled.
714 */
715 if (!low_disk_space && sl.num_snapshots <=
716 1 << OPT_UINT32_VAL(DSS, NUM_INTERVALS))
717 goto out;
718 why = "outdated";
719 victim = find_outdated_snapshot(&sl);
720 if (victim)
721 goto remove;
722 why = "redundant";
723 victim = find_redundant_snapshot(&sl);
724 if (victim)
725 goto remove;
726 why = "orphaned";
727 victim = find_orphaned_snapshot(&sl);
728 if (victim)
729 goto remove;
730 /* try harder only if disk space is low */
731 if (!low_disk_space)
732 goto out;
733 DSS_WARNING_LOG(("disk space low and nothing obvious to remove\n"));
734 victim = find_oldest_removable_snapshot(&sl);
735 if (victim)
736 goto remove;
737 DSS_CRIT_LOG(("uhuhu: disk space low and nothing to remove\n"));
738 ret = -ERRNO_TO_DSS_ERROR(ENOSPC);
739 goto out;
740 remove:
741 pre_remove_hook(victim, why);
742 out:
743 free_snapshot_list(&sl);
744 return ret;
745 }
746
747 static void post_create_hook(void)
748 {
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);
754 free(cmd);
755 snapshot_creation_status = HS_POST_RUNNING;
756 }
757
758 static void post_remove_hook(void)
759 {
760 char *cmd;
761 struct snapshot *s = snapshot_currently_being_removed;
762
763 assert(s);
764
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);
769 free(cmd);
770 snapshot_removal_status = HS_POST_RUNNING;
771 }
772
773 static void dss_kill(pid_t pid, int sig, const char *msg)
774 {
775 const char *signame, *process_name;
776
777 if (pid == 0)
778 return;
779 switch (sig) {
780 case SIGTERM: signame = "TERM"; break;
781 case SIGSTOP: signame = "STOP"; break;
782 case SIGCONT: signame = "CONT"; break;
783 default: signame = "????";
784 }
785
786 if (pid == create_pid)
787 process_name = "create";
788 else if (pid == remove_pid)
789 process_name = "remove";
790 else process_name = "??????";
791
792 if (msg)
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)
797 return;
798 DSS_INFO_LOG(("failed to send signal %d (%s) to pid %d (%s process)\n",
799 sig, signame, (int)pid, process_name));
800 }
801
802 static void stop_create_process(void)
803 {
804 if (create_process_stopped)
805 return;
806 dss_kill(create_pid, SIGSTOP, "suspending create process");
807 create_process_stopped = 1;
808 }
809
810 static void restart_create_process(void)
811 {
812 if (!create_process_stopped)
813 return;
814 dss_kill(create_pid, SIGCONT, "resuming create process");
815 create_process_stopped = 0;
816 }
817
818 /**
819 * Print a log message about the exit status of a child.
820 */
821 static void log_termination_msg(pid_t pid, int status)
822 {
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,
828 WTERMSIG(status)));
829 else
830 DSS_WARNING_LOG(("child %i terminated abormally\n", (int)pid));
831 }
832
833 static int wait_for_process(pid_t pid, int *status)
834 {
835 int ret;
836
837 DSS_DEBUG_LOG(("Waiting for process %d to terminate\n", (int)pid));
838 for (;;) {
839 fd_set rfds;
840
841 FD_ZERO(&rfds);
842 FD_SET(signal_pipe, &rfds);
843 ret = dss_select(signal_pipe + 1, &rfds, NULL, NULL);
844 if (ret < 0)
845 break;
846 ret = next_signal();
847 if (!ret)
848 continue;
849 if (ret == SIGCHLD) {
850 ret = waitpid(pid, status, 0);
851 if (ret >= 0)
852 break;
853 if (errno != EINTR) { /* error */
854 ret = -ERRNO_TO_DSS_ERROR(errno);
855 break;
856 }
857 }
858 /* SIGINT or SIGTERM */
859 dss_kill(pid, SIGTERM, "killing child process");
860 }
861 if (ret < 0)
862 DSS_ERROR_LOG(("failed to wait for process %d\n", (int)pid));
863 else
864 log_termination_msg(pid, *status);
865 return ret;
866 }
867
868 static void handle_pre_remove_exit(int status)
869 {
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;
874 return;
875 }
876 snapshot_removal_status = HS_PRE_SUCCESS;
877 }
878
879 static int handle_rm_exit(int status)
880 {
881 if (!WIFEXITED(status)) {
882 snapshot_removal_status = HS_READY;
883 return -E_INVOLUNTARY_EXIT;
884 }
885 if (WEXITSTATUS(status)) {
886 snapshot_removal_status = HS_READY;
887 return -E_BAD_EXIT_CODE;
888 }
889 snapshot_removal_status = HS_SUCCESS;
890 return 1;
891 }
892
893 static void handle_post_remove_exit(void)
894 {
895 snapshot_removal_status = HS_READY;
896 }
897
898 static int handle_remove_exit(int status)
899 {
900 int ret;
901 struct snapshot *s = snapshot_currently_being_removed;
902
903 assert(s);
904 switch (snapshot_removal_status) {
905 case HS_PRE_RUNNING:
906 handle_pre_remove_exit(status);
907 ret = 1;
908 break;
909 case HS_RUNNING:
910 ret = handle_rm_exit(status);
911 break;
912 case HS_POST_RUNNING:
913 handle_post_remove_exit();
914 ret = 1;
915 break;
916 default:
917 ret = -E_BUG;
918 }
919 if (snapshot_removal_status == HS_READY) {
920 free(s->name);
921 free(s);
922 snapshot_currently_being_removed = NULL;
923 }
924 remove_pid = 0;
925 return ret;
926 }
927
928 static int wait_for_remove_process(void)
929 {
930 int status, ret;
931
932 assert(remove_pid);
933 assert(
934 snapshot_removal_status == HS_PRE_RUNNING ||
935 snapshot_removal_status == HS_RUNNING ||
936 snapshot_removal_status == HS_POST_RUNNING
937 );
938 ret = wait_for_process(remove_pid, &status);
939 if (ret < 0)
940 return ret;
941 return handle_remove_exit(status);
942 }
943
944 static int handle_rsync_exit(int status)
945 {
946 int es, ret;
947
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;
952 goto out;
953 }
954 es = WEXITSTATUS(status);
955 /*
956 * Restart rsync on non-fatal errors:
957 * 24: Partial transfer due to vanished source files
958 */
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;
964 goto out;
965 }
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;
970 goto out;
971 }
972 DSS_WARNING_LOG(("restarting rsync process\n"));
973 snapshot_creation_status = HS_NEEDS_RESTART;
974 next_snapshot_time = get_current_time() + 60;
975 ret = 1;
976 goto out;
977 }
978 num_consecutive_rsync_errors = 0;
979 ret = rename_incomplete_snapshot(current_snapshot_creation_time);
980 if (ret < 0)
981 goto out;
982 snapshot_creation_status = HS_SUCCESS;
983 free(name_of_reference_snapshot);
984 name_of_reference_snapshot = NULL;
985 out:
986 create_process_stopped = 0;
987 return ret;
988 }
989
990 static int handle_pre_create_hook_exit(int status)
991 {
992 int es, ret;
993 static int warn_count;
994
995 if (!WIFEXITED(status)) {
996 snapshot_creation_status = HS_READY;
997 ret = -E_INVOLUNTARY_EXIT;
998 goto out;
999 }
1000 es = WEXITSTATUS(status);
1001 if (es) {
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 */
1007 }
1008 next_snapshot_time = get_current_time() + 60;
1009 snapshot_creation_status = HS_READY;
1010 ret = 0;
1011 goto out;
1012 }
1013 warn_count = 0;
1014 snapshot_creation_status = HS_PRE_SUCCESS;
1015 ret = 1;
1016 out:
1017 return ret;
1018 }
1019
1020 static int handle_sigchld(void)
1021 {
1022 pid_t pid;
1023 int status, ret = reap_child(&pid, &status);
1024
1025 if (ret <= 0)
1026 return ret;
1027
1028 if (pid == create_pid) {
1029 switch (snapshot_creation_status) {
1030 case HS_PRE_RUNNING:
1031 ret = handle_pre_create_hook_exit(status);
1032 break;
1033 case HS_RUNNING:
1034 ret = handle_rsync_exit(status);
1035 break;
1036 case HS_POST_RUNNING:
1037 snapshot_creation_status = HS_READY;
1038 ret = 1;
1039 break;
1040 default:
1041 DSS_EMERG_LOG(("BUG: create can't die in status %d\n",
1042 snapshot_creation_status));
1043 return -E_BUG;
1044 }
1045 create_pid = 0;
1046 return ret;
1047 }
1048 if (pid == remove_pid) {
1049 ret = handle_remove_exit(status);
1050 if (ret < 0)
1051 return ret;
1052 return ret;
1053 }
1054 DSS_EMERG_LOG(("BUG: unknown process %d died\n", (int)pid));
1055 return -E_BUG;
1056 }
1057
1058 static int change_to_dest_dir(void)
1059 {
1060 int ret;
1061 const char *dd = OPT_STRING_VAL(DSS, DEST_DIR);
1062
1063 DSS_INFO_LOG(("changing cwd to %s\n", dd));
1064 if (chdir(dd) >= 0)
1065 return 1;
1066 ret = -ERRNO_TO_DSS_ERROR(errno);
1067 DSS_ERROR_LOG(("could not change cwd to %s\n", dd));
1068 return ret;
1069 }
1070
1071 static int check_config(void)
1072 {
1073 int ret;
1074 uint32_t unit_interval = OPT_UINT32_VAL(DSS, UNIT_INTERVAL);
1075 uint32_t num_intervals = OPT_UINT32_VAL(DSS, NUM_INTERVALS);
1076
1077 if (unit_interval == 0) {
1078 DSS_ERROR_LOG(("bad unit interval: %i\n", unit_interval));
1079 return -E_INVALID_NUMBER;
1080 }
1081 DSS_DEBUG_LOG(("unit interval: %i day(s)\n", unit_interval));
1082
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;
1086 }
1087 if (subcmd == CMD_PTR(RUN) || subcmd == CMD_PTR(CREATE))
1088 if (!OPT_GIVEN(DSS, SOURCE_DIR)) {
1089 DSS_ERROR_LOG(("--source-dir required\n"));
1090 return -E_SYNTAX;
1091 }
1092 if (subcmd == CMD_PTR(RUN) || subcmd == CMD_PTR(CREATE)
1093 || subcmd == CMD_PTR(LS) || subcmd == CMD_PTR(PRUNE)) {
1094 if (!OPT_GIVEN(DSS, DEST_DIR)) {
1095 DSS_ERROR_LOG(("--dest-dir required\n"));
1096 return -E_SYNTAX;
1097 }
1098 ret = change_to_dest_dir();
1099 if (ret < 0)
1100 return ret;
1101 }
1102 DSS_DEBUG_LOG(("number of intervals: %i\n", num_intervals));
1103 return 1;
1104 }
1105
1106 static int lopsub_error(int lopsub_ret, char **errctx)
1107 {
1108 const char *msg = lls_strerror(-lopsub_ret);
1109 if (*errctx)
1110 DSS_ERROR_LOG(("%s: %s\n", *errctx, msg));
1111 else
1112 DSS_ERROR_LOG(("%s\n", msg));
1113 free(*errctx);
1114 *errctx = NULL;
1115 return -E_LOPSUB;
1116 }
1117
1118 static int parse_config_file(bool sighup, const struct lls_command *cmd)
1119 {
1120 int ret, fd = -1;
1121 char *config_file = get_config_file_name();
1122 struct stat statbuf;
1123 void *map;
1124 size_t sz;
1125 int cf_argc;
1126 char **cf_argv, *errctx = NULL;
1127 struct lls_parse_result *cf_lpr, *merged_lpr, *clpr;
1128 const char *subcmd_name;
1129
1130 ret = open(config_file, O_RDONLY);
1131 if (ret < 0) {
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",
1135 config_file));
1136 goto out;
1137 }
1138 /* no config file -- nothing to do */
1139 ret = 0;
1140 goto success;
1141 }
1142 fd = ret;
1143 ret = fstat(fd, &statbuf);
1144 if (ret < 0) {
1145 ret = -ERRNO_TO_DSS_ERROR(errno);
1146 DSS_ERROR_LOG(("failed to stat config file %s\n", config_file));
1147 goto close_fd;
1148 }
1149 sz = statbuf.st_size;
1150 if (sz == 0) { /* config file is empty -- nothing to do */
1151 ret = 0;
1152 goto success;
1153 }
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",
1158 config_file));
1159 goto close_fd;
1160 }
1161 if (cmd == CMD_PTR(DSS))
1162 subcmd_name = NULL;
1163 else
1164 subcmd_name = lls_command_name(cmd);
1165 ret = lls_convert_config(map, sz, subcmd_name, &cf_argv, &errctx);
1166 munmap(map, sz);
1167 if (ret < 0) {
1168 DSS_ERROR_LOG(("failed to convert config file %s\n",
1169 config_file));
1170 ret = lopsub_error(ret, &errctx);
1171 goto close_fd;
1172 }
1173 cf_argc = ret;
1174 ret = lls_parse(cf_argc, cf_argv, cmd, &cf_lpr, &errctx);
1175 lls_free_argv(cf_argv);
1176 if (ret < 0) {
1177 ret = lopsub_error(ret, &errctx);
1178 goto close_fd;
1179 }
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);
1186 if (ret < 0) {
1187 ret = lopsub_error(ret, &errctx);
1188 goto close_fd;
1189 }
1190 ret = 1;
1191 success:
1192 assert(ret >= 0);
1193 DSS_DEBUG_LOG(("loglevel: %d\n", OPT_UINT32_VAL(DSS, LOGLEVEL)));
1194 if (cmd != CMD_PTR(DSS)) {
1195 if (ret > 0) {
1196 if (sublpr != cmdline_sublpr)
1197 lls_free_parse_result(sublpr, cmd);
1198 sublpr = merged_lpr;
1199 } else
1200 sublpr = cmdline_sublpr;
1201 } else {
1202 if (ret > 0) {
1203 if (lpr != cmdline_lpr)
1204 lls_free_parse_result(lpr, cmd);
1205 lpr = merged_lpr;
1206 } else
1207 lpr = cmdline_lpr;
1208 }
1209 close_fd:
1210 if (fd >= 0)
1211 close(fd);
1212 out:
1213 free(config_file);
1214 if (ret < 0)
1215 DSS_EMERG_LOG(("%s\n", dss_strerror(-ret)));
1216 return ret;
1217 }
1218
1219 static int handle_sighup(void)
1220 {
1221 int ret;
1222
1223 DSS_NOTICE_LOG(("SIGHUP, re-reading config\n"));
1224 dump_dss_config("old");
1225 ret = parse_config_file(true /* SIGHUP */, CMD_PTR(DSS));
1226 if (ret < 0)
1227 return ret;
1228 ret = parse_config_file(true /* SIGHUP */, CMD_PTR(RUN));
1229 if (ret < 0)
1230 return ret;
1231 ret = check_config();
1232 if (ret < 0)
1233 return ret;
1234 close_log(logfile);
1235 logfile = NULL;
1236 if (OPT_GIVEN(RUN, DAEMON) || daemonized) {
1237 logfile = open_log(OPT_STRING_VAL(RUN, LOGFILE));
1238 log_welcome(OPT_UINT32_VAL(DSS, LOGLEVEL));
1239 daemonized = true;
1240 }
1241 dump_dss_config("reloaded");
1242 invalidate_next_snapshot_time();
1243 return 1;
1244 }
1245
1246 static void kill_children(void)
1247 {
1248 restart_create_process();
1249 dss_kill(create_pid, SIGTERM, NULL);
1250 dss_kill(remove_pid, SIGTERM, NULL);
1251 }
1252
1253 static int handle_signal(void)
1254 {
1255 int sig, ret = next_signal();
1256
1257 if (ret <= 0)
1258 goto out;
1259 sig = ret;
1260 switch (sig) {
1261 case SIGINT:
1262 case SIGTERM:
1263 kill_children();
1264 ret = -E_SIGNAL;
1265 break;
1266 case SIGHUP:
1267 ret = handle_sighup();
1268 break;
1269 case SIGCHLD:
1270 ret = handle_sigchld();
1271 break;
1272 }
1273 out:
1274 if (ret < 0)
1275 DSS_ERROR_LOG(("%s\n", dss_strerror(-ret)));
1276 return ret;
1277 }
1278
1279 /*
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).
1282 */
1283 static int use_rsync_locally(char *logname)
1284 {
1285 const char *h = OPT_STRING_VAL(DSS, REMOTE_HOST);
1286
1287 if (strcmp(h, "localhost") && strcmp(h, "127.0.0.1"))
1288 return 0;
1289 if (OPT_GIVEN(DSS, REMOTE_USER) &&
1290 strcmp(OPT_STRING_VAL(DSS, REMOTE_USER), logname))
1291 return 0;
1292 return 1;
1293 }
1294
1295 static int rename_resume_snap(int64_t creation_time)
1296 {
1297 struct snapshot_list sl;
1298 struct snapshot *s = NULL;
1299 char *new_name = incomplete_name(creation_time);
1300 int ret;
1301 const char *why;
1302
1303 sl.num_snapshots = 0;
1304
1305 ret = 0;
1306 dss_get_snapshot_list(&sl);
1307 /*
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.
1314 *
1315 * Only if no existing snapshot is suitable for recycling, we bite the
1316 * bullet and create a new one.
1317 */
1318 s = get_newest_snapshot(&sl);
1319 if (!s) /* no snapshots at all */
1320 goto out;
1321 /* re-use last snapshot if it is incomplete */
1322 why = "aborted";
1323 if ((s->flags & SS_COMPLETE) == 0)
1324 goto out;
1325 why = "outdated";
1326 s = find_outdated_snapshot(&sl);
1327 if (s)
1328 goto out;
1329 why = "redundant";
1330 s = find_redundant_snapshot(&sl);
1331 if (s)
1332 goto out;
1333 why = "orphaned";
1334 s = find_orphaned_snapshot(&sl);
1335 out:
1336 if (s) {
1337 DSS_NOTICE_LOG(("recycling %s snapshot %s\n", why, s->name));
1338 ret = dss_rename(s->name, new_name);
1339 }
1340 if (ret >= 0)
1341 DSS_NOTICE_LOG(("creating %s\n", new_name));
1342 free(new_name);
1343 free_snapshot_list(&sl);
1344 return ret;
1345 }
1346
1347 static void create_rsync_argv(char ***argv, int64_t *num)
1348 {
1349 char *logname;
1350 int i = 0, j, N = OPT_GIVEN(DSS, RSYNC_OPTION);
1351 struct snapshot_list sl;
1352 static bool seeded;
1353
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);
1358
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");
1363 if (!seeded) {
1364 srandom((unsigned)time(NULL)); /* no need to be fancy here */
1365 seeded = true;
1366 }
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");
1370 }
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);
1378 } else
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));
1383 else
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));
1389 free(logname);
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]));
1395 }
1396
1397 static void free_rsync_argv(char **argv)
1398 {
1399 int i;
1400
1401 if (!argv)
1402 return;
1403 for (i = 0; argv[i]; i++)
1404 free(argv[i]);
1405 free(argv);
1406 }
1407
1408 static int create_snapshot(char **argv)
1409 {
1410 int ret;
1411
1412 ret = rename_resume_snap(current_snapshot_creation_time);
1413 if (ret < 0)
1414 return ret;
1415 dss_exec(&create_pid, argv[0], argv);
1416 snapshot_creation_status = HS_RUNNING;
1417 return ret;
1418 }
1419
1420 static int select_loop(void)
1421 {
1422 int ret;
1423 /* check every 60 seconds for free disk space */
1424 struct timeval tv;
1425 char **rsync_argv = NULL;
1426
1427 for (;;) {
1428 fd_set rfds;
1429 struct timeval *tvp;
1430
1431 if (remove_pid)
1432 tvp = NULL; /* sleep until rm hook/process dies */
1433 else { /* sleep one minute */
1434 tv.tv_sec = 60;
1435 tv.tv_usec = 0;
1436 tvp = &tv;
1437 }
1438 FD_ZERO(&rfds);
1439 FD_SET(signal_pipe, &rfds);
1440 ret = dss_select(signal_pipe + 1, &rfds, NULL, tvp);
1441 if (ret < 0)
1442 goto out;
1443 if (FD_ISSET(signal_pipe, &rfds)) {
1444 ret = handle_signal();
1445 if (ret < 0)
1446 goto out;
1447 }
1448 if (remove_pid)
1449 continue;
1450 if (snapshot_removal_status == HS_PRE_SUCCESS) {
1451 ret = exec_rm();
1452 if (ret < 0)
1453 goto out;
1454 continue;
1455 }
1456 if (snapshot_removal_status == HS_SUCCESS) {
1457 post_remove_hook();
1458 continue;
1459 }
1460 ret = try_to_free_disk_space();
1461 if (ret < 0)
1462 goto out;
1463 if (snapshot_removal_status != HS_READY) {
1464 stop_create_process();
1465 continue;
1466 }
1467 restart_create_process();
1468 switch (snapshot_creation_status) {
1469 case HS_READY:
1470 if (!next_snapshot_is_due())
1471 continue;
1472 pre_create_hook();
1473 continue;
1474 case HS_PRE_RUNNING:
1475 case HS_RUNNING:
1476 case HS_POST_RUNNING:
1477 continue;
1478 case HS_PRE_SUCCESS:
1479 if (!name_of_reference_snapshot) {
1480 free_rsync_argv(rsync_argv);
1481 create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
1482 }
1483 ret = create_snapshot(rsync_argv);
1484 if (ret < 0)
1485 goto out;
1486 continue;
1487 case HS_NEEDS_RESTART:
1488 if (!next_snapshot_is_due())
1489 continue;
1490 ret = create_snapshot(rsync_argv);
1491 if (ret < 0)
1492 goto out;
1493 continue;
1494 case HS_SUCCESS:
1495 post_create_hook();
1496 continue;
1497 }
1498 }
1499 out:
1500 return ret;
1501 }
1502
1503 static void exit_hook(int exit_code)
1504 {
1505 const char *argv[3];
1506 pid_t pid;
1507
1508 argv[0] = OPT_STRING_VAL(DSS, EXIT_HOOK);
1509 argv[1] = dss_strerror(-exit_code);
1510 argv[2] = NULL;
1511
1512 DSS_NOTICE_LOG(("executing %s %s\n", argv[0], argv[1]));
1513 dss_exec(&pid, argv[0], (char **)argv);
1514 }
1515
1516 static void lock_dss_or_die(void)
1517 {
1518 char *config_file = get_config_file_name();
1519 int ret = lock_dss(config_file);
1520
1521 free(config_file);
1522 if (ret < 0) {
1523 DSS_EMERG_LOG(("failed to lock: %s\n", dss_strerror(-ret)));
1524 exit(EXIT_FAILURE);
1525 }
1526 }
1527
1528 static int com_run(void)
1529 {
1530 int ret, fd = -1;
1531 char *config_file;
1532 pid_t pid;
1533
1534 if (OPT_GIVEN(DSS, DRY_RUN)) {
1535 DSS_ERROR_LOG(("dry run not supported by this command\n"));
1536 return -E_SYNTAX;
1537 }
1538 config_file = get_config_file_name();
1539 ret = get_dss_pid(config_file, &pid);
1540 free(config_file);
1541 if (ret >= 0) {
1542 DSS_ERROR_LOG(("pid %d\n", (int)pid));
1543 return -E_ALREADY_RUNNING;
1544 }
1545 if (OPT_GIVEN(RUN, DAEMON)) {
1546 fd = daemon_init();
1547 daemonized = true;
1548 logfile = open_log(OPT_STRING_VAL(RUN, LOGFILE));
1549 }
1550 lock_dss_or_die();
1551 dump_dss_config("startup");
1552 ret = install_sighandler(SIGHUP);
1553 if (ret < 0)
1554 return ret;
1555 if (fd >= 0) {
1556 ret = write(fd, "\0", 1);
1557 if (ret != 1) {
1558 DSS_ERROR_LOG(("write to daemon pipe returned %d\n",
1559 ret));
1560 if (ret < 0)
1561 return -ERRNO_TO_DSS_ERROR(errno);
1562 return -E_BUG;
1563 }
1564 }
1565 ret = select_loop();
1566 if (ret >= 0) /* impossible */
1567 ret = -E_BUG;
1568 kill_children();
1569 exit_hook(ret);
1570 return ret;
1571 }
1572 EXPORT_CMD_HANDLER(run);
1573
1574 static int com_prune(void)
1575 {
1576 int ret;
1577 struct snapshot_list sl;
1578 struct snapshot *victim;
1579 struct disk_space ds;
1580 const char *why;
1581
1582 lock_dss_or_die();
1583 ret = get_disk_space(".", &ds);
1584 if (ret < 0)
1585 return ret;
1586 log_disk_space(&ds);
1587 dss_get_snapshot_list(&sl);
1588 why = "outdated";
1589 victim = find_outdated_snapshot(&sl);
1590 if (victim)
1591 goto rm;
1592 why = "redundant";
1593 victim = find_redundant_snapshot(&sl);
1594 if (victim)
1595 goto rm;
1596 ret = 0;
1597 goto out;
1598 rm:
1599 if (OPT_GIVEN(DSS, DRY_RUN)) {
1600 dss_msg("%s snapshot %s (interval = %i)\n",
1601 why, victim->name, victim->interval);
1602 ret = 0;
1603 goto out;
1604 }
1605 pre_remove_hook(victim, why);
1606 if (snapshot_removal_status == HS_PRE_RUNNING) {
1607 ret = wait_for_remove_process();
1608 if (ret < 0)
1609 goto out;
1610 if (snapshot_removal_status != HS_PRE_SUCCESS)
1611 goto out;
1612 }
1613 ret = exec_rm();
1614 if (ret < 0)
1615 goto out;
1616 ret = wait_for_remove_process();
1617 if (ret < 0)
1618 goto out;
1619 if (snapshot_removal_status != HS_SUCCESS)
1620 goto out;
1621 post_remove_hook();
1622 if (snapshot_removal_status != HS_POST_RUNNING)
1623 goto out;
1624 ret = wait_for_remove_process();
1625 if (ret < 0)
1626 goto out;
1627 ret = 1;
1628 out:
1629 free_snapshot_list(&sl);
1630 return ret;
1631 }
1632 EXPORT_CMD_HANDLER(prune);
1633
1634 static int com_create(void)
1635 {
1636 int ret, status;
1637 char **rsync_argv;
1638
1639 lock_dss_or_die();
1640 if (OPT_GIVEN(DSS, DRY_RUN)) {
1641 int i;
1642 char *msg = NULL;
1643 create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
1644 for (i = 0; rsync_argv[i]; i++) {
1645 char *tmp = msg;
1646 msg = make_message("%s%s%s", tmp? tmp : "",
1647 tmp? " " : "", rsync_argv[i]);
1648 free(tmp);
1649 }
1650 free_rsync_argv(rsync_argv);
1651 dss_msg("%s\n", msg);
1652 free(msg);
1653 return 1;
1654 }
1655 pre_create_hook();
1656 if (create_pid) {
1657 ret = wait_for_process(create_pid, &status);
1658 if (ret < 0)
1659 return ret;
1660 ret = handle_pre_create_hook_exit(status);
1661 if (ret <= 0) /* error, or pre-create failed */
1662 return ret;
1663 }
1664 create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
1665 ret = create_snapshot(rsync_argv);
1666 if (ret < 0)
1667 goto out;
1668 ret = wait_for_process(create_pid, &status);
1669 if (ret < 0)
1670 goto out;
1671 ret = handle_rsync_exit(status);
1672 if (ret < 0)
1673 goto out;
1674 post_create_hook();
1675 if (create_pid)
1676 ret = wait_for_process(create_pid, &status);
1677 out:
1678 free_rsync_argv(rsync_argv);
1679 return ret;
1680 }
1681 EXPORT_CMD_HANDLER(create);
1682
1683 static int com_ls(void)
1684 {
1685 int i;
1686 struct snapshot_list sl;
1687 struct snapshot *s;
1688
1689 dss_get_snapshot_list(&sl);
1690 FOR_EACH_SNAPSHOT(s, i, &sl) {
1691 int64_t d = 0;
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);
1695 }
1696 free_snapshot_list(&sl);
1697 return 1;
1698 }
1699 EXPORT_CMD_HANDLER(ls);
1700
1701 static int setup_signal_handling(void)
1702 {
1703 int ret;
1704
1705 DSS_INFO_LOG(("setting up signal handlers\n"));
1706 signal_pipe = signal_init(); /* always successful */
1707 ret = install_sighandler(SIGINT);
1708 if (ret < 0)
1709 return ret;
1710 ret = install_sighandler(SIGTERM);
1711 if (ret < 0)
1712 return ret;
1713 return install_sighandler(SIGCHLD);
1714 }
1715
1716 static void handle_version_and_help(void)
1717 {
1718 char *txt;
1719
1720 if (OPT_GIVEN(DSS, DETAILED_HELP))
1721 txt = lls_long_help(CMD_PTR(DSS));
1722 else if (OPT_GIVEN(DSS, HELP))
1723 txt = lls_short_help(CMD_PTR(DSS));
1724 else if (OPT_GIVEN(DSS, VERSION))
1725 txt = dss_strdup(VERSION_STRING);
1726 else
1727 return;
1728 printf("%s", txt);
1729 free(txt);
1730 exit(EXIT_SUCCESS);
1731 }
1732
1733 static void show_subcommand_summary(void)
1734 {
1735 const struct lls_command *cmd;
1736 int i;
1737
1738 printf("Available subcommands:\n");
1739 for (i = 1; (cmd = lls_cmd(i, dss_suite)); i++) {
1740 const char *name = lls_command_name(cmd);
1741 const char *purpose = lls_purpose(cmd);
1742 printf("%-10s%s\n", name, purpose);
1743 }
1744 exit(EXIT_SUCCESS);
1745 }
1746
1747 int main(int argc, char **argv)
1748 {
1749 int ret;
1750 char *errctx = NULL;
1751 unsigned num_inputs;
1752 const struct dss_user_data *ud;
1753
1754 ret = lls_parse(argc, argv, CMD_PTR(DSS), &cmdline_lpr, &errctx);
1755 if (ret < 0) {
1756 ret = lopsub_error(ret, &errctx);
1757 goto out;
1758 }
1759 lpr = cmdline_lpr;
1760 ret = parse_config_file(false /* no SIGHUP */, CMD_PTR(DSS));
1761 if (ret < 0)
1762 goto out;
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);
1768 if (ret < 0) {
1769 ret = lopsub_error(ret, &errctx);
1770 goto out;
1771 }
1772 subcmd = lls_cmd(ret, dss_suite);
1773 ret = lls_parse(num_inputs, argv + argc - num_inputs, subcmd,
1774 &cmdline_sublpr, &errctx);
1775 if (ret < 0) {
1776 ret = lopsub_error(ret, &errctx);
1777 goto out;
1778 }
1779 sublpr = cmdline_sublpr;
1780 ret = parse_config_file(false /* no SIGHUP */, subcmd);
1781 if (ret < 0)
1782 goto out;
1783 ret = check_config();
1784 if (ret < 0)
1785 goto out;
1786 ret = setup_signal_handling();
1787 if (ret < 0)
1788 goto out;
1789 ud = lls_user_data(subcmd);
1790 ret = ud->handler();
1791 signal_shutdown();
1792 out:
1793 if (ret < 0) {
1794 if (errctx)
1795 DSS_ERROR_LOG(("%s\n", errctx));
1796 DSS_EMERG_LOG(("%s\n", dss_strerror(-ret)));
1797 }
1798 free(errctx);
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, subcmd);
1803 if (sublpr != cmdline_sublpr)
1804 lls_free_parse_result(cmdline_sublpr, subcmd);
1805 exit(ret >= 0? EXIT_SUCCESS : EXIT_FAILURE);
1806 }