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