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