Imported Upstream version 2.6.1p1
[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         /* keep only first dump if only_one */
150         if (only_one &&
151             curmatch != matches &&
152             (strcmp(curmatch->hostname, matches->hostname) ||
153              strcmp(curmatch->diskname, matches->diskname) ||
154              strcmp(curmatch->timestamp, matches->timestamp) ||
155              curmatch->level != matches->level)) {
156             continue;
157         }
158         if(strcmp("OK", curmatch->status)){
159             g_fprintf(stderr,_("Dump %s %s %s %d had status '%s', skipping\n"),
160                              curmatch->timestamp, curmatch->hostname,
161                              curmatch->diskname, curmatch->level,
162                              curmatch->status);
163             continue;
164         }
165
166         for(iter = needed_tapes; iter; iter = iter->next) {
167             needed_tape_t *curtape = iter->data;
168             if (!strcmp(curtape->label, curmatch->label)) {
169                 int keep = 1;
170
171                 havetape = 1;
172
173                 for(iter2 = curtape->files; iter2; iter2 = iter2->next){
174                     find_result_t *rsttemp = iter2->data;
175                     if(curmatch->filenum == rsttemp->filenum){
176                         g_fprintf(stderr, _("Seeing multiple entries for tape "
177                                    "%s file %lld, using most recent\n"),
178                                     curtape->label,
179                                     (long long)curmatch->filenum);
180                         keep = 0;
181                     }
182                 }
183                 if(!keep){
184                     break;
185                 }
186
187                 curtape->isafile = (curmatch->filenum < 1);
188                 curtape->files = g_slist_prepend(curtape->files, curmatch);
189                 break;
190             }
191         }
192         if (!havetape) {
193             needed_tape_t *newtape = g_new0(needed_tape_t, 1);
194             newtape->files = g_slist_prepend(newtape->files, curmatch);
195             newtape->isafile = (curmatch->filenum < 1);
196             newtape->label = curmatch->label;
197             needed_tapes = g_slist_prepend(needed_tapes, newtape);
198         } /* if(!havetape) */
199
200     } /* for(curmatch = matches ... */
201
202     if(g_slist_length(needed_tapes) == 0){
203       g_fprintf(stderr, _("No matching dumps found\n"));
204       exit(1);
205       /* NOTREACHED */
206     }
207
208     /* sort the tapelist by tape write_timestamp */
209     needed_tapes = g_slist_sort(needed_tapes, sort_needed_tapes_by_write_timestamp);
210
211     /* stick that list in a structure that librestore will understand, removing
212      * files we have already seen in the process; this prefers the earliest written
213      * copy of any dumps which are available on multiple tapes */
214     seen_dumps = NULL;
215     for(iter = needed_tapes; iter; iter = iter->next) {
216         needed_tape_t *curtape = iter->data;
217         for(iter2 = curtape->files; iter2; iter2 = iter2->next) {
218             find_result_t *curfind = iter2->data;
219             find_result_t *prev;
220             GSList *iter;
221             int have_part;
222
223             /* have we already seen this? */
224             have_part = 0;
225             for (iter = seen_dumps; iter; iter = iter->next) {
226                 prev = iter->data;
227
228                 if (!strcmp(prev->partnum, curfind->partnum) &&
229                     !strcmp(prev->hostname, curfind->hostname) &&
230                     !strcmp(prev->diskname, curfind->diskname) &&
231                     !strcmp(prev->timestamp, curfind->timestamp) &&
232                     prev->level == curfind->level) {
233                     have_part = 1;
234                     break;
235                 }
236             }
237
238             if (!have_part) {
239                 seen_dumps = g_slist_prepend(seen_dumps, curfind);
240                 tapes = append_to_tapelist(tapes, curtape->label,
241                                            curfind->filenum, -1, curtape->isafile);
242             }
243         }
244     }
245
246     /* free our resources */
247     for (iter = needed_tapes; iter; iter = iter->next) {
248         needed_tape_t *curtape = iter->data;
249         g_slist_free(curtape->files);
250         g_free(curtape);
251     }
252     g_slist_free(seen_dumps);
253     g_slist_free(needed_tapes);
254     free_find_result(&matches);
255
256     /* and we're done */
257     g_fprintf(stderr, _("%d tape(s) needed for restoration\n"), num_entries(tapes));
258     return(tapes);
259 }
260
261
262 /*
263  * Parses command line, then loops through all files on tape, restoring
264  * files that match the command line criteria.
265  */
266
267 int
268 main(
269     int         argc,
270     char **     argv)
271 {
272     extern int optind;
273     int opt;
274     GSList *dumpspecs = NULL;
275     int fd;
276     tapelist_t *needed_tapes = NULL;
277     char *e;
278     rst_flags_t *rst_flags;
279     int minimum_arguments;
280     config_overwrites_t *cfg_ovr = NULL;
281     disklist_t diskq;
282     char * conf_diskfile = NULL;
283
284     /*
285      * Configure program for internationalization:
286      *   1) Only set the message locale for now.
287      *   2) Set textdomain for all amanda related programs to "amanda"
288      *      We don't want to be forced to support dozens of message catalogs.
289      */  
290     setlocale(LC_MESSAGES, "C");
291     textdomain("amanda"); 
292
293     for(fd = 3; fd < (int)FD_SETSIZE; fd++) {
294         /*
295          * Make sure nobody spoofs us with a lot of extra open files
296          * that would cause a successful open to get a very high file
297          * descriptor, which in turn might be used as an index into
298          * an array (e.g. an fd_set).
299          */
300         close(fd);
301     }
302
303     set_pname("amfetchdump");
304
305     /* Don't die when child closes pipe */
306     signal(SIGPIPE, SIG_IGN);
307
308     dbopen(DBG_SUBDIR_SERVER);
309
310     erroutput_type = ERR_INTERACTIVE;
311     error_exit_status = 2;
312
313     rst_flags = new_rst_flags();
314     rst_flags->wait_tape_prompt = 1;
315
316     /* handle options */
317     cfg_ovr = new_config_overwrites(argc/2);
318     while( (opt = getopt(argc, argv, "alht:scCpb:nwi:d:O:o:")) != -1) {
319         switch(opt) {
320         case 'b':
321             rst_flags->blocksize = (ssize_t)strtol(optarg, &e, 10);
322             if(*e == 'k' || *e == 'K') {
323                 rst_flags->blocksize *= 1024;
324             } else if(*e == 'm' || *e == 'M') {
325                 rst_flags->blocksize *= 1024 * 1024;
326             } else if(*e != '\0') {
327                 error(_("invalid blocksize value \"%s\""), optarg);
328                 /*NOTREACHED*/
329             }
330             if(rst_flags->blocksize < DISK_BLOCK_BYTES) {
331                 error(_("minimum block size is %dk"), DISK_BLOCK_BYTES / 1024);
332                 /*NOTREACHED*/
333             }
334             break;
335         case 'c': rst_flags->compress = 1; break;
336         case 'O': rst_flags->restore_dir = stralloc(optarg) ; break;
337         case 'd': rst_flags->alt_tapedev = stralloc(optarg) ; break;
338         case 'C':
339             rst_flags->compress = 1;
340             rst_flags->comp_type = COMPRESS_BEST_OPT;
341             break;
342         case 'p': rst_flags->pipe_to_fd = STDOUT_FILENO; break;
343         case 's': rst_flags->fsf = (off_t)0; break;
344         case 'l': rst_flags->leave_comp = 1; break;
345         case 'i': rst_flags->inventory_log = stralloc(optarg); break;
346         case 'n': rst_flags->inline_assemble = 0; break;
347         case 'w': rst_flags->delay_assemble = 1; break;
348         case 'a': rst_flags->wait_tape_prompt = 0; break;
349         case 'h': rst_flags->headers = 1; break;
350         case 'o': add_config_overwrite_opt(cfg_ovr, optarg); break;
351         default:
352             usage();
353             /*NOTREACHED*/
354         }
355     }
356
357     /* Check some flags that affect inventorying */
358     if(rst_flags->inventory_log){
359         if(rst_flags->inline_assemble) rst_flags->delay_assemble = 1;
360         rst_flags->inline_assemble = 0;
361         rst_flags->leave_comp = 1;
362         if(rst_flags->compress){
363             error(_("Cannot force compression when doing inventory/search"));
364             /*NOTREACHED*/
365         }
366         g_fprintf(stderr, _("Doing inventory/search, dumps will not be uncompressed or assembled on-the-fly.\n"));
367     }
368     else{
369         if(rst_flags->delay_assemble){
370             g_fprintf(stderr, _("Using -w, split dumpfiles will *not* be automatically uncompressed.\n"));
371         }
372     }
373
374     /* make sure our options all make sense otherwise */
375     if(check_rst_flags(rst_flags) == -1) {
376         usage();
377         /*NOTREACHED*/
378     }
379
380     if (rst_flags->inventory_log) {
381         minimum_arguments = 1;
382     } else {
383         minimum_arguments = 2;
384     }
385  
386     if(argc - optind < minimum_arguments) {
387         usage();
388         /*NOTREACHED*/
389     }
390
391     config_init(CONFIG_INIT_EXPLICIT_NAME, argv[optind++]);
392     apply_config_overwrites(cfg_ovr);
393
394     conf_diskfile = config_dir_relative(getconf_str(CNF_DISKFILE));
395     read_diskfile(conf_diskfile, &diskq);
396     amfree(conf_diskfile);
397
398     if (config_errors(NULL) >= CFGERR_WARNINGS) {
399         config_print_errors();
400         if (config_errors(NULL) >= CFGERR_ERRORS) {
401             g_critical(_("errors processing config file"));
402         }
403     }
404
405     check_running_as(RUNNING_AS_DUMPUSER);
406
407     dbrename(get_config_name(), DBG_SUBDIR_SERVER);
408
409     dumpspecs = cmdline_parse_dumpspecs(argc - optind, argv + optind,
410                                         CMDLINE_PARSE_DATESTAMP |
411                                         CMDLINE_PARSE_LEVEL |
412                                         CMDLINE_EMPTY_TO_WILDCARD);
413
414     /*
415      * We've been told explicitly to go and search through the tapes the hard
416      * way.
417      */
418     if(rst_flags->inventory_log){
419         g_fprintf(stderr, _("Beginning tape-by-tape search.\n"));
420         search_tapes(stderr, stdin, rst_flags->alt_tapedev == NULL,
421                      NULL, dumpspecs, rst_flags, NULL);
422         exit(0);
423     }
424
425
426     /* Decide what tapes we'll need */
427     needed_tapes = list_needed_tapes(dumpspecs,
428                                      rst_flags->pipe_to_fd == STDOUT_FILENO,
429                                      &diskq);
430
431     parent_pid = getpid();
432     atexit(cleanup);
433     get_lock = lock_logfile(); /* config is loaded, should be ok here */
434     if(get_lock == 0) {
435         char *process_name = get_master_process(rst_conf_logfile);
436         error(_("%s exists: %s is already running, or you must run amcleanup"), rst_conf_logfile, process_name);
437     }
438     log_add(L_INFO, "%s pid %ld", get_pname(), (long)getpid());
439     search_tapes(NULL, stdin, rst_flags->alt_tapedev == NULL,
440                  needed_tapes, dumpspecs, rst_flags, NULL);
441     cleanup();
442
443     dumpspec_list_free(dumpspecs);
444
445     if(rst_flags->inline_assemble || rst_flags->delay_assemble)
446         flush_open_outputs(1, NULL);
447     else flush_open_outputs(0, NULL);
448
449     free_disklist(&diskq);
450     free_rst_flags(rst_flags);
451
452     return(0);
453 }
454
455 static void
456 cleanup(void)
457 {
458     if (parent_pid == getpid()) {
459         if (get_lock) {
460             log_add(L_INFO, "pid-done %ld\n", (long)getpid());
461             unlink(rst_conf_logfile);
462         }
463     }
464 }