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