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