-
Notifications
You must be signed in to change notification settings - Fork 199
/
client.go
1925 lines (1608 loc) · 62.7 KB
/
client.go
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 2014-2022 Aerospike, 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 aerospike
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"os"
"regexp"
"runtime"
"strconv"
"strings"
"time"
"github.com/aerospike/aerospike-client-go/v7/logger"
"github.com/aerospike/aerospike-client-go/v7/types"
)
const unreachable = "UNREACHABLE"
// Client encapsulates an Aerospike cluster.
// All database operations are available against this object.
type Client struct {
cluster *Cluster
// DefaultPolicy is used for all read commands without a specific policy.
DefaultPolicy *BasePolicy
// DefaultBatchPolicy is the default parent policy used in batch read commands. Base policy fields
// include socketTimeout, totalTimeout, maxRetries, etc...
DefaultBatchPolicy *BatchPolicy
// DefaultBatchReadPolicy is the default read policy used in batch operate commands.
DefaultBatchReadPolicy *BatchReadPolicy
// DefaultBatchWritePolicy is the default write policy used in batch operate commands.
// Write policy fields include generation, expiration, durableDelete, etc...
DefaultBatchWritePolicy *BatchWritePolicy
// DefaultBatchDeletePolicy is the default delete policy used in batch delete commands.
DefaultBatchDeletePolicy *BatchDeletePolicy
// DefaultBatchUDFPolicy is the default user defined function policy used in batch UDF execute commands.
DefaultBatchUDFPolicy *BatchUDFPolicy
// DefaultWritePolicy is used for all write commands without a specific policy.
DefaultWritePolicy *WritePolicy
// DefaultScanPolicy is used for all scan commands without a specific policy.
DefaultScanPolicy *ScanPolicy
// DefaultQueryPolicy is used for all query commands without a specific policy.
DefaultQueryPolicy *QueryPolicy
// DefaultAdminPolicy is used for all security commands without a specific policy.
DefaultAdminPolicy *AdminPolicy
// DefaultInfoPolicy is used for all info commands without a specific policy.
DefaultInfoPolicy *InfoPolicy
}
func clientFinalizer(f *Client) {
f.Close()
}
//-------------------------------------------------------
// Constructors
//-------------------------------------------------------
// NewClient generates a new Client instance.
// The connection pool after connecting to the database is initially empty,
// and connections are established on a per need basis, which can be slow and
// time out some initial commands.
// It is recommended to call the client.WarmUp() method right after connecting to the database
// to fill up the connection pool to the required service level.
func NewClient(hostname string, port int) (*Client, Error) {
return NewClientWithPolicyAndHost(NewClientPolicy(), NewHost(hostname, port))
}
// NewClientWithPolicy generates a new Client using the specified ClientPolicy.
// If the policy is nil, the default relevant policy will be used.
// The connection pool after connecting to the database is initially empty,
// and connections are established on a per need basis, which can be slow and
// time out some initial commands.
// It is recommended to call the client.WarmUp() method right after connecting to the database
// to fill up the connection pool to the required service level.
func NewClientWithPolicy(policy *ClientPolicy, hostname string, port int) (*Client, Error) {
return NewClientWithPolicyAndHost(policy, NewHost(hostname, port))
}
// NewClientWithPolicyAndHost generates a new Client with the specified ClientPolicy and
// sets up the cluster using the provided hosts.
// If the policy is nil, the default relevant policy will be used.
// The connection pool after connecting to the database is initially empty,
// and connections are established on a per need basis, which can be slow and
// time out some initial commands.
// It is recommended to call the client.WarmUp() method right after connecting to the database
// to fill up the connection pool to the required service level.
func NewClientWithPolicyAndHost(policy *ClientPolicy, hosts ...*Host) (*Client, Error) {
if policy == nil {
policy = NewClientPolicy()
}
cluster, err := NewCluster(policy, hosts)
if err != nil && policy.FailIfNotConnected {
logger.Logger.Debug("Failed to connect to host(s): %v; error: %s", hosts, err)
return nil, err
}
client := &Client{
cluster: cluster,
DefaultPolicy: NewPolicy(),
DefaultBatchPolicy: NewBatchPolicy(),
DefaultBatchReadPolicy: NewBatchReadPolicy(),
DefaultBatchWritePolicy: NewBatchWritePolicy(),
DefaultBatchDeletePolicy: NewBatchDeletePolicy(),
DefaultBatchUDFPolicy: NewBatchUDFPolicy(),
DefaultWritePolicy: NewWritePolicy(0, 0),
DefaultScanPolicy: NewScanPolicy(),
DefaultQueryPolicy: NewQueryPolicy(),
DefaultAdminPolicy: NewAdminPolicy(),
DefaultInfoPolicy: NewInfoPolicy(),
}
runtime.SetFinalizer(client, clientFinalizer)
return client, err
}
//-------------------------------------------------------
// Policy methods
//-------------------------------------------------------
// DefaultPolicy returns corresponding default policy from the client
func (clnt *Client) GetDefaultPolicy() *BasePolicy {
return clnt.DefaultPolicy
}
// DefaultBatchPolicy returns corresponding default policy from the client
func (clnt *Client) GetDefaultBatchPolicy() *BatchPolicy {
return clnt.DefaultBatchPolicy
}
// DefaultBatchWritePolicy returns corresponding default policy from the client
func (clnt *Client) GetDefaultBatchWritePolicy() *BatchWritePolicy {
return clnt.DefaultBatchWritePolicy
}
// DefaultBatchReadPolicy returns corresponding default policy from the client
func (clnt *Client) GetDefaultBatchReadPolicy() *BatchReadPolicy {
return clnt.DefaultBatchReadPolicy
}
// DefaultBatchDeletePolicy returns corresponding default policy from the client
func (clnt *Client) GetDefaultBatchDeletePolicy() *BatchDeletePolicy {
return clnt.DefaultBatchDeletePolicy
}
// DefaultBatchUDFPolicy returns corresponding default policy from the client
func (clnt *Client) GetDefaultBatchUDFPolicy() *BatchUDFPolicy {
return clnt.DefaultBatchUDFPolicy
}
// DefaultWritePolicy returns corresponding default policy from the client
func (clnt *Client) GetDefaultWritePolicy() *WritePolicy {
return clnt.DefaultWritePolicy
}
// DefaultScanPolicy returns corresponding default policy from the client
func (clnt *Client) GetDefaultScanPolicy() *ScanPolicy {
return clnt.DefaultScanPolicy
}
// DefaultQueryPolicy returns corresponding default policy from the client
func (clnt *Client) GetDefaultQueryPolicy() *QueryPolicy {
return clnt.DefaultQueryPolicy
}
// DefaultAdminPolicy returns corresponding default policy from the client
func (clnt *Client) GetDefaultAdminPolicy() *AdminPolicy {
return clnt.DefaultAdminPolicy
}
// DefaultInfoPolicy returns corresponding default policy from the client
func (clnt *Client) GetDefaultInfoPolicy() *InfoPolicy {
return clnt.DefaultInfoPolicy
}
// DefaultPolicy returns corresponding default policy from the client
func (clnt *Client) SetDefaultPolicy(policy *BasePolicy) {
clnt.DefaultPolicy = policy
}
// DefaultBatchPolicy returns corresponding default policy from the client
func (clnt *Client) SetDefaultBatchPolicy(policy *BatchPolicy) {
clnt.DefaultBatchPolicy = policy
}
// DefaultBatchWritePolicy returns corresponding default policy from the client
func (clnt *Client) SetDefaultBatchWritePolicy(policy *BatchWritePolicy) {
clnt.DefaultBatchWritePolicy = policy
}
// DefaultBatchReadPolicy returns corresponding default policy from the client
func (clnt *Client) SetDefaultBatchReadPolicy(policy *BatchReadPolicy) {
clnt.DefaultBatchReadPolicy = policy
}
// DefaultBatchDeletePolicy returns corresponding default policy from the client
func (clnt *Client) SetDefaultBatchDeletePolicy(policy *BatchDeletePolicy) {
clnt.DefaultBatchDeletePolicy = policy
}
// DefaultBatchUDFPolicy returns corresponding default policy from the client
func (clnt *Client) SetDefaultBatchUDFPolicy(policy *BatchUDFPolicy) {
clnt.DefaultBatchUDFPolicy = policy
}
// DefaultWritePolicy returns corresponding default policy from the client
func (clnt *Client) SetDefaultWritePolicy(policy *WritePolicy) {
clnt.DefaultWritePolicy = policy
}
// DefaultScanPolicy returns corresponding default policy from the client
func (clnt *Client) SetDefaultScanPolicy(policy *ScanPolicy) {
clnt.DefaultScanPolicy = policy
}
// DefaultQueryPolicy returns corresponding default policy from the client
func (clnt *Client) SetDefaultQueryPolicy(policy *QueryPolicy) {
clnt.DefaultQueryPolicy = policy
}
// DefaultAdminPolicy returns corresponding default policy from the client
func (clnt *Client) SetDefaultAdminPolicy(policy *AdminPolicy) {
clnt.DefaultAdminPolicy = policy
}
// DefaultInfoPolicy returns corresponding default policy from the client
func (clnt *Client) SetDefaultInfoPolicy(policy *InfoPolicy) {
clnt.DefaultInfoPolicy = policy
}
//-------------------------------------------------------
// Cluster Connection Management
//-------------------------------------------------------
// Close closes all client connections to database server nodes.
func (clnt *Client) Close() {
clnt.cluster.Close()
}
// IsConnected determines if the client is ready to talk to the database server cluster.
func (clnt *Client) IsConnected() bool {
return clnt.cluster.IsConnected()
}
// GetNodes returns an array of active server nodes in the cluster.
func (clnt *Client) GetNodes() []*Node {
return clnt.cluster.GetNodes()
}
// GetNodeNames returns a list of active server node names in the cluster.
func (clnt *Client) GetNodeNames() []string {
nodes := clnt.cluster.GetNodes()
names := make([]string, 0, len(nodes))
for _, node := range nodes {
names = append(names, node.GetName())
}
return names
}
//-------------------------------------------------------
// Write Record Operations
//-------------------------------------------------------
// Put writes record bin(s) to the server.
// The policy specifies the transaction timeout, record expiration and how the transaction is
// handled when the record already exists.
// If the policy is nil, the default relevant policy will be used.
func (clnt *Client) Put(policy *WritePolicy, key *Key, binMap BinMap) Error {
policy = clnt.getUsableWritePolicy(policy)
command, err := newWriteCommand(clnt.cluster, policy, key, nil, binMap, _WRITE)
if err != nil {
return err
}
return command.Execute()
}
// PutBins writes record bin(s) to the server.
// The policy specifies the transaction timeout, record expiration and how the transaction is
// handled when the record already exists.
// This method avoids using the BinMap allocation and iteration and is lighter on GC.
// If the policy is nil, the default relevant policy will be used.
func (clnt *Client) PutBins(policy *WritePolicy, key *Key, bins ...*Bin) Error {
policy = clnt.getUsableWritePolicy(policy)
command, err := newWriteCommand(clnt.cluster, policy, key, bins, nil, _WRITE)
if err != nil {
return err
}
return command.Execute()
}
//-------------------------------------------------------
// Operations string
//-------------------------------------------------------
// Append appends bin value's string to existing record bin values.
// The policy specifies the transaction timeout, record expiration and how the transaction is
// handled when the record already exists.
// This call only works for string and []byte values.
// If the policy is nil, the default relevant policy will be used.
func (clnt *Client) Append(policy *WritePolicy, key *Key, binMap BinMap) Error {
policy = clnt.getUsableWritePolicy(policy)
command, err := newWriteCommand(clnt.cluster, policy, key, nil, binMap, _APPEND)
if err != nil {
return err
}
return command.Execute()
}
// AppendBins works the same as Append, but avoids BinMap allocation and iteration.
func (clnt *Client) AppendBins(policy *WritePolicy, key *Key, bins ...*Bin) Error {
policy = clnt.getUsableWritePolicy(policy)
command, err := newWriteCommand(clnt.cluster, policy, key, bins, nil, _APPEND)
if err != nil {
return err
}
return command.Execute()
}
// Prepend prepends bin value's string to existing record bin values.
// The policy specifies the transaction timeout, record expiration and how the transaction is
// handled when the record already exists.
// This call works only for string and []byte values.
// If the policy is nil, the default relevant policy will be used.
func (clnt *Client) Prepend(policy *WritePolicy, key *Key, binMap BinMap) Error {
policy = clnt.getUsableWritePolicy(policy)
command, err := newWriteCommand(clnt.cluster, policy, key, nil, binMap, _PREPEND)
if err != nil {
return err
}
return command.Execute()
}
// PrependBins works the same as Prepend, but avoids BinMap allocation and iteration.
func (clnt *Client) PrependBins(policy *WritePolicy, key *Key, bins ...*Bin) Error {
policy = clnt.getUsableWritePolicy(policy)
command, err := newWriteCommand(clnt.cluster, policy, key, bins, nil, _PREPEND)
if err != nil {
return err
}
return command.Execute()
}
//-------------------------------------------------------
// Arithmetic Operations
//-------------------------------------------------------
// Add adds integer bin values to existing record bin values.
// The policy specifies the transaction timeout, record expiration and how the transaction is
// handled when the record already exists.
// This call only works for integer values.
// If the policy is nil, the default relevant policy will be used.
func (clnt *Client) Add(policy *WritePolicy, key *Key, binMap BinMap) Error {
policy = clnt.getUsableWritePolicy(policy)
command, err := newWriteCommand(clnt.cluster, policy, key, nil, binMap, _ADD)
if err != nil {
return err
}
return command.Execute()
}
// AddBins works the same as Add, but avoids BinMap allocation and iteration.
func (clnt *Client) AddBins(policy *WritePolicy, key *Key, bins ...*Bin) Error {
policy = clnt.getUsableWritePolicy(policy)
command, err := newWriteCommand(clnt.cluster, policy, key, bins, nil, _ADD)
if err != nil {
return err
}
return command.Execute()
}
//-------------------------------------------------------
// Delete Operations
//-------------------------------------------------------
// Delete deletes a record for specified key.
// The policy specifies the transaction timeout.
// If the policy is nil, the default relevant policy will be used.
func (clnt *Client) Delete(policy *WritePolicy, key *Key) (bool, Error) {
policy = clnt.getUsableWritePolicy(policy)
command, err := newDeleteCommand(clnt.cluster, policy, key)
if err != nil {
return false, err
}
err = command.Execute()
return command.Existed(), err
}
//-------------------------------------------------------
// Touch Operations
//-------------------------------------------------------
// Touch updates a record's metadata.
// If the record exists, the record's TTL will be reset to the
// policy's expiration.
// If the record doesn't exist, it will return an error.
func (clnt *Client) Touch(policy *WritePolicy, key *Key) Error {
policy = clnt.getUsableWritePolicy(policy)
command, err := newTouchCommand(clnt.cluster, policy, key)
if err != nil {
return err
}
return command.Execute()
}
//-------------------------------------------------------
// Existence-Check Operations
//-------------------------------------------------------
// Exists determine if a record key exists.
// The policy can be used to specify timeouts.
// If the policy is nil, the default relevant policy will be used.
func (clnt *Client) Exists(policy *BasePolicy, key *Key) (bool, Error) {
policy = clnt.getUsablePolicy(policy)
command, err := newExistsCommand(clnt.cluster, policy, key)
if err != nil {
return false, err
}
err = command.Execute()
return command.Exists(), err
}
// BatchExists determines if multiple record keys exist in one batch request.
// The returned boolean array is in positional order with the original key array order.
// The policy can be used to specify timeouts.
// If the policy is nil, the default relevant policy will be used.
func (clnt *Client) BatchExists(policy *BatchPolicy, keys []*Key) ([]bool, Error) {
policy = clnt.getUsableBatchPolicy(policy)
// same array can be used without synchronization;
// when a key exists, the corresponding index will be marked true
existsArray := make([]bool, len(keys))
batchNodes, err := newBatchNodeList(clnt.cluster, policy, keys, nil, false)
if err != nil {
return nil, err
}
// pass nil to make sure it will be cloned and prepared
cmd := newBatchCommandExists(clnt, nil, policy, keys, existsArray)
filteredOut, err := clnt.batchExecute(policy, batchNodes, cmd)
if filteredOut > 0 {
err = chainErrors(ErrFilteredOut.err(), err)
}
if err != nil {
return nil, err
}
return existsArray, err
}
//-------------------------------------------------------
// Read Record Operations
//-------------------------------------------------------
// Get reads a record header and bins for specified key.
// The policy can be used to specify timeouts.
// If the policy is nil, the default relevant policy will be used.
func (clnt *Client) Get(policy *BasePolicy, key *Key, binNames ...string) (*Record, Error) {
policy = clnt.getUsablePolicy(policy)
command, err := newReadCommand(clnt.cluster, policy, key, binNames, nil)
if err != nil {
return nil, err
}
if err := command.Execute(); err != nil {
return nil, err
}
return command.GetRecord(), nil
}
// GetHeader reads a record generation and expiration only for specified key.
// Bins are not read.
// The policy can be used to specify timeouts.
// If the policy is nil, the default relevant policy will be used.
func (clnt *Client) GetHeader(policy *BasePolicy, key *Key) (*Record, Error) {
policy = clnt.getUsablePolicy(policy)
command, err := newReadHeaderCommand(clnt.cluster, policy, key)
if err != nil {
return nil, err
}
if err := command.Execute(); err != nil {
return nil, err
}
return command.GetRecord(), nil
}
//-------------------------------------------------------
// Batch Read Operations
//-------------------------------------------------------
// BatchGet reads multiple record headers and bins for specified keys in one batch request.
// The returned records are in positional order with the original key array order.
// If a key is not found, the positional record will be nil.
// The policy can be used to specify timeouts.
// If the policy is nil, the default relevant policy will be used.
func (clnt *Client) BatchGet(policy *BatchPolicy, keys []*Key, binNames ...string) ([]*Record, Error) {
policy = clnt.getUsableBatchPolicy(policy)
// same array can be used without synchronization;
// when a key exists, the corresponding index will be set to record
records := make([]*Record, len(keys))
batchNodes, err := newBatchNodeList(clnt.cluster, policy, keys, nil, false)
if err != nil {
return nil, err
}
cmd := newBatchCommandGet(clnt, nil, policy, keys, binNames, nil, records, _INFO1_READ, false)
filteredOut, err := clnt.batchExecute(policy, batchNodes, cmd)
if err != nil && !policy.AllowPartialResults {
return nil, err
}
if filteredOut > 0 {
err = chainErrors(ErrFilteredOut.err(), err)
}
return records, err
}
// BatchGetOperate reads multiple records for specified keys using read operations in one batch call.
// The returned records are in positional order with the original key array order.
// If a key is not found, the positional record will be nil.
//
// If a batch request to a node fails, the entire batch is cancelled.
func (clnt *Client) BatchGetOperate(policy *BatchPolicy, keys []*Key, ops ...*Operation) ([]*Record, Error) {
policy = clnt.getUsableBatchPolicy(policy)
// same array can be used without synchronization;
// when a key exists, the corresponding index will be set to record
records := make([]*Record, len(keys))
batchNodes, err := newBatchNodeList(clnt.cluster, policy, keys, nil, false)
if err != nil {
return nil, err
}
cmd := newBatchCommandGet(clnt, nil, policy, keys, nil, ops, records, _INFO1_READ, true)
filteredOut, err := clnt.batchExecute(policy, batchNodes, cmd)
if err != nil && !policy.AllowPartialResults {
return nil, err
}
if filteredOut > 0 {
err = chainErrors(ErrFilteredOut.err(), err)
}
return records, err
}
// BatchGetComplex reads multiple records for specified batch keys in one batch call.
// This method allows different namespaces/bins to be requested for each key in the batch.
// The returned records are located in the same list.
// If the BatchRead key field is not found, the corresponding record field will be nil.
// The policy can be used to specify timeouts and maximum concurrent goroutines.
// This method requires Aerospike Server version >= 3.6.0.
func (clnt *Client) BatchGetComplex(policy *BatchPolicy, records []*BatchRead) Error {
policy = clnt.getUsableBatchPolicy(policy)
cmd := newBatchIndexCommandGet(clnt, nil, policy, records, true)
batchNodes, err := newBatchIndexNodeList(clnt.cluster, policy, records)
if err != nil {
return err
}
filteredOut, err := clnt.batchExecute(policy, batchNodes, cmd)
if err != nil && !policy.AllowPartialResults {
return err
}
if filteredOut > 0 {
err = chainErrors(ErrFilteredOut.err(), err)
}
return err
}
// BatchGetHeader reads multiple record header data for specified keys in one batch request.
// The returned records are in positional order with the original key array order.
// If a key is not found, the positional record will be nil.
// The policy can be used to specify timeouts.
// If the policy is nil, the default relevant policy will be used.
func (clnt *Client) BatchGetHeader(policy *BatchPolicy, keys []*Key) ([]*Record, Error) {
policy = clnt.getUsableBatchPolicy(policy)
// same array can be used without synchronization;
// when a key exists, the corresponding index will be set to record
records := make([]*Record, len(keys))
batchNodes, err := newBatchNodeList(clnt.cluster, policy, keys, nil, false)
if err != nil {
return nil, err
}
cmd := newBatchCommandGet(clnt, nil, policy, keys, nil, nil, records, _INFO1_READ|_INFO1_NOBINDATA, false)
filteredOut, err := clnt.batchExecute(policy, batchNodes, cmd)
if err != nil && !policy.AllowPartialResults {
return nil, err
}
if filteredOut > 0 {
err = chainErrors(ErrFilteredOut.err(), err)
}
return records, err
}
// BatchDelete deletes records for specified keys. If a key is not found, the corresponding result
// BatchRecord.ResultCode will be types.KEY_NOT_FOUND_ERROR.
//
// Requires server version 6.0+
func (clnt *Client) BatchDelete(policy *BatchPolicy, deletePolicy *BatchDeletePolicy, keys []*Key) ([]*BatchRecord, Error) {
policy = clnt.getUsableBatchPolicy(policy)
deletePolicy = clnt.getUsableBatchDeletePolicy(deletePolicy)
attr := &batchAttr{}
attr.setBatchDelete(deletePolicy)
// same array can be used without synchronization;
// when a key exists, the corresponding index will be set to record
records := make([]*BatchRecord, len(keys))
for i := range records {
records[i] = newSimpleBatchRecord(keys[i], true)
}
batchNodes, err := newBatchNodeList(clnt.cluster, policy, keys, records, true)
if err != nil {
return nil, err
}
cmd := newBatchCommandDelete(clnt, nil, policy, deletePolicy, keys, records, attr)
_, err = clnt.batchExecute(policy, batchNodes, cmd)
return records, err
}
// BatchOperate will read/write multiple records for specified batch keys in one batch call.
// This method allows different namespaces/bins for each key in the batch.
// The returned records are located in the same list.
//
// BatchRecord can be *BatchRead, *BatchWrite, *BatchDelete or *BatchUDF.
//
// Requires server version 6.0+
func (clnt *Client) BatchOperate(policy *BatchPolicy, records []BatchRecordIfc) Error {
policy = clnt.getUsableBatchPolicy(policy)
batchNodes, err := newBatchOperateNodeListIfc(clnt.cluster, policy, records)
if err != nil && policy.RespondAllKeys {
return err
}
cmd := newBatchCommandOperate(clnt, nil, policy, records)
_, err = clnt.batchExecute(policy, batchNodes, cmd)
return err
}
// BatchExecute will read/write multiple records for specified batch keys in one batch call.
// This method allows different namespaces/bins for each key in the batch.
// The returned records are located in the same list.
//
// BatchRecord can be *BatchRead, *BatchWrite, *BatchDelete or *BatchUDF.
//
// Requires server version 6.0+
func (clnt *Client) BatchExecute(policy *BatchPolicy, udfPolicy *BatchUDFPolicy, keys []*Key, packageName string, functionName string, args ...Value) ([]*BatchRecord, Error) {
policy = clnt.getUsableBatchPolicy(policy)
udfPolicy = clnt.getUsableBatchUDFPolicy(udfPolicy)
attr := &batchAttr{}
attr.setBatchUDF(udfPolicy)
// same array can be used without synchronization;
// when a key exists, the corresponding index will be set to record
records := make([]*BatchRecord, len(keys))
for i := range records {
records[i] = newSimpleBatchRecord(keys[i], attr.hasWrite)
}
batchNodes, err := newBatchNodeList(clnt.cluster, policy, keys, records, attr.hasWrite)
if err != nil {
return nil, err
}
cmd := newBatchCommandUDF(clnt, nil, policy, udfPolicy, keys, packageName, functionName, args, records, attr)
_, err = clnt.batchExecute(policy, batchNodes, cmd)
return records, err
}
//-------------------------------------------------------
// Generic Database Operations
//-------------------------------------------------------
// Operate performs multiple read/write operations on a single key in one batch request.
// An example would be to add an integer value to an existing record and then
// read the result, all in one database call.
//
// If the policy is nil, the default relevant policy will be used.
func (clnt *Client) Operate(policy *WritePolicy, key *Key, operations ...*Operation) (*Record, Error) {
return clnt.operate(policy, key, false, operations...)
}
// useOpResults is used in batch single nodes commands and should be true to return the right type for BatchOperate results
func (clnt *Client) operate(policy *WritePolicy, key *Key, useOpResults bool, operations ...*Operation) (*Record, Error) {
// TODO: Remove this method in the next major release.
policy = clnt.getUsableWritePolicy(policy)
args, err := newOperateArgs(clnt.cluster, policy, key, operations)
if err != nil {
return nil, err
}
command, err := newOperateCommand(clnt.cluster, policy, key, args, useOpResults)
if err != nil {
return nil, err
}
if err := command.Execute(); err != nil {
return nil, err
}
return command.GetRecord(), nil
}
//-------------------------------------------------------
// Scan Operations
//-------------------------------------------------------
// ScanPartitions Read records in specified namespace, set and partition filter.
// If the policy's concurrentNodes is specified, each server node will be read in
// parallel. Otherwise, server nodes are read sequentially.
// If partitionFilter is nil, all partitions will be scanned.
// If the policy is nil, the default relevant policy will be used.
// This method is only supported by Aerospike 4.9+ servers.
func (clnt *Client) ScanPartitions(apolicy *ScanPolicy, partitionFilter *PartitionFilter, namespace string, setName string, binNames ...string) (*Recordset, Error) {
policy := *clnt.getUsableScanPolicy(apolicy)
nodes := clnt.cluster.GetNodes()
if len(nodes) == 0 {
return nil, ErrClusterIsEmpty.err()
}
var tracker *partitionTracker
if partitionFilter == nil {
tracker = newPartitionTrackerForNodes(&policy.MultiPolicy, nodes)
} else {
tracker = newPartitionTracker(&policy.MultiPolicy, partitionFilter, nodes)
}
// result recordset
res := newRecordset(policy.RecordQueueSize, 1)
go clnt.scanPartitions(&policy, tracker, namespace, setName, res, binNames...)
return res, nil
}
// ScanAll reads all records in specified namespace and set from all nodes.
// If the policy's concurrentNodes is specified, each server node will be read in
// parallel. Otherwise, server nodes are read sequentially.
// If the policy is nil, the default relevant policy will be used.
func (clnt *Client) ScanAll(apolicy *ScanPolicy, namespace string, setName string, binNames ...string) (*Recordset, Error) {
return clnt.ScanPartitions(apolicy, nil, namespace, setName, binNames...)
}
// scanNodePartitions reads all records in specified namespace and set for one node only.
// If the policy is nil, the default relevant policy will be used.
func (clnt *Client) scanNodePartitions(apolicy *ScanPolicy, node *Node, namespace string, setName string, binNames ...string) (*Recordset, Error) {
policy := *clnt.getUsableScanPolicy(apolicy)
tracker := newPartitionTrackerForNode(&policy.MultiPolicy, node)
// result recordset
res := newRecordset(policy.RecordQueueSize, 1)
go clnt.scanPartitions(&policy, tracker, namespace, setName, res, binNames...)
return res, nil
}
// ScanNode reads all records in specified namespace and set for one node only.
// If the policy is nil, the default relevant policy will be used.
func (clnt *Client) ScanNode(apolicy *ScanPolicy, node *Node, namespace string, setName string, binNames ...string) (*Recordset, Error) {
return clnt.scanNodePartitions(apolicy, node, namespace, setName, binNames...)
}
//---------------------------------------------------------------
// User defined functions (Supported by Aerospike 3+ servers only)
//---------------------------------------------------------------
// RegisterUDFFromFile reads a file from file system and registers
// the containing a package user defined functions with the server.
// This asynchronous server call will return before command is complete.
// The user can optionally wait for command completion by using the returned
// RegisterTask instance.
//
// This method is only supported by Aerospike 3+ servers.
// If the policy is nil, the default relevant policy will be used.
func (clnt *Client) RegisterUDFFromFile(policy *WritePolicy, clientPath string, serverPath string, language Language) (*RegisterTask, Error) {
policy = clnt.getUsableWritePolicy(policy)
udfBody, err := os.ReadFile(clientPath)
if err != nil {
return nil, newCommonError(err)
}
return clnt.RegisterUDF(policy, udfBody, serverPath, language)
}
// RegisterUDF registers a package containing user defined functions with server.
// This asynchronous server call will return before command is complete.
// The user can optionally wait for command completion by using the returned
// RegisterTask instance.
//
// This method is only supported by Aerospike 3+ servers.
// If the policy is nil, the default relevant policy will be used.
func (clnt *Client) RegisterUDF(policy *WritePolicy, udfBody []byte, serverPath string, language Language) (*RegisterTask, Error) {
policy = clnt.getUsableWritePolicy(policy)
content := base64.StdEncoding.EncodeToString(udfBody)
var strCmd bytes.Buffer
// errors are to remove errcheck warnings
// they will always be nil as stated in golang docs
strCmd.WriteString("udf-put:filename=")
strCmd.WriteString(serverPath)
strCmd.WriteString(";content=")
strCmd.WriteString(content)
strCmd.WriteString(";content-len=")
strCmd.WriteString(strconv.Itoa(len(content)))
strCmd.WriteString(";udf-type=")
strCmd.WriteString(string(language))
strCmd.WriteString(";")
// Send UDF to one node. That node will distribute the UDF to other nodes.
responseMap, err := clnt.sendInfoCommand(policy.TotalTimeout, strCmd.String())
if err != nil {
return nil, err
}
response := responseMap[strCmd.String()]
if strings.EqualFold(response, "ok") {
return NewRegisterTask(clnt.cluster, serverPath), nil
}
err = parseInfoErrorCode(response)
res := make(map[string]string)
vals := strings.Split("error="+err.Error(), ";")
for _, pair := range vals {
t := strings.SplitN(pair, "=", 2)
if len(t) == 2 {
res[strings.ToLower(t[0])] = t[1]
} else if len(t) == 1 {
res[strings.ToLower(t[0])] = ""
}
}
if _, exists := res["error"]; exists {
msg, _ := base64.StdEncoding.DecodeString(res["message"])
return nil, newError(err.resultCode(), fmt.Sprintf("Registration failed: %s\nFile: %s\nLine: %s\nMessage: %s",
res["error"], res["file"], res["line"], msg))
}
// if message was not parsable
return nil, parseInfoErrorCode(response)
}
// RemoveUDF removes a package containing user defined functions in the server.
// This asynchronous server call will return before command is complete.
// The user can optionally wait for command completion by using the returned
// RemoveTask instance.
//
// This method is only supported by Aerospike 3+ servers.
// If the policy is nil, the default relevant policy will be used.
func (clnt *Client) RemoveUDF(policy *WritePolicy, udfName string) (*RemoveTask, Error) {
policy = clnt.getUsableWritePolicy(policy)
var strCmd bytes.Buffer
// errors are to remove errcheck warnings
// they will always be nil as stated in golang docs
strCmd.WriteString("udf-remove:filename=")
strCmd.WriteString(udfName)
strCmd.WriteString(";")
// Send command to one node. That node will distribute it to other nodes.
responseMap, err := clnt.sendInfoCommand(policy.TotalTimeout, strCmd.String())
if err != nil {
return nil, err
}
response := responseMap[strCmd.String()]
if strings.EqualFold(response, "ok") {
return NewRemoveTask(clnt.cluster, udfName), nil
}
return nil, parseInfoErrorCode(response)
}
// ListUDF lists all packages containing user defined functions in the server.
// This method is only supported by Aerospike 3+ servers.
// If the policy is nil, the default relevant policy will be used.
func (clnt *Client) ListUDF(policy *BasePolicy) ([]*UDF, Error) {
policy = clnt.getUsablePolicy(policy)
var strCmd bytes.Buffer
// errors are to remove errcheck warnings
// they will always be nil as stated in golang docs
strCmd.WriteString("udf-list")
// Send command to one node. That node will distribute it to other nodes.
responseMap, err := clnt.sendInfoCommand(policy.TotalTimeout, strCmd.String())
if err != nil {
return nil, err
}
response := responseMap[strCmd.String()]
vals := strings.Split(response, ";")
res := make([]*UDF, 0, len(vals))
for _, udfInfo := range vals {
if strings.Trim(udfInfo, " ") == "" {
continue
}
udfParts := strings.Split(udfInfo, ",")
udf := &UDF{}
for _, values := range udfParts {
valueParts := strings.Split(values, "=")
if len(valueParts) == 2 {
switch valueParts[0] {
case "filename":
udf.Filename = valueParts[1]
case "hash":
udf.Hash = valueParts[1]
case "type":
udf.Language = Language(valueParts[1])
}
}
}
res = append(res, udf)
}
return res, nil
}
// Execute executes a user defined function on server and return results.
// The function operates on a single record.
// The package name is used to locate the udf file location:
//
// udf file = <server udf dir>/<package name>.lua
//
// This method is only supported by Aerospike 3+ servers.
// If the policy is nil, the default relevant policy will be used.
func (clnt *Client) Execute(policy *WritePolicy, key *Key, packageName string, functionName string, args ...Value) (interface{}, Error) {
record, err := clnt.execute(policy, key, packageName, functionName, args...)
if err != nil {
return nil, err
}
if record == nil || len(record.Bins) == 0 {
return nil, nil
}
for k, v := range record.Bins {
if strings.Contains(k, "SUCCESS") {
return v, nil
} else if strings.Contains(k, "FAILURE") {
return nil, newError(ErrUDFBadResponse.ResultCode, fmt.Sprintf("%v", v))
}
}
return nil, ErrUDFBadResponse.err()
}
func (clnt *Client) execute(policy *WritePolicy, key *Key, packageName string, functionName string, args ...Value) (*Record, Error) {
policy = clnt.getUsableWritePolicy(policy)
command, err := newExecuteCommand(clnt.cluster, policy, key, packageName, functionName, NewValueArray(args))
if err != nil {
return nil, err