Imported Upstream version 2.5.1
[debian/amanda] / server-src / amflush.c
1 /*
2  * Amanda, The Advanced Maryland Automatic Network Disk Archiver
3  * Copyright (c) 1991-1998 University of Maryland at College Park
4  * All Rights Reserved.
5  *
6  * Permission to use, copy, modify, distribute, and sell this software and its
7  * documentation for any purpose is hereby granted without fee, provided that
8  * the above copyright notice appear in all copies and that both that
9  * copyright notice and this permission notice appear in supporting
10  * documentation, and that the name of U.M. not be used in advertising or
11  * publicity pertaining to distribution of the software without specific,
12  * written prior permission.  U.M. makes no representations about the
13  * suitability of this software for any purpose.  It is provided "as is"
14  * without express or implied warranty.
15  *
16  * U.M. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL U.M.
18  * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
19  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
20  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
21  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
22  *
23  * Authors: the Amanda Development Team.  Its members are listed in a
24  * file named AUTHORS, in the root directory of this distribution.
25  */
26 /*
27  * $Id: amflush.c,v 1.95 2006/07/25 21:41:24 martinea Exp $
28  *
29  * write files from work directory onto tape
30  */
31 #include "amanda.h"
32
33 #include "conffile.h"
34 #include "diskfile.h"
35 #include "tapefile.h"
36 #include "logfile.h"
37 #include "clock.h"
38 #include "version.h"
39 #include "holding.h"
40 #include "driverio.h"
41 #include "server_util.h"
42
43 static char *conf_logdir;
44 FILE *driver_stream;
45 char *driver_program;
46 char *reporter_program;
47 char *logroll_program;
48 char *datestamp;
49 char *amflush_timestamp;
50 char *amflush_datestamp;
51 sl_t *datestamp_list;
52
53 /* local functions */
54 int main(int main_argc, char **main_argv);
55 void flush_holdingdisk(char *diskdir, char *datestamp);
56 void confirm(void);
57 void redirect_stderr(void);
58 void detach(void);
59 void run_dumps(void);
60 static int get_letter_from_user(void);
61
62 int
63 main(
64     int         main_argc,
65     char **     main_argv)
66 {
67     int foreground;
68     int batch;
69     int redirect;
70     struct passwd *pw;
71     char *dumpuser;
72     char **datearg = NULL;
73     int nb_datearg = 0;
74     char *conffile;
75     char *conf_diskfile;
76     char *conf_tapelist;
77     char *conf_logfile;
78     int conf_usetimestamps;
79     disklist_t diskq;
80     disk_t *dp;
81     pid_t pid;
82     pid_t driver_pid, reporter_pid;
83     amwait_t exitcode;
84     int opt;
85     dumpfile_t file;
86     sl_t *holding_list=NULL;
87     sle_t *holding_file;
88     int driver_pipe[2];
89     char date_string[100];
90     time_t today;
91     int    new_argc,   my_argc;
92     char **new_argv, **my_argv;
93     char *errstr;
94     struct tm *tm;
95
96     safe_fd(-1, 0);
97     safe_cd();
98
99     set_pname("amflush");
100
101     dbopen(DBG_SUBDIR_SERVER);
102
103     /* Don't die when child closes pipe */
104     signal(SIGPIPE, SIG_IGN);
105
106     erroutput_type = ERR_INTERACTIVE;
107     foreground = 0;
108     batch = 0;
109     redirect = 1;
110
111     /* process arguments */
112
113     parse_server_conf(main_argc, main_argv, &new_argc, &new_argv);
114     my_argc = new_argc;
115     my_argv = new_argv;
116
117     while((opt = getopt(my_argc, my_argv, "bfsD:")) != EOF) {
118         switch(opt) {
119         case 'b': batch = 1;
120                   break;
121         case 'f': foreground = 1;
122                   break;
123         case 's': redirect = 0;
124                   break;
125         case 'D': if (datearg == NULL)
126                       datearg = alloc(21*SIZEOF(char *));
127                   if(nb_datearg == 20) {
128                       fprintf(stderr,"maximum of 20 -D arguments.\n");
129                       exit(1);
130                   }
131                   datearg[nb_datearg++] = stralloc(optarg);
132                   datearg[nb_datearg] = NULL;
133                   break;
134         }
135     }
136     if(!foreground && !redirect) {
137         fprintf(stderr,"Can't redirect to stdout/stderr if not in forground.\n");
138         exit(1);
139     }
140
141     my_argc -= optind, my_argv += optind;
142
143     if(my_argc < 1) {
144         error("Usage: amflush%s [-b] [-f] [-s] [-D date]* <confdir> [host [disk]* ]* [-o configoption]*", versionsuffix());
145         /*NOTREACHED*/
146     }
147
148     config_name = my_argv[0];
149     config_dir = vstralloc(CONFIG_DIR, "/", config_name, "/", NULL);
150
151     conffile = stralloc2(config_dir, CONFFILE_NAME);
152     if(read_conffile(conffile)) {
153         error("errors processing config file \"%s\"", conffile);
154         /*NOTREACHED*/
155     }
156     amfree(conffile);
157
158     dbrename(config_name, DBG_SUBDIR_SERVER);
159
160     report_bad_conf_arg();
161
162     conf_diskfile = getconf_str(CNF_DISKFILE);
163     if (*conf_diskfile == '/') {
164         conf_diskfile = stralloc(conf_diskfile);
165     } else {
166         conf_diskfile = stralloc2(config_dir, conf_diskfile);
167     }
168     if (read_diskfile(conf_diskfile, &diskq) < 0) {
169         error("could not read disklist file \"%s\"", conf_diskfile);
170         /*NOTREACHED*/
171     }
172     errstr = match_disklist(&diskq, my_argc-1, my_argv+1);
173     if (errstr) {
174         printf("%s",errstr);
175         amfree(errstr);
176     }
177     amfree(conf_diskfile);
178
179     conf_tapelist = getconf_str(CNF_TAPELIST);
180     if (*conf_tapelist == '/') {
181         conf_tapelist = stralloc(conf_tapelist);
182     } else {
183         conf_tapelist = stralloc2(config_dir, conf_tapelist);
184     }
185     if(read_tapelist(conf_tapelist)) {
186         error("could not load tapelist \"%s\"", conf_tapelist);
187         /*NOTREACHED*/
188     }
189     amfree(conf_tapelist);
190
191     conf_usetimestamps = getconf_boolean(CNF_USETIMESTAMPS);
192
193     amflush_datestamp = construct_datestamp(NULL);
194     if(conf_usetimestamps == 0) {
195         amflush_timestamp = stralloc(amflush_datestamp);
196     }
197     else {
198         amflush_timestamp = construct_timestamp(NULL);
199     }
200
201     dumpuser = getconf_str(CNF_DUMPUSER);
202     if((pw = getpwnam(dumpuser)) == NULL) {
203         error("dumpuser %s not found in password file", dumpuser);
204         /*NOTREACHED*/
205     }
206     if(pw->pw_uid != getuid()) {
207         error("must run amflush as user %s", dumpuser);
208         /*NOTREACHED*/
209     }
210
211     conf_logdir = getconf_str(CNF_LOGDIR);
212     if (*conf_logdir == '/') {
213         conf_logdir = stralloc(conf_logdir);
214     } else {
215         conf_logdir = stralloc2(config_dir, conf_logdir);
216     }
217     conf_logfile = vstralloc(conf_logdir, "/log", NULL);
218     if (access(conf_logfile, F_OK) == 0) {
219         error("%s exists: amdump or amflush is already running, or you must run amcleanup", conf_logfile);
220         /*NOTREACHED*/
221     }
222     amfree(conf_logfile);
223
224     driver_program = vstralloc(libexecdir, "/", "driver", versionsuffix(),
225                                NULL);
226     reporter_program = vstralloc(sbindir, "/", "amreport", versionsuffix(),
227                                  NULL);
228     logroll_program = vstralloc(libexecdir, "/", "amlogroll", versionsuffix(),
229                                 NULL);
230
231     if(datearg) {
232         sle_t *dir, *next_dir;
233         int i, ok;
234
235         datestamp_list = pick_all_datestamp(1);
236         for(dir = datestamp_list->first; dir != NULL;) {
237             next_dir = dir->next;
238             ok = 0;
239             for(i=0; i<nb_datearg && ok==0; i++) {
240                 ok = match_datestamp(datearg[i], dir->name);
241             }
242             if(ok == 0) { /* remove dir */
243                 remove_sl(datestamp_list, dir);
244             }
245             dir = next_dir;
246         }
247     }
248     else {
249         if(batch) {
250             datestamp_list = pick_all_datestamp(1);
251         }
252         else {
253             datestamp_list = pick_datestamp(1);
254         }
255     }
256
257     if(is_empty_sl(datestamp_list)) {
258         printf("Could not find any Amanda directories to flush.\n");
259         exit(1);
260     }
261
262     holding_list = get_flush(datestamp_list, NULL, 1, 0);
263     if(holding_list->first == NULL) {
264         printf("Could not find any valid dump image, check directory.\n");
265         exit(1);
266     }
267
268     if(!batch) confirm();
269
270     for(dp = diskq.head; dp != NULL; dp = dp->next) {
271         if(dp->todo)
272             log_add(L_DISK, "%s %s", dp->host->hostname, dp->name);
273     }
274
275     if(!foreground) { /* write it before redirecting stdout */
276         puts("Running in background, you can log off now.");
277         puts("You'll get mail when amflush is finished.");
278     }
279
280     if(redirect) redirect_stderr();
281
282     if(!foreground) detach();
283
284     erroutput_type = (ERR_AMANDALOG|ERR_INTERACTIVE);
285     set_logerror(logerror);
286     today = time(NULL);
287     tm = localtime(&today);
288     if (tm)
289         strftime(date_string, 100, "%a %b %e %H:%M:%S %Z %Y", tm);
290     else
291         error("BAD DATE"); /* should never happen */
292     fprintf(stderr, "amflush: start at %s\n", date_string);
293     fprintf(stderr, "amflush: datestamp %s\n", amflush_timestamp);
294     log_add(L_START, "date %s", amflush_timestamp);
295
296     /* START DRIVER */
297     if(pipe(driver_pipe) == -1) {
298         error("error [opening pipe to driver: %s]", strerror(errno));
299         /*NOTREACHED*/
300     }
301     if((driver_pid = fork()) == 0) {
302         /*
303          * This is the child process.
304          */
305         dup2(driver_pipe[0], 0);
306         close(driver_pipe[1]);
307         execle(driver_program,
308                "driver", config_name, "nodump", (char *)0,
309                safe_env());
310         error("cannot exec %s: %s", driver_program, strerror(errno));
311         /*NOTREACHED*/
312     } else if(driver_pid == -1) {
313         error("cannot fork for %s: %s", driver_program, strerror(errno));
314         /*NOTREACHED*/
315     }
316     driver_stream = fdopen(driver_pipe[1], "w");
317     if (!driver_stream) {
318         error("Can't fdopen: %s", strerror(errno));
319         /*NOTREACHED*/
320     }
321
322     fprintf(driver_stream, "DATE %s\n", amflush_timestamp);
323     for(holding_file=holding_list->first; holding_file != NULL;
324                                    holding_file = holding_file->next) {
325         get_dumpfile(holding_file->name, &file);
326
327         dp = lookup_disk(file.name, file.disk);
328         if (!dp) {
329             error("dp == NULL");
330             /*NOTREACHED*/
331         }
332         if (dp->todo == 0) continue;
333
334         fprintf(stderr,
335                 "FLUSH %s %s %s %d %s\n",
336                 file.name,
337                 file.disk,
338                 file.datestamp,
339                 file.dumplevel,
340                 holding_file->name);
341         fprintf(driver_stream,
342                 "FLUSH %s %s %s %d %s\n",
343                 file.name,
344                 file.disk,
345                 file.datestamp,
346                 file.dumplevel,
347                 holding_file->name);
348     }
349     fprintf(stderr, "ENDFLUSH\n"); fflush(stderr);
350     fprintf(driver_stream, "ENDFLUSH\n"); fflush(driver_stream);
351     fclose(driver_stream);
352
353     /* WAIT DRIVER */
354     while(1) {
355         if((pid = wait(&exitcode)) == -1) {
356             if(errno == EINTR) {
357                 continue;
358             } else {
359                 error("wait for %s: %s", driver_program, strerror(errno));
360                 /*NOTREACHED*/
361             }
362         } else if (pid == driver_pid) {
363             break;
364         }
365     }
366
367     free_sl(datestamp_list);
368     datestamp_list = NULL;
369     free_sl(holding_list);
370     holding_list = NULL;
371
372     if(redirect) { /* rename errfile */
373         char *errfile, *errfilex, *nerrfilex, number[100];
374         int tapecycle;
375         int maxdays, days;
376                 
377         struct stat stat_buf;
378
379         errfile = vstralloc(conf_logdir, "/amflush", NULL);
380         errfilex = NULL;
381         nerrfilex = NULL;
382         tapecycle = getconf_int(CNF_TAPECYCLE);
383         maxdays = tapecycle + 2;
384         days = 1;
385         /* First, find out the last existing errfile,           */
386         /* to avoid ``infinite'' loops if tapecycle is infinite */
387
388         snprintf(number,100,"%d",days);
389         errfilex = newvstralloc(errfilex, errfile, ".", number, NULL);
390         while ( days < maxdays && stat(errfilex,&stat_buf)==0) {
391             days++;
392             snprintf(number,100,"%d",days);
393             errfilex = newvstralloc(errfilex, errfile, ".", number, NULL);
394         }
395         snprintf(number,100,"%d",days);
396         errfilex = newvstralloc(errfilex, errfile, ".", number, NULL);
397         nerrfilex = NULL;
398         while (days > 1) {
399             amfree(nerrfilex);
400             nerrfilex = errfilex;
401             days--;
402             snprintf(number,100,"%d",days);
403             errfilex = vstralloc(errfile, ".", number, NULL);
404             if (rename(errfilex, nerrfilex) != 0) {
405                 error("cannot rename \"%s\" to \"%s\": %s",
406                       errfilex, nerrfilex, strerror(errno));
407                 /*NOTREACHED*/
408             }
409         }
410         errfilex = newvstralloc(errfilex, errfile, ".1", NULL);
411         if (rename(errfile,errfilex) != 0) {
412             error("cannot rename \"%s\" to \"%s\": %s",
413                   errfilex, nerrfilex, strerror(errno));
414             /*NOTREACHED*/
415         }
416         amfree(errfile);
417         amfree(errfilex);
418         amfree(nerrfilex);
419     }
420
421     /*
422      * Have amreport generate report and send mail.  Note that we do
423      * not bother checking the exit status.  If it does not work, it
424      * can be rerun.
425      */
426
427     if((reporter_pid = fork()) == 0) {
428         /*
429          * This is the child process.
430          */
431         execle(reporter_program,
432                "amreport", config_name, (char *)0,
433                safe_env());
434         error("cannot exec %s: %s", reporter_program, strerror(errno));
435         /*NOTREACHED*/
436     } else if(reporter_pid == -1) {
437         error("cannot fork for %s: %s", reporter_program, strerror(errno));
438         /*NOTREACHED*/
439     }
440     while(1) {
441         if((pid = wait(&exitcode)) == -1) {
442             if(errno == EINTR) {
443                 continue;
444             } else {
445                 error("wait for %s: %s", reporter_program, strerror(errno));
446                 /*NOTREACHED*/
447             }
448         } else if (pid == reporter_pid) {
449             break;
450         }
451     }
452
453     /*
454      * Call amlogroll to rename the log file to its datestamped version.
455      * Since we exec at this point, our exit code will be that of amlogroll.
456      */
457     execle(logroll_program,
458            "amlogroll", config_name, (char *)0,
459            safe_env());
460     error("cannot exec %s: %s", logroll_program, strerror(errno));
461     /*NOTREACHED*/
462     return 0;                           /* keep the compiler happy */
463 }
464
465
466 static int
467 get_letter_from_user(void)
468 {
469     int r, ch;
470
471     fflush(stdout); fflush(stderr);
472     while((ch = getchar()) != EOF && ch != '\n' && isspace(ch)) {
473         (void)ch; /* Quite lint */
474     }
475     if(ch == '\n') {
476         r = '\0';
477     } else if (ch != EOF) {
478         r = ch;
479         if(islower(r)) r = toupper(r);
480         while((ch = getchar()) != EOF && ch != '\n') { 
481             (void)ch; /* Quite lint */
482         }
483     } else {
484         r = ch;
485         clearerr(stdin);
486     }
487     return r;
488 }
489
490
491 /*
492  * confirm before detaching and running
493  */
494
495 void
496 confirm(void)
497 {
498     tape_t *tp;
499     char *tpchanger;
500     sle_t *dir;
501     int ch;
502     char *extra;
503
504     printf("\nToday is: %s\n",amflush_datestamp);
505     printf("Flushing dumps in");
506     extra = "";
507     for(dir = datestamp_list->first; dir != NULL; dir = dir->next) {
508         printf("%s %s", extra, dir->name);
509         extra = ",";
510     }
511     tpchanger = getconf_str(CNF_TPCHANGER);
512     if(*tpchanger != '\0') {
513         printf(" using tape changer \"%s\".\n", tpchanger);
514     } else {
515         printf(" to tape drive \"%s\".\n", getconf_str(CNF_TAPEDEV));
516     }
517
518     printf("Expecting ");
519     tp = lookup_last_reusable_tape(0);
520     if(tp != NULL) printf("tape %s or ", tp->label);
521     printf("a new tape.");
522     tp = lookup_tapepos(1);
523     if(tp != NULL) printf("  (The last dumps were to tape %s)", tp->label);
524
525     while (1) {
526         printf("\nAre you sure you want to do this [yN]? ");
527         if((ch = get_letter_from_user()) == 'Y') {
528             return;
529         } else if (ch == 'N' || ch == '\0' || ch == EOF) {
530             if (ch == EOF) {
531                 putchar('\n');
532             }
533             break;
534         }
535     }
536
537     printf("Ok, quitting.  Run amflush again when you are ready.\n");
538     exit(1);
539 }
540
541 void
542 redirect_stderr(void)
543 {
544     int fderr;
545     char *errfile;
546
547     fflush(stdout); fflush(stderr);
548     errfile = vstralloc(conf_logdir, "/amflush", NULL);
549     if((fderr = open(errfile, O_WRONLY| O_CREAT | O_TRUNC, 0600)) == -1) {
550         error("could not open %s: %s", errfile, strerror(errno));
551         /*NOTREACHED*/
552     }
553     dup2(fderr,1);
554     dup2(fderr,2);
555     aclose(fderr);
556     amfree(errfile);
557 }
558
559 void
560 detach(void)
561 {
562     int fd;
563
564     fflush(stdout); fflush(stderr);
565     if((fd = open("/dev/null", O_RDWR, 0666)) == -1) {
566         error("could not open /dev/null: %s", strerror(errno));
567         /*NOTREACHED*/
568     }
569
570     dup2(fd,0);
571     aclose(fd);
572
573     switch(fork()) {
574     case -1:
575         error("could not fork: %s", strerror(errno));
576         /*NOTREACHED*/
577
578     case 0:
579         setsid();
580         return;
581     }
582
583     exit(0);
584 }