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