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