forked from mariadb-corporation/mariadb-columnstore-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrowstorage.cpp
2369 lines (2126 loc) · 62.2 KB
/
rowstorage.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
/* Copyright (C) 2021-2022 MariaDB Corporation
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; version 2 of
the 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 General Public License for more details.
You should have received a copy of the GNU 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. */
#include <unistd.h>
#include <sys/stat.h>
#include <boost/filesystem.hpp>
#include "rowgroup.h"
#include <resourcemanager.h>
#include <fcntl.h>
#include "rowstorage.h"
#include "robin_hood.h"
namespace
{
int writeData(int fd, const char* buf, size_t sz)
{
if (sz == 0)
return 0;
auto to_write = sz;
while (to_write > 0)
{
auto r = write(fd, buf + sz - to_write, to_write);
if (UNLIKELY(r < 0))
{
if (errno == EAGAIN)
continue;
return errno;
}
assert(size_t(r) <= to_write);
to_write -= r;
}
return 0;
}
int readData(int fd, char* buf, size_t sz)
{
if (sz == 0)
return 0;
auto to_read = sz;
while (to_read > 0)
{
auto r = read(fd, buf + sz - to_read, to_read);
if (UNLIKELY(r < 0))
{
if (errno == EAGAIN)
continue;
return errno;
}
assert(size_t(r) <= to_read);
to_read -= r;
}
return 0;
}
std::string errorString(int errNo)
{
char tmp[1024];
auto* buf = strerror_r(errNo, tmp, sizeof(tmp));
return {buf};
}
} // anonymous namespace
namespace rowgroup
{
uint64_t hashRow(const rowgroup::Row& r, std::size_t lastCol)
{
uint64_t ret = 0;
if (lastCol >= r.getColumnCount())
return 0;
datatypes::MariaDBHasher h;
utils::Hasher64_r columnHasher;
bool strHashUsed = false;
for (uint32_t i = 0; i <= lastCol; ++i)
{
switch (r.getColType(i))
{
case execplan::CalpontSystemCatalog::CHAR:
case execplan::CalpontSystemCatalog::VARCHAR:
case execplan::CalpontSystemCatalog::BLOB:
case execplan::CalpontSystemCatalog::TEXT:
{
auto cs = r.getCharset(i);
auto strColValue = r.getConstString(i);
auto strColValueLen = strColValue.length();
if (strColValueLen > MaxConstStrSize)
{
h.add(cs, strColValue);
strHashUsed = true;
}
else
{
// This is relatively big stack allocation.
// It is aligned for future vectorization of hash calculation.
uchar buf[MaxConstStrBufSize] __attribute__((aligned(64)));
// Pay attention to the last strxfrm argument value.
// It is called flags and in many cases it has padding
// enabled(MY_STRXFRM_PAD_WITH_SPACE bit). With padding enabled
// strxfrm returns MaxConstStrBufSize bytes and not the actual
// weights array length. Here I disable padding.
auto charset = datatypes::Charset(cs);
auto trimStrColValue = strColValue.rtrimSpaces();
// The padding is disabled b/c we previously use rtrimSpaces().
// strColValueLen is used here.
size_t nActualWeights = charset.strnxfrm(buf, MaxConstStrBufSize, strColValueLen,
reinterpret_cast<const uchar*>(trimStrColValue.str()),
trimStrColValue.length(), 0);
ret = columnHasher(reinterpret_cast<const void*>(buf), nActualWeights, ret);
}
break;
}
default: ret = columnHasher(r.getData() + r.getOffset(i), r.getColumnWidth(i), ret); break;
}
}
// The properties of the hash produced are worse if MDB hasher results are incorporated
// so late but these results must be used very infrequently.
if (strHashUsed)
{
uint64_t strhash = h.finalize();
ret = columnHasher(&strhash, sizeof(strhash), ret);
}
return columnHasher.finalize(ret, lastCol << 2);
}
/** @brief NoOP interface to LRU-cache used by RowGroupStorage & HashStorage
*/
struct LRUIface
{
using List = std::list<uint64_t>;
virtual ~LRUIface() = default;
/** @brief Put an ID to cache or set it as last used */
virtual void add(uint64_t)
{
}
/** @brief Remove an ID from cache */
virtual void remove(uint64_t)
{
}
/** @brief Get iterator of the most recently used ID */
virtual List::const_reverse_iterator begin() const
{
return List::const_reverse_iterator();
}
/** @brief Get iterator after the latest ID */
virtual List::const_reverse_iterator end() const
{
return List::const_reverse_iterator();
}
/** @brief Get iterator of the latest ID */
virtual List::const_iterator rbegin() const
{
return {};
}
/** @brief Get iterator after the most recently used ID */
virtual List::const_iterator rend() const
{
return {};
}
virtual void clear()
{
}
virtual std::size_t size() const
{
return 0;
}
virtual bool empty() const
{
return true;
}
virtual LRUIface* clone() const
{
return new LRUIface();
}
};
struct LRU : public LRUIface
{
~LRU() override
{
fMap.clear();
fList.clear();
}
inline void add(uint64_t rgid) final
{
auto it = fMap.find(rgid);
if (it != fMap.end())
{
fList.erase(it->second);
}
fMap[rgid] = fList.insert(fList.end(), rgid);
}
inline void remove(uint64_t rgid) final
{
auto it = fMap.find(rgid);
if (UNLIKELY(it != fMap.end()))
{
fList.erase(it->second);
fMap.erase(it);
}
}
inline List::const_reverse_iterator begin() const final
{
return fList.crbegin();
}
inline List::const_reverse_iterator end() const final
{
return fList.crend();
}
inline List::const_iterator rbegin() const final
{
return fList.cbegin();
}
inline List::const_iterator rend() const final
{
return fList.cend();
}
inline void clear() final
{
fMap.clear();
fList.clear();
}
size_t size() const final
{
return fMap.size();
}
bool empty() const final
{
return fList.empty();
}
LRUIface* clone() const final
{
return new LRU();
}
robin_hood::unordered_flat_map<uint64_t, List::iterator> fMap;
List fList;
};
/** @brief Some service wrapping around ResourceManager (or NoOP) */
class MemManager
{
public:
MemManager()
{
}
virtual ~MemManager()
{
release(fMemUsed);
}
bool acquire(std::size_t amount)
{
return acquireImpl(amount);
}
void release(ssize_t amount = 0)
{
// in some cases it tries to release more memory than acquired, ie create
// new rowgroup, acquire maximum size (w/o strings), add some rows with
// strings and finally release the actual size of RG with strings
if (amount == 0 || amount > fMemUsed)
amount = fMemUsed;
releaseImpl(amount);
}
ssize_t getUsed() const
{
return fMemUsed;
}
virtual int64_t getFree() const
{
return std::numeric_limits<int64_t>::max();
}
virtual int64_t getConfigured() const
{
return std::numeric_limits<int64_t>::max();
}
virtual bool isStrict() const
{
return false;
}
virtual MemManager* clone() const
{
return new MemManager();
}
virtual joblist::ResourceManager* getResourceManaged()
{
return nullptr;
}
virtual boost::shared_ptr<int64_t> getSessionLimit()
{
return {};
}
protected:
virtual bool acquireImpl(std::size_t amount)
{
fMemUsed += amount;
return true;
}
virtual void releaseImpl(std::size_t amount)
{
fMemUsed -= amount;
}
ssize_t fMemUsed = 0;
};
class RMMemManager : public MemManager
{
public:
RMMemManager(joblist::ResourceManager* rm, boost::shared_ptr<int64_t> sl, bool wait = true,
bool strict = true)
: fRm(rm), fSessLimit(std::move(sl)), fWait(wait), fStrict(strict)
{
}
~RMMemManager() override
{
release(fMemUsed);
fMemUsed = 0;
}
int64_t getConfigured() const final
{
return fRm->getConfiguredUMMemLimit();
}
int64_t getFree() const final
{
return std::min(fRm->availableMemory(), *fSessLimit);
}
bool isStrict() const final
{
return fStrict;
}
MemManager* clone() const final
{
return new RMMemManager(fRm, fSessLimit, fWait, fStrict);
}
joblist::ResourceManager* getResourceManaged() override
{
return fRm;
}
boost::shared_ptr<int64_t> getSessionLimit() override
{
return fSessLimit;
}
protected:
bool acquireImpl(size_t amount) final
{
if (amount)
{
if (!fRm->getMemory(amount, fSessLimit, fWait) && fStrict)
{
return false;
}
MemManager::acquireImpl(amount);
}
return true;
}
void releaseImpl(size_t amount) override
{
if (amount)
{
MemManager::releaseImpl(amount);
fRm->returnMemory(amount, fSessLimit);
}
}
private:
joblist::ResourceManager* fRm = nullptr;
boost::shared_ptr<int64_t> fSessLimit;
const bool fWait;
const bool fStrict;
};
class Dumper
{
public:
Dumper(const compress::CompressInterface* comp, MemManager* mm) : fCompressor(comp), fMM(mm->clone())
{
}
int write(const std::string& fname, const char* buf, size_t sz)
{
if (sz == 0)
return 0;
int fd = open(fname.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (UNLIKELY(fd < 0))
return errno;
const char* tmpbuf;
if (fCompressor)
{
auto len = fCompressor->maxCompressedSize(sz);
checkBuffer(len);
fCompressor->compress(buf, sz, fTmpBuf.data(), &len);
tmpbuf = fTmpBuf.data();
sz = len;
}
else
{
tmpbuf = buf;
}
auto to_write = sz;
int ret = 0;
while (to_write > 0)
{
auto r = ::write(fd, tmpbuf + sz - to_write, to_write);
if (UNLIKELY(r < 0))
{
if (errno == EAGAIN)
continue;
ret = errno;
close(fd);
return ret;
}
assert(size_t(r) <= to_write);
to_write -= r;
}
close(fd);
return ret;
}
int read(const std::string& fname, std::vector<char>& buf)
{
int fd = open(fname.c_str(), O_RDONLY);
if (UNLIKELY(fd < 0))
return errno;
struct stat st
{
};
fstat(fd, &st);
size_t sz = st.st_size;
std::vector<char>* tmpbuf;
if (fCompressor)
{
tmpbuf = &fTmpBuf;
checkBuffer(sz);
}
else
{
tmpbuf = &buf;
buf.resize(sz);
}
auto to_read = sz;
int ret = 0;
while (to_read > 0)
{
auto r = ::read(fd, tmpbuf->data() + sz - to_read, to_read);
if (UNLIKELY(r < 0))
{
if (errno == EAGAIN)
continue;
ret = errno;
close(fd);
return ret;
}
assert(size_t(r) <= to_read);
to_read -= r;
}
if (fCompressor)
{
size_t len;
if (!fCompressor->getUncompressedSize(tmpbuf->data(), sz, &len))
{
ret = EPROTO;
close(fd);
return ret;
}
buf.resize(len);
fCompressor->uncompress(tmpbuf->data(), sz, buf.data(), &len);
}
close(fd);
return ret;
}
size_t size() const
{
return fTmpBuf.size();
}
private:
void checkBuffer(size_t len)
{
if (fTmpBuf.size() < len)
{
size_t newtmpsz = (len + 8191) / 8192 * 8192;
std::vector<char> tmpvec(newtmpsz);
fMM->acquire(newtmpsz - fTmpBuf.size());
fTmpBuf.swap(tmpvec);
}
}
private:
const compress::CompressInterface* fCompressor;
std::unique_ptr<MemManager> fMM;
std::vector<char> fTmpBuf;
};
/** @brief Storage for RGData with LRU-cache & memory management
*/
class RowGroupStorage
{
public:
using RGDataStorage = std::vector<std::unique_ptr<RGData>>;
public:
/** @brief Default constructor
*
* @param tmpDir(in) directory for tmp data
* @param rowGroupOut(in,out) RowGroup metadata
* @param maxRows(in) number of rows per rowgroup
* @param rm ResourceManager to use or nullptr if we don't
* need memory accounting
* @param sessLimit session memory limit
* @param wait shall we wait a bit if we haven't enough memory
* right now?
* @param strict true -> throw an exception if not enough memory
* false -> deal with it later
* @param compressor pointer to CompressInterface impl or nullptr
*/
RowGroupStorage(const std::string& tmpDir, RowGroup* rowGroupOut, size_t maxRows,
joblist::ResourceManager* rm = nullptr, boost::shared_ptr<int64_t> sessLimit = {},
bool wait = false, bool strict = false, compress::CompressInterface* compressor = nullptr)
: fRowGroupOut(rowGroupOut)
, fMaxRows(maxRows)
, fRGDatas()
, fUniqId(this)
, fTmpDir(tmpDir)
, fCompressor(compressor)
{
if (rm)
{
fMM.reset(new RMMemManager(rm, sessLimit, wait, strict));
if (!wait && !strict)
{
fLRU = std::unique_ptr<LRUIface>(new LRU());
}
else
{
fLRU = std::unique_ptr<LRUIface>(new LRUIface());
}
}
else
{
fMM.reset(new MemManager());
fLRU = std::unique_ptr<LRUIface>(new LRUIface());
}
fDumper.reset(new Dumper(fCompressor, fMM.get()));
auto* curRG = new RGData(*fRowGroupOut, fMaxRows);
fRowGroupOut->setData(curRG);
fRowGroupOut->resetRowGroup(0);
fRGDatas.emplace_back(curRG);
fMM->acquire(fRowGroupOut->getSizeWithStrings(fMaxRows));
}
~RowGroupStorage() = default;
ssize_t getAproxRGSize() const
{
return fRowGroupOut->getSizeWithStrings(fMaxRows);
}
/** @brief Take away RGDatas from another RowGroupStorage
*
* If some of the RGDatas is not in the memory do not load them,
* just rename dump file to match new RowGroupStorage pattern
*
* @param o RowGroupStorage to take from
*/
void append(std::unique_ptr<RowGroupStorage> o)
{
return append(o.get());
}
void append(RowGroupStorage* o)
{
std::unique_ptr<RGData> rgd;
std::string ofname;
while (o->getNextRGData(rgd, ofname))
{
fRGDatas.push_back(std::move(rgd));
uint64_t rgid = fRGDatas.size() - 1;
if (fRGDatas[rgid])
{
fRowGroupOut->setData(fRGDatas[rgid].get());
int64_t memSz = fRowGroupOut->getSizeWithStrings(fMaxRows);
if (!fMM->acquire(memSz))
{
throw logging::IDBExcept(
logging::IDBErrorInfo::instance()->errorMsg(logging::ERR_AGGREGATION_TOO_BIG),
logging::ERR_AGGREGATION_TOO_BIG);
}
if (fMM->getFree() < memSz * 2)
{
saveRG(rgid);
fRGDatas[rgid].reset();
}
else
fLRU->add(rgid);
}
else
{
auto r = rename(ofname.c_str(), makeRGFilename(rgid).c_str());
if (UNLIKELY(r < 0))
{
throw logging::IDBExcept(logging::IDBErrorInfo::instance()->errorMsg(
logging::ERR_DISKAGG_FILEIO_ERROR, errorString(errno)),
logging::ERR_DISKAGG_FILEIO_ERROR);
}
}
rgd.reset();
ofname.clear();
}
}
/** @brief Returns next RGData, load it from disk if necessary.
*
* @returns pointer to the next RGData or empty pointer if there is nothing
*/
std::unique_ptr<RGData> getNextRGData()
{
while (!fRGDatas.empty())
{
uint64_t rgid = fRGDatas.size() - 1;
if (!fRGDatas[rgid])
loadRG(rgid, fRGDatas[rgid], true);
unlink(makeRGFilename(rgid).c_str());
auto rgdata = std::move(fRGDatas[rgid]);
fRGDatas.pop_back();
fRowGroupOut->setData(rgdata.get());
int64_t memSz = fRowGroupOut->getSizeWithStrings(fMaxRows);
fMM->release(memSz);
fLRU->remove(rgid);
if (fRowGroupOut->getRowCount() == 0)
continue;
return rgdata;
}
return {};
}
void initRow(Row& row) const
{
fRowGroupOut->initRow(&row);
}
/** @brief Get the row at the specified position, loading corresponding RGData if needed.
*
* @param idx(in) index (from 0) of the row
* @param row(out) resulting row
*/
void getRow(uint64_t idx, Row& row)
{
uint64_t rgid = idx / fMaxRows;
uint64_t rid = idx % fMaxRows;
if (UNLIKELY(!fRGDatas[rgid]))
{
loadRG(rgid);
}
fRGDatas[rgid]->getRow(rid, &row);
fLRU->add(rgid);
}
/** @brief Return a row and an index at the first free position.
*
* @param idx(out) index of the row
* @param row(out) the row itself
*/
void putRow(uint64_t& idx, Row& row)
{
bool need_new = false;
if (UNLIKELY(fRGDatas.empty()))
{
need_new = true;
}
else if (UNLIKELY(!fRGDatas[fCurRgid]))
{
need_new = true;
}
else
{
fRowGroupOut->setData(fRGDatas[fCurRgid].get());
if (UNLIKELY(fRowGroupOut->getRowCount() >= fMaxRows))
need_new = true;
}
if (UNLIKELY(need_new))
{
for (auto rgid : *fLRU)
{
if (LIKELY(static_cast<bool>(fRGDatas[rgid])))
{
fRowGroupOut->setData(fRGDatas[rgid].get());
if (fRowGroupOut->getRowCount() < fMaxRows)
{
fCurRgid = rgid;
need_new = false;
break;
}
}
}
}
if (UNLIKELY(need_new))
{
auto memSz = fRowGroupOut->getSizeWithStrings(fMaxRows);
if (!fMM->acquire(memSz))
{
throw logging::IDBExcept(
logging::IDBErrorInfo::instance()->errorMsg(logging::ERR_AGGREGATION_TOO_BIG),
logging::ERR_AGGREGATION_TOO_BIG);
}
auto* curRG = new RGData(*fRowGroupOut, fMaxRows);
fRowGroupOut->setData(curRG);
fRowGroupOut->resetRowGroup(0);
fRGDatas.emplace_back(curRG);
fCurRgid = fRGDatas.size() - 1;
}
fLRU->add(fCurRgid);
idx = fCurRgid * fMaxRows + fRowGroupOut->getRowCount();
fRowGroupOut->getRow(fRowGroupOut->getRowCount(), &row);
fRowGroupOut->incRowCount();
}
/** @brief Create a row at the specified position.
*
* Used only for key rows in case of external keys. Indexes of data row and
* corresponding key row are always the same.
*
* @param idx(in) index to create row
* @param row(out) row itself
*/
void putKeyRow(uint64_t idx, Row& row)
{
uint64_t rgid = idx / fMaxRows;
while (rgid >= fRGDatas.size())
{
int64_t memSz = fRowGroupOut->getSizeWithStrings(fMaxRows);
if (!fMM->acquire(memSz))
{
throw logging::IDBExcept(
logging::IDBErrorInfo::instance()->errorMsg(logging::ERR_AGGREGATION_TOO_BIG),
logging::ERR_AGGREGATION_TOO_BIG);
}
auto* curRG = new RGData(*fRowGroupOut, fMaxRows);
fRowGroupOut->setData(curRG);
fRowGroupOut->resetRowGroup(0);
fRGDatas.emplace_back(curRG);
fCurRgid = fRGDatas.size() - 1;
fLRU->add(fCurRgid);
}
if (UNLIKELY(!fRGDatas[rgid]))
{
loadRG(rgid);
}
else
{
fRowGroupOut->setData(fRGDatas[rgid].get());
}
fLRU->add(rgid);
assert(idx % fMaxRows == fRowGroupOut->getRowCount());
fRowGroupOut->getRow(fRowGroupOut->getRowCount(), &row);
fRowGroupOut->incRowCount();
}
/** @brief Dump the oldest RGData to disk, freeing memory
*
* @returns true if any RGData was dumped
*/
bool dump()
{
// Always leave at least 2 RG as this is the minimum size of the hashmap
constexpr size_t MIN_INMEMORY = 2;
if (fLRU->size() <= MIN_INMEMORY)
{
return false;
}
size_t moved = 0;
auto it = fLRU->rbegin();
while (LIKELY(it != fLRU->rend()))
{
if (fLRU->size() <= MIN_INMEMORY)
return false;
uint64_t rgid = *it;
if (UNLIKELY(!fRGDatas[rgid]))
{
++it;
fLRU->remove(rgid);
continue;
}
fRowGroupOut->setData(fRGDatas[rgid].get());
if (moved <= MIN_INMEMORY && fRowGroupOut->getRowCount() < fMaxRows)
{
++it;
++moved;
fLRU->add(rgid);
continue;
}
saveRG(rgid);
fLRU->remove(rgid);
fRGDatas[rgid].reset();
return true;
}
return false;
}
/** @brief Dump all data, clear state and start over */
void startNewGeneration()
{
dumpAll();
fLRU->clear();
fMM->release();
fRGDatas.clear();
// we need at least one RGData so create it right now
auto* curRG = new RGData(*fRowGroupOut, fMaxRows);
fRowGroupOut->setData(curRG);
fRowGroupOut->resetRowGroup(0);
fRGDatas.emplace_back(curRG);
auto memSz = fRowGroupOut->getSizeWithStrings(fMaxRows);
if (!fMM->acquire(memSz))
{
throw logging::IDBExcept(logging::IDBErrorInfo::instance()->errorMsg(logging::ERR_AGGREGATION_TOO_BIG),
logging::ERR_AGGREGATION_TOO_BIG);
}
fCurRgid = 0;
++fGeneration;
}
/** @brief Save "finalized" bitmap to disk for future use */
void dumpFinalizedInfo() const
{
auto fname = makeFinalizedFilename();
int fd = open(fname.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (UNLIKELY(fd < 0))
{
throw logging::IDBExcept(
logging::IDBErrorInfo::instance()->errorMsg(logging::ERR_DISKAGG_FILEIO_ERROR, errorString(errno)),
logging::ERR_DISKAGG_FILEIO_ERROR);
}
uint64_t sz = fRGDatas.size();
uint64_t finsz = fFinalizedRows.size();
int errNo;
if ((errNo = writeData(fd, (const char*)&sz, sizeof(sz))) != 0 ||
(errNo = writeData(fd, (const char*)&finsz, sizeof(finsz)) != 0) ||
(errNo = writeData(fd, (const char*)fFinalizedRows.data(), finsz * sizeof(uint64_t)) != 0))
{
close(fd);
unlink(fname.c_str());
throw logging::IDBExcept(
logging::IDBErrorInfo::instance()->errorMsg(logging::ERR_DISKAGG_FILEIO_ERROR, errorString(errNo)),
logging::ERR_DISKAGG_FILEIO_ERROR);
}
close(fd);
}
/** @brief Load "finalized" bitmap */
void loadFinalizedInfo()
{
auto fname = makeFinalizedFilename();
int fd = open(fname.c_str(), O_RDONLY);
if (fd < 0)
{
throw logging::IDBExcept(
logging::IDBErrorInfo::instance()->errorMsg(logging::ERR_DISKAGG_FILEIO_ERROR, errorString(errno)),
logging::ERR_DISKAGG_FILEIO_ERROR);
}
uint64_t sz;
uint64_t finsz;
int errNo;
if ((errNo = readData(fd, (char*)&sz, sizeof(sz)) != 0) ||
(errNo = readData(fd, (char*)&finsz, sizeof(finsz)) != 0))
{
close(fd);
unlink(fname.c_str());
throw logging::IDBExcept(
logging::IDBErrorInfo::instance()->errorMsg(logging::ERR_DISKAGG_FILEIO_ERROR, errorString(errNo)),
logging::ERR_DISKAGG_FILEIO_ERROR);
}
fRGDatas.resize(sz);
fFinalizedRows.resize(finsz);
if ((errNo = readData(fd, (char*)fFinalizedRows.data(), finsz * sizeof(uint64_t))) != 0)
{
close(fd);
unlink(fname.c_str());
throw logging::IDBExcept(
logging::IDBErrorInfo::instance()->errorMsg(logging::ERR_DISKAGG_FILEIO_ERROR, errorString(errNo)),
logging::ERR_DISKAGG_FILEIO_ERROR);
}
close(fd);
}
/** @brief Save all RGData to disk */
void dumpAll(bool dumpFin = true) const
{
#ifdef DISK_AGG_DEBUG
dumpMeta();
#endif
for (uint64_t i = 0; i < fRGDatas.size(); ++i)
{
if (fRGDatas[i])
saveRG(i, fRGDatas[i].get());
else
{
auto fname = makeRGFilename(i);
if (access(fname.c_str(), F_OK) != 0)
::abort();
}
}
if (dumpFin)
dumpFinalizedInfo();
}
/** @brief Create new RowGroupStorage with the save LRU, MemManager & uniq ID */
RowGroupStorage* clone(uint16_t gen) const
{
auto* ret = new RowGroupStorage(fTmpDir, fRowGroupOut, fMaxRows);
ret->fRGDatas.clear();
ret->fLRU.reset(fLRU->clone());
ret->fMM.reset(fMM->clone());
ret->fUniqId = fUniqId;
ret->fGeneration = gen;
ret->fCompressor = fCompressor;
ret->fDumper.reset(new Dumper(fCompressor, fMM.get()));
ret->loadFinalizedInfo();
return ret;
}
/** @brief Mark row at specified index as finalized so it should be skipped
*/
void markFinalized(uint64_t idx)
{
uint64_t gid = idx / 64;
uint64_t rid = idx % 64;
if (LIKELY(fFinalizedRows.size() <= gid))
fFinalizedRows.resize(gid + 1, 0ULL);
fFinalizedRows[gid] |= 1ULL << rid;
}