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