This repository has been archived by the owner on Dec 22, 2021. It is now read-only.
/
MongoClient.pm
1277 lines (950 loc) · 35.2 KB
/
MongoClient.pm
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 2009-2013 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.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.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package MongoDB::MongoClient;
# ABSTRACT: A connection to a MongoDB server
use version;
our $VERSION = 'v0.703.5'; # TRIAL
use Moose;
use Moose::Util::TypeConstraints;
use MongoDB;
use MongoDB::Cursor;
use MongoDB::BSON::Binary;
use MongoDB::BSON::Regexp;
use Digest::MD5;
use Tie::IxHash;
use Carp 'carp', 'croak';
use Scalar::Util 'reftype';
use boolean;
use Encode;
use Try::Tiny;
use constant {
PRIMARY => 0,
SECONDARY => 1,
PRIMARY_PREFERRED => 2,
SECONDARY_PREFERRED => 3,
NEAREST => 4
};
use constant _READPREF_MODENAMES => ['primary',
'secondary',
'primaryPreferred',
'secondaryPreferred',
'nearest'];
has host => (
is => 'ro',
isa => 'Str',
required => 1,
default => 'mongodb://localhost:27017',
);
has w => (
is => 'rw',
isa => 'Int|Str',
default => 1,
);
has wtimeout => (
is => 'rw',
isa => 'Int',
default => 1000,
);
has j => (
is => 'rw',
isa => 'Bool',
default => 0
);
has _readpref_mode => (
is => 'rw',
isa => 'Str',
default => MongoDB::MongoClient->PRIMARY
);
has _readpref_tagsets => (
is => 'rw',
isa => 'ArrayRef',
required => 0
);
has _readpref_pinned => (
is => 'rw',
isa => 'MongoDB::MongoClient',
required => 0
);
has _readpref_retries => (
is => 'ro',
isa => 'Int',
required => 1,
default => 3
);
has _readpref_pingfreq_sec => (
is => 'ro',
isa => 'Int',
required => 1,
default => 5
);
has port => (
is => 'ro',
isa => 'Int',
required => 1,
default => 27017,
);
has auto_reconnect => (
is => 'ro',
isa => 'Bool',
required => 1,
default => 1,
);
has auto_connect => (
is => 'ro',
isa => 'Bool',
required => 1,
default => 1,
);
has timeout => (
is => 'ro',
isa => 'Int',
required => 1,
default => 20000,
);
has username => (
is => 'rw',
isa => 'Str',
required => 0,
);
has password => (
is => 'rw',
isa => 'Str',
required => 0,
);
has db_name => (
is => 'rw',
isa => 'Str',
required => 1,
default => 'admin',
);
has query_timeout => (
is => 'rw',
isa => 'Int',
required => 1,
default => sub { return $MongoDB::Cursor::timeout; },
);
has max_bson_size => (
is => 'rw',
isa => 'Int',
required => 1,
default => 4194304
);
has find_master => (
is => 'ro',
isa => 'Bool',
required => 1,
default => 0,
);
has _is_mongos => (
is => 'rw',
isa => 'Bool',
required => 1,
default => 0
);
has _ismaster_version => (
is => 'rw',
isa => 'Int',
default => 0
);
has ssl => (
is => 'ro',
isa => 'Bool',
required => 1,
default => 0,
);
has sasl => (
is => 'ro',
isa => 'Bool',
required => 1,
default => 0
);
has sasl_mechanism => (
is => 'ro',
isa => subtype( Str => where { /^GSSAPI|PLAIN$/ } ),
required => 1,
default => 'GSSAPI',
);
# hash of servers in a set
# call connected() to determine if a connection is enabled
has _servers => (
is => 'rw',
isa => 'HashRef',
default => sub { {} },
);
# actual connection to a server in the set
has _master => (
is => 'rw',
# isa => 'MongoDB::Connection',
required => 0,
);
# cache our original constructor args in BUILD for creating
# new, per-host connections
has _opts => (
is => 'rw',
isa => 'HashRef',
default => sub { {} },
);
has ts => (
is => 'rw',
isa => 'Int',
default => 0
);
has dt_type => (
is => 'rw',
required => 0,
default => 'DateTime'
);
has inflate_dbrefs => (
is => 'rw',
isa => 'Bool',
required => 0,
default => 1
);
has inflate_regexps => (
is => 'rw',
isa => 'Bool',
required => 0,
default => 0,
);
# attributes for keeping track of client and server wire protocol versions
has min_wire_version => (
is => 'ro',
isa => 'Int',
required => 1,
default => 0
);
has max_wire_version => (
is => 'ro',
isa => 'Int',
required => 1,
default => 2
);
has _use_write_cmd => (
is => 'ro',
isa => 'Bool',
required => 1,
lazy_build => 1
);
sub BUILD {
my ($self, $opts) = @_;
eval "use ${_}" # no Any::Moose::load_class becase the namespaces already have symbols from the xs bootstrap
for qw/MongoDB::Database MongoDB::Cursor MongoDB::OID MongoDB::Timestamp/;
my @pairs;
# supported syntax (see http://docs.mongodb.org/manual/reference/connection-string/)
if ($self->host =~ m{ ^
mongodb://
(?: ([^:]*) : ([^@]*) @ )? # [username:password@]
([^/]*) # host1[:port1][,host2[:port2],...[,hostN[:portN]]]
(?:
/ ([^?]*) # /[database]
(?: [?] (.*) )? # [?options]
)?
$ }x ) {
my ($username, $password, $hostpairs, $database, $options) = ($1, $2, $3, $4, $5);
# we add these things to $opts as well as self so that they get propagated when we recurse for multiple servers
$self->username($opts->{username} = $username) if $username;
$self->password($opts->{password} = $password) if $password;
$self->db_name($opts->{db_name} = $database) if $database;
$hostpairs = 'localhost' unless $hostpairs;
@pairs = map { $_ .= ':27017' unless $_ =~ /:/ ; $_ } split ',', $hostpairs;
# TODO handle standard options from $options
}
# deprecated syntax
else {
push @pairs, $self->host.":".$self->port;
}
# We cache our updated constructor arguments because we need them again for
# creating new, per-host objects
$self->_opts( $opts );
# a simple single server is special-cased (so we don't recurse forever)
if (@pairs == 1 && !$self->find_master) {
my @hp = split ":", $pairs[0];
$self->_init_conn($hp[0], $hp[1], $self->ssl);
if ($self->auto_connect) {
$self->connect;
$self->_check_wire_version;
$self->max_bson_size($self->_get_max_bson_size);
}
return;
}
# multiple servers
my $connected = 0;
foreach (@pairs) {
# override host, find_master and auto_connect
my $args = {
%$opts,
host => "mongodb://$_",
find_master => 0,
auto_connect => 0,
};
$self->_servers->{$_} = MongoDB::MongoClient->new($args);
next unless $self->auto_connect;
# it's okay if we can't connect, so long as someone can
eval {
$self->_servers->{$_}->connect;
$self->_servers->{$_}->_check_wire_version;
$self->_servers->{$_}->max_bson_size($self->_servers->{$_}->_get_max_bson_size);
};
# at least one connection worked
if (!$@) {
$connected = 1;
}
}
my $master;
if ($self->auto_connect) {
# if we still aren't connected to anyone, give up
if (!$connected) {
die "couldn't connect to any servers listed: ".join(",", @pairs);
}
$master = $self->get_master;
if ($master == -1) {
die "couldn't find master";
}
else {
$self->max_bson_size($master->max_bson_size);
}
}
else {
# no auto-connect so just pick one. if auto-reconnect is set then it will connect as needed
($master) = values %{$self->_servers};
}
# create a struct that just points to the master's connection
$self->_init_conn_holder($master);
}
sub _build__use_write_cmd {
my $self = shift;
# find out if we support write commands
my $result = $self->get_database( "test" )->run_command( { insert => "test", documents => [ ] } );
return 1 if ref $result && $result->{ok} == 1;
return 0;
}
sub _get_max_bson_size {
my $self = shift;
my $buildinfo = $self->get_database('admin')->run_command({buildinfo => 1});
if (ref($buildinfo) eq 'HASH' && exists $buildinfo->{'maxBsonObjectSize'}) {
return $buildinfo->{'maxBsonObjectSize'};
}
# default: 4MB
return 4194304;
}
sub database_names {
my ($self) = @_;
my $ret = $self->get_database('admin')->run_command({ listDatabases => 1 });
if (ref($ret) eq 'HASH' && exists $ret->{databases}) {
return map { $_->{name} } @{ $ret->{databases} };
}
else {
die ($ret);
}
}
sub get_database {
my ($self, $database_name) = @_;
return MongoDB::Database->new(
_client => $self,
name => $database_name,
);
}
sub _get_a_specific_connection {
my ($self, $host) = @_;
if ($self->_servers->{$host}->connected) {
return $self->_servers->{$host};
}
eval {
$self->_servers->{$host}->connect;
};
if (!$@) {
return $self->_servers->{$host};
}
return 0;
}
sub _get_any_connection {
my ($self) = @_;
while ((my $key, my $value) = each(%{$self->_servers})) {
my $conn = $self->_get_a_specific_connection($key);
if ($conn) {
# force a reset of the iterator
my $reset = keys %{$self->_servers};
return $conn;
}
}
return 0;
}
sub get_master {
my ($self, $conn) = @_;
$conn = defined $conn ? $conn : $self->_get_any_connection();
# if we couldn't connect to anything, just return
if (!$conn) {
return -1;
}
# a single server or list of servers
if (!$self->find_master) {
$self->_master($conn);
return $self->_master;
}
# auto-detect master
else {
my $master = try {
$conn->get_database($self->db_name)->_try_run_command({"ismaster" => 1})
};
# check for errors
return -1 unless $master;
# msg field from ismaster command will
# be set if in a sharded environment
$self->_is_mongos(1) if $master->{'msg'};
# if this is a replica set & we haven't renewed the host list in 1 sec
if ($master->{'hosts'} && (!$master->{'setVersion'} || $master->{'setVersion'} > $self->_ismaster_version)) {
# update rs config version
if ($master->{'setVersion'}) {
$self->_ismaster_version($master->{'setVersion'});
}
# clear old host list before refreshing
%{$self->_servers} = ();
for (@{$master->{'hosts'}}) {
# override host, find_master and auto_connect
my $args = {
%{ $self->_opts },
host => "mongodb://$_",
find_master => 0,
auto_connect => 0,
};
$self->_servers->{$_} = MongoDB::MongoClient->new($args);
}
}
# if this is the master, whether or not it's a replica set, return it
if ($master->{'ismaster'}) {
$self->_master($conn);
return $self->_master;
}
elsif ($self->find_master && exists $master->{'primary'}) {
my $primary = $self->_get_a_specific_connection($master->{'primary'});
if (!$primary) {
return -1;
}
# double-check that this is master
my $result = try {
$primary->get_database("admin")->_try_run_command({"ismaster" => 1})
};
if ($result && $result->{'ismaster'}) {
$self->_master($primary);
return $self->_master;
}
}
}
return -1;
}
sub read_preference {
my ($self, $mode, $tagsets) = @_;
croak "Missing read preference mode" if @_ < 2;
croak "Unrecognized read preference mode: $mode" if $mode < 0 || $mode > 4;
croak "NEAREST read preference mode not supported" if $mode == MongoDB::MongoClient->NEAREST;
if (!$self->_is_mongos && (!$self->find_master || keys %{$self->_servers} < 2)) {
croak "Read preference must be used with a replica set; is find_master false?";
}
croak "PRIMARY cannot be combined with tags" if $mode == MongoDB::MongoClient->PRIMARY && $tagsets;
# only repin if mode or tagsets have changed
return if $mode == $self->_readpref_mode &&
defined $self->_readpref_tagsets &&
defined $tagsets &&
$tagsets == $self->_readpref_tagsets;
$self->_readpref_mode($mode);
$self->_readpref_tagsets($tagsets) if defined $tagsets;
$self->_readpref_tagsets([]) if !(defined $tagsets);
$self->repin();
}
sub _choose_secondary {
my ($self, $servers) = @_;
for (1 .. $self->_readpref_retries) {
my @secondaries = keys %{$servers};
return undef if @secondaries == 0;
my $secondary = $servers->{$secondaries[int(rand(scalar @secondaries))]};
if ($secondary->_check_ok(1)) {
return $secondary;
}
else {
delete $servers->{$secondary->host};
}
}
return undef;
}
sub _narrow_by_tagsets {
my ($self, $servers) = @_;
return unless @{$self->_readpref_tagsets};
my $conn = $self->_get_any_connection();
if (!$conn) {
# no connections available, clear the hash
undef %{$servers};
return;
}
my $replcoll = $conn->get_database('local')->get_collection('system.replset');
my $rsconf = $replcoll->find_one();
foreach my $conf (@{$rsconf->{'members'}}) {
next unless exists $conf->{'tags'};
my $member_matches = 0;
# see if any of the tagsets match the rs conf
TAGSET:
foreach my $tagset (@{$self->_readpref_tagsets}) {
foreach my $tagkey (keys %{$tagset}) {
next TAGSET unless exists $conf->{'tags'}->{$tagkey} &&
$tagset->{$tagkey} eq $conf->{'tags'}->{$tagkey};
}
$member_matches = 1;
}
# eliminate non-matching RS members
delete $servers->{'mongodb://' . $conf->{'host'}} unless $member_matches;
}
}
sub _check_ok {
my ($self, $retries) = @_;
foreach (1 .. $retries) {
my $status = try {
$self->get_database('admin')->_try_run_command({ping => 1});
};
return 1 if $status;
}
return 0;
}
sub repin {
my ($self) = @_;
if ($self->_is_mongos) {
$self->_readpref_pinned($self);
return;
}
$self->get_master if !$self->_master;
my %secondaries = %{$self->_servers};
foreach (keys %secondaries) {
my $value = $secondaries{$_};
$value->{'query_timeout'} = $self->query_timeout;
delete $secondaries{$_};
$secondaries{"mongodb://$_"} = $value;
}
my $primary = $secondaries{$self->_master->host};
delete $secondaries{$primary->host};
my $mode = $self->_readpref_mode;
# pin the primary or die
if ($mode == MongoDB::MongoClient->PRIMARY) {
if ($primary->_check_ok($self->_readpref_retries)) {
$self->_readpref_pinned($primary);
return;
}
else {
die "No replica set primary available for query with read_preference PRIMARY";
}
}
# pin an arbitrary secondary or die
elsif ($mode == MongoDB::MongoClient->SECONDARY) {
$self->_narrow_by_tagsets(\%secondaries);
my $secondary = $self->_choose_secondary(\%secondaries);
if ($secondary) {
$self->_readpref_pinned($secondary);
return;
}
else {
die "No replica set secondary available for query with read_preference SECONDARY";
}
}
# if no primary available, then pin an arbitrary secondary
elsif ($mode == MongoDB::MongoClient->PRIMARY_PREFERRED) {
if ($primary->_check_ok($self->_readpref_retries)) {
$self->_readpref_pinned($primary);
return;
}
else {
$self->_narrow_by_tagsets(\%secondaries);
my $secondary = $self->_choose_secondary(\%secondaries);
if ($secondary) {
$self->_readpref_pinned($secondary);
return;
}
}
}
# if no secondary available, then pin the primary
elsif ($mode == MongoDB::MongoClient->SECONDARY_PREFERRED) {
$self->_narrow_by_tagsets(\%secondaries);
my $secondary = $self->_choose_secondary(\%secondaries);
if ($secondary) {
$self->_readpref_pinned($secondary);
return;
}
elsif ($primary->_check_ok($self->_readpref_retries)) {
$self->_readpref_pinned($primary);
return;
}
}
die "No replica set members available for query";
}
sub rs_refresh {
my ($self) = @_;
# only refresh if connected directly
# to a replica set
return unless $self->find_master;
return unless $self->_readpref_pinned;
return if $self->_is_mongos;
# ping rs members, and repin if something has changed
my $repin_required = 0;
my $any_conn;
if (time() > ($self->ts + $self->_readpref_pingfreq_sec)) {
for (keys %{$self->_servers}) {
my $server = $self->_servers->{$_};
my $connected = $server->connected;
my $ok = $server->_check_ok(1);
if (($ok && !$connected) || (!$ok && $connected)) {
$repin_required = 1;
}
if ($ok && !$any_conn) {
$any_conn = $server;
}
}
$self->get_master($any_conn) if $any_conn;
}
$self->repin if $repin_required;
$self->ts(time());
}
sub authenticate {
my ($self, $dbname, $username, $password, $is_digest) = @_;
my $hash = $password;
# create a hash if the password isn't yet encrypted
if (!$is_digest) {
$hash = Digest::MD5::md5_hex("${username}:mongo:${password}");
}
# get the nonce
my $db = $self->get_database($dbname);
my $result = eval { $db->_try_run_command({getnonce => 1}) };
if (!$result) {
return $@
}
my $nonce = $result->{'nonce'};
my $digest = Digest::MD5::md5_hex($nonce.$username.$hash);
# run the login command
my $login = tie(my %hash, 'Tie::IxHash');
%hash = (authenticate => 1,
user => $username,
nonce => $nonce,
key => $digest);
$result = $db->run_command($login);
return $result;
}
sub fsync {
my ($self, $args) = @_;
$args ||= {};
# Pass this in as array-ref to ensure that 'fsync => 1' is the first argument.
return $self->get_database('admin')->run_command([fsync => 1, %$args]);
}
sub fsync_unlock {
my ($self) = @_;
# Have to fetch from a special collection to unlock.
return $self->get_database('admin')->get_collection('$cmd.sys.unlock')->find_one();
}
sub _w_want_safe {
my ( $self ) = @_;
my $w = $self->w;
return 0 if $w =~ /^-?\d+$/ && $w <= 0;
return 1;
}
sub _sasl_check {
my ( $self, $res ) = @_;
die "Invalid SASL response document from server:"
unless reftype $res eq reftype { };
if ( $res->{ok} != 1 ) {
die "SASL authentication error: $res->{errmsg}";
}
return $res->{conversationId};
}
sub _sasl_start {
my ( $self, $payload, $mechanism ) = @_;
# warn "SASL start, payload = [$payload], mechanism = [$mechanism]\n";
my $res = $self->get_database( '$external' )->run_command( [
saslStart => 1,
mechanism => $mechanism,
payload => $payload,
autoAuthorize => 1 ] );
$self->_sasl_check( $res );
return $res;
}
sub _sasl_continue {
my ( $self, $payload, $conv_id ) = @_;
# warn "SASL continue, payload = [$payload], conv ID = [$conv_id]";
my $res = $self->get_database( '$external' )->run_command( [
saslContinue => 1,
conversationId => $conv_id,
payload => $payload
] );
$self->_sasl_check( $res );
return $res;
}
sub _sasl_plain_authenticate {
my ( $self ) = @_;
my $username = defined $self->username ? $self->username : "";
my $password = defined $self->password ? $self->password : "";
my $auth_bytes = encode( "UTF-8", "\x00" . $username . "\x00" . $password );
my $payload = MongoDB::BSON::Binary->new( data => $auth_bytes );
$self->_sasl_start( $payload, "PLAIN" );
}
sub _check_wire_version {
my ( $self ) = @_;
# check our wire protocol version compatibility
my $master = $self->get_database( $self->db_name )->_try_run_command( { ismaster => 1 } );
if ( exists $master->{minWireVersion} && exists $master->{maxWireVersion} ) {
if ( ( $master->{minWireVersion} > $self->max_wire_version )
or ( $master->{maxWireVersion} < $self->min_wire_version ) ) {
die "Incompatible wire protocol version. This version of the MongoDB driver is not compatible with the server. You probably need to upgrade this library.";
}
}
}
__PACKAGE__->meta->make_immutable( inline_destructor => 0 );
1;
__END__
=pod
=head1 SYNOPSIS
The MongoDB::MongoClient class creates a client connection to the MongoDB server.
By default, it connects to a single server running on the local machine
listening on the default port:
# connects to localhost:27017
my $client = MongoDB::MongoClient->new;
It can connect to a database server running anywhere, though:
my $client = MongoDB::MongoClient->new(host => 'example.com:12345');
See the L</"host"> section for more options for connecting to MongoDB.
=head1 MULTITHREADING
Cloning instances of this class is disabled in Perl 5.8.7+, so forked threads
will have to create their own connections to the database.
=head1 SEE ALSO
Core documentation on connections: L<http://docs.mongodb.org/manual/reference/connection-string/>.
=attr host
Server or servers to connect to. Defaults to C<mongodb://localhost:27017>.
To connect to more than one database server, use the format:
mongodb://host1[:port1][,host2[:port2],...[,hostN[:portN]]]
An arbitrary number of hosts can be specified.
The connect method will return success if it can connect to at least one of the
hosts listed. If it cannot connect to any hosts, it will die.
If a port is not specified for a given host, it will default to 27017. For
example, to connecting to C<localhost:27017> and C<localhost:27018>:
my $client = MongoDB::MongoClient->new("host" => "mongodb://localhost,localhost:27018");
This will succeed if either C<localhost:27017> or C<localhost:27018> are available.
The connect method will also try to determine who is the primary if more than one
server is given. It will try the hosts in order from left to right. As soon as
one of the hosts reports that it is the primary, the connect will return success. If
no hosts report themselves as a primary, the connect will die.
If username and password are given, success is conditional on being able to log
into the database as well as connect. By default, the driver will attempt to
authenticate with the admin database. If a different database is specified
using the C<db_name> property, it will be used instead.
=attr w
The client I<write concern>.
=over 4
=item * C<-1> Errors ignored. Do not use this.
=item * C<0> Unacknowledged. MongoClient will B<NOT> wait for an acknowledgment that
the server has received and processed the request. Older documentation may refer
to this as "fire-and-forget" mode. You must call C<getLastError> manually to check
if a request succeeds. This option is not recommended.
=item * C<1> Acknowledged. This is the default. MongoClient will wait until the
primary MongoDB acknowledges the write.
=item * C<2> Replica acknowledged. MongoClient will wait until at least two
replicas (primary and one secondary) acknowledge the write. You can set a higher
number for more replicas.
=item * C<all> All replicas acknowledged.
=item * C<majority> A majority of replicas acknowledged.
=back
In MongoDB v2.0+, you can "tag" replica members. With "tagging" you can specify a
new "getLastErrorMode" where you can create new
rules on how your data is replicated. To used you getLastErrorMode, you pass in the
name of the mode to the C<w> parameter. For more infomation see:
http://www.mongodb.org/display/DOCS/Data+Center+Awareness
=attr wtimeout
The number of milliseconds an operation should wait for C<w> slaves to replicate
it.
Defaults to 1000 (1 second).
See C<w> above for more information.
=attr j
If true, the client will block until write operations have been committed to the
server's journal. Prior to MongoDB 2.6, this option was ignored if the server was
running without journaling. Starting with MongoDB 2.6, write operations will fail
if this option is used when the server is running without journaling.
=attr auto_reconnect
Boolean indicating whether or not to reconnect if the connection is
interrupted. Defaults to C<1>.