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