1cd9749056612f0d29476a1e2e2a80c303cb137f
[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.80 2006/01/14 04:37:19 paddy_s 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 sl_t *datestamp_list;
50
51 /* local functions */
52 int main P((int main_argc, char **main_argv));
53 void flush_holdingdisk P((char *diskdir, char *datestamp));
54 void confirm P((void));
55 void redirect_stderr P((void));
56 void detach P((void));
57 void run_dumps P((void));
58 static int get_letter_from_user P((void));
59
60 int main(main_argc, main_argv)
61 int main_argc;
62 char **main_argv;
63 {
64     int foreground;
65     int batch;
66     int redirect;
67     struct passwd *pw;
68     char *dumpuser;
69     char **datearg = NULL;
70     int nb_datearg = 0;
71     char *conffile;
72     char *conf_diskfile;
73     char *conf_tapelist;
74     char *conf_logfile;
75     disklist_t diskq;
76     disk_t *dp;
77     pid_t pid;
78     pid_t driver_pid, reporter_pid;
79     amwait_t exitcode;
80     int opt;
81     dumpfile_t file;
82     sl_t *holding_list=NULL;
83     sle_t *holding_file;
84     int driver_pipe[2];
85     char date_string[100];
86     time_t today;
87
88     safe_fd(-1, 0);
89     safe_cd();
90
91     set_pname("amflush");
92
93     /* Don't die when child closes pipe */
94     signal(SIGPIPE, SIG_IGN);
95
96     erroutput_type = ERR_INTERACTIVE;
97     foreground = 0;
98     batch = 0;
99     redirect = 1;
100
101     /* process arguments */
102
103     while((opt = getopt(main_argc, main_argv, "bfsD:")) != EOF) {
104         switch(opt) {
105         case 'b': batch = 1;
106                   break;
107         case 'f': foreground = 1;
108                   break;
109         case 's': redirect = 0;
110                   break;
111         case 'D': if (datearg == NULL)
112                       datearg = alloc(21*sizeof(char *));
113                   if(nb_datearg == 20) {
114                       fprintf(stderr,"maximum of 20 -D arguments.\n");
115                       exit(1);
116                   }
117                   datearg[nb_datearg++] = stralloc(optarg);
118                   datearg[nb_datearg] = NULL;
119                   break;
120         }
121     }
122     if(!foreground && !redirect) {
123         fprintf(stderr,"Can't redirect to stdout/stderr if not in forground.\n");
124         exit(1);
125     }
126
127     main_argc -= optind, main_argv += optind;
128
129     if(main_argc < 1) {
130         error("Usage: amflush%s [-b] [-f] [-s] [-D date]* <confdir> [host [disk]* ]*", versionsuffix());
131     }
132
133     config_name = main_argv[0];
134     config_dir = vstralloc(CONFIG_DIR, "/", config_name, "/", NULL);
135
136     conffile = stralloc2(config_dir, CONFFILE_NAME);
137     if(read_conffile(conffile))
138         error("errors processing config file \"%s\"", conffile);
139     amfree(conffile);
140
141     conf_diskfile = getconf_str(CNF_DISKFILE);
142     if (*conf_diskfile == '/') {
143         conf_diskfile = stralloc(conf_diskfile);
144     } else {
145         conf_diskfile = stralloc2(config_dir, conf_diskfile);
146     }
147     if (read_diskfile(conf_diskfile, &diskq) < 0)
148         error("could not read disklist file \"%s\"", conf_diskfile);
149     match_disklist(&diskq, main_argc-1, main_argv+1);
150     amfree(conf_diskfile);
151
152     conf_tapelist = getconf_str(CNF_TAPELIST);
153     if (*conf_tapelist == '/') {
154         conf_tapelist = stralloc(conf_tapelist);
155     } else {
156         conf_tapelist = stralloc2(config_dir, conf_tapelist);
157     }
158     if(read_tapelist(conf_tapelist))
159         error("could not load tapelist \"%s\"", conf_tapelist);
160     amfree(conf_tapelist);
161
162     datestamp = construct_datestamp(NULL);
163
164     dumpuser = getconf_str(CNF_DUMPUSER);
165     if((pw = getpwnam(dumpuser)) == NULL)
166         error("dumpuser %s not found in password file", dumpuser);
167     if(pw->pw_uid != getuid())
168         error("must run amflush as user %s", dumpuser);
169
170     conf_logdir = getconf_str(CNF_LOGDIR);
171     if (*conf_logdir == '/') {
172         conf_logdir = stralloc(conf_logdir);
173     } else {
174         conf_logdir = stralloc2(config_dir, conf_logdir);
175     }
176     conf_logfile = vstralloc(conf_logdir, "/log", NULL);
177     if (access(conf_logfile, F_OK) == 0)
178         error("%s exists: amdump or amflush is already running, or you must run amcleanup", conf_logfile);
179     amfree(conf_logfile);
180
181     driver_program = vstralloc(libexecdir, "/", "driver", versionsuffix(),
182                                NULL);
183     reporter_program = vstralloc(sbindir, "/", "amreport", versionsuffix(),
184                                  NULL);
185     logroll_program = vstralloc(libexecdir, "/", "amlogroll", versionsuffix(),
186                                 NULL);
187
188     if(datearg) {
189         sle_t *dir, *next_dir;
190         int i, ok;
191
192         datestamp_list = pick_all_datestamp(1);
193         for(dir = datestamp_list->first; dir != NULL;) {
194             next_dir = dir->next;
195             ok = 0;
196             for(i=0; i<nb_datearg && ok==0; i++) {
197                 ok = match_datestamp(datearg[i], dir->name);
198             }
199             if(ok == 0) { /* remove dir */
200                 remove_sl(datestamp_list, dir);
201             }
202             dir = next_dir;
203         }
204     }
205     else {
206         if(batch) {
207             datestamp_list = pick_all_datestamp(1);
208         }
209         else {
210             datestamp_list = pick_datestamp(1);
211         }
212     }
213
214     if(is_empty_sl(datestamp_list)) {
215         printf("Could not find any Amanda directories to flush.\n");
216         exit(1);
217     }
218
219     holding_list = get_flush(datestamp_list, NULL, 1, 0);
220     if(holding_list->first == NULL) {
221         printf("Could not find any valid dump image, check directory.\n");
222         exit(1);
223     }
224
225     if(!batch) confirm();
226
227     for(dp = diskq.head; dp != NULL; dp = dp->next) {
228         if(dp->todo)
229             log_add(L_DISK, "%s %s", dp->host->hostname, dp->name);
230     }
231
232     if(!foreground) { /* write it before redirecting stdout */
233         puts("Running in background, you can log off now.");
234         puts("You'll get mail when amflush is finished.");
235     }
236
237     if(redirect) redirect_stderr();
238
239     if(!foreground) detach();
240
241     erroutput_type = (ERR_AMANDALOG|ERR_INTERACTIVE);
242     set_logerror(logerror);
243     today = time(NULL);
244     strftime(date_string, 100, "%a %b %e %H:%M:%S %Z %Y", localtime (&today));
245     fprintf(stderr, "amflush: start at %s\n", date_string);
246     fprintf(stderr, "amflush: datestamp %s\n", datestamp);
247     log_add(L_START, "date %s", datestamp);
248
249     /* START DRIVER */
250     if(pipe(driver_pipe) == -1) {
251         error("error [opening pipe to driver: %s]", strerror(errno));
252     }
253     if((driver_pid = fork()) == 0) {
254         /*
255          * This is the child process.
256          */
257         dup2(driver_pipe[0], 0);
258         close(driver_pipe[1]);
259         execle(driver_program,
260                "driver", config_name, "nodump", (char *)0,
261                safe_env());
262         error("cannot exec %s: %s", driver_program, strerror(errno));
263     } else if(driver_pid == -1) {
264         error("cannot fork for %s: %s", driver_program, strerror(errno));
265     }
266     driver_stream = fdopen(driver_pipe[1], "w");
267
268     for(holding_file=holding_list->first; holding_file != NULL;
269                                    holding_file = holding_file->next) {
270         get_dumpfile(holding_file->name, &file);
271
272         dp = lookup_disk(file.name, file.disk);
273         if (dp->todo == 0) continue;
274
275         fprintf(stderr,
276                 "FLUSH %s %s %s %d %s\n",
277                 file.name,
278                 file.disk,
279                 file.datestamp,
280                 file.dumplevel,
281                 holding_file->name);
282         fprintf(driver_stream,
283                 "FLUSH %s %s %s %d %s\n",
284                 file.name,
285                 file.disk,
286                 file.datestamp,
287                 file.dumplevel,
288                 holding_file->name);
289     }
290     fprintf(stderr, "ENDFLUSH\n"); fflush(stderr);
291     fprintf(driver_stream, "ENDFLUSH\n"); fflush(driver_stream);
292     fclose(driver_stream);
293
294     /* WAIT DRIVER */
295     while(1) {
296         if((pid = wait(&exitcode)) == -1) {
297             if(errno == EINTR) {
298                 continue;
299             } else {
300                 error("wait for %s: %s", driver_program, strerror(errno));
301             }
302         } else if (pid == driver_pid) {
303             break;
304         }
305     }
306
307     free_sl(datestamp_list);
308     datestamp_list = NULL;
309     free_sl(holding_list);
310     holding_list = NULL;
311
312     if(redirect) { /* rename errfile */
313         char *errfile, *errfilex, *nerrfilex, number[100];
314         int tapecycle;
315         int maxdays, days;
316                 
317         struct stat stat_buf;
318
319         errfile = vstralloc(conf_logdir, "/amflush", NULL);
320         errfilex = NULL;
321         nerrfilex = NULL;
322         tapecycle = getconf_int(CNF_TAPECYCLE);
323         maxdays = tapecycle + 2;
324         days = 1;
325         /* First, find out the last existing errfile,           */
326         /* to avoid ``infinite'' loops if tapecycle is infinite */
327
328         snprintf(number,100,"%d",days);
329         errfilex = newvstralloc(errfilex, errfile, ".", number, NULL);
330         while ( days < maxdays && stat(errfilex,&stat_buf)==0) {
331             days++;
332             snprintf(number,100,"%d",days);
333             errfilex = newvstralloc(errfilex, errfile, ".", number, NULL);
334         }
335         snprintf(number,100,"%d",days);
336         errfilex = newvstralloc(errfilex, errfile, ".", number, NULL);
337         nerrfilex = NULL;
338         while (days > 1) {
339             amfree(nerrfilex);
340             nerrfilex = errfilex;
341             days--;
342             snprintf(number,100,"%d",days);
343             errfilex = vstralloc(errfile, ".", number, NULL);
344             if (rename(errfilex, nerrfilex) != 0) {
345                 error("cannot rename \"%s\" to \"%s\": %s",
346                       errfilex, nerrfilex, strerror(errno));
347             }
348         }
349         errfilex = newvstralloc(errfilex, errfile, ".1", NULL);
350         if (rename(errfile,errfilex) != 0) {
351             error("cannot rename \"%s\" to \"%s\": %s",
352                   errfilex, nerrfilex, strerror(errno));
353         }
354         amfree(errfile);
355         amfree(errfilex);
356         amfree(nerrfilex);
357     }
358
359     /*
360      * Have amreport generate report and send mail.  Note that we do
361      * not bother checking the exit status.  If it does not work, it
362      * can be rerun.
363      */
364
365     if((reporter_pid = fork()) == 0) {
366         /*
367          * This is the child process.
368          */
369         execle(reporter_program,
370                "amreport", config_name, (char *)0,
371                safe_env());
372         error("cannot exec %s: %s", reporter_program, strerror(errno));
373     } else if(reporter_pid == -1) {
374         error("cannot fork for %s: %s", reporter_program, strerror(errno));
375     }
376     while(1) {
377         if((pid = wait(&exitcode)) == -1) {
378             if(errno == EINTR) {
379                 continue;
380             } else {
381                 error("wait for %s: %s", reporter_program, strerror(errno));
382             }
383         } else if (pid == reporter_pid) {
384             break;
385         }
386     }
387
388     /*
389      * Call amlogroll to rename the log file to its datestamped version.
390      * Since we exec at this point, our exit code will be that of amlogroll.
391      */
392
393     execle(logroll_program,
394            "amlogroll", config_name, (char *)0,
395            safe_env());
396     error("cannot exec %s: %s", logroll_program, strerror(errno));
397     return 0;                           /* keep the compiler happy */
398 }
399
400
401 static int get_letter_from_user()
402 {
403     int r, ch;
404
405     fflush(stdout); fflush(stderr);
406     while((ch = getchar()) != EOF && ch != '\n' && isspace(ch)) {}
407     if(ch == '\n') {
408         r = '\0';
409     } else if (ch != EOF) {
410         r = ch;
411         if(islower(r)) r = toupper(r);
412         while((ch = getchar()) != EOF && ch != '\n') {}
413     } else {
414         r = ch;
415         clearerr(stdin);
416     }
417     return r;
418 }
419
420
421 void confirm()
422 /* confirm before detaching and running */
423 {
424     tape_t *tp;
425     char *tpchanger;
426     sle_t *dir;
427     int ch;
428     char *extra;
429
430     printf("\nToday is: %s\n",datestamp);
431     printf("Flushing dumps in");
432     extra = "";
433     for(dir = datestamp_list->first; dir != NULL; dir = dir->next) {
434         printf("%s %s", extra, dir->name);
435         extra = ",";
436     }
437     tpchanger = getconf_str(CNF_TPCHANGER);
438     if(*tpchanger != '\0') {
439         printf(" using tape changer \"%s\".\n", tpchanger);
440     } else {
441         printf(" to tape drive \"%s\".\n", getconf_str(CNF_TAPEDEV));
442     }
443
444     printf("Expecting ");
445     tp = lookup_last_reusable_tape(0);
446     if(tp != NULL) printf("tape %s or ", tp->label);
447     printf("a new tape.");
448     tp = lookup_tapepos(1);
449     if(tp != NULL) printf("  (The last dumps were to tape %s)", tp->label);
450
451     while (1) {
452         printf("\nAre you sure you want to do this [yN]? ");
453         if((ch = get_letter_from_user()) == 'Y') {
454             return;
455         } else if (ch == 'N' || ch == '\0' || ch == EOF) {
456             if (ch == EOF) {
457                 putchar('\n');
458             }
459             break;
460         }
461     }
462
463     printf("Ok, quitting.  Run amflush again when you are ready.\n");
464     exit(1);
465 }
466
467 void redirect_stderr()
468 {
469     int fderr;
470     char *errfile;
471
472     fflush(stdout); fflush(stderr);
473     errfile = vstralloc(conf_logdir, "/amflush", NULL);
474     if((fderr = open(errfile, O_WRONLY| O_CREAT | O_TRUNC, 0600)) == -1)
475         error("could not open %s: %s", errfile, strerror(errno));
476     dup2(fderr,1);
477     dup2(fderr,2);
478     aclose(fderr);
479     amfree(errfile);
480 }
481
482 void detach()
483 {
484     int fd;
485
486     fflush(stdout); fflush(stderr);
487     if((fd = open("/dev/null", O_RDWR, 0666)) == -1)
488         error("could not open /dev/null: %s", strerror(errno));
489
490     dup2(fd,0);
491     aclose(fd);
492
493     switch(fork()) {
494     case -1: error("could not fork: %s", strerror(errno));
495     case 0:
496         setsid();
497         return;
498     }
499
500     exit(0);
501 }
502
503