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