Imported Upstream version 2.6.1
[debian/amanda] / restore-src / amfetchdump.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: amfetchdump.c,v 1.16 2006/08/24 01:57:15 paddy_s Exp $
28  *
29  * retrieves specific dumps from a set of amanda tapes
30  */
31
32 #include "amanda.h"
33 #include "fileheader.h"
34 #include "util.h"
35 #include "restore.h"
36 #include "diskfile.h"
37 #include "tapefile.h"
38 #include "find.h"
39 #include "changer.h"
40 #include "logfile.h"
41 #include "cmdline.h"
42 #include "server_util.h"
43
44 #define CREAT_MODE      0640
45
46 extern char *rst_conf_logfile;
47 extern char *config_dir;
48 int get_lock = 0;
49
50 typedef struct needed_tapes_s {
51     char *label;
52     int isafile;
53     GSList *files;
54 } needed_tape_t;
55
56 /* local functions */
57
58 tapelist_t *list_needed_tapes(GSList *dumpspecs, int only_one, disklist_t *diskqp);
59 void usage(void);
60 int main(int argc, char **argv);
61
62 /* exit routine */
63 static pid_t parent_pid = -1;
64 static void cleanup(void);
65
66
67 /*
68  * Print usage message and terminate.
69  */
70
71 void
72 usage(void)
73 {
74     g_fprintf(stderr, _("Usage: amfetchdump [options] config hostname [diskname [datestamp [level [hostname [diskname [datestamp [level ... ]]]]]]] [-o configoption]*\n\n"));
75     g_fprintf(stderr, _("Goes and grabs a dump from tape, moving tapes around and assembling parts as\n"));
76     g_fprintf(stderr, _("necessary.  Files are restored to the current directory, unless otherwise\nspecified.\n\n"));
77     g_fprintf(stderr, _("  -p Pipe exactly *one* complete dumpfile to stdout, instead of to disk.\n"));
78     g_fprintf(stderr, _("  -O <output dir> Restore files to this directory.\n"));
79     g_fprintf(stderr, _("  -d <device> Force restoration from a particular tape device.\n"));
80     g_fprintf(stderr, _("  -c Compress output, fastest method available.\n"));
81     g_fprintf(stderr, _("  -C Compress output, best filesize method available.\n"));
82     g_fprintf(stderr, _("  -l Leave dumps (un)compressed, whichever way they were originally on tape.\n"));
83     g_fprintf(stderr, _("  -a Assume all tapes are available via changer, do not prompt for initial load.\n"));
84     g_fprintf(stderr, _("  -i <dst_file> Search through tapes and write out an inventory while we\n     restore.  Useful only if normal logs are unavailable.\n"));
85     g_fprintf(stderr, _("  -w Wait to put split dumps together until all chunks have been restored.\n"));
86     g_fprintf(stderr, _("  -n Do not reassemble split dumpfiles.\n"));
87     g_fprintf(stderr, _("  -k Skip the rewind/label read when reading a new tape.\n"));
88     g_fprintf(stderr, _("  -s Do not use fast forward to skip files we won't restore.  Use only if fsf\n     causes your tapes to skip too far.\n"));
89     g_fprintf(stderr, _("  -b <blocksize> Force a particular block size (default is 32kb).\n"));
90     exit(1);
91 }
92
93 static gint
94 sort_needed_tapes_by_write_timestamp(
95         gconstpointer a,
96         gconstpointer b)
97 {
98     needed_tape_t *a_nt = (needed_tape_t *)a;
99     needed_tape_t *b_nt = (needed_tape_t *)b;
100     tape_t *a_t = a_nt->isafile? NULL : lookup_tapelabel(a_nt->label);
101     tape_t *b_t = b_nt->isafile? NULL : lookup_tapelabel(b_nt->label);
102     char *a_ds = a_t? a_t->datestamp : "none";
103     char *b_ds = b_t? b_t->datestamp : "none";
104
105     return strcmp(a_ds, b_ds);
106 }
107
108 /*
109  * Build the list of tapes we'll be wanting, and include data about the
110  * files we want from said tapes while we're at it (the whole find_result
111  * should do fine)
112  */
113 tapelist_t *
114 list_needed_tapes(
115     GSList *    dumpspecs,
116     int         only_one,
117     disklist_t  *diskqp)
118 {
119     GSList *needed_tapes = NULL;
120     GSList *seen_dumps = NULL;
121     GSList *iter, *iter2;
122     find_result_t *alldumps = NULL;
123     find_result_t *curmatch = NULL;
124     find_result_t *matches = NULL;
125     tapelist_t *tapes = NULL;
126     char *conf_tapelist;
127
128     /* Load the tape list */
129     conf_tapelist = config_dir_relative(getconf_str(CNF_TAPELIST));
130     if(read_tapelist(conf_tapelist)) {
131         error(_("could not load tapelist \"%s\""), conf_tapelist);
132         /*NOTREACHED*/
133     }
134     amfree(conf_tapelist);
135
136     /* Grab a find_output_t of all logged dumps */
137     alldumps = find_dump(diskqp);
138     if(alldumps == NULL){
139         g_fprintf(stderr, _("No dump records found\n"));
140         exit(1);
141     }
142
143     /* Compare all known dumps to our match list, note what we'll need */
144     matches = dumps_match_dumpspecs(alldumps, dumpspecs, 1);
145     sort_find_result("Dhklpw", &matches);
146     for(curmatch = matches; curmatch; curmatch = curmatch->next) {
147         int havetape = 0;
148
149         g_fprintf(stderr, "Examining %s %s on %s\n", curmatch->hostname, curmatch->diskname, curmatch->label);
150         /* keep only first dump if only_one */
151         if (only_one &&
152             curmatch != matches &&
153             (strcmp(curmatch->hostname, matches->hostname) ||
154              strcmp(curmatch->diskname, matches->diskname) ||
155              strcmp(curmatch->timestamp, matches->timestamp) ||
156              curmatch->level != matches->level)) {
157             g_fprintf(stderr, "only_one matched\n");
158             continue;
159         }
160         if(strcmp("OK", curmatch->status)){
161             g_fprintf(stderr,_("Dump %s %s %s %d had status '%s', skipping\n"),
162                              curmatch->timestamp, curmatch->hostname,
163                              curmatch->diskname, curmatch->level,
164                              curmatch->status);
165             g_fprintf(stderr, "!OK\n");
166             continue;
167         }
168
169         for(iter = needed_tapes; iter; iter = iter->next) {
170             needed_tape_t *curtape = iter->data;
171             if (!strcmp(curtape->label, curmatch->label)) {
172                 int keep = 1;
173
174                 havetape = 1;
175
176                 for(iter2 = curtape->files; iter2; iter2 = iter2->next){
177                     find_result_t *rsttemp = iter2->data;
178                     if(curmatch->filenum == rsttemp->filenum){
179                         g_fprintf(stderr, _("Seeing multiple entries for tape "
180                                    "%s file %lld, using most recent\n"),
181                                     curtape->label,
182                                     (long long)curmatch->filenum);
183                         keep = 0;
184                     }
185                 }
186                 if(!keep){
187                     break;
188                 }
189
190                 curtape->isafile = (curmatch->filenum < 1);
191                 curtape->files = g_slist_prepend(curtape->files, curmatch);
192                 break;
193             }
194         }
195         if (!havetape) {
196             needed_tape_t *newtape = g_new0(needed_tape_t, 1);
197             newtape->files = g_slist_prepend(newtape->files, curmatch);
198             newtape->isafile = (curmatch->filenum < 1);
199             newtape->label = curmatch->label;
200             needed_tapes = g_slist_prepend(needed_tapes, newtape);
201         } /* if(!havetape) */
202
203     } /* for(curmatch = matches ... */
204
205     if(g_slist_length(needed_tapes) == 0){
206       g_fprintf(stderr, _("No matching dumps found\n"));
207       exit(1);
208       /* NOTREACHED */
209     }
210
211     /* sort the tapelist by tape write_timestamp */
212     needed_tapes = g_slist_sort(needed_tapes, sort_needed_tapes_by_write_timestamp);
213
214     /* stick that list in a structure that librestore will understand, removing
215      * files we have already seen in the process; this prefers the earliest written
216      * copy of any dumps which are available on multiple tapes */
217     seen_dumps = NULL;
218     for(iter = needed_tapes; iter; iter = iter->next) {
219         needed_tape_t *curtape = iter->data;
220         for(iter2 = curtape->files; iter2; iter2 = iter2->next) {
221             find_result_t *curfind = iter2->data;
222             find_result_t *prev;
223             GSList *iter;
224             int have_part;
225
226             /* have we already seen this? */
227             have_part = 0;
228             for (iter = seen_dumps; iter; iter = iter->next) {
229                 prev = iter->data;
230
231                 if (!strcmp(prev->partnum, curfind->partnum) &&
232                     !strcmp(prev->hostname, curfind->hostname) &&
233                     !strcmp(prev->diskname, curfind->diskname) &&
234                     !strcmp(prev->timestamp, curfind->timestamp) &&
235                     prev->level == curfind->level) {
236                     have_part = 1;
237                     break;
238                 }
239             }
240
241             if (!have_part) {
242                 seen_dumps = g_slist_prepend(seen_dumps, curfind);
243                 tapes = append_to_tapelist(tapes, curtape->label,
244                                            curfind->filenum, -1, curtape->isafile);
245             }
246         }
247     }
248
249     /* free our resources */
250     for (iter = needed_tapes; iter; iter = iter->next) {
251         needed_tape_t *curtape = iter->data;
252         g_slist_free(curtape->files);
253         g_free(curtape);
254     }
255     g_slist_free(seen_dumps);
256     g_slist_free(needed_tapes);
257     free_find_result(&matches);
258
259     /* and we're done */
260     g_fprintf(stderr, _("%d tape(s) needed for restoration\n"), num_entries(tapes));
261     return(tapes);
262 }
263
264
265 /*
266  * Parses command line, then loops through all files on tape, restoring
267  * files that match the command line criteria.
268  */
269
270 int
271 main(
272     int         argc,
273     char **     argv)
274 {
275     extern int optind;
276     int opt;
277     GSList *dumpspecs = NULL;
278     int fd;
279     tapelist_t *needed_tapes = NULL;
280     char *e;
281     rst_flags_t *rst_flags;
282     int minimum_arguments;
283     config_overwrites_t *cfg_ovr = NULL;
284     disklist_t diskq;
285     char * conf_diskfile = NULL;
286
287     /*
288      * Configure program for internationalization:
289      *   1) Only set the message locale for now.
290      *   2) Set textdomain for all amanda related programs to "amanda"
291      *      We don't want to be forced to support dozens of message catalogs.
292      */  
293     setlocale(LC_MESSAGES, "C");
294     textdomain("amanda"); 
295
296     for(fd = 3; fd < (int)FD_SETSIZE; fd++) {
297         /*
298          * Make sure nobody spoofs us with a lot of extra open files
299          * that would cause a successful open to get a very high file
300          * descriptor, which in turn might be used as an index into
301          * an array (e.g. an fd_set).
302          */
303         close(fd);
304     }
305
306     set_pname("amfetchdump");
307
308     /* Don't die when child closes pipe */
309     signal(SIGPIPE, SIG_IGN);
310
311     dbopen(DBG_SUBDIR_SERVER);
312
313     erroutput_type = ERR_INTERACTIVE;
314     error_exit_status = 2;
315
316     rst_flags = new_rst_flags();
317     rst_flags->wait_tape_prompt = 1;
318
319     /* handle options */
320     cfg_ovr = new_config_overwrites(argc/2);
321     while( (opt = getopt(argc, argv, "alht:scCpb:nwi:d:O:o:")) != -1) {
322         switch(opt) {
323         case 'b':
324             rst_flags->blocksize = (ssize_t)strtol(optarg, &e, 10);
325             if(*e == 'k' || *e == 'K') {
326                 rst_flags->blocksize *= 1024;
327             } else if(*e == 'm' || *e == 'M') {
328                 rst_flags->blocksize *= 1024 * 1024;
329             } else if(*e != '\0') {
330                 error(_("invalid blocksize value \"%s\""), optarg);
331                 /*NOTREACHED*/
332             }
333             if(rst_flags->blocksize < DISK_BLOCK_BYTES) {
334                 error(_("minimum block size is %dk"), DISK_BLOCK_BYTES / 1024);
335                 /*NOTREACHED*/
336             }
337             break;
338         case 'c': rst_flags->compress = 1; break;
339         case 'O': rst_flags->restore_dir = stralloc(optarg) ; break;
340         case 'd': rst_flags->alt_tapedev = stralloc(optarg) ; break;
341         case 'C':
342             rst_flags->compress = 1;
343             rst_flags->comp_type = COMPRESS_BEST_OPT;
344             break;
345         case 'p': rst_flags->pipe_to_fd = STDOUT_FILENO; break;
346         case 's': rst_flags->fsf = (off_t)0; break;
347         case 'l': rst_flags->leave_comp = 1; break;
348         case 'i': rst_flags->inventory_log = stralloc(optarg); break;
349         case 'n': rst_flags->inline_assemble = 0; break;
350         case 'w': rst_flags->delay_assemble = 1; break;
351         case 'a': rst_flags->wait_tape_prompt = 0; break;
352         case 'h': rst_flags->headers = 1; break;
353         case 'o': add_config_overwrite_opt(cfg_ovr, optarg); break;
354         default:
355             usage();
356             /*NOTREACHED*/
357         }
358     }
359
360     /* Check some flags that affect inventorying */
361     if(rst_flags->inventory_log){
362         if(rst_flags->inline_assemble) rst_flags->delay_assemble = 1;
363         rst_flags->inline_assemble = 0;
364         rst_flags->leave_comp = 1;
365         if(rst_flags->compress){
366             error(_("Cannot force compression when doing inventory/search"));
367             /*NOTREACHED*/
368         }
369         g_fprintf(stderr, _("Doing inventory/search, dumps will not be uncompressed or assembled on-the-fly.\n"));
370     }
371     else{
372         if(rst_flags->delay_assemble){
373             g_fprintf(stderr, _("Using -w, split dumpfiles will *not* be automatically uncompressed.\n"));
374         }
375     }
376
377     /* make sure our options all make sense otherwise */
378     if(check_rst_flags(rst_flags) == -1) {
379         usage();
380         /*NOTREACHED*/
381     }
382
383     if (rst_flags->inventory_log) {
384         minimum_arguments = 1;
385     } else {
386         minimum_arguments = 2;
387     }
388  
389     if(argc - optind < minimum_arguments) {
390         usage();
391         /*NOTREACHED*/
392     }
393
394     config_init(CONFIG_INIT_EXPLICIT_NAME, argv[optind++]);
395     apply_config_overwrites(cfg_ovr);
396
397     conf_diskfile = config_dir_relative(getconf_str(CNF_DISKFILE));
398     read_diskfile(conf_diskfile, &diskq);
399     amfree(conf_diskfile);
400
401     if (config_errors(NULL) >= CFGERR_WARNINGS) {
402         config_print_errors();
403         if (config_errors(NULL) >= CFGERR_ERRORS) {
404             g_critical(_("errors processing config file"));
405         }
406     }
407
408     check_running_as(RUNNING_AS_DUMPUSER);
409
410     dbrename(get_config_name(), DBG_SUBDIR_SERVER);
411
412     dumpspecs = cmdline_parse_dumpspecs(argc - optind, argv + optind,
413                                         CMDLINE_PARSE_DATESTAMP |
414                                         CMDLINE_PARSE_LEVEL |
415                                         CMDLINE_EMPTY_TO_WILDCARD);
416
417     /*
418      * We've been told explicitly to go and search through the tapes the hard
419      * way.
420      */
421     if(rst_flags->inventory_log){
422         g_fprintf(stderr, _("Beginning tape-by-tape search.\n"));
423         search_tapes(stderr, stdin, rst_flags->alt_tapedev == NULL,
424                      NULL, dumpspecs, rst_flags, NULL);
425         exit(0);
426     }
427
428
429     /* Decide what tapes we'll need */
430     needed_tapes = list_needed_tapes(dumpspecs,
431                                      rst_flags->pipe_to_fd == STDOUT_FILENO,
432                                      &diskq);
433
434     parent_pid = getpid();
435     atexit(cleanup);
436     get_lock = lock_logfile(); /* config is loaded, should be ok here */
437     if(get_lock == 0) {
438         char *process_name = get_master_process(rst_conf_logfile);
439         error(_("%s exists: %s is already running, or you must run amcleanup"), rst_conf_logfile, process_name);
440     }
441     log_add(L_INFO, "%s pid %ld", get_pname(), (long)getpid());
442     search_tapes(NULL, stdin, rst_flags->alt_tapedev == NULL,
443                  needed_tapes, dumpspecs, rst_flags, NULL);
444     cleanup();
445
446     dumpspec_list_free(dumpspecs);
447
448     if(rst_flags->inline_assemble || rst_flags->delay_assemble)
449         flush_open_outputs(1, NULL);
450     else flush_open_outputs(0, NULL);
451
452     free_disklist(&diskq);
453     free_rst_flags(rst_flags);
454
455     return(0);
456 }
457
458 static void
459 cleanup(void)
460 {
461     if (parent_pid == getpid()) {
462         if (get_lock) {
463             log_add(L_INFO, "pid-done %ld\n", (long)getpid());
464             unlink(rst_conf_logfile);
465         }
466     }
467 }