File: stable-bloom.hh

package info (click to toggle)
pdns-recursor 4.8.8-1%2Bdeb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 9,620 kB
  • sloc: cpp: 95,714; javascript: 20,651; sh: 4,679; makefile: 652; xml: 37
file content (193 lines) | stat: -rw-r--r-- 6,058 bytes parent folder | download
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
/*
 * This file is part of PowerDNS or dnsdist.
 * Copyright -- PowerDNS.COM B.V. and its contributors
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of version 2 of the GNU General Public License as
 * published by the Free Software Foundation.
 *
 * In addition, for the avoidance of any doubt, permission is granted to
 * link this program with OpenSSL and to (re)distribute the binaries
 * produced as the result of such linking.
 *
 * 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.
 */

#pragma once

#include <vector>
#include <cmath>
#include <random>
#include <arpa/inet.h>
#include <boost/dynamic_bitset.hpp>
#include "misc.hh"
#include "noinitvector.hh"
#include "ext/probds/murmur3.h"

namespace bf
{
// Based on http://webdocs.cs.ualberta.ca/~drafiei/papers/DupDetExt.pdf
// Max is always 1 in this implementation, which is best for streaming data
// This also means we can use a bitset for storing values which is very
// efficient
class stableBF
{
public:
  stableBF(float fp_rate, uint32_t num_cells, uint8_t p) :
    d_k(optimalK(fp_rate)),
    d_num_cells(num_cells),
    d_p(p),
    d_cells(num_cells),
    d_gen(std::random_device()()),
    d_dis(0, num_cells) {}
  stableBF(uint8_t k, uint32_t num_cells, uint8_t p, const std::string& bitstr) :
    d_k(k),
    d_num_cells(num_cells),
    d_p(p),
    d_cells(bitstr),
    d_gen(std::random_device()()),
    d_dis(0, num_cells) {}
  void add(const std::string& data)
  {
    decrement();
    auto hashes = hash(data);
    for (auto& i : hashes) {
      d_cells.set(i % d_num_cells);
    }
  }
  bool test(const std::string& data) const
  {
    auto hashes = hash(data);
    for (auto& i : hashes) {
      if (d_cells.test(i % d_num_cells) == false)
        return false;
    }
    return true;
  }
  bool testAndAdd(const std::string& data)
  {
    auto hashes = hash(data);
    bool retval = true;
    for (auto& i : hashes) {
      if (d_cells.test(i % d_num_cells) == false) {
        retval = false;
        break;
      }
    }
    decrement();
    for (auto& i : hashes) {
      d_cells.set(i % d_num_cells);
    }
    return retval;
  }
  void dump(std::ostream& os)
  {
    os.write((char*)&d_k, sizeof(d_k));
    uint32_t nint = htonl(d_num_cells);
    os.write((char*)&nint, sizeof(nint));
    os.write((char*)&d_p, sizeof(d_p));
    std::string temp_str;
    boost::to_string(d_cells, temp_str);
    uint32_t bitstr_length = htonl((uint32_t)temp_str.length());
    os.write((char*)&bitstr_length, sizeof(bitstr_length));
    os.write((char*)temp_str.c_str(), temp_str.length());
    if (os.fail()) {
      throw std::runtime_error("SBF: Failed to dump");
    }
  }
  void restore(std::istream& is)
  {
    uint8_t k, p;
    uint32_t num_cells, bitstr_len;
    is.read((char*)&k, sizeof(k));
    if (is.fail()) {
      throw std::runtime_error("SBF: read failed (file too short?)");
    }
    is.read((char*)&num_cells, sizeof(num_cells));
    if (is.fail()) {
      throw std::runtime_error("SBF: read failed (file too short?)");
    }
    num_cells = ntohl(num_cells);
    is.read((char*)&p, sizeof(p));
    if (is.fail()) {
      throw std::runtime_error("SBF: read failed (file too short?)");
    }
    is.read((char*)&bitstr_len, sizeof(bitstr_len));
    if (is.fail()) {
      throw std::runtime_error("SBF: read failed (file too short?)");
    }
    bitstr_len = ntohl(bitstr_len);
    if (bitstr_len > 2 * 64 * 1024 * 1024U) { // twice the current size
      throw std::runtime_error("SBF: read failed (bitstr_len too big)");
    }
    auto bitcstr = std::make_unique<char[]>(bitstr_len);
    is.read(bitcstr.get(), bitstr_len);
    if (is.fail()) {
      throw std::runtime_error("SBF: read failed (file too short?)");
    }
    std::string bitstr(bitcstr.get(), bitstr_len);
    stableBF tempbf(k, num_cells, p, bitstr);
    swap(tempbf);
  }

private:
  unsigned int optimalK(float fp_rate)
  {
    return std::ceil(std::log2(1 / fp_rate));
  }
  void decrement()
  {
    // Choose a random cell then decrement the next p-1
    // The stable bloom algorithm described in the paper says
    // to choose p independent positions, but that is much slower
    // and this shouldn't change the properties of the SBF
    size_t r = d_dis(d_gen);
    for (uint64_t i = 0; i < d_p; ++i) {
      d_cells.reset((r + i) % d_num_cells);
    }
  }
  void swap(stableBF& rhs)
  {
    std::swap(d_k, rhs.d_k);
    std::swap(d_num_cells, rhs.d_num_cells);
    std::swap(d_p, rhs.d_p);
    d_cells.swap(rhs.d_cells);
  }
  // This is a double hash implementation returning an array of
  // k hashes
  std::vector<uint32_t> hash(const std::string& data) const
  {
    uint32_t h1, h2;
    // MurmurHash3 assumes the data is uint32_t aligned, so fixup if needed
    // It does handle string lengths that are not a multiple of sizeof(uint32_t) correctly
    if (reinterpret_cast<uintptr_t>(data.data()) % sizeof(uint32_t) != 0) {
      NoInitVector<uint32_t> x((data.length() / sizeof(uint32_t)) + 1);
      memcpy(x.data(), data.data(), data.length());
      MurmurHash3_x86_32(x.data(), data.length(), 1, &h1);
      MurmurHash3_x86_32(x.data(), data.length(), 2, &h2);
    }
    else {
      MurmurHash3_x86_32(data.data(), data.length(), 1, &h1);
      MurmurHash3_x86_32(data.data(), data.length(), 2, &h2);
    }
    std::vector<uint32_t> ret_hashes(d_k);
    for (size_t i = 0; i < d_k; ++i) {
      ret_hashes[i] = h1 + i * h2;
    }
    return ret_hashes;
  }
  uint8_t d_k;
  uint32_t d_num_cells;
  uint8_t d_p;
  boost::dynamic_bitset<> d_cells;
  std::mt19937 d_gen;
  std::uniform_int_distribution<> d_dis;
};
}