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