This repository has been archived by the owner on Sep 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
/
client.go
2020 lines (1832 loc) · 56.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"
"net/url"
"os"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/golang/protobuf/proto"
"github.com/opentracing/opentracing-go"
pbuf "github.com/pilosa/go-pilosa/gopilosa_pbuf"
"github.com/pilosa/go-pilosa/lru"
"github.com/pilosa/pilosa/roaring"
"github.com/pkg/errors"
"golang.org/x/sync/errgroup"
)
// PQLVersion is the version of PQL expected by the client
const PQLVersion = "1.0"
// DefaultShardWidth is used if an index doesn't have it defined.
const DefaultShardWidth = 1 << 20
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
importManager *recordImportManager
logger *log.Logger
coordinatorURI *URI
coordinatorLock *sync.RWMutex
manualFragmentNode *fragmentNode
manualServerURI *URI
tracer opentracing.Tracer
// Number of retries if an HTTP request fails
retries int
minRetrySleepTime time.Duration
maxRetrySleepTime time.Duration
importLogEncoder encoder
logLock sync.Mutex
shardNodes shardNodes
tick *time.Ticker
done chan struct{}
}
func (c *Client) getURIsForShard(index string, shard uint64) ([]*URI, error) {
uris, ok := c.shardNodes.Get(index, shard)
if ok {
return uris, nil
}
fragmentNodes, err := c.fetchFragmentNodes(index, shard)
if err != nil {
return nil, errors.Wrap(err, "trying to look up nodes for shard")
}
uris = make([]*URI, 0, len(fragmentNodes))
for _, fn := range fragmentNodes {
uris = append(uris, fn.URI())
}
c.shardNodes.Put(index, shard, uris)
return uris, nil
}
func (c *Client) runChangeDetection() {
for {
select {
case <-c.tick.C:
c.detectClusterChanges()
case <-c.done:
return
}
}
}
func (c *Client) Close() error {
c.tick.Stop()
close(c.done)
return nil
}
// detectClusterChanges chooses a random index and shard from the
// shardNodes cache and deletes it. It then looks it up from Pilosa to
// see if it still matches, and if not it drops the whole cache.
func (c *Client) detectClusterChanges() {
c.shardNodes.mu.Lock()
// we rely on Go's random map iteration order to get a random
// element. If it doesn't end up being random, it shouldn't
// actually matter.
for index, shardMap := range c.shardNodes.data {
for shard, uris := range shardMap {
delete(shardMap, shard)
c.shardNodes.data[index] = shardMap
c.shardNodes.mu.Unlock()
newURIs, err := c.getURIsForShard(index, shard) // refetch URIs from server.
if err != nil {
c.logger.Printf("problem invalidating shard node cache: %v", err)
return
}
if len(uris) != len(newURIs) {
c.logger.Printf("invalidating shard node cache old: %s, new: %s", URIs(uris), URIs(newURIs))
c.shardNodes.Invalidate()
return
}
for i := range uris {
u1, u2 := uris[i], newURIs[i]
if *u1 != *u2 {
c.logger.Printf("invalidating shard node cache, uri mismatch at %d old: %s, new: %s", i, URIs(uris), URIs(newURIs))
c.shardNodes.Invalidate()
return
}
}
break
}
break
}
}
// 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 {
client := newClientWithOptions(options)
client.cluster = cluster
return client
}
func newClientWithURI(uri *URI, options *ClientOptions) *Client {
client := newClientWithOptions(options)
if options.manualServerAddress {
fragmentNode := newFragmentNodeFromURI(uri)
client.manualFragmentNode = &fragmentNode
client.manualServerURI = uri
client.cluster = NewClusterWithHost()
}
client.cluster = NewClusterWithHost(uri)
return client
}
func newClientWithOptions(options *ClientOptions) *Client {
if options == nil {
options = &ClientOptions{}
}
options = options.withDefaults()
c := &Client{
client: newHTTPClient(options.withDefaults()),
logger: log.New(os.Stderr, "go-pilosa ", log.Flags()),
coordinatorLock: &sync.RWMutex{},
shardNodes: newShardNodes(),
tick: time.NewTicker(time.Minute),
done: make(chan struct{}, 0),
}
if options.importLogWriter != nil {
c.importLogEncoder = newImportLogEncoder(options.importLogWriter)
}
if options.tracer == nil {
c.tracer = NoopTracer{}
} else {
c.tracer = options.tracer
}
c.retries = *options.retries
c.minRetrySleepTime = 100 * time.Millisecond
c.maxRetrySleepTime = 2 * time.Minute
c.importManager = newRecordImportManager(c)
go c.runChangeDetection()
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
}
return newClientWithURI(uri, clientOptions), nil
case []string:
if len(u) == 1 {
uri, err := NewURIFromAddress(u[0])
if err != nil {
return nil, err
}
return newClientWithURI(uri, clientOptions), nil
} else if clientOptions.manualServerAddress {
return nil, ErrSingleServerAddressRequired
}
return newClientFromAddresses(u, clientOptions)
case *URI:
uriCopy := *u
return newClientWithURI(&uriCopy, clientOptions), nil
case []*URI:
if len(u) == 1 {
uriCopy := *u[0]
return newClientWithURI(&uriCopy, clientOptions), nil
} else if clientOptions.manualServerAddress {
return nil, ErrSingleServerAddressRequired
}
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) {
span := c.tracer.StartSpan("Client.Query")
defer span.Finish()
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.HasWriteKeys()
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 {
span := c.tracer.StartSpan("Client.CreateIndex")
defer span.Finish()
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 {
span := c.tracer.StartSpan("Client.CreateField")
defer span.Finish()
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 errors.Wrap(err, "creating index")
}
// 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 {
return c.DeleteIndexByName(index.Name())
}
// DeleteIndexByName deletes the named index on the server.
func (c *Client) DeleteIndexByName(index string) error {
span := c.tracer.StartSpan("Client.DeleteIndex")
defer span.Finish()
path := fmt.Sprintf("/index/%s", index)
_, _, err := c.httpRequest("DELETE", path, nil, nil, false)
return err
}
// DeleteField deletes a field on the server.
func (c *Client) DeleteField(field *Field) error {
span := c.tracer.StartSpan("Client.DeleteField")
defer span.Finish()
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 {
span := c.tracer.StartSpan("Client.SyncSchema")
defer span.Finish()
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 errors.Wrap(err, "ensuring index")
}
}
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) {
span := c.tracer.StartSpan("Client.Schema")
defer span.Finish()
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.ShardWidth, 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 {
span := c.tracer.StartSpan("Client.ImportField")
defer span.Finish()
importOptions := ImportOptions{}
for _, option := range options {
if err := option(&importOptions); err != nil {
return err
}
}
importOptions = importOptions.withDefaults()
if importOptions.importRecordsFunction == nil {
// if import records function was not already set, set it.
if field.options != nil && field.options.fieldType == FieldTypeInt {
importRecordsFunction(c.importValues)(&importOptions)
} else {
// Check whether roaring imports is available
if importOptions.wantRoaring != nil && *importOptions.wantRoaring == true {
importOptions.hasRoaring = c.hasRoaringImportSupport(field)
}
importRecordsFunction(c.importColumns)(&importOptions)
}
}
// if the index doesn't have its shardWidth set, we need to get it from the schema
if field.index.shardWidth == 0 {
indexes, err := c.readSchema()
if err != nil {
return err
}
for _, index := range indexes {
if index.Name != field.index.name {
continue
}
indexCopy := field.index.copy()
indexCopy.shardWidth = index.ShardWidth
field = field.copy()
field.index = indexCopy
break
}
if field.index.shardWidth == 0 {
// the index does not have shard width, use the default
field.index.shardWidth = DefaultShardWidth
}
}
return c.importManager.run(field, iterator, importOptions)
}
func (c *Client) importColumns(field *Field,
shard uint64,
records []Record,
nodes []fragmentNode,
options *ImportOptions,
state *importState) error {
if len(nodes) == 0 {
return errors.New("No nodes to import to")
}
if options.hasRoaring {
return c.importColumnsRoaring(field, shard, records, nodes, options, state)
}
if !options.skipSort {
sort.Sort(recordSort(records))
}
importReq := columnsToImportRequest(field, shard, records)
path, data, err := importPathData(field, shard, importReq, options)
if err != nil {
return err
}
c.logImport(importReq.GetIndex(), path, shard, false, data)
eg := errgroup.Group{}
for _, node := range nodes {
uri := node.URI()
eg.Go(func() error {
return c.importData(uri, path, data)
})
}
err = eg.Wait()
return errors.Wrap(err, "importing columns to nodes")
}
func (c *Client) importColumnsRoaring(field *Field,
shard uint64,
records []Record,
nodes []fragmentNode,
options *ImportOptions,
state *importState) error {
var err error
shardWidth := field.index.shardWidth
columns := make([]Column, 0, len(records))
for _, rec := range records {
columns = append(columns, rec.(Column))
}
if field.options.keys {
// attempt to translate row keys
if state.rowKeyIDMap == nil {
// create the row key cache if it doesn't exist
state.rowKeyIDMap, err = lru.NewLRU(options.rowKeyCacheSize)
if err != nil {
panic(errors.Wrap(err, "while creating rowKey to ID map"))
}
}
err = c.translateRecordsRowKeys(state.rowKeyIDMap, field, columns)
if err != nil {
return errors.Wrap(err, "translating records row keys")
}
}
if field.index.options.keys {
// attempt to translate column keys
if state.columnKeyIDMap == nil {
// create the column key cache if it doesn't exist
state.columnKeyIDMap, err = lru.NewLRU(options.columnKeyCacheSize)
if err != nil {
panic(errors.Wrap(err, "while creating columnKey to ID map"))
}
}
err = c.translateRecordsColumnKeys(state.columnKeyIDMap, field.index, columns)
if err != nil {
return errors.Wrap(err, "translating records column keys")
}
}
uri := nodes[0].URI()
var views viewImports
if field.options.fieldType == FieldTypeTime {
views = columnsToBitmapTimeField(field.options.timeQuantum, shardWidth, columns, field.options.noStandardView)
} else {
views = columnsToBitmap(shardWidth, columns)
}
return c.importRoaringBitmap(uri, field, shard, views, options)
}
func (c *Client) translateRecordsRowKeys(rowKeyIDMap *lru.LRU, field *Field, columns []Column) error {
uniqueMissingKeys := map[string]struct{}{}
for _, col := range columns {
if !rowKeyIDMap.Contains(col.RowKey) {
uniqueMissingKeys[col.RowKey] = struct{}{}
}
}
keys := make([]string, 0, len(uniqueMissingKeys))
for key := range uniqueMissingKeys {
keys = append(keys, key)
}
if len(keys) > 0 {
// translate missing keys
ids, err := c.TranslateRowKeys(field, keys)
if err != nil {
return err
}
for i, key := range keys {
// we have to add without evicting here lest a key which was in cache prior to adding those not in cache is evicted.
rowKeyIDMap.AddNoEvict(key, ids[i])
}
}
// replace RowKeys with RowIDs
for i, col := range columns {
if rowID, ok := rowKeyIDMap.Get(col.RowKey); ok {
col.RowID = rowID
columns[i] = col
} else {
return fmt.Errorf("Key '%s' does not exist in the rowKey to ID map", col.RowKey)
}
}
// since we called AddNoEvict, we clean up at the end
rowKeyIDMap.Cleanup()
return nil
}
func (c *Client) translateRecordsColumnKeys(columnKeyIDMap *lru.LRU, index *Index, columns []Column) error {
uniqueMissingKeys := map[string]struct{}{}
for _, col := range columns {
if !columnKeyIDMap.Contains(col.ColumnKey) {
uniqueMissingKeys[col.ColumnKey] = struct{}{}
}
}
keys := make([]string, 0, len(uniqueMissingKeys))
for key := range uniqueMissingKeys {
keys = append(keys, key)
}
if len(keys) > 0 {
// translate missing keys
ids, err := c.TranslateColumnKeys(index, keys)
if err != nil {
return err
}
for i, key := range keys {
columnKeyIDMap.Add(key, ids[i])
}
}
// replace ColumnKeys with ColumnIDs
for i, col := range columns {
if columnID, ok := columnKeyIDMap.Get(col.ColumnKey); ok {
col.ColumnID = columnID
columns[i] = col
} else {
return fmt.Errorf("Key '%s' does not exist in the columnKey to ID map", col.ColumnKey)
}
}
return nil
}
func (c *Client) hasRoaringImportSupport(field *Field) bool {
if field.options.fieldType != FieldTypeSet &&
field.options.fieldType != FieldTypeDefault &&
field.options.fieldType != FieldTypeBool &&
field.options.fieldType != FieldTypeTime {
// Roaring imports is available for only set, bool and time fields.
return false
}
// Check whether the roaring import endpoint exists
path := makeRoaringImportPath(field, 0, url.Values{})
// err may contain an HTTP error, but we don't use it.
resp, _, _ := c.httpRequest("GET", path, nil, nil, false)
if resp == nil {
return false
}
if resp.StatusCode == http.StatusMethodNotAllowed || resp.StatusCode == http.StatusOK {
// Roaring import endpoint exists
return true
}
return false
}
func (c *Client) importValues(field *Field,
shard uint64,
vals []Record,
nodes []fragmentNode,
options *ImportOptions,
state *importState) error {
sort.Sort(recordSort(vals))
importReq := valsToImportRequest(field, shard, vals)
path, data, err := importPathData(field, shard, importReq, options)
if err != nil {
return err
}
c.logImport(importReq.GetIndex(), path, shard, false, data)
eg := errgroup.Group{}
for _, node := range nodes {
uri := node.URI()
eg.Go(func() error {
return c.importData(uri, path, data)
})
}
err = eg.Wait()
return errors.Wrap(err, "importing values to nodes")
}
// ImportValues takes the given integer values and column ids (which
// must all be in the given shard) and imports them into the given
// index,field,shard on all nodes which should hold that shard. It
// assumes that the ids have been translated from keys if necessary
// and so tells Pilosa to ignore checking if the index uses column
// keys. ImportValues wraps EncodeImportValues and DoImportValues —
// these are broken out and exported so that performance conscious
// users can re-use the same vals and ids byte buffers for local
// encoding, while performing the imports concurrently.
func (c *Client) ImportValues(index, field string, shard uint64, vals []int64, ids []uint64, clear bool) error {
path, data, err := c.EncodeImportValues(index, field, shard, vals, ids, clear)
if err != nil {
return errors.Wrap(err, "encoding import-values request")
}
err = c.DoImportValues(index, shard, path, data)
return errors.Wrap(err, "doing import values")
}
// EncodeImportValues computes the HTTP path and payload for an
// import-values request. It is typically followed by a call to
// DoImportValues.
func (c *Client) EncodeImportValues(index, field string, shard uint64, vals []int64, ids []uint64, clear bool) (path string, data []byte, err error) {
msg := &pbuf.ImportValueRequest{
Index: index,
Field: field,
Shard: shard,
ColumnIDs: ids,
Values: vals,
}
data, err = proto.Marshal(msg)
if err != nil {
return "", nil, errors.Wrap(err, "marshaling to protobuf")
}
path = fmt.Sprintf("/index/%s/field/%s/import?clear=%s&ignoreKeyCheck=true", index, field, strconv.FormatBool(clear))
return path, data, nil
}
// DoImportValues takes a path and data payload (normally from
// EncodeImportValues), logs the import, finds all nodes which own
// this shard, and concurrently imports to those nodes.
func (c *Client) DoImportValues(index string, shard uint64, path string, data []byte) error {
c.logImport(index, path, shard, false, data)
uris, err := c.getURIsForShard(index, shard)
if err != nil {
return errors.Wrap(err, "getting uris")
}
eg := errgroup.Group{}
for _, uri := range uris {
eg.Go(func() error {
return c.importData(uri, path, data)
})
}
return errors.Wrap(eg.Wait(), "importing values to nodes")
}
func importPathData(field *Field, shard uint64, msg proto.Message, options *ImportOptions) (path string, data []byte, err error) {
data, err = proto.Marshal(msg)
if err != nil {
return "", nil, errors.Wrap(err, "marshaling to protobuf")
}
params := url.Values{}
params.Add("clear", strconv.FormatBool(options.clear))
path = fmt.Sprintf("/index/%s/field/%s/import?%s", field.index.Name(), field.Name(), params.Encode())
return path, data, nil
}
func (c *Client) fetchFragmentNodes(indexName string, shard uint64) ([]fragmentNode, error) {
if c.manualFragmentNode != nil {
return []fragmentNode{*c.manualFragmentNode}, nil
}
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) {
if c.manualFragmentNode != nil {
return *c.manualFragmentNode, nil
}
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) importData(uri *URI, path string, data []byte) error {
resp, err := c.doRequest(uri, "POST", path, defaultProtobufHeaders(), data)
if err = anyError(resp, err); err != nil {
return errors.Wrapf(err, "import to %s", uri.HostPort())
}
defer resp.Body.Close()
return nil
}
// ImportRoaringBitmap can import pre-made bitmaps for a number of
// different views into the given field/shard. If the view name in the
// map is an empty string, the standard view will be used.
func (c *Client) ImportRoaringBitmap(field *Field, shard uint64, views map[string]*roaring.Bitmap, clear bool) error {
uris, err := c.getURIsForShard(field.index.Name(), shard)
if err != nil {
return errors.Wrap(err, "getting URIs for import")
}
err = c.importRoaringBitmap(uris[0], field, shard, views, &ImportOptions{clear: clear})
return errors.Wrap(err, "importing bitmap")
}
func (c *Client) importRoaringBitmap(uri *URI, field *Field, shard uint64, views viewImports, options *ImportOptions) error {
protoViews := []*pbuf.ImportRoaringRequestView{}
for name, bmp := range views {
buf := &bytes.Buffer{}
_, err := bmp.WriteTo(buf)
if err != nil {
return errors.Wrap(err, "marshalling bitmap")
}
protoViews = append(protoViews, &pbuf.ImportRoaringRequestView{
Name: name,
Data: buf.Bytes(),
})
}
params := url.Values{}
params.Add("clear", strconv.FormatBool(options.clear))
path := makeRoaringImportPath(field, shard, params)
req := &pbuf.ImportRoaringRequest{
Clear: options.clear,
Views: protoViews,
}
data, err := proto.Marshal(req)
if err != nil {
return err
}
c.logImport(field.index.Name(), path, shard, true, data)
resp, err := c.doRequest(uri, "POST", path, defaultProtobufHeaders(), data)
if err = anyError(resp, err); err != nil {
return errors.Wrapf(err, "roaring import to %s", uri.HostPort())
}
defer resp.Body.Close()
return nil
}
// ExportField exports columns for a field.
func (c *Client) ExportField(field *Field) (io.Reader, error) {
span := c.tracer.StartSpan("Client.ExportField")
defer span.Finish()
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
}
// Info returns the server's configuration/host information.
func (c *Client) Info() (Info, error) {
span := c.tracer.StartSpan("Client.Info")
defer span.Finish()
_, data, err := c.httpRequest("GET", "/info", nil, nil, false)
if err != nil {
return Info{}, errors.Wrap(err, "requesting /info")
}
info := Info{}
err = json.Unmarshal(data, &info)
if err != nil {
return Info{}, errors.Wrap(err, "unmarshaling /info data")
}
return info, nil
}
// Status returns the server's status.
func (c *Client) Status() (Status, error) {
span := c.tracer.StartSpan("Client.Status")
defer span.Finish()
_, 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) {
span := c.tracer.StartSpan("Client.HttpRequest")
defer span.Finish()
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