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