ef42e39cf0923a141eb1d9b3f4f07a1f1a252089
[dss.git] / dss.c
1 #include <string.h>
2 #include <stdlib.h>
3 #include <stdarg.h>
4 #include <assert.h>
5 #include <errno.h>
6 #include <sys/types.h>
7 #include <signal.h>
8 #include <ctype.h>
9 #include <sys/stat.h>
10 #include <unistd.h>
11 #include <inttypes.h>
12 #include <sys/time.h>
13 #include <time.h>
14 #include <sys/wait.h>
15 #include <fnmatch.h>
16 #include <limits.h>
17
18
19 #include "gcc-compat.h"
20 #include "cmdline.h"
21 #include "log.h"
22 #include "string.h"
23 #include "error.h"
24 #include "fd.h"
25 #include "exec.h"
26 #include "daemon.h"
27 #include "signal.h"
28 #include "df.h"
29 #include "time.h"
30 #include "snap.h"
31
32 /** Command line and config file options. */
33 static struct gengetopt_args_info conf;
34 /** Non-NULL if we log to a file. */
35 static FILE *logfile;
36 /** The read end of the signal pipe */
37 static int signal_pipe;
38 /** Process id of current rsync process. */
39 static pid_t rsync_pid;
40 /** Whether the rsync process is currently stopped */
41 static int rsync_stopped;
42 /** Process id of current rm process. */
43 static pid_t rm_pid;
44 /** When the next snapshot is due. */
45 static struct timeval next_snapshot_time;
46 /** The pid of the pre-create hook. */
47 static pid_t pre_create_hook_pid;
48 /** The pid of the post-create hook. */
49 static pid_t post_create_hook_pid;
50 /** Creation time of the snapshot currently being created. */
51 static int64_t current_snapshot_creation_time;
52 /** Needed by the post-create hook. */
53 static char *path_to_last_complete_snapshot;
54 /** \sa \ref snap.h for details. */
55 static unsigned snapshot_creation_status;
56
57
58 DEFINE_DSS_ERRLIST;
59
60
61 /* a litte cpp magic helps to DRY */
62 #define COMMANDS \
63         COMMAND(ls) \
64         COMMAND(create) \
65         COMMAND(prune) \
66         COMMAND(run)
67 #define COMMAND(x) static int com_ ##x(void);
68 COMMANDS
69 #undef COMMAND
70 #define COMMAND(x) if (conf.x ##_given) return com_ ##x();
71 static int call_command_handler(void)
72 {
73         COMMANDS
74         DSS_EMERG_LOG("BUG: did not find command handler\n");
75         exit(EXIT_FAILURE);
76 }
77 #undef COMMAND
78 #undef COMMANDS
79
80 /**
81  * The log function of dss.
82  *
83  * \param ll Loglevel.
84  * \param fml Usual format string.
85  *
86  * All DSS_XXX_LOG() macros use this function.
87  */
88 __printf_2_3 void dss_log(int ll, const char* fmt,...)
89 {
90         va_list argp;
91         FILE *outfd;
92         struct tm *tm;
93         time_t t1;
94         char str[255] = "";
95
96         if (ll < conf.loglevel_arg)
97                 return;
98         outfd = logfile? logfile : stderr;
99         time(&t1);
100         tm = localtime(&t1);
101         strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
102         fprintf(outfd, "%s ", str);
103         if (conf.loglevel_arg <= INFO)
104                 fprintf(outfd, "%i: ", ll);
105         va_start(argp, fmt);
106         vfprintf(outfd, fmt, argp);
107         va_end(argp);
108 }
109
110 /**
111  * Print a message either to stdout or to the log file.
112  */
113 static __printf_1_2 void dss_msg(const char* fmt,...)
114 {
115         FILE *outfd = conf.daemon_given? logfile : stdout;
116         va_list argp;
117         va_start(argp, fmt);
118         vfprintf(outfd, fmt, argp);
119         va_end(argp);
120 }
121
122 /* TODO: Also consider number of inodes. */
123 static int disk_space_low(void)
124 {
125         struct disk_space ds;
126         int ret = get_disk_space(".", &ds);
127
128         if (ret < 0)
129                 return ret;
130         if (conf.min_free_mb_arg)
131                 if (ds.free_mb < conf.min_free_mb_arg)
132                         return 1;
133         if (conf.min_free_percent_arg)
134                 if (ds.percent_free < conf.min_free_percent_arg)
135                         return 1;
136         if (conf.min_free_percent_inodes_arg)
137                 if (ds.percent_free_inodes < conf.min_free_percent_inodes_arg)
138                         return 1;
139         return 0;
140 }
141
142 static void dss_get_snapshot_list(struct snapshot_list *sl)
143 {
144         get_snapshot_list(sl, conf.unit_interval_arg, conf.num_intervals_arg);
145 }
146
147 static void compute_next_snapshot_time(void)
148 {
149         struct timeval now, unit_interval = {.tv_sec = 24 * 3600 * conf.unit_interval_arg},
150                 tmp, diff;
151         int64_t x = 0;
152         unsigned wanted = desired_number_of_snapshots(0, conf.num_intervals_arg),
153                 num_complete_snapshots = 0;
154         int i, ret;
155         struct snapshot *s = NULL;
156         struct snapshot_list sl;
157
158         assert(snapshot_creation_status == SCS_READY);
159         current_snapshot_creation_time = 0;
160         dss_get_snapshot_list(&sl);
161         FOR_EACH_SNAPSHOT(s, i, &sl) {
162                 if (!(s->flags & SS_COMPLETE))
163                         continue;
164                 num_complete_snapshots++;
165                 x += s->completion_time - s->creation_time;
166         }
167         assert(x >= 0);
168         if (num_complete_snapshots)
169                 x /= num_complete_snapshots; /* avg time to create one snapshot */
170         x *= wanted; /* time to create all snapshots in interval 0 */
171         tmp.tv_sec = x;
172         tmp.tv_usec = 0;
173         ret = tv_diff(&unit_interval, &tmp, &diff); /* total sleep time per unit interval */
174         gettimeofday(&now, NULL);
175         if (ret < 0 || !s)
176                 goto min_sleep;
177         tv_divide(wanted, &diff, &tmp); /* sleep time betweeen two snapshots */
178         diff.tv_sec = s->completion_time;
179         diff.tv_usec = 0;
180         tv_add(&diff, &tmp, &next_snapshot_time);
181         if (tv_diff(&now, &next_snapshot_time, NULL) < 0)
182                 goto out;
183 min_sleep:
184         next_snapshot_time = now;
185         next_snapshot_time.tv_sec += 60;
186 out:
187         free_snapshot_list(&sl);
188 }
189
190
191 static int remove_snapshot(struct snapshot *s)
192 {
193         int fds[3] = {0, 0, 0};
194         assert(!rm_pid);
195         char *new_name = being_deleted_name(s);
196         int ret = dss_rename(s->name, new_name);
197         char *argv[] = {"rm", "-rf", new_name, NULL};
198
199         if (ret < 0)
200                 goto out;
201         DSS_NOTICE_LOG("removing %s (interval = %i)\n", s->name, s->interval);
202         ret = dss_exec(&rm_pid, argv[0], argv, fds);
203 out:
204         free(new_name);
205         return ret;
206 }
207
208 /*
209  * return: 0: no redundant snapshots, 1: rm process started, negative: error
210  */
211 static int remove_redundant_snapshot(struct snapshot_list *sl)
212 {
213         int ret, i, interval;
214         struct snapshot *s;
215         unsigned missing = 0;
216
217         DSS_INFO_LOG("looking for intervals containing too many snapshots\n");
218         for (interval = conf.num_intervals_arg - 1; interval >= 0; interval--) {
219                 unsigned keep = desired_number_of_snapshots(interval, conf.num_intervals_arg);
220                 unsigned num = sl->interval_count[interval];
221                 struct snapshot *victim = NULL, *prev = NULL;
222                 int64_t score = LONG_MAX;
223
224                 if (keep >= num)
225                         missing += keep - num;
226 //              DSS_DEBUG_LOG("interval %i: keep: %u, have: %u, missing: %u\n",
227 //                      interval, keep, num, missing);
228                 if (keep + missing >= num)
229                         continue;
230                 /* redundant snapshot in this interval, pick snapshot with lowest score */
231                 FOR_EACH_SNAPSHOT(s, i, sl) {
232                         int64_t this_score;
233
234                         //DSS_DEBUG_LOG("checking %s\n", s->name);
235                         if (s->interval > interval) {
236                                 prev = s;
237                                 continue;
238                         }
239                         if (s->interval < interval)
240                                 break;
241                         if (!victim) {
242                                 victim = s;
243                                 prev = s;
244                                 continue;
245                         }
246                         assert(prev);
247                         /* check if s is a better victim */
248                         this_score = s->creation_time - prev->creation_time;
249                         assert(this_score >= 0);
250                         //DSS_DEBUG_LOG("%s: score %lli\n", s->name, (long long)score);
251                         if (this_score < score) {
252                                 score = this_score;
253                                 victim = s;
254                         }
255                         prev = s;
256                 }
257                 assert(victim);
258                 if (conf.dry_run_given) {
259                         dss_msg("%s would be removed (interval = %i)\n",
260                                 victim->name, victim->interval);
261                         continue;
262                 }
263                 ret = remove_snapshot(victim);
264                 return ret < 0? ret : 1;
265         }
266         return 0;
267 }
268
269 static int remove_outdated_snapshot(struct snapshot_list *sl)
270 {
271         int i, ret;
272         struct snapshot *s;
273
274         DSS_INFO_LOG("looking for snapshots belonging to intervals greater than %d\n",
275                 conf.num_intervals_arg);
276         FOR_EACH_SNAPSHOT(s, i, sl) {
277                 if (s->interval <= conf.num_intervals_arg)
278                         continue;
279                 if (conf.dry_run_given) {
280                         dss_msg("%s would be removed (interval = %i)\n",
281                                 s->name, s->interval);
282                         continue;
283                 }
284                 ret = remove_snapshot(s);
285                 if (ret < 0)
286                         return ret;
287                 return 1;
288         }
289         return 0;
290 }
291
292 static int remove_oldest_snapshot(struct snapshot_list *sl)
293 {
294         struct snapshot *s = get_oldest_snapshot(sl);
295
296         if (!s) /* no snapshot found */
297                 return 0;
298         DSS_INFO_LOG("oldest snapshot: %s\n", s->name);
299         if (s->creation_time == current_snapshot_creation_time)
300                 return 0; /* do not remove the snapshot currently being created */
301         return remove_snapshot(s);
302 }
303
304 static int rename_incomplete_snapshot(int64_t start)
305 {
306         char *old_name;
307         int ret;
308
309         free(path_to_last_complete_snapshot);
310         ret = complete_name(start, get_current_time(),
311                 &path_to_last_complete_snapshot);
312         if (ret < 0)
313                 return ret;
314         old_name = incomplete_name(start);
315         ret = dss_rename(old_name, path_to_last_complete_snapshot);
316         if (ret >= 0)
317                 DSS_NOTICE_LOG("%s -> %s\n", old_name,
318                         path_to_last_complete_snapshot);
319         free(old_name);
320         return ret;
321 }
322
323 static int try_to_free_disk_space(int low_disk_space)
324 {
325         int ret;
326         struct snapshot_list sl;
327
328         dss_get_snapshot_list(&sl);
329         ret = remove_outdated_snapshot(&sl);
330         if (ret) /* error, or we are removing something */
331                 goto out;
332         /* no outdated snapshot */
333         ret = remove_redundant_snapshot(&sl);
334         if (ret)
335                 goto out;
336         ret = 0;
337         if (!low_disk_space)
338                 goto out;
339         DSS_WARNING_LOG("disk space low and nothing obvious to remove\n");
340         ret = remove_oldest_snapshot(&sl);
341         if (ret)
342                 goto out;
343         DSS_CRIT_LOG("uhuhu: not enough disk space for a single snapshot\n");
344         ret= -ENOSPC;
345 out:
346         free_snapshot_list(&sl);
347         return ret;
348 }
349
350 static int pre_create_hook(void)
351 {
352         int ret, fds[3] = {0, 0, 0};
353
354         if (!conf.pre_create_hook_given) {
355                 snapshot_creation_status = SCS_PRE_HOOK_SUCCESS;
356                 return 0;
357         }
358         DSS_NOTICE_LOG("executing %s\n", conf.pre_create_hook_arg);
359         ret = dss_exec_cmdline_pid(&pre_create_hook_pid,
360                 conf.pre_create_hook_arg, fds);
361         if (ret < 0)
362                 return ret;
363         snapshot_creation_status = SCS_PRE_HOOK_RUNNING;
364         return ret;
365 }
366
367 static int post_create_hook(void)
368 {
369         int ret, fds[3] = {0, 0, 0};
370         char *cmd;
371
372         if (!conf.post_create_hook_given) {
373                 snapshot_creation_status = SCS_READY;
374                 compute_next_snapshot_time();
375                 return 0;
376         }
377         cmd = make_message("%s %s", conf.post_create_hook_arg,
378                 path_to_last_complete_snapshot);
379         DSS_NOTICE_LOG("executing %s\n", cmd);
380         ret = dss_exec_cmdline_pid(&post_create_hook_pid, cmd, fds);
381         free(cmd);
382         if (ret < 0)
383                 return ret;
384         snapshot_creation_status = SCS_POST_HOOK_RUNNING;
385         return ret;
386 }
387
388 static void kill_process(pid_t pid)
389 {
390         if (!pid)
391                 return;
392         DSS_WARNING_LOG("sending SIGTERM to pid %d\n", (int)pid);
393         kill(pid, SIGTERM);
394 }
395
396 static void stop_rsync_process(void)
397 {
398         if (!rsync_pid || rsync_stopped)
399                 return;
400         kill(SIGSTOP, rsync_pid);
401         rsync_stopped = 1;
402 }
403
404 static void restart_rsync_process(void)
405 {
406         if (!rsync_pid || !rsync_stopped)
407                 return;
408         kill (SIGCONT, rsync_pid);
409         rsync_stopped = 0;
410 }
411
412
413 /**
414  * Print a log message about the exit status of a child.
415  */
416 static void log_termination_msg(pid_t pid, int status)
417 {
418         if (WIFEXITED(status))
419                 DSS_INFO_LOG("child %i exited. Exit status: %i\n", (int)pid,
420                         WEXITSTATUS(status));
421         else if (WIFSIGNALED(status))
422                 DSS_NOTICE_LOG("child %i was killed by signal %i\n", (int)pid,
423                         WTERMSIG(status));
424         else
425                 DSS_WARNING_LOG("child %i terminated abormally\n", (int)pid);
426 }
427
428 static int wait_for_process(pid_t pid, int *status)
429 {
430         int ret;
431
432         DSS_DEBUG_LOG("Waiting for process %d to terminate\n", (int)pid);
433         for (;;) {
434                 fd_set rfds;
435
436                 FD_ZERO(&rfds);
437                 FD_SET(signal_pipe, &rfds);
438                 ret = dss_select(signal_pipe + 1, &rfds, NULL, NULL);
439                 if (ret < 0)
440                         break;
441                 ret = next_signal();
442                 if (!ret)
443                         continue;
444                 if (ret == SIGCHLD) {
445                         ret = waitpid(pid, status, 0);
446                         if (ret >= 0)
447                                 break;
448                         if (errno != EINTR) { /* error */
449                                 ret = -ERRNO_TO_DSS_ERROR(errno);
450                                 break;
451                         }
452                 }
453                 /* SIGINT or SIGTERM */
454                 DSS_WARNING_LOG("sending SIGTERM to pid %d\n", (int)pid);
455                 kill(pid, SIGTERM);
456         }
457         if (ret < 0)
458                 DSS_ERROR_LOG("failed to wait for process %d\n", (int)pid);
459         else
460                 log_termination_msg(pid, *status);
461         return ret;
462 }
463
464 static int handle_rm_exit(int status)
465 {
466         rm_pid = 0;
467         if (!WIFEXITED(status))
468                 return -E_INVOLUNTARY_EXIT;
469         if (WEXITSTATUS(status))
470                 return -E_BAD_EXIT_CODE;
471         return 1;
472 }
473
474 static int wait_for_rm_process(void)
475 {
476         int status, ret = wait_for_process(rm_pid, &status);
477
478         if (ret < 0)
479                 return ret;
480         return handle_rm_exit(status);
481 }
482
483 static int handle_rsync_exit(int status)
484 {
485         int es, ret;
486
487         if (!WIFEXITED(status)) {
488                 DSS_ERROR_LOG("rsync process %d died involuntary\n", (int)rsync_pid);
489                 ret = -E_INVOLUNTARY_EXIT;
490                 snapshot_creation_status = SCS_READY;
491                 compute_next_snapshot_time();
492                 goto out;
493         }
494         es = WEXITSTATUS(status);
495         if (es != 0 && es != 23 && es != 24) {
496                 DSS_ERROR_LOG("rsync process %d returned %d\n", (int)rsync_pid, es);
497                 ret = -E_BAD_EXIT_CODE;
498                 snapshot_creation_status = SCS_READY;
499                 compute_next_snapshot_time();
500                 goto out;
501         }
502         ret = rename_incomplete_snapshot(current_snapshot_creation_time);
503         if (ret < 0)
504                 goto out;
505         snapshot_creation_status = SCS_RSYNC_SUCCESS;
506 out:
507         rsync_pid = 0;
508         rsync_stopped = 0;
509         return ret;
510 }
511
512 static int handle_pre_create_hook_exit(int status)
513 {
514         int es, ret;
515
516         if (!WIFEXITED(status)) {
517                 snapshot_creation_status = SCS_READY;
518                 compute_next_snapshot_time();
519                 ret = -E_INVOLUNTARY_EXIT;
520                 goto out;
521         }
522         es = WEXITSTATUS(status);
523         if (es) {
524                 snapshot_creation_status = SCS_READY;
525                 compute_next_snapshot_time();
526                 ret = -E_BAD_EXIT_CODE;
527                 goto out;
528         }
529         snapshot_creation_status = SCS_PRE_HOOK_SUCCESS;
530         ret = 1;
531 out:
532         pre_create_hook_pid = 0;
533         return ret;
534 }
535
536 static int handle_sigchld(void)
537 {
538         pid_t pid;
539         int status, ret = reap_child(&pid, &status);
540
541         if (ret <= 0)
542                 return ret;
543         if (pid == rsync_pid)
544                 return handle_rsync_exit(status);
545         if (pid == rm_pid)
546                 return handle_rm_exit(status);
547         if (pid == pre_create_hook_pid)
548                 return handle_pre_create_hook_exit(status);
549         if (pid == post_create_hook_pid) {
550                 snapshot_creation_status = SCS_READY;
551                 compute_next_snapshot_time();
552                 return 1;
553         }
554         DSS_EMERG_LOG("BUG: unknown process %d died\n", (int)pid);
555         exit(EXIT_FAILURE);
556 }
557
558 static int check_config(void)
559 {
560         if (conf.unit_interval_arg <= 0) {
561                 DSS_ERROR_LOG("bad unit interval: %i\n", conf.unit_interval_arg);
562                 return -E_INVALID_NUMBER;
563         }
564         DSS_DEBUG_LOG("unit interval: %i day(s)\n", conf.unit_interval_arg);
565         if (conf.num_intervals_arg <= 0) {
566                 DSS_ERROR_LOG("bad number of intervals  %i\n", conf.num_intervals_arg);
567                 return -E_INVALID_NUMBER;
568         }
569         DSS_DEBUG_LOG("number of intervals: %i\n", conf.num_intervals_arg);
570         return 1;
571 }
572
573 /* exits on errors */
574 static void parse_config_file(int override)
575 {
576         int ret;
577         char *config_file;
578         struct stat statbuf;
579         char *old_logfile_arg = NULL;
580         int old_daemon_given = 0;
581
582         if (conf.config_file_given)
583                 config_file = dss_strdup(conf.config_file_arg);
584         else {
585                 char *home = get_homedir();
586                 config_file = make_message("%s/.dssrc", home);
587                 free(home);
588         }
589         if (override) { /* SIGHUP */
590                 if (conf.logfile_given)
591                         old_logfile_arg = dss_strdup(conf.logfile_arg);
592                 old_daemon_given = conf.daemon_given;
593         }
594
595         ret = stat(config_file, &statbuf);
596         if (ret && conf.config_file_given) {
597                 ret = -ERRNO_TO_DSS_ERROR(errno);
598                 DSS_ERROR_LOG("failed to stat config file %s\n", config_file);
599                 goto out;
600         }
601         if (!ret) {
602                 struct cmdline_parser_params params = {
603                         .override = override,
604                         .initialize = 0,
605                         .check_required = 1,
606                         .check_ambiguity = 0
607                 };
608                 cmdline_parser_config_file(config_file, &conf, &params);
609         }
610         ret = check_config();
611         if (ret < 0)
612                 goto out;
613         if (override) {
614                 /* don't change daemon mode on SIGHUP */
615                 conf.daemon_given = old_daemon_given;
616                 close_log(logfile);
617                 logfile = NULL;
618                 if (conf.logfile_given)
619                         free(old_logfile_arg);
620                 else if (conf.daemon_given) { /* re-use old logfile */
621                         conf.logfile_arg = old_logfile_arg;
622                         conf.logfile_given = 1;
623                 }
624         }
625         if (conf.logfile_given) {
626                 logfile = open_log(conf.logfile_arg);
627                 log_welcome(conf.loglevel_arg);
628         }
629         DSS_EMERG_LOG("loglevel: %d\n", conf.loglevel_arg);
630 //      cmdline_parser_dump(logfile? logfile : stdout, &conf);
631         ret = dss_chdir(conf.dest_dir_arg);
632 out:
633         free(config_file);
634         if (ret >= 0)
635                 return;
636         DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
637         exit(EXIT_FAILURE);
638 }
639
640 static void handle_sighup(void)
641 {
642         DSS_NOTICE_LOG("SIGHUP\n");
643         parse_config_file(1);
644 }
645
646 static void handle_signal(void)
647 {
648         int sig, ret = next_signal();
649
650         if (ret <= 0)
651                 goto out;
652         sig = ret;
653         switch (sig) {
654         case SIGINT:
655         case SIGTERM:
656                 restart_rsync_process();
657                 kill_process(rsync_pid);
658                 kill_process(rm_pid);
659                 exit(EXIT_FAILURE);
660         case SIGHUP:
661                 handle_sighup();
662                 ret = 1;
663                 break;
664         case SIGCHLD:
665                 ret = handle_sigchld();
666                 break;
667         }
668 out:
669         if (ret < 0)
670                 DSS_ERROR_LOG("%s\n", dss_strerror(-ret));
671 }
672
673 static void create_rsync_argv(char ***argv, int64_t *num)
674 {
675         char *logname, *newest;
676         int i = 0, j;
677         struct snapshot_list sl;
678
679         dss_get_snapshot_list(&sl);
680         newest = name_of_newest_complete_snapshot(&sl);
681         free_snapshot_list(&sl);
682
683         *argv = dss_malloc((15 + conf.rsync_option_given) * sizeof(char *));
684         (*argv)[i++] = dss_strdup("rsync");
685         (*argv)[i++] = dss_strdup("-aq");
686         (*argv)[i++] = dss_strdup("--delete");
687         for (j = 0; j < conf.rsync_option_given; j++)
688                 (*argv)[i++] = dss_strdup(conf.rsync_option_arg[j]);
689         if (newest) {
690                 DSS_INFO_LOG("using %s as reference snapshot\n", newest);
691                 (*argv)[i++] = make_message("--link-dest=../%s", newest);
692                 free(newest);
693         } else
694                 DSS_INFO_LOG("no previous snapshot found\n");
695         if (conf.exclude_patterns_given) {
696                 (*argv)[i++] = dss_strdup("--exclude-from");
697                 (*argv)[i++] = dss_strdup(conf.exclude_patterns_arg);
698
699         }
700         logname = dss_logname();
701         if (conf.remote_user_given && !strcmp(conf.remote_user_arg, logname))
702                 (*argv)[i++] = dss_strdup(conf.source_dir_arg);
703         else
704                 (*argv)[i++] = make_message("%s@%s:%s/", conf.remote_user_given?
705                         conf.remote_user_arg : logname,
706                         conf.remote_host_arg, conf.source_dir_arg);
707         free(logname);
708         *num = get_current_time();
709         (*argv)[i++] = incomplete_name(*num);
710         (*argv)[i++] = NULL;
711         for (j = 0; j < i; j++)
712                 DSS_DEBUG_LOG("argv[%d] = %s\n", j, (*argv)[j]);
713 }
714
715 static void free_rsync_argv(char **argv)
716 {
717         int i;
718         for (i = 0; argv[i]; i++)
719                 free(argv[i]);
720         free(argv);
721 }
722
723 static int create_snapshot(char **argv)
724 {
725         int ret, fds[3] = {0, 0, 0};
726         char *name;
727
728         name = incomplete_name(current_snapshot_creation_time);
729         DSS_NOTICE_LOG("creating new snapshot %s\n", name);
730         free(name);
731         ret = dss_exec(&rsync_pid, argv[0], argv, fds);
732         if (ret < 0)
733                 return ret;
734         snapshot_creation_status = SCS_RSYNC_RUNNING;
735         return ret;
736 }
737
738 static int select_loop(void)
739 {
740         int ret;
741         struct timeval tv = {.tv_sec = 0, .tv_usec = 0};
742
743         for (;;) {
744                 fd_set rfds;
745                 int low_disk_space;
746                 char **rsync_argv;
747                 struct timeval now, *tvp = &tv;
748
749                 if (rsync_pid)
750                         tv.tv_sec = 60; /* check every 60 seconds for free disk space */
751                 else if (rm_pid)
752                         tvp = NULL; /* sleep until rm process dies */
753                 FD_ZERO(&rfds);
754                 FD_SET(signal_pipe, &rfds);
755                 DSS_DEBUG_LOG("tvp: %p, tv_sec: %lu\n", tvp, (long unsigned) tv.tv_sec);
756                 ret = dss_select(signal_pipe + 1, &rfds, NULL, tvp);
757                 if (ret < 0)
758                         return ret;
759                 if (FD_ISSET(signal_pipe, &rfds))
760                         handle_signal();
761                 if (rm_pid)
762                         continue;
763                 ret = disk_space_low();
764                 if (ret < 0)
765                         break;
766                 low_disk_space = ret;
767                 ret = try_to_free_disk_space(low_disk_space);
768                 if (ret < 0)
769                         break;
770                 if (rm_pid) {
771                         stop_rsync_process();
772                         continue;
773                 }
774                 restart_rsync_process();
775                 gettimeofday(&now, NULL);
776                 if (tv_diff(&next_snapshot_time, &now, &tv) > 0)
777                         continue;
778                 switch (snapshot_creation_status) {
779                 case SCS_READY:
780                         ret = pre_create_hook();
781                         if (ret < 0)
782                                 goto out;
783                         continue;
784                 case SCS_PRE_HOOK_RUNNING:
785                         continue;
786                 case SCS_PRE_HOOK_SUCCESS:
787                         create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
788                         ret = create_snapshot(rsync_argv);
789                         free_rsync_argv(rsync_argv);
790                         if (ret < 0)
791                                 goto out;
792                         continue;
793                 case SCS_RSYNC_RUNNING:
794                         continue;
795                 case SCS_RSYNC_SUCCESS:
796                         ret = post_create_hook();
797                         if (ret < 0)
798                                 goto out;
799                         continue;
800                 case SCS_POST_HOOK_RUNNING:
801                         continue;
802                 }
803         }
804 out:
805         return ret;
806 }
807
808 static int com_run(void)
809 {
810         int ret;
811
812         if (conf.dry_run_given) {
813                 DSS_ERROR_LOG("dry_run not supported by this command\n");
814                 return -E_SYNTAX;
815         }
816         ret = install_sighandler(SIGHUP);
817         if (ret < 0)
818                 return ret;
819         compute_next_snapshot_time();
820         return select_loop();
821 }
822
823 static int com_prune(void)
824 {
825         int ret;
826         struct snapshot_list sl;
827         struct disk_space ds;
828
829         ret = get_disk_space(".", &ds);
830         if (ret < 0)
831                 return ret;
832         log_disk_space(&ds);
833         for (;;) {
834                 dss_get_snapshot_list(&sl);
835                 ret = remove_outdated_snapshot(&sl);
836                 free_snapshot_list(&sl);
837                 if (ret < 0)
838                         return ret;
839                 if (!ret)
840                         break;
841                 ret = wait_for_rm_process();
842                 if (ret < 0)
843                         goto out;
844         }
845         for (;;) {
846                 dss_get_snapshot_list(&sl);
847                 ret = remove_redundant_snapshot(&sl);
848                 free_snapshot_list(&sl);
849                 if (ret < 0)
850                         return ret;
851                 if (!ret)
852                         break;
853                 ret = wait_for_rm_process();
854                 if (ret < 0)
855                         goto out;
856         }
857         return 1;
858 out:
859         return ret;
860 }
861
862 static int com_create(void)
863 {
864         int ret, status;
865         char **rsync_argv;
866
867         if (conf.dry_run_given) {
868                 int i;
869                 char *msg = NULL;
870                 create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
871                 for (i = 0; rsync_argv[i]; i++) {
872                         char *tmp = msg;
873                         msg = make_message("%s%s%s", tmp? tmp : "",
874                                 tmp? " " : "", rsync_argv[i]);
875                         free(tmp);
876                 }
877                 free_rsync_argv(rsync_argv);
878                 dss_msg("%s\n", msg);
879                 free(msg);
880                 return 1;
881         }
882         ret = pre_create_hook();
883         if (ret < 0)
884                 return ret;
885         if (pre_create_hook_pid) {
886                 ret = wait_for_process(pre_create_hook_pid, &status);
887                 if (ret < 0)
888                         return ret;
889                 ret = handle_pre_create_hook_exit(status);
890                 if (ret < 0)
891                         return ret;
892         }
893         create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
894         ret = create_snapshot(rsync_argv);
895         if (ret < 0)
896                 goto out;
897         ret = wait_for_process(rsync_pid, &status);
898         if (ret < 0)
899                 goto out;
900         ret = handle_rsync_exit(status);
901         if (ret < 0)
902                 goto out;
903         post_create_hook();
904         if (post_create_hook_pid)
905                 ret = wait_for_process(post_create_hook_pid, &status);
906 out:
907         free_rsync_argv(rsync_argv);
908         return ret;
909 }
910
911 static int com_ls(void)
912 {
913         int i;
914         struct snapshot_list sl;
915         struct snapshot *s;
916
917         dss_get_snapshot_list(&sl);
918         FOR_EACH_SNAPSHOT(s, i, &sl)
919                 dss_msg("%u\t%s\n", s->interval, s->name);
920         free_snapshot_list(&sl);
921         return 1;
922 }
923
924 static void setup_signal_handling(void)
925 {
926         int ret;
927
928         DSS_INFO_LOG("setting up signal handlers\n");
929         signal_pipe = signal_init(); /* always successful */
930         ret = install_sighandler(SIGINT);
931         if (ret < 0)
932                 goto err;
933         ret = install_sighandler(SIGTERM);
934         if (ret < 0)
935                 goto err;
936         ret = install_sighandler(SIGCHLD);
937         if (ret < 0)
938                 goto err;
939         return;
940 err:
941         DSS_EMERG_LOG("could not install signal handlers\n");
942         exit(EXIT_FAILURE);
943 }
944
945 /**
946  * The main function of dss.
947  *
948  * \param argc Usual argument count.
949  * \param argv Usual argument vector.
950  */
951 int main(int argc, char **argv)
952 {
953         int ret;
954         struct cmdline_parser_params params = {
955                 .override = 0,
956                 .initialize = 1,
957                 .check_required = 0,
958                 .check_ambiguity = 0
959         };
960
961         cmdline_parser_ext(argc, argv, &conf, &params); /* aborts on errors */
962         parse_config_file(0);
963
964         if (conf.daemon_given)
965                 daemon_init();
966         setup_signal_handling();
967         ret = call_command_handler();
968         if (ret < 0)
969                 DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
970         exit(ret >= 0? EXIT_SUCCESS : EXIT_FAILURE);
971 }