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