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