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