forked from FeatureBaseDB/go-pilosa
/
client.go
1133 lines (1020 loc) · 30.2 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 2017 Pilosa Corp.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
// CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
package pilosa
import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"strings"
"sync"
"time"
"github.com/golang/protobuf/proto"
pbuf "github.com/pilosa/go-pilosa/gopilosa_pbuf"
"github.com/pkg/errors"
"golang.org/x/sync/errgroup"
)
const PQLVersion = "1.0"
const maxHosts = 10
// Client is the HTTP client for Pilosa server.
type Client struct {
cluster *Cluster
client *http.Client
// User-Agent header cache. Not used until cluster-resize support branch is merged
// and user agent is saved here in NewClient
userAgent string
importThreadCount int
shardWidth uint64
importManager *recordImportManager
logger *log.Logger
coordinatorURI *URI
coordinatorLock *sync.RWMutex
}
// DefaultClient creates a client with the default address and options.
func DefaultClient() *Client {
return newClientWithCluster(NewClusterWithHost(DefaultURI()), nil)
}
func newClientFromAddresses(addresses []string, options *ClientOptions) (*Client, error) {
uris := make([]*URI, len(addresses))
for i, address := range addresses {
uri, err := NewURIFromAddress(address)
if err != nil {
return nil, err
}
uris[i] = uri
}
cluster := NewClusterWithHost(uris...)
client := newClientWithCluster(cluster, options)
return client, nil
}
func newClientWithCluster(cluster *Cluster, options *ClientOptions) *Client {
if options == nil {
options = &ClientOptions{}
}
options = options.withDefaults()
c := &Client{
cluster: cluster,
client: newHTTPClient(options.withDefaults()),
logger: log.New(os.Stderr, "go-pilosa ", log.Flags()),
coordinatorLock: &sync.RWMutex{},
}
c.importManager = newRecordImportManager(c)
return c
}
// NewClient creates a client with the given address, URI, or cluster and options.
func NewClient(addrUriOrCluster interface{}, options ...ClientOption) (*Client, error) {
var cluster *Cluster
clientOptions := &ClientOptions{}
err := clientOptions.addOptions(options...)
if err != nil {
return nil, err
}
switch u := addrUriOrCluster.(type) {
case string:
uri, err := NewURIFromAddress(u)
if err != nil {
return nil, err
}
cluster = NewClusterWithHost(uri)
case []string:
return newClientFromAddresses(u, clientOptions)
case *URI:
cluster = NewClusterWithHost(u)
case []*URI:
cluster = NewClusterWithHost(u...)
case *Cluster:
cluster = u
case nil:
cluster = NewClusterWithHost()
default:
return nil, ErrAddrURIClusterExpected
}
return newClientWithCluster(cluster, clientOptions), nil
}
// Query runs the given query against the server with the given options.
// Pass nil for default options.
func (c *Client) Query(query PQLQuery, options ...interface{}) (*QueryResponse, error) {
if err := query.Error(); err != nil {
return nil, err
}
queryOptions := &QueryOptions{}
err := queryOptions.addOptions(options...)
if err != nil {
return nil, err
}
serializedQuery := query.serialize()
data, err := makeRequestData(serializedQuery.String(), queryOptions)
if err != nil {
return nil, errors.Wrap(err, "making request data")
}
useCoordinator := serializedQuery.HasKeys
path := fmt.Sprintf("/index/%s/query", query.Index().name)
_, buf, err := c.httpRequest("POST", path, data, defaultProtobufHeaders(), useCoordinator)
if err != nil {
return nil, err
}
iqr := &pbuf.QueryResponse{}
err = proto.Unmarshal(buf, iqr)
if err != nil {
return nil, err
}
queryResponse, err := newQueryResponseFromInternal(iqr)
if err != nil {
return nil, err
}
return queryResponse, nil
}
// CreateIndex creates an index on the server using the given Index struct.
func (c *Client) CreateIndex(index *Index) error {
data := []byte(index.options.String())
path := fmt.Sprintf("/index/%s", index.name)
response, _, err := c.httpRequest("POST", path, data, nil, false)
if err != nil {
if response != nil && response.StatusCode == 409 {
return ErrIndexExists
}
return err
}
return nil
}
// CreateField creates a field on the server using the given Field struct.
func (c *Client) CreateField(field *Field) error {
data := []byte(field.options.String())
path := fmt.Sprintf("/index/%s/field/%s", field.index.name, field.name)
response, _, err := c.httpRequest("POST", path, data, nil, false)
if err != nil {
if response != nil && response.StatusCode == 409 {
return ErrFieldExists
}
return err
}
return nil
}
// EnsureIndex creates an index on the server if it does not exist.
func (c *Client) EnsureIndex(index *Index) error {
err := c.CreateIndex(index)
if err == ErrIndexExists {
return nil
}
return err
}
// EnsureField creates a field on the server if it doesn't exists.
func (c *Client) EnsureField(field *Field) error {
err := c.CreateField(field)
if err == ErrFieldExists {
return nil
}
return err
}
// DeleteIndex deletes an index on the server.
func (c *Client) DeleteIndex(index *Index) error {
path := fmt.Sprintf("/index/%s", index.name)
_, _, err := c.httpRequest("DELETE", path, nil, nil, false)
return err
}
// DeleteField deletes a field on the server.
func (c *Client) DeleteField(field *Field) error {
path := fmt.Sprintf("/index/%s/field/%s", field.index.name, field.name)
_, _, err := c.httpRequest("DELETE", path, nil, nil, false)
return err
}
// SyncSchema updates a schema with the indexes and fields on the server and
// creates the indexes and fields in the schema on the server side.
// This function does not delete indexes and the fields on the server side nor in the schema.
func (c *Client) SyncSchema(schema *Schema) error {
serverSchema, err := c.Schema()
if err != nil {
return err
}
return c.syncSchema(schema, serverSchema)
}
func (c *Client) syncSchema(schema *Schema, serverSchema *Schema) error {
var err error
// find out local - remote schema
diffSchema := schema.diff(serverSchema)
// create the indexes and fields which doesn't exist on the server side
for indexName, index := range diffSchema.indexes {
if _, ok := serverSchema.indexes[indexName]; !ok {
err = c.EnsureIndex(index)
if err != nil {
return err
}
}
for _, field := range index.fields {
err = c.EnsureField(field)
if err != nil {
return err
}
}
}
// find out remote - local schema
diffSchema = serverSchema.diff(schema)
for indexName, index := range diffSchema.indexes {
if localIndex, ok := schema.indexes[indexName]; !ok {
schema.indexes[indexName] = index
} else {
for fieldName, field := range index.fields {
localIndex.fields[fieldName] = field
}
}
}
return nil
}
// Schema returns the indexes and fields on the server.
func (c *Client) Schema() (*Schema, error) {
var indexes []SchemaIndex
indexes, err := c.readSchema()
if err != nil {
return nil, err
}
schema := NewSchema()
for _, indexInfo := range indexes {
index := schema.indexWithOptions(indexInfo.Name, indexInfo.Options.asIndexOptions())
for _, fieldInfo := range indexInfo.Fields {
index.fieldWithOptions(fieldInfo.Name, fieldInfo.Options.asFieldOptions())
}
}
return schema, nil
}
// ImportField imports records from the given iterator.
func (c *Client) ImportField(field *Field, iterator RecordIterator, options ...ImportOption) error {
importOptions := &ImportOptions{}
if field.options != nil && field.options.fieldType == FieldTypeInt {
importRecordsFunction(c.importValues)(importOptions)
} else {
importRecordsFunction(c.importColumns)(importOptions)
}
for _, option := range options {
if err := option(importOptions); err != nil {
return err
}
}
return c.importManager.Run(field, iterator, importOptions.withDefaults())
}
func (c *Client) importColumns(field *Field, shard uint64, records []Record, nodes []fragmentNode) error {
eg := errgroup.Group{}
for _, node := range nodes {
uri := &URI{
scheme: node.Scheme,
host: node.Host,
port: node.Port,
}
eg.Go(func() error {
return c.importNode(uri, columnsToImportRequest(field, shard, records))
})
}
err := eg.Wait()
return errors.Wrap(err, "importing columns to nodes")
}
func (c *Client) importValues(field *Field, shard uint64, vals []Record, nodes []fragmentNode) error {
eg := errgroup.Group{}
for _, node := range nodes {
uri := &URI{
scheme: node.Scheme,
host: node.Host,
port: node.Port,
}
eg.Go(func() error {
return c.importValueNode(uri, valsToImportRequest(field, shard, vals))
})
}
err := eg.Wait()
return errors.Wrap(err, "importing values to nodes")
}
func (c *Client) fetchFragmentNodes(indexName string, shard uint64) ([]fragmentNode, error) {
path := fmt.Sprintf("/internal/fragment/nodes?shard=%d&index=%s", shard, indexName)
_, body, err := c.httpRequest("GET", path, []byte{}, nil, false)
if err != nil {
return nil, err
}
fragmentNodes := []fragmentNode{}
var fragmentNodeURIs []fragmentNodeRoot
err = json.Unmarshal(body, &fragmentNodeURIs)
if err != nil {
return nil, errors.Wrap(err, "unmarshaling fragment node URIs")
}
for _, nodeURI := range fragmentNodeURIs {
fragmentNodes = append(fragmentNodes, nodeURI.URI)
}
return fragmentNodes, nil
}
func (c *Client) fetchCoordinatorNode() (fragmentNode, error) {
status, err := c.Status()
if err != nil {
return fragmentNode{}, err
}
for _, node := range status.Nodes {
if node.IsCoordinator {
nodeURI := node.URI
return fragmentNode{
Scheme: nodeURI.Scheme,
Host: nodeURI.Host,
Port: nodeURI.Port,
}, nil
}
}
return fragmentNode{}, errors.New("Coordinator node not found")
}
func (c *Client) importNode(uri *URI, request *pbuf.ImportRequest) error {
data, err := proto.Marshal(request)
if err != nil {
return errors.Wrap(err, "marshaling to protobuf")
}
return c.importData(uri, request.GetIndex(), request.GetField(), data)
}
func (c *Client) importValueNode(uri *URI, request *pbuf.ImportValueRequest) error {
data, err := proto.Marshal(request)
if err != nil {
return errors.Wrap(err, "marshaling to protobuf")
}
return c.importData(uri, request.GetIndex(), request.GetField(), data)
}
func (c *Client) importData(uri *URI, indexName string, fieldName string, data []byte) error {
path := fmt.Sprintf("/index/%s/field/%s/import", indexName, fieldName)
resp, err := c.doRequest(uri, "POST", path, defaultProtobufHeaders(), bytes.NewReader(data))
if err = anyError(resp, err); err != nil {
return errors.Wrap(err, "doing import")
}
defer resp.Body.Close()
return nil
}
// ExportField exports columns for a field.
func (c *Client) ExportField(field *Field) (io.Reader, error) {
var shardsMax map[string]uint64
var err error
status, err := c.Status()
if err != nil {
return nil, err
}
shardsMax, err = c.shardsMax()
if err != nil {
return nil, err
}
status.indexMaxShard = shardsMax
shardURIs, err := c.statusToNodeShardsForIndex(status, field.index.Name())
if err != nil {
return nil, err
}
return newExportReader(c, shardURIs, field), nil
}
// Status returns the serves status.
func (c *Client) Status() (Status, error) {
_, data, err := c.httpRequest("GET", "/status", nil, nil, false)
if err != nil {
return Status{}, errors.Wrap(err, "requesting /status")
}
status := Status{}
err = json.Unmarshal(data, &status)
if err != nil {
return Status{}, errors.Wrap(err, "unmarshaling /status data")
}
return status, nil
}
func (c *Client) readSchema() ([]SchemaIndex, error) {
_, data, err := c.httpRequest("GET", "/schema", nil, nil, false)
if err != nil {
return nil, errors.Wrap(err, "requesting /schema")
}
schemaInfo := SchemaInfo{}
err = json.Unmarshal(data, &schemaInfo)
if err != nil {
return nil, errors.Wrap(err, "unmarshaling /schema data")
}
return schemaInfo.Indexes, nil
}
func (c *Client) shardsMax() (map[string]uint64, error) {
_, data, err := c.httpRequest("GET", "/internal/shards/max", nil, nil, false)
if err != nil {
return nil, errors.Wrap(err, "requesting /internal/shards/max")
}
m := map[string]map[string]uint64{}
err = json.Unmarshal(data, &m)
if err != nil {
return nil, errors.Wrap(err, "unmarshaling /internal/shards/max data")
}
return m["standard"], nil
}
// HttpRequest sends an HTTP request to the Pilosa server.
// **NOTE**: This function is experimental and may be removed in later revisions.
func (c *Client) HttpRequest(method string, path string, data []byte, headers map[string]string) (*http.Response, []byte, error) {
return c.httpRequest(method, path, data, headers, false)
}
// httpRequest makes a request to the cluster - use this when you want the
// client to choose a host, and it doesn't matter if the request goes to a
// specific host
func (c *Client) httpRequest(method string, path string, data []byte, headers map[string]string, useCoordinator bool) (*http.Response, []byte, error) {
if data == nil {
data = []byte{}
}
// try at most maxHosts non-failed hosts; protect against broken cluster.removeHost
var response *http.Response
var err error
for i := 0; i < maxHosts; i++ {
reader := bytes.NewReader(data)
host, err := c.host(useCoordinator)
if err != nil {
return nil, nil, err
}
response, err = c.doRequest(host, method, path, c.augmentHeaders(headers), reader)
if err == nil {
break
}
if useCoordinator {
c.coordinatorLock.Lock()
c.coordinatorURI = nil
c.coordinatorLock.Unlock()
} else {
c.cluster.RemoveHost(host)
}
}
if response == nil {
return nil, nil, ErrTriedMaxHosts
}
defer response.Body.Close()
warning := response.Header.Get("warning")
if warning != "" {
c.logger.Println(warning)
}
// TODO: Optimize buffer creation
buf, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, nil, err
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
err := NewError(fmt.Sprintf("Server error (%d) %s: %s", response.StatusCode, response.Status, string(buf)))
return response, buf, err
}
return response, buf, nil
}
func (c *Client) host(useCoordinator bool) (*URI, error) {
var host *URI
if useCoordinator {
c.coordinatorLock.RLock()
host = c.coordinatorURI
c.coordinatorLock.RUnlock()
if host == nil {
c.coordinatorLock.Lock()
if c.coordinatorURI == nil {
node, err := c.fetchCoordinatorNode()
if err != nil {
c.coordinatorLock.Unlock()
return nil, errors.Wrap(err, "fetching coordinator node")
}
host = URIFromAddress(fmt.Sprintf("%s://%s:%d", node.Scheme, node.Host, node.Port))
} else {
host = c.coordinatorURI
}
c.coordinatorURI = host
c.coordinatorLock.Unlock()
}
} else {
// get a host from the cluster
host = c.cluster.Host()
if host == nil {
return nil, ErrEmptyCluster
}
}
return host, nil
}
// anyError checks an http Response and error to see if anything went wrong with
// a request (either locally, or on the server) and returns a single error if
// so.
func anyError(resp *http.Response, err error) error {
if err != nil {
return errors.Wrap(err, "unable to perform request")
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
defer resp.Body.Close()
buf, err := ioutil.ReadAll(resp.Body)
if err != nil {
return errors.Wrapf(err, "bad status '%s' and err reading body", resp.Status)
}
msg := string(buf)
return errors.Errorf("Server error %s body:'%s'", resp.Status, msg)
}
return nil
}
// doRequest creates and performs an http request.
func (c *Client) doRequest(host *URI, method, path string, headers map[string]string, reader io.Reader) (*http.Response, error) {
req, err := makeRequest(host, method, path, headers, reader)
if err != nil {
return nil, errors.Wrap(err, "building request")
}
return c.client.Do(req)
}
// statusToNodeShardsForIndex finds the hosts which contains shards for the given index
func (c *Client) statusToNodeShardsForIndex(status Status, indexName string) (map[uint64]*URI, error) {
result := make(map[uint64]*URI)
if maxShard, ok := status.indexMaxShard[indexName]; ok {
for shard := 0; shard <= int(maxShard); shard++ {
fragmentNodes, err := c.fetchFragmentNodes(indexName, uint64(shard))
if err != nil {
return nil, err
}
if len(fragmentNodes) == 0 {
return nil, ErrNoFragmentNodes
}
node := fragmentNodes[0]
uri := &URI{
host: node.Host,
port: node.Port,
scheme: node.Scheme,
}
result[uint64(shard)] = uri
}
} else {
return nil, ErrNoShard
}
return result, nil
}
func (c *Client) augmentHeaders(headers map[string]string) map[string]string {
if headers == nil {
headers = map[string]string{}
}
// TODO: move the following block to NewClient once cluster-resize support branch is merged.
version := Version
if strings.HasPrefix(version, "v") {
version = version[1:]
}
headers["User-Agent"] = fmt.Sprintf("go-pilosa/%s", version)
return headers
}
func defaultProtobufHeaders() map[string]string {
return map[string]string{
"Content-Type": "application/x-protobuf",
"Accept": "application/x-protobuf",
"PQL-Version": PQLVersion,
}
}
func makeRequest(host *URI, method, path string, headers map[string]string, reader io.Reader) (*http.Request, error) {
request, err := http.NewRequest(method, host.Normalize()+path, reader)
if err != nil {
return nil, err
}
for k, v := range headers {
request.Header.Set(k, v)
}
return request, nil
}
func newHTTPClient(options *ClientOptions) *http.Client {
transport := &http.Transport{
Dial: (&net.Dialer{
Timeout: options.ConnectTimeout,
}).Dial,
TLSClientConfig: options.TLSConfig,
MaxIdleConnsPerHost: options.PoolSizePerRoute,
MaxIdleConns: options.TotalPoolSize,
}
return &http.Client{
Transport: transport,
Timeout: options.SocketTimeout,
}
}
func makeRequestData(query string, options *QueryOptions) ([]byte, error) {
request := &pbuf.QueryRequest{
Query: query,
Shards: options.Shards,
ColumnAttrs: options.ColumnAttrs,
ExcludeRowAttrs: options.ExcludeRowAttrs,
ExcludeColumns: options.ExcludeColumns,
}
r, err := proto.Marshal(request)
if err != nil {
return nil, errors.Wrap(err, "marshaling request to protobuf")
}
return r, nil
}
func columnsToImportRequest(field *Field, shard uint64, records []Record) *pbuf.ImportRequest {
var rowIDs []uint64
var columnIDs []uint64
var rowKeys []string
var columnKeys []string
recordCount := len(records)
timestamps := make([]int64, 0, recordCount)
hasRowKeys := field.options.keys
hasColKeys := field.index.options.keys
if hasRowKeys {
rowKeys = make([]string, 0, recordCount)
} else {
rowIDs = make([]uint64, 0, recordCount)
}
if hasColKeys {
columnKeys = make([]string, 0, recordCount)
} else {
columnIDs = make([]uint64, 0, recordCount)
}
for _, record := range records {
column := record.(Column)
if hasRowKeys {
rowKeys = append(rowKeys, column.RowKey)
} else {
rowIDs = append(rowIDs, column.RowID)
}
if hasColKeys {
columnKeys = append(columnKeys, column.ColumnKey)
} else {
columnIDs = append(columnIDs, column.ColumnID)
}
timestamps = append(timestamps, column.Timestamp)
}
return &pbuf.ImportRequest{
Index: field.index.name,
Field: field.name,
Shard: shard,
RowIDs: rowIDs,
ColumnIDs: columnIDs,
RowKeys: rowKeys,
ColumnKeys: columnKeys,
Timestamps: timestamps,
}
}
func valsToImportRequest(field *Field, shard uint64, vals []Record) *pbuf.ImportValueRequest {
var columnIDs []uint64
var columnKeys []string
values := make([]int64, 0, len(vals))
keys := field.index.options.keys
if keys {
columnKeys = make([]string, 0, len(vals))
} else {
columnIDs = make([]uint64, 0, len(vals))
}
for _, record := range vals {
val := record.(FieldValue)
if keys {
columnKeys = append(columnKeys, val.ColumnKey)
} else {
columnIDs = append(columnIDs, val.ColumnID)
}
values = append(values, val.Value)
}
return &pbuf.ImportValueRequest{
Index: field.index.name,
Field: field.name,
Shard: shard,
ColumnIDs: columnIDs,
ColumnKeys: columnKeys,
Values: values,
}
}
// ClientOptions control the properties of client connection to the server.
type ClientOptions struct {
SocketTimeout time.Duration
ConnectTimeout time.Duration
PoolSizePerRoute int
TotalPoolSize int
TLSConfig *tls.Config
}
func (co *ClientOptions) addOptions(options ...ClientOption) error {
for _, option := range options {
err := option(co)
if err != nil {
return err
}
}
return nil
}
// ClientOption is used when creating a PilosaClient struct.
type ClientOption func(options *ClientOptions) error
// OptClientSocketTimeout is the maximum idle socket time in nanoseconds
func OptClientSocketTimeout(timeout time.Duration) ClientOption {
return func(options *ClientOptions) error {
options.SocketTimeout = timeout
return nil
}
}
// OptClientConnectTimeout is the maximum time to connect in nanoseconds.
func OptClientConnectTimeout(timeout time.Duration) ClientOption {
return func(options *ClientOptions) error {
options.ConnectTimeout = timeout
return nil
}
}
// OptPoolSizePerRoute is the maximum number of active connections in the pool to a host.
func OptClientPoolSizePerRoute(size int) ClientOption {
return func(options *ClientOptions) error {
options.PoolSizePerRoute = size
return nil
}
}
// OptClientTotalPoolSize is the maximum number of connections in the pool.
func OptClientTotalPoolSize(size int) ClientOption {
return func(options *ClientOptions) error {
options.TotalPoolSize = size
return nil
}
}
// OptClientTLSConfig contains the TLS configuration.
func OptClientTLSConfig(config *tls.Config) ClientOption {
return func(options *ClientOptions) error {
options.TLSConfig = config
return nil
}
}
type versionInfo struct {
Version string `json:"version"`
}
func (co *ClientOptions) withDefaults() (updated *ClientOptions) {
// copy options so the original is not updated
updated = &ClientOptions{}
*updated = *co
// impose defaults
if updated.SocketTimeout <= 0 {
updated.SocketTimeout = time.Second * 300
}
if updated.ConnectTimeout <= 0 {
updated.ConnectTimeout = time.Second * 60
}
if updated.PoolSizePerRoute <= 0 {
updated.PoolSizePerRoute = 10
}
if updated.TotalPoolSize <= 0 {
updated.TotalPoolSize = 100
}
if updated.TLSConfig == nil {
updated.TLSConfig = &tls.Config{}
}
return
}
// QueryOptions contains options to customize the Query function.
type QueryOptions struct {
// Shards restricts query to a subset of shards. Queries all shards if nil.
Shards []uint64
// ColumnAttrs enables returning columns in the query response.
ColumnAttrs bool
// ExcludeRowAttrs inhibits returning attributes
ExcludeRowAttrs bool
// ExcludeColumns inhibits returning columns
ExcludeColumns bool
}
func (qo *QueryOptions) addOptions(options ...interface{}) error {
for i, option := range options {
switch o := option.(type) {
case nil:
if i != 0 {
return ErrInvalidQueryOption
}
continue
case *QueryOptions:
if i != 0 {
return ErrInvalidQueryOption
}
*qo = *o
case QueryOption:
err := o(qo)
if err != nil {
return err
}
default:
return ErrInvalidQueryOption
}
}
return nil
}
// QueryOption is used when using options with a client.Query,
type QueryOption func(options *QueryOptions) error
// OptQueryColumnAttrs enables returning column attributes in the result.
func OptQueryColumnAttrs(enable bool) QueryOption {
return func(options *QueryOptions) error {
options.ColumnAttrs = enable
return nil
}
}
// OptQueryShards restricts the set of shards on which a query operates.
func OptQueryShards(shards ...uint64) QueryOption {
return func(options *QueryOptions) error {
options.Shards = append(options.Shards, shards...)
return nil
}
}
// OptQueryExcludeAttrs enables discarding attributes from a result,
func OptQueryExcludeAttrs(enable bool) QueryOption {
return func(options *QueryOptions) error {
options.ExcludeRowAttrs = enable
return nil
}
}
// OptQueryExcludeColumns enables discarding columns from a result,
func OptQueryExcludeColumns(enable bool) QueryOption {
return func(options *QueryOptions) error {
options.ExcludeColumns = enable
return nil
}
}
type ImportWorkerStrategy int
const (
DefaultImport ImportWorkerStrategy = iota
BatchImport
TimeoutImport
)
type ImportOptions struct {
threadCount int
shardWidth uint64
timeout time.Duration
batchSize int
strategy ImportWorkerStrategy
statusChan chan<- ImportStatusUpdate
importRecordsFunction func(field *Field, shard uint64, records []Record, nodes []fragmentNode) error
}
func (opt *ImportOptions) withDefaults() (updated ImportOptions) {
updated = *opt
updated.shardWidth = 1048576
if updated.threadCount <= 0 {
updated.threadCount = 1
}
if updated.timeout <= 0 {
updated.timeout = 100 * time.Millisecond
}
if updated.batchSize <= 0 {
updated.batchSize = 100000
}
if updated.strategy == DefaultImport {
updated.strategy = BatchImport
}
return
}
// ImportOption is used when running imports.
type ImportOption func(options *ImportOptions) error
func OptImportThreadCount(count int) ImportOption {
return func(options *ImportOptions) error {
options.threadCount = count
return nil
}
}
func OptImportTimeout(timeout time.Duration) ImportOption {
return func(options *ImportOptions) error {
options.timeout = timeout
return nil
}
}
func OptImportBatchSize(batchSize int) ImportOption {
return func(options *ImportOptions) error {
options.batchSize = batchSize
return nil
}
}
func OptImportStrategy(strategy ImportWorkerStrategy) ImportOption {
return func(options *ImportOptions) error {
options.strategy = strategy
return nil
}
}
func OptImportStatusChannel(statusChan chan<- ImportStatusUpdate) ImportOption {
return func(options *ImportOptions) error {
options.statusChan = statusChan
return nil
}
}