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