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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
|
package MaxMind::DB::Writer::Tree;
use strict;
use warnings;
use namespace::autoclean;
use autodie;
our $VERSION = '0.300003';
use IO::Handle;
use Math::Int64 0.51;
use Math::Int128 0.21 qw( uint128 );
use MaxMind::DB::Common 0.031003 qw(
DATA_SECTION_SEPARATOR
METADATA_MARKER
);
use MaxMind::DB::Metadata;
use MaxMind::DB::Writer::Serializer;
use MaxMind::DB::Writer::Util qw( key_for_data );
use MooseX::Params::Validate qw( validated_list );
use Sereal::Decoder qw( decode_sereal );
use Sereal::Encoder qw( encode_sereal );
use Moose;
use Moose::Util::TypeConstraints;
use MooseX::StrictConstructor;
use XSLoader;
## no critic (ProhibitCallsToUnexportedSubs)
XSLoader::load( __PACKAGE__, $VERSION );
## use critic
has ip_version => (
is => 'ro',
isa => 'Int',
required => 1,
);
#<<<
my $RecordSizeType = subtype
as 'Int',
where { ( $_ % 4 == 0 ) && $_ >= 24 && $_ <= 128 },
message {
'The record size must be a number from 24-128 that is divisible by 4';
};
#>>>
has record_size => (
is => 'ro',
isa => $RecordSizeType,
required => 1,
);
my $MergeStrategyEnum
= enum( [qw( add-only-if-parent-exists none recurse toplevel )] );
has merge_strategy => (
is => 'ro',
isa => $MergeStrategyEnum,
lazy => 1,
default => 'none',
);
has remove_reserved_networks => (
is => 'ro',
isa => 'Bool',
default => 1,
);
has _tree => (
is => 'ro',
lazy => 1,
builder => '_build_tree',
predicate => '_has_tree',
);
# All records in the tree will point to a value of this type in the data
# section.
has _root_data_type => (
is => 'ro',
isa => 'Str', # XXX - should make sure it's valid type
init_arg => 'root_data_type',
default => 'map',
);
has map_key_type_callback => (
is => 'ro',
isa => 'CodeRef',
required => 1,
);
has database_type => (
is => 'ro',
isa => 'Str',
required => 1,
);
has languages => (
is => 'ro',
isa => 'ArrayRef[Str]',
default => sub { [] },
);
has description => (
is => 'ro',
isa => 'HashRef[Str]',
required => 1,
);
has alias_ipv6_to_ipv4 => (
is => 'ro',
isa => 'Bool',
default => 0,
);
has _serializer => (
is => 'ro',
isa => 'MaxMind::DB::Writer::Serializer',
init_arg => undef,
lazy => 1,
builder => '_build_serializer',
);
# This is an attribute so that we can explicitly set it from test code when we
# want to compare the binary output for two trees that we want to be
# identical.
has _build_epoch => (
is => 'rw',
writer => '_set_build_epoch',
isa => 'Int',
lazy => 1,
default => sub { time() },
);
around BUILDARGS => sub {
my $orig = shift;
my $class = shift;
my $args = $class->$orig(@_);
if ( exists $args->{merge_record_collisions} ) {
warn
'merge_record_collisions is deprecated. Use merge_strategy instead.';
}
return $args unless exists $args->{merge_record_collisions};
my $merge_record_collisions = delete $args->{merge_record_collisions};
if ( $args->{merge_strategy}
&& !( $args->{merge_strategy} eq 'none' xor $merge_record_collisions )
) {
die sprintf(
'merge_strategy cannot be "%s" if merge_record_collisions is "%s"',
$args->{merge_strategy}, $args->{merge_record_collisions}
);
}
$args->{merge_strategy} //=
$merge_record_collisions ? 'toplevel' : 'none';
return $args;
};
# The XS code expects $self->{_tree} to be populated.
sub BUILD {
$_[0]->_tree();
}
sub _build_tree {
my $self = shift;
return _create_tree(
$self->ip_version,
$self->record_size,
$self->merge_strategy,
$self->alias_ipv6_to_ipv4,
$self->remove_reserved_networks,
);
}
sub merge_record_collisions {
warn
'merge_record_collisions is deprecated and will be removed in a future release';
return $_[0]->merge_strategy ne 'none';
}
sub insert_network {
my $self = shift;
my $network = shift;
my $data = shift;
my $args = shift // {};
my ( $ip_address, $prefix_length ) = split qr{/}, $network, 2;
if ( !defined $prefix_length
|| int($prefix_length) != $prefix_length
|| $prefix_length < 0
|| $prefix_length > 128 ) {
die "Invalid network inserted: $network";
}
my $merge_strategy = %{$args} ? $self->_merge_strategy($args) : q{};
$self->_insert_network(
$ip_address,
$prefix_length,
key_for_data($data),
$data,
$merge_strategy,
);
return;
}
sub insert_range {
my $self = shift;
my $start_ip_address = shift;
my $end_ip_address = shift;
my $data = shift;
my $args = shift // {};
my $merge_strategy = %{$args} ? $self->_merge_strategy($args) : q{};
$self->_insert_range(
$start_ip_address,
$end_ip_address,
key_for_data($data),
$data,
$merge_strategy,
);
return;
}
sub _merge_strategy {
my $self = shift;
my $args = shift;
if ( ( $args->{insert_only_if_parent_exists} ? 1 : 0 )
+ ( $args->{force_overwrite} ? 1 : 0 )
+ ( $args->{merge_strategy} ? 1 : 0 ) > 1 ) {
die 'Only one of merge_strategy, force_overwrite, or '
. 'insert_only_if_parent_exists can be set at a time';
}
if ( $args->{insert_only_if_parent_exists} ) {
warn 'The argument insert_only_if_parent_exists is deprecated. '
. 'Use the merge_strategy "add-if-parent-exists" instead.';
return 'add-only-if-parent-exists';
}
if ( $args->{force_overwrite} ) {
warn 'The argument force_overwrite is deprecated. '
. 'Use the merge_strategy "none" instead.';
return 'none';
}
return undef unless $args->{merge_strategy};
die "Unknown merge strategy: $args->{merge_strategy}"
unless $MergeStrategyEnum->check( $args->{merge_strategy} );
return $args->{merge_strategy};
}
sub remove_network {
my $self = shift;
my $network = shift;
my ( $ip_address, $prefix_length ) = split qr{/}, $network, 2;
$self->_remove_network(
$ip_address,
$prefix_length,
);
return;
}
sub _build_serializer {
my $self = shift;
return MaxMind::DB::Writer::Serializer->new(
map_key_type_callback => $self->map_key_type_callback(),
);
}
sub write_tree {
my $self = shift;
my $output = shift;
$self->_write_search_tree(
$output,
$self->_root_data_type(),
$self->_serializer(),
);
$output->print(
DATA_SECTION_SEPARATOR,
${ $self->_serializer()->buffer() },
METADATA_MARKER,
$self->_encoded_metadata(),
);
}
{
my %key_types = (
binary_format_major_version => 'uint16',
binary_format_minor_version => 'uint16',
build_epoch => 'uint64',
database_type => 'utf8_string',
description => 'map',
ip_version => 'uint16',
languages => [ 'array', 'utf8_string' ],
node_count => 'uint32',
record_size => 'uint16',
);
my $type_callback = sub {
return $key_types{ $_[0] } || 'utf8_string';
};
sub _encoded_metadata {
my $self = shift;
my $metadata = MaxMind::DB::Metadata->new(
binary_format_major_version => 2,
binary_format_minor_version => 0,
build_epoch => uint128( $self->_build_epoch() ),
database_type => $self->database_type(),
description => $self->description(),
ip_version => $self->ip_version(),
languages => $self->languages(),
node_count => $self->node_count(),
record_size => $self->record_size(),
);
my $serializer = MaxMind::DB::Writer::Serializer->new(
map_key_type_callback => $type_callback,
);
$serializer->store_data( 'map', $metadata->metadata_to_encode() );
return ${ $serializer->buffer() };
}
}
{
my %do_not_freeze = map { $_ => 1 } qw(
map_key_type_callback
_tree
);
sub freeze_tree {
my $self = shift;
my $filename = shift;
my %constructor_params;
for my $attr ( $self->meta()->get_all_attributes() ) {
next unless $attr->init_arg();
next if $do_not_freeze{ $attr->name() };
my $reader = $attr->get_read_method();
$constructor_params{ $attr->init_arg() } = $self->$reader();
}
my $frozen = encode_sereal( \%constructor_params );
$self->_freeze_tree( $filename, $frozen, length $frozen );
return;
}
}
sub new_from_frozen_tree {
my $class = shift;
my (
$filename, $callback, $database_type, $description, $merge_strategy,
$record_size
)
= validated_list(
\@_,
filename => { isa => 'Str' },
map_key_type_callback => { isa => 'CodeRef' },
database_type => { isa => 'Str', optional => 1 },
description => { isa => 'HashRef[Str]', optional => 1 },
merge_strategy => { isa => $MergeStrategyEnum, optional => 1 },
record_size => { isa => $RecordSizeType, optional => 1 },
);
## no critic (InputOutput::RequireBriefOpen)
open my $fh, '<:raw', $filename or die $!;
my $packed_params_size;
unless ( read( $fh, $packed_params_size, 4 ) == 4 ) {
die "Could not read 4 bytes from $filename: $!";
}
my $params_size = unpack( 'L', $packed_params_size );
my $frozen_params;
unless ( read( $fh, $frozen_params, $params_size ) == $params_size ) {
die "Could not read $params_size bytes from $filename: $!";
}
close $fh or die $!;
my $params = decode_sereal($frozen_params);
$params->{database_type} = $database_type if defined $database_type;
$params->{description} = $description if defined $description;
$params->{record_size} = $record_size if defined $record_size;
if ( defined $merge_strategy ) {
$params->{merge_strategy} = $merge_strategy;
}
elsif ( $params->{merge_record_collisions} ) {
# This is for backwards compatibility with frozen trees created before
# "merge_strategy" was added.
$params->{merge_strategy} = 'toplevel';
}
my $tree = _thaw_tree(
$filename,
$params_size + 4,
@{$params}{
qw(
ip_version
record_size
merge_strategy
alias_ipv6_to_ipv4
remove_reserved_networks
)
},
);
return $class->new(
%{$params},
map_key_type_callback => $callback,
_tree => $tree,
);
}
sub DEMOLISH {
my $self = shift;
$self->_free_tree()
if $self->_has_tree();
return;
}
__PACKAGE__->meta()->make_immutable();
1;
# ABSTRACT: Tree representing a MaxMind DB database in memory - then write it to a file
__END__
=pod
=encoding UTF-8
=head1 NAME
MaxMind::DB::Writer::Tree - Tree representing a MaxMind DB database in memory - then write it to a file
=head1 VERSION
version 0.300003
=head1 SYNOPSIS
use MaxMind::DB::Writer::Tree;
my %types = (
color => 'utf8_string',
dogs => [ 'array', 'utf8_string' ],
size => 'uint16',
);
my $tree = MaxMind::DB::Writer::Tree->new(
ip_version => 6,
record_size => 24,
database_type => 'My-IP-Data',
languages => ['en'],
description => { en => 'My database of IP data' },
map_key_type_callback => sub { $types{ $_[0] } },
);
$tree->insert_network(
'8.8.8.0/24',
{
color => 'blue',
dogs => [ 'Fido', 'Ms. Pretty Paws' ],
size => 42,
},
);
open my $fh, '>:raw', '/path/to/my-ip-data.mmdb';
$tree->write_tree($fh);
=head1 DESCRIPTION
This is the main class you'll use to write L<MaxMind DB database
files|http://maxmind.github.io/MaxMind-DB/>. This class represents the
database in memory. Once you've created the full tree you can write to a file.
=head1 API
This class provides the following methods:
=head2 MaxMind::DB::Writer::Tree->new()
This creates a new tree object. The constructor accepts the following
parameters:
=over 4
=item * ip_version
The IP version for the database. It must be 4 or 6.
This parameter is required.
=item * record_size
This is the record size in I<bits>. This should be one of 24, 28, 32 (in
theory any number divisible by 4 up to 128 will work but the available readers
all expect 24-32).
This parameter is required.
=item * database_type
This is a string containing the database type. This can be anything,
really. MaxMind uses strings like "GeoIP2-City", "GeoIP2-Country", etc.
This parameter is required.
=item * languages
This should be an array reference of languages used in the database, like
"en", "zh-TW", etc. This is useful as metadata for database readers and end users.
This parameter is optional.
=item * description
This is a hashref where the keys are language names and the values are
descriptions of the database in that language. For example, you might have
something like:
{
en => 'My IP data',
fr => q{Mon Data d'IP},
}
This parameter is required.
=item * map_key_type_callback
This is a subroutine reference that is called in order to determine how to
store each value in a map (hash) data structure. See L<DATA TYPES> below for
more details.
This parameter is required.
=item * merge_record_collisions
By default, when an insert collides with a previous insert, the new data
simply overwrites the old data where the two networks overlap.
If this is set to true, then on a collision, the writer will merge the old
data with the new data. The merge strategy employed is controlled by the
C<merge_strategy> attribute, described below.
This parameter is optional. It defaults to false unless C<merge_strategy> is
set to something other than C<none>.
This parameter is deprecated. New code should just set C<merge_strategy>
directly.
B<This parameter is deprecated. Use C<merge_strategy> instead.>
=item * merge_strategy
Controls what merge strategy is employed.
=over 8
=item * none
No merging will be done. C<merge_record_collisions> must either be not set or
set to false.
=item * toplevel
If both data structures are hashrefs then the data from the top level keys in
the new data structure are copied over to the existing data structure,
potentially replacing any existing values for existing keys completely.
=item * recurse
Recursively merges the new data structure with the old data structure. Hash
values and array elements are either - in the case of simple values - replaced
with the new values, or - in the case of complex structures - have their values
recursively merged.
For example if this data is originally inserted for an IP range:
{
families => [ {
husband => 'Fred',
wife => 'Wilma',
}, ],
year => 1960,
}
And then this subsequent data is inserted for a range covered by the previous
IP range:
{
families => [ {
wife => 'Wilma',
child => 'Pebbles',
}, {
husband => 'Barney',
wife => 'Betty',
child => 'Bamm-Bamm',
}, ],
company => 'Hanna-Barbera Productions',
}
Then querying within the range will produce the results:
{
families => [ {
husband => 'Fred',
wife => 'Wilma', # note replaced value
child => 'Pebbles',
}, {
husband => 'Barney',
wife => 'Betty',
child => 'Bamm-Bamm',
}, ],
year => 1960,
company => 'Hanna-Barbera Productions',
}
=item * add-only-if-parent-exists
With this merge strategy, data will only be inserted when there is already a
record for the network (or sub-network). Similarly, when merging the data
record with an existing data record, no new hash or array references will be
created within the data record for the new data. For instance, if the original
data record is C<{parent_a => {sibling => 1}}> and C<{parent_a => {child_a =>
1}, parent_b => {child_b => 1}}> is inserted, only C<child_a>, not C<child_b>,
will appear in the merged record.
This option is intended to be used when inserting data that supplements
existing data but that is not independently useful.
=back
In all merge strategies attempting to merge two differing data structures
causes an exception.
This parameter is optional. If C<merge_record_collisions> is true, this
defaults to C<toplevel>; otherwise, it defaults to C<none>.
=item * alias_ipv6_to_ipv4
If this is true then the final database will map some IPv6 ranges to the IPv4
range. These ranges are:
=over 8
=item * ::ffff:0:0/96
This is the IPv4-mapped IPv6 range
=item * 2001::/32
This is the Teredo range. Note that lookups for Teredo ranges will find the
Teredo server's IPv4 address, not the client's IPv4.
=item * 2002::/16
This is the 6to4 range
=back
When aliasing is enabled, insertions into the aliased locations will throw an
exception. Inserting a network containing them does not throw an exception, but
no information will be stored for the aliased locations.
To insert an IPv4 address, insert it using IPv4 notation or insert
directly into ::/96.
Aliased nodes are I<not> followed when merging nodes. Only merges into the
original IPv4 location, ::/96, will be followed.
This parameter is optional. It defaults to false.
=item * remove_reserved_networks
If this is true, reserved networks may not be inserted.
Attempts to insert these networks or any inside them will be silently ignored.
Inserting a network containing them does not throw an exception, but no
information will be stored for the reserved sections.
Reserved networks that are globally routable to an individual device, such as
Teredo, may still be added.
This parameter is optional. It defaults to true.
=back
=head2 $tree->insert_network( $network, $data, $additional_args )
This method expects two parameters. The first is a network in CIDR notation.
The second can be any Perl data structure (except a coderef, glob, or
filehandle).
The C<$data> payload is encoded according to the L<MaxMind DB database format
spec|http://maxmind.github.io/MaxMind-DB/>. The short overview is that
anything that can be encoded in JSON can be stored in an MMDB file. It can
also handle unsigned 64-bit and 128-bit integers if they are passed as
L<Math::UInt128|Math::Int128> objects.
C<$additional_args> is a hash reference containing additional arguments that
change the behavior of the insert. The following arguments are supported:
=over 3
=item * C<merge_strategy>
When set, the tree's default merge strategy will be overridden for the
insertion with this merge strategy.
=item * C<force_overwrite>
This make the merge strategy for the insert C<none>.
B<This option is deprecated.>
=item * C<insert_only_if_parent_exists>
This make the merge strategy for the insert C<add-only-if-parent-exists>.
B<This option is deprecated.>
=back
=head3 Insert Order, Merging, and Overwriting
When C<merge_strategy> is I<none>, the last insert "wins". This
means that if you insert C<1.2.3.255/32> and then C<1.2.3.0/24>, the data for
C<1.2.3.255/24> will overwrite the data you previously inserted for
C<1.2.3.255/232>. On the other hand, if you insert C<1.2.3.255/32> last, then
the tree will be split so that the C<1.2.3.0 - 1.2.3.254> range has different
data than C<1.2.3.255>.
In this scenario, if you want to make sure that no data is overwritten then
you need to sort your input by network prefix length.
When C<merge_strategy> is not I<none>, then records will be merged based on
the particular strategy. For instance, the C<1.2.3.255/32> network will end up
with its data plus the data provided for the C<1.2.3.0/24> network, while
C<1.2.3.0 - 1.2.3.254> will have the expected data. The merge strategy can be
changed on a per-insert basis by using the C<merge_strategy> argument when
inserting a network as discussed above.
=head2 $tree->insert_range( $first_ip, $last_ip, $data, $additional_args )
This method is similar to C<insert_network()>, except that it takes an IP
range rather than a network. The first parameter is the first IP address in
the range. The second is the last IP address in the range. The third is a
Perl data structure containing the data to be inserted. The final parameter
are additional arguments, as outlined for C<insert_network()>.
=head2 $tree->remove_network( $network )
This method removes the network from the database. It takes one parameter, the
network in CIDR notation.
=head2 $tree->write_tree($fh)
Given a filehandle, this method writes the contents of the tree as a MaxMind
DB database to that filehandle.
=head2 $tree->iterate($object)
This method iterates over the tree by calling methods on the passed
object. The object must have at least one of the following three methods:
C<process_empty_record>, C<process_node_record>, C<process_data_record>.
The iteration is done in depth-first order, which means that it visits each
network in order.
Each method on the object is called with the following position parameters:
=over 4
=item
The node number as a 64-bit number.
=item
A boolean indicating whether or not this is the right or left record for the
node. True for right, false for left.
=item
The first IP number in the node's network as a 128-bit number.
=item
The prefix length for the node's network.
=item
The first IP number in the record's network as a 128-bit number.
=item
The prefix length for the record's network.
=back
If the record is a data record, the final argument will be the Perl data
structure associated with the record.
The record's network is what matches with a given data structure for data
records.
For node (and alias) records, the final argument will be the number of the
node that this record points to.
For empty records, there are no additional arguments.
=head2 $tree->freeze_tree($filename)
Given a file name, this method freezes the tree to that file. Unlike the
C<write_tree()> method, this method does write out a MaxMind DB file. Instead,
it writes out something that can be quickly thawed via the C<<
MaxMind::DB::Writer::Tree->new_from_frozen_tree >> constructor. This is useful if
you want to pass the in-memory representation of the tree between processes.
=head2 $tree->ip_version()
Returns the tree's IP version, as passed to the constructor.
=head2 $tree->record_size()
Returns the tree's record size, as passed to the constructor.
=head2 $tree->merge_record_collisions()
Returns a boolean indicating whether the tree will merge colliding records, as
determined by the merge strategy.
B<This is deprecated.>
=head2 $tree->merge_strategy()
Returns the merge strategy used when two records collide.
=head2 $tree->map_key_type_callback()
Returns the callback used to determine the type of a map's values, as passed
to the constructor.
=head2 $tree->database_type()
Returns the tree's database type, as passed to the constructor.
=head2 $tree->languages()
Returns the tree's languages, as passed to the constructor.
=head2 $tree->description()
Returns the tree's description hashref, as passed to the constructor.
=head2 $tree->alias_ipv6_to_ipv4()
Returns a boolean indicating whether the tree will alias some IPv6 ranges to
their corresponding IPv4 ranges when the tree is written to disk.
=head2 MaxMind::DB::Writer::Tree->new_from_frozen_tree()
This method constructs a tree from a file containing a frozen tree.
This method accepts the following parameters:
=over 4
=item * filename
The filename containing the frozen tree.
This parameter is required.
=item * map_key_type_callback
This is a subroutine reference that is called in order to determine how to
store each value in a map (hash) data structure. See L<DATA TYPES> below for
more details.
This needs to be passed because subroutine references cannot be reliably
serialized and restored between processes.
This parameter is required.
=item * database_type
Override the C<<database_type>> of the frozen tree. This accepts a string of
the same form as the C<<new()>> constructor.
This parameter is optional.
=item * description
Override the C<<description>> of the frozen tree. This accepts a hashref of
the same form as the C<<new()>> constructor.
This parameter is optional.
=item * merge_strategy
Override the C<<merge_strategy>> setting for the frozen tree.
This parameter is optional.
=back
=head2 Caveat for Freeze/Thaw
The frozen tree is more or less the raw C data structures written to disk. As
such, it is very much not portable, and your ability to thaw a tree on a
machine not identical to the one on which it was written is not guaranteed.
In addition, there is no guarantee that the freeze/thaw format will be stable
across different versions of this module.
=head1 DATA TYPES
The MaxMind DB file format is strongly typed. Because Perl is not strongly
typed, you will need to explicitly specify the types for each piece of
data. Currently, this class assumes that your top-level data structure for an
IP address will always be a map (hash). You can then provide a
C<map_key_type_callback> subroutine that will be called as the data is
serialized. This callback is given a key name and is expected to return that
key's data type.
Let's use the following structure as an example:
{
names => {
en => 'United States',
es => 'Estados Unidos',
},
population => 319_000_000,
fizzle_factor => 65.7294,
states => [ 'Alabama', 'Alaska', ... ],
}
Given this data structure, our C<map_key_type_callback> might look something like this:
my %types = (
names => 'map',
en => 'utf8_string',
es => 'utf8_string',
population => 'uint32',
fizzle_factor => 'double',
states => [ 'array', 'utf8_string' ],
);
sub {
my $key = shift;
return $type{$key};
}
If the callback returns C<undef>, the serialization code will throw an
error. Note that for an array we return a 2 element arrayref where the first
element is C<'array'> and the second element is the type of content in the
array.
The valid types are:
=over 4
=item * utf8_string
=item * uint16
=item * uint32
=item * uint64
=item * uint128
=item * int32
=item * double
64 bits of precision.
=item * float
32 bits of precision.
=item * boolean
=item * map
=item * array
=back
=head1 SUPPORT
Bugs may be submitted through L<https://github.com/maxmind/MaxMind-DB-Writer-perl/issues>.
=head1 AUTHORS
=over 4
=item *
Olaf Alders <oalders@maxmind.com>
=item *
Greg Oschwald <goschwald@maxmind.com>
=item *
Dave Rolsky <drolsky@maxmind.com>
=item *
Mark Fowler <mfowler@maxmind.com>
=back
=head1 COPYRIGHT AND LICENSE
This software is copyright (c) 2018 by MaxMind, Inc.
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
=cut
|