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