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