]> git.tuebingen.mpg.de Git - dss.git/blob - dss.c
Fix create mode in case no post-create hook is given.
[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                 create_pid = 0;
510                 snapshot_creation_status = HS_READY;
511                 return 0;
512         }
513         cmd = make_message("%s %s/%s", conf.post_create_hook_arg,
514                 conf.dest_dir_arg, path_to_last_complete_snapshot);
515         DSS_NOTICE_LOG("executing %s\n", cmd);
516         ret = dss_exec_cmdline_pid(&create_pid, cmd, fds);
517         free(cmd);
518         if (ret < 0)
519                 return ret;
520         snapshot_creation_status = HS_POST_RUNNING;
521         return ret;
522 }
523
524 static int post_remove_hook(void)
525 {
526         int ret, fds[3] = {0, 0, 0};
527         char *cmd;
528         struct snapshot *s = snapshot_currently_being_removed;
529
530         assert(s);
531
532         if (!conf.post_remove_hook_given) {
533                 snapshot_removal_status = HS_READY;
534                 return 0;
535         }
536         cmd = make_message("%s %s/%s", conf.post_remove_hook_arg,
537                 conf.dest_dir_arg, s->name);
538         DSS_NOTICE_LOG("executing %s\n", cmd);
539         ret = dss_exec_cmdline_pid(&remove_pid, cmd, fds);
540         free(cmd);
541         if (ret < 0)
542                 return ret;
543         snapshot_removal_status = HS_POST_RUNNING;
544         return ret;
545 }
546
547 static void kill_process(pid_t pid)
548 {
549         if (!pid)
550                 return;
551         DSS_WARNING_LOG("sending SIGTERM to pid %d\n", (int)pid);
552         kill(pid, SIGTERM);
553 }
554
555 static void stop_create_process(void)
556 {
557         if (!create_pid || create_process_stopped)
558                 return;
559         kill(SIGSTOP, create_pid);
560         create_process_stopped = 1;
561 }
562
563 static void restart_create_process(void)
564 {
565         if (!create_pid || !create_process_stopped)
566                 return;
567         kill (SIGCONT, create_pid);
568         create_process_stopped = 0;
569 }
570
571 /**
572  * Print a log message about the exit status of a child.
573  */
574 static void log_termination_msg(pid_t pid, int status)
575 {
576         if (WIFEXITED(status))
577                 DSS_INFO_LOG("child %i exited. Exit status: %i\n", (int)pid,
578                         WEXITSTATUS(status));
579         else if (WIFSIGNALED(status))
580                 DSS_NOTICE_LOG("child %i was killed by signal %i\n", (int)pid,
581                         WTERMSIG(status));
582         else
583                 DSS_WARNING_LOG("child %i terminated abormally\n", (int)pid);
584 }
585
586 static int wait_for_process(pid_t pid, int *status)
587 {
588         int ret;
589
590         DSS_DEBUG_LOG("Waiting for process %d to terminate\n", (int)pid);
591         for (;;) {
592                 fd_set rfds;
593
594                 FD_ZERO(&rfds);
595                 FD_SET(signal_pipe, &rfds);
596                 ret = dss_select(signal_pipe + 1, &rfds, NULL, NULL);
597                 if (ret < 0)
598                         break;
599                 ret = next_signal();
600                 if (!ret)
601                         continue;
602                 if (ret == SIGCHLD) {
603                         ret = waitpid(pid, status, 0);
604                         if (ret >= 0)
605                                 break;
606                         if (errno != EINTR) { /* error */
607                                 ret = -ERRNO_TO_DSS_ERROR(errno);
608                                 break;
609                         }
610                 }
611                 /* SIGINT or SIGTERM */
612                 DSS_WARNING_LOG("sending SIGTERM to pid %d\n", (int)pid);
613                 kill(pid, SIGTERM);
614         }
615         if (ret < 0)
616                 DSS_ERROR_LOG("failed to wait for process %d\n", (int)pid);
617         else
618                 log_termination_msg(pid, *status);
619         return ret;
620 }
621
622 static void handle_pre_remove_exit(int status)
623 {
624         if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
625                 snapshot_removal_status = HS_READY;
626                 gettimeofday(&next_removal_check, NULL);
627                 next_removal_check.tv_sec += 60;
628                 return;
629         }
630         snapshot_removal_status = HS_PRE_SUCCESS;
631 }
632
633 static int handle_rm_exit(int status)
634 {
635         if (!WIFEXITED(status)) {
636                 snapshot_removal_status = HS_READY;
637                 return -E_INVOLUNTARY_EXIT;
638         }
639         if (WEXITSTATUS(status)) {
640                 snapshot_removal_status = HS_READY;
641                 return -E_BAD_EXIT_CODE;
642         }
643         if (conf.post_remove_hook_given)
644                 snapshot_removal_status = HS_SUCCESS;
645         else
646                 snapshot_removal_status = HS_READY;
647         return 1;
648 }
649
650 static void handle_post_remove_exit(void)
651 {
652         snapshot_removal_status = HS_READY;
653 }
654
655 static int handle_remove_exit(int status)
656 {
657         int ret;
658         struct snapshot *s = snapshot_currently_being_removed;
659
660         assert(s);
661         switch (snapshot_removal_status) {
662         case HS_PRE_RUNNING:
663                 handle_pre_remove_exit(status);
664                 ret = 1;
665                 break;
666         case HS_RUNNING:
667                 ret = handle_rm_exit(status);
668                 break;
669         case HS_POST_RUNNING:
670                 handle_post_remove_exit();
671                 ret = 1;
672                 break;
673         default:
674                 ret = -E_BUG;
675         }
676         if (snapshot_removal_status == HS_READY) {
677                 free(s->name);
678                 free(s);
679                 snapshot_currently_being_removed = NULL;
680         }
681         remove_pid = 0;
682         return ret;
683 }
684
685 static int wait_for_remove_process(void)
686 {
687         int status, ret;
688
689         assert(remove_pid);
690         assert(
691                 snapshot_removal_status == HS_PRE_RUNNING ||
692                 snapshot_removal_status == HS_RUNNING ||
693                 snapshot_removal_status == HS_POST_RUNNING
694         );
695         ret = wait_for_process(remove_pid, &status);
696         if (ret < 0)
697                 return ret;
698         return handle_remove_exit(status);
699 }
700
701 static int handle_rsync_exit(int status)
702 {
703         int es, ret;
704
705         if (!WIFEXITED(status)) {
706                 DSS_ERROR_LOG("rsync process %d died involuntary\n", (int)create_pid);
707                 ret = -E_INVOLUNTARY_EXIT;
708                 snapshot_creation_status = HS_READY;
709                 goto out;
710         }
711         es = WEXITSTATUS(status);
712         /*
713          * Restart rsync on non-fatal errors:
714          * 12: Error in rsync protocol data stream
715          * 13: Errors with program diagnostics
716          */
717         if (es == 12 || es == 13) {
718                 DSS_WARNING_LOG("rsync process %d returned %d -- restarting\n",
719                         (int)create_pid, es);
720                 snapshot_creation_status = HS_NEEDS_RESTART;
721                 next_snapshot_time = get_current_time() + 60;
722                 ret = 1;
723                 goto out;
724         }
725         if (es != 0 && es != 23 && es != 24) {
726                 DSS_ERROR_LOG("rsync process %d returned %d\n", (int)create_pid, es);
727                 ret = -E_BAD_EXIT_CODE;
728                 snapshot_creation_status = HS_READY;
729                 goto out;
730         }
731         ret = rename_incomplete_snapshot(current_snapshot_creation_time);
732         if (ret < 0)
733                 goto out;
734         snapshot_creation_status = HS_SUCCESS;
735         free(name_of_reference_snapshot);
736         name_of_reference_snapshot = NULL;
737 out:
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         return ret;
770 }
771
772 static int handle_sigchld(void)
773 {
774         pid_t pid;
775         int status, ret = reap_child(&pid, &status);
776
777         if (ret <= 0)
778                 return ret;
779
780         if (pid == create_pid) {
781                 switch (snapshot_creation_status) {
782                 case HS_PRE_RUNNING:
783                         return handle_pre_create_hook_exit(status);
784                 case HS_RUNNING:
785                         return handle_rsync_exit(status);
786                 case HS_POST_RUNNING:
787                         snapshot_creation_status = HS_READY;
788                         return 1;
789                 default:
790                         DSS_EMERG_LOG("BUG: create can't die in status %d\n",
791                                 snapshot_creation_status);
792                         return -E_BUG;
793                 }
794                 create_pid = 0;
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 /*
822  * Returns < 0 on errors, 0 if no config file is given and > 0 if the config
823  * file was read successfully.
824  */
825 static int parse_config_file(int override)
826 {
827         int ret, config_file_exists;
828         char *config_file;
829         struct stat statbuf;
830         char *old_logfile_arg = NULL;
831         int old_daemon_given = 0;
832
833         if (conf.config_file_given)
834                 config_file = dss_strdup(conf.config_file_arg);
835         else {
836                 char *home = get_homedir();
837                 config_file = make_message("%s/.dssrc", home);
838                 free(home);
839         }
840         if (override) { /* SIGHUP */
841                 if (conf.logfile_given)
842                         old_logfile_arg = dss_strdup(conf.logfile_arg);
843                 old_daemon_given = conf.daemon_given;
844         }
845
846         config_file_exists = !stat(config_file, &statbuf);
847         if (!config_file_exists && conf.config_file_given) {
848                 ret = -ERRNO_TO_DSS_ERROR(errno);
849                 DSS_ERROR_LOG("failed to stat config file %s\n", config_file);
850                 goto out;
851         }
852         if (config_file_exists) {
853                 struct cmdline_parser_params params = {
854                         .override = override,
855                         .initialize = 0,
856                         .check_required = 1,
857                         .check_ambiguity = 0,
858                         .print_errors = 1
859                 };
860                 if (override) { /* invalidate all rsync options */
861                         int i;
862
863                         for (i = 0; i < conf.rsync_option_given; i++) {
864                                 free(conf.rsync_option_arg[i]);
865                                 conf.rsync_option_arg[i] = NULL;
866                         }
867                         conf.rsync_option_given = 0;
868                 }
869                 cmdline_parser_config_file(config_file, &conf, &params);
870         }
871         ret = check_config();
872         if (ret < 0)
873                 goto out;
874         if (override) {
875                 /* don't change daemon mode on SIGHUP */
876                 conf.daemon_given = old_daemon_given;
877                 close_log(logfile);
878                 logfile = NULL;
879                 if (conf.logfile_given)
880                         free(old_logfile_arg);
881                 else if (conf.daemon_given) { /* re-use old logfile */
882                         conf.logfile_arg = old_logfile_arg;
883                         conf.logfile_given = 1;
884                 }
885         }
886         if (conf.logfile_given) {
887                 logfile = open_log(conf.logfile_arg);
888                 log_welcome(conf.loglevel_arg);
889         }
890         DSS_DEBUG_LOG("loglevel: %d\n", conf.loglevel_arg);
891         ret = config_file_exists;
892 out:
893         free(config_file);
894         if (ret < 0)
895                 DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
896         return ret;
897 }
898
899 static int change_to_dest_dir(void)
900 {
901         DSS_INFO_LOG("changing cwd to %s\n", conf.dest_dir_arg);
902         return dss_chdir(conf.dest_dir_arg);
903 }
904
905 static void dump_dss_config(const char *msg)
906 {
907         if (conf.loglevel_arg > INFO)
908                 return;
909         DSS_INFO_LOG("%s\n", msg);
910         cmdline_parser_dump(logfile? logfile : stderr, &conf);
911 }
912
913 static int handle_sighup(void)
914 {
915         int ret;
916
917         DSS_NOTICE_LOG("SIGHUP, re-reading config\n");
918         dump_dss_config("current config");
919         ret = parse_config_file(1);
920         if (ret < 0)
921                 return ret;
922         dump_dss_config("new config");
923         invalidate_next_snapshot_time();
924         return change_to_dest_dir();
925 }
926
927 static int handle_signal(void)
928 {
929         int sig, ret = next_signal();
930
931         if (ret <= 0)
932                 goto out;
933         sig = ret;
934         switch (sig) {
935         case SIGINT:
936         case SIGTERM:
937                 restart_create_process();
938                 kill_process(create_pid);
939                 kill_process(remove_pid);
940                 ret = -E_SIGNAL;
941                 break;
942         case SIGHUP:
943                 ret = handle_sighup();
944                 break;
945         case SIGCHLD:
946                 ret = handle_sigchld();
947                 break;
948         }
949 out:
950         if (ret < 0)
951                 DSS_ERROR_LOG("%s\n", dss_strerror(-ret));
952         return ret;
953 }
954
955 /*
956  * We can not use rsync locally if the local user is different from the remote
957  * user or if the src dir is not on the local host (or both).
958  */
959 static int use_rsync_locally(char *logname)
960 {
961         char *h = conf.remote_host_arg;
962
963         if (strcmp(h, "localhost") && strcmp(h, "127.0.0.1"))
964                 return 0;
965         if (conf.remote_user_given && strcmp(conf.remote_user_arg, logname))
966                 return 0;
967         return 1;
968 }
969
970 static int rename_resume_snap(int64_t creation_time)
971 {
972         struct snapshot_list sl = {.num_snapshots = 0};
973         struct snapshot *s;
974         char *new_name = incomplete_name(creation_time);
975         int ret;
976
977         ret = 0;
978         if (conf.no_resume_given)
979                 goto out;
980         dss_get_snapshot_list(&sl);
981         s = get_newest_snapshot(&sl);
982         if (!s)
983                 goto out;
984         if ((s->flags & SS_COMPLETE) != 0) /* complete */
985                 goto out;
986         DSS_INFO_LOG("resuming: reusing %s as destination dir\n", s->name);
987         ret = dss_rename(s->name, new_name);
988 out:
989         if (ret >= 0)
990                 DSS_NOTICE_LOG("creating new snapshot %s\n", new_name);
991         free(new_name);
992         free_snapshot_list(&sl);
993         return ret;
994 }
995
996 static void create_rsync_argv(char ***argv, int64_t *num)
997 {
998         char *logname;
999         int i = 0, j;
1000         struct snapshot_list sl;
1001
1002         dss_get_snapshot_list(&sl);
1003         assert(!name_of_reference_snapshot);
1004         name_of_reference_snapshot = name_of_newest_complete_snapshot(&sl);
1005         free_snapshot_list(&sl);
1006
1007         *argv = dss_malloc((15 + conf.rsync_option_given) * sizeof(char *));
1008         (*argv)[i++] = dss_strdup("rsync");
1009         (*argv)[i++] = dss_strdup("-aq");
1010         (*argv)[i++] = dss_strdup("--delete");
1011         for (j = 0; j < conf.rsync_option_given; j++)
1012                 (*argv)[i++] = dss_strdup(conf.rsync_option_arg[j]);
1013         if (name_of_reference_snapshot) {
1014                 DSS_INFO_LOG("using %s as reference\n", name_of_reference_snapshot);
1015                 (*argv)[i++] = make_message("--link-dest=../%s",
1016                         name_of_reference_snapshot);
1017         } else
1018                 DSS_INFO_LOG("no suitable reference snapshot found\n");
1019         logname = dss_logname();
1020         if (use_rsync_locally(logname))
1021                 (*argv)[i++] = dss_strdup(conf.source_dir_arg);
1022         else
1023                 (*argv)[i++] = make_message("%s@%s:%s/", conf.remote_user_given?
1024                         conf.remote_user_arg : logname,
1025                         conf.remote_host_arg, conf.source_dir_arg);
1026         free(logname);
1027         *num = get_current_time();
1028         (*argv)[i++] = incomplete_name(*num);
1029         (*argv)[i++] = NULL;
1030         for (j = 0; j < i; j++)
1031                 DSS_DEBUG_LOG("argv[%d] = %s\n", j, (*argv)[j]);
1032 }
1033
1034 static void free_rsync_argv(char **argv)
1035 {
1036         int i;
1037
1038         if (!argv)
1039                 return;
1040         for (i = 0; argv[i]; i++)
1041                 free(argv[i]);
1042         free(argv);
1043 }
1044
1045 static int create_snapshot(char **argv)
1046 {
1047         int ret, fds[3] = {0, 0, 0};
1048
1049         ret = rename_resume_snap(current_snapshot_creation_time);
1050         if (ret < 0)
1051                 return ret;
1052         ret = dss_exec(&create_pid, argv[0], argv, fds);
1053         if (ret < 0)
1054                 return ret;
1055         snapshot_creation_status = HS_RUNNING;
1056         return ret;
1057 }
1058
1059 static int select_loop(void)
1060 {
1061         int ret;
1062         /* check every 60 seconds for free disk space */
1063         struct timeval tv;
1064         char **rsync_argv = NULL;
1065
1066         for (;;) {
1067                 fd_set rfds;
1068                 struct timeval *tvp;
1069
1070                 if (remove_pid)
1071                         tvp = NULL; /* sleep until rm hook/process dies */
1072                 else { /* sleep one minute */
1073                         tv.tv_sec = 60;
1074                         tv.tv_usec = 0;
1075                         tvp = &tv;
1076                 }
1077                 FD_ZERO(&rfds);
1078                 FD_SET(signal_pipe, &rfds);
1079                 DSS_DEBUG_LOG("tvp: %p, tv_sec : %lu\n", tvp, (long unsigned) tv.tv_sec);
1080                 ret = dss_select(signal_pipe + 1, &rfds, NULL, tvp);
1081                 if (ret < 0)
1082                         goto out;
1083                 if (FD_ISSET(signal_pipe, &rfds)) {
1084                         ret = handle_signal();
1085                         if (ret < 0)
1086                                 goto out;
1087                 }
1088                 if (remove_pid)
1089                         continue;
1090                 if (snapshot_removal_status == HS_PRE_SUCCESS) {
1091                         ret = exec_rm();
1092                         if (ret < 0)
1093                                 goto out;
1094                         continue;
1095                 }
1096                 if (snapshot_removal_status == HS_SUCCESS) {
1097                         ret = post_remove_hook();
1098                         if (ret < 0)
1099                                 goto out;
1100                         continue;
1101                 }
1102                 ret = try_to_free_disk_space();
1103                 if (ret < 0)
1104                         goto out;
1105                 if (snapshot_removal_status != HS_READY) {
1106                         stop_create_process();
1107                         continue;
1108                 }
1109                 restart_create_process();
1110                 switch (snapshot_creation_status) {
1111                 case HS_READY:
1112                         if (!next_snapshot_is_due())
1113                                 continue;
1114                         ret = pre_create_hook();
1115                         if (ret < 0)
1116                                 goto out;
1117                         continue;
1118                 case HS_PRE_RUNNING:
1119                 case HS_RUNNING:
1120                 case HS_POST_RUNNING:
1121                         continue;
1122                 case HS_PRE_SUCCESS:
1123                         free_rsync_argv(rsync_argv);
1124                         create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
1125                         /* fall through */
1126                 case HS_NEEDS_RESTART:
1127                         ret = create_snapshot(rsync_argv);
1128                         if (ret < 0)
1129                                 goto out;
1130                         continue;
1131                 case HS_SUCCESS:
1132                         ret = post_create_hook();
1133                         if (ret < 0)
1134                                 goto out;
1135                         continue;
1136                 }
1137         }
1138 out:
1139         return ret;
1140 }
1141
1142 static void exit_hook(int exit_code)
1143 {
1144         int fds[3] = {0, 0, 0};
1145         char *argv[] = {conf.exit_hook_arg, dss_strerror(-exit_code), NULL};
1146         pid_t pid;
1147
1148         if (!conf.exit_hook_given)
1149                 return;
1150         DSS_NOTICE_LOG("executing %s %s\n", argv[0], argv[1]);
1151         dss_exec(&pid, conf.exit_hook_arg, argv, fds);
1152 }
1153
1154 static int com_run(void)
1155 {
1156         int ret;
1157
1158         if (conf.dry_run_given) {
1159                 DSS_ERROR_LOG("dry_run not supported by this command\n");
1160                 return -E_SYNTAX;
1161         }
1162         ret = install_sighandler(SIGHUP);
1163         if (ret < 0)
1164                 return ret;
1165         ret = select_loop();
1166         if (ret >= 0) /* impossible */
1167                 ret = -E_BUG;
1168         exit_hook(ret);
1169         return ret;
1170 }
1171
1172 static int com_prune(void)
1173 {
1174         int ret;
1175         struct snapshot_list sl;
1176         struct snapshot *victim;
1177         struct disk_space ds;
1178         const char *why;
1179
1180         ret = get_disk_space(".", &ds);
1181         if (ret < 0)
1182                 return ret;
1183         log_disk_space(&ds);
1184         dss_get_snapshot_list(&sl);
1185         why = "outdated";
1186         victim = find_outdated_snapshot(&sl);
1187         if (victim)
1188                 goto rm;
1189         why = "redundant";
1190         victim = find_redundant_snapshot(&sl);
1191         if (victim)
1192                 goto rm;
1193         ret = 0;
1194         goto out;
1195 rm:
1196         if (conf.dry_run_given) {
1197                 dss_msg("%s snapshot %s (interval = %i)\n",
1198                         why, victim->name, victim->interval);
1199                 ret = 0;
1200                 goto out;
1201         }
1202         ret = pre_remove_hook(victim, why);
1203         if (ret < 0)
1204                 goto out;
1205         if (snapshot_removal_status == HS_PRE_RUNNING) {
1206                 ret = wait_for_remove_process();
1207                 if (ret < 0)
1208                         goto out;
1209                 if (snapshot_removal_status != HS_PRE_SUCCESS)
1210                         goto out;
1211         }
1212         ret = exec_rm();
1213         if (ret < 0)
1214                 goto out;
1215         ret = wait_for_remove_process();
1216         if (ret < 0)
1217                 goto out;
1218         if (snapshot_removal_status != HS_SUCCESS)
1219                 goto out;
1220         ret = post_remove_hook();
1221         if (ret < 0)
1222                 goto out;
1223         if (snapshot_removal_status != HS_POST_RUNNING)
1224                 goto out;
1225         ret = wait_for_remove_process();
1226         if (ret < 0)
1227                 goto out;
1228         ret = 1;
1229 out:
1230         free_snapshot_list(&sl);
1231         return ret;
1232 }
1233
1234 static int com_create(void)
1235 {
1236         int ret, status;
1237         char **rsync_argv;
1238
1239         if (conf.dry_run_given) {
1240                 int i;
1241                 char *msg = NULL;
1242                 create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
1243                 for (i = 0; rsync_argv[i]; i++) {
1244                         char *tmp = msg;
1245                         msg = make_message("%s%s%s", tmp? tmp : "",
1246                                 tmp? " " : "", rsync_argv[i]);
1247                         free(tmp);
1248                 }
1249                 free_rsync_argv(rsync_argv);
1250                 dss_msg("%s\n", msg);
1251                 free(msg);
1252                 return 1;
1253         }
1254         ret = pre_create_hook();
1255         if (ret < 0)
1256                 return ret;
1257         if (create_pid) {
1258                 ret = wait_for_process(create_pid, &status);
1259                 if (ret < 0)
1260                         return ret;
1261                 ret = handle_pre_create_hook_exit(status);
1262                 if (ret <= 0) /* error, or pre-create failed */
1263                         return ret;
1264         }
1265         create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
1266         ret = create_snapshot(rsync_argv);
1267         if (ret < 0)
1268                 goto out;
1269         ret = wait_for_process(create_pid, &status);
1270         if (ret < 0)
1271                 goto out;
1272         ret = handle_rsync_exit(status);
1273         if (ret < 0)
1274                 goto out;
1275         post_create_hook();
1276         if (create_pid)
1277                 ret = wait_for_process(create_pid, &status);
1278 out:
1279         free_rsync_argv(rsync_argv);
1280         return ret;
1281 }
1282
1283 static int com_ls(void)
1284 {
1285         int i;
1286         struct snapshot_list sl;
1287         struct snapshot *s;
1288
1289         dss_get_snapshot_list(&sl);
1290         FOR_EACH_SNAPSHOT(s, i, &sl) {
1291                 int64_t d = 0;
1292                 if (s->flags & SS_COMPLETE)
1293                         d = (s->completion_time - s->creation_time) / 60;
1294                 dss_msg("%u\t%s\t%3" PRId64 ":%02" PRId64 "\n", s->interval, s->name, d/60, d%60);
1295         };
1296         free_snapshot_list(&sl);
1297         return 1;
1298 }
1299
1300 static int setup_signal_handling(void)
1301 {
1302         int ret;
1303
1304         DSS_INFO_LOG("setting up signal handlers\n");
1305         signal_pipe = signal_init(); /* always successful */
1306         ret = install_sighandler(SIGINT);
1307         if (ret < 0)
1308                 return ret;
1309         ret = install_sighandler(SIGTERM);
1310         if (ret < 0)
1311                 return ret;
1312         return install_sighandler(SIGCHLD);
1313 }
1314
1315 /**
1316  * The main function of dss.
1317  *
1318  * \param argc Usual argument count.
1319  * \param argv Usual argument vector.
1320  */
1321 int main(int argc, char **argv)
1322 {
1323         int ret;
1324         struct cmdline_parser_params params = {
1325                 .override = 0,
1326                 .initialize = 1,
1327                 .check_required = 0,
1328                 .check_ambiguity = 0,
1329                 .print_errors = 1
1330         };
1331
1332         cmdline_parser_ext(argc, argv, &conf, &params); /* aborts on errors */
1333         ret = parse_config_file(0);
1334         if (ret < 0)
1335                 goto out;
1336         if (ret == 0) { /* no config file given */
1337                 /*
1338                  * Parse the command line options again, but this time check
1339                  * that all required options are given.
1340                  */
1341                 params = (struct cmdline_parser_params) {
1342                         .override = 1,
1343                         .initialize = 1,
1344                         .check_required = 1,
1345                         .check_ambiguity = 1,
1346                         .print_errors = 1
1347                 };
1348                 cmdline_parser_ext(argc, argv, &conf, &params); /* aborts on errors */
1349         }
1350         if (conf.daemon_given)
1351                 daemon_init();
1352         dump_dss_config("dss configuration");
1353         ret = change_to_dest_dir();
1354         if (ret < 0)
1355                 goto out;
1356         ret = setup_signal_handling();
1357         if (ret < 0)
1358                 goto out;
1359         ret = call_command_handler();
1360 out:
1361         if (ret < 0)
1362                 DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
1363         exit(ret >= 0? EXIT_SUCCESS : EXIT_FAILURE);
1364 }