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