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