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