This repository has been archived by the owner on Feb 11, 2022. It is now read-only.
forked from aerospike/aerospike-client-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
1345 lines (1130 loc) · 44.4 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 2013-2019 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"
"errors"
"fmt"
"io/ioutil"
"runtime"
"strconv"
"strings"
"sync"
"time"
. "github.com/aerospike/aerospike-client-go/logger"
. "github.com/aerospike/aerospike-client-go/types"
xornd "github.com/aerospike/aerospike-client-go/types/rand"
)
// 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 used for all batch commands without a specific policy.
DefaultBatchPolicy *BatchPolicy
// 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
}
func clientFinalizer(f *Client) {
f.Close()
}
//-------------------------------------------------------
// Constructors
//-------------------------------------------------------
// NewClient generates a new Client instance.
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.
func NewClientWithPolicy(policy *ClientPolicy, hostname string, port int) (*Client, error) {
return NewClientWithPolicyAndHost(policy, NewHost(hostname, port))
}
// NewClientWithPolicyAndHost generates a new Client the specified ClientPolicy and
// sets up the cluster using the provided hosts.
// If the policy is nil, the default relevant policy will be used.
func NewClientWithPolicyAndHost(policy *ClientPolicy, hosts ...*Host) (*Client, error) {
if policy == nil {
policy = NewClientPolicy()
}
cluster, err := NewCluster(policy, hosts)
if err != nil && policy.FailIfNotConnected {
if aerr, ok := err.(AerospikeError); ok {
Logger.Debug("Failed to connect to host(s): %v; error: %s", hosts, err)
return nil, aerr
}
return nil, fmt.Errorf("Failed to connect to host(s): %v; error: %s", hosts, err)
}
client := &Client{
cluster: cluster,
DefaultPolicy: NewPolicy(),
DefaultBatchPolicy: NewBatchPolicy(),
DefaultWritePolicy: NewWritePolicy(0, 0),
DefaultScanPolicy: NewScanPolicy(),
DefaultQueryPolicy: NewQueryPolicy(),
DefaultAdminPolicy: NewAdminPolicy(),
}
runtime.SetFinalizer(client, clientFinalizer)
return client, err
}
//-------------------------------------------------------
// 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 := newWriteCommand(clnt.cluster, policy, key, nil, binMap, WRITE)
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 := newWriteCommand(clnt.cluster, policy, key, bins, nil, WRITE)
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 := newWriteCommand(clnt.cluster, policy, key, nil, binMap, APPEND)
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 := newWriteCommand(clnt.cluster, policy, key, bins, nil, APPEND)
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 := newWriteCommand(clnt.cluster, policy, key, nil, binMap, PREPEND)
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 := newWriteCommand(clnt.cluster, policy, key, bins, nil, PREPEND)
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 := newWriteCommand(clnt.cluster, policy, key, nil, binMap, ADD)
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 := newWriteCommand(clnt.cluster, policy, key, bins, nil, ADD)
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 := newDeleteCommand(clnt.cluster, policy, key)
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 := newTouchCommand(clnt.cluster, policy, key)
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 := newExistsCommand(clnt.cluster, policy, key)
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))
// pass nil to make sure it will be cloned and prepared
cmd := newBatchCommandExists(nil, nil, nil, policy, keys, existsArray)
if err := clnt.batchExecute(policy, keys, cmd); err != nil {
return nil, err
}
return existsArray, nil
}
//-------------------------------------------------------
// 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 := newReadCommand(clnt.cluster, policy, key, binNames)
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 := newReadHeaderCommand(clnt.cluster, policy, key)
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))
cmd := newBatchCommandGet(nil, nil, nil, policy, keys, binNames, records, _INFO1_READ)
err := clnt.batchExecute(policy, keys, cmd)
if err != nil && !policy.AllowPartialResults {
return nil, 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 null.
// The policy can be used to specify timeouts and maximum concurrent threads.
// This method requires Aerospike Server version >= 3.6.0.
func (clnt *Client) BatchGetComplex(policy *BatchPolicy, records []*BatchRead) error {
policy = clnt.getUsableBatchPolicy(policy)
cmd := newBatchIndexCommandGet(nil, policy, records)
return clnt.batchIndexExecute(policy, records, cmd)
}
// 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))
cmd := newBatchCommandGet(nil, nil, nil, policy, keys, nil, records, _INFO1_READ|_INFO1_NOBINDATA)
err := clnt.batchExecute(policy, keys, cmd)
if err != nil && !policy.AllowPartialResults {
return nil, err
}
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) {
policy = clnt.getUsableWritePolicy(policy)
command := newOperateCommand(clnt.cluster, policy, key, operations)
if err := command.Execute(); err != nil {
return nil, err
}
return command.GetRecord(), nil
}
//-------------------------------------------------------
// Scan Operations
//-------------------------------------------------------
// 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) {
policy := *clnt.getUsableScanPolicy(apolicy)
nodes := clnt.cluster.GetNodes()
if len(nodes) == 0 {
return nil, NewAerospikeError(SERVER_NOT_AVAILABLE, "Scan failed because cluster is empty.")
}
if policy.WaitUntilMigrationsAreOver {
// wait until all migrations are finished
if err := clnt.cluster.WaitUntillMigrationIsFinished(policy.Timeout); err != nil {
return nil, err
}
}
// result recordset
taskId := uint64(xornd.Int64())
res := newRecordset(policy.RecordQueueSize, len(nodes), taskId)
// the whole call should be wrapped in a goroutine
if policy.ConcurrentNodes {
for _, node := range nodes {
go func(node *Node) {
clnt.scanNode(&policy, node, res, namespace, setName, taskId, binNames...)
}(node)
}
} else {
// scan nodes one by one
go func() {
for _, node := range nodes {
clnt.scanNode(&policy, node, res, namespace, setName, taskId, 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) {
policy := *clnt.getUsableScanPolicy(apolicy)
// results channel must be async for performance
taskId := uint64(xornd.Int64())
res := newRecordset(policy.RecordQueueSize, 1, taskId)
go clnt.scanNode(&policy, node, res, namespace, setName, taskId, 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(policy *ScanPolicy, node *Node, recordset *Recordset, namespace string, setName string, taskId uint64, binNames ...string) error {
if policy.WaitUntilMigrationsAreOver {
// wait until migrations on node are finished
if err := node.WaitUntillMigrationIsFinished(policy.Timeout); err != nil {
recordset.signalEnd()
return err
}
}
command := newScanCommand(node, policy, namespace, setName, binNames, recordset, taskId)
return command.Execute()
}
//---------------------------------------------------------------
// 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 := ioutil.ReadFile(clientPath)
if err != nil {
return nil, 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
_, err := strCmd.WriteString("udf-put:filename=")
_, err = strCmd.WriteString(serverPath)
_, err = strCmd.WriteString(";content=")
_, err = strCmd.WriteString(content)
_, err = strCmd.WriteString(";content-len=")
_, err = strCmd.WriteString(strconv.Itoa(len(content)))
_, err = strCmd.WriteString(";udf-type=")
_, err = strCmd.WriteString(string(language))
_, err = strCmd.WriteString(";")
// Send UDF to one node. That node will distribute the UDF to other nodes.
responseMap, err := clnt.sendInfoCommand(policy.Timeout, strCmd.String())
if err != nil {
return nil, err
}
response := responseMap[strCmd.String()]
res := make(map[string]string)
vals := strings.Split(response, ";")
for _, pair := range vals {
t := strings.SplitN(pair, "=", 2)
if len(t) == 2 {
res[t[0]] = t[1]
} else if len(t) == 1 {
res[t[0]] = ""
}
}
if _, exists := res["error"]; exists {
msg, _ := base64.StdEncoding.DecodeString(res["message"])
return nil, NewAerospikeError(COMMAND_REJECTED, fmt.Sprintf("Registration failed: %s\nFile: %s\nLine: %s\nMessage: %s",
res["error"], res["file"], res["line"], msg))
}
return NewRegisterTask(clnt.cluster, serverPath), nil
}
// 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
_, err := strCmd.WriteString("udf-remove:filename=")
_, err = strCmd.WriteString(udfName)
_, err = strCmd.WriteString(";")
// Send command to one node. That node will distribute it to other nodes.
responseMap, err := clnt.sendInfoCommand(policy.Timeout, strCmd.String())
if err != nil {
return nil, err
}
response := responseMap[strCmd.String()]
if response == "ok" {
return NewRemoveTask(clnt.cluster, udfName), nil
}
return nil, NewAerospikeError(SERVER_ERROR, 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
_, err := strCmd.WriteString("udf-list")
// Send command to one node. That node will distribute it to other nodes.
responseMap, err := clnt.sendInfoCommand(policy.Timeout, 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) {
policy = clnt.getUsableWritePolicy(policy)
command := newExecuteCommand(clnt.cluster, policy, key, packageName, functionName, NewValueArray(args))
if err := command.Execute(); err != nil {
return nil, err
}
record := command.GetRecord()
if record == nil || len(record.Bins) == 0 {
return nil, nil
}
resultMap := record.Bins
// User defined functions don't have to return a value.
if exists, obj := mapContainsKeyPartial(resultMap, "SUCCESS"); exists {
return obj, nil
}
if _, obj := mapContainsKeyPartial(resultMap, "FAILURE"); obj != nil {
return nil, fmt.Errorf("%v", obj)
}
return nil, NewAerospikeError(UDF_BAD_RESPONSE, "Invalid UDF return value")
}
func mapContainsKeyPartial(theMap map[string]interface{}, key string) (bool, interface{}) {
for k, v := range theMap {
if strings.Contains(k, key) {
return true, v
}
}
return false, nil
}
//----------------------------------------------------------
// Query/Execute UDF (Supported by Aerospike 3 servers only)
//----------------------------------------------------------
// ExecuteUDF applies user defined function on records that match the statement filter.
// Records are not returned to the client.
// This asynchronous server call will return before command is complete.
// The user can optionally wait for command completion by using the returned
// ExecuteTask 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) ExecuteUDF(policy *QueryPolicy,
statement *Statement,
packageName string,
functionName string,
functionArgs ...Value,
) (*ExecuteTask, error) {
policy = clnt.getUsableQueryPolicy(policy)
nodes := clnt.cluster.GetNodes()
if len(nodes) == 0 {
return nil, NewAerospikeError(SERVER_NOT_AVAILABLE, "ExecuteUDF failed because cluster is empty.")
}
// wait until all migrations are finished
if err := clnt.cluster.WaitUntillMigrationIsFinished(policy.Timeout); err != nil {
return nil, err
}
statement.SetAggregateFunction(packageName, functionName, functionArgs, false)
errs := []error{}
for i := range nodes {
command := newServerCommand(nodes[i], policy, statement)
if err := command.Execute(); err != nil {
errs = append(errs, err)
}
}
return NewExecuteTask(clnt.cluster, statement), mergeErrors(errs)
}
// ExecuteUDFNode applies user defined function on records that match the statement filter on the specified node.
// Records are not returned to the client.
// This asynchronous server call will return before command is complete.
// The user can optionally wait for command completion by using the returned
// ExecuteTask 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) ExecuteUDFNode(policy *QueryPolicy,
node *Node,
statement *Statement,
packageName string,
functionName string,
functionArgs ...Value,
) (*ExecuteTask, error) {
policy = clnt.getUsableQueryPolicy(policy)
if node == nil {
return nil, NewAerospikeError(SERVER_NOT_AVAILABLE, "ExecuteUDFNode failed because node is nil.")
}
// wait until all migrations are finished
if err := clnt.cluster.WaitUntillMigrationIsFinished(policy.Timeout); err != nil {
return nil, err
}
statement.SetAggregateFunction(packageName, functionName, functionArgs, false)
command := newServerCommand(node, policy, statement)
err := command.Execute()
return NewExecuteTask(clnt.cluster, statement), err
}
//--------------------------------------------------------
// Query functions (Supported by Aerospike 3 servers only)
//--------------------------------------------------------
// Query executes a query and returns a Recordset.
// The query executor puts records on the channel from separate goroutines.
// The caller can concurrently pop records off the channel through the
// Recordset.Records channel.
//
// This method is only supported by Aerospike 3 servers.
// If the policy is nil, the default relevant policy will be used.
func (clnt *Client) Query(policy *QueryPolicy, statement *Statement) (*Recordset, error) {
policy = clnt.getUsableQueryPolicy(policy)
nodes := clnt.cluster.GetNodes()
if len(nodes) == 0 {
return nil, NewAerospikeError(SERVER_NOT_AVAILABLE, "Query failed because cluster is empty.")
}
if policy.WaitUntilMigrationsAreOver {
// wait until all migrations are finished
if err := clnt.cluster.WaitUntillMigrationIsFinished(policy.Timeout); err != nil {
return nil, err
}
}
// results channel must be async for performance
recSet := newRecordset(policy.RecordQueueSize, len(nodes), statement.TaskId)
// results channel must be async for performance
for _, node := range nodes {
// copy policies to avoid race conditions
newPolicy := *policy
command := newQueryRecordCommand(node, &newPolicy, statement, recSet)
go func() {
command.Execute()
}()
}
return recSet, nil
}
// QueryNode executes a query on a specific node and returns a recordset.
// The caller can concurrently pop records off the channel through the
// record channel.
//
// This method is only supported by Aerospike 3 servers.
// If the policy is nil, the default relevant policy will be used.
func (clnt *Client) QueryNode(policy *QueryPolicy, node *Node, statement *Statement) (*Recordset, error) {
policy = clnt.getUsableQueryPolicy(policy)
if policy.WaitUntilMigrationsAreOver {
// wait until all migrations are finished
if err := clnt.cluster.WaitUntillMigrationIsFinished(policy.Timeout); err != nil {
return nil, err
}
}
// results channel must be async for performance
recSet := newRecordset(policy.RecordQueueSize, 1, statement.TaskId)
// copy policies to avoid race conditions
newPolicy := *policy
command := newQueryRecordCommand(node, &newPolicy, statement, recSet)
go func() {
command.Execute()
}()
return recSet, nil
}
// CreateIndex creates a secondary index.
// This asynchronous server call will return before the command is complete.
// The user can optionally wait for command completion by using the returned
// IndexTask 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) CreateIndex(
policy *WritePolicy,
namespace string,
setName string,
indexName string,
binName string,
indexType IndexType,
) (*IndexTask, error) {
policy = clnt.getUsableWritePolicy(policy)
return clnt.CreateComplexIndex(policy, namespace, setName, indexName, binName, indexType, ICT_DEFAULT)
}
// CreateComplexIndex creates a secondary index, with the ability to put indexes
// on bin containing complex data types, e.g: Maps and Lists.
// This asynchronous server call will return before the command is complete.
// The user can optionally wait for command completion by using the returned
// IndexTask 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) CreateComplexIndex(
policy *WritePolicy,
namespace string,
setName string,
indexName string,
binName string,
indexType IndexType,
indexCollectionType IndexCollectionType,
) (*IndexTask, error) {
policy = clnt.getUsableWritePolicy(policy)
var strCmd bytes.Buffer
_, err := strCmd.WriteString("sindex-create:ns=")
_, err = strCmd.WriteString(namespace)
if len(setName) > 0 {
_, err = strCmd.WriteString(";set=")
_, err = strCmd.WriteString(setName)
}
_, err = strCmd.WriteString(";indexname=")
_, err = strCmd.WriteString(indexName)
_, err = strCmd.WriteString(";numbins=1")
if indexCollectionType != ICT_DEFAULT {
_, err = strCmd.WriteString(";indextype=")
_, err = strCmd.WriteString(ictToString(indexCollectionType))
}
_, err = strCmd.WriteString(";indexdata=")
_, err = strCmd.WriteString(binName)
_, err = strCmd.WriteString(",")
_, err = strCmd.WriteString(string(indexType))
_, err = strCmd.WriteString(";priority=normal")
// Send index command to one node. That node will distribute the command to other nodes.
responseMap, err := clnt.sendInfoCommand(policy.Timeout, strCmd.String())
if err != nil {
return nil, err
}
response := responseMap[strCmd.String()]
if strings.ToUpper(response) == "OK" {
// Return task that could optionally be polled for completion.
return NewIndexTask(clnt.cluster, namespace, indexName), nil
}
if strings.HasPrefix(response, "FAIL:200") {
// Index has already been created. Do not need to poll for completion.
return nil, NewAerospikeError(INDEX_FOUND)
}
return nil, NewAerospikeError(INDEX_GENERIC, "Create index failed: "+response)
}
// DropIndex deletes a secondary index. It will block until index is dropped on all nodes.
// This method is only supported by Aerospike 3 servers.
// If the policy is nil, the default relevant policy will be used.
func (clnt *Client) DropIndex(
policy *WritePolicy,
namespace string,
setName string,
indexName string,
) error {
policy = clnt.getUsableWritePolicy(policy)
var strCmd bytes.Buffer
_, err := strCmd.WriteString("sindex-delete:ns=")
_, err = strCmd.WriteString(namespace)
if len(setName) > 0 {
_, err = strCmd.WriteString(";set=")
_, err = strCmd.WriteString(setName)
}
_, err = strCmd.WriteString(";indexname=")
_, err = strCmd.WriteString(indexName)
// Send index command to one node. That node will distribute the command to other nodes.
responseMap, err := clnt.sendInfoCommand(policy.Timeout, strCmd.String())
if err != nil {
return err
}
response := responseMap[strCmd.String()]
if strings.ToUpper(response) == "OK" {
// Return task that could optionally be polled for completion.
task := NewDropIndexTask(clnt.cluster, namespace, indexName)
return <-task.OnComplete()
}
if strings.HasPrefix(response, "FAIL:201") {
// Index did not previously exist. Return without error.
return nil
}
return NewAerospikeError(INDEX_GENERIC, "Drop index failed: "+response)
}
// Truncate removes records in specified namespace/set efficiently. This method is many orders of magnitude
// faster than deleting records one at a time. Works with Aerospike Server versions >= 3.12.
// This asynchronous server call may return before the truncation is complete. The user can still
// write new records after the server call returns because new records will have last update times
// greater than the truncate cutoff (set at the time of truncate call).
// For more information, See https://www.aerospike.com/docs/reference/info#truncate
func (clnt *Client) Truncate(policy *WritePolicy, namespace, set string, beforeLastUpdate *time.Time) error {
policy = clnt.getUsableWritePolicy(policy)
node, err := clnt.cluster.GetRandomNode()
if err != nil {
return err
}
node.tendConnLock.Lock()
defer node.tendConnLock.Unlock()
if err := node.initTendConn(policy.Timeout); err != nil {
return err
}
var strCmd bytes.Buffer
if len(set) > 0 {
_, err = strCmd.WriteString("truncate:namespace=")
_, err = strCmd.WriteString(namespace)
_, err = strCmd.WriteString(";set=")
_, err = strCmd.WriteString(set)
} else {
// Servers >= 4.5.1.0 support truncate-namespace.
if node.supportsTruncateNamespace.Get() {
_, err = strCmd.WriteString("truncate-namespace:namespace=")
_, err = strCmd.WriteString(namespace)
} else {
_, err = strCmd.WriteString("truncate:namespace=")
_, err = strCmd.WriteString(namespace)
}
}
if beforeLastUpdate != nil {
_, err = strCmd.WriteString(";lut=")
_, err = strCmd.WriteString(strconv.FormatInt(beforeLastUpdate.UnixNano(), 10))
} else {
// Servers >= 4.3.1.4 and <= 4.5.0.1 require lut argument.
if node.supportsLUTNow.Get() {
_, err = strCmd.WriteString(";lut=now")
}
}
responseMap, err := RequestInfo(node.tendConn, strCmd.String())
if err != nil {
node.tendConn.Close()
return err
}
response := responseMap[strCmd.String()]
if strings.ToUpper(response) == "OK" {
return nil
}
return NewAerospikeError(SERVER_ERROR, "Truncate failed: "+response)
}
//-------------------------------------------------------
// User administration
//-------------------------------------------------------
// CreateUser creates a new user with password and roles. Clear-text password will be hashed using bcrypt
// before sending to server.
func (clnt *Client) CreateUser(policy *AdminPolicy, user string, password string, roles []string) error {
policy = clnt.getUsableAdminPolicy(policy)
hash, err := hashPassword(password)