/
backup.cc
1232 lines (1098 loc) · 37.8 KB
/
backup.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
BAREOS® - Backup Archiving REcovery Open Sourced
Copyright (C) 2000-2012 Free Software Foundation Europe e.V.
Copyright (C) 2011-2016 Planets Communications B.V.
Copyright (C) 2013-2018 Bareos GmbH & Co. KG
This program is Free Software; you can redistribute it and/or
modify it under the terms of version three of the GNU Affero General Public
License as published by the Free Software Foundation and included
in the file LICENSE.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
/*
* Kern Sibbald, March MM
*/
/**
* @file
* responsible for doing backup jobs
*
* Basic tasks done here:
* Open DB and create records for this job.
* Open Message Channel with Storage daemon to tell him a job will be starting.
* Open connection with File daemon and pass him commands to do the backup.
* When the File daemon finishes the job, update the DB.
*/
#include "include/bareos.h"
#include "dird.h"
#include "dird/backup.h"
#include "dird/fd_cmds.h"
#include "dird/getmsg.h"
#include "dird/inc_conf.h"
#include "dird/job.h"
#include "dird/msgchan.h"
#include "dird/quota.h"
#include "dird/sd_cmds.h"
#include "dird/storage.h"
#include "cats/sql.h"
#include "lib/bnet.h"
#include "lib/edit.h"
/* Commands sent to File daemon */
static char backupcmd[] =
"backup FileIndex=%ld\n";
static char storaddrcmd[] =
"storage address=%s port=%d ssl=%d\n";
static char passiveclientcmd[] =
"passive client address=%s port=%d ssl=%d\n";
/* Responses received from File daemon */
static char OKbackup[] =
"2000 OK backup\n";
static char OKstore[] =
"2000 OK storage\n";
static char OKpassiveclient[] =
"2000 OK passive client\n";
static char EndJob[] =
"2800 End Job TermCode=%d JobFiles=%u "
"ReadBytes=%llu JobBytes=%llu Errors=%u "
"VSS=%d Encrypt=%d\n";
static inline bool ValidateClient(JobControlRecord *jcr)
{
switch (jcr->res.client->Protocol) {
case APT_NATIVE:
return true;
default:
Jmsg(jcr, M_FATAL, 0, _("Client %s has illegal backup protocol %s for Native backup\n"),
jcr->res.client->name(), auth_protocol_to_str(jcr->res.client->Protocol));
return false;
}
}
/**
* if both FD and SD have LanAddress set, use the storages' LanAddress to connect to.
*/
char* StorageAddressToContact(ClientResource *client, StorageResource *store)
{
if (store->lanaddress && client->lanaddress) {
return store->lanaddress;
} else {
return store->address;
}
}
/**
* if both FD and SD have LanAddress set, use the clients' LanAddress to connect to.
*
*/
char* ClientAddressToContact(ClientResource *client, StorageResource *store)
{
if (store->lanaddress && client->lanaddress) {
return client->lanaddress;
} else {
return client->address;
}
}
/**
* if both readstorage and writestorage have LanAddress set,
* use wstores' LanAddress to connect to.
*
*/
char* StorageAddressToContact(StorageResource *rstore, StorageResource *wstore)
{
if (rstore->lanaddress && wstore->lanaddress) {
return wstore->lanaddress;
} else {
return wstore->address;
}
}
static inline bool ValidateStorage(JobControlRecord *jcr)
{
StorageResource *store;
foreach_alist(store, jcr->res.wstorage) {
switch (store->Protocol) {
case APT_NATIVE:
continue;
default:
Jmsg(jcr, M_FATAL, 0, _("Storage %s has illegal backup protocol %s for Native backup\n"),
store->name(), auth_protocol_to_str(store->Protocol));
return false;
}
}
return true;
}
/*
* Called here before the job is run to do the job specific setup.
*/
bool DoNativeBackupInit(JobControlRecord *jcr)
{
FreeRstorage(jcr); /* we don't read so release */
if (!AllowDuplicateJob(jcr)) {
return false;
}
jcr->jr.PoolId = GetOrCreatePoolRecord(jcr, jcr->res.pool->name());
if (jcr->jr.PoolId == 0) {
return false;
}
/*
* If pool storage specified, use it instead of job storage
*/
CopyWstorage(jcr, jcr->res.pool->storage, _("Pool resource"));
if (!jcr->res.wstorage) {
Jmsg(jcr, M_FATAL, 0, _("No Storage specification found in Job or Pool.\n"));
return false;
}
/*
* Validate that we have a native client and storage(s).
*/
if (!ValidateClient(jcr) || !ValidateStorage(jcr)) {
return false;
}
CreateClones(jcr); /* run any clone jobs */
return true;
}
/*
* Take all base jobs from job resource and find the last L_BASE jobid.
*/
static bool GetBaseJobids(JobControlRecord *jcr, db_list_ctx *jobids)
{
JobDbRecord jr;
JobResource *job;
JobId_t id;
char str_jobid[50];
if (!jcr->res.job->base) {
return false; /* no base job, stop accurate */
}
memset(&jr, 0, sizeof(jr));
jr.StartTime = jcr->jr.StartTime;
foreach_alist(job, jcr->res.job->base) {
bstrncpy(jr.Name, job->name(), sizeof(jr.Name));
jcr->db->GetBaseJobid(jcr, &jr, &id);
if (id) {
if (jobids->count) {
PmStrcat(jobids->list, ",");
}
PmStrcat(jobids->list, edit_uint64(id, str_jobid));
jobids->count++;
}
}
return jobids->count > 0;
}
/*
* Foreach files in currrent list, send "/path/fname\0LStat\0MD5\0Delta" to FD
* row[0]=Path, row[1]=Filename, row[2]=FileIndex
* row[3]=JobId row[4]=LStat row[5]=DeltaSeq row[6]=MD5
*/
static int AccurateListHandler(void *ctx, int num_fields, char **row)
{
JobControlRecord *jcr = (JobControlRecord *)ctx;
if (JobControlRecord::JobCanceled(jcr)) {
return 1;
}
if (row[2][0] == '0') { /* discard when file_index == 0 */
return 0;
}
/* sending with checksum */
if (jcr->use_accurate_chksum &&
num_fields == 9 &&
row[6][0] && /* skip checksum = '0' */
row[6][1]) {
jcr->file_bsock->fsend("%s%s%c%s%c%s%c%s",
row[0], row[1], 0, row[4], 0, row[6], 0, row[5]);
} else {
jcr->file_bsock->fsend("%s%s%c%s%c%c%s",
row[0], row[1], 0, row[4], 0, 0, row[5]);
}
return 0;
}
/* In this procedure, we check if the current fileset is using checksum
* FileSet-> Include-> Options-> Accurate/Verify/BaseJob=checksum
* This procedure uses jcr->HasBase, so it must be call after the initialization
*/
static bool IsChecksumNeededByFileset(JobControlRecord *jcr)
{
IncludeExcludeItem *inc;
FileOptions *fopts;
FilesetResource *fs;
bool in_block=false;
bool have_basejob_option=false;
if (!jcr->res.job || !jcr->res.job->fileset) {
return false;
}
fs = jcr->res.job->fileset;
for (int i = 0; i < fs->num_includes; i++) { /* Parse all Include {} */
inc = fs->include_items[i];
for (int j = 0; j < inc->num_opts; j++) { /* Parse all Options {} */
fopts = inc->opts_list[j];
for (char *k = fopts->opts; *k; k++) { /* Try to find one request */
switch (*k) {
case 'V': /* verify */
in_block = jcr->is_JobType(JT_VERIFY); /* not used now */
break;
case 'J': /* Basejob keyword */
have_basejob_option = in_block = jcr->HasBase;
break;
case 'C': /* Accurate keyword */
in_block = !jcr->is_JobLevel(L_FULL);
break;
case ':': /* End of keyword */
in_block = false;
break;
case '5': /* MD5 */
case '1': /* SHA1 */
if (in_block) {
Dmsg0(50, "Checksum will be sent to FD\n");
return true;
}
break;
default:
break;
}
}
}
}
/* By default for BaseJobs, we send the checksum */
if (!have_basejob_option && jcr->HasBase) {
return true;
}
Dmsg0(50, "Checksum will be sent to FD\n");
return false;
}
/*
* Send current file list to FD
* DIR -> FD : accurate files=xxxx
* DIR -> FD : /path/to/file\0Lstat\0MD5\0Delta
* DIR -> FD : /path/to/dir/\0Lstat\0MD5\0Delta
* ...
* DIR -> FD : EOD
*/
bool SendAccurateCurrentFiles(JobControlRecord *jcr)
{
PoolMem buf;
db_list_ctx jobids;
db_list_ctx nb;
/*
* In base level, no previous job is used and no restart incomplete jobs
*/
if (jcr->IsCanceled() || jcr->is_JobLevel(L_BASE)) {
return true;
}
if (!jcr->accurate) {
return true;
}
if (jcr->is_JobLevel(L_FULL)) {
/*
* On Full mode, if no previous base job, no accurate things
*/
if (GetBaseJobids(jcr, &jobids)) {
jcr->HasBase = true;
Jmsg(jcr, M_INFO, 0, _("Using BaseJobId(s): %s\n"), jobids.list);
} else {
return true;
}
} else {
/*
* For Incr/Diff level, we search for older jobs
*/
jcr->db->AccurateGetJobids(jcr, &jcr->jr, &jobids);
/*
* We are in Incr/Diff, but no Full to build the accurate list...
*/
if (jobids.count == 0) {
Jmsg(jcr, M_FATAL, 0, _("Cannot find previous jobids.\n"));
return false; /* fail */
}
}
/*
* Don't send and store the checksum if fileset doesn't require it
*/
jcr->use_accurate_chksum = IsChecksumNeededByFileset(jcr);
if (jcr->JobId) { /* display the message only for real jobs */
Jmsg(jcr, M_INFO, 0, _("Sending Accurate information.\n"));
}
/*
* To be able to allocate the right size for htable
*/
Mmsg(buf, "SELECT sum(JobFiles) FROM Job WHERE JobId IN (%s)", jobids.list);
jcr->db->SqlQuery(buf.c_str(), DbListHandler, &nb);
Dmsg2(200, "jobids=%s nb=%s\n", jobids.list, nb.list);
jcr->file_bsock->fsend("accurate files=%s\n", nb.list);
if (jcr->HasBase) {
jcr->nb_base_files = str_to_int64(nb.list);
if (!jcr->db->CreateBaseFileList(jcr, jobids.list)){
Jmsg(jcr, M_FATAL, 0, "error in jcr->db->CreateBaseFileList:%s\n"
,jcr->db->strerror());
return false;
}
if (!jcr->db->GetBaseFileList(jcr, jcr->use_accurate_chksum,
AccurateListHandler, (void *)jcr)) {
Jmsg(jcr, M_FATAL, 0, "error in jcr->db->GetBaseFileList:%s\n"
,jcr->db->strerror());
return false;
}
} else {
if (!jcr->db->OpenBatchConnection(jcr)) {
Jmsg0(jcr, M_FATAL, 0, "Can't get batch sql connection");
return false; /* Fail */
}
jcr->db_batch->GetFileList(jcr, jobids.list, jcr->use_accurate_chksum,
false /* no delta */, AccurateListHandler, (void *)jcr);
}
jcr->file_bsock->signal(BNET_EOD);
return true;
}
/*
* Do a backup of the specified FileSet
*
* Returns: false on failure
* true on success
*/
bool DoNativeBackup(JobControlRecord *jcr)
{
int status;
uint32_t tls_need = 0;
BareosSocket *fd = NULL;
BareosSocket *sd = NULL;
StorageResource *store = NULL;
ClientResource *client = NULL;
char ed1[100];
db_int64_ctx job;
PoolMem buf;
/* Print Job Start message */
Jmsg(jcr, M_INFO, 0, _("Start Backup JobId %s, Job=%s\n"),
edit_uint64(jcr->JobId, ed1), jcr->Job);
jcr->setJobStatus(JS_Running);
Dmsg2(100, "JobId=%d JobLevel=%c\n", jcr->jr.JobId, jcr->jr.JobLevel);
if (!jcr->db->UpdateJobStartRecord(jcr, &jcr->jr)) {
Jmsg(jcr, M_FATAL, 0, "%s", jcr->db->strerror());
return false;
}
if (CheckHardquotas(jcr)) {
Jmsg(jcr, M_FATAL, 0, _("Quota Exceeded. Job terminated.\n"));
return false;
}
if (CheckSoftquotas(jcr)) {
Dmsg0(10, "Quota exceeded\n");
Jmsg(jcr, M_FATAL, 0, _("Soft Quota exceeded / Grace Time expired. Job terminated.\n"));
return false;
}
/*
* Open a message channel connection with the Storage
* daemon. This is to let him know that our client
* will be contacting him for a backup session.
*/
Dmsg0(110, "Open connection with storage daemon\n");
jcr->setJobStatus(JS_WaitSD);
/*
* Start conversation with Storage daemon
*/
if (!ConnectToStorageDaemon(jcr, 10, me->SDConnectTimeout, true)) {
return false;
}
sd = jcr->store_bsock;
/*
* Now start a job with the Storage daemon
*/
if (!StartStorageDaemonJob(jcr, NULL, jcr->res.wstorage)) {
return false;
}
/*
* When the client is not in passive mode we can put the SD in
* listen mode for the FD connection.
*/
jcr->passive_client = jcr->res.client->passive;
if (!jcr->passive_client) {
/*
* Start the job prior to starting the message thread below
* to avoid two threads from using the BareosSocket structure at
* the same time.
*/
if (!sd->fsend("run")) {
return false;
}
/*
* Now start a Storage daemon message thread. Note,
* this thread is used to provide the catalog services
* for the backup job, including inserting the attributes
* into the catalog. See CatalogUpdate() in catreq.c
*/
if (!StartStorageDaemonMessageThread(jcr)) {
return false;
}
Dmsg0(150, "Storage daemon connection OK\n");
}
jcr->setJobStatus(JS_WaitFD);
if (!ConnectToFileDaemon(jcr, 10, me->FDConnectTimeout, true)) {
goto bail_out;
}
Dmsg1(120, "jobid: %d: connected\n", jcr->JobId);
SendJobInfo(jcr);
fd = jcr->file_bsock;
/*
* Check if the file daemon supports passive client mode.
*/
if (jcr->passive_client && jcr->FDVersion < FD_VERSION_51) {
Jmsg(jcr, M_FATAL, 0,
_("Client \"%s\" doesn't support passive client mode. "
"Please upgrade your client or disable compat mode.\n"),
jcr->res.client->name());
goto close_fd;
}
jcr->setJobStatus(JS_Running);
if (!SendLevelCommand(jcr)) {
goto bail_out;
}
if (!SendIncludeList(jcr)) {
goto bail_out;
}
if (!SendExcludeList(jcr)) {
goto bail_out;
}
if (!SendPreviousRestoreObjects(jcr)) {
goto bail_out;
}
if (!SendSecureEraseReqToFd(jcr)) {
Dmsg1(500,"Unexpected %s secure erase\n","client");
}
if (jcr->res.job->max_bandwidth > 0) {
jcr->max_bandwidth = jcr->res.job->max_bandwidth;
} else if (jcr->res.client->max_bandwidth > 0) {
jcr->max_bandwidth = jcr->res.client->max_bandwidth;
}
if (jcr->max_bandwidth > 0) {
SendBwlimitToFd(jcr, jcr->Job); /* Old clients don't have this command */
}
client = jcr->res.client;
store = jcr->res.wstore;
char *connection_target_address;
/*
* See if the client is a passive client or not.
*/
if (!jcr->passive_client) {
/*
* Send Storage daemon address to the File daemon
*/
if (store->SDDport == 0) {
store->SDDport = store->SDport;
}
/*
* TLS Requirement
*/
tls_need = GetNeedFromConfiguration(client);
connection_target_address = StorageAddressToContact(client, store);
fd->fsend(storaddrcmd, connection_target_address, store->SDDport, tls_need);
if (!response(jcr, fd, OKstore, "Storage", DISPLAY_ERROR)) {
goto bail_out;
}
} else {
/*
* TLS Requirement
*/
tls_need = GetNeedFromConfiguration(me);
connection_target_address = ClientAddressToContact(client, store);
/*
* Tell the SD to connect to the FD.
*/
sd->fsend(passiveclientcmd, connection_target_address, client->FDport, tls_need);
if (!response(jcr, sd, OKpassiveclient, "Passive client", DISPLAY_ERROR)) {
goto bail_out;
}
/*
* Start the job prior to starting the message thread below
* to avoid two threads from using the BareosSocket structure at
* the same time.
*/
if (!jcr->store_bsock->fsend("run")) {
return false;
}
/*
* Now start a Storage daemon message thread. Note,
* this thread is used to provide the catalog services
* for the backup job, including inserting the attributes
* into the catalog. See CatalogUpdate() in catreq.c
*/
if (!StartStorageDaemonMessageThread(jcr)) {
return false;
}
Dmsg0(150, "Storage daemon connection OK\n");
}
/*
* Declare the job started to start the MaxRunTime check
*/
jcr->setJobStarted();
/*
* Send and run the RunBefore
*/
if (!SendRunscriptsCommands(jcr)) {
goto bail_out;
}
/*
* We re-update the job start record so that the start
* time is set after the run before job. This avoids
* that any files created by the run before job will
* be saved twice. They will be backed up in the current
* job, but not in the next one unless they are changed.
* Without this, they will be backed up in this job and
* in the next job run because in that case, their date
* is after the start of this run.
*/
jcr->start_time = time(NULL);
jcr->jr.StartTime = jcr->start_time;
if (!jcr->db->UpdateJobStartRecord(jcr, &jcr->jr)) {
Jmsg(jcr, M_FATAL, 0, "%s", jcr->db->strerror());
}
/*
* If backup is in accurate mode, we send the list of
* all files to FD.
*/
if (!SendAccurateCurrentFiles(jcr)) {
goto bail_out; /* error */
}
/*
* Send backup command
*/
fd->fsend(backupcmd, jcr->JobFiles);
Dmsg1(100, ">filed: %s", fd->msg);
if (!response(jcr, fd, OKbackup, "Backup", DISPLAY_ERROR)) {
goto bail_out;
}
/*
* Pickup Job termination data
*/
status = WaitForJobTermination(jcr);
jcr->db_batch->WriteBatchFileRecords(jcr); /* used by bulk batch file insert */
if (jcr->HasBase && !jcr->db->CommitBaseFileAttributesRecord(jcr)) {
Jmsg(jcr, M_FATAL, 0, "%s", jcr->db->strerror());
}
/*
* Check softquotas after job did run.
* If quota is exceeded now, set the GraceTime.
*/
CheckSoftquotas(jcr);
if (status == JS_Terminated) {
NativeBackupCleanup(jcr, status);
return true;
}
return false;
close_fd:
if (jcr->file_bsock) {
jcr->file_bsock->signal(BNET_TERMINATE);
jcr->file_bsock->close();
delete jcr->file_bsock;
jcr->file_bsock = NULL;
}
bail_out:
jcr->setJobStatus(JS_ErrorTerminated);
WaitForJobTermination(jcr, me->FDConnectTimeout);
return false;
}
/*
* Here we wait for the File daemon to signal termination,
* then we wait for the Storage daemon. When both are done,
* we return the job status.
*
* Also used by restore.c
*/
int WaitForJobTermination(JobControlRecord *jcr, int timeout)
{
int32_t n = 0;
BareosSocket *fd = jcr->file_bsock;
bool fd_ok = false;
uint32_t JobFiles, JobErrors;
uint32_t JobWarnings = 0;
uint64_t ReadBytes = 0;
uint64_t JobBytes = 0;
int VSS = 0;
int Encrypt = 0;
btimer_t *tid=NULL;
jcr->setJobStatus(JS_Running);
if (fd) {
if (timeout) {
tid = StartBsockTimer(fd, timeout); /* TODO: New timeout directive??? */
}
/*
* Wait for Client to terminate
*/
while ((n = BgetDirmsg(fd)) >= 0) {
if (!fd_ok &&
sscanf(fd->msg, EndJob, &jcr->FDJobStatus, &JobFiles,
&ReadBytes, &JobBytes, &JobErrors, &VSS, &Encrypt) == 7) {
fd_ok = true;
jcr->setJobStatus(jcr->FDJobStatus);
Dmsg1(100, "FDStatus=%c\n", (char)jcr->JobStatus);
} else {
Jmsg(jcr, M_WARNING, 0, _("Unexpected Client Job message: %s\n"),
fd->msg);
}
if (JobControlRecord::JobCanceled(jcr)) {
break;
}
}
if (tid) {
StopBsockTimer(tid);
}
if (IsBnetError(fd)) {
int i = 0;
Jmsg(jcr, M_FATAL, 0, _("Network error with FD during %s: ERR=%s\n"),
job_type_to_str(jcr->getJobType()), fd->bstrerror());
while (i++ < 10 && jcr->res.job->RescheduleIncompleteJobs && jcr->IsCanceled()) {
Bmicrosleep(3, 0);
}
}
fd->signal(BNET_TERMINATE); /* tell Client we are terminating */
}
/*
* Force cancel in SD if failing, but not for Incomplete jobs so that we let the SD despool.
*/
Dmsg5(100, "cancel=%d fd_ok=%d FDJS=%d JS=%d SDJS=%d\n", jcr->IsCanceled(), fd_ok, jcr->FDJobStatus,
jcr->JobStatus, jcr->SDJobStatus);
if (jcr->IsCanceled() || (!jcr->res.job->RescheduleIncompleteJobs && !fd_ok)) {
Dmsg4(100, "fd_ok=%d FDJS=%d JS=%d SDJS=%d\n", fd_ok, jcr->FDJobStatus,
jcr->JobStatus, jcr->SDJobStatus);
CancelStorageDaemonJob(jcr);
}
/*
* Note, the SD stores in jcr->JobFiles/ReadBytes/JobBytes/JobErrors
*/
WaitForStorageDaemonTermination(jcr);
/*
* Return values from FD
*/
if (fd_ok) {
jcr->JobFiles = JobFiles;
jcr->JobErrors += JobErrors; /* Keep total errors */
jcr->ReadBytes = ReadBytes;
jcr->JobBytes = JobBytes;
jcr->JobWarnings = JobWarnings;
jcr->VSS = VSS;
jcr->Encrypt = Encrypt;
} else {
Jmsg(jcr, M_FATAL, 0, _("No Job status returned from FD.\n"));
}
// Dmsg4(100, "fd_ok=%d FDJS=%d JS=%d SDJS=%d\n", fd_ok, jcr->FDJobStatus,
// jcr->JobStatus, jcr->SDJobStatus);
/*
* Return the first error status we find Dir, FD, or SD
*/
if (!fd_ok || IsBnetError(fd)) { /* if fd not set, that use !fd_ok */
jcr->FDJobStatus = JS_ErrorTerminated;
}
if (jcr->JobStatus != JS_Terminated) {
return jcr->JobStatus;
}
if (jcr->FDJobStatus != JS_Terminated) {
return jcr->FDJobStatus;
}
return jcr->SDJobStatus;
}
/*
* Release resources allocated during backup.
*/
void NativeBackupCleanup(JobControlRecord *jcr, int TermCode)
{
const char *TermMsg;
char term_code[100];
int msg_type = M_INFO;
ClientDbRecord cr;
Dmsg2(100, "Enter backup_cleanup %d %c\n", TermCode, TermCode);
memset(&cr, 0, sizeof(cr));
if (jcr->is_JobStatus(JS_Terminated) &&
(jcr->JobErrors || jcr->SDErrors || jcr->JobWarnings)) {
TermCode = JS_Warnings;
}
UpdateJobEnd(jcr, TermCode);
if (!jcr->db->GetJobRecord(jcr, &jcr->jr)) {
Jmsg(jcr, M_WARNING, 0, _("Error getting Job record for Job report: ERR=%s"), jcr->db->strerror());
jcr->setJobStatus(JS_ErrorTerminated);
}
bstrncpy(cr.Name, jcr->res.client->name(), sizeof(cr.Name));
if (!jcr->db->GetClientRecord(jcr, &cr)) {
Jmsg(jcr, M_WARNING, 0, _("Error getting Client record for Job report: ERR=%s"), jcr->db->strerror());
}
UpdateBootstrapFile(jcr);
switch (jcr->JobStatus) {
case JS_Terminated:
TermMsg = _("Backup OK");
break;
case JS_Incomplete:
TermMsg = _("Backup failed -- incomplete");
break;
case JS_Warnings:
TermMsg = _("Backup OK -- with warnings");
break;
case JS_FatalError:
case JS_ErrorTerminated:
TermMsg = _("*** Backup Error ***");
msg_type = M_ERROR; /* Generate error message */
if (jcr->store_bsock) {
jcr->store_bsock->signal(BNET_TERMINATE);
if (jcr->SD_msg_chan_started) {
pthread_cancel(jcr->SD_msg_chan);
}
}
break;
case JS_Canceled:
TermMsg = _("Backup Canceled");
if (jcr->store_bsock) {
jcr->store_bsock->signal(BNET_TERMINATE);
if (jcr->SD_msg_chan_started) {
pthread_cancel(jcr->SD_msg_chan);
}
}
break;
default:
TermMsg = term_code;
sprintf(term_code, _("Inappropriate term code: %c\n"), jcr->JobStatus);
break;
}
GenerateBackupSummary(jcr, &cr, msg_type, TermMsg);
Dmsg0(100, "Leave backup_cleanup()\n");
}
void UpdateBootstrapFile(JobControlRecord *jcr)
{
/*
* Now update the bootstrap file if any
*/
if (jcr->JobTerminatedSuccessfully() &&
jcr->jr.JobBytes &&
jcr->res.job->WriteBootstrap) {
FILE *fd;
int VolCount;
int got_pipe = 0;
Bpipe *bpipe = NULL;
VolumeParameters *VolParams = NULL;
char edt[50], ed1[50], ed2[50];
POOLMEM *fname = GetPoolMemory(PM_FNAME);
fname = edit_job_codes(jcr, fname, jcr->res.job->WriteBootstrap, "");
if (*fname == '|') {
got_pipe = 1;
bpipe = OpenBpipe(fname+1, 0, "w"); /* skip first char "|" */
fd = bpipe ? bpipe->wfd : NULL;
} else {
/* ***FIXME*** handle BASE */
fd = fopen(fname, jcr->is_JobLevel(L_FULL)?"w+b":"a+b");
}
if (fd) {
VolCount = jcr->db->GetJobVolumeParameters(jcr, jcr->JobId, &VolParams);
if (VolCount == 0) {
Jmsg(jcr, M_ERROR, 0, _("Could not get Job Volume Parameters to "
"update Bootstrap file. ERR=%s\n"), jcr->db->strerror());
if (jcr->SDJobFiles != 0) {
jcr->setJobStatus(JS_ErrorTerminated);
}
}
/* Start output with when and who wrote it */
bstrftimes(edt, sizeof(edt), time(NULL));
fprintf(fd, "# %s - %s - %s%s\n", edt, jcr->jr.Job,
level_to_str(jcr->getJobLevel()), jcr->since);
for (int i=0; i < VolCount; i++) {
/* Write the record */
fprintf(fd, "Volume=\"%s\"\n", VolParams[i].VolumeName);
fprintf(fd, "MediaType=\"%s\"\n", VolParams[i].MediaType);
if (VolParams[i].Slot > 0) {
fprintf(fd, "Slot=%d\n", VolParams[i].Slot);
}
fprintf(fd, "VolSessionId=%u\n", jcr->VolSessionId);
fprintf(fd, "VolSessionTime=%u\n", jcr->VolSessionTime);
fprintf(fd, "VolAddr=%s-%s\n",
edit_uint64(VolParams[i].StartAddr, ed1),
edit_uint64(VolParams[i].EndAddr, ed2));
fprintf(fd, "FileIndex=%d-%d\n", VolParams[i].FirstIndex,
VolParams[i].LastIndex);
}
if (VolParams) {
free(VolParams);
}
if (got_pipe) {
CloseBpipe(bpipe);
} else {
fclose(fd);
}
} else {
BErrNo be;
Jmsg(jcr, M_ERROR, 0, _("Could not open WriteBootstrap file:\n"
"%s: ERR=%s\n"), fname, be.bstrerror());
jcr->setJobStatus(JS_ErrorTerminated);
}
FreePoolMemory(fname);
}
}
/*
* Generic function which generates a backup summary message.
* Used by:
* - NativeBackupCleanup e.g. normal backups
* - NativeVbackupCleanup e.g. virtual backups
* - NdmpBackupCleanup e.g. NDMP backups
*/
void GenerateBackupSummary(JobControlRecord *jcr, ClientDbRecord *cr, int msg_type, const char *TermMsg)
{
char sdt[50], edt[50], schedt[50], gdt[50];
char ec1[30], ec2[30], ec3[30], ec4[30], ec5[30], compress[50];
char ec6[30], ec7[30], ec8[30], elapsed[50];
char fd_term_msg[100], sd_term_msg[100];
double kbps, compression;
utime_t RunTime;
MediaDbRecord mr;
PoolMem temp,
level_info,
statistics,
quota_info,
client_options,
daemon_status,
secure_erase_status,
compress_algo_list;
memset(&mr, 0, sizeof(mr));
bstrftimes(schedt, sizeof(schedt), jcr->jr.SchedTime);
bstrftimes(sdt, sizeof(sdt), jcr->jr.StartTime);
bstrftimes(edt, sizeof(edt), jcr->jr.EndTime);
RunTime = jcr->jr.EndTime - jcr->jr.StartTime;
bstrftimes(gdt, sizeof(gdt),
jcr->res.client->GraceTime +
jcr->res.client->SoftQuotaGracePeriod);
if (RunTime <= 0) {
kbps = 0;
} else {
kbps = ((double)jcr->jr.JobBytes) / (1000.0 * (double)RunTime);
}
if (!jcr->db->GetJobVolumeNames(jcr, jcr->jr.JobId, jcr->VolumeName)) {
/*
* Note, if the job has erred, most likely it did not write any
* tape, so suppress this "error" message since in that case
* it is normal. Or look at it the other way, only for a
* normal exit should we complain about this error.
*/
if (jcr->JobTerminatedSuccessfully() && jcr->jr.JobBytes) {
Jmsg(jcr, M_ERROR, 0, "%s", jcr->db->strerror());
}
jcr->VolumeName[0] = 0; /* none */
}
if (jcr->VolumeName[0]) {
/*
* Find last volume name. Multiple vols are separated by |
*/
char *p = strrchr(jcr->VolumeName, '|');