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