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