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