]> git.tuebingen.mpg.de Git - dss.git/blob - dss.c
Avoid busy loop on rsync exit status 12 or 13.
[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         current_snapshot_creation_time = 0;
165         dss_get_snapshot_list(&sl);
166         FOR_EACH_SNAPSHOT(s, i, &sl) {
167                 if (!(s->flags & SS_COMPLETE))
168                         continue;
169                 num_complete_snapshots++;
170                 x += s->completion_time - s->creation_time;
171         }
172         assert(x >= 0);
173
174         ret = now;
175         if (num_complete_snapshots == 0)
176                 goto out;
177         x /= num_complete_snapshots; /* avg time to create one snapshot */
178         if (unit_interval < x * wanted) /* oops, no sleep at all */
179                 goto out;
180         ret = s->completion_time + unit_interval / wanted - x;
181 out:
182         free_snapshot_list(&sl);
183         return ret;
184 }
185
186 static inline void invalidate_next_snapshot_time(void)
187 {
188         next_snapshot_time = 0;
189 }
190
191 static inline int next_snapshot_time_is_valid(void)
192 {
193         return next_snapshot_time != 0;
194 }
195
196 static int next_snapshot_is_due(void)
197 {
198         int64_t now = get_current_time();
199
200         if (!next_snapshot_time_is_valid())
201                 next_snapshot_time = compute_next_snapshot_time();
202         if (next_snapshot_time <= now) {
203                 DSS_DEBUG_LOG("next snapshot: now\n");
204                 return 1;
205         }
206         DSS_DEBUG_LOG("next snapshot due in %" PRId64 " seconds\n",
207                 next_snapshot_time - now);
208         return 0;
209 }
210
211 static int pre_create_hook(void)
212 {
213         int ret, fds[3] = {0, 0, 0};
214
215         assert(snapshot_creation_status == HS_READY);
216         /* make sure that the next snapshot time will be recomputed */
217         invalidate_next_snapshot_time();
218         if (!conf.pre_create_hook_given) {
219                 snapshot_creation_status = HS_PRE_SUCCESS;
220                 return 0;
221         }
222         DSS_DEBUG_LOG("executing %s\n", conf.pre_create_hook_arg);
223         ret = dss_exec_cmdline_pid(&create_pid,
224                 conf.pre_create_hook_arg, fds);
225         if (ret < 0)
226                 return ret;
227         snapshot_creation_status = HS_PRE_RUNNING;
228         return ret;
229 }
230
231 static int pre_remove_hook(struct snapshot *s, const char *why)
232 {
233         int ret, fds[3] = {0, 0, 0};
234         char *cmd;
235
236         if (!s)
237                 return 0;
238         DSS_DEBUG_LOG("%s snapshot %s\n", why, s->name);
239         assert(snapshot_removal_status == HS_READY);
240         assert(remove_pid == 0);
241         assert(!snapshot_currently_being_removed);
242
243         snapshot_currently_being_removed = dss_malloc(sizeof(struct snapshot));
244         *snapshot_currently_being_removed = *s;
245         snapshot_currently_being_removed->name = dss_strdup(s->name);
246
247         if (!conf.pre_remove_hook_given) {
248                 snapshot_removal_status = HS_PRE_SUCCESS;
249                 return 0;
250         }
251         cmd = make_message("%s %s/%s", conf.pre_remove_hook_arg,
252                 conf.dest_dir_arg, s->name);
253         DSS_DEBUG_LOG("executing %s\n", cmd);
254         ret = dss_exec_cmdline_pid(&remove_pid,
255                 conf.pre_remove_hook_arg, fds);
256         free(cmd);
257         if (ret < 0)
258                 return ret;
259         snapshot_removal_status = HS_PRE_RUNNING;
260         return ret;
261 }
262
263 static int exec_rm(void)
264 {
265         struct snapshot *s = snapshot_currently_being_removed;
266         int fds[3] = {0, 0, 0};
267         char *new_name = being_deleted_name(s);
268         char *argv[] = {"rm", "-rf", new_name, NULL};
269         int ret;
270
271         assert(snapshot_removal_status == HS_PRE_SUCCESS);
272         assert(remove_pid == 0);
273
274         DSS_NOTICE_LOG("removing %s (interval = %i)\n", s->name, s->interval);
275         ret = dss_rename(s->name, new_name);
276         if (ret < 0)
277                 goto out;
278         ret = dss_exec(&remove_pid, argv[0], argv, fds);
279         if (ret < 0)
280                 goto out;
281         snapshot_removal_status = HS_RUNNING;
282 out:
283         free(new_name);
284         return ret;
285 }
286
287 static int snapshot_is_being_created(struct snapshot *s)
288 {
289         return s->creation_time == current_snapshot_creation_time;
290 }
291
292 static struct snapshot *find_orphaned_snapshot(struct snapshot_list *sl)
293 {
294         struct snapshot *s;
295         int i;
296
297         DSS_DEBUG_LOG("looking for orphaned snapshots\n");
298         FOR_EACH_SNAPSHOT(s, i, sl) {
299                 if (snapshot_is_being_created(s))
300                         continue;
301                 /*
302                  * We know that no rm is currently running, so if s is marked
303                  * as being deleted, a previously started rm must have failed.
304                  */
305                 if (s->flags & SS_BEING_DELETED)
306                         return s;
307
308                 if (s->flags & SS_COMPLETE) /* good snapshot */
309                         continue;
310                 /*
311                  * This snapshot is incomplete and it is not the snapshot
312                  * currently being created. However, we must not remove it if
313                  * rsync is about to be restarted. As only the newest snapshot
314                  * can be restarted, this snapshot is orphaned if it is not the
315                  * newest snapshot or if we are not about to restart rsync.
316                  */
317                 if (get_newest_snapshot(sl) != s)
318                         return s;
319                 if (snapshot_creation_status != HS_NEEDS_RESTART)
320                         return s;
321         }
322         /* no orphaned snapshots */
323         return NULL;
324 }
325
326 static int is_reference_snapshot(struct snapshot *s)
327 {
328         if (!name_of_reference_snapshot)
329                 return 0;
330         return strcmp(s->name, name_of_reference_snapshot)? 0 : 1;
331 }
332
333 /*
334  * return: 0: no redundant snapshots, 1: rm process started, negative: error
335  */
336 static struct snapshot *find_redundant_snapshot(struct snapshot_list *sl)
337 {
338         int i, interval;
339         struct snapshot *s;
340         unsigned missing = 0;
341
342         DSS_DEBUG_LOG("looking for intervals containing too many snapshots\n");
343         for (interval = conf.num_intervals_arg - 1; interval >= 0; interval--) {
344                 unsigned keep = desired_number_of_snapshots(interval, conf.num_intervals_arg);
345                 unsigned num = sl->interval_count[interval];
346                 struct snapshot *victim = NULL, *prev = NULL;
347                 int64_t score = LONG_MAX;
348
349                 if (keep >= num)
350                         missing += keep - num;
351 //              DSS_DEBUG_LOG("interval %i: keep: %u, have: %u, missing: %u\n",
352 //                      interval, keep, num, missing);
353                 if (keep + missing >= num)
354                         continue;
355                 /* redundant snapshot in this interval, pick snapshot with lowest score */
356                 FOR_EACH_SNAPSHOT(s, i, sl) {
357                         int64_t this_score;
358
359                         if (snapshot_is_being_created(s))
360                                 continue;
361                         if (is_reference_snapshot(s))
362                                 continue;
363                         //DSS_DEBUG_LOG("checking %s\n", s->name);
364                         if (s->interval > interval) {
365                                 prev = s;
366                                 continue;
367                         }
368                         if (s->interval < interval)
369                                 break;
370                         if (!victim) {
371                                 victim = s;
372                                 prev = s;
373                                 continue;
374                         }
375                         assert(prev);
376                         /* check if s is a better victim */
377                         this_score = s->creation_time - prev->creation_time;
378                         assert(this_score >= 0);
379                         //DSS_DEBUG_LOG("%s: score %lli\n", s->name, (long long)score);
380                         if (this_score < score) {
381                                 score = this_score;
382                                 victim = s;
383                         }
384                         prev = s;
385                 }
386                 assert(victim);
387                 return victim;
388         }
389         return NULL;
390 }
391
392 static struct snapshot *find_outdated_snapshot(struct snapshot_list *sl)
393 {
394         int i;
395         struct snapshot *s;
396
397         DSS_DEBUG_LOG("looking for snapshots belonging to intervals >= %d\n",
398                 conf.num_intervals_arg);
399         FOR_EACH_SNAPSHOT(s, i, sl) {
400                 if (snapshot_is_being_created(s))
401                         continue;
402                 if (is_reference_snapshot(s))
403                         continue;
404                 if (s->interval < conf.num_intervals_arg)
405                         continue;
406                 return s;
407         }
408         return NULL;
409 }
410
411 struct snapshot *find_oldest_removable_snapshot(struct snapshot_list *sl)
412 {
413         int i;
414         struct snapshot *s;
415         FOR_EACH_SNAPSHOT(s, i, sl) {
416                 if (snapshot_is_being_created(s))
417                         continue;
418                 if (is_reference_snapshot(s))
419                         continue;
420                 DSS_INFO_LOG("oldest removable snapshot: %s\n", s->name);
421                 return s;
422         }
423         return NULL;
424 }
425
426 static int rename_incomplete_snapshot(int64_t start)
427 {
428         char *old_name;
429         int ret;
430
431         free(path_to_last_complete_snapshot);
432         ret = complete_name(start, get_current_time(),
433                 &path_to_last_complete_snapshot);
434         if (ret < 0)
435                 return ret;
436         old_name = incomplete_name(start);
437         ret = dss_rename(old_name, path_to_last_complete_snapshot);
438         if (ret >= 0)
439                 DSS_NOTICE_LOG("%s -> %s\n", old_name,
440                         path_to_last_complete_snapshot);
441         free(old_name);
442         return ret;
443 }
444
445 static int try_to_free_disk_space(void)
446 {
447         int ret;
448         struct snapshot_list sl;
449         struct snapshot *victim;
450         struct timeval now;
451         const char *why;
452         int low_disk_space;
453
454         ret = disk_space_low();
455         if (ret < 0)
456                 return ret;
457         low_disk_space = ret;
458         gettimeofday(&now, NULL);
459         if (tv_diff(&next_removal_check, &now, NULL) > 0)
460                 return 0;
461         if (!low_disk_space) {
462                 if (conf.keep_redundant_given)
463                         return 0;
464                 if (snapshot_creation_status != HS_READY)
465                         return 0;
466                 if (next_snapshot_is_due())
467                         return 0;
468         }
469         dss_get_snapshot_list(&sl);
470         ret = 0;
471         if (!low_disk_space && sl.num_snapshots <= 1)
472                 goto out;
473         why = "outdated";
474         victim = find_outdated_snapshot(&sl);
475         if (victim)
476                 goto remove;
477         why = "redundant";
478         victim = find_redundant_snapshot(&sl);
479         if (victim)
480                 goto remove;
481         /* try harder only if disk space is low */
482         if (!low_disk_space)
483                 goto out;
484         why = "orphaned";
485         victim = find_orphaned_snapshot(&sl);
486         if (victim)
487                 goto remove;
488         DSS_WARNING_LOG("disk space low and nothing obvious to remove\n");
489         victim = find_oldest_removable_snapshot(&sl);
490         if (victim)
491                 goto remove;
492         DSS_CRIT_LOG("uhuhu: disk space low and nothing to remove\n");
493         ret = -ERRNO_TO_DSS_ERROR(ENOSPC);
494         goto out;
495 remove:
496         ret = pre_remove_hook(victim, why);
497 out:
498         free_snapshot_list(&sl);
499         return ret;
500 }
501
502 static int post_create_hook(void)
503 {
504         int ret, fds[3] = {0, 0, 0};
505         char *cmd;
506
507         if (!conf.post_create_hook_given) {
508                 create_pid = 0;
509                 snapshot_creation_status = HS_READY;
510                 return 0;
511         }
512         cmd = make_message("%s %s/%s", conf.post_create_hook_arg,
513                 conf.dest_dir_arg, path_to_last_complete_snapshot);
514         DSS_NOTICE_LOG("executing %s\n", cmd);
515         ret = dss_exec_cmdline_pid(&create_pid, cmd, fds);
516         free(cmd);
517         if (ret < 0)
518                 return ret;
519         snapshot_creation_status = HS_POST_RUNNING;
520         return ret;
521 }
522
523 static int post_remove_hook(void)
524 {
525         int ret, fds[3] = {0, 0, 0};
526         char *cmd;
527         struct snapshot *s = snapshot_currently_being_removed;
528
529         assert(s);
530
531         if (!conf.post_remove_hook_given) {
532                 snapshot_removal_status = HS_READY;
533                 return 0;
534         }
535         cmd = make_message("%s %s/%s", conf.post_remove_hook_arg,
536                 conf.dest_dir_arg, s->name);
537         DSS_NOTICE_LOG("executing %s\n", cmd);
538         ret = dss_exec_cmdline_pid(&remove_pid, cmd, fds);
539         free(cmd);
540         if (ret < 0)
541                 return ret;
542         snapshot_removal_status = HS_POST_RUNNING;
543         return ret;
544 }
545
546 static void kill_process(pid_t pid)
547 {
548         if (!pid)
549                 return;
550         DSS_WARNING_LOG("sending SIGTERM to pid %d\n", (int)pid);
551         kill(pid, SIGTERM);
552 }
553
554 static void stop_create_process(void)
555 {
556         if (!create_pid || create_process_stopped)
557                 return;
558         kill(SIGSTOP, create_pid);
559         create_process_stopped = 1;
560 }
561
562 static void restart_create_process(void)
563 {
564         if (!create_pid || !create_process_stopped)
565                 return;
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                         return handle_pre_create_hook_exit(status);
783                 case HS_RUNNING:
784                         return handle_rsync_exit(status);
785                 case HS_POST_RUNNING:
786                         snapshot_creation_status = HS_READY;
787                         return 1;
788                 default:
789                         DSS_EMERG_LOG("BUG: create can't die in status %d\n",
790                                 snapshot_creation_status);
791                         return -E_BUG;
792                 }
793                 create_pid = 0;
794         }
795         if (pid == remove_pid) {
796                 ret = handle_remove_exit(status);
797                 if (ret < 0)
798                         return ret;
799                 return ret;
800         }
801         DSS_EMERG_LOG("BUG: unknown process %d died\n", (int)pid);
802         return -E_BUG;
803 }
804
805 static int check_config(void)
806 {
807         if (conf.unit_interval_arg <= 0) {
808                 DSS_ERROR_LOG("bad unit interval: %i\n", conf.unit_interval_arg);
809                 return -E_INVALID_NUMBER;
810         }
811         DSS_DEBUG_LOG("unit interval: %i day(s)\n", conf.unit_interval_arg);
812         if (conf.num_intervals_arg <= 0) {
813                 DSS_ERROR_LOG("bad number of intervals  %i\n", conf.num_intervals_arg);
814                 return -E_INVALID_NUMBER;
815         }
816         DSS_DEBUG_LOG("number of intervals: %i\n", conf.num_intervals_arg);
817         return 1;
818 }
819
820 /*
821  * Returns < 0 on errors, 0 if no config file is given and > 0 if the config
822  * file was read successfully.
823  */
824 static int parse_config_file(int override)
825 {
826         int ret, config_file_exists;
827         char *config_file;
828         struct stat statbuf;
829         char *old_logfile_arg = NULL;
830         int old_daemon_given = 0;
831
832         if (conf.config_file_given)
833                 config_file = dss_strdup(conf.config_file_arg);
834         else {
835                 char *home = get_homedir();
836                 config_file = make_message("%s/.dssrc", home);
837                 free(home);
838         }
839         if (override) { /* SIGHUP */
840                 if (conf.logfile_given)
841                         old_logfile_arg = dss_strdup(conf.logfile_arg);
842                 old_daemon_given = conf.daemon_given;
843         }
844
845         config_file_exists = !stat(config_file, &statbuf);
846         if (!config_file_exists && conf.config_file_given) {
847                 ret = -ERRNO_TO_DSS_ERROR(errno);
848                 DSS_ERROR_LOG("failed to stat config file %s\n", config_file);
849                 goto out;
850         }
851         if (config_file_exists) {
852                 struct cmdline_parser_params params = {
853                         .override = override,
854                         .initialize = 0,
855                         .check_required = 1,
856                         .check_ambiguity = 0,
857                         .print_errors = 1
858                 };
859                 if (override) { /* invalidate all rsync options */
860                         int i;
861
862                         for (i = 0; i < conf.rsync_option_given; i++) {
863                                 free(conf.rsync_option_arg[i]);
864                                 conf.rsync_option_arg[i] = NULL;
865                         }
866                         conf.rsync_option_given = 0;
867                 }
868                 cmdline_parser_config_file(config_file, &conf, &params);
869         }
870         ret = check_config();
871         if (ret < 0)
872                 goto out;
873         if (override) {
874                 /* don't change daemon mode on SIGHUP */
875                 conf.daemon_given = old_daemon_given;
876                 close_log(logfile);
877                 logfile = NULL;
878                 if (conf.logfile_given)
879                         free(old_logfile_arg);
880                 else if (conf.daemon_given) { /* re-use old logfile */
881                         conf.logfile_arg = old_logfile_arg;
882                         conf.logfile_given = 1;
883                 }
884         }
885         if (conf.logfile_given) {
886                 logfile = open_log(conf.logfile_arg);
887                 log_welcome(conf.loglevel_arg);
888         }
889         DSS_DEBUG_LOG("loglevel: %d\n", conf.loglevel_arg);
890         ret = config_file_exists;
891 out:
892         free(config_file);
893         if (ret < 0)
894                 DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
895         return ret;
896 }
897
898 static int change_to_dest_dir(void)
899 {
900         DSS_INFO_LOG("changing cwd to %s\n", conf.dest_dir_arg);
901         return dss_chdir(conf.dest_dir_arg);
902 }
903
904 static void dump_dss_config(const char *msg)
905 {
906         if (conf.loglevel_arg > INFO)
907                 return;
908         DSS_INFO_LOG("%s\n", msg);
909         cmdline_parser_dump(logfile? logfile : stderr, &conf);
910 }
911
912 static int handle_sighup(void)
913 {
914         int ret;
915
916         DSS_NOTICE_LOG("SIGHUP, re-reading config\n");
917         dump_dss_config("current config");
918         ret = parse_config_file(1);
919         if (ret < 0)
920                 return ret;
921         dump_dss_config("new config");
922         invalidate_next_snapshot_time();
923         return change_to_dest_dir();
924 }
925
926 static int handle_signal(void)
927 {
928         int sig, ret = next_signal();
929
930         if (ret <= 0)
931                 goto out;
932         sig = ret;
933         switch (sig) {
934         case SIGINT:
935         case SIGTERM:
936                 restart_create_process();
937                 kill_process(create_pid);
938                 kill_process(remove_pid);
939                 ret = -E_SIGNAL;
940                 break;
941         case SIGHUP:
942                 ret = handle_sighup();
943                 break;
944         case SIGCHLD:
945                 ret = handle_sigchld();
946                 break;
947         }
948 out:
949         if (ret < 0)
950                 DSS_ERROR_LOG("%s\n", dss_strerror(-ret));
951         return ret;
952 }
953
954 /*
955  * We can not use rsync locally if the local user is different from the remote
956  * user or if the src dir is not on the local host (or both).
957  */
958 static int use_rsync_locally(char *logname)
959 {
960         char *h = conf.remote_host_arg;
961
962         if (strcmp(h, "localhost") && strcmp(h, "127.0.0.1"))
963                 return 0;
964         if (conf.remote_user_given && strcmp(conf.remote_user_arg, logname))
965                 return 0;
966         return 1;
967 }
968
969 static int rename_resume_snap(int64_t creation_time)
970 {
971         struct snapshot_list sl = {.num_snapshots = 0};
972         struct snapshot *s;
973         char *new_name = incomplete_name(creation_time);
974         int ret;
975
976         ret = 0;
977         if (conf.no_resume_given)
978                 goto out;
979         dss_get_snapshot_list(&sl);
980         s = get_newest_snapshot(&sl);
981         if (!s)
982                 goto out;
983         if ((s->flags & SS_COMPLETE) != 0) /* complete */
984                 goto out;
985         DSS_INFO_LOG("resuming: reusing %s as destination dir\n", s->name);
986         ret = dss_rename(s->name, new_name);
987 out:
988         if (ret >= 0)
989                 DSS_NOTICE_LOG("creating new snapshot %s\n", new_name);
990         free(new_name);
991         free_snapshot_list(&sl);
992         return ret;
993 }
994
995 static void create_rsync_argv(char ***argv, int64_t *num)
996 {
997         char *logname;
998         int i = 0, j;
999         struct snapshot_list sl;
1000
1001         dss_get_snapshot_list(&sl);
1002         assert(!name_of_reference_snapshot);
1003         name_of_reference_snapshot = name_of_newest_complete_snapshot(&sl);
1004         free_snapshot_list(&sl);
1005
1006         *argv = dss_malloc((15 + conf.rsync_option_given) * sizeof(char *));
1007         (*argv)[i++] = dss_strdup("rsync");
1008         (*argv)[i++] = dss_strdup("-aq");
1009         (*argv)[i++] = dss_strdup("--delete");
1010         for (j = 0; j < conf.rsync_option_given; j++)
1011                 (*argv)[i++] = dss_strdup(conf.rsync_option_arg[j]);
1012         if (name_of_reference_snapshot) {
1013                 DSS_INFO_LOG("using %s as reference\n", name_of_reference_snapshot);
1014                 (*argv)[i++] = make_message("--link-dest=../%s",
1015                         name_of_reference_snapshot);
1016         } else
1017                 DSS_INFO_LOG("no suitable reference snapshot found\n");
1018         logname = dss_logname();
1019         if (use_rsync_locally(logname))
1020                 (*argv)[i++] = dss_strdup(conf.source_dir_arg);
1021         else
1022                 (*argv)[i++] = make_message("%s@%s:%s/", conf.remote_user_given?
1023                         conf.remote_user_arg : logname,
1024                         conf.remote_host_arg, conf.source_dir_arg);
1025         free(logname);
1026         *num = get_current_time();
1027         (*argv)[i++] = incomplete_name(*num);
1028         (*argv)[i++] = NULL;
1029         for (j = 0; j < i; j++)
1030                 DSS_DEBUG_LOG("argv[%d] = %s\n", j, (*argv)[j]);
1031 }
1032
1033 static void free_rsync_argv(char **argv)
1034 {
1035         int i;
1036
1037         if (!argv)
1038                 return;
1039         for (i = 0; argv[i]; i++)
1040                 free(argv[i]);
1041         free(argv);
1042 }
1043
1044 static int create_snapshot(char **argv)
1045 {
1046         int ret, fds[3] = {0, 0, 0};
1047
1048         ret = rename_resume_snap(current_snapshot_creation_time);
1049         if (ret < 0)
1050                 return ret;
1051         ret = dss_exec(&create_pid, argv[0], argv, fds);
1052         if (ret < 0)
1053                 return ret;
1054         snapshot_creation_status = HS_RUNNING;
1055         return ret;
1056 }
1057
1058 static int select_loop(void)
1059 {
1060         int ret;
1061         /* check every 60 seconds for free disk space */
1062         struct timeval tv;
1063         char **rsync_argv = NULL;
1064
1065         for (;;) {
1066                 fd_set rfds;
1067                 struct timeval *tvp;
1068
1069                 if (remove_pid)
1070                         tvp = NULL; /* sleep until rm hook/process dies */
1071                 else { /* sleep one minute */
1072                         tv.tv_sec = 60;
1073                         tv.tv_usec = 0;
1074                         tvp = &tv;
1075                 }
1076                 FD_ZERO(&rfds);
1077                 FD_SET(signal_pipe, &rfds);
1078                 DSS_DEBUG_LOG("tvp: %p, tv_sec : %lu\n", tvp, (long unsigned) tv.tv_sec);
1079                 ret = dss_select(signal_pipe + 1, &rfds, NULL, tvp);
1080                 if (ret < 0)
1081                         goto out;
1082                 if (FD_ISSET(signal_pipe, &rfds)) {
1083                         ret = handle_signal();
1084                         if (ret < 0)
1085                                 goto out;
1086                 }
1087                 if (remove_pid)
1088                         continue;
1089                 if (snapshot_removal_status == HS_PRE_SUCCESS) {
1090                         ret = exec_rm();
1091                         if (ret < 0)
1092                                 goto out;
1093                         continue;
1094                 }
1095                 if (snapshot_removal_status == HS_SUCCESS) {
1096                         ret = post_remove_hook();
1097                         if (ret < 0)
1098                                 goto out;
1099                         continue;
1100                 }
1101                 ret = try_to_free_disk_space();
1102                 if (ret < 0)
1103                         goto out;
1104                 if (snapshot_removal_status != HS_READY) {
1105                         stop_create_process();
1106                         continue;
1107                 }
1108                 restart_create_process();
1109                 switch (snapshot_creation_status) {
1110                 case HS_READY:
1111                         if (!next_snapshot_is_due())
1112                                 continue;
1113                         ret = pre_create_hook();
1114                         if (ret < 0)
1115                                 goto out;
1116                         continue;
1117                 case HS_PRE_RUNNING:
1118                 case HS_RUNNING:
1119                 case HS_POST_RUNNING:
1120                         continue;
1121                 case HS_PRE_SUCCESS:
1122                         free_rsync_argv(rsync_argv);
1123                         create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
1124                         /* fall through */
1125                 case HS_NEEDS_RESTART:
1126                         if (!next_snapshot_is_due())
1127                                 continue;
1128                         ret = create_snapshot(rsync_argv);
1129                         if (ret < 0)
1130                                 goto out;
1131                         continue;
1132                 case HS_SUCCESS:
1133                         ret = post_create_hook();
1134                         if (ret < 0)
1135                                 goto out;
1136                         continue;
1137                 }
1138         }
1139 out:
1140         return ret;
1141 }
1142
1143 static void exit_hook(int exit_code)
1144 {
1145         int fds[3] = {0, 0, 0};
1146         char *argv[] = {conf.exit_hook_arg, dss_strerror(-exit_code), NULL};
1147         pid_t pid;
1148
1149         if (!conf.exit_hook_given)
1150                 return;
1151         DSS_NOTICE_LOG("executing %s %s\n", argv[0], argv[1]);
1152         dss_exec(&pid, conf.exit_hook_arg, argv, fds);
1153 }
1154
1155 static int com_run(void)
1156 {
1157         int ret;
1158
1159         if (conf.dry_run_given) {
1160                 DSS_ERROR_LOG("dry_run not supported by this command\n");
1161                 return -E_SYNTAX;
1162         }
1163         ret = install_sighandler(SIGHUP);
1164         if (ret < 0)
1165                 return ret;
1166         ret = select_loop();
1167         if (ret >= 0) /* impossible */
1168                 ret = -E_BUG;
1169         exit_hook(ret);
1170         return ret;
1171 }
1172
1173 static int com_prune(void)
1174 {
1175         int ret;
1176         struct snapshot_list sl;
1177         struct snapshot *victim;
1178         struct disk_space ds;
1179         const char *why;
1180
1181         ret = get_disk_space(".", &ds);
1182         if (ret < 0)
1183                 return ret;
1184         log_disk_space(&ds);
1185         dss_get_snapshot_list(&sl);
1186         why = "outdated";
1187         victim = find_outdated_snapshot(&sl);
1188         if (victim)
1189                 goto rm;
1190         why = "redundant";
1191         victim = find_redundant_snapshot(&sl);
1192         if (victim)
1193                 goto rm;
1194         ret = 0;
1195         goto out;
1196 rm:
1197         if (conf.dry_run_given) {
1198                 dss_msg("%s snapshot %s (interval = %i)\n",
1199                         why, victim->name, victim->interval);
1200                 ret = 0;
1201                 goto out;
1202         }
1203         ret = pre_remove_hook(victim, why);
1204         if (ret < 0)
1205                 goto out;
1206         if (snapshot_removal_status == HS_PRE_RUNNING) {
1207                 ret = wait_for_remove_process();
1208                 if (ret < 0)
1209                         goto out;
1210                 if (snapshot_removal_status != HS_PRE_SUCCESS)
1211                         goto out;
1212         }
1213         ret = exec_rm();
1214         if (ret < 0)
1215                 goto out;
1216         ret = wait_for_remove_process();
1217         if (ret < 0)
1218                 goto out;
1219         if (snapshot_removal_status != HS_SUCCESS)
1220                 goto out;
1221         ret = post_remove_hook();
1222         if (ret < 0)
1223                 goto out;
1224         if (snapshot_removal_status != HS_POST_RUNNING)
1225                 goto out;
1226         ret = wait_for_remove_process();
1227         if (ret < 0)
1228                 goto out;
1229         ret = 1;
1230 out:
1231         free_snapshot_list(&sl);
1232         return ret;
1233 }
1234
1235 static int com_create(void)
1236 {
1237         int ret, status;
1238         char **rsync_argv;
1239
1240         if (conf.dry_run_given) {
1241                 int i;
1242                 char *msg = NULL;
1243                 create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
1244                 for (i = 0; rsync_argv[i]; i++) {
1245                         char *tmp = msg;
1246                         msg = make_message("%s%s%s", tmp? tmp : "",
1247                                 tmp? " " : "", rsync_argv[i]);
1248                         free(tmp);
1249                 }
1250                 free_rsync_argv(rsync_argv);
1251                 dss_msg("%s\n", msg);
1252                 free(msg);
1253                 return 1;
1254         }
1255         ret = pre_create_hook();
1256         if (ret < 0)
1257                 return ret;
1258         if (create_pid) {
1259                 ret = wait_for_process(create_pid, &status);
1260                 if (ret < 0)
1261                         return ret;
1262                 ret = handle_pre_create_hook_exit(status);
1263                 if (ret <= 0) /* error, or pre-create failed */
1264                         return ret;
1265         }
1266         create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
1267         ret = create_snapshot(rsync_argv);
1268         if (ret < 0)
1269                 goto out;
1270         ret = wait_for_process(create_pid, &status);
1271         if (ret < 0)
1272                 goto out;
1273         ret = handle_rsync_exit(status);
1274         if (ret < 0)
1275                 goto out;
1276         post_create_hook();
1277         if (create_pid)
1278                 ret = wait_for_process(create_pid, &status);
1279 out:
1280         free_rsync_argv(rsync_argv);
1281         return ret;
1282 }
1283
1284 static int com_ls(void)
1285 {
1286         int i;
1287         struct snapshot_list sl;
1288         struct snapshot *s;
1289
1290         dss_get_snapshot_list(&sl);
1291         FOR_EACH_SNAPSHOT(s, i, &sl) {
1292                 int64_t d = 0;
1293                 if (s->flags & SS_COMPLETE)
1294                         d = (s->completion_time - s->creation_time) / 60;
1295                 dss_msg("%u\t%s\t%3" PRId64 ":%02" PRId64 "\n", s->interval, s->name, d/60, d%60);
1296         };
1297         free_snapshot_list(&sl);
1298         return 1;
1299 }
1300
1301 static int setup_signal_handling(void)
1302 {
1303         int ret;
1304
1305         DSS_INFO_LOG("setting up signal handlers\n");
1306         signal_pipe = signal_init(); /* always successful */
1307         ret = install_sighandler(SIGINT);
1308         if (ret < 0)
1309                 return ret;
1310         ret = install_sighandler(SIGTERM);
1311         if (ret < 0)
1312                 return ret;
1313         return install_sighandler(SIGCHLD);
1314 }
1315
1316 /**
1317  * The main function of dss.
1318  *
1319  * \param argc Usual argument count.
1320  * \param argv Usual argument vector.
1321  */
1322 int main(int argc, char **argv)
1323 {
1324         int ret;
1325         struct cmdline_parser_params params = {
1326                 .override = 0,
1327                 .initialize = 1,
1328                 .check_required = 0,
1329                 .check_ambiguity = 0,
1330                 .print_errors = 1
1331         };
1332
1333         cmdline_parser_ext(argc, argv, &conf, &params); /* aborts on errors */
1334         ret = parse_config_file(0);
1335         if (ret < 0)
1336                 goto out;
1337         if (ret == 0) { /* no config file given */
1338                 /*
1339                  * Parse the command line options again, but this time check
1340                  * that all required options are given.
1341                  */
1342                 params = (struct cmdline_parser_params) {
1343                         .override = 1,
1344                         .initialize = 1,
1345                         .check_required = 1,
1346                         .check_ambiguity = 1,
1347                         .print_errors = 1
1348                 };
1349                 cmdline_parser_ext(argc, argv, &conf, &params); /* aborts on errors */
1350         }
1351         if (conf.daemon_given)
1352                 daemon_init();
1353         dump_dss_config("dss configuration");
1354         ret = change_to_dest_dir();
1355         if (ret < 0)
1356                 goto out;
1357         ret = setup_signal_handling();
1358         if (ret < 0)
1359                 goto out;
1360         ret = call_command_handler();
1361 out:
1362         if (ret < 0)
1363                 DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
1364         exit(ret >= 0? EXIT_SUCCESS : EXIT_FAILURE);
1365 }