d2afc10d59d266e0db54cdae04c283feca68c306
[dss.git] / dss.c
1 /*
2 * Copyright (C) 2008 Andre Noll <maan@systemlinux.org>
3 *
4 * Licensed under the GPL v2. For licencing details see COPYING.
5 */
6 #include <string.h>
7 #include <stdlib.h>
8 #include <stdarg.h>
9 #include <assert.h>
10 #include <errno.h>
11 #include <sys/types.h>
12 #include <signal.h>
13 #include <ctype.h>
14 #include <sys/stat.h>
15 #include <unistd.h>
16 #include <inttypes.h>
17 #include <sys/time.h>
18 #include <time.h>
19 #include <sys/wait.h>
20 #include <fnmatch.h>
21 #include <limits.h>
22
23
24 #include "gcc-compat.h"
25 #include "cmdline.h"
26 #include "log.h"
27 #include "string.h"
28 #include "error.h"
29 #include "fd.h"
30 #include "exec.h"
31 #include "daemon.h"
32 #include "signal.h"
33 #include "df.h"
34 #include "time.h"
35 #include "snap.h"
36
37 /** Command line and config file options. */
38 static struct gengetopt_args_info conf;
39 /** Non-NULL if we log to a file. */
40 static FILE *logfile;
41 /** The read end of the signal pipe */
42 static int signal_pipe;
43 /** Process id of current pre-create-hook/rsync/post-create-hook process. */
44 static pid_t create_pid;
45 /** Whether the pre-create-hook/rsync/post-create-hook is currently stopped. */
46 static int create_process_stopped;
47 /** Process id of current pre-remove/rm/post-remove process. */
48 static pid_t remove_pid;
49 /** When the next snapshot is due. */
50 static struct timeval next_snapshot_time;
51 /** When to try to remove something. */
52 static struct timeval next_removal_check;
53 /** Creation time of the snapshot currently being created. */
54 static int64_t current_snapshot_creation_time;
55 /* The snapshot currently being removed. */
56 struct snapshot *snapshot_currently_being_removed;
57 /** Needed by the post-create hook. */
58 static char *path_to_last_complete_snapshot;
59 /** \sa \ref snap.h for details. */
60 enum hook_status snapshot_creation_status;
61 /** \sa \ref snap.h for details. */
62 enum hook_status snapshot_removal_status;
63
64
65 DEFINE_DSS_ERRLIST;
66
67
68 /* a litte cpp magic helps to DRY */
69 #define COMMANDS \
70 COMMAND(ls) \
71 COMMAND(create) \
72 COMMAND(prune) \
73 COMMAND(run)
74 #define COMMAND(x) static int com_ ##x(void);
75 COMMANDS
76 #undef COMMAND
77 #define COMMAND(x) if (conf.x ##_given) return com_ ##x();
78 static int call_command_handler(void)
79 {
80 COMMANDS
81 DSS_EMERG_LOG("BUG: did not find command handler\n");
82 return -E_BUG;
83 }
84 #undef COMMAND
85 #undef COMMANDS
86
87 /**
88 * The log function of dss.
89 *
90 * \param ll Loglevel.
91 * \param fml Usual format string.
92 *
93 * All DSS_XXX_LOG() macros use this function.
94 */
95 __printf_2_3 void dss_log(int ll, const char* fmt,...)
96 {
97 va_list argp;
98 FILE *outfd;
99 struct tm *tm;
100 time_t t1;
101 char str[255] = "";
102
103 if (ll < conf.loglevel_arg)
104 return;
105 outfd = logfile? logfile : stderr;
106 time(&t1);
107 tm = localtime(&t1);
108 strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
109 fprintf(outfd, "%s ", str);
110 if (conf.loglevel_arg <= INFO)
111 fprintf(outfd, "%i: ", ll);
112 va_start(argp, fmt);
113 vfprintf(outfd, fmt, argp);
114 va_end(argp);
115 }
116
117 /**
118 * Print a message either to stdout or to the log file.
119 */
120 static __printf_1_2 void dss_msg(const char* fmt,...)
121 {
122 FILE *outfd = conf.daemon_given? logfile : stdout;
123 va_list argp;
124 va_start(argp, fmt);
125 vfprintf(outfd, fmt, argp);
126 va_end(argp);
127 }
128
129 static int disk_space_low(void)
130 {
131 struct disk_space ds;
132 int ret = get_disk_space(".", &ds);
133
134 if (ret < 0)
135 return ret;
136 if (conf.min_free_mb_arg)
137 if (ds.free_mb < conf.min_free_mb_arg)
138 return 1;
139 if (conf.min_free_percent_arg)
140 if (ds.percent_free < conf.min_free_percent_arg)
141 return 1;
142 if (conf.min_free_percent_inodes_arg)
143 if (ds.percent_free_inodes < conf.min_free_percent_inodes_arg)
144 return 1;
145 return 0;
146 }
147
148 static void dss_get_snapshot_list(struct snapshot_list *sl)
149 {
150 get_snapshot_list(sl, conf.unit_interval_arg, conf.num_intervals_arg);
151 }
152
153 static int next_snapshot_is_due(void)
154 {
155 struct timeval now, unit_interval = {.tv_sec = 24 * 3600 * conf.unit_interval_arg},
156 tmp, diff;
157 int64_t x = 0;
158 unsigned wanted = desired_number_of_snapshots(0, conf.num_intervals_arg),
159 num_complete_snapshots = 0;
160 int i, ret;
161 struct snapshot *s = NULL;
162 struct snapshot_list sl;
163
164 gettimeofday(&now, NULL);
165 if (tv_diff(&next_snapshot_time, &now, NULL) > 0)
166 return 0;
167 assert(snapshot_creation_status == HS_READY);
168 current_snapshot_creation_time = 0;
169 dss_get_snapshot_list(&sl);
170 FOR_EACH_SNAPSHOT(s, i, &sl) {
171 if (!(s->flags & SS_COMPLETE))
172 continue;
173 num_complete_snapshots++;
174 x += s->completion_time - s->creation_time;
175 }
176 assert(x >= 0);
177 if (num_complete_snapshots)
178 x /= num_complete_snapshots; /* avg time to create one snapshot */
179 x *= wanted; /* time to create all snapshots in interval 0 */
180 tmp.tv_sec = x;
181 tmp.tv_usec = 0;
182 ret = tv_diff(&unit_interval, &tmp, &diff); /* total sleep time per unit interval */
183 if (ret < 0 || !s) { /* unit_interval < tmp or no snapshot */
184 ret = 1;
185 goto out;
186 }
187
188 tv_divide(wanted, &diff, &tmp); /* sleep time between two snapshots */
189 diff.tv_sec = s->completion_time; /* completion time of the latest snapshot */
190 diff.tv_usec = 0;
191 tv_add(&diff, &tmp, &next_snapshot_time);
192 ret = (tv_diff(&now, &next_snapshot_time, &diff) < 0)? 0 : 1;
193 out:
194 free_snapshot_list(&sl);
195 if (ret == 0)
196 DSS_DEBUG_LOG("next snapshot due in %lu seconds\n",
197 tv2ms(&diff) / 1000);
198 else
199 DSS_DEBUG_LOG("next snapshot: now\n");
200 return ret;
201 }
202
203 static int pre_create_hook(void)
204 {
205 int ret, fds[3] = {0, 0, 0};
206
207 assert(snapshot_creation_status == HS_READY);
208 if (!conf.pre_create_hook_given) {
209 snapshot_creation_status = HS_PRE_SUCCESS;
210 return 0;
211 }
212 DSS_DEBUG_LOG("executing %s\n", conf.pre_create_hook_arg);
213 ret = dss_exec_cmdline_pid(&create_pid,
214 conf.pre_create_hook_arg, fds);
215 if (ret < 0)
216 return ret;
217 snapshot_creation_status = HS_PRE_RUNNING;
218 return ret;
219 }
220
221 static int pre_remove_hook(struct snapshot *s, const char *why)
222 {
223 int ret, fds[3] = {0, 0, 0};
224 char *cmd;
225
226 if (!s)
227 return 0;
228 DSS_DEBUG_LOG("%s snapshot %s\n", why, s->name);
229 assert(snapshot_removal_status == HS_READY);
230 assert(remove_pid == 0);
231 assert(!snapshot_currently_being_removed);
232
233 snapshot_currently_being_removed = dss_malloc(sizeof(struct snapshot));
234 *snapshot_currently_being_removed = *s;
235 snapshot_currently_being_removed->name = dss_strdup(s->name);
236
237 if (!conf.pre_remove_hook_given) {
238 snapshot_removal_status = HS_PRE_SUCCESS;
239 return 0;
240 }
241 cmd = make_message("%s %s/%s", conf.pre_remove_hook_arg,
242 conf.dest_dir_arg, s->name);
243 DSS_DEBUG_LOG("executing %s\n", cmd);
244 ret = dss_exec_cmdline_pid(&remove_pid,
245 conf.pre_remove_hook_arg, fds);
246 free(cmd);
247 if (ret < 0)
248 return ret;
249 snapshot_removal_status = HS_PRE_RUNNING;
250 return ret;
251 }
252
253 static int exec_rm(void)
254 {
255 struct snapshot *s = snapshot_currently_being_removed;
256 int fds[3] = {0, 0, 0};
257 char *new_name = being_deleted_name(s);
258 char *argv[] = {"rm", "-rf", new_name, NULL};
259 int ret;
260
261 assert(snapshot_removal_status == HS_PRE_SUCCESS);
262 assert(remove_pid == 0);
263
264 DSS_NOTICE_LOG("removing %s (interval = %i)\n", s->name, s->interval);
265 ret = dss_rename(s->name, new_name);
266 if (ret < 0)
267 goto out;
268 ret = dss_exec(&remove_pid, argv[0], argv, fds);
269 if (ret < 0)
270 goto out;
271 snapshot_removal_status = HS_RUNNING;
272 out:
273 free(new_name);
274 return ret;
275 }
276
277 static int snapshot_is_being_created(struct snapshot *s)
278 {
279 return s->creation_time == current_snapshot_creation_time;
280 }
281
282 static struct snapshot *find_orphaned_snapshot(struct snapshot_list *sl)
283 {
284 struct snapshot *s;
285 int i;
286
287 DSS_DEBUG_LOG("looking for orphaned snapshots\n");
288 FOR_EACH_SNAPSHOT(s, i, sl) {
289 if (snapshot_is_being_created(s))
290 continue;
291 /*
292 * We know that no rm is currently running, so if s is marked
293 * as being deleted, a previously started rm must have failed.
294 */
295 if (s->flags & SS_BEING_DELETED)
296 return s;
297
298 if (s->flags & SS_COMPLETE) /* good snapshot */
299 continue;
300 /*
301 * This snapshot is incomplete and it is not the snapshot
302 * currently being created. However, we must not remove it if
303 * rsync is about to be restarted. As only the newest snapshot
304 * can be restarted, this snapshot is orphaned if it is not the
305 * newest snapshot or if we are not about to restart rsync.
306 */
307 if (get_newest_snapshot(sl) != s)
308 return s;
309 if (snapshot_creation_status != HS_NEEDS_RESTART)
310 return s;
311 }
312 /* no orphaned snapshots */
313 return NULL;
314 }
315
316 /*
317 * return: 0: no redundant snapshots, 1: rm process started, negative: error
318 */
319 static struct snapshot *find_redundant_snapshot(struct snapshot_list *sl)
320 {
321 int i, interval;
322 struct snapshot *s;
323 unsigned missing = 0;
324
325 DSS_DEBUG_LOG("looking for intervals containing too many snapshots\n");
326 for (interval = conf.num_intervals_arg - 1; interval >= 0; interval--) {
327 unsigned keep = desired_number_of_snapshots(interval, conf.num_intervals_arg);
328 unsigned num = sl->interval_count[interval];
329 struct snapshot *victim = NULL, *prev = NULL;
330 int64_t score = LONG_MAX;
331
332 if (keep >= num)
333 missing += keep - num;
334 // DSS_DEBUG_LOG("interval %i: keep: %u, have: %u, missing: %u\n",
335 // interval, keep, num, missing);
336 if (keep + missing >= num)
337 continue;
338 /* redundant snapshot in this interval, pick snapshot with lowest score */
339 FOR_EACH_SNAPSHOT(s, i, sl) {
340 int64_t this_score;
341
342 if (snapshot_is_being_created(s))
343 continue;
344 //DSS_DEBUG_LOG("checking %s\n", s->name);
345 if (s->interval > interval) {
346 prev = s;
347 continue;
348 }
349 if (s->interval < interval)
350 break;
351 if (!victim) {
352 victim = s;
353 prev = s;
354 continue;
355 }
356 assert(prev);
357 /* check if s is a better victim */
358 this_score = s->creation_time - prev->creation_time;
359 assert(this_score >= 0);
360 //DSS_DEBUG_LOG("%s: score %lli\n", s->name, (long long)score);
361 if (this_score < score) {
362 score = this_score;
363 victim = s;
364 }
365 prev = s;
366 }
367 assert(victim);
368 return victim;
369 }
370 return NULL;
371 }
372
373 static struct snapshot *find_outdated_snapshot(struct snapshot_list *sl)
374 {
375 int i;
376 struct snapshot *s;
377
378 DSS_DEBUG_LOG("looking for snapshots belonging to intervals greater than %d\n",
379 conf.num_intervals_arg);
380 FOR_EACH_SNAPSHOT(s, i, sl) {
381 if (snapshot_is_being_created(s))
382 continue;
383 if (s->interval <= conf.num_intervals_arg)
384 continue;
385 return s;
386 }
387 return NULL;
388 }
389
390 struct snapshot *find_oldest_removable_snapshot(struct snapshot_list *sl)
391 {
392 struct snapshot *s = get_oldest_snapshot(sl);
393
394 if (!s) /* no snapshot found */
395 return NULL;
396 DSS_INFO_LOG("oldest snapshot: %s\n", s->name);
397 if (snapshot_is_being_created(s))
398 return NULL;
399 return s;
400 }
401
402 static int rename_incomplete_snapshot(int64_t start)
403 {
404 char *old_name;
405 int ret;
406
407 free(path_to_last_complete_snapshot);
408 ret = complete_name(start, get_current_time(),
409 &path_to_last_complete_snapshot);
410 if (ret < 0)
411 return ret;
412 old_name = incomplete_name(start);
413 ret = dss_rename(old_name, path_to_last_complete_snapshot);
414 if (ret >= 0)
415 DSS_NOTICE_LOG("%s -> %s\n", old_name,
416 path_to_last_complete_snapshot);
417 free(old_name);
418 return ret;
419 }
420
421 static int try_to_free_disk_space(int low_disk_space)
422 {
423 int ret;
424 struct snapshot_list sl;
425 struct snapshot *victim;
426 struct timeval now;
427 const char *why;
428
429 gettimeofday(&now, NULL);
430 if (tv_diff(&next_removal_check, &now, NULL) > 0)
431 return 0;
432 if (!low_disk_space && conf.keep_redundant_given)
433 return 0;
434 dss_get_snapshot_list(&sl);
435 why = "outdated";
436 victim = find_outdated_snapshot(&sl);
437 if (victim)
438 goto remove;
439 why = "redundant";
440 victim = find_redundant_snapshot(&sl);
441 if (victim)
442 goto remove;
443 /* try harder only if disk space is low */
444 ret = 0;
445 if (!low_disk_space)
446 goto out;
447 why = "orphaned";
448 victim = find_orphaned_snapshot(&sl);
449 if (victim)
450 goto remove;
451 DSS_WARNING_LOG("disk space low and nothing obvious to remove\n");
452 victim = find_oldest_removable_snapshot(&sl);
453 if (victim)
454 goto remove;
455 DSS_CRIT_LOG("uhuhu: not enough disk space for a single snapshot\n");
456 ret = -ERRNO_TO_DSS_ERROR(ENOSPC);
457 goto out;
458 remove:
459 ret = pre_remove_hook(victim, why);
460 out:
461 free_snapshot_list(&sl);
462 return ret;
463 }
464
465 static int post_create_hook(void)
466 {
467 int ret, fds[3] = {0, 0, 0};
468 char *cmd;
469
470 if (!conf.post_create_hook_given) {
471 snapshot_creation_status = HS_READY;
472 return 0;
473 }
474 cmd = make_message("%s %s/%s", conf.post_create_hook_arg,
475 conf.dest_dir_arg, path_to_last_complete_snapshot);
476 DSS_NOTICE_LOG("executing %s\n", cmd);
477 ret = dss_exec_cmdline_pid(&create_pid, cmd, fds);
478 free(cmd);
479 if (ret < 0)
480 return ret;
481 snapshot_creation_status = HS_POST_RUNNING;
482 return ret;
483 }
484
485 static int post_remove_hook(void)
486 {
487 int ret, fds[3] = {0, 0, 0};
488 char *cmd;
489 struct snapshot *s = snapshot_currently_being_removed;
490
491 assert(s);
492
493 if (!conf.post_remove_hook_given) {
494 snapshot_removal_status = HS_READY;
495 return 0;
496 }
497 cmd = make_message("%s %s/%s", conf.post_remove_hook_arg,
498 conf.dest_dir_arg, s->name);
499 DSS_NOTICE_LOG("executing %s\n", cmd);
500 ret = dss_exec_cmdline_pid(&remove_pid, cmd, fds);
501 free(cmd);
502 if (ret < 0)
503 return ret;
504 snapshot_removal_status = HS_POST_RUNNING;
505 return ret;
506 }
507
508 static void kill_process(pid_t pid)
509 {
510 if (!pid)
511 return;
512 DSS_WARNING_LOG("sending SIGTERM to pid %d\n", (int)pid);
513 kill(pid, SIGTERM);
514 }
515
516 static void stop_create_process(void)
517 {
518 if (!create_pid || create_process_stopped)
519 return;
520 kill(SIGSTOP, create_pid);
521 create_process_stopped = 1;
522 }
523
524 static void restart_create_process(void)
525 {
526 if (!create_pid || !create_process_stopped)
527 return;
528 kill (SIGCONT, create_pid);
529 create_process_stopped = 0;
530 }
531
532 /**
533 * Print a log message about the exit status of a child.
534 */
535 static void log_termination_msg(pid_t pid, int status)
536 {
537 if (WIFEXITED(status))
538 DSS_INFO_LOG("child %i exited. Exit status: %i\n", (int)pid,
539 WEXITSTATUS(status));
540 else if (WIFSIGNALED(status))
541 DSS_NOTICE_LOG("child %i was killed by signal %i\n", (int)pid,
542 WTERMSIG(status));
543 else
544 DSS_WARNING_LOG("child %i terminated abormally\n", (int)pid);
545 }
546
547 static int wait_for_process(pid_t pid, int *status)
548 {
549 int ret;
550
551 DSS_DEBUG_LOG("Waiting for process %d to terminate\n", (int)pid);
552 for (;;) {
553 fd_set rfds;
554
555 FD_ZERO(&rfds);
556 FD_SET(signal_pipe, &rfds);
557 ret = dss_select(signal_pipe + 1, &rfds, NULL, NULL);
558 if (ret < 0)
559 break;
560 ret = next_signal();
561 if (!ret)
562 continue;
563 if (ret == SIGCHLD) {
564 ret = waitpid(pid, status, 0);
565 if (ret >= 0)
566 break;
567 if (errno != EINTR) { /* error */
568 ret = -ERRNO_TO_DSS_ERROR(errno);
569 break;
570 }
571 }
572 /* SIGINT or SIGTERM */
573 DSS_WARNING_LOG("sending SIGTERM to pid %d\n", (int)pid);
574 kill(pid, SIGTERM);
575 }
576 if (ret < 0)
577 DSS_ERROR_LOG("failed to wait for process %d\n", (int)pid);
578 else
579 log_termination_msg(pid, *status);
580 return ret;
581 }
582
583 static void handle_pre_remove_exit(int status)
584 {
585 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
586 snapshot_removal_status = HS_READY;
587 gettimeofday(&next_removal_check, NULL);
588 next_removal_check.tv_sec += 60;
589 return;
590 }
591 snapshot_removal_status = HS_PRE_SUCCESS;
592 }
593
594 static int handle_rm_exit(int status)
595 {
596 if (!WIFEXITED(status)) {
597 snapshot_removal_status = HS_READY;
598 return -E_INVOLUNTARY_EXIT;
599 }
600 if (WEXITSTATUS(status)) {
601 snapshot_removal_status = HS_READY;
602 return -E_BAD_EXIT_CODE;
603 }
604 if (conf.post_remove_hook_given)
605 snapshot_removal_status = HS_SUCCESS;
606 else
607 snapshot_removal_status = HS_READY;
608 return 1;
609 }
610
611 static void handle_post_remove_exit(void)
612 {
613 snapshot_removal_status = HS_READY;
614 }
615
616 static int handle_remove_exit(int status)
617 {
618 int ret;
619 struct snapshot *s = snapshot_currently_being_removed;
620
621 assert(s);
622 switch (snapshot_removal_status) {
623 case HS_PRE_RUNNING:
624 handle_pre_remove_exit(status);
625 ret = 1;
626 break;
627 case HS_RUNNING:
628 ret = handle_rm_exit(status);
629 break;
630 case HS_POST_RUNNING:
631 handle_post_remove_exit();
632 ret = 1;
633 break;
634 default:
635 ret = -E_BUG;
636 }
637 if (snapshot_removal_status == HS_READY) {
638 free(s->name);
639 free(s);
640 snapshot_currently_being_removed = NULL;
641 }
642 remove_pid = 0;
643 return ret;
644 }
645
646 static int wait_for_remove_process(void)
647 {
648 int status, ret;
649
650 assert(remove_pid);
651 assert(
652 snapshot_removal_status == HS_PRE_RUNNING ||
653 snapshot_removal_status == HS_RUNNING ||
654 snapshot_removal_status == HS_POST_RUNNING
655 );
656 ret = wait_for_process(remove_pid, &status);
657 if (ret < 0)
658 return ret;
659 return handle_remove_exit(status);
660 }
661
662 static int handle_rsync_exit(int status)
663 {
664 int es, ret;
665
666 if (!WIFEXITED(status)) {
667 DSS_ERROR_LOG("rsync process %d died involuntary\n", (int)create_pid);
668 ret = -E_INVOLUNTARY_EXIT;
669 snapshot_creation_status = HS_READY;
670 goto out;
671 }
672 es = WEXITSTATUS(status);
673 /*
674 * Restart rsync on non-fatal errors:
675 * 12: Error in rsync protocol data stream
676 * 13: Errors with program diagnostics
677 */
678 if (es == 12 || es == 13) {
679 DSS_WARNING_LOG("rsync process %d returned %d -- restarting\n",
680 (int)create_pid, es);
681 snapshot_creation_status = HS_NEEDS_RESTART;
682 gettimeofday(&next_snapshot_time, NULL);
683 next_snapshot_time.tv_sec += 60;
684 ret = 1;
685 goto out;
686 }
687 if (es != 0 && es != 23 && es != 24) {
688 DSS_ERROR_LOG("rsync process %d returned %d\n", (int)create_pid, es);
689 ret = -E_BAD_EXIT_CODE;
690 snapshot_creation_status = HS_READY;
691 goto out;
692 }
693 ret = rename_incomplete_snapshot(current_snapshot_creation_time);
694 if (ret < 0)
695 goto out;
696 snapshot_creation_status = HS_SUCCESS;
697 out:
698 create_pid = 0;
699 create_process_stopped = 0;
700 return ret;
701 }
702
703 static int handle_pre_create_hook_exit(int status)
704 {
705 int es, ret;
706 static int warn_count;
707
708 if (!WIFEXITED(status)) {
709 snapshot_creation_status = HS_READY;
710 ret = -E_INVOLUNTARY_EXIT;
711 goto out;
712 }
713 es = WEXITSTATUS(status);
714 if (es) {
715 if (!warn_count--) {
716 DSS_NOTICE_LOG("pre_create_hook %s returned %d\n",
717 conf.pre_create_hook_arg, es);
718 DSS_NOTICE_LOG("deferring snapshot creation...\n");
719 warn_count = 60; /* warn only once per hour */
720 }
721 gettimeofday(&next_snapshot_time, NULL);
722 next_snapshot_time.tv_sec += 60;
723 snapshot_creation_status = HS_READY;
724 ret = 0;
725 goto out;
726 }
727 warn_count = 0;
728 snapshot_creation_status = HS_PRE_SUCCESS;
729 ret = 1;
730 out:
731 create_pid = 0;
732 return ret;
733 }
734
735 static int handle_sigchld(void)
736 {
737 pid_t pid;
738 int status, ret = reap_child(&pid, &status);
739
740 if (ret <= 0)
741 return ret;
742
743 if (pid == create_pid) {
744 switch (snapshot_creation_status) {
745 case HS_PRE_RUNNING:
746 return handle_pre_create_hook_exit(status);
747 case HS_RUNNING:
748 return handle_rsync_exit(status);
749 case HS_POST_RUNNING:
750 snapshot_creation_status = HS_READY;
751 return 1;
752 default:
753 DSS_EMERG_LOG("BUG: create can't die in status %d\n",
754 snapshot_creation_status);
755 return -E_BUG;
756 }
757 }
758 if (pid == remove_pid) {
759 ret = handle_remove_exit(status);
760 if (ret < 0)
761 return ret;
762 return ret;
763 }
764 DSS_EMERG_LOG("BUG: unknown process %d died\n", (int)pid);
765 return -E_BUG;
766 }
767
768 static int check_config(void)
769 {
770 if (conf.unit_interval_arg <= 0) {
771 DSS_ERROR_LOG("bad unit interval: %i\n", conf.unit_interval_arg);
772 return -E_INVALID_NUMBER;
773 }
774 DSS_DEBUG_LOG("unit interval: %i day(s)\n", conf.unit_interval_arg);
775 if (conf.num_intervals_arg <= 0) {
776 DSS_ERROR_LOG("bad number of intervals %i\n", conf.num_intervals_arg);
777 return -E_INVALID_NUMBER;
778 }
779 DSS_DEBUG_LOG("number of intervals: %i\n", conf.num_intervals_arg);
780 return 1;
781 }
782
783 static int parse_config_file(int override)
784 {
785 int ret;
786 char *config_file;
787 struct stat statbuf;
788 char *old_logfile_arg = NULL;
789 int old_daemon_given = 0;
790
791 if (conf.config_file_given)
792 config_file = dss_strdup(conf.config_file_arg);
793 else {
794 char *home = get_homedir();
795 config_file = make_message("%s/.dssrc", home);
796 free(home);
797 }
798 if (override) { /* SIGHUP */
799 if (conf.logfile_given)
800 old_logfile_arg = dss_strdup(conf.logfile_arg);
801 old_daemon_given = conf.daemon_given;
802 }
803
804 ret = stat(config_file, &statbuf);
805 if (ret && conf.config_file_given) {
806 ret = -ERRNO_TO_DSS_ERROR(errno);
807 DSS_ERROR_LOG("failed to stat config file %s\n", config_file);
808 goto out;
809 }
810 if (!ret) {
811 struct cmdline_parser_params params = {
812 .override = override,
813 .initialize = 0,
814 .check_required = 1,
815 .check_ambiguity = 0,
816 .print_errors = 1
817 };
818 if (override) { /* invalidate all rsync options */
819 int i;
820
821 for (i = 0; i < conf.rsync_option_given; i++) {
822 free(conf.rsync_option_arg[i]);
823 conf.rsync_option_arg[i] = NULL;
824 }
825 conf.rsync_option_given = 0;
826 }
827 cmdline_parser_config_file(config_file, &conf, &params);
828 }
829 ret = check_config();
830 if (ret < 0)
831 goto out;
832 if (override) {
833 /* don't change daemon mode on SIGHUP */
834 conf.daemon_given = old_daemon_given;
835 close_log(logfile);
836 logfile = NULL;
837 if (conf.logfile_given)
838 free(old_logfile_arg);
839 else if (conf.daemon_given) { /* re-use old logfile */
840 conf.logfile_arg = old_logfile_arg;
841 conf.logfile_given = 1;
842 }
843 }
844 if (conf.logfile_given) {
845 logfile = open_log(conf.logfile_arg);
846 log_welcome(conf.loglevel_arg);
847 }
848 DSS_DEBUG_LOG("loglevel: %d\n", conf.loglevel_arg);
849 // cmdline_parser_dump(logfile? logfile : stdout, &conf);
850 out:
851 free(config_file);
852 if (ret < 0)
853 DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
854 return ret;
855 }
856
857 static int change_to_dest_dir(void)
858 {
859 DSS_INFO_LOG("changing cwd to %s\n", conf.dest_dir_arg);
860 return dss_chdir(conf.dest_dir_arg);
861 }
862
863 static int handle_sighup(void)
864 {
865 int ret;
866
867 DSS_NOTICE_LOG("SIGHUP\n");
868 ret = parse_config_file(1);
869 if (ret < 0)
870 return ret;
871 return change_to_dest_dir();
872 }
873
874 static int handle_signal(void)
875 {
876 int sig, ret = next_signal();
877
878 if (ret <= 0)
879 goto out;
880 sig = ret;
881 switch (sig) {
882 case SIGINT:
883 case SIGTERM:
884 restart_create_process();
885 kill_process(create_pid);
886 kill_process(remove_pid);
887 ret = -E_SIGNAL;
888 break;
889 case SIGHUP:
890 ret = handle_sighup();
891 break;
892 case SIGCHLD:
893 ret = handle_sigchld();
894 break;
895 }
896 out:
897 if (ret < 0)
898 DSS_ERROR_LOG("%s\n", dss_strerror(-ret));
899 return ret;
900 }
901
902 /*
903 * We can not use rsync locally if the local user is different from the remote
904 * user or if the src dir is not on the local host (or both).
905 */
906 static int use_rsync_locally(char *logname)
907 {
908 char *h = conf.remote_host_arg;
909
910 if (strcmp(h, "localhost") && strcmp(h, "127.0.0.1"))
911 return 0;
912 if (conf.remote_user_given && strcmp(conf.remote_user_arg, logname))
913 return 0;
914 return 1;
915 }
916
917 static void create_rsync_argv(char ***argv, int64_t *num)
918 {
919 char *logname, *newest;
920 int i = 0, j;
921 struct snapshot_list sl;
922
923 dss_get_snapshot_list(&sl);
924 newest = name_of_newest_complete_snapshot(&sl);
925 free_snapshot_list(&sl);
926
927 *argv = dss_malloc((15 + conf.rsync_option_given) * sizeof(char *));
928 (*argv)[i++] = dss_strdup("rsync");
929 (*argv)[i++] = dss_strdup("-aq");
930 (*argv)[i++] = dss_strdup("--delete");
931 for (j = 0; j < conf.rsync_option_given; j++)
932 (*argv)[i++] = dss_strdup(conf.rsync_option_arg[j]);
933 if (newest) {
934 DSS_INFO_LOG("using %s as reference snapshot\n", newest);
935 (*argv)[i++] = make_message("--link-dest=../%s", newest);
936 free(newest);
937 } else
938 DSS_INFO_LOG("no previous snapshot found\n");
939 logname = dss_logname();
940 if (use_rsync_locally(logname))
941 (*argv)[i++] = dss_strdup(conf.source_dir_arg);
942 else
943 (*argv)[i++] = make_message("%s@%s:%s/", conf.remote_user_given?
944 conf.remote_user_arg : logname,
945 conf.remote_host_arg, conf.source_dir_arg);
946 free(logname);
947 *num = get_current_time();
948 (*argv)[i++] = incomplete_name(*num);
949 (*argv)[i++] = NULL;
950 for (j = 0; j < i; j++)
951 DSS_DEBUG_LOG("argv[%d] = %s\n", j, (*argv)[j]);
952 }
953
954 static void free_rsync_argv(char **argv)
955 {
956 int i;
957
958 if (!argv)
959 return;
960 for (i = 0; argv[i]; i++)
961 free(argv[i]);
962 free(argv);
963 }
964
965 static int create_snapshot(char **argv)
966 {
967 int ret, fds[3] = {0, 0, 0};
968 char *name;
969
970 name = incomplete_name(current_snapshot_creation_time);
971 DSS_NOTICE_LOG("creating new snapshot %s\n", name);
972 free(name);
973 ret = dss_exec(&create_pid, argv[0], argv, fds);
974 if (ret < 0)
975 return ret;
976 snapshot_creation_status = HS_RUNNING;
977 return ret;
978 }
979
980 static int select_loop(void)
981 {
982 int ret;
983 /* check every 60 seconds for free disk space */
984 struct timeval tv;
985 char **rsync_argv = NULL;
986
987 for (;;) {
988 fd_set rfds;
989 int low_disk_space;
990 struct timeval *tvp;
991
992 if (remove_pid)
993 tvp = NULL; /* sleep until rm hook/process dies */
994 else { /* sleep one minute */
995 tv.tv_sec = 60;
996 tv.tv_usec = 0;
997 tvp = &tv;
998 }
999 FD_ZERO(&rfds);
1000 FD_SET(signal_pipe, &rfds);
1001 DSS_DEBUG_LOG("tvp: %p, tv_sec : %lu\n", tvp, (long unsigned) tv.tv_sec);
1002 ret = dss_select(signal_pipe + 1, &rfds, NULL, tvp);
1003 if (ret < 0)
1004 goto out;
1005 if (FD_ISSET(signal_pipe, &rfds)) {
1006 ret = handle_signal();
1007 if (ret < 0)
1008 goto out;
1009 }
1010 if (remove_pid)
1011 continue;
1012 if (snapshot_removal_status == HS_PRE_SUCCESS) {
1013 ret = exec_rm();
1014 if (ret < 0)
1015 goto out;
1016 continue;
1017 }
1018 if (snapshot_removal_status == HS_SUCCESS) {
1019 ret = post_remove_hook();
1020 if (ret < 0)
1021 goto out;
1022 continue;
1023 }
1024 ret = disk_space_low();
1025 if (ret < 0)
1026 goto out;
1027 low_disk_space = ret;
1028 ret = try_to_free_disk_space(low_disk_space);
1029 if (ret < 0)
1030 goto out;
1031 if (snapshot_removal_status != HS_READY) {
1032 stop_create_process();
1033 continue;
1034 }
1035 restart_create_process();
1036 switch (snapshot_creation_status) {
1037 case HS_READY:
1038 if (!next_snapshot_is_due())
1039 continue;
1040 ret = pre_create_hook();
1041 if (ret < 0)
1042 goto out;
1043 continue;
1044 case HS_PRE_RUNNING:
1045 case HS_RUNNING:
1046 case HS_POST_RUNNING:
1047 continue;
1048 case HS_PRE_SUCCESS:
1049 free_rsync_argv(rsync_argv);
1050 create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
1051 /* fall through */
1052 case HS_NEEDS_RESTART:
1053 ret = create_snapshot(rsync_argv);
1054 if (ret < 0)
1055 goto out;
1056 continue;
1057 case HS_SUCCESS:
1058 ret = post_create_hook();
1059 if (ret < 0)
1060 goto out;
1061 continue;
1062 }
1063 }
1064 out:
1065 return ret;
1066 }
1067
1068 static void exit_hook(int exit_code)
1069 {
1070 int fds[3] = {0, 0, 0};
1071 char *argv[] = {conf.exit_hook_arg, dss_strerror(-exit_code), NULL};
1072 pid_t pid;
1073
1074 if (!conf.exit_hook_given)
1075 return;
1076 DSS_NOTICE_LOG("executing %s %s\n", argv[0], argv[1]);
1077 dss_exec(&pid, conf.exit_hook_arg, argv, fds);
1078 }
1079
1080 static int com_run(void)
1081 {
1082 int ret;
1083
1084 if (conf.dry_run_given) {
1085 DSS_ERROR_LOG("dry_run not supported by this command\n");
1086 return -E_SYNTAX;
1087 }
1088 ret = install_sighandler(SIGHUP);
1089 if (ret < 0)
1090 return ret;
1091 ret = select_loop();
1092 if (ret >= 0) /* impossible */
1093 ret = -E_BUG;
1094 exit_hook(ret);
1095 return ret;
1096 }
1097
1098 static int com_prune(void)
1099 {
1100 int ret;
1101 struct snapshot_list sl;
1102 struct snapshot *victim;
1103 struct disk_space ds;
1104 const char *why;
1105
1106 ret = get_disk_space(".", &ds);
1107 if (ret < 0)
1108 return ret;
1109 log_disk_space(&ds);
1110 dss_get_snapshot_list(&sl);
1111 why = "outdated";
1112 victim = find_outdated_snapshot(&sl);
1113 if (victim)
1114 goto rm;
1115 why = "redundant";
1116 victim = find_redundant_snapshot(&sl);
1117 if (victim)
1118 goto rm;
1119 ret = 0;
1120 goto out;
1121 rm:
1122 if (conf.dry_run_given) {
1123 dss_msg("%s snapshot %s (interval = %i)\n",
1124 why, victim->name, victim->interval);
1125 ret = 0;
1126 goto out;
1127 }
1128 ret = pre_remove_hook(victim, why);
1129 if (ret < 0)
1130 goto out;
1131 if (snapshot_removal_status == HS_PRE_RUNNING) {
1132 ret = wait_for_remove_process();
1133 if (ret < 0)
1134 goto out;
1135 if (snapshot_removal_status != HS_PRE_SUCCESS)
1136 goto out;
1137 }
1138 ret = exec_rm();
1139 if (ret < 0)
1140 goto out;
1141 ret = wait_for_remove_process();
1142 if (ret < 0)
1143 goto out;
1144 if (snapshot_removal_status != HS_SUCCESS)
1145 goto out;
1146 ret = post_remove_hook();
1147 if (ret < 0)
1148 goto out;
1149 if (snapshot_removal_status != HS_POST_RUNNING)
1150 goto out;
1151 ret = wait_for_remove_process();
1152 if (ret < 0)
1153 goto out;
1154 ret = 1;
1155 out:
1156 free_snapshot_list(&sl);
1157 return ret;
1158 }
1159
1160 static int com_create(void)
1161 {
1162 int ret, status;
1163 char **rsync_argv;
1164
1165 if (conf.dry_run_given) {
1166 int i;
1167 char *msg = NULL;
1168 create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
1169 for (i = 0; rsync_argv[i]; i++) {
1170 char *tmp = msg;
1171 msg = make_message("%s%s%s", tmp? tmp : "",
1172 tmp? " " : "", rsync_argv[i]);
1173 free(tmp);
1174 }
1175 free_rsync_argv(rsync_argv);
1176 dss_msg("%s\n", msg);
1177 free(msg);
1178 return 1;
1179 }
1180 ret = pre_create_hook();
1181 if (ret < 0)
1182 return ret;
1183 if (create_pid) {
1184 ret = wait_for_process(create_pid, &status);
1185 if (ret < 0)
1186 return ret;
1187 ret = handle_pre_create_hook_exit(status);
1188 if (ret <= 0) /* error, or pre-create failed */
1189 return ret;
1190 }
1191 create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
1192 ret = create_snapshot(rsync_argv);
1193 if (ret < 0)
1194 goto out;
1195 ret = wait_for_process(create_pid, &status);
1196 if (ret < 0)
1197 goto out;
1198 ret = handle_rsync_exit(status);
1199 if (ret < 0)
1200 goto out;
1201 post_create_hook();
1202 if (create_pid)
1203 ret = wait_for_process(create_pid, &status);
1204 out:
1205 free_rsync_argv(rsync_argv);
1206 return ret;
1207 }
1208
1209 static int com_ls(void)
1210 {
1211 int i;
1212 struct snapshot_list sl;
1213 struct snapshot *s;
1214
1215 dss_get_snapshot_list(&sl);
1216 FOR_EACH_SNAPSHOT(s, i, &sl) {
1217 int64_t d = 0;
1218 if (s->flags & SS_COMPLETE)
1219 d = (s->completion_time - s->creation_time) / 60;
1220 dss_msg("%u\t%s\t%3" PRId64 ":%02" PRId64 "\n", s->interval, s->name, d/60, d%60);
1221 };
1222 free_snapshot_list(&sl);
1223 return 1;
1224 }
1225
1226 static int setup_signal_handling(void)
1227 {
1228 int ret;
1229
1230 DSS_INFO_LOG("setting up signal handlers\n");
1231 signal_pipe = signal_init(); /* always successful */
1232 ret = install_sighandler(SIGINT);
1233 if (ret < 0)
1234 return ret;
1235 ret = install_sighandler(SIGTERM);
1236 if (ret < 0)
1237 return ret;
1238 return install_sighandler(SIGCHLD);
1239 }
1240
1241 /**
1242 * The main function of dss.
1243 *
1244 * \param argc Usual argument count.
1245 * \param argv Usual argument vector.
1246 */
1247 int main(int argc, char **argv)
1248 {
1249 int ret;
1250 struct cmdline_parser_params params = {
1251 .override = 0,
1252 .initialize = 1,
1253 .check_required = 0,
1254 .check_ambiguity = 0,
1255 .print_errors = 1
1256 };
1257
1258 cmdline_parser_ext(argc, argv, &conf, &params); /* aborts on errors */
1259 ret = parse_config_file(0);
1260 if (ret < 0)
1261 goto out;
1262 if (conf.daemon_given)
1263 daemon_init();
1264 ret = change_to_dest_dir();
1265 if (ret < 0)
1266 goto out;
1267 ret = setup_signal_handling();
1268 if (ret < 0)
1269 goto out;
1270 ret = call_command_handler();
1271 out:
1272 if (ret < 0)
1273 DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
1274 exit(ret >= 0? EXIT_SUCCESS : EXIT_FAILURE);
1275 }