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
|
// DCSO go bloom filter
// Copyright (c) 2017, DCSO GmbH
package main
import (
"bufio"
"bytes"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/DCSO/bloom"
"github.com/urfave/cli"
)
// BloomParams represents the parameters of the 'bloom' command line tool.
type BloomParams struct {
gzip bool
interactive bool
split bool
printEachMatch bool
delimiter string
fields []int
printFields []int
}
func exitWithError(message string) {
fmt.Fprintf(os.Stderr, "Error: %s \n", message)
os.Exit(-1)
}
func readValuesIntoFilter(filter *bloom.BloomFilter, bloomParams BloomParams) {
//we determine if the program is run interactively or within a pipe
stat, _ := os.Stdin.Stat()
var isTerminal = (stat.Mode() & os.ModeCharDevice) != 0
//if we are not in an interactive session and this is a terminal, we quit
if !bloomParams.interactive && isTerminal {
return
}
if bloomParams.interactive {
fmt.Println("Interactive mode: Enter a blank line [by pressing ENTER] to exit (values will not be stored otherwise).")
}
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
line := scanner.Text()
if line == "" && bloomParams.interactive {
break
}
if bloomParams.split {
values := strings.Split(line, bloomParams.delimiter)
for i, value := range values {
j := i - len(values)
if len(bloomParams.fields) > 0 {
if !contains(bloomParams.fields, i) && !contains(bloomParams.fields, j) {
continue
}
}
filter.Add([]byte(value))
}
} else {
filter.Add([]byte(line))
}
}
}
func readInputIntoData(filter *bloom.BloomFilter, bloomParams BloomParams) {
//we determine if the program is run interactively or within a pipe
stat, _ := os.Stdin.Stat()
var isTerminal = (stat.Mode() & os.ModeCharDevice) != 0
//if we are not in an interactive session and this is a terminal, we quit
if !bloomParams.interactive && isTerminal {
return
}
if bloomParams.interactive {
fmt.Println("Interactive mode: Enter a blank line [by pressing ENTER] to exit (values will not be stored otherwise).")
}
scanner := bufio.NewScanner(os.Stdin)
dataBuffer := bytes.NewBuffer([]byte(""))
for scanner.Scan() {
line := scanner.Bytes()
if len(line) == 0 && bloomParams.interactive {
break
}
dataBuffer.Write(line)
dataBuffer.Write([]byte("\n"))
}
filter.Data = dataBuffer.Bytes()
}
func insertIntoFilter(path string, bloomParams BloomParams) {
filter, err := bloom.LoadFilter(path, bloomParams.gzip)
if err != nil {
exitWithError(err.Error())
}
readValuesIntoFilter(filter, bloomParams)
err = bloom.WriteFilter(filter, path, bloomParams.gzip)
if err != nil {
exitWithError(err.Error())
}
}
func updateFilterData(path string, bloomParams BloomParams) {
filter, err := bloom.LoadFilter(path, bloomParams.gzip)
if err != nil {
exitWithError(err.Error())
}
readInputIntoData(filter, bloomParams)
err = bloom.WriteFilter(filter, path, bloomParams.gzip)
if err != nil {
exitWithError(err.Error())
}
}
func getFilterData(path string, bloomParams BloomParams) {
filter, err := bloom.LoadFilter(path, bloomParams.gzip)
if err != nil {
exitWithError(err.Error())
}
fmt.Print(string(filter.Data))
}
func contains(s []int, e int) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
func checkAgainstFilter(path string, bloomParams BloomParams) {
filter, err := bloom.LoadFilter(path, bloomParams.gzip)
if err != nil {
exitWithError(err.Error())
}
scanner := bufio.NewScanner(os.Stdin)
if bloomParams.interactive {
fmt.Println("Interactive mode: Enter a blank line [by pressing ENTER] to exit.")
}
for scanner.Scan() {
line := scanner.Text()
if line == "" && bloomParams.interactive {
break
}
var valuesToCheck []string
if bloomParams.split {
valuesToCheck = strings.Split(line, bloomParams.delimiter)
} else {
valuesToCheck = make([]string, 1)
valuesToCheck[0] = line
}
printed := false
prefix := ""
if bloomParams.interactive {
prefix = ">"
}
for i, value := range valuesToCheck {
j := i - len(valuesToCheck)
//we only check fields that are in the "fields" parameters (if defined)
if len(bloomParams.fields) > 0 {
if !contains(bloomParams.fields, i) && !contains(bloomParams.fields, j) {
continue
}
}
if filter.Check([]byte(value)) {
if bloomParams.printEachMatch {
fmt.Printf("%s%s\n", prefix, value)
} else {
if !printed {
if len(bloomParams.printFields) > 0 {
values := make([]string, 0, len(bloomParams.printFields))
for _, i := range bloomParams.printFields {
j := i
if j < 0 {
j = j + len(valuesToCheck)
}
if j >= len(valuesToCheck) || j < 0 {
continue
}
values = append(values, valuesToCheck[j])
}
fmt.Printf("%s%s\n", prefix, strings.Join(values, bloomParams.delimiter))
} else {
fmt.Printf("%s%s\n", prefix, line)
}
}
printed = true
}
}
}
}
}
func printStats(path string, bloomParams BloomParams) {
filter, err := bloom.LoadFilter(path, bloomParams.gzip)
if err != nil {
exitWithError(err.Error())
}
fmt.Printf("File:\t\t\t%s\n", path)
fmt.Printf("Capacity:\t\t%d\n", filter.MaxNumElements())
fmt.Printf("Elements present:\t%d\n", filter.N)
fmt.Printf("FP probability:\t\t%.2e\n", filter.FalsePositiveProb())
fmt.Printf("Bits:\t\t\t%d\n", filter.NumBits())
fmt.Printf("Hash functions:\t\t%d\n", filter.NumHashFuncs())
}
func createFilter(path string, n uint64, p float64, bloomParams BloomParams) {
filter := bloom.Initialize(n, p)
readValuesIntoFilter(&filter, bloomParams)
err := bloom.WriteFilter(&filter, path, bloomParams.gzip)
if err != nil {
exitWithError(err.Error())
}
}
func joinFilters(path string, pathToAdd string, bloomParams BloomParams) {
filter, err := bloom.LoadFilter(path, bloomParams.gzip)
if err != nil {
exitWithError(err.Error())
}
filter2, err := bloom.LoadFilter(pathToAdd, bloomParams.gzip)
if err != nil {
exitWithError(err.Error())
}
err = filter.Join(filter2)
if err != nil {
exitWithError(err.Error())
}
err = bloom.WriteFilter(filter, path, bloomParams.gzip)
if err != nil {
exitWithError(err.Error())
}
}
func parseFieldIndexes(s string) ([]int, error) {
fields := strings.Split(s, ",")
fieldNumbers := make([]int, len(fields))
for i, field := range fields {
num, err := strconv.Atoi(field)
if err != nil {
return nil, err
}
fieldNumbers[i] = num
}
return fieldNumbers, nil
}
func parseBloomParams(c *cli.Context) BloomParams {
var bloomParams BloomParams
var err error
bloomParams.gzip = c.GlobalBool("gzip")
bloomParams.interactive = c.GlobalBool("interactive")
bloomParams.split = c.GlobalBool("split")
bloomParams.delimiter = c.GlobalString("delimiter")
bloomParams.printEachMatch = c.GlobalBool("each")
if c.GlobalString("fields") != "" {
bloomParams.fields, err = parseFieldIndexes(c.GlobalString("fields"))
if err != nil {
exitWithError(err.Error())
}
}
if c.GlobalString("print-fields") != "" {
bloomParams.printFields, err = parseFieldIndexes(c.GlobalString("print-fields"))
if err != nil {
exitWithError(err.Error())
}
//if printFields is set we also set printEachMatch
if len(bloomParams.printFields) > 0 {
bloomParams.printEachMatch = false
}
}
return bloomParams
}
func main() {
app := cli.NewApp()
app.Name = "Bloom Filter"
app.Usage = "Utility to work with bloom filters"
app.Flags = []cli.Flag{
cli.BoolFlag{
Name: "gzip, gz",
Usage: "compress bloom file with gzip",
},
cli.BoolFlag{
Name: "interactive, i",
Usage: "interactively add values to the filter",
},
cli.BoolFlag{
Name: "split, s",
Usage: "split the input string",
},
cli.BoolFlag{
Name: "each, e",
Usage: "print each match of a split string individually",
},
cli.StringFlag{
Name: "delimiter, d",
Value: ",",
Usage: "delimiter to use for splitting",
},
cli.StringFlag{
Name: "fields, f",
Value: "",
Usage: "fields of split output to use in filter (a single number or a comma-separated list of numbers, zero-indexed)",
},
cli.StringFlag{
Name: "print-fields, pf",
Value: "",
Usage: "fields of split output to print for a successful match (a single number or a comma-separated list of numbers, zero-indexed).",
},
}
app.Commands = []cli.Command{
{
Name: "create",
Aliases: []string{"cr"},
Flags: []cli.Flag{
cli.Float64Flag{Name: "p", Value: 0.01, Usage: "The desired false positive probability."},
cli.Uint64Flag{Name: "n", Value: 10000, Usage: "The desired capacity."},
},
Usage: "Create a new Bloom filter and store it in the given filename.",
Action: func(c *cli.Context) error {
path := c.Args().First()
bloomParams := parseBloomParams(c)
if path == "" {
exitWithError("No filename given.")
}
path, err := filepath.Abs(path)
if err != nil {
return err
}
n := c.Uint64("n")
p := c.Float64("p")
if n < 0 {
exitWithError("n cannot be negative.")
}
if p < 0 || p > 1 {
exitWithError("p must be between 0 and 1.")
}
createFilter(path, n, p, bloomParams)
return nil
},
},
{
Name: "insert",
Aliases: []string{"i"},
Flags: []cli.Flag{},
Usage: "Inserts new values into an existing Bloom filter.",
Action: func(c *cli.Context) error {
path := c.Args().First()
bloomParams := parseBloomParams(c)
if path == "" {
exitWithError("No filename given.")
}
path, err := filepath.Abs(path)
if err != nil {
return err
}
insertIntoFilter(path, bloomParams)
return nil
},
},
{
Name: "join",
Aliases: []string{"j", "merge", "m"},
Flags: []cli.Flag{},
Usage: "Joins two Bloom filters into one.",
Action: func(c *cli.Context) error {
if len(c.Args()) != 2 {
exitWithError("Two filenames are required.")
}
bloomParams := parseBloomParams(c)
path := c.Args().First()
if path == "" {
exitWithError("No first filename given.")
}
path, err := filepath.Abs(path)
if err != nil {
return err
}
pathToAdd := c.Args().Get(1)
if pathToAdd == "" {
exitWithError("No second filename given.")
}
pathToAdd, err = filepath.Abs(pathToAdd)
if err != nil {
return err
}
joinFilters(path, pathToAdd, bloomParams)
return nil
},
},
{
Name: "check",
Aliases: []string{"c"},
Flags: []cli.Flag{},
Usage: "Checks values against an existing Bloom filter.",
Action: func(c *cli.Context) error {
path := c.Args().First()
bloomParams := parseBloomParams(c)
if path == "" {
exitWithError("No filename given.")
}
path, err := filepath.Abs(path)
if err != nil {
return err
}
checkAgainstFilter(path, bloomParams)
return nil
},
},
{
Name: "set-data",
Aliases: []string{"sd"},
Flags: []cli.Flag{},
Usage: "Sets the data associated with the Bloom filter.",
Action: func(c *cli.Context) error {
path := c.Args().First()
bloomParams := parseBloomParams(c)
if path == "" {
exitWithError("No filename given.")
}
path, err := filepath.Abs(path)
if err != nil {
return err
}
updateFilterData(path, bloomParams)
return nil
},
},
{
Name: "get-data",
Aliases: []string{"gd"},
Flags: []cli.Flag{},
Usage: "Prints the data associated with the Bloom filter.",
Action: func(c *cli.Context) error {
path := c.Args().First()
bloomParams := parseBloomParams(c)
if path == "" {
exitWithError("No filename given.")
}
path, err := filepath.Abs(path)
if err != nil {
return err
}
getFilterData(path, bloomParams)
return nil
},
},
{
Name: "show",
Aliases: []string{"s"},
Flags: []cli.Flag{},
Usage: "Shows various details about a given Bloom filter.",
Action: func(c *cli.Context) error {
path := c.Args().First()
bloomParams := parseBloomParams(c)
if path == "" {
exitWithError("No filename given.")
}
path, err := filepath.Abs(path)
if err != nil {
return err
}
printStats(path, bloomParams)
return nil
},
},
}
app.Version = "0.2.4"
app.Run(os.Args)
}
|