]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/bscan.c
45f53f5332e447bc80d1323f1d9625fef7ef8203
[bacula/bacula] / bacula / src / stored / bscan.c
1 /*
2  *
3  *  Program to scan a Bacula Volume and compare it with
4  *    the catalog and optionally synchronize the catalog
5  *    with the tape.
6  *
7  *   Kern E. Sibbald, December 2001
8  *
9  *
10  *   Version $Id$
11  */
12 /*
13    Copyright (C) 2001-2004 Kern Sibbald and John Walker
14
15    This program is free software; you can redistribute it and/or
16    modify it under the terms of the GNU General Public License as
17    published by the Free Software Foundation; either version 2 of
18    the License, or (at your option) any later version.
19
20    This program is distributed in the hope that it will be useful,
21    but WITHOUT ANY WARRANTY; without even the implied warranty of
22    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23    General Public License for more details.
24
25    You should have received a copy of the GNU General Public
26    License along with this program; if not, write to the Free
27    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
28    MA 02111-1307, USA.
29
30  */
31
32 #include "bacula.h"
33 #include "stored.h"
34 #include "findlib/find.h"
35 #include "cats/cats.h"
36
37 /* Forward referenced functions */
38 static void do_scan(void);
39 static bool record_cb(JCR *jcr, DEVICE *dev, DEV_BLOCK *block, DEV_RECORD *rec);
40 static int  create_file_attributes_record(B_DB *db, JCR *mjcr, 
41                                char *fname, char *lname, int type,
42                                char *ap, DEV_RECORD *rec);
43 static int  create_media_record(B_DB *db, MEDIA_DBR *mr, VOLUME_LABEL *vl);
44 static bool update_media_record(B_DB *db, MEDIA_DBR *mr);
45 static int  create_pool_record(B_DB *db, POOL_DBR *pr);
46 static JCR *create_job_record(B_DB *db, JOB_DBR *mr, SESSION_LABEL *label, DEV_RECORD *rec);
47 static int  update_job_record(B_DB *db, JOB_DBR *mr, SESSION_LABEL *elabel, 
48                               DEV_RECORD *rec);
49 static int  create_client_record(B_DB *db, CLIENT_DBR *cr);
50 static int  create_fileset_record(B_DB *db, FILESET_DBR *fsr);
51 static int  create_jobmedia_record(B_DB *db, JCR *jcr);
52 static JCR *create_jcr(JOB_DBR *jr, DEV_RECORD *rec, uint32_t JobId);
53 static int update_SIG_record(B_DB *db, char *SIGbuf, DEV_RECORD *rec, int type);
54
55
56 /* Global variables */
57 STORES *me;
58 #if defined(HAVE_CYGWIN) || defined(HAVE_WIN32)
59 int win32_client = 1;
60 #else
61 int win32_client = 0;
62 #endif
63
64
65 /* Local variables */
66 static DEVICE *dev = NULL;
67 static B_DB *db;
68 static JCR *bjcr;                     /* jcr for bscan */
69 static BSR *bsr = NULL;
70 static MEDIA_DBR mr;
71 static POOL_DBR pr;
72 static JOB_DBR jr;
73 static CLIENT_DBR cr;
74 static FILESET_DBR fsr;
75 static ATTR_DBR ar;
76 static FILE_DBR fr;
77 static SESSION_LABEL label;
78 static SESSION_LABEL elabel;
79 static ATTR *attr;
80
81 static time_t lasttime = 0;
82
83 static const char *db_name = "bacula";
84 static const char *db_user = "bacula";
85 static const char *db_password = "";
86 static const char *db_host = NULL;
87 static const char *wd = NULL;
88 static bool update_db = false;
89 static bool update_vol_info = false;
90 static bool list_records = false;
91 static int ignored_msgs = 0;
92
93 static uint64_t currentVolumeSize;
94 static int64_t last_pct = -1;
95 static bool showProgress = false;
96 static int num_jobs = 0;
97 static int num_pools = 0;
98 static int num_media = 0;
99 static int num_files = 0;
100
101 #define CONFIG_FILE "bacula-sd.conf"
102 char *configfile;
103 bool forge_on = false;
104
105
106 static void usage()
107 {
108    fprintf(stderr, _(
109 "Copyright (C) 2001-2004 Kern Sibbald and John Walker.\n"
110 "\nVersion: " VERSION " (" BDATE ")\n\n"
111 "Usage: bscan [ options ] <bacula-archive>\n"
112 "       -b bootstrap      specify a bootstrap file\n"
113 "       -c <file>         specify configuration file\n"
114 "       -d <nn>           set debug level to nn\n"
115 "       -m                update media info in database\n"
116 "       -n <name>         specify the database name (default bacula)\n"
117 "       -u <user>         specify database user name (default bacula)\n"
118 "       -P <password      specify database password (default none)\n"
119 "       -h <host>         specify database host (default NULL)\n"
120 "       -p                proceed inspite of I/O errors\n"
121 "       -r                list records\n"
122 "       -s                synchronize or store in database\n"
123 "       -v                verbose\n"
124 "       -V <Volumes>      specify Volume names (separated by |)\n"
125 "       -w <dir>          specify working directory (default from conf file)\n"
126 "       -?                print this message\n\n"));
127    exit(1);
128 }
129
130 int main (int argc, char *argv[])
131 {
132    int ch;
133    struct stat stat_buf;
134    char *VolumeName = NULL;
135
136    my_name_is(argc, argv, "bscan");
137    init_msg(NULL, NULL);
138
139
140    while ((ch = getopt(argc, argv, "b:c:d:h:mn:pP:rsSu:vV:w:?")) != -1) {
141       switch (ch) {
142       case 'S' :
143          showProgress = true;
144          break;
145       case 'b':
146          bsr = parse_bsr(NULL, optarg);
147          break;
148
149       case 'c':                    /* specify config file */
150          if (configfile != NULL) {
151             free(configfile);
152          }
153          configfile = bstrdup(optarg);
154          break;
155
156       case 'd':                    /* debug level */
157          debug_level = atoi(optarg);
158          if (debug_level <= 0)
159             debug_level = 1; 
160          break;
161
162       case 'h':
163          db_host = optarg;
164          break;
165
166       case 'm':
167          update_vol_info = true;
168          break;
169
170       case 'n':
171          db_name = optarg;
172          break;
173
174       case 'u':
175          db_user = optarg;
176          break;
177
178       case 'P':
179          db_password = optarg;
180          break;
181
182       case 'p':
183          forge_on = true;
184          break;
185
186       case 'r':
187          list_records = true;
188          break;
189
190       case 's':
191          update_db = true;
192          break;
193
194       case 'v':
195          verbose++;
196          break;
197
198       case 'V':                    /* Volume name */
199          VolumeName = optarg;
200          break;
201
202       case 'w':
203          wd = optarg;
204          break;
205
206       case '?':
207       default:
208          usage();
209
210       }  
211    }
212    argc -= optind;
213    argv += optind;
214
215    if (argc != 1) {
216       Pmsg0(0, _("Wrong number of arguments: \n"));
217       usage();
218    }
219
220    if (configfile == NULL) {
221       configfile = bstrdup(CONFIG_FILE);
222    }
223
224    parse_config(configfile);
225    LockRes();
226    me = (STORES *)GetNextRes(R_STORAGE, NULL);
227    if (!me) {
228       UnlockRes();
229       Emsg1(M_ERROR_TERM, 0, _("No Storage resource defined in %s. Cannot continue.\n"), 
230          configfile);
231    }
232    UnlockRes();
233    /* Check if -w option given, otherwise use resource for working directory */
234    if (wd) { 
235       working_directory = wd;
236    } else if (!me->working_directory) {
237       Emsg1(M_ERROR_TERM, 0, _("No Working Directory defined in %s. Cannot continue.\n"),
238          configfile);
239    } else {
240       working_directory = me->working_directory;
241    }
242
243    /* Check that working directory is good */
244    if (stat(working_directory, &stat_buf) != 0) {
245       Emsg1(M_ERROR_TERM, 0, _("Working Directory: %s not found. Cannot continue.\n"),
246          working_directory);
247    }
248    if (!S_ISDIR(stat_buf.st_mode)) {
249       Emsg1(M_ERROR_TERM, 0, _("Working Directory: %s is not a directory. Cannot continue.\n"),
250          working_directory);
251    }
252
253    bjcr = setup_jcr("bscan", argv[0], bsr, VolumeName);
254    dev = setup_to_access_device(bjcr, 1);   /* read device */
255    if (!dev) { 
256       exit(1);
257    }
258    if (showProgress) {
259       struct stat sb;
260       fstat(dev->fd, &sb);
261       currentVolumeSize = sb.st_size;
262       Pmsg1(000, _("Current Volume Size = %" llu "\n"), currentVolumeSize);
263    }
264
265    if ((db=db_init_database(NULL, db_name, db_user, db_password, db_host, 0, NULL)) == NULL) {
266       Emsg0(M_ERROR_TERM, 0, _("Could not init Bacula database\n"));
267    }
268    if (!db_open_database(NULL, db)) {
269       Emsg0(M_ERROR_TERM, 0, db_strerror(db));
270    }
271    Dmsg0(200, "Database opened\n");
272    if (verbose) {
273       Pmsg2(000, _("Using Database: %s, User: %s\n"), db_name, db_user);
274    }
275
276    do_scan();
277    printf("Records %sadded to catalog:\n%7d Media\n%7d Pool\n%7d Job\n%7d File\n",
278       update_db?"":"would have been ",
279       num_media, num_pools, num_jobs, num_files);
280
281    free_jcr(bjcr);
282    term_dev(dev);
283    return 0;
284 }
285   
286 /*  
287  * We are at the end of reading a tape. Now, we simulate handling
288  *   the end of writing a tape by wiffling through the attached
289  *   jcrs creating jobmedia records.
290  */
291 static bool bscan_mount_next_read_volume(JCR *jcr, DEVICE *dev, DEV_BLOCK *block)
292 {
293    Dmsg1(100, "Walk attached jcrs. Volume=%s\n", dev->VolCatInfo.VolCatName);
294    DCR *dcr;
295    foreach_dlist(dcr, dev->attached_dcrs) {
296       JCR *mjcr = dcr->jcr;
297       if (mjcr->JobId == 0) {
298          continue;
299       }
300       if (verbose) {
301          Pmsg1(000, _("Create JobMedia for Job %s\n"), mjcr->Job);
302       }
303       if (dev->state & ST_TAPE) {
304          dcr->EndBlock = dev->EndBlock;
305          dcr->EndFile = dev->EndFile;
306       } else {
307          dcr->EndBlock = (uint32_t)dev->file_addr;
308          dcr->EndFile = (uint32_t)(dev->file_addr >> 32);
309       }
310       if (!create_jobmedia_record(db, mjcr)) {
311          Pmsg2(000, _("Could not create JobMedia record for Volume=%s Job=%s\n"),
312             dev->VolCatInfo.VolCatName, mjcr->Job);
313       }
314    }  
315    /* Now let common read routine get up next tape. Note,
316     * we call mount_next... with bscan's jcr because that is where we
317     * have the Volume list, but we get attached.
318     */
319    bool stat = mount_next_read_volume(jcr, dev, block);
320
321    if (showProgress) {
322       struct stat sb;
323       fstat(dev->fd, &sb);
324       currentVolumeSize = sb.st_size;
325       Pmsg1(000, _("Current Volume Size = %" llu "\n"), currentVolumeSize);
326    }
327    return stat;
328 }
329
330 static void do_scan()             
331 {
332    attr = new_attr();
333
334    memset(&ar, 0, sizeof(ar));
335    memset(&pr, 0, sizeof(pr));
336    memset(&jr, 0, sizeof(jr));
337    memset(&cr, 0, sizeof(cr));
338    memset(&fsr, 0, sizeof(fsr));
339    memset(&fr, 0, sizeof(fr));
340
341    /* Detach bscan's jcr as we are not a real Job on the tape */
342
343    read_records(bjcr->dcr, record_cb, bscan_mount_next_read_volume);
344 // release_device(bjcr);
345
346    free_attr(attr);
347 }
348
349 /*
350  * Returns: true  if OK
351  *          false if error
352  */
353 static bool record_cb(JCR *bjcr, DEVICE *dev, DEV_BLOCK *block, DEV_RECORD *rec)
354 {
355    JCR *mjcr;
356    DCR *dcr;
357    char ec1[30];
358
359    if (rec->data_len > 0) {
360       mr.VolBytes += rec->data_len + WRITE_RECHDR_LENGTH; /* Accumulate Volume bytes */
361       if (showProgress) {
362          int64_t pct = (mr.VolBytes * 100) / currentVolumeSize;
363          if (pct != last_pct) {
364             fprintf(stdout, "done: %" lld "\n", pct);
365             fflush(stdout);
366             last_pct = pct;
367          }
368       }
369    }
370    
371    if (list_records) {
372       Pmsg5(000, _("Record: SessId=%u SessTim=%u FileIndex=%d Stream=%d len=%u\n"),
373             rec->VolSessionId, rec->VolSessionTime, rec->FileIndex, 
374             rec->Stream, rec->data_len);
375    }
376    /* 
377     * Check for Start or End of Session Record 
378     *
379     */
380    if (rec->FileIndex < 0) {
381       bool save_update_db = update_db;
382
383       if (verbose > 1) {
384          dump_label_record(dev, rec, 1);
385       }
386       switch (rec->FileIndex) {
387       case PRE_LABEL:
388          Pmsg0(000, _("Volume is prelabeled. This tape cannot be scanned.\n"));
389          return false;
390          break;
391
392       case VOL_LABEL:
393          unser_volume_label(dev, rec);
394          /* Check Pool info */
395          bstrncpy(pr.Name, dev->VolHdr.PoolName, sizeof(pr.Name));
396          bstrncpy(pr.PoolType, dev->VolHdr.PoolType, sizeof(pr.PoolType));
397          num_pools++;
398          if (db_get_pool_record(bjcr, db, &pr)) {
399             if (verbose) {
400                Pmsg1(000, _("Pool record for %s found in DB.\n"), pr.Name);
401             }
402          } else {
403             if (!update_db) {
404                Pmsg1(000, _("VOL_LABEL: Pool record not found for Pool: %s\n"),
405                   pr.Name);
406             }
407             create_pool_record(db, &pr);
408          }
409          if (strcmp(pr.PoolType, dev->VolHdr.PoolType) != 0) {
410             Pmsg2(000, _("VOL_LABEL: PoolType mismatch. DB=%s Vol=%s\n"),
411                pr.PoolType, dev->VolHdr.PoolType);
412             return true;
413          } else if (verbose) {
414             Pmsg1(000, _("Pool type \"%s\" is OK.\n"), pr.PoolType);
415          }
416
417          /* Check Media Info */
418          memset(&mr, 0, sizeof(mr));
419          bstrncpy(mr.VolumeName, dev->VolHdr.VolName, sizeof(mr.VolumeName));
420          mr.PoolId = pr.PoolId;
421          num_media++;
422          if (db_get_media_record(bjcr, db, &mr)) {
423             if (verbose) {
424                Pmsg1(000, _("Media record for %s found in DB.\n"), mr.VolumeName);
425             }
426             /* Clear out some volume statistics that will be updated */
427             mr.VolJobs = mr.VolFiles = mr.VolBlocks = 0;
428             mr.VolBytes = rec->data_len + 20;
429          } else {
430             if (!update_db) {
431                Pmsg1(000, _("VOL_LABEL: Media record not found for Volume: %s\n"),
432                   mr.VolumeName);
433             }
434             bstrncpy(mr.MediaType, dev->VolHdr.MediaType, sizeof(mr.MediaType));
435             create_media_record(db, &mr, &dev->VolHdr);
436          }
437          if (strcmp(mr.MediaType, dev->VolHdr.MediaType) != 0) {
438             Pmsg2(000, _("VOL_LABEL: MediaType mismatch. DB=%s Vol=%s\n"),
439                mr.MediaType, dev->VolHdr.MediaType);
440             return true;              /* ignore error */
441          } else if (verbose) {
442             Pmsg1(000, _("Media type \"%s\" is OK.\n"), mr.MediaType);
443          }
444          /* Reset some JCR variables */
445          foreach_dlist(dcr, dev->attached_dcrs) {
446             dcr->VolFirstIndex = dcr->FileIndex = 0;
447             dcr->StartBlock = dcr->EndBlock = 0;
448             dcr->StartFile = dcr->EndFile = 0;
449          }
450
451          Pmsg1(000, _("VOL_LABEL: OK for Volume: %s\n"), mr.VolumeName);
452          break;
453
454       case SOS_LABEL:
455          mr.VolJobs++;
456          num_jobs++;
457          if (ignored_msgs > 0) {
458             Pmsg1(000, _("%d \"errors\" ignored before first Start of Session record.\n"), 
459                   ignored_msgs);
460             ignored_msgs = 0;
461          }
462          unser_session_label(&label, rec);
463          memset(&jr, 0, sizeof(jr));
464          bstrncpy(jr.Job, label.Job, sizeof(jr.Job));
465          if (db_get_job_record(bjcr, db, &jr)) {
466             /* Job record already exists in DB */
467             update_db = false;  /* don't change db in create_job_record */
468             if (verbose) {
469                Pmsg1(000, _("SOS_LABEL: Found Job record for JobId: %d\n"), jr.JobId);
470             }
471          } else {
472             /* Must create a Job record in DB */
473             if (!update_db) {
474                Pmsg1(000, _("SOS_LABEL: Job record not found for JobId: %d\n"),
475                   jr.JobId);
476             }
477          }
478          /* Create Client record if not already there */
479             bstrncpy(cr.Name, label.ClientName, sizeof(cr.Name));
480             create_client_record(db, &cr);
481             jr.ClientId = cr.ClientId;
482
483          /* process label, if Job record exists don't update db */
484          mjcr = create_job_record(db, &jr, &label, rec);
485          dcr = mjcr->dcr;
486          update_db = save_update_db;
487
488          jr.PoolId = pr.PoolId;
489          /* Set start positions into JCR */
490          if (dev->state & ST_TAPE) {
491             /*
492              * Note, we have already advanced past current block,
493              *  so the correct number is block_num - 1 
494              */ 
495             dcr->StartBlock = dev->block_num - 1;
496             dcr->StartFile = dev->file;
497          } else {
498             dcr->StartBlock = (uint32_t)dev->file_addr;
499             dcr->StartFile = (uint32_t)(dev->file_addr >> 32);
500          }
501          mjcr->start_time = jr.StartTime;
502          mjcr->JobLevel = jr.JobLevel;
503
504          mjcr->client_name = get_pool_memory(PM_FNAME);
505          pm_strcpy(&mjcr->client_name, label.ClientName);
506          mjcr->pool_type = get_pool_memory(PM_FNAME);
507          pm_strcpy(&mjcr->pool_type, label.PoolType);
508          mjcr->fileset_name = get_pool_memory(PM_FNAME);
509          pm_strcpy(&mjcr->fileset_name, label.FileSetName);
510          mjcr->pool_name = get_pool_memory(PM_FNAME);
511          pm_strcpy(&mjcr->pool_name, label.PoolName);
512
513          if (rec->VolSessionId != jr.VolSessionId) {
514             Pmsg3(000, _("SOS_LABEL: VolSessId mismatch for JobId=%u. DB=%d Vol=%d\n"),
515                jr.JobId,
516                jr.VolSessionId, rec->VolSessionId);
517             return true;              /* ignore error */
518          }
519          if (rec->VolSessionTime != jr.VolSessionTime) {
520             Pmsg3(000, _("SOS_LABEL: VolSessTime mismatch for JobId=%u. DB=%d Vol=%d\n"),
521                jr.JobId,
522                jr.VolSessionTime, rec->VolSessionTime);
523             return true;              /* ignore error */
524          }
525          if (jr.PoolId != pr.PoolId) {
526             Pmsg3(000, _("SOS_LABEL: PoolId mismatch for JobId=%u. DB=%d Vol=%d\n"),
527                jr.JobId,
528                jr.PoolId, pr.PoolId);
529             return true;              /* ignore error */
530          }
531          break;
532
533       case EOS_LABEL:
534          unser_session_label(&elabel, rec);
535
536          /* Create FileSet record */
537          bstrncpy(fsr.FileSet, label.FileSetName, sizeof(fsr.FileSet));
538          bstrncpy(fsr.MD5, label.FileSetMD5, sizeof(fsr.MD5));
539          create_fileset_record(db, &fsr);
540          jr.FileSetId = fsr.FileSetId;
541
542          mjcr = get_jcr_by_session(rec->VolSessionId, rec->VolSessionTime);
543          if (!mjcr) {
544             Pmsg2(000, _("Could not find SessId=%d SessTime=%d for EOS record.\n"),
545                   rec->VolSessionId, rec->VolSessionTime);
546             break;
547          }
548
549          /* Do the final update to the Job record */
550          update_job_record(db, &jr, &elabel, rec);
551
552          mjcr->end_time = jr.EndTime;
553          mjcr->JobStatus = JS_Terminated;
554
555          /* Create JobMedia record */
556          create_jobmedia_record(db, mjcr);
557          dev->attached_dcrs->remove(mjcr->dcr);
558          free_jcr(mjcr);
559
560          break;
561
562       case EOM_LABEL:
563          break;
564
565       case EOT_LABEL:              /* end of all tapes */
566          /* 
567           * Wiffle through all jobs still open and close
568           *   them.
569           */
570          if (update_db) {
571             DCR *mdcr;
572             foreach_dlist(mdcr, dev->attached_dcrs) {
573                JCR *mjcr = mdcr->jcr;
574                if (!mjcr || mjcr->JobId == 0) {
575                   continue;
576                }
577                jr.JobId = mjcr->JobId;
578                /* Mark Job as Error Terimined */
579                jr.JobStatus = JS_ErrorTerminated;
580                jr.JobFiles = mjcr->JobFiles;
581                jr.JobBytes = mjcr->JobBytes;
582                jr.VolSessionId = mjcr->VolSessionId;
583                jr.VolSessionTime = mjcr->VolSessionTime;
584                jr.JobTDate = (utime_t)mjcr->start_time;
585                jr.ClientId = mjcr->ClientId;
586                if (!db_update_job_end_record(bjcr, db, &jr)) {
587                   Pmsg1(0, _("Could not update job record. ERR=%s\n"), db_strerror(db));
588                }
589                mjcr->dcr = NULL;
590                free_jcr(mjcr);
591             }
592          }
593          mr.VolFiles = rec->File;
594          mr.VolBlocks = rec->Block;
595          mr.VolBytes += mr.VolBlocks * WRITE_BLKHDR_LENGTH; /* approx. */
596          mr.VolMounts++;
597          update_media_record(db, &mr);
598          Pmsg3(0, _("End of all Volumes. VolFiles=%u VolBlocks=%u VolBytes=%s\n"), mr.VolFiles,
599                     mr.VolBlocks, edit_uint64_with_commas(mr.VolBytes, ec1));
600          break;
601       default:
602          break;
603       } /* end switch */
604       return true;
605    }
606
607    mjcr = get_jcr_by_session(rec->VolSessionId, rec->VolSessionTime);
608    if (!mjcr) {
609       if (mr.VolJobs > 0) {
610          Pmsg2(000, _("Could not find Job for SessId=%d SessTime=%d record.\n"),
611                       rec->VolSessionId, rec->VolSessionTime);
612       } else {
613          ignored_msgs++;
614       }
615       return true;
616    }
617    dcr = mjcr->dcr;
618    if (dcr->VolFirstIndex == 0) {
619       dcr->VolFirstIndex = block->FirstIndex;
620    }
621
622    /* File Attributes stream */
623    switch (rec->Stream) {
624    case STREAM_UNIX_ATTRIBUTES:   
625    case STREAM_UNIX_ATTRIBUTES_EX:  
626
627       if (!unpack_attributes_record(bjcr, rec->Stream, rec->data, attr)) {
628          Emsg0(M_ERROR_TERM, 0, _("Cannot continue.\n"));
629       }
630
631       if (attr->file_index != rec->FileIndex) {
632          Emsg2(M_ERROR_TERM, 0, _("Record header file index %ld not equal record index %ld\n"),
633             rec->FileIndex, attr->file_index);
634       }
635        
636       if (verbose > 1) {
637          decode_stat(attr->attr, &attr->statp, &attr->LinkFI);
638          build_attr_output_fnames(bjcr, attr);
639          print_ls_output(bjcr, attr);
640       }
641       fr.JobId = mjcr->JobId;
642       fr.FileId = 0;
643       num_files++;
644       if (verbose && (num_files & 0x7FFF) == 0) {
645          char ed1[30], ed2[30], ed3[30], ed4[30];
646          Pmsg4(000, _("%s file records. At file:blk=%s:%s bytes=%s\n"),
647                      edit_uint64_with_commas(num_files, ed1),
648                      edit_uint64_with_commas(rec->File, ed2),
649                      edit_uint64_with_commas(rec->Block, ed3),
650                      edit_uint64_with_commas(mr.VolBytes, ed4));
651       } 
652       create_file_attributes_record(db, mjcr, attr->fname, attr->lname, 
653             attr->type, attr->attr, rec);
654       free_jcr(mjcr);
655       break;
656
657    /* Data stream */
658    case STREAM_WIN32_DATA:
659    case STREAM_FILE_DATA:
660    case STREAM_SPARSE_DATA:
661       mjcr->JobBytes += rec->data_len;
662       if (rec->Stream == STREAM_SPARSE_DATA) {
663          mjcr->JobBytes -= sizeof(uint64_t);
664       }
665          
666       free_jcr(mjcr);                 /* done using JCR */
667       break;
668
669    case STREAM_GZIP_DATA:
670       mjcr->JobBytes += rec->data_len; /* No correct, we should expand it */
671       free_jcr(mjcr);                 /* done using JCR */
672       break;
673
674    case STREAM_SPARSE_GZIP_DATA:
675       mjcr->JobBytes += rec->data_len - sizeof(uint64_t); /* No correct, we should expand it */
676       free_jcr(mjcr);                 /* done using JCR */
677       break;
678
679    /* Win32 GZIP stream */
680    case STREAM_WIN32_GZIP_DATA:
681       mjcr->JobBytes += rec->data_len;
682       free_jcr(mjcr);                 /* done using JCR */
683       break;
684
685    case STREAM_MD5_SIGNATURE:
686       char MD5buf[50];
687       bin_to_base64(MD5buf, (char *)rec->data, 16); /* encode 16 bytes */
688       if (verbose > 1) {
689          Pmsg1(000, _("Got MD5 record: %s\n"), MD5buf);
690       }
691       update_SIG_record(db, MD5buf, rec, MD5_SIG);
692       break;
693
694    case STREAM_SHA1_SIGNATURE:
695       char SIGbuf[50];
696       bin_to_base64(SIGbuf, (char *)rec->data, 20); /* encode 20 bytes */
697       if (verbose > 1) {
698          Pmsg1(000, _("Got SHA1 record: %s\n"), SIGbuf);
699       }
700       update_SIG_record(db, SIGbuf, rec, SHA1_SIG);
701       break;
702
703
704    case STREAM_PROGRAM_NAMES:
705       if (verbose) {
706          Pmsg1(000, _("Got Prog Names Stream: %s\n"), rec->data);
707       }
708       break;
709
710    case STREAM_PROGRAM_DATA:
711       if (verbose > 1) {
712          Pmsg0(000, _("Got Prog Data Stream record.\n"));
713       }
714       break;
715    default:
716       Pmsg2(0, _("Unknown stream type!!! stream=%d data=%s\n"), rec->Stream, rec->data);
717       break;
718    }
719    return true;
720 }
721
722 /*
723  * Free the Job Control Record if no one is still using it.
724  *  Called from main free_jcr() routine in src/lib/jcr.c so
725  *  that we can do our Director specific cleanup of the jcr.
726  */
727 static void bscan_free_jcr(JCR *jcr)
728 {
729    Dmsg0(200, "Start dird free_jcr\n");
730
731    if (jcr->file_bsock) {
732       Dmsg0(200, "Close File bsock\n");
733       bnet_close(jcr->file_bsock);
734    }
735    if (jcr->store_bsock) {
736       Dmsg0(200, "Close Store bsock\n");
737       bnet_close(jcr->store_bsock);
738    }
739    if (jcr->RestoreBootstrap) {
740       free(jcr->RestoreBootstrap);
741    }
742    if (jcr->dcr) {
743       free_dcr(jcr->dcr);
744       jcr->dcr = NULL;
745    }
746    Dmsg0(200, "End dird free_jcr\n");
747 }
748
749 /*
750  * We got a File Attributes record on the tape.  Now, lookup the Job
751  *   record, and then create the attributes record.
752  */
753 static int create_file_attributes_record(B_DB *db, JCR *mjcr,
754                                char *fname, char *lname, int type,
755                                char *ap, DEV_RECORD *rec)
756 {
757    DCR *dcr = mjcr->dcr;
758    ar.fname = fname;
759    ar.link = lname;
760    ar.ClientId = mjcr->ClientId;
761    ar.JobId = mjcr->JobId;
762    ar.Stream = rec->Stream;
763    ar.FileIndex = rec->FileIndex;
764    ar.attr = ap;
765    if (dcr->VolFirstIndex == 0) {
766       dcr->VolFirstIndex = rec->FileIndex;
767    }
768    dcr->FileIndex = rec->FileIndex;
769    mjcr->JobFiles++;
770
771    if (!update_db) {
772       return 1;
773    }
774
775    if (!db_create_file_attributes_record(bjcr, db, &ar)) {
776       Pmsg1(0, _("Could not create File Attributes record. ERR=%s\n"), db_strerror(db));
777       return 0;
778    }
779    mjcr->FileId = ar.FileId;
780
781    if (verbose > 1) {
782       Pmsg1(000, _("Created File record: %s\n"), fname);   
783    }
784    return 1;
785 }
786
787 /*
788  * For each Volume we see, we create a Medium record
789  */
790 static int create_media_record(B_DB *db, MEDIA_DBR *mr, VOLUME_LABEL *vl)
791 {
792    struct date_time dt;
793    struct tm tm;
794
795    /* We mark Vols as Archive to keep them from being re-written */
796    bstrncpy(mr->VolStatus, "Archive", sizeof(mr->VolStatus));
797    mr->VolRetention = 365 * 3600 * 24; /* 1 year */
798    if (vl->VerNum >= 11) {
799       mr->FirstWritten = btime_to_utime(vl->write_btime);
800       mr->LabelDate    = btime_to_utime(vl->label_btime);
801    } else {
802       /* DEPRECATED DO NOT USE */
803       dt.julian_day_number = vl->write_date;
804       dt.julian_day_fraction = vl->write_time;
805       tm_decode(&dt, &tm);
806       mr->FirstWritten = mktime(&tm);
807       dt.julian_day_number = vl->label_date;
808       dt.julian_day_fraction = vl->label_time;
809       tm_decode(&dt, &tm);
810       mr->LabelDate = mktime(&tm);
811    }
812    lasttime = mr->LabelDate;
813
814    if (!update_db) {
815       return 1;
816    }
817
818    if (!db_create_media_record(bjcr, db, mr)) {
819       Pmsg1(0, _("Could not create media record. ERR=%s\n"), db_strerror(db));
820       return 0;
821    }
822    if (!db_update_media_record(bjcr, db, mr)) {
823       Pmsg1(0, _("Could not update media record. ERR=%s\n"), db_strerror(db));
824       return 0;
825    }
826    if (verbose) {
827       Pmsg1(000, _("Created Media record for Volume: %s\n"), mr->VolumeName);
828    }
829    return 1;
830
831 }
832
833 /*
834  * Called at end of media to update it
835  */
836 static bool update_media_record(B_DB *db, MEDIA_DBR *mr)
837 {
838    if (!update_db && !update_vol_info) {
839       return true;
840    }
841
842    mr->LastWritten = lasttime;
843    if (!db_update_media_record(bjcr, db, mr)) {
844       Pmsg1(0, _("Could not update media record. ERR=%s\n"), db_strerror(db));
845       return false;;
846    }
847    if (verbose) {
848       Pmsg1(000, _("Updated Media record at end of Volume: %s\n"), mr->VolumeName);
849    }
850    return true;
851
852 }
853
854
855 static int create_pool_record(B_DB *db, POOL_DBR *pr)
856 {
857    pr->NumVols++;
858    pr->UseCatalog = 1;
859    pr->VolRetention = 355 * 3600 * 24; /* 1 year */
860
861    if (!update_db) {
862       return 1;
863    }
864    if (!db_create_pool_record(bjcr, db, pr)) {
865       Pmsg1(0, _("Could not create pool record. ERR=%s\n"), db_strerror(db));
866       return 0;
867    }
868    if (verbose) {
869       Pmsg1(000, _("Created Pool record for Pool: %s\n"), pr->Name);
870    }
871    return 1;
872
873 }
874
875
876 /*
877  * Called from SOS to create a client for the current Job 
878  */
879 static int create_client_record(B_DB *db, CLIENT_DBR *cr)
880 {
881    if (!update_db) {
882       return 1;
883    }
884    if (!db_create_client_record(bjcr, db, cr)) {
885       Pmsg1(0, _("Could not create Client record. ERR=%s\n"), db_strerror(db));
886       return 0;
887    }
888    if (verbose) {
889       Pmsg1(000, _("Created Client record for Client: %s\n"), cr->Name);
890    }
891    return 1;
892 }
893
894 static int create_fileset_record(B_DB *db, FILESET_DBR *fsr)
895 {
896    if (!update_db) {
897       return 1;
898    }
899    fsr->FileSetId = 0;
900    if (fsr->MD5[0] == 0) {
901       fsr->MD5[0] = ' ';              /* Equivalent to nothing */
902       fsr->MD5[1] = 0;
903    }
904    if (db_get_fileset_record(bjcr, db, fsr)) {
905       if (verbose) {
906          Pmsg1(000, _("Fileset \"%s\" already exists.\n"), fsr->FileSet);
907       }
908    } else {
909       if (!db_create_fileset_record(bjcr, db, fsr)) {
910          Pmsg2(0, _("Could not create FileSet record \"%s\". ERR=%s\n"), 
911             fsr->FileSet, db_strerror(db));
912          return 0;
913       }
914       if (verbose) {
915          Pmsg1(000, _("Created FileSet record \"%s\"\n"), fsr->FileSet);
916       }
917    }
918    return 1;
919 }
920
921 /*
922  * Simulate the two calls on the database to create
923  *  the Job record and to update it when the Job actually
924  *  begins running.
925  */
926 static JCR *create_job_record(B_DB *db, JOB_DBR *jr, SESSION_LABEL *label, 
927                              DEV_RECORD *rec)
928 {
929    JCR *mjcr;
930    struct date_time dt;
931    struct tm tm;
932
933    jr->JobId = label->JobId;
934    jr->JobType = label->JobType;
935    jr->JobLevel = label->JobLevel;
936    jr->JobStatus = JS_Created;
937    bstrncpy(jr->Name, label->JobName, sizeof(jr->Name));
938    bstrncpy(jr->Job, label->Job, sizeof(jr->Job));
939    if (label->VerNum >= 11) {
940       jr->SchedTime = btime_to_unix(label->write_btime);
941    } else {
942       dt.julian_day_number = label->write_date;
943       dt.julian_day_fraction = label->write_time;
944       tm_decode(&dt, &tm);
945       jr->SchedTime = mktime(&tm);
946    }
947
948    jr->StartTime = jr->SchedTime;
949    jr->JobTDate = (utime_t)jr->SchedTime;
950    jr->VolSessionId = rec->VolSessionId;
951    jr->VolSessionTime = rec->VolSessionTime;
952
953    /* Now create a JCR as if starting the Job */
954    mjcr = create_jcr(jr, rec, label->JobId);
955
956    if (!update_db) {
957       return mjcr;
958    }
959
960    /* This creates the bare essentials */
961    if (!db_create_job_record(bjcr, db, jr)) {
962       Pmsg1(0, _("Could not create JobId record. ERR=%s\n"), db_strerror(db));
963       return mjcr;
964    }
965
966    /* This adds the client, StartTime, JobTDate, ... */
967    if (!db_update_job_start_record(bjcr, db, jr)) {
968       Pmsg1(0, _("Could not update job start record. ERR=%s\n"), db_strerror(db));
969       return mjcr;
970    }
971    Pmsg2(000, _("Created new JobId=%u record for original JobId=%u\n"), jr->JobId, 
972          label->JobId);
973    mjcr->JobId = jr->JobId;           /* set new JobId */
974    return mjcr;
975 }
976
977 /* 
978  * Simulate the database call that updates the Job 
979  *  at Job termination time.
980  */
981 static int update_job_record(B_DB *db, JOB_DBR *jr, SESSION_LABEL *elabel,
982                               DEV_RECORD *rec)
983 {
984    struct date_time dt;
985    struct tm tm;
986    JCR *mjcr;
987
988    mjcr = get_jcr_by_session(rec->VolSessionId, rec->VolSessionTime);
989    if (!mjcr) {
990       Pmsg2(000, _("Could not find SessId=%d SessTime=%d for EOS record.\n"),
991                    rec->VolSessionId, rec->VolSessionTime);
992       return 0;
993    }
994    if (elabel->VerNum >= 11) {
995       jr->EndTime = btime_to_unix(elabel->write_btime);
996    } else {
997       dt.julian_day_number = elabel->write_date;
998       dt.julian_day_fraction = elabel->write_time;
999       tm_decode(&dt, &tm);
1000       jr->EndTime = mktime(&tm);
1001    }
1002    lasttime = jr->EndTime;
1003    mjcr->end_time = jr->EndTime;
1004
1005    jr->JobId = mjcr->JobId;
1006    jr->JobStatus = elabel->JobStatus;
1007    mjcr->JobStatus = elabel->JobStatus;
1008    jr->JobFiles = elabel->JobFiles;
1009    jr->JobBytes = elabel->JobBytes;
1010    jr->VolSessionId = rec->VolSessionId;
1011    jr->VolSessionTime = rec->VolSessionTime;
1012    jr->JobTDate = (utime_t)mjcr->start_time;
1013    jr->ClientId = mjcr->ClientId;
1014
1015    if (!update_db) {
1016       free_jcr(mjcr);
1017       return 1;
1018    }
1019    
1020    if (!db_update_job_end_record(bjcr, db, jr)) {
1021       Pmsg2(0, _("Could not update JobId=%u record. ERR=%s\n"), jr->JobId,  db_strerror(db));
1022       free_jcr(mjcr);
1023       return 0;
1024    }
1025    if (verbose) {
1026       Pmsg2(000, _("Updated Job termination record for JobId=%u TermStat=%c\n"), jr->JobId,
1027          jr->JobStatus);
1028    }
1029    if (verbose > 1) {
1030       const char *term_msg;
1031       static char term_code[70];
1032       char sdt[50], edt[50];
1033       char ec1[30], ec2[30], ec3[30];
1034
1035       switch (mjcr->JobStatus) {
1036       case JS_Terminated:
1037          term_msg = _("Backup OK");
1038          break;
1039       case JS_FatalError:
1040       case JS_ErrorTerminated:
1041          term_msg = _("*** Backup Error ***");
1042          break;
1043       case JS_Canceled:
1044          term_msg = _("Backup Canceled");
1045          break;
1046       default:
1047          term_msg = term_code;
1048          sprintf(term_code, _("Job Termination code: %d"), mjcr->JobStatus);
1049          break;
1050       }
1051       bstrftime(sdt, sizeof(sdt), mjcr->start_time);
1052       bstrftime(edt, sizeof(edt), mjcr->end_time);
1053       Pmsg14(000,  _("%s\n\
1054 JobId:                  %d\n\
1055 Job:                    %s\n\
1056 FileSet:                %s\n\
1057 Backup Level:           %s\n\
1058 Client:                 %s\n\
1059 Start time:             %s\n\
1060 End time:               %s\n\
1061 Files Written:          %s\n\
1062 Bytes Written:          %s\n\
1063 Volume Session Id:      %d\n\
1064 Volume Session Time:    %d\n\
1065 Last Volume Bytes:      %s\n\
1066 Termination:            %s\n\n"),
1067         edt,
1068         mjcr->JobId,
1069         mjcr->Job,
1070         mjcr->fileset_name,
1071         job_level_to_str(mjcr->JobLevel),
1072         mjcr->client_name,
1073         sdt,
1074         edt,
1075         edit_uint64_with_commas(mjcr->JobFiles, ec1),
1076         edit_uint64_with_commas(mjcr->JobBytes, ec2),
1077         mjcr->VolSessionId,
1078         mjcr->VolSessionTime,
1079         edit_uint64_with_commas(mr.VolBytes, ec3),
1080         term_msg);
1081    }
1082    free_jcr(mjcr);
1083    return 1;
1084 }
1085
1086 static int create_jobmedia_record(B_DB *db, JCR *mjcr)
1087 {
1088    JOBMEDIA_DBR jmr;
1089    DCR *dcr = mjcr->dcr;
1090
1091    if (dev->state & ST_TAPE) {
1092       dcr->EndBlock = dev->EndBlock;
1093       dcr->EndFile  = dev->EndFile;
1094    } else {
1095       dcr->EndBlock = (uint32_t)dev->file_addr;
1096       dcr->EndFile = (uint32_t)(dev->file_addr >> 32);
1097    }
1098
1099    memset(&jmr, 0, sizeof(jmr));
1100    jmr.JobId = mjcr->JobId;
1101    jmr.MediaId = mr.MediaId;
1102    jmr.FirstIndex = dcr->VolFirstIndex;
1103    jmr.LastIndex = dcr->FileIndex;
1104    jmr.StartFile = dcr->StartFile;
1105    jmr.EndFile = dcr->EndFile;
1106    jmr.StartBlock = dcr->StartBlock;
1107    jmr.EndBlock = dcr->EndBlock;
1108
1109
1110    if (!update_db) {
1111       return 1;
1112    }
1113
1114    if (!db_create_jobmedia_record(bjcr, db, &jmr)) {
1115       Pmsg1(0, _("Could not create JobMedia record. ERR=%s\n"), db_strerror(db));
1116       return 0;
1117    }
1118    if (verbose) {
1119       Pmsg2(000, _("Created JobMedia record JobId %d, MediaId %d\n"), 
1120                 jmr.JobId, jmr.MediaId);
1121    }
1122    return 1;
1123 }
1124
1125 /* 
1126  * Simulate the database call that updates the MD5/SHA1 record
1127  */
1128 static int update_SIG_record(B_DB *db, char *SIGbuf, DEV_RECORD *rec, int type)
1129 {
1130    JCR *mjcr;
1131
1132    mjcr = get_jcr_by_session(rec->VolSessionId, rec->VolSessionTime);
1133    if (!mjcr) {
1134       if (mr.VolJobs > 0) {
1135          Pmsg2(000, _("Could not find SessId=%d SessTime=%d for MD5/SHA1 record.\n"),
1136                       rec->VolSessionId, rec->VolSessionTime);
1137       } else {
1138          ignored_msgs++;
1139       }
1140       return 0;
1141    }
1142
1143    if (!update_db || mjcr->FileId == 0) {
1144       free_jcr(mjcr);
1145       return 1;
1146    }
1147    
1148    if (!db_add_SIG_to_file_record(bjcr, db, mjcr->FileId, SIGbuf, type)) {
1149       Pmsg1(0, _("Could not add MD5/SHA1 to File record. ERR=%s\n"), db_strerror(db));
1150       free_jcr(mjcr);
1151       return 0;
1152    }
1153    if (verbose > 1) {
1154       Pmsg0(000, _("Updated MD5/SHA1 record\n"));
1155    }
1156    free_jcr(mjcr);
1157    return 1;
1158 }
1159
1160
1161 /* 
1162  * Create a JCR as if we are really starting the job
1163  */
1164 static JCR *create_jcr(JOB_DBR *jr, DEV_RECORD *rec, uint32_t JobId)
1165 {
1166    JCR *jobjcr;
1167    /*
1168     * Transfer as much as possible to the Job JCR. Most important is
1169     *   the JobId and the ClientId.
1170     */
1171    jobjcr = new_jcr(sizeof(JCR), bscan_free_jcr);
1172    jobjcr->JobType = jr->JobType;
1173    jobjcr->JobLevel = jr->JobLevel;
1174    jobjcr->JobStatus = jr->JobStatus;
1175    bstrncpy(jobjcr->Job, jr->Job, sizeof(jobjcr->Job));
1176    jobjcr->JobId = JobId;      /* this is JobId on tape */
1177    jobjcr->sched_time = jr->SchedTime;
1178    jobjcr->start_time = jr->StartTime;
1179    jobjcr->VolSessionId = rec->VolSessionId;
1180    jobjcr->VolSessionTime = rec->VolSessionTime;
1181    jobjcr->ClientId = jr->ClientId;
1182 // attach_jcr_to_device(dev, jobjcr);
1183    new_dcr(jobjcr, dev);
1184    return jobjcr;
1185 }
1186
1187 /* Dummies to replace askdir.c */
1188 bool    dir_get_volume_info(DCR *dcr, enum get_vol_info_rw  writing) { return 1;}
1189 bool    dir_find_next_appendable_volume(DCR *dcr) { return 1;}
1190 bool    dir_update_volume_info(DCR *dcr, bool relabel) { return 1; }
1191 bool    dir_create_jobmedia_record(DCR *dcr) { return 1; }
1192 bool    dir_ask_sysop_to_create_appendable_volume(DCR *dcr) { return 1; }
1193 bool    dir_update_file_attributes(DCR *dcr, DEV_RECORD *rec) { return 1;}
1194 bool    dir_send_job_status(JCR *jcr) {return 1;}
1195
1196
1197 bool dir_ask_sysop_to_mount_volume(DCR *dcr)
1198 {
1199    DEVICE *dev = dcr->dev;
1200    JCR *jcr = dcr->jcr;
1201    fprintf(stderr, _("Mount Volume \"%s\" on device \"%s\" and press return when ready: "),
1202       jcr->VolumeName, dev_name(dev));
1203    getchar();   
1204    return 1;
1205 }