Fix compute_next_snapshot_time().
[dss.git] / dss.c
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #include <string.h>
3 #include <stdlib.h>
4 #include <stdio.h>
5 #include <stdarg.h>
6 #include <assert.h>
7 #include <errno.h>
8 #include <sys/types.h>
9 #include <signal.h>
10 #include <ctype.h>
11 #include <stdbool.h>
12 #include <sys/stat.h>
13 #include <unistd.h>
14 #include <inttypes.h>
15 #include <sys/time.h>
16 #include <time.h>
17 #include <sys/wait.h>
18 #include <fnmatch.h>
19 #include <limits.h>
20 #include <fcntl.h>
21 #include <lopsub.h>
22 #include <sys/mman.h>
23
24 #include "gcc-compat.h"
25 #include "log.h"
26 #include "str.h"
27 #include "err.h"
28 #include "file.h"
29 #include "exec.h"
30 #include "daemon.h"
31 #include "sig.h"
32 #include "df.h"
33 #include "tv.h"
34 #include "snap.h"
35 #include "ipc.h"
36 #include "dss.lsg.h"
37
38 #define CMD_PTR(_cname) lls_cmd(LSG_DSS_CMD_ ## _cname, dss_suite)
39 #define OPT_RESULT(_cname, _oname) (lls_opt_result(\
40         LSG_DSS_ ## _cname ## _OPT_ ## _oname, (CMD_PTR(_cname) == CMD_PTR(DSS))? lpr : sublpr))
41 #define OPT_GIVEN(_cname, _oname) (lls_opt_given(OPT_RESULT(_cname, _oname)))
42 #define OPT_STRING_VAL(_cname, _oname) (lls_string_val(0, \
43         OPT_RESULT(_cname, _oname)))
44 #define OPT_UINT32_VAL(_cname, _oname) (lls_uint32_val(0, \
45                 OPT_RESULT(_cname, _oname)))
46
47 struct dss_user_data {int (*handler)(void);};
48 #define EXPORT_CMD_HANDLER(_cmd) const struct dss_user_data \
49         lsg_dss_com_ ## _cmd ## _user_data = { \
50                 .handler = com_ ## _cmd \
51         };
52
53 /*
54  * Command line and active options. We need to keep a copy of the parsed
55  * command line options for the SIGHUP case where we merge the command line
56  * options and the new config file options.
57  */
58 static struct lls_parse_result *cmdline_lpr, *lpr;
59
60 /** Parsed subcommand options. */
61 static struct lls_parse_result *cmdline_sublpr, *sublpr;
62 /* The executing subcommand (NULL at startup). */
63 static const struct lls_command *subcmd;
64 /** Wether daemon_init() was called. */
65 static bool daemonized;
66 /** Non-NULL if we log to a file. */
67 static FILE *logfile;
68 /** The read end of the signal pipe */
69 static int signal_pipe;
70 /** Process id of current pre-create-hook/rsync/post-create-hook process. */
71 static pid_t create_pid;
72 /** Whether the pre-create-hook/rsync/post-create-hook is currently stopped. */
73 static int create_process_stopped;
74 /** How many times in a row the rsync command failed. */
75 static int num_consecutive_rsync_errors;
76 /** Process id of current pre-remove/rm/post-remove process. */
77 static pid_t remove_pid;
78 /** When the next snapshot is due. */
79 static int64_t next_snapshot_time;
80 /** When to try to remove something. */
81 static struct timeval next_removal_check;
82 /** Creation time of the snapshot currently being created. */
83 static int64_t current_snapshot_creation_time;
84 /** The snapshot currently being removed. */
85 struct snapshot *snapshot_currently_being_removed;
86 /** Needed by the post-create hook. */
87 static char *path_to_last_complete_snapshot;
88 static char *name_of_reference_snapshot;
89 /** \sa \ref snap.h for details. */
90 enum hook_status snapshot_creation_status;
91 /** \sa \ref snap.h for details. */
92 enum hook_status snapshot_removal_status;
93
94
95 DEFINE_DSS_ERRLIST;
96 static const char *hook_status_description[] = {HOOK_STATUS_ARRAY};
97
98 /* may be called with ds == NULL. */
99 static int disk_space_low(struct disk_space *ds)
100 {
101         struct disk_space ds_struct;
102         uint32_t val;
103
104         if (!ds) {
105                 int ret = get_disk_space(".", &ds_struct);
106                 if (ret < 0)
107                         return ret;
108                 ds = &ds_struct;
109         }
110         val = OPT_UINT32_VAL(DSS, MIN_FREE_MB);
111         if (val != 0)
112                 if (ds->free_mb < val)
113                         return 1;
114         val = OPT_UINT32_VAL(DSS, MIN_FREE_PERCENT);
115         if (val != 0)
116                 if (ds->percent_free < val)
117                         return 1;
118         val = OPT_UINT32_VAL(DSS, MIN_FREE_PERCENT_INODES);
119         if (val != 0)
120                 if (ds->percent_free_inodes < val)
121                         return 1;
122         return 0;
123 }
124
125 static void dump_dss_config(const char *msg)
126 {
127         const char dash[] = "-----------------------------";
128         char *lopsub_dump;
129         int ret;
130         FILE *log = logfile? logfile : stderr;
131         struct disk_space ds;
132         int64_t now = get_current_time();
133
134         if (OPT_UINT32_VAL(DSS, LOGLEVEL) > INFO)
135                 return;
136
137         fprintf(log, "%s <%s config> %s\n", dash, msg, dash);
138         fprintf(log, "\n*** disk space ***\n\n");
139         ret = get_disk_space(".", &ds);
140         if (ret >= 0) {
141                 DSS_INFO_LOG(("disk space low: %s\n", disk_space_low(&ds)?
142                         "yes" : "no"));
143                 log_disk_space(&ds);
144         } else
145                 DSS_ERROR_LOG(("can not get free disk space: %s\n",
146                         dss_strerror(-ret)));
147
148         /* we continue on errors from get_disk_space */
149
150         fprintf(log, "\n*** non-default options ***\n\n");
151         lopsub_dump = lls_dump_parse_result(lpr, CMD_PTR(DSS), true);
152         fprintf(log, "%s", lopsub_dump);
153         free(lopsub_dump);
154         fprintf(log, "\n*** non-default options for \"run\" ***\n\n");
155         lopsub_dump = lls_dump_parse_result(lpr, CMD_PTR(RUN), true);
156         fprintf(log, "%s", lopsub_dump);
157         free(lopsub_dump);
158         fprintf(log, "\n*** internal state ***\n\n");
159         fprintf(log,
160                 "pid: %d\n"
161                 "logile: %s\n"
162                 "snapshot_currently_being_removed: %s\n"
163                 "path_to_last_complete_snapshot: %s\n"
164                 "reference_snapshot: %s\n"
165                 "snapshot_creation_status: %s\n"
166                 "snapshot_removal_status: %s\n"
167                 "num_consecutive_rsync_errors: %d\n"
168                 ,
169                 (int) getpid(),
170                 logfile? OPT_STRING_VAL(RUN, LOGFILE) : "stderr",
171                 snapshot_currently_being_removed?
172                         snapshot_currently_being_removed->name : "(none)",
173                 path_to_last_complete_snapshot?
174                         path_to_last_complete_snapshot : "(none)",
175                 name_of_reference_snapshot?
176                         name_of_reference_snapshot : "(none)",
177                 hook_status_description[snapshot_creation_status],
178                 hook_status_description[snapshot_removal_status],
179                 num_consecutive_rsync_errors
180         );
181         if (create_pid != 0)
182                 fprintf(log,
183                         "create_pid: %" PRId32 "\n"
184                         "create process is %sstopped\n"
185                         ,
186                         create_pid,
187                         create_process_stopped? "" : "not "
188                 );
189         if (remove_pid != 0)
190                 fprintf(log, "remove_pid: %" PRId32 "\n", remove_pid);
191         if (next_snapshot_time != 0)
192                 fprintf(log, "next snapshot due in %" PRId64 " seconds\n",
193                         next_snapshot_time - now);
194         if (current_snapshot_creation_time != 0)
195                 fprintf(log, "current_snapshot_creation_time: %"
196                         PRId64 " (%" PRId64 " seconds ago)\n",
197                         current_snapshot_creation_time,
198                         now - current_snapshot_creation_time
199                 );
200         if (next_removal_check.tv_sec != 0) {
201                 fprintf(log, "next removal check: %llu (%llu seconds ago)\n",
202                         (long long unsigned)next_removal_check.tv_sec,
203                         now - (long long unsigned)next_removal_check.tv_sec
204                 );
205
206         }
207         fprintf(log, "%s </%s config> %s\n", dash, msg, dash);
208 }
209
210 static int loglevel = -1;
211 static const char *location_file = NULL;
212 static int         location_line = -1;
213 static const char *location_func = NULL;
214
215 void dss_log_set_params(int ll, const char *file, int line, const char *func)
216 {
217         loglevel = ll;
218         location_file = file;
219         location_line = line;
220         location_func = func;
221 }
222
223 /**
224  * The log function of dss.
225  *
226  * \param ll Loglevel.
227  * \param fml Usual format string.
228  *
229  * All DSS_XXX_LOG() macros use this function.
230  */
231 __printf_1_2 void dss_log(const char* fmt,...)
232 {
233         va_list argp;
234         FILE *outfd;
235         struct tm *tm;
236         time_t t1;
237         char str[255] = "";
238         int lpr_ll = lpr? OPT_UINT32_VAL(DSS, LOGLEVEL) : WARNING;
239
240         if (loglevel < lpr_ll)
241                 return;
242         outfd = logfile? logfile : stderr;
243         if (subcmd == CMD_PTR(RUN)) {
244                 time(&t1);
245                 tm = localtime(&t1);
246                 strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
247                 fprintf(outfd, "%s ", str);
248                 if (lpr_ll <= INFO)
249                         fprintf(outfd, "%i: ", loglevel);
250         }
251         if (subcmd == CMD_PTR(RUN))
252 #ifdef DSS_NO_FUNC_NAMES
253                 fprintf(outfd, "%s:%d: ", location_file, location_line);
254 #else
255                 fprintf(outfd, "%s: ", location_func);
256 #endif
257         va_start(argp, fmt);
258         vfprintf(outfd, fmt, argp);
259         va_end(argp);
260 }
261
262 /**
263  * Print a message either to stdout or to the log file.
264  */
265 static __printf_1_2 void dss_msg(const char* fmt,...)
266 {
267         FILE *outfd = logfile? logfile : stdout;
268         va_list argp;
269         va_start(argp, fmt);
270         vfprintf(outfd, fmt, argp);
271         va_end(argp);
272 }
273
274 static char *get_config_file_name(void)
275 {
276         char *home, *config_file;
277
278         if (OPT_GIVEN(DSS, CONFIG_FILE))
279                 return dss_strdup(OPT_STRING_VAL(DSS, CONFIG_FILE));
280         home = get_homedir();
281         config_file = make_message("%s/.dssrc", home);
282         free(home);
283         return config_file;
284 }
285
286 static int send_signal(int sig, bool wait)
287 {
288         pid_t pid;
289         char *config_file = get_config_file_name();
290         int ret = get_dss_pid(config_file, &pid);
291         unsigned ms = 32;
292         struct timespec ts;
293
294         free(config_file);
295         if (ret < 0)
296                 return ret;
297         if (OPT_GIVEN(DSS, DRY_RUN)) {
298                 dss_msg("%d\n", (int)pid);
299                 return 0;
300         }
301         DSS_NOTICE_LOG(("sending signal %d to pid %d\n", sig, (int)pid));
302         ret = kill(pid, sig);
303         if (ret < 0)
304                 return -ERRNO_TO_DSS_ERROR(errno);
305         if (!wait)
306                 return 1;
307         while (ms < 5000) {
308                 ts.tv_sec = ms / 1000;
309                 ts.tv_nsec = (ms % 1000) * 1000 * 1000;
310                 ret = nanosleep(&ts, NULL);
311                 if (ret < 0)
312                         return -ERRNO_TO_DSS_ERROR(errno);
313                 ret = kill(pid, 0);
314                 if (ret < 0) {
315                         if (errno != ESRCH)
316                                 return -ERRNO_TO_DSS_ERROR(errno);
317                         return 1;
318                 }
319                 ms *= 2;
320         }
321         return -E_KILL_TIMEOUT;
322 }
323
324 struct signal_info {
325         const char * const name;
326         int num;
327 };
328
329 /*
330  * The table below was taken 2016 from proc/sig.c of procps-3.2.8. Copyright
331  * 1998-2003 by Albert Cahalan, GPLv2.
332  */
333 static const struct signal_info signal_table[] = {
334         {"ABRT",   SIGABRT},  /* IOT */
335         {"ALRM",   SIGALRM},
336         {"BUS",    SIGBUS},
337         {"CHLD",   SIGCHLD},  /* CLD */
338         {"CONT",   SIGCONT},
339         {"FPE",    SIGFPE},
340         {"HUP",    SIGHUP},
341         {"ILL",    SIGILL},
342         {"INT",    SIGINT},
343         {"KILL",   SIGKILL},
344         {"PIPE",   SIGPIPE},
345 #ifdef SIGPOLL
346         {"POLL",   SIGPOLL},  /* IO */
347 #endif
348         {"PROF",   SIGPROF},
349 #ifdef SIGPWR
350         {"PWR",    SIGPWR},
351 #endif
352         {"QUIT",   SIGQUIT},
353         {"SEGV",   SIGSEGV},
354 #ifdef SIGSTKFLT
355         {"STKFLT", SIGSTKFLT},
356 #endif
357         {"STOP",   SIGSTOP},
358         {"SYS",    SIGSYS},   /* UNUSED */
359         {"TERM",   SIGTERM},
360         {"TRAP",   SIGTRAP},
361         {"TSTP",   SIGTSTP},
362         {"TTIN",   SIGTTIN},
363         {"TTOU",   SIGTTOU},
364         {"URG",    SIGURG},
365         {"USR1",   SIGUSR1},
366         {"USR2",   SIGUSR2},
367         {"VTALRM", SIGVTALRM},
368         {"WINCH",  SIGWINCH},
369         {"XCPU",   SIGXCPU},
370         {"XFSZ",   SIGXFSZ}
371 };
372
373 #define SIGNAL_TABLE_SIZE (sizeof(signal_table) / sizeof(signal_table[0]))
374 #ifndef SIGRTMAX
375 #define SIGRTMAX 64
376 #endif
377
378 static int com_kill(void)
379 {
380         bool w_given = OPT_GIVEN(KILL, WAIT);
381         const char *arg = OPT_STRING_VAL(KILL, SIGNAL);
382         int ret, i;
383
384         if (*arg >= '0' && *arg <= '9') {
385                 int64_t val;
386                 ret = dss_atoi64(arg, &val);
387                 if (ret < 0)
388                         return ret;
389                 if (val < 0 || val > SIGRTMAX)
390                         return -ERRNO_TO_DSS_ERROR(EINVAL);
391                 return send_signal(val, w_given);
392         }
393         if (strncasecmp(arg, "sig", 3) == 0)
394                 arg += 3;
395         if (strcasecmp(arg, "CLD") == 0)
396                 return send_signal(SIGCHLD, w_given);
397         if (strcasecmp(arg, "IOT") == 0)
398                 return send_signal(SIGABRT, w_given);
399         for (i = 0; i < SIGNAL_TABLE_SIZE; i++)
400                 if (strcasecmp(arg, signal_table[i].name) == 0)
401                         return send_signal(signal_table[i].num, w_given);
402         DSS_ERROR_LOG(("invalid sigspec: %s\n", arg));
403         return -ERRNO_TO_DSS_ERROR(EINVAL);
404 }
405 EXPORT_CMD_HANDLER(kill);
406
407 static void dss_get_snapshot_list(struct snapshot_list *sl)
408 {
409         get_snapshot_list(sl, OPT_UINT32_VAL(DSS, UNIT_INTERVAL),
410                 OPT_UINT32_VAL(DSS, NUM_INTERVALS));
411 }
412
413 static int64_t compute_next_snapshot_time(void)
414 {
415         int64_t x = 0, now = get_current_time(), unit_interval
416                 = 24 * 3600 * OPT_UINT32_VAL(DSS, UNIT_INTERVAL), ret,
417                 last_completion_time;
418         unsigned wanted = desired_number_of_snapshots(0,
419                 OPT_UINT32_VAL(DSS, NUM_INTERVALS)),
420                 num_complete = 0;
421         int i;
422         struct snapshot *s = NULL;
423         struct snapshot_list sl;
424
425         dss_get_snapshot_list(&sl);
426         FOR_EACH_SNAPSHOT(s, i, &sl) {
427                 if (!(s->flags & SS_COMPLETE))
428                         continue;
429                 num_complete++;
430                 x += s->completion_time - s->creation_time;
431                 last_completion_time = s->completion_time;
432         }
433         assert(x >= 0);
434
435         ret = now;
436         if (num_complete == 0)
437                 goto out;
438         x /= num_complete; /* avg time to create one snapshot */
439         if (unit_interval < x * wanted) /* oops, no sleep at all */
440                 goto out;
441         ret = last_completion_time + unit_interval / wanted - x;
442 out:
443         free_snapshot_list(&sl);
444         return ret;
445 }
446
447 static inline void invalidate_next_snapshot_time(void)
448 {
449         next_snapshot_time = 0;
450 }
451
452 static inline int next_snapshot_time_is_valid(void)
453 {
454         return next_snapshot_time != 0;
455 }
456
457 static int next_snapshot_is_due(void)
458 {
459         int64_t now = get_current_time();
460
461         if (!next_snapshot_time_is_valid())
462                 next_snapshot_time = compute_next_snapshot_time();
463         if (next_snapshot_time <= now) {
464                 DSS_DEBUG_LOG(("next snapshot: now\n"));
465                 return 1;
466         }
467         DSS_DEBUG_LOG(("next snapshot due in %" PRId64 " seconds\n",
468                 next_snapshot_time - now));
469         return 0;
470 }
471
472 static void pre_create_hook(void)
473 {
474         assert(snapshot_creation_status == HS_READY);
475         /* make sure that the next snapshot time will be recomputed */
476         invalidate_next_snapshot_time();
477         DSS_DEBUG_LOG(("executing %s\n", OPT_STRING_VAL(DSS, PRE_CREATE_HOOK)));
478         dss_exec_cmdline_pid(&create_pid, OPT_STRING_VAL(DSS, PRE_CREATE_HOOK));
479         snapshot_creation_status = HS_PRE_RUNNING;
480 }
481
482 static void pre_remove_hook(struct snapshot *s, const char *why)
483 {
484         char *cmd;
485
486         if (!s)
487                 return;
488         DSS_DEBUG_LOG(("%s snapshot %s\n", why, s->name));
489         assert(snapshot_removal_status == HS_READY);
490         assert(remove_pid == 0);
491         assert(!snapshot_currently_being_removed);
492
493         snapshot_currently_being_removed = dss_malloc(sizeof(struct snapshot));
494         *snapshot_currently_being_removed = *s;
495         snapshot_currently_being_removed->name = dss_strdup(s->name);
496
497         cmd = make_message("%s %s/%s", OPT_STRING_VAL(DSS, PRE_REMOVE_HOOK),
498                 OPT_STRING_VAL(DSS, DEST_DIR), s->name);
499         DSS_DEBUG_LOG(("executing %s\n", cmd));
500         dss_exec_cmdline_pid(&remove_pid, cmd);
501         free(cmd);
502         snapshot_removal_status = HS_PRE_RUNNING;
503 }
504
505 static int exec_rm(void)
506 {
507         struct snapshot *s = snapshot_currently_being_removed;
508         char *new_name = being_deleted_name(s);
509         char *argv[4];
510         int ret;
511
512         argv[0] = "rm";
513         argv[1] = "-rf";
514         argv[2] = new_name;
515         argv[3] = NULL;
516
517         assert(snapshot_removal_status == HS_PRE_SUCCESS);
518         assert(remove_pid == 0);
519
520         DSS_NOTICE_LOG(("removing %s (interval = %i)\n", s->name, s->interval));
521         ret = dss_rename(s->name, new_name);
522         if (ret < 0)
523                 goto out;
524         dss_exec(&remove_pid, argv[0], argv);
525         snapshot_removal_status = HS_RUNNING;
526 out:
527         free(new_name);
528         return ret;
529 }
530
531 static int snapshot_is_being_created(struct snapshot *s)
532 {
533         return s->creation_time == current_snapshot_creation_time;
534 }
535
536 static struct snapshot *find_orphaned_snapshot(struct snapshot_list *sl)
537 {
538         struct snapshot *s;
539         int i;
540
541         DSS_DEBUG_LOG(("looking for old incomplete snapshots\n"));
542         FOR_EACH_SNAPSHOT(s, i, sl) {
543                 if (snapshot_is_being_created(s))
544                         continue;
545                 /*
546                  * We know that no rm is currently running, so if s is marked
547                  * as being deleted, a previously started rm must have failed.
548                  */
549                 if (s->flags & SS_BEING_DELETED)
550                         return s;
551
552                 if (s->flags & SS_COMPLETE) /* good snapshot */
553                         continue;
554                 /*
555                  * This snapshot is incomplete and it is not the snapshot
556                  * currently being created. However, we must not remove it if
557                  * rsync is about to be restarted. As only the newest snapshot
558                  * can be restarted, this snapshot is orphaned if it is not the
559                  * newest snapshot or if we are not about to restart rsync.
560                  */
561                 if (get_newest_snapshot(sl) != s)
562                         return s;
563                 if (snapshot_creation_status != HS_NEEDS_RESTART)
564                         return s;
565         }
566         /* no orphaned snapshots */
567         return NULL;
568 }
569
570 static int is_reference_snapshot(struct snapshot *s)
571 {
572         if (!name_of_reference_snapshot)
573                 return 0;
574         return strcmp(s->name, name_of_reference_snapshot)? 0 : 1;
575 }
576
577 /*
578  * return: 0: no redundant snapshots, 1: rm process started, negative: error
579  */
580 static struct snapshot *find_redundant_snapshot(struct snapshot_list *sl)
581 {
582         int i, interval;
583         struct snapshot *s;
584         unsigned missing = 0;
585         uint32_t N = OPT_UINT32_VAL(DSS, NUM_INTERVALS);
586
587         DSS_DEBUG_LOG(("looking for intervals containing too many snapshots\n"));
588         for (interval = N - 1; interval >= 0; interval--) {
589                 unsigned keep = desired_number_of_snapshots(interval, N);
590                 unsigned num = sl->interval_count[interval];
591                 struct snapshot *victim = NULL, *prev = NULL;
592                 int64_t score = LONG_MAX;
593
594                 if (keep >= num)
595                         missing += keep - num;
596                 if (keep + missing >= num)
597                         continue;
598                 /* redundant snapshot in this interval, pick snapshot with lowest score */
599                 FOR_EACH_SNAPSHOT(s, i, sl) {
600                         int64_t this_score;
601
602                         if (snapshot_is_being_created(s))
603                                 continue;
604                         if (is_reference_snapshot(s))
605                                 continue;
606                         if (s->interval > interval) {
607                                 prev = s;
608                                 continue;
609                         }
610                         if (s->interval < interval)
611                                 break;
612                         if (!victim) {
613                                 victim = s;
614                                 prev = s;
615                                 continue;
616                         }
617                         assert(prev);
618                         /* check if s is a better victim */
619                         this_score = s->creation_time - prev->creation_time;
620                         assert(this_score >= 0);
621                         if (this_score < score) {
622                                 score = this_score;
623                                 victim = s;
624                         }
625                         prev = s;
626                 }
627                 assert(victim);
628                 return victim;
629         }
630         return NULL;
631 }
632
633 static struct snapshot *find_outdated_snapshot(struct snapshot_list *sl)
634 {
635         int i;
636         struct snapshot *s;
637
638         DSS_DEBUG_LOG(("looking for snapshots belonging to intervals >= %d\n",
639                 OPT_UINT32_VAL(DSS, NUM_INTERVALS)));
640         FOR_EACH_SNAPSHOT(s, i, sl) {
641                 if (snapshot_is_being_created(s))
642                         continue;
643                 if (is_reference_snapshot(s))
644                         continue;
645                 if (s->interval < OPT_UINT32_VAL(DSS, NUM_INTERVALS))
646                         continue;
647                 return s;
648         }
649         return NULL;
650 }
651
652 static struct snapshot *find_oldest_removable_snapshot(struct snapshot_list *sl)
653 {
654         int i, num_complete;
655         struct snapshot *s, *ref = NULL;
656
657         num_complete = num_complete_snapshots(sl);
658         if (num_complete <= OPT_UINT32_VAL(DSS, MIN_COMPLETE))
659                 return NULL;
660         FOR_EACH_SNAPSHOT(s, i, sl) {
661                 if (snapshot_is_being_created(s))
662                         continue;
663                 if (is_reference_snapshot(s)) { /* avoid this one */
664                         ref = s;
665                         continue;
666                 }
667                 DSS_INFO_LOG(("oldest removable snapshot: %s\n", s->name));
668                 return s;
669         }
670         assert(ref);
671         DSS_WARNING_LOG(("removing reference snapshot %s\n", ref->name));
672         return ref;
673 }
674
675 static int rename_incomplete_snapshot(int64_t start)
676 {
677         char *old_name;
678         int ret;
679         int64_t now;
680
681         /*
682          * We don't want the dss_rename() below to fail with EEXIST because the
683          * last complete snapshot was created (and completed) in the same
684          * second as this one.
685          */
686         while ((now = get_current_time()) == start)
687                 sleep(1);
688         free(path_to_last_complete_snapshot);
689         ret = complete_name(start, now, &path_to_last_complete_snapshot);
690         if (ret < 0)
691                 return ret;
692         old_name = incomplete_name(start);
693         ret = dss_rename(old_name, path_to_last_complete_snapshot);
694         if (ret >= 0)
695                 DSS_NOTICE_LOG(("%s -> %s\n", old_name,
696                         path_to_last_complete_snapshot));
697         free(old_name);
698         return ret;
699 }
700
701 static int try_to_free_disk_space(void)
702 {
703         int ret;
704         struct snapshot_list sl;
705         struct snapshot *victim;
706         struct timeval now;
707         const char *why;
708         int low_disk_space;
709
710         ret = disk_space_low(NULL);
711         if (ret < 0)
712                 return ret;
713         low_disk_space = ret;
714         gettimeofday(&now, NULL);
715         if (tv_diff(&next_removal_check, &now, NULL) > 0)
716                 return 0;
717         if (!low_disk_space) {
718                 if (OPT_GIVEN(DSS, KEEP_REDUNDANT))
719                         return 0;
720                 if (snapshot_creation_status != HS_READY)
721                         return 0;
722                 if (next_snapshot_is_due())
723                         return 0;
724         }
725         /*
726          * Idle and --keep_redundant not given, or low disk space. Look at
727          * existing snapshots.
728          */
729         dss_get_snapshot_list(&sl);
730         ret = 0;
731         /*
732          * Don't remove anything if there is free space and we have fewer
733          * snapshots than configured, plus one. This way there is always one
734          * snapshot that can be recycled.
735          */
736         if (!low_disk_space && sl.num_snapshots <=
737                         1 << OPT_UINT32_VAL(DSS, NUM_INTERVALS))
738                 goto out;
739         why = "outdated";
740         victim = find_outdated_snapshot(&sl);
741         if (victim)
742                 goto remove;
743         why = "redundant";
744         victim = find_redundant_snapshot(&sl);
745         if (victim)
746                 goto remove;
747         why = "orphaned";
748         victim = find_orphaned_snapshot(&sl);
749         if (victim)
750                 goto remove;
751         /* try harder only if disk space is low */
752         if (!low_disk_space)
753                 goto out;
754         DSS_WARNING_LOG(("disk space low and nothing obvious to remove\n"));
755         why = "oldest";
756         victim = find_oldest_removable_snapshot(&sl);
757         if (victim)
758                 goto remove;
759         DSS_CRIT_LOG(("uhuhu: disk space low and nothing to remove\n"));
760         ret = -ERRNO_TO_DSS_ERROR(ENOSPC);
761         goto out;
762 remove:
763         pre_remove_hook(victim, why);
764 out:
765         free_snapshot_list(&sl);
766         return ret;
767 }
768
769 static void post_create_hook(void)
770 {
771         char *cmd = make_message("%s %s/%s",
772                 OPT_STRING_VAL(DSS, POST_CREATE_HOOK),
773                 OPT_STRING_VAL(DSS, DEST_DIR), path_to_last_complete_snapshot);
774         DSS_NOTICE_LOG(("executing %s\n", cmd));
775         dss_exec_cmdline_pid(&create_pid, cmd);
776         free(cmd);
777         snapshot_creation_status = HS_POST_RUNNING;
778 }
779
780 static void post_remove_hook(void)
781 {
782         char *cmd;
783         struct snapshot *s = snapshot_currently_being_removed;
784
785         assert(s);
786
787         cmd = make_message("%s %s/%s", OPT_STRING_VAL(DSS, POST_REMOVE_HOOK),
788                 OPT_STRING_VAL(DSS, DEST_DIR), s->name);
789         DSS_NOTICE_LOG(("executing %s\n", cmd));
790         dss_exec_cmdline_pid(&remove_pid, cmd);
791         free(cmd);
792         snapshot_removal_status = HS_POST_RUNNING;
793 }
794
795 static void dss_kill(pid_t pid, int sig, const char *msg)
796 {
797         const char *signame, *process_name;
798
799         if (pid == 0)
800                 return;
801         switch (sig) {
802         case SIGTERM: signame = "TERM"; break;
803         case SIGSTOP: signame = "STOP"; break;
804         case SIGCONT: signame = "CONT"; break;
805         default: signame = "????";
806         }
807
808         if (pid == create_pid)
809                 process_name = "create";
810         else if (pid == remove_pid)
811                 process_name = "remove";
812         else process_name = "??????";
813
814         if (msg)
815                 DSS_INFO_LOG(("%s\n", msg));
816         DSS_DEBUG_LOG(("sending signal %d (%s) to pid %d (%s process)\n",
817                 sig, signame, (int)pid, process_name));
818         if (kill(pid, sig) >= 0)
819                 return;
820         DSS_INFO_LOG(("failed to send signal %d (%s) to pid %d (%s process)\n",
821                 sig, signame, (int)pid, process_name));
822 }
823
824 static void stop_create_process(void)
825 {
826         if (create_process_stopped)
827                 return;
828         dss_kill(create_pid, SIGSTOP, "suspending create process");
829         create_process_stopped = 1;
830 }
831
832 static void restart_create_process(void)
833 {
834         if (!create_process_stopped)
835                 return;
836         dss_kill(create_pid, SIGCONT, "resuming create process");
837         create_process_stopped = 0;
838 }
839
840 /**
841  * Print a log message about the exit status of a child.
842  */
843 static void log_termination_msg(pid_t pid, int status)
844 {
845         if (WIFEXITED(status))
846                 DSS_INFO_LOG(("child %i exited. Exit status: %i\n", (int)pid,
847                         WEXITSTATUS(status)));
848         else if (WIFSIGNALED(status))
849                 DSS_NOTICE_LOG(("child %i was killed by signal %i\n", (int)pid,
850                         WTERMSIG(status)));
851         else
852                 DSS_WARNING_LOG(("child %i terminated abormally\n", (int)pid));
853 }
854
855 static int wait_for_process(pid_t pid, int *status)
856 {
857         int ret;
858
859         DSS_DEBUG_LOG(("Waiting for process %d to terminate\n", (int)pid));
860         for (;;) {
861                 fd_set rfds;
862
863                 FD_ZERO(&rfds);
864                 FD_SET(signal_pipe, &rfds);
865                 ret = dss_select(signal_pipe + 1, &rfds, NULL, NULL);
866                 if (ret < 0)
867                         break;
868                 ret = next_signal();
869                 if (!ret)
870                         continue;
871                 if (ret == SIGCHLD) {
872                         ret = waitpid(pid, status, 0);
873                         if (ret >= 0)
874                                 break;
875                         if (errno != EINTR) { /* error */
876                                 ret = -ERRNO_TO_DSS_ERROR(errno);
877                                 break;
878                         }
879                 }
880                 /* SIGINT or SIGTERM */
881                 dss_kill(pid, SIGTERM, "killing child process");
882         }
883         if (ret < 0)
884                 DSS_ERROR_LOG(("failed to wait for process %d\n", (int)pid));
885         else
886                 log_termination_msg(pid, *status);
887         return ret;
888 }
889
890 static void handle_pre_remove_exit(int status)
891 {
892         if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
893                 snapshot_removal_status = HS_READY;
894                 gettimeofday(&next_removal_check, NULL);
895                 next_removal_check.tv_sec += 60;
896                 return;
897         }
898         snapshot_removal_status = HS_PRE_SUCCESS;
899 }
900
901 static int handle_rm_exit(int status)
902 {
903         if (!WIFEXITED(status)) {
904                 snapshot_removal_status = HS_READY;
905                 return -E_INVOLUNTARY_EXIT;
906         }
907         if (WEXITSTATUS(status)) {
908                 snapshot_removal_status = HS_READY;
909                 return -E_BAD_EXIT_CODE;
910         }
911         snapshot_removal_status = HS_SUCCESS;
912         return 1;
913 }
914
915 static void handle_post_remove_exit(void)
916 {
917         snapshot_removal_status = HS_READY;
918 }
919
920 static int handle_remove_exit(int status)
921 {
922         int ret;
923         struct snapshot *s = snapshot_currently_being_removed;
924
925         assert(s);
926         switch (snapshot_removal_status) {
927         case HS_PRE_RUNNING:
928                 handle_pre_remove_exit(status);
929                 ret = 1;
930                 break;
931         case HS_RUNNING:
932                 ret = handle_rm_exit(status);
933                 break;
934         case HS_POST_RUNNING:
935                 handle_post_remove_exit();
936                 ret = 1;
937                 break;
938         default:
939                 ret = -E_BUG;
940         }
941         if (snapshot_removal_status == HS_READY) {
942                 free(s->name);
943                 free(s);
944                 snapshot_currently_being_removed = NULL;
945         }
946         remove_pid = 0;
947         return ret;
948 }
949
950 static int wait_for_remove_process(void)
951 {
952         int status, ret;
953
954         assert(remove_pid);
955         assert(
956                 snapshot_removal_status == HS_PRE_RUNNING ||
957                 snapshot_removal_status == HS_RUNNING ||
958                 snapshot_removal_status == HS_POST_RUNNING
959         );
960         ret = wait_for_process(remove_pid, &status);
961         if (ret < 0)
962                 return ret;
963         return handle_remove_exit(status);
964 }
965
966 static int handle_rsync_exit(int status)
967 {
968         int es, ret;
969
970         if (!WIFEXITED(status)) {
971                 DSS_ERROR_LOG(("rsync process %d died involuntary\n", (int)create_pid));
972                 ret = -E_INVOLUNTARY_EXIT;
973                 snapshot_creation_status = HS_READY;
974                 goto out;
975         }
976         es = WEXITSTATUS(status);
977         /*
978          * Restart rsync on non-fatal errors:
979          * 24: Partial transfer due to vanished source files
980          */
981         if (es != 0 && es != 24) {
982                 DSS_WARNING_LOG(("rsync exit code %d, error count %d\n",
983                         es, ++num_consecutive_rsync_errors));
984                 if (!logfile) { /* called by com_run() */
985                         ret = -E_BAD_EXIT_CODE;
986                         goto out;
987                 }
988                 if (num_consecutive_rsync_errors >
989                                 OPT_UINT32_VAL(RUN, MAX_RSYNC_ERRORS)) {
990                         ret = -E_TOO_MANY_RSYNC_ERRORS;
991                         snapshot_creation_status = HS_READY;
992                         goto out;
993                 }
994                 DSS_WARNING_LOG(("restarting rsync process\n"));
995                 snapshot_creation_status = HS_NEEDS_RESTART;
996                 next_snapshot_time = get_current_time() + 60;
997                 ret = 1;
998                 goto out;
999         }
1000         num_consecutive_rsync_errors = 0;
1001         ret = rename_incomplete_snapshot(current_snapshot_creation_time);
1002         if (ret < 0)
1003                 goto out;
1004         snapshot_creation_status = HS_SUCCESS;
1005         free(name_of_reference_snapshot);
1006         name_of_reference_snapshot = NULL;
1007 out:
1008         create_process_stopped = 0;
1009         return ret;
1010 }
1011
1012 static int handle_pre_create_hook_exit(int status)
1013 {
1014         int es, ret;
1015         static int warn_count;
1016
1017         if (!WIFEXITED(status)) {
1018                 snapshot_creation_status = HS_READY;
1019                 ret = -E_INVOLUNTARY_EXIT;
1020                 goto out;
1021         }
1022         es = WEXITSTATUS(status);
1023         if (es) {
1024                 if (!warn_count--) {
1025                         DSS_NOTICE_LOG(("pre_create_hook %s returned %d\n",
1026                                 OPT_STRING_VAL(DSS, PRE_CREATE_HOOK), es));
1027                         DSS_NOTICE_LOG(("deferring snapshot creation...\n"));
1028                         warn_count = 60; /* warn only once per hour */
1029                 }
1030                 next_snapshot_time = get_current_time() + 60;
1031                 snapshot_creation_status = HS_READY;
1032                 ret = 0;
1033                 goto out;
1034         }
1035         warn_count = 0;
1036         snapshot_creation_status = HS_PRE_SUCCESS;
1037         ret = 1;
1038 out:
1039         return ret;
1040 }
1041
1042 static int handle_sigchld(void)
1043 {
1044         pid_t pid;
1045         int status, ret = reap_child(&pid, &status);
1046
1047         if (ret <= 0)
1048                 return ret;
1049
1050         if (pid == create_pid) {
1051                 switch (snapshot_creation_status) {
1052                 case HS_PRE_RUNNING:
1053                         ret = handle_pre_create_hook_exit(status);
1054                         break;
1055                 case HS_RUNNING:
1056                         ret = handle_rsync_exit(status);
1057                         break;
1058                 case HS_POST_RUNNING:
1059                         snapshot_creation_status = HS_READY;
1060                         ret = 1;
1061                         break;
1062                 default:
1063                         DSS_EMERG_LOG(("BUG: create can't die in status %d\n",
1064                                 snapshot_creation_status));
1065                         return -E_BUG;
1066                 }
1067                 create_pid = 0;
1068                 return ret;
1069         }
1070         if (pid == remove_pid) {
1071                 ret = handle_remove_exit(status);
1072                 if (ret < 0)
1073                         return ret;
1074                 return ret;
1075         }
1076         DSS_EMERG_LOG(("BUG: unknown process %d died\n", (int)pid));
1077         return -E_BUG;
1078 }
1079
1080 /* also checks if . is a mountpoint, if --mountpoint was given */
1081 static int change_to_dest_dir(void)
1082 {
1083         int ret;
1084         const char *dd = OPT_STRING_VAL(DSS, DEST_DIR);
1085         struct stat dot, dotdot;
1086
1087         DSS_INFO_LOG(("changing cwd to %s\n", dd));
1088         if (chdir(dd) < 0) {
1089                 ret = -ERRNO_TO_DSS_ERROR(errno);
1090                 DSS_ERROR_LOG(("could not change cwd to %s\n", dd));
1091                 return ret;
1092         }
1093         if (!OPT_GIVEN(DSS, MOUNTPOINT))
1094                 return 0;
1095         if (stat(".", &dot) < 0) {
1096                 ret = -ERRNO_TO_DSS_ERROR(errno);
1097                 DSS_ERROR_LOG(("could not stat .\n"));
1098                 return ret;
1099         }
1100         if (stat("..", &dotdot) < 0) {
1101                 ret = -ERRNO_TO_DSS_ERROR(errno);
1102                 DSS_ERROR_LOG(("could not stat ..\n"));
1103                 return ret;
1104         }
1105         if (dot.st_dev == dotdot.st_dev && dot.st_ino != dotdot.st_ino) {
1106                 DSS_ERROR_LOG(("mountpoint check failed for %s\n", dd));
1107                 return -E_MOUNTPOINT;
1108         }
1109         return 1;
1110 }
1111
1112 static int check_config(void)
1113 {
1114         int ret;
1115         uint32_t unit_interval = OPT_UINT32_VAL(DSS, UNIT_INTERVAL);
1116         uint32_t num_intervals = OPT_UINT32_VAL(DSS, NUM_INTERVALS);
1117
1118         if (unit_interval == 0) {
1119                 DSS_ERROR_LOG(("bad unit interval: %i\n", unit_interval));
1120                 return -E_INVALID_NUMBER;
1121         }
1122         DSS_DEBUG_LOG(("unit interval: %i day(s)\n", unit_interval));
1123
1124         if (num_intervals == 0 || num_intervals > 30) {
1125                 DSS_ERROR_LOG(("bad number of intervals: %i\n", num_intervals));
1126                 return -E_INVALID_NUMBER;
1127         }
1128         if (subcmd == CMD_PTR(RUN) || subcmd == CMD_PTR(CREATE))
1129                 if (!OPT_GIVEN(DSS, SOURCE_DIR)) {
1130                         DSS_ERROR_LOG(("--source-dir required\n"));
1131                         return -E_SYNTAX;
1132                 }
1133         if (subcmd == CMD_PTR(RUN) || subcmd == CMD_PTR(CREATE)
1134                         || subcmd == CMD_PTR(LS) || subcmd == CMD_PTR(PRUNE)) {
1135                 if (!OPT_GIVEN(DSS, DEST_DIR)) {
1136                         DSS_ERROR_LOG(("--dest-dir required\n"));
1137                         return -E_SYNTAX;
1138                 }
1139                 ret = change_to_dest_dir();
1140                 if (ret < 0)
1141                         return ret;
1142         }
1143         DSS_DEBUG_LOG(("number of intervals: %i\n", num_intervals));
1144         return 1;
1145 }
1146
1147 static int lopsub_error(int lopsub_ret, char **errctx)
1148 {
1149         const char *msg = lls_strerror(-lopsub_ret);
1150         if (*errctx)
1151                 DSS_ERROR_LOG(("%s: %s\n", *errctx, msg));
1152         else
1153                 DSS_ERROR_LOG(("%s\n", msg));
1154         free(*errctx);
1155         *errctx = NULL;
1156         return -E_LOPSUB;
1157 }
1158
1159 static int parse_config_file(bool sighup, const struct lls_command *cmd)
1160 {
1161         int ret, fd = -1;
1162         char *config_file = get_config_file_name();
1163         struct stat statbuf;
1164         void *map;
1165         size_t sz;
1166         int cf_argc;
1167         char **cf_argv, *errctx = NULL;
1168         struct lls_parse_result *cf_lpr, *merged_lpr, *clpr;
1169         const char *subcmd_name;
1170
1171         ret = open(config_file, O_RDONLY);
1172         if (ret < 0) {
1173                 if (errno != ENOENT || OPT_GIVEN(DSS, CONFIG_FILE)) {
1174                         ret = -ERRNO_TO_DSS_ERROR(errno);
1175                         DSS_ERROR_LOG(("config file %s can not be opened\n",
1176                                 config_file));
1177                         goto out;
1178                 }
1179                 /* no config file -- nothing to do */
1180                 ret = 0;
1181                 goto success;
1182         }
1183         fd = ret;
1184         ret = fstat(fd, &statbuf);
1185         if (ret < 0) {
1186                 ret = -ERRNO_TO_DSS_ERROR(errno);
1187                 DSS_ERROR_LOG(("failed to stat config file %s\n", config_file));
1188                 goto close_fd;
1189         }
1190         sz = statbuf.st_size;
1191         if (sz == 0) { /* config file is empty -- nothing to do */
1192                 ret = 0;
1193                 goto success;
1194         }
1195         map = mmap(NULL, sz, PROT_READ, MAP_PRIVATE, fd, 0);
1196         if (map == MAP_FAILED) {
1197                 ret = -ERRNO_TO_DSS_ERROR(errno);
1198                 DSS_ERROR_LOG(("failed to mmap config file %s\n",
1199                         config_file));
1200                 goto close_fd;
1201         }
1202         if (cmd == CMD_PTR(DSS))
1203                 subcmd_name = NULL;
1204         else
1205                 subcmd_name = lls_command_name(cmd);
1206         ret = lls_convert_config(map, sz, subcmd_name, &cf_argv, &errctx);
1207         munmap(map, sz);
1208         if (ret < 0) {
1209                 DSS_ERROR_LOG(("failed to convert config file %s\n",
1210                         config_file));
1211                 ret = lopsub_error(ret, &errctx);
1212                 goto close_fd;
1213         }
1214         cf_argc = ret;
1215         ret = lls_parse(cf_argc, cf_argv, cmd, &cf_lpr, &errctx);
1216         lls_free_argv(cf_argv);
1217         if (ret < 0) {
1218                 ret = lopsub_error(ret, &errctx);
1219                 goto close_fd;
1220         }
1221         clpr = cmd == CMD_PTR(DSS)? cmdline_lpr : cmdline_sublpr;
1222         if (sighup) /* config file overrides command line */
1223                 ret = lls_merge(cf_lpr, clpr, cmd, &merged_lpr, &errctx);
1224         else /* command line options overrride config file options */
1225                 ret = lls_merge(clpr, cf_lpr, cmd, &merged_lpr, &errctx);
1226         lls_free_parse_result(cf_lpr, cmd);
1227         if (ret < 0) {
1228                 ret = lopsub_error(ret, &errctx);
1229                 goto close_fd;
1230         }
1231         ret = 1;
1232 success:
1233         assert(ret >= 0);
1234         DSS_DEBUG_LOG(("loglevel: %d\n", OPT_UINT32_VAL(DSS, LOGLEVEL)));
1235         if (cmd != CMD_PTR(DSS)) {
1236                 if (ret > 0) {
1237                         if (sublpr != cmdline_sublpr)
1238                                 lls_free_parse_result(sublpr, cmd);
1239                         sublpr = merged_lpr;
1240                 } else
1241                         sublpr = cmdline_sublpr;
1242         } else {
1243                 if (ret > 0) {
1244                         if (lpr != cmdline_lpr)
1245                                 lls_free_parse_result(lpr, cmd);
1246                         lpr = merged_lpr;
1247                 } else
1248                         lpr = cmdline_lpr;
1249         }
1250 close_fd:
1251         if (fd >= 0)
1252                 close(fd);
1253 out:
1254         free(config_file);
1255         if (ret < 0)
1256                 DSS_EMERG_LOG(("%s\n", dss_strerror(-ret)));
1257         return ret;
1258 }
1259
1260 static int handle_sighup(void)
1261 {
1262         int ret;
1263
1264         DSS_NOTICE_LOG(("SIGHUP, re-reading config\n"));
1265         dump_dss_config("old");
1266         ret = parse_config_file(true /* SIGHUP */, CMD_PTR(DSS));
1267         if (ret < 0)
1268                 return ret;
1269         ret = parse_config_file(true /* SIGHUP */, CMD_PTR(RUN));
1270         if (ret < 0)
1271                 return ret;
1272         ret = check_config();
1273         if (ret < 0)
1274                 return ret;
1275         close_log(logfile);
1276         logfile = NULL;
1277         if (OPT_GIVEN(RUN, DAEMON) || daemonized) {
1278                 logfile = open_log(OPT_STRING_VAL(RUN, LOGFILE));
1279                 log_welcome(OPT_UINT32_VAL(DSS, LOGLEVEL));
1280                 daemonized = true;
1281         }
1282         dump_dss_config("reloaded");
1283         invalidate_next_snapshot_time();
1284         return 1;
1285 }
1286
1287 static void kill_children(void)
1288 {
1289         restart_create_process();
1290         dss_kill(create_pid, SIGTERM, NULL);
1291         dss_kill(remove_pid, SIGTERM, NULL);
1292 }
1293
1294 static int handle_signal(void)
1295 {
1296         int sig, ret = next_signal();
1297
1298         if (ret <= 0)
1299                 goto out;
1300         sig = ret;
1301         switch (sig) {
1302         case SIGINT:
1303         case SIGTERM:
1304                 kill_children();
1305                 ret = -E_SIGNAL;
1306                 break;
1307         case SIGHUP:
1308                 ret = handle_sighup();
1309                 break;
1310         case SIGCHLD:
1311                 ret = handle_sigchld();
1312                 break;
1313         }
1314 out:
1315         if (ret < 0)
1316                 DSS_ERROR_LOG(("%s\n", dss_strerror(-ret)));
1317         return ret;
1318 }
1319
1320 /*
1321  * We can not use rsync locally if the local user is different from the remote
1322  * user or if the src dir is not on the local host (or both).
1323  */
1324 static int use_rsync_locally(char *logname)
1325 {
1326         const char *h = OPT_STRING_VAL(DSS, REMOTE_HOST);
1327
1328         if (strcmp(h, "localhost") && strcmp(h, "127.0.0.1"))
1329                 return 0;
1330         if (OPT_GIVEN(DSS, REMOTE_USER) &&
1331                         strcmp(OPT_STRING_VAL(DSS, REMOTE_USER), logname))
1332                 return 0;
1333         return 1;
1334 }
1335
1336 static int rename_resume_snap(int64_t creation_time)
1337 {
1338         struct snapshot_list sl;
1339         struct snapshot *s = NULL;
1340         char *new_name = incomplete_name(creation_time);
1341         int ret;
1342         const char *why;
1343
1344         sl.num_snapshots = 0;
1345
1346         ret = 0;
1347         dss_get_snapshot_list(&sl);
1348         /*
1349          * Snapshot recycling: We first look at the newest snapshot. If this
1350          * snapshot happens to be incomplete, the last rsync process was
1351          * aborted and we reuse this one. Otherwise we look at snapshots which
1352          * could be removed (outdated and redundant snapshots) as candidates
1353          * for recycling. If no outdated/redundant snapshot exists, we check if
1354          * there is an orphaned snapshot, which likely is useless anyway.
1355          *
1356          * Only if no existing snapshot is suitable for recycling, we bite the
1357          * bullet and create a new one.
1358          */
1359         s = get_newest_snapshot(&sl);
1360         if (!s) /* no snapshots at all */
1361                 goto out;
1362         /* re-use last snapshot if it is incomplete */
1363         why = "aborted";
1364         if ((s->flags & SS_COMPLETE) == 0)
1365                 goto out;
1366         why = "outdated";
1367         s = find_outdated_snapshot(&sl);
1368         if (s)
1369                 goto out;
1370         why = "redundant";
1371         s = find_redundant_snapshot(&sl);
1372         if (s)
1373                 goto out;
1374         why = "orphaned";
1375         s = find_orphaned_snapshot(&sl);
1376 out:
1377         if (s) {
1378                 DSS_NOTICE_LOG(("recycling %s snapshot %s\n", why, s->name));
1379                 ret = dss_rename(s->name, new_name);
1380         }
1381         if (ret >= 0)
1382                 DSS_NOTICE_LOG(("creating %s\n", new_name));
1383         free(new_name);
1384         free_snapshot_list(&sl);
1385         return ret;
1386 }
1387
1388 static void create_rsync_argv(char ***argv, int64_t *num)
1389 {
1390         char *logname;
1391         int i = 0, j, N = OPT_GIVEN(DSS, RSYNC_OPTION);
1392         struct snapshot_list sl;
1393         static bool seeded;
1394
1395         dss_get_snapshot_list(&sl);
1396         assert(!name_of_reference_snapshot);
1397         name_of_reference_snapshot = name_of_newest_complete_snapshot(&sl);
1398         free_snapshot_list(&sl);
1399
1400         *argv = dss_malloc((15 + N) * sizeof(char *));
1401         (*argv)[i++] = dss_strdup("rsync");
1402         (*argv)[i++] = dss_strdup("-a");
1403         (*argv)[i++] = dss_strdup("--delete");
1404         if (!seeded) {
1405                 srandom((unsigned)time(NULL)); /* no need to be fancy here */
1406                 seeded = true;
1407         }
1408         if (1000 * (random() / (RAND_MAX + 1.0)) < OPT_UINT32_VAL(DSS, CHECKSUM)) {
1409                 DSS_NOTICE_LOG(("adding --checksum to rsync options\n"));
1410                 (*argv)[i++] = dss_strdup("--checksum");
1411         }
1412         for (j = 0; j < N; j++)
1413                 (*argv)[i++] = dss_strdup(lls_string_val(j,
1414                         OPT_RESULT(DSS, RSYNC_OPTION)));
1415         if (name_of_reference_snapshot) {
1416                 DSS_INFO_LOG(("using %s as reference\n", name_of_reference_snapshot));
1417                 (*argv)[i++] = make_message("--link-dest=../%s",
1418                         name_of_reference_snapshot);
1419         } else
1420                 DSS_INFO_LOG(("no suitable reference snapshot found\n"));
1421         logname = dss_logname();
1422         if (use_rsync_locally(logname))
1423                 (*argv)[i++] = dss_strdup(OPT_STRING_VAL(DSS, SOURCE_DIR));
1424         else
1425                 (*argv)[i++] = make_message("%s@%s:%s/",
1426                         OPT_GIVEN(DSS, REMOTE_USER)?
1427                                 OPT_STRING_VAL(DSS, REMOTE_USER) : logname,
1428                         OPT_STRING_VAL(DSS, REMOTE_HOST),
1429                         OPT_STRING_VAL(DSS, SOURCE_DIR));
1430         free(logname);
1431         *num = get_current_time();
1432         (*argv)[i++] = incomplete_name(*num);
1433         (*argv)[i++] = NULL;
1434         for (j = 0; j < i; j++)
1435                 DSS_DEBUG_LOG(("argv[%d] = %s\n", j, (*argv)[j]));
1436 }
1437
1438 static void free_rsync_argv(char **argv)
1439 {
1440         int i;
1441
1442         if (!argv)
1443                 return;
1444         for (i = 0; argv[i]; i++)
1445                 free(argv[i]);
1446         free(argv);
1447 }
1448
1449 static int create_snapshot(char **argv)
1450 {
1451         int ret;
1452
1453         assert(argv);
1454         ret = rename_resume_snap(current_snapshot_creation_time);
1455         if (ret < 0)
1456                 return ret;
1457         dss_exec(&create_pid, argv[0], argv);
1458         snapshot_creation_status = HS_RUNNING;
1459         return ret;
1460 }
1461
1462 static int select_loop(void)
1463 {
1464         int ret;
1465         /* check every 60 seconds for free disk space */
1466         struct timeval tv;
1467         char **rsync_argv = NULL;
1468
1469         for (;;) {
1470                 fd_set rfds;
1471                 struct timeval *tvp;
1472
1473                 if (remove_pid)
1474                         tvp = NULL; /* sleep until rm hook/process dies */
1475                 else { /* sleep one minute */
1476                         tv.tv_sec = 60;
1477                         tv.tv_usec = 0;
1478                         tvp = &tv;
1479                 }
1480                 FD_ZERO(&rfds);
1481                 FD_SET(signal_pipe, &rfds);
1482                 ret = dss_select(signal_pipe + 1, &rfds, NULL, tvp);
1483                 if (ret < 0)
1484                         goto out;
1485                 if (FD_ISSET(signal_pipe, &rfds)) {
1486                         ret = handle_signal();
1487                         if (ret < 0)
1488                                 goto out;
1489                 }
1490                 if (remove_pid)
1491                         continue;
1492                 if (snapshot_removal_status == HS_PRE_SUCCESS) {
1493                         ret = exec_rm();
1494                         if (ret < 0)
1495                                 goto out;
1496                         continue;
1497                 }
1498                 if (snapshot_removal_status == HS_SUCCESS) {
1499                         post_remove_hook();
1500                         continue;
1501                 }
1502                 ret = try_to_free_disk_space();
1503                 if (ret < 0)
1504                         goto out;
1505                 if (snapshot_removal_status != HS_READY) {
1506                         stop_create_process();
1507                         continue;
1508                 }
1509                 restart_create_process();
1510                 switch (snapshot_creation_status) {
1511                 case HS_READY:
1512                         if (!next_snapshot_is_due())
1513                                 continue;
1514                         pre_create_hook();
1515                         continue;
1516                 case HS_PRE_RUNNING:
1517                 case HS_RUNNING:
1518                 case HS_POST_RUNNING:
1519                         continue;
1520                 case HS_PRE_SUCCESS:
1521                         if (!name_of_reference_snapshot) {
1522                                 free_rsync_argv(rsync_argv);
1523                                 create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
1524                         }
1525                         ret = create_snapshot(rsync_argv);
1526                         if (ret < 0)
1527                                 goto out;
1528                         continue;
1529                 case HS_NEEDS_RESTART:
1530                         if (!next_snapshot_is_due())
1531                                 continue;
1532                         ret = create_snapshot(rsync_argv);
1533                         if (ret < 0)
1534                                 goto out;
1535                         continue;
1536                 case HS_SUCCESS:
1537                         post_create_hook();
1538                         continue;
1539                 }
1540         }
1541 out:
1542         return ret;
1543 }
1544
1545 static void exit_hook(int exit_code)
1546 {
1547         pid_t pid;
1548         char **argv, *tmp = dss_strdup(OPT_STRING_VAL(DSS, EXIT_HOOK));
1549         unsigned n = split_args(tmp, &argv, " \t");
1550
1551         n++;
1552         argv = dss_realloc(argv, (n + 1) * sizeof(char *));
1553         argv[n - 1] = dss_strdup(dss_strerror(-exit_code));
1554         argv[n] = NULL;
1555         dss_exec(&pid, argv[0], argv);
1556         free(argv[n - 1]);
1557         free(argv);
1558         free(tmp);
1559 }
1560
1561 static void lock_dss_or_die(void)
1562 {
1563         char *config_file = get_config_file_name();
1564         int ret = lock_dss(config_file);
1565
1566         free(config_file);
1567         if (ret < 0) {
1568                 DSS_EMERG_LOG(("failed to lock: %s\n", dss_strerror(-ret)));
1569                 exit(EXIT_FAILURE);
1570         }
1571 }
1572
1573 static int com_run(void)
1574 {
1575         int ret, fd = -1;
1576         char *config_file;
1577         pid_t pid;
1578
1579         if (OPT_GIVEN(DSS, DRY_RUN)) {
1580                 DSS_ERROR_LOG(("dry run not supported by this command\n"));
1581                 return -E_SYNTAX;
1582         }
1583         config_file = get_config_file_name();
1584         ret = get_dss_pid(config_file, &pid);
1585         free(config_file);
1586         if (ret >= 0) {
1587                 DSS_ERROR_LOG(("pid %d\n", (int)pid));
1588                 return -E_ALREADY_RUNNING;
1589         }
1590         if (OPT_GIVEN(RUN, DAEMON)) {
1591                 fd = daemon_init();
1592                 daemonized = true;
1593                 logfile = open_log(OPT_STRING_VAL(RUN, LOGFILE));
1594         }
1595         lock_dss_or_die();
1596         dump_dss_config("startup");
1597         ret = install_sighandler(SIGHUP);
1598         if (ret < 0)
1599                 return ret;
1600         if (fd >= 0) {
1601                 ret = write(fd, "\0", 1);
1602                 if (ret != 1) {
1603                         DSS_ERROR_LOG(("write to daemon pipe returned %d\n",
1604                                 ret));
1605                         if (ret < 0)
1606                                 return -ERRNO_TO_DSS_ERROR(errno);
1607                         return -E_BUG;
1608                 }
1609         }
1610         ret = select_loop();
1611         if (ret >= 0) /* impossible */
1612                 ret = -E_BUG;
1613         kill_children();
1614         exit_hook(ret);
1615         while (wait(NULL) >= 0 || errno != ECHILD)
1616                 ; /* still have children to wait for */
1617         return ret;
1618 }
1619 EXPORT_CMD_HANDLER(run);
1620
1621 static int com_prune(void)
1622 {
1623         int ret;
1624         struct snapshot_list sl;
1625         struct snapshot *victim;
1626         struct disk_space ds;
1627         const char *why;
1628
1629         lock_dss_or_die();
1630         ret = get_disk_space(".", &ds);
1631         if (ret < 0)
1632                 return ret;
1633         log_disk_space(&ds);
1634         dss_get_snapshot_list(&sl);
1635         why = "outdated";
1636         victim = find_outdated_snapshot(&sl);
1637         if (victim)
1638                 goto rm;
1639         why = "redundant";
1640         victim = find_redundant_snapshot(&sl);
1641         if (victim)
1642                 goto rm;
1643         ret = 0;
1644         goto out;
1645 rm:
1646         if (OPT_GIVEN(DSS, DRY_RUN)) {
1647                 dss_msg("%s snapshot %s (interval = %i)\n",
1648                         why, victim->name, victim->interval);
1649                 ret = 0;
1650                 goto out;
1651         }
1652         pre_remove_hook(victim, why);
1653         if (snapshot_removal_status == HS_PRE_RUNNING) {
1654                 ret = wait_for_remove_process();
1655                 if (ret < 0)
1656                         goto out;
1657                 if (snapshot_removal_status != HS_PRE_SUCCESS)
1658                         goto out;
1659         }
1660         ret = exec_rm();
1661         if (ret < 0)
1662                 goto out;
1663         ret = wait_for_remove_process();
1664         if (ret < 0)
1665                 goto out;
1666         if (snapshot_removal_status != HS_SUCCESS)
1667                 goto out;
1668         post_remove_hook();
1669         if (snapshot_removal_status != HS_POST_RUNNING)
1670                 goto out;
1671         ret = wait_for_remove_process();
1672         if (ret < 0)
1673                 goto out;
1674         ret = 1;
1675 out:
1676         free_snapshot_list(&sl);
1677         return ret;
1678 }
1679 EXPORT_CMD_HANDLER(prune);
1680
1681 static int com_create(void)
1682 {
1683         int ret, status;
1684         char **rsync_argv;
1685
1686         lock_dss_or_die();
1687         if (OPT_GIVEN(DSS, DRY_RUN)) {
1688                 int i;
1689                 char *msg = NULL;
1690                 create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
1691                 for (i = 0; rsync_argv[i]; i++) {
1692                         char *tmp = msg;
1693                         msg = make_message("%s%s%s", tmp? tmp : "",
1694                                 tmp? " " : "", rsync_argv[i]);
1695                         free(tmp);
1696                 }
1697                 free_rsync_argv(rsync_argv);
1698                 dss_msg("%s\n", msg);
1699                 free(msg);
1700                 return 1;
1701         }
1702         pre_create_hook();
1703         if (create_pid) {
1704                 ret = wait_for_process(create_pid, &status);
1705                 if (ret < 0)
1706                         return ret;
1707                 ret = handle_pre_create_hook_exit(status);
1708                 if (ret <= 0) /* error, or pre-create failed */
1709                         return ret;
1710         }
1711         create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
1712         ret = create_snapshot(rsync_argv);
1713         if (ret < 0)
1714                 goto out;
1715         ret = wait_for_process(create_pid, &status);
1716         if (ret < 0)
1717                 goto out;
1718         ret = handle_rsync_exit(status);
1719         if (ret < 0)
1720                 goto out;
1721         post_create_hook();
1722         if (create_pid)
1723                 ret = wait_for_process(create_pid, &status);
1724 out:
1725         free_rsync_argv(rsync_argv);
1726         return ret;
1727 }
1728 EXPORT_CMD_HANDLER(create);
1729
1730 static int com_ls(void)
1731 {
1732         int i;
1733         struct snapshot_list sl;
1734         struct snapshot *s;
1735         int64_t now = get_current_time();
1736
1737         dss_get_snapshot_list(&sl);
1738         FOR_EACH_SNAPSHOT(s, i, &sl) {
1739                 int64_t d;
1740                 if (s->flags & SS_COMPLETE)
1741                         d = (s->completion_time - s->creation_time) / 60;
1742                 else
1743                         d = (now - s->creation_time) / 60;
1744                 dss_msg("%u\t%s\t%3" PRId64 ":%02" PRId64 "\n", s->interval,
1745                         s->name, d / 60, d % 60);
1746         }
1747         free_snapshot_list(&sl);
1748         return 1;
1749 }
1750 EXPORT_CMD_HANDLER(ls);
1751
1752 static int com_configtest(void)
1753 {
1754         printf("Syntax Ok\n");
1755         return 0;
1756 }
1757 EXPORT_CMD_HANDLER(configtest);
1758
1759 static int setup_signal_handling(void)
1760 {
1761         int ret;
1762
1763         DSS_INFO_LOG(("setting up signal handlers\n"));
1764         signal_pipe = signal_init(); /* always successful */
1765         ret = install_sighandler(SIGINT);
1766         if (ret < 0)
1767                 return ret;
1768         ret = install_sighandler(SIGTERM);
1769         if (ret < 0)
1770                 return ret;
1771         return install_sighandler(SIGCHLD);
1772 }
1773
1774 static void handle_version_and_help(void)
1775 {
1776         char *txt;
1777
1778         if (OPT_GIVEN(DSS, DETAILED_HELP))
1779                 txt = lls_long_help(CMD_PTR(DSS));
1780         else if (OPT_GIVEN(DSS, HELP))
1781                 txt = lls_short_help(CMD_PTR(DSS));
1782         else if (OPT_GIVEN(DSS, VERSION))
1783                 txt = dss_strdup(VERSION_STRING);
1784         else
1785                 return;
1786         printf("%s", txt);
1787         free(txt);
1788         exit(EXIT_SUCCESS);
1789 }
1790
1791 static void show_subcommand_summary(void)
1792 {
1793         const struct lls_command *cmd;
1794         int i;
1795
1796         printf("Available subcommands:\n");
1797         for (i = 1; (cmd = lls_cmd(i, dss_suite)); i++) {
1798                 const char *name = lls_command_name(cmd);
1799                 const char *purpose = lls_purpose(cmd);
1800                 printf("%-11s%s\n", name, purpose);
1801         }
1802         exit(EXIT_SUCCESS);
1803 }
1804
1805 int main(int argc, char **argv)
1806 {
1807         int ret;
1808         char *errctx = NULL;
1809         unsigned num_inputs;
1810         const struct dss_user_data *ud;
1811
1812         ret = lls_parse(argc, argv, CMD_PTR(DSS), &cmdline_lpr, &errctx);
1813         if (ret < 0) {
1814                 ret = lopsub_error(ret, &errctx);
1815                 goto out;
1816         }
1817         lpr = cmdline_lpr;
1818         ret = parse_config_file(false /* no SIGHUP */, CMD_PTR(DSS));
1819         if (ret < 0)
1820                 goto out;
1821         handle_version_and_help();
1822         num_inputs = lls_num_inputs(lpr);
1823         if (num_inputs == 0)
1824                 show_subcommand_summary();
1825         ret = lls_lookup_subcmd(argv[argc - num_inputs], dss_suite, &errctx);
1826         if (ret < 0) {
1827                 ret = lopsub_error(ret, &errctx);
1828                 goto out;
1829         }
1830         subcmd = lls_cmd(ret, dss_suite);
1831         ret = lls_parse(num_inputs, argv + argc - num_inputs, subcmd,
1832                 &cmdline_sublpr, &errctx);
1833         if (ret < 0) {
1834                 ret = lopsub_error(ret, &errctx);
1835                 goto out;
1836         }
1837         sublpr = cmdline_sublpr;
1838         ret = parse_config_file(false /* no SIGHUP */, subcmd);
1839         if (ret < 0)
1840                 goto out;
1841         ret = check_config();
1842         if (ret < 0)
1843                 goto out;
1844         ret = setup_signal_handling();
1845         if (ret < 0)
1846                 goto out;
1847         ud = lls_user_data(subcmd);
1848         ret = ud->handler();
1849         signal_shutdown();
1850 out:
1851         if (ret < 0) {
1852                 if (errctx)
1853                         DSS_ERROR_LOG(("%s\n", errctx));
1854                 DSS_EMERG_LOG(("%s\n", dss_strerror(-ret)));
1855         }
1856         free(errctx);
1857         lls_free_parse_result(lpr, CMD_PTR(DSS));
1858         if (lpr != cmdline_lpr)
1859                 lls_free_parse_result(cmdline_lpr, CMD_PTR(DSS));
1860         lls_free_parse_result(sublpr, subcmd);
1861         if (sublpr != cmdline_sublpr)
1862                 lls_free_parse_result(cmdline_sublpr, subcmd);
1863         exit(ret >= 0? EXIT_SUCCESS : EXIT_FAILURE);
1864 }