-
-
Notifications
You must be signed in to change notification settings - Fork 206
/
DatabaseSnapshot.cpp
1292 lines (1089 loc) · 33.1 KB
/
DatabaseSnapshot.cpp
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
/*
* The contents of this file are subject to the Initial
* Developer's Public License Version 1.0 (the "License");
* you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
* http://www.ibphoenix.com/main.nfs?a=ibphoenix&page=ibp_idpl.
*
* Software distributed under the License is distributed AS IS,
* WITHOUT WARRANTY OF ANY KIND, either express or implied.
* See the License for the specific language governing rights
* and limitations under the License.
*
* The Original Code was created by Dmitry Yemanov
* for the Firebird Open Source RDBMS project.
*
* Copyright (c) 2006 Dmitry Yemanov <dimitr@users.sf.net>
* and all contributors signed below.
*
* All Rights Reserved.
* Contributor(s): ______________________________________.
*/
#include "firebird.h"
#include "ids.h"
#include "../common/classes/auto.h"
#include "../common/classes/locks.h"
#include "../jrd/gdsassert.h"
#include "../jrd/jrd.h"
#include "../jrd/cch.h"
#include "../jrd/ini.h"
#include "../jrd/nbak.h"
#include "../jrd/os/guid.h"
#include "../jrd/os/pio.h"
#include "../jrd/req.h"
#include "../jrd/tra.h"
#include "../jrd/blb_proto.h"
#include "../jrd/isc_proto.h"
#include "../jrd/isc_s_proto.h"
#include "../jrd/lck_proto.h"
#include "../jrd/met_proto.h"
#include "../jrd/os/pio_proto.h"
#include "../jrd/pag_proto.h"
#include "../jrd/thread_proto.h"
#include "../jrd/Relation.h"
#include "../jrd/RecordBuffer.h"
#include "../jrd/DatabaseSnapshot.h"
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef UNIX
#include <signal.h>
#endif
#ifdef WIN_NT
#include <process.h>
#include <windows.h>
#endif
using namespace Firebird;
using namespace Jrd;
const UCHAR TAG_DBB = '\xFF'; //-1U
const UCHAR TAG_RECORD = '\xFE'; //-2U;
// SharedMemory class
const size_t DatabaseSnapshot::SharedMemory::VERSION = 1;
const size_t DatabaseSnapshot::SharedMemory::DEFAULT_SIZE = 1048576;
DatabaseSnapshot::SharedMemory::SharedMemory()
{
TEXT filename[MAXPATHLEN];
gds__prefix_lock(filename, MONITOR_FILE);
ISC_STATUS_ARRAY statusVector;
base = (Header*) ISC_map_file(statusVector,
filename,
init, this,
DEFAULT_SIZE,
&handle);
if (!base)
{
gds__log("Cannot initialize the shared memory region");
status_exception::raise(statusVector);
}
fb_assert(base->version == VERSION);
}
DatabaseSnapshot::SharedMemory::~SharedMemory()
{
ISC_STATUS_ARRAY statusVector;
ISC_unmap_file(statusVector, &handle, 0);
}
void DatabaseSnapshot::SharedMemory::acquire()
{
#ifdef WIN_NT
checkMutex("lock", ISC_mutex_lock(&mutex));
#else
checkMutex("lock", ISC_mutex_lock(&base->mutex));
#endif
if (base->allocated > handle.sh_mem_length_mapped)
{
#if (defined HAVE_MMAP || defined WIN_NT)
const size_t newSize = base->allocated;
ISC_STATUS_ARRAY statusVector;
base = (Header*) ISC_remap_file(statusVector, &handle, newSize, FALSE);
if (!base)
{
Firebird::status_exception::raise(statusVector);
}
#else
Firebird::status_exception::raise(isc_random, isc_arg_string,
"Monitoring table space exhausted",
0);
#endif
}
}
void DatabaseSnapshot::SharedMemory::release()
{
#ifdef WIN_NT
checkMutex("unlock", ISC_mutex_unlock(&mutex));
#else
checkMutex("unlock", ISC_mutex_unlock(&base->mutex));
#endif
}
ClumpletReader* DatabaseSnapshot::SharedMemory::readData(thread_db* tdbb)
{
garbageCollect(tdbb, false);
const UCHAR* const buffer = (UCHAR*) base + sizeof(Header);
const size_t length = base->used;
MemoryPool& pool = *tdbb->getDefaultPool();
ClumpletReader* reader = FB_NEW(pool)
ClumpletReader(pool, ClumpletReader::WideUnTagged, buffer, length);
return reader;
}
void DatabaseSnapshot::SharedMemory::writeData(thread_db* tdbb, ClumpletWriter& writer)
{
garbageCollect(tdbb, true);
// Get number of bytes to add
const size_t length = writer.getBufferLength();
// Do we need to extend the allocated memory?
while (base->used + length > base->allocated)
{
extend();
}
// Get the remapped pointer
UCHAR* buffer = (UCHAR*) base + sizeof(Header);
// Copy the data at the insertion point
memcpy(buffer + base->used, writer.getBuffer(), length);
// Adjust the length
base->used += length;
}
void DatabaseSnapshot::SharedMemory::garbageCollect(thread_db* tdbb, bool self)
{
fb_assert(tdbb);
Database* dbb = tdbb->getDatabase();
fb_assert(dbb);
// Get the buffer length
UCHAR* buffer = (UCHAR*) base + sizeof(Header);
const size_t length = base->used;
if (!length)
{
// No data means no garbage to collect
return;
}
// Initialize reader and writer helpers
ClumpletReader reader(ClumpletReader::WideUnTagged, buffer, length);
ClumpletWriter writer(ClumpletReader::WideUnTagged, MAX_ULONG);
// Temporary lock used to check existence of the given dbb instance
AutoPtr<Lock> temp_lock(FB_NEW_RPT(*tdbb->getDefaultPool(), sizeof(FB_GUID)) Lock());
temp_lock->lck_type = LCK_instance;
temp_lock->lck_owner_handle =
LCK_get_owner_handle(tdbb, temp_lock->lck_type);
temp_lock->lck_length = sizeof(FB_GUID);
temp_lock->lck_dbb = dbb;
// Parse the data and remove all garbage clumplets
bool garbage_collect = false;
while (!reader.isEof())
{
if (reader.getClumpTag() == TAG_DBB)
{
FB_GUID guid;
fb_assert(reader.getClumpLength() == sizeof(FB_GUID));
memcpy(&guid, reader.getBytes(), sizeof(FB_GUID));
// Is this our own dbb instance?
const bool our_dbb =
!memcmp(&guid, &dbb->dbb_guid, sizeof(FB_GUID));
if (self)
{
// We're asked to garbage collect our own data only
garbage_collect = our_dbb;
}
else if (our_dbb)
{
// We're a generic reader and this is our dbb clumplet.
// Don't garbage collect as we're definitely alive.
garbage_collect = false;
}
else
{
ISC_STATUS_ARRAY temp_status;
ISC_STATUS* const org_status = tdbb->tdbb_status_vector;
tdbb->tdbb_status_vector = temp_status;
memcpy(temp_lock->lck_key.lck_string, &guid, sizeof(FB_GUID));
if (LCK_lock(tdbb, temp_lock, LCK_EX, LCK_NO_WAIT))
{
// This clumplet identifies the instance already died.
// Garbage collect this unneccessary crap.
LCK_release(tdbb, temp_lock);
garbage_collect = true;
}
else
{
// This clumplet identifies the instance still alive.
// Don't remove its data.
garbage_collect = false;
}
tdbb->tdbb_status_vector = org_status;
}
}
// Copy data if we shouldn't garbage collect this clumplet
if (!garbage_collect)
{
writer.insertBytes(reader.getClumpTag(),
reader.getBytes(),
reader.getClumpLength());
}
reader.moveNext();
}
// If we have compacted the data, let's adjust the stored length
const size_t newLength = writer.getBufferLength();
if (newLength < base->used)
{
memcpy(buffer, writer.getBuffer(), newLength);
base->used = newLength;
}
}
void DatabaseSnapshot::SharedMemory::extend()
{
const size_t newSize = handle.sh_mem_length_mapped + DEFAULT_SIZE;
#if (defined HAVE_MMAP || defined WIN_NT)
ISC_STATUS_ARRAY statusVector;
base = (Header*) ISC_remap_file(statusVector, &handle, newSize, TRUE);
if (!base)
{
Firebird::status_exception::raise(statusVector);
}
base->allocated = handle.sh_mem_length_mapped;
#else
Firebird::status_exception::raise(isc_random, isc_arg_string,
"Monitoring table space exhausted",
0);
#endif
}
void DatabaseSnapshot::SharedMemory::checkMutex(const TEXT* string, int state)
{
if (state)
{
TEXT msg[BUFFER_TINY];
sprintf(msg, "MONITOR: mutex %s error, status = %d", string, state);
gds__log(msg);
fprintf(stderr, "%s\n", msg);
exit(FINI_ERROR);
}
}
void DatabaseSnapshot::SharedMemory::init(void* arg, SH_MEM_T* shmemData, bool initialize)
{
SharedMemory* shmem = (SharedMemory*) arg;
fb_assert(shmem);
#ifdef WIN_NT
char buffer[MAXPATHLEN];
gds__prefix_lock(buffer, MONITOR_FILE);
checkMutex("init", ISC_mutex_init(&shmem->mutex, buffer));
#endif
if (!initialize)
return;
// Initialize the shared data header
Header* header = (Header*) shmemData->sh_mem_address;
header->version = VERSION;
header->used = 0;
header->allocated = 0;
#ifndef WIN_NT
checkMutex("init", ISC_mutex_init(&header->mutex));
#endif
}
// DatabaseSnapshot class
GlobalPtr<Mutex> DatabaseSnapshot::initMutex;
DatabaseSnapshot::SharedMemory* DatabaseSnapshot::dump = NULL;
int DatabaseSnapshot::pid = getpid();
DatabaseSnapshot* DatabaseSnapshot::create(thread_db* tdbb)
{
SET_TDBB(tdbb);
jrd_tra* transaction = tdbb->getTransaction();
fb_assert(transaction);
if (!transaction->tra_db_snapshot)
{
// Create a database snapshot and store it
// in the transaction block
MemoryPool& pool = *transaction->tra_pool;
transaction->tra_db_snapshot =
FB_NEW(pool) DatabaseSnapshot(tdbb, pool);
}
return transaction->tra_db_snapshot;
}
int DatabaseSnapshot::blockingAst(void* ast_object)
{
Database* dbb = static_cast<Database*>(ast_object);
try
{
Lock* lock = dbb->dbb_monitor_lock;
Database::SyncGuard dsGuard(dbb, true);
ThreadContextHolder tdbb;
tdbb->setDatabase(lock->lck_dbb);
tdbb->setAttachment(lock->lck_attachment);
Jrd::ContextPoolHolder context(tdbb, dbb->dbb_permanent);
if (!(dbb->dbb_ast_flags & DBB_monitor_off))
{
try {
// Write the data to the shared memory
dumpData(tdbb, true);
// Release the lock and mark dbb as requesting a new one
LCK_release(tdbb, lock);
dbb->dbb_ast_flags |= DBB_monitor_off;
}
catch (const Exception&) {
gds__log("Unexpected exception at the AST level");
}
}
}
catch (const Firebird::Exception&)
{} // no-op
return 0;
}
DatabaseSnapshot::DatabaseSnapshot(thread_db* tdbb, MemoryPool& pool)
: snapshot(pool), idMap(pool), idCounter(0)
{
Database* const dbb = tdbb->getDatabase();
fb_assert(dbb);
const USHORT ods_version = ENCODE_ODS(dbb->dbb_ods_version, dbb->dbb_minor_original);
// Initialize record buffers
RecordBuffer* const dbb_buffer =
ods_version >= ODS_11_1 ? allocBuffer(tdbb, pool, rel_mon_database) : NULL;
RecordBuffer* const att_buffer =
ods_version >= ODS_11_1 ? allocBuffer(tdbb, pool, rel_mon_attachments) : NULL;
RecordBuffer* const tra_buffer =
ods_version >= ODS_11_1 ? allocBuffer(tdbb, pool, rel_mon_transactions) : NULL;
RecordBuffer* const stmt_buffer =
ods_version >= ODS_11_1 ? allocBuffer(tdbb, pool, rel_mon_statements) : NULL;
RecordBuffer* const call_buffer =
ods_version >= ODS_11_1 ? allocBuffer(tdbb, pool, rel_mon_calls) : NULL;
RecordBuffer* const io_stat_buffer =
ods_version >= ODS_11_1 ? allocBuffer(tdbb, pool, rel_mon_io_stats) : NULL;
RecordBuffer* const rec_stat_buffer =
ods_version >= ODS_11_1 ? allocBuffer(tdbb, pool, rel_mon_rec_stats) : NULL;
RecordBuffer* const ctx_var_buffer =
ods_version >= ODS_11_2 ? allocBuffer(tdbb, pool, rel_mon_ctx_vars) : NULL;
const Attachment* const attachment = tdbb->getAttachment();
fb_assert(attachment);
// This variable defines whether we're interested in the global data
// (i.e. all attachments) and hence should signal other processes
// or it's enough to return the local data (our own attachment) only.
const bool broadcast = attachment->att_user->locksmith();
AutoPtr<ClumpletReader> reader(NULL);
if (broadcast)
{
dumpData(tdbb, true);
// Release our own lock and mark dbb as requesting a new one
LCK_release(tdbb, dbb->dbb_monitor_lock);
dbb->dbb_ast_flags |= DBB_monitor_off;
// Signal other processes to dump their data
Lock temp_lock, *lock = &temp_lock;
lock->lck_dbb = dbb;
lock->lck_length = sizeof(SLONG);
lock->lck_key.lck_long = 0;
lock->lck_type = LCK_monitor;
lock->lck_owner_handle = LCK_get_owner_handle(tdbb, lock->lck_type);
lock->lck_parent = dbb->dbb_lock;
if (LCK_lock(tdbb, lock, LCK_EX, LCK_WAIT))
LCK_release(tdbb, lock);
// Read the shared memory
DumpGuard guard(dump);
reader = dump->readData(tdbb);
}
else
{
reader = dumpData(tdbb, false);
}
reader->rewind();
// Parse the dump
RecordBuffer* buffer = NULL;
Record* record = NULL;
int rid = 0;
bool database_processed = false, database_seen = false;
bool fields_processed = false, allowed = false;
while (!reader->isEof())
{
if (reader->getClumpTag() == TAG_DBB)
{
reader->moveNext();
if (fields_processed)
{
buffer->store(record);
fields_processed = false;
}
}
else if (reader->getClumpTag() == TAG_RECORD)
{
rid = reader->getInt();
reader->moveNext();
if (fields_processed)
{
buffer->store(record);
fields_processed = false;
}
switch (rid)
{
case rel_mon_database:
buffer = dbb_buffer;
break;
case rel_mon_attachments:
buffer = att_buffer;
break;
case rel_mon_transactions:
buffer = tra_buffer;
break;
case rel_mon_statements:
buffer = stmt_buffer;
break;
case rel_mon_calls:
buffer = call_buffer;
break;
case rel_mon_io_stats:
buffer = io_stat_buffer;
break;
case rel_mon_rec_stats:
buffer = rec_stat_buffer;
break;
case rel_mon_ctx_vars:
buffer = ctx_var_buffer;
break;
default:
fb_assert(false);
}
if (buffer)
{
record = buffer->getTempRecord();
clearRecord(record);
}
else
{
record = NULL;
}
}
else
{
const int fid = reader->getClumpTag();
const size_t length = reader->getClumpLength();
const char* source =
checkNull(rid, fid, (char*) reader->getBytes(), length);
reader->moveNext();
if (rid == rel_mon_database)
{
if (fid == f_mon_db_name)
{
database_processed = database_seen;
// Do we look at our own database record?
allowed = !dbb->dbb_database_name.compare(source, length);
if (allowed)
{
// Yep, we've seen it
database_seen = true;
}
}
// We need to return the database record only once
if (record && allowed && !database_processed)
{
putField(record, fid, source, length);
fields_processed = true;
}
}
// The generic logic that covers all relations
// except MON$DATABASE
else if (record && allowed)
{
putField(record, fid, source, length);
fields_processed = true;
}
}
}
if (fields_processed)
{
buffer->store(record);
fields_processed = false;
}
}
DatabaseSnapshot::~DatabaseSnapshot()
{
for (size_t i = 0; i < snapshot.getCount(); i++)
{
delete snapshot[i].data;
}
}
RecordBuffer* DatabaseSnapshot::getData(const jrd_rel* relation) const
{
fb_assert(relation);
for (size_t i = 0; i < snapshot.getCount(); i++)
{
if (snapshot[i].rel_id == relation->rel_id)
return snapshot[i].data;
}
return NULL;
}
RecordBuffer* DatabaseSnapshot::allocBuffer(thread_db* tdbb,
MemoryPool& pool,
int rel_id)
{
jrd_rel* relation = MET_lookup_relation_id(tdbb, rel_id, false);
fb_assert(relation);
MET_scan_relation(tdbb, relation);
fb_assert(relation->isVirtual());
Format* format = MET_current(tdbb, relation);
fb_assert(format);
RecordBuffer* buffer = FB_NEW(pool) RecordBuffer(pool, format);
RelationData data = {relation->rel_id, buffer};
snapshot.add(data);
return buffer;
}
void DatabaseSnapshot::clearRecord(Record* record)
{
fb_assert(record);
// Initialize all fields to NULLs
memset(record->rec_data, 0, record->rec_length);
const size_t null_bytes = (record->rec_format->fmt_count + 7) >> 3;
memset(record->rec_data, 0xFF, null_bytes);
}
void DatabaseSnapshot::putField(Record* record, int id, const void* source, size_t length)
{
fb_assert(record);
const Format* const format = record->rec_format;
fb_assert(format && id < format->fmt_count);
const dsc desc = format->fmt_desc[id];
UCHAR* const address = record->rec_data + (IPTR) desc.dsc_address;
if (!source)
{
SET_NULL(record, id);
return;
}
if (length == sizeof(SINT64) && desc.dsc_dtype == dtype_long)
{
// special case: translate 64-bit global ID into 32-bit local ID
const SINT64 global_id = *(SINT64*) source;
SLONG local_id = 0;
if (!idMap.get(global_id, local_id))
{
local_id = ++idCounter;
idMap.put(global_id, local_id);
}
*(SLONG*) address = local_id;
CLEAR_NULL(record, id);
return;
}
switch (desc.dsc_dtype) {
case dtype_text:
{
const char* const string = (char*) source;
const size_t max_length = desc.dsc_length;
length = MIN(length, max_length);
memcpy(address, string, length);
memset(address + length, ' ', max_length - length);
}
break;
case dtype_varying:
{
const char* const string = (char*) source;
const size_t max_length = desc.dsc_length - sizeof(USHORT);
length = MIN(length, max_length);
vary* varying = (vary*) address;
varying->vary_length = length;
memcpy(varying->vary_string, string, length);
}
break;
case dtype_short:
*(SSHORT*) address = *(SSHORT*) source;
break;
case dtype_long:
*(SLONG*) address = *(SLONG*) source;
break;
case dtype_int64:
*(SINT64*) address = *(SINT64*) source;
break;
case dtype_real:
*(float*) address = *(float*) source;
break;
case dtype_double:
*(double*) address = *(double*) source;
break;
case dtype_sql_date:
*(ISC_DATE*) address = *(ISC_DATE*) source;
break;
case dtype_sql_time:
*(ISC_TIME*) address = *(ISC_TIME*) source;
break;
case dtype_timestamp:
*(ISC_TIMESTAMP*) address = *(ISC_TIMESTAMP*) source;
break;
case dtype_blob:
{
thread_db* tdbb = JRD_get_thread_data();
UCharBuffer bpb;
bpb.resize(15);
UCHAR* p = bpb.begin();
*p++ = isc_bpb_version1;
*p++ = isc_bpb_source_type;
*p++ = 2;
put_short(p, isc_blob_text);
p += 2;
*p++ = isc_bpb_source_interp;
*p++ = 1;
*p++ = tdbb->getAttachment()->att_charset;
*p++ = isc_bpb_target_type;
*p++ = 2;
put_short(p, isc_blob_text);
p += 2;
*p++ = isc_bpb_target_interp;
*p++ = 1;
*p++ = CS_METADATA;
bpb.shrink(p - bpb.begin());
bid blob_id;
blb* blob = BLB_create2(tdbb, tdbb->getTransaction(), &blob_id,
bpb.getCount(), bpb.begin());
length = MIN(length, MAX_USHORT);
BLB_put_segment(tdbb, blob, (const UCHAR*) source, length);
BLB_close(tdbb, blob);
*(bid*) address = blob_id;
}
break;
default:
fb_assert(false);
}
CLEAR_NULL(record, id);
}
const char* DatabaseSnapshot::checkNull(int rid, int fid, const char* source, size_t length)
{
// The only goal of this function is to substitute some numeric zeroes
// and empty strings with NULLs
switch (rid) {
case rel_mon_attachments:
switch (fid) {
case f_mon_att_remote_proto:
case f_mon_att_remote_addr:
case f_mon_att_remote_process:
return length ? source : NULL;
case f_mon_att_remote_pid:
return (*(SLONG*) source) ? source : NULL;
default:
break;
}
break;
case rel_mon_statements:
switch (fid) {
case f_mon_stmt_att_id:
case f_mon_stmt_tra_id:
return (*(SLONG*) source) ? source : NULL;
case f_mon_stmt_timestamp:
return (*(SINT64*) source) ? source : NULL;
case f_mon_stmt_sql_text:
return length ? source : NULL;
default:
break;
}
break;
case rel_mon_calls:
switch (fid) {
case f_mon_call_caller_id:
case f_mon_call_type:
case f_mon_call_src_line:
case f_mon_call_src_column:
return (*(SLONG*) source) ? source : NULL;
case f_mon_call_name:
return length ? source : NULL;
default:
break;
}
break;
default:
break;
}
return source;
}
ClumpletReader* DatabaseSnapshot::dumpData(thread_db* tdbb, bool broadcast)
{
fb_assert(tdbb);
Database* const dbb = tdbb->getDatabase();
fb_assert(dbb);
const Attachment* const self_attachment = tdbb->getAttachment();
fb_assert(self_attachment);
MemoryPool& pool = *tdbb->getDefaultPool();
AutoPtr<ClumpletWriter> writer(FB_NEW(pool)
ClumpletWriter(pool, ClumpletReader::WideUnTagged, MAX_ULONG));
writer->insertBytes(TAG_DBB, (UCHAR*) &dbb->dbb_guid, sizeof(FB_GUID));
// Database information
putDatabase(dbb, *writer, dbb->generateId());
// Attachment information
for (Attachment* attachment = dbb->dbb_attachments;
attachment; attachment = attachment->att_next)
{
if (broadcast || attachment == self_attachment)
{
putAttachment(attachment, *writer, dbb->generateId());
putContextVars(attachment->att_context_vars, *writer,
attachment->att_attachment_id, true);
jrd_tra* transaction = NULL;
const jrd_req* request = NULL;
// Transaction information
for (transaction = attachment->att_transactions;
transaction; transaction = transaction->tra_next)
{
putTransaction(transaction, *writer, dbb->generateId());
putContextVars(transaction->tra_context_vars, *writer,
transaction->tra_number, false);
}
// Request information
for (request = attachment->att_requests;
request; request = request->req_request)
{
if (!(request->req_flags & (req_internal | req_sys_trigger)))
{
putRequest(request, *writer, dbb->generateId());
}
}
// Call stack information
for (transaction = attachment->att_transactions;
transaction; transaction = transaction->tra_next)
{
for (request = transaction->tra_requests;
request; request = request->req_tra_next)
{
if (!(request->req_flags & (req_internal | req_sys_trigger)) &&
request->req_caller)
{
putCall(request, *writer, dbb->generateId());
}
}
}
}
}
if (broadcast)
{
if (!dump)
{
// Initialize the shared memory region
MutexLockGuard guard(initMutex);
if (!dump)
{
dump = FB_NEW(*getDefaultMemoryPool()) SharedMemory;
}
}
DumpGuard guard(dump);
dump->writeData(tdbb, *writer);
return NULL;
}
return writer.release();
}
void DatabaseSnapshot::putDatabase(const Database* database,
ClumpletWriter& writer,
int stat_id)
{
fb_assert(database);
writer.insertByte(TAG_RECORD, rel_mon_database);
// Reload header
const PageSpace* const pageSpace =
database->dbb_page_manager.findPageSpace(DB_PAGE_SPACE);
const jrd_file* const file = pageSpace->file;
PAG_header(true);
// database name or alias
writer.insertPath(f_mon_db_name, database->dbb_database_name);
// page size
writer.insertInt(f_mon_db_page_size, database->dbb_page_size);
// major ODS version
writer.insertInt(f_mon_db_ods_major, database->dbb_ods_version);
// minor ODS version
writer.insertInt(f_mon_db_ods_minor, database->dbb_minor_version);
// oldest interesting transaction
writer.insertInt(f_mon_db_oit, database->dbb_oldest_transaction);
// oldest active transaction
writer.insertInt(f_mon_db_oat, database->dbb_oldest_active);
// oldest snapshot transaction
writer.insertInt(f_mon_db_ost, database->dbb_oldest_snapshot);
// next transaction
writer.insertInt(f_mon_db_nt, database->dbb_next_transaction);
// number of page buffers
writer.insertInt(f_mon_db_page_bufs, database->dbb_bcb->bcb_count);
int temp;
// SQL dialect
temp = (database->dbb_flags & DBB_DB_SQL_dialect_3) ? 3 : 1;
writer.insertInt(f_mon_db_dialect, temp);
// shutdown mode
if (database->dbb_ast_flags & DBB_shutdown_full)
temp = shut_mode_full;
else if (database->dbb_ast_flags & DBB_shutdown_single)
temp = shut_mode_single;
else if (database->dbb_ast_flags & DBB_shutdown)
temp = shut_mode_multi;
else
temp = shut_mode_online;
writer.insertInt(f_mon_db_shut_mode, temp);
// sweep interval
writer.insertInt(f_mon_db_sweep_int, database->dbb_sweep_interval);
// read only flag
temp = (database->dbb_flags & DBB_read_only) ? 1 : 0;
writer.insertInt(f_mon_db_read_only, temp);
// forced writes flag
temp = (database->dbb_flags & DBB_force_write) ? 1 : 0;
writer.insertInt(f_mon_db_forced_writes, temp);
// reserve space flag
temp = (database->dbb_flags & DBB_no_reserve) ? 0 : 1;
writer.insertInt(f_mon_db_res_space, temp);
// creation date
writer.insertBytes(f_mon_db_created,
(UCHAR*) &database->dbb_creation_date.value(),
sizeof(ISC_TIMESTAMP));
// database size
writer.insertBigInt(f_mon_db_pages, PageSpace::actAlloc(database));
// database state
thread_db* tdbb = JRD_get_thread_data();
{ // scope
BackupManager::SharedDatabaseHolder sdbHolder(tdbb, database->dbb_backup_manager);
switch (database->dbb_backup_manager->get_state())
{
case nbak_state_normal:
temp = backup_state_normal;
break;