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