repo stringlengths 5 67 | path stringlengths 4 218 | func_name stringlengths 0 151 | original_string stringlengths 52 373k | language stringclasses 6 values | code stringlengths 52 373k | code_tokens listlengths 10 512 | docstring stringlengths 3 47.2k | docstring_tokens listlengths 3 234 | sha stringlengths 40 40 | url stringlengths 85 339 | partition stringclasses 3 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
pilosa/pilosa | fragment.go | incrementOpN | func (f *fragment) incrementOpN() error {
f.opN++
if f.opN <= f.MaxOpN {
return nil
}
if err := f.snapshot(); err != nil {
return fmt.Errorf("snapshot: %s", err)
}
return nil
} | go | func (f *fragment) incrementOpN() error {
f.opN++
if f.opN <= f.MaxOpN {
return nil
}
if err := f.snapshot(); err != nil {
return fmt.Errorf("snapshot: %s", err)
}
return nil
} | [
"func",
"(",
"f",
"*",
"fragment",
")",
"incrementOpN",
"(",
")",
"error",
"{",
"f",
".",
"opN",
"++",
"\n",
"if",
"f",
".",
"opN",
"<=",
"f",
".",
"MaxOpN",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"err",
":=",
"f",
".",
"snapshot",
"(",
... | // incrementOpN increase the operation count by one.
// If the count exceeds the maximum allowed then a snapshot is performed. | [
"incrementOpN",
"increase",
"the",
"operation",
"count",
"by",
"one",
".",
"If",
"the",
"count",
"exceeds",
"the",
"maximum",
"allowed",
"then",
"a",
"snapshot",
"is",
"performed",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/fragment.go#L1896-L1906 | train |
pilosa/pilosa | fragment.go | Snapshot | func (f *fragment) Snapshot() error {
f.mu.Lock()
defer f.mu.Unlock()
return f.snapshot()
} | go | func (f *fragment) Snapshot() error {
f.mu.Lock()
defer f.mu.Unlock()
return f.snapshot()
} | [
"func",
"(",
"f",
"*",
"fragment",
")",
"Snapshot",
"(",
")",
"error",
"{",
"f",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"f",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"f",
".",
"snapshot",
"(",
")",
"\n",
"}"
] | // Snapshot writes the storage bitmap to disk and reopens it. | [
"Snapshot",
"writes",
"the",
"storage",
"bitmap",
"to",
"disk",
"and",
"reopens",
"it",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/fragment.go#L1909-L1913 | train |
pilosa/pilosa | fragment.go | unprotectedWriteToFragment | func unprotectedWriteToFragment(f *fragment, bm *roaring.Bitmap) (n int64, err error) { // nolint: interfacer
completeMessage := fmt.Sprintf("fragment: snapshot complete %s/%s/%s/%d", f.index, f.field, f.view, f.shard)
start := time.Now()
defer track(start, completeMessage, f.stats, f.Logger)
// Create a temporary file to snapshot to.
snapshotPath := f.path + snapshotExt
file, err := os.Create(snapshotPath)
if err != nil {
return n, fmt.Errorf("create snapshot file: %s", err)
}
defer file.Close()
// Write storage to snapshot.
bw := bufio.NewWriter(file)
if n, err = bm.WriteTo(bw); err != nil {
return n, fmt.Errorf("snapshot write to: %s", err)
}
if err := bw.Flush(); err != nil {
return n, fmt.Errorf("flush: %s", err)
}
// Close current storage.
if err := f.closeStorage(); err != nil {
return n, fmt.Errorf("close storage: %s", err)
}
// Move snapshot to data file location.
if err := os.Rename(snapshotPath, f.path); err != nil {
return n, fmt.Errorf("rename snapshot: %s", err)
}
// Reopen storage.
if err := f.openStorage(); err != nil {
return n, fmt.Errorf("open storage: %s", err)
}
// Reset operation count.
f.opN = 0
return n, nil
} | go | func unprotectedWriteToFragment(f *fragment, bm *roaring.Bitmap) (n int64, err error) { // nolint: interfacer
completeMessage := fmt.Sprintf("fragment: snapshot complete %s/%s/%s/%d", f.index, f.field, f.view, f.shard)
start := time.Now()
defer track(start, completeMessage, f.stats, f.Logger)
// Create a temporary file to snapshot to.
snapshotPath := f.path + snapshotExt
file, err := os.Create(snapshotPath)
if err != nil {
return n, fmt.Errorf("create snapshot file: %s", err)
}
defer file.Close()
// Write storage to snapshot.
bw := bufio.NewWriter(file)
if n, err = bm.WriteTo(bw); err != nil {
return n, fmt.Errorf("snapshot write to: %s", err)
}
if err := bw.Flush(); err != nil {
return n, fmt.Errorf("flush: %s", err)
}
// Close current storage.
if err := f.closeStorage(); err != nil {
return n, fmt.Errorf("close storage: %s", err)
}
// Move snapshot to data file location.
if err := os.Rename(snapshotPath, f.path); err != nil {
return n, fmt.Errorf("rename snapshot: %s", err)
}
// Reopen storage.
if err := f.openStorage(); err != nil {
return n, fmt.Errorf("open storage: %s", err)
}
// Reset operation count.
f.opN = 0
return n, nil
} | [
"func",
"unprotectedWriteToFragment",
"(",
"f",
"*",
"fragment",
",",
"bm",
"*",
"roaring",
".",
"Bitmap",
")",
"(",
"n",
"int64",
",",
"err",
"error",
")",
"{",
"completeMessage",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"fragment: snapshot complete %s/%s/%s/%d\"",
... | // unprotectedWriteToFragment writes the fragment f with bm as the data. It is unprotected, and
// f.mu must be locked when calling it. | [
"unprotectedWriteToFragment",
"writes",
"the",
"fragment",
"f",
"with",
"bm",
"as",
"the",
"data",
".",
"It",
"is",
"unprotected",
"and",
"f",
".",
"mu",
"must",
"be",
"locked",
"when",
"calling",
"it",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/fragment.go#L1927-L1970 | train |
pilosa/pilosa | fragment.go | RecalculateCache | func (f *fragment) RecalculateCache() {
f.mu.Lock()
f.cache.Recalculate()
f.mu.Unlock()
} | go | func (f *fragment) RecalculateCache() {
f.mu.Lock()
f.cache.Recalculate()
f.mu.Unlock()
} | [
"func",
"(",
"f",
"*",
"fragment",
")",
"RecalculateCache",
"(",
")",
"{",
"f",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"f",
".",
"cache",
".",
"Recalculate",
"(",
")",
"\n",
"f",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // RecalculateCache rebuilds the cache regardless of invalidate time delay. | [
"RecalculateCache",
"rebuilds",
"the",
"cache",
"regardless",
"of",
"invalidate",
"time",
"delay",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/fragment.go#L1973-L1977 | train |
pilosa/pilosa | fragment.go | FlushCache | func (f *fragment) FlushCache() error {
f.mu.Lock()
defer f.mu.Unlock()
return f.flushCache()
} | go | func (f *fragment) FlushCache() error {
f.mu.Lock()
defer f.mu.Unlock()
return f.flushCache()
} | [
"func",
"(",
"f",
"*",
"fragment",
")",
"FlushCache",
"(",
")",
"error",
"{",
"f",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"f",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"f",
".",
"flushCache",
"(",
")",
"\n",
"}"
] | // FlushCache writes the cache data to disk. | [
"FlushCache",
"writes",
"the",
"cache",
"data",
"to",
"disk",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/fragment.go#L1980-L1984 | train |
pilosa/pilosa | fragment.go | WriteTo | func (f *fragment) WriteTo(w io.Writer) (n int64, err error) {
// Force cache flush.
if err := f.FlushCache(); err != nil {
return 0, errors.Wrap(err, "flushing cache")
}
// Write out data and cache to a tar archive.
tw := tar.NewWriter(w)
if err := f.writeStorageToArchive(tw); err != nil {
return 0, fmt.Errorf("write storage: %s", err)
}
if err := f.writeCacheToArchive(tw); err != nil {
return 0, fmt.Errorf("write cache: %s", err)
}
return 0, nil
} | go | func (f *fragment) WriteTo(w io.Writer) (n int64, err error) {
// Force cache flush.
if err := f.FlushCache(); err != nil {
return 0, errors.Wrap(err, "flushing cache")
}
// Write out data and cache to a tar archive.
tw := tar.NewWriter(w)
if err := f.writeStorageToArchive(tw); err != nil {
return 0, fmt.Errorf("write storage: %s", err)
}
if err := f.writeCacheToArchive(tw); err != nil {
return 0, fmt.Errorf("write cache: %s", err)
}
return 0, nil
} | [
"func",
"(",
"f",
"*",
"fragment",
")",
"WriteTo",
"(",
"w",
"io",
".",
"Writer",
")",
"(",
"n",
"int64",
",",
"err",
"error",
")",
"{",
"if",
"err",
":=",
"f",
".",
"FlushCache",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"e... | // WriteTo writes the fragment's data to w. | [
"WriteTo",
"writes",
"the",
"fragment",
"s",
"data",
"to",
"w",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/fragment.go#L2013-L2028 | train |
pilosa/pilosa | fragment.go | ReadFrom | func (f *fragment) ReadFrom(r io.Reader) (n int64, err error) {
f.mu.Lock()
defer f.mu.Unlock()
tr := tar.NewReader(r)
for {
// Read next tar header.
hdr, err := tr.Next()
if err == io.EOF {
break
} else if err != nil {
return 0, errors.Wrap(err, "opening")
}
// Process file based on file name.
switch hdr.Name {
case "data":
if err := f.readStorageFromArchive(tr); err != nil {
return 0, errors.Wrap(err, "reading storage")
}
case "cache":
if err := f.readCacheFromArchive(tr); err != nil {
return 0, errors.Wrap(err, "reading cache")
}
default:
return 0, fmt.Errorf("invalid fragment archive file: %s", hdr.Name)
}
}
return 0, nil
} | go | func (f *fragment) ReadFrom(r io.Reader) (n int64, err error) {
f.mu.Lock()
defer f.mu.Unlock()
tr := tar.NewReader(r)
for {
// Read next tar header.
hdr, err := tr.Next()
if err == io.EOF {
break
} else if err != nil {
return 0, errors.Wrap(err, "opening")
}
// Process file based on file name.
switch hdr.Name {
case "data":
if err := f.readStorageFromArchive(tr); err != nil {
return 0, errors.Wrap(err, "reading storage")
}
case "cache":
if err := f.readCacheFromArchive(tr); err != nil {
return 0, errors.Wrap(err, "reading cache")
}
default:
return 0, fmt.Errorf("invalid fragment archive file: %s", hdr.Name)
}
}
return 0, nil
} | [
"func",
"(",
"f",
"*",
"fragment",
")",
"ReadFrom",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"n",
"int64",
",",
"err",
"error",
")",
"{",
"f",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"f",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"... | // ReadFrom reads a data file from r and loads it into the fragment. | [
"ReadFrom",
"reads",
"a",
"data",
"file",
"from",
"r",
"and",
"loads",
"it",
"into",
"the",
"fragment",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/fragment.go#L2104-L2134 | train |
pilosa/pilosa | fragment.go | syncFragment | func (s *fragmentSyncer) syncFragment() error {
span, ctx := tracing.StartSpanFromContext(context.Background(), "FragmentSyncer.syncFragment")
defer span.Finish()
// Determine replica set.
nodes := s.Cluster.shardNodes(s.Fragment.index, s.Fragment.shard)
if len(nodes) == 1 {
return nil
}
// Create a set of blocks.
blockSets := make([][]FragmentBlock, 0, len(nodes))
for _, node := range nodes {
// Read local blocks.
if node.ID == s.Node.ID {
b := s.Fragment.Blocks()
blockSets = append(blockSets, b)
continue
}
// Retrieve remote blocks.
blocks, err := s.Cluster.InternalClient.FragmentBlocks(ctx, &node.URI, s.Fragment.index, s.Fragment.field, s.Fragment.view, s.Fragment.shard)
if err != nil && err != ErrFragmentNotFound {
return errors.Wrap(err, "getting blocks")
}
blockSets = append(blockSets, blocks)
// Verify sync is not prematurely closing.
if s.isClosing() {
return nil
}
}
// Iterate over all blocks and find differences.
checksums := make([][]byte, len(nodes))
for {
// Find min block id.
blockID := -1
for _, blocks := range blockSets {
if len(blocks) == 0 {
continue
} else if blockID == -1 || blocks[0].ID < blockID {
blockID = blocks[0].ID
}
}
// Exit loop if no blocks are left.
if blockID == -1 {
break
}
// Read the checksum for the current block.
for i, blocks := range blockSets {
// Clear checksum if the next block for the node doesn't match current ID.
if len(blocks) == 0 || blocks[0].ID != blockID {
checksums[i] = nil
continue
}
// Otherwise set checksum and move forward.
checksums[i] = blocks[0].Checksum
blockSets[i] = blockSets[i][1:]
}
// Ignore if all the blocks on each node match.
if byteSlicesEqual(checksums) {
continue
}
// Synchronize block.
if err := s.syncBlock(blockID); err != nil {
return fmt.Errorf("sync block: id=%d, err=%s", blockID, err)
}
s.Fragment.stats.Count("BlockRepair", 1, 1.0)
}
return nil
} | go | func (s *fragmentSyncer) syncFragment() error {
span, ctx := tracing.StartSpanFromContext(context.Background(), "FragmentSyncer.syncFragment")
defer span.Finish()
// Determine replica set.
nodes := s.Cluster.shardNodes(s.Fragment.index, s.Fragment.shard)
if len(nodes) == 1 {
return nil
}
// Create a set of blocks.
blockSets := make([][]FragmentBlock, 0, len(nodes))
for _, node := range nodes {
// Read local blocks.
if node.ID == s.Node.ID {
b := s.Fragment.Blocks()
blockSets = append(blockSets, b)
continue
}
// Retrieve remote blocks.
blocks, err := s.Cluster.InternalClient.FragmentBlocks(ctx, &node.URI, s.Fragment.index, s.Fragment.field, s.Fragment.view, s.Fragment.shard)
if err != nil && err != ErrFragmentNotFound {
return errors.Wrap(err, "getting blocks")
}
blockSets = append(blockSets, blocks)
// Verify sync is not prematurely closing.
if s.isClosing() {
return nil
}
}
// Iterate over all blocks and find differences.
checksums := make([][]byte, len(nodes))
for {
// Find min block id.
blockID := -1
for _, blocks := range blockSets {
if len(blocks) == 0 {
continue
} else if blockID == -1 || blocks[0].ID < blockID {
blockID = blocks[0].ID
}
}
// Exit loop if no blocks are left.
if blockID == -1 {
break
}
// Read the checksum for the current block.
for i, blocks := range blockSets {
// Clear checksum if the next block for the node doesn't match current ID.
if len(blocks) == 0 || blocks[0].ID != blockID {
checksums[i] = nil
continue
}
// Otherwise set checksum and move forward.
checksums[i] = blocks[0].Checksum
blockSets[i] = blockSets[i][1:]
}
// Ignore if all the blocks on each node match.
if byteSlicesEqual(checksums) {
continue
}
// Synchronize block.
if err := s.syncBlock(blockID); err != nil {
return fmt.Errorf("sync block: id=%d, err=%s", blockID, err)
}
s.Fragment.stats.Count("BlockRepair", 1, 1.0)
}
return nil
} | [
"func",
"(",
"s",
"*",
"fragmentSyncer",
")",
"syncFragment",
"(",
")",
"error",
"{",
"span",
",",
"ctx",
":=",
"tracing",
".",
"StartSpanFromContext",
"(",
"context",
".",
"Background",
"(",
")",
",",
"\"FragmentSyncer.syncFragment\"",
")",
"\n",
"defer",
"... | // syncFragment compares checksums for the local and remote fragments and
// then merges any blocks which have differences. | [
"syncFragment",
"compares",
"checksums",
"for",
"the",
"local",
"and",
"remote",
"fragments",
"and",
"then",
"merges",
"any",
"blocks",
"which",
"have",
"differences",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/fragment.go#L2381-L2457 | train |
pilosa/pilosa | fragment.go | syncBlock | func (s *fragmentSyncer) syncBlock(id int) error {
span, ctx := tracing.StartSpanFromContext(context.Background(), "FragmentSyncer.syncBlock")
defer span.Finish()
f := s.Fragment
// Read pairs from each remote block.
var uris []*URI
var pairSets []pairSet
for _, node := range s.Cluster.shardNodes(f.index, f.shard) {
if s.Node.ID == node.ID {
continue
}
// Verify sync is not prematurely closing.
if s.isClosing() {
return nil
}
uri := &node.URI
uris = append(uris, uri)
// Only sync the standard block.
rowIDs, columnIDs, err := s.Cluster.InternalClient.BlockData(ctx, &node.URI, f.index, f.field, f.view, f.shard, id)
if err != nil {
return errors.Wrap(err, "getting block")
}
pairSets = append(pairSets, pairSet{
columnIDs: columnIDs,
rowIDs: rowIDs,
})
}
// Verify sync is not prematurely closing.
if s.isClosing() {
return nil
}
// Merge blocks together.
sets, clears, err := f.mergeBlock(id, pairSets)
if err != nil {
return errors.Wrap(err, "merging")
}
// Write updates to remote blocks.
for i := 0; i < len(uris); i++ {
set, clear := sets[i], clears[i]
// Handle Sets.
if len(set.columnIDs) > 0 {
setData, err := bitsToRoaringData(set)
if err != nil {
return errors.Wrap(err, "converting bits to roaring data (set)")
}
setReq := &ImportRoaringRequest{
Clear: false,
Views: map[string][]byte{cleanViewName(f.view): setData},
}
if err := s.Cluster.InternalClient.ImportRoaring(ctx, uris[i], f.index, f.field, f.shard, true, setReq); err != nil {
return errors.Wrap(err, "sending roaring data (set)")
}
}
// Handle Clears.
if len(clear.columnIDs) > 0 {
clearData, err := bitsToRoaringData(clear)
if err != nil {
return errors.Wrap(err, "converting bits to roaring data (clear)")
}
clearReq := &ImportRoaringRequest{
Clear: true,
Views: map[string][]byte{"": clearData},
}
if err := s.Cluster.InternalClient.ImportRoaring(ctx, uris[i], f.index, f.field, f.shard, true, clearReq); err != nil {
return errors.Wrap(err, "sending roaring data (clear)")
}
}
}
return nil
} | go | func (s *fragmentSyncer) syncBlock(id int) error {
span, ctx := tracing.StartSpanFromContext(context.Background(), "FragmentSyncer.syncBlock")
defer span.Finish()
f := s.Fragment
// Read pairs from each remote block.
var uris []*URI
var pairSets []pairSet
for _, node := range s.Cluster.shardNodes(f.index, f.shard) {
if s.Node.ID == node.ID {
continue
}
// Verify sync is not prematurely closing.
if s.isClosing() {
return nil
}
uri := &node.URI
uris = append(uris, uri)
// Only sync the standard block.
rowIDs, columnIDs, err := s.Cluster.InternalClient.BlockData(ctx, &node.URI, f.index, f.field, f.view, f.shard, id)
if err != nil {
return errors.Wrap(err, "getting block")
}
pairSets = append(pairSets, pairSet{
columnIDs: columnIDs,
rowIDs: rowIDs,
})
}
// Verify sync is not prematurely closing.
if s.isClosing() {
return nil
}
// Merge blocks together.
sets, clears, err := f.mergeBlock(id, pairSets)
if err != nil {
return errors.Wrap(err, "merging")
}
// Write updates to remote blocks.
for i := 0; i < len(uris); i++ {
set, clear := sets[i], clears[i]
// Handle Sets.
if len(set.columnIDs) > 0 {
setData, err := bitsToRoaringData(set)
if err != nil {
return errors.Wrap(err, "converting bits to roaring data (set)")
}
setReq := &ImportRoaringRequest{
Clear: false,
Views: map[string][]byte{cleanViewName(f.view): setData},
}
if err := s.Cluster.InternalClient.ImportRoaring(ctx, uris[i], f.index, f.field, f.shard, true, setReq); err != nil {
return errors.Wrap(err, "sending roaring data (set)")
}
}
// Handle Clears.
if len(clear.columnIDs) > 0 {
clearData, err := bitsToRoaringData(clear)
if err != nil {
return errors.Wrap(err, "converting bits to roaring data (clear)")
}
clearReq := &ImportRoaringRequest{
Clear: true,
Views: map[string][]byte{"": clearData},
}
if err := s.Cluster.InternalClient.ImportRoaring(ctx, uris[i], f.index, f.field, f.shard, true, clearReq); err != nil {
return errors.Wrap(err, "sending roaring data (clear)")
}
}
}
return nil
} | [
"func",
"(",
"s",
"*",
"fragmentSyncer",
")",
"syncBlock",
"(",
"id",
"int",
")",
"error",
"{",
"span",
",",
"ctx",
":=",
"tracing",
".",
"StartSpanFromContext",
"(",
"context",
".",
"Background",
"(",
")",
",",
"\"FragmentSyncer.syncBlock\"",
")",
"\n",
"... | // syncBlock sends and receives all rows for a given block.
// Returns an error if any remote hosts are unreachable. | [
"syncBlock",
"sends",
"and",
"receives",
"all",
"rows",
"for",
"a",
"given",
"block",
".",
"Returns",
"an",
"error",
"if",
"any",
"remote",
"hosts",
"are",
"unreachable",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/fragment.go#L2461-L2546 | train |
pilosa/pilosa | fragment.go | bitsToRoaringData | func bitsToRoaringData(ps pairSet) ([]byte, error) {
bmp := roaring.NewBitmap()
for j := 0; j < len(ps.columnIDs); j++ {
bmp.DirectAdd(ps.rowIDs[j]*ShardWidth + (ps.columnIDs[j] % ShardWidth))
}
var buf bytes.Buffer
_, err := bmp.WriteTo(&buf)
if err != nil {
return nil, errors.Wrap(err, "writing to buffer")
}
return buf.Bytes(), nil
} | go | func bitsToRoaringData(ps pairSet) ([]byte, error) {
bmp := roaring.NewBitmap()
for j := 0; j < len(ps.columnIDs); j++ {
bmp.DirectAdd(ps.rowIDs[j]*ShardWidth + (ps.columnIDs[j] % ShardWidth))
}
var buf bytes.Buffer
_, err := bmp.WriteTo(&buf)
if err != nil {
return nil, errors.Wrap(err, "writing to buffer")
}
return buf.Bytes(), nil
} | [
"func",
"bitsToRoaringData",
"(",
"ps",
"pairSet",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"bmp",
":=",
"roaring",
".",
"NewBitmap",
"(",
")",
"\n",
"for",
"j",
":=",
"0",
";",
"j",
"<",
"len",
"(",
"ps",
".",
"columnIDs",
")",
";",
... | // bitsToRoaringData converts a pairSet into a roaring.Bitmap
// which represents the data within a single shard. | [
"bitsToRoaringData",
"converts",
"a",
"pairSet",
"into",
"a",
"roaring",
".",
"Bitmap",
"which",
"represents",
"the",
"data",
"within",
"a",
"single",
"shard",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/fragment.go#L2566-L2579 | train |
pilosa/pilosa | fragment.go | byteSlicesEqual | func byteSlicesEqual(a [][]byte) bool {
if len(a) == 0 {
return true
}
for _, v := range a[1:] {
if !bytes.Equal(a[0], v) {
return false
}
}
return true
} | go | func byteSlicesEqual(a [][]byte) bool {
if len(a) == 0 {
return true
}
for _, v := range a[1:] {
if !bytes.Equal(a[0], v) {
return false
}
}
return true
} | [
"func",
"byteSlicesEqual",
"(",
"a",
"[",
"]",
"[",
"]",
"byte",
")",
"bool",
"{",
"if",
"len",
"(",
"a",
")",
"==",
"0",
"{",
"return",
"true",
"\n",
"}",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"a",
"[",
"1",
":",
"]",
"{",
"if",
"!",
... | // byteSlicesEqual returns true if all slices are equal. | [
"byteSlicesEqual",
"returns",
"true",
"if",
"all",
"slices",
"are",
"equal",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/fragment.go#L2596-L2607 | train |
pilosa/pilosa | http/client.go | NewInternalClient | func NewInternalClient(host string, remoteClient *http.Client) (*InternalClient, error) {
if host == "" {
return nil, pilosa.ErrHostRequired
}
uri, err := pilosa.NewURIFromAddress(host)
if err != nil {
return nil, errors.Wrap(err, "getting URI")
}
client := NewInternalClientFromURI(uri, remoteClient)
return client, nil
} | go | func NewInternalClient(host string, remoteClient *http.Client) (*InternalClient, error) {
if host == "" {
return nil, pilosa.ErrHostRequired
}
uri, err := pilosa.NewURIFromAddress(host)
if err != nil {
return nil, errors.Wrap(err, "getting URI")
}
client := NewInternalClientFromURI(uri, remoteClient)
return client, nil
} | [
"func",
"NewInternalClient",
"(",
"host",
"string",
",",
"remoteClient",
"*",
"http",
".",
"Client",
")",
"(",
"*",
"InternalClient",
",",
"error",
")",
"{",
"if",
"host",
"==",
"\"\"",
"{",
"return",
"nil",
",",
"pilosa",
".",
"ErrHostRequired",
"\n",
"... | // NewInternalClient returns a new instance of InternalClient to connect to host. | [
"NewInternalClient",
"returns",
"a",
"new",
"instance",
"of",
"InternalClient",
"to",
"connect",
"to",
"host",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/client.go#L46-L58 | train |
pilosa/pilosa | http/client.go | MaxShardByIndex | func (c *InternalClient) MaxShardByIndex(ctx context.Context) (map[string]uint64, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "InternalClient.MaxShardByIndex")
defer span.Finish()
return c.maxShardByIndex(ctx)
} | go | func (c *InternalClient) MaxShardByIndex(ctx context.Context) (map[string]uint64, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "InternalClient.MaxShardByIndex")
defer span.Finish()
return c.maxShardByIndex(ctx)
} | [
"func",
"(",
"c",
"*",
"InternalClient",
")",
"MaxShardByIndex",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"map",
"[",
"string",
"]",
"uint64",
",",
"error",
")",
"{",
"span",
",",
"ctx",
":=",
"tracing",
".",
"StartSpanFromContext",
"(",
"ctx",
... | // MaxShardByIndex returns the number of shards on a server by index. | [
"MaxShardByIndex",
"returns",
"the",
"number",
"of",
"shards",
"on",
"a",
"server",
"by",
"index",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/client.go#L69-L73 | train |
pilosa/pilosa | http/client.go | maxShardByIndex | func (c *InternalClient) maxShardByIndex(ctx context.Context) (map[string]uint64, error) {
// Execute request against the host.
u := uriPathToURL(c.defaultURI, "/internal/shards/max")
// Build request.
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return nil, errors.Wrap(err, "creating request")
}
req.Header.Set("User-Agent", "pilosa/"+pilosa.Version)
req.Header.Set("Accept", "application/json")
// Execute request.
resp, err := c.executeRequest(req.WithContext(ctx))
if err != nil {
return nil, err
}
defer resp.Body.Close()
var rsp getShardsMaxResponse
if err := json.NewDecoder(resp.Body).Decode(&rsp); err != nil {
return nil, fmt.Errorf("json decode: %s", err)
}
return rsp.Standard, nil
} | go | func (c *InternalClient) maxShardByIndex(ctx context.Context) (map[string]uint64, error) {
// Execute request against the host.
u := uriPathToURL(c.defaultURI, "/internal/shards/max")
// Build request.
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return nil, errors.Wrap(err, "creating request")
}
req.Header.Set("User-Agent", "pilosa/"+pilosa.Version)
req.Header.Set("Accept", "application/json")
// Execute request.
resp, err := c.executeRequest(req.WithContext(ctx))
if err != nil {
return nil, err
}
defer resp.Body.Close()
var rsp getShardsMaxResponse
if err := json.NewDecoder(resp.Body).Decode(&rsp); err != nil {
return nil, fmt.Errorf("json decode: %s", err)
}
return rsp.Standard, nil
} | [
"func",
"(",
"c",
"*",
"InternalClient",
")",
"maxShardByIndex",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"map",
"[",
"string",
"]",
"uint64",
",",
"error",
")",
"{",
"u",
":=",
"uriPathToURL",
"(",
"c",
".",
"defaultURI",
",",
"\"/internal/shard... | // maxShardByIndex returns the number of shards on a server by index. | [
"maxShardByIndex",
"returns",
"the",
"number",
"of",
"shards",
"on",
"a",
"server",
"by",
"index",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/client.go#L76-L102 | train |
pilosa/pilosa | http/client.go | Schema | func (c *InternalClient) Schema(ctx context.Context) ([]*pilosa.IndexInfo, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "InternalClient.Schema")
defer span.Finish()
// Execute request against the host.
u := c.defaultURI.Path("/schema")
// Build request.
req, err := http.NewRequest("GET", u, nil)
if err != nil {
return nil, errors.Wrap(err, "creating request")
}
req.Header.Set("User-Agent", "pilosa/"+pilosa.Version)
req.Header.Set("Accept", "application/json")
// Execute request.
resp, err := c.executeRequest(req.WithContext(ctx))
if err != nil {
return nil, err
}
defer resp.Body.Close()
var rsp getSchemaResponse
if err := json.NewDecoder(resp.Body).Decode(&rsp); err != nil {
return nil, fmt.Errorf("json decode: %s", err)
}
return rsp.Indexes, nil
} | go | func (c *InternalClient) Schema(ctx context.Context) ([]*pilosa.IndexInfo, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "InternalClient.Schema")
defer span.Finish()
// Execute request against the host.
u := c.defaultURI.Path("/schema")
// Build request.
req, err := http.NewRequest("GET", u, nil)
if err != nil {
return nil, errors.Wrap(err, "creating request")
}
req.Header.Set("User-Agent", "pilosa/"+pilosa.Version)
req.Header.Set("Accept", "application/json")
// Execute request.
resp, err := c.executeRequest(req.WithContext(ctx))
if err != nil {
return nil, err
}
defer resp.Body.Close()
var rsp getSchemaResponse
if err := json.NewDecoder(resp.Body).Decode(&rsp); err != nil {
return nil, fmt.Errorf("json decode: %s", err)
}
return rsp.Indexes, nil
} | [
"func",
"(",
"c",
"*",
"InternalClient",
")",
"Schema",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"[",
"]",
"*",
"pilosa",
".",
"IndexInfo",
",",
"error",
")",
"{",
"span",
",",
"ctx",
":=",
"tracing",
".",
"StartSpanFromContext",
"(",
"ctx",
... | // Schema returns all index and field schema information. | [
"Schema",
"returns",
"all",
"index",
"and",
"field",
"schema",
"information",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/client.go#L105-L133 | train |
pilosa/pilosa | http/client.go | CreateIndex | func (c *InternalClient) CreateIndex(ctx context.Context, index string, opt pilosa.IndexOptions) error {
span, ctx := tracing.StartSpanFromContext(ctx, "InternalClient.CreateIndex")
defer span.Finish()
// Encode query request.
buf, err := json.Marshal(&postIndexRequest{
Options: opt,
})
if err != nil {
return errors.Wrap(err, "encoding request")
}
// Create URL & HTTP request.
u := uriPathToURL(c.defaultURI, fmt.Sprintf("/index/%s", index))
req, err := http.NewRequest("POST", u.String(), bytes.NewReader(buf))
if err != nil {
return errors.Wrap(err, "creating request")
}
req.Header.Set("Content-Length", strconv.Itoa(len(buf)))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", "pilosa/"+pilosa.Version)
// Execute request against the host.
resp, err := c.executeRequest(req.WithContext(ctx))
if err != nil {
if resp != nil && resp.StatusCode == http.StatusConflict {
return pilosa.ErrIndexExists
}
return err
}
return errors.Wrap(resp.Body.Close(), "closing response body")
} | go | func (c *InternalClient) CreateIndex(ctx context.Context, index string, opt pilosa.IndexOptions) error {
span, ctx := tracing.StartSpanFromContext(ctx, "InternalClient.CreateIndex")
defer span.Finish()
// Encode query request.
buf, err := json.Marshal(&postIndexRequest{
Options: opt,
})
if err != nil {
return errors.Wrap(err, "encoding request")
}
// Create URL & HTTP request.
u := uriPathToURL(c.defaultURI, fmt.Sprintf("/index/%s", index))
req, err := http.NewRequest("POST", u.String(), bytes.NewReader(buf))
if err != nil {
return errors.Wrap(err, "creating request")
}
req.Header.Set("Content-Length", strconv.Itoa(len(buf)))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", "pilosa/"+pilosa.Version)
// Execute request against the host.
resp, err := c.executeRequest(req.WithContext(ctx))
if err != nil {
if resp != nil && resp.StatusCode == http.StatusConflict {
return pilosa.ErrIndexExists
}
return err
}
return errors.Wrap(resp.Body.Close(), "closing response body")
} | [
"func",
"(",
"c",
"*",
"InternalClient",
")",
"CreateIndex",
"(",
"ctx",
"context",
".",
"Context",
",",
"index",
"string",
",",
"opt",
"pilosa",
".",
"IndexOptions",
")",
"error",
"{",
"span",
",",
"ctx",
":=",
"tracing",
".",
"StartSpanFromContext",
"(",... | // CreateIndex creates a new index on the server. | [
"CreateIndex",
"creates",
"a",
"new",
"index",
"on",
"the",
"server",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/client.go#L163-L195 | train |
pilosa/pilosa | http/client.go | FragmentNodes | func (c *InternalClient) FragmentNodes(ctx context.Context, index string, shard uint64) ([]*pilosa.Node, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "InternalClient.FragmentNodes")
defer span.Finish()
// Execute request against the host.
u := uriPathToURL(c.defaultURI, "/internal/fragment/nodes")
u.RawQuery = (url.Values{"index": {index}, "shard": {strconv.FormatUint(shard, 10)}}).Encode()
// Build request.
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return nil, errors.Wrap(err, "creating request")
}
req.Header.Set("User-Agent", "pilosa/"+pilosa.Version)
req.Header.Set("Accept", "application/json")
// Execute request.
resp, err := c.executeRequest(req.WithContext(ctx))
if err != nil {
return nil, err
}
defer resp.Body.Close()
var a []*pilosa.Node
if err := json.NewDecoder(resp.Body).Decode(&a); err != nil {
return nil, fmt.Errorf("json decode: %s", err)
}
return a, nil
} | go | func (c *InternalClient) FragmentNodes(ctx context.Context, index string, shard uint64) ([]*pilosa.Node, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "InternalClient.FragmentNodes")
defer span.Finish()
// Execute request against the host.
u := uriPathToURL(c.defaultURI, "/internal/fragment/nodes")
u.RawQuery = (url.Values{"index": {index}, "shard": {strconv.FormatUint(shard, 10)}}).Encode()
// Build request.
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return nil, errors.Wrap(err, "creating request")
}
req.Header.Set("User-Agent", "pilosa/"+pilosa.Version)
req.Header.Set("Accept", "application/json")
// Execute request.
resp, err := c.executeRequest(req.WithContext(ctx))
if err != nil {
return nil, err
}
defer resp.Body.Close()
var a []*pilosa.Node
if err := json.NewDecoder(resp.Body).Decode(&a); err != nil {
return nil, fmt.Errorf("json decode: %s", err)
}
return a, nil
} | [
"func",
"(",
"c",
"*",
"InternalClient",
")",
"FragmentNodes",
"(",
"ctx",
"context",
".",
"Context",
",",
"index",
"string",
",",
"shard",
"uint64",
")",
"(",
"[",
"]",
"*",
"pilosa",
".",
"Node",
",",
"error",
")",
"{",
"span",
",",
"ctx",
":=",
... | // FragmentNodes returns a list of nodes that own a shard. | [
"FragmentNodes",
"returns",
"a",
"list",
"of",
"nodes",
"that",
"own",
"a",
"shard",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/client.go#L198-L227 | train |
pilosa/pilosa | http/client.go | Nodes | func (c *InternalClient) Nodes(ctx context.Context) ([]*pilosa.Node, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "InternalClient.Nodes")
defer span.Finish()
// Execute request against the host.
u := uriPathToURL(c.defaultURI, "/internal/nodes")
// Build request.
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return nil, errors.Wrap(err, "creating request")
}
req.Header.Set("User-Agent", "pilosa/"+pilosa.Version)
req.Header.Set("Accept", "application/json")
// Execute request.
resp, err := c.executeRequest(req.WithContext(ctx))
if err != nil {
return nil, err
}
defer resp.Body.Close()
var a []*pilosa.Node
if err := json.NewDecoder(resp.Body).Decode(&a); err != nil {
return nil, fmt.Errorf("json decode: %s", err)
}
return a, nil
} | go | func (c *InternalClient) Nodes(ctx context.Context) ([]*pilosa.Node, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "InternalClient.Nodes")
defer span.Finish()
// Execute request against the host.
u := uriPathToURL(c.defaultURI, "/internal/nodes")
// Build request.
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return nil, errors.Wrap(err, "creating request")
}
req.Header.Set("User-Agent", "pilosa/"+pilosa.Version)
req.Header.Set("Accept", "application/json")
// Execute request.
resp, err := c.executeRequest(req.WithContext(ctx))
if err != nil {
return nil, err
}
defer resp.Body.Close()
var a []*pilosa.Node
if err := json.NewDecoder(resp.Body).Decode(&a); err != nil {
return nil, fmt.Errorf("json decode: %s", err)
}
return a, nil
} | [
"func",
"(",
"c",
"*",
"InternalClient",
")",
"Nodes",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"[",
"]",
"*",
"pilosa",
".",
"Node",
",",
"error",
")",
"{",
"span",
",",
"ctx",
":=",
"tracing",
".",
"StartSpanFromContext",
"(",
"ctx",
",",
... | // Nodes returns a list of all nodes. | [
"Nodes",
"returns",
"a",
"list",
"of",
"all",
"nodes",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/client.go#L230-L258 | train |
pilosa/pilosa | http/client.go | Query | func (c *InternalClient) Query(ctx context.Context, index string, queryRequest *pilosa.QueryRequest) (*pilosa.QueryResponse, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "InternalClient.Query")
defer span.Finish()
return c.QueryNode(ctx, c.defaultURI, index, queryRequest)
} | go | func (c *InternalClient) Query(ctx context.Context, index string, queryRequest *pilosa.QueryRequest) (*pilosa.QueryResponse, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "InternalClient.Query")
defer span.Finish()
return c.QueryNode(ctx, c.defaultURI, index, queryRequest)
} | [
"func",
"(",
"c",
"*",
"InternalClient",
")",
"Query",
"(",
"ctx",
"context",
".",
"Context",
",",
"index",
"string",
",",
"queryRequest",
"*",
"pilosa",
".",
"QueryRequest",
")",
"(",
"*",
"pilosa",
".",
"QueryResponse",
",",
"error",
")",
"{",
"span",
... | // Query executes query against the index. | [
"Query",
"executes",
"query",
"against",
"the",
"index",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/client.go#L261-L265 | train |
pilosa/pilosa | http/client.go | QueryNode | func (c *InternalClient) QueryNode(ctx context.Context, uri *pilosa.URI, index string, queryRequest *pilosa.QueryRequest) (*pilosa.QueryResponse, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "QueryNode")
defer span.Finish()
if index == "" {
return nil, pilosa.ErrIndexRequired
} else if queryRequest.Query == "" {
return nil, pilosa.ErrQueryRequired
}
buf, err := c.serializer.Marshal(queryRequest)
if err != nil {
return nil, errors.Wrap(err, "marshaling queryRequest")
}
// Create HTTP request.
u := uri.Path(fmt.Sprintf("/index/%s/query", index))
req, err := http.NewRequest("POST", u, bytes.NewReader(buf))
if err != nil {
return nil, errors.Wrap(err, "creating request")
}
req.Header.Set("Content-Length", strconv.Itoa(len(buf)))
req.Header.Set("Content-Type", "application/x-protobuf")
req.Header.Set("Accept", "application/x-protobuf")
req.Header.Set("User-Agent", "pilosa/"+pilosa.Version)
// Execute request against the host.
resp, err := c.executeRequest(req.WithContext(ctx))
if err != nil {
return nil, err
}
defer resp.Body.Close()
// Read body and unmarshal response.
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, errors.Wrap(err, "reading")
}
qresp := &pilosa.QueryResponse{}
if err := c.serializer.Unmarshal(body, qresp); err != nil {
return nil, fmt.Errorf("unmarshal response: %s", err)
} else if qresp.Err != nil {
return nil, qresp.Err
}
return qresp, nil
} | go | func (c *InternalClient) QueryNode(ctx context.Context, uri *pilosa.URI, index string, queryRequest *pilosa.QueryRequest) (*pilosa.QueryResponse, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "QueryNode")
defer span.Finish()
if index == "" {
return nil, pilosa.ErrIndexRequired
} else if queryRequest.Query == "" {
return nil, pilosa.ErrQueryRequired
}
buf, err := c.serializer.Marshal(queryRequest)
if err != nil {
return nil, errors.Wrap(err, "marshaling queryRequest")
}
// Create HTTP request.
u := uri.Path(fmt.Sprintf("/index/%s/query", index))
req, err := http.NewRequest("POST", u, bytes.NewReader(buf))
if err != nil {
return nil, errors.Wrap(err, "creating request")
}
req.Header.Set("Content-Length", strconv.Itoa(len(buf)))
req.Header.Set("Content-Type", "application/x-protobuf")
req.Header.Set("Accept", "application/x-protobuf")
req.Header.Set("User-Agent", "pilosa/"+pilosa.Version)
// Execute request against the host.
resp, err := c.executeRequest(req.WithContext(ctx))
if err != nil {
return nil, err
}
defer resp.Body.Close()
// Read body and unmarshal response.
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, errors.Wrap(err, "reading")
}
qresp := &pilosa.QueryResponse{}
if err := c.serializer.Unmarshal(body, qresp); err != nil {
return nil, fmt.Errorf("unmarshal response: %s", err)
} else if qresp.Err != nil {
return nil, qresp.Err
}
return qresp, nil
} | [
"func",
"(",
"c",
"*",
"InternalClient",
")",
"QueryNode",
"(",
"ctx",
"context",
".",
"Context",
",",
"uri",
"*",
"pilosa",
".",
"URI",
",",
"index",
"string",
",",
"queryRequest",
"*",
"pilosa",
".",
"QueryRequest",
")",
"(",
"*",
"pilosa",
".",
"Que... | // QueryNode executes query against the index, sending the request to the node specified. | [
"QueryNode",
"executes",
"query",
"against",
"the",
"index",
"sending",
"the",
"request",
"to",
"the",
"node",
"specified",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/client.go#L268-L316 | train |
pilosa/pilosa | http/client.go | Import | func (c *InternalClient) Import(ctx context.Context, index, field string, shard uint64, bits []pilosa.Bit, opts ...pilosa.ImportOption) error {
span, ctx := tracing.StartSpanFromContext(ctx, "InternalClient.Import")
defer span.Finish()
if index == "" {
return pilosa.ErrIndexRequired
} else if field == "" {
return pilosa.ErrFieldRequired
}
// Set up import options.
options := &pilosa.ImportOptions{}
for _, opt := range opts {
err := opt(options)
if err != nil {
return errors.Wrap(err, "applying option")
}
}
buf, err := c.marshalImportPayload(index, field, shard, bits)
if err != nil {
return fmt.Errorf("Error Creating Payload: %s", err)
}
// Retrieve a list of nodes that own the shard.
nodes, err := c.FragmentNodes(ctx, index, shard)
if err != nil {
return fmt.Errorf("shard nodes: %s", err)
}
// Import to each node.
for _, node := range nodes {
if err := c.importNode(ctx, node, index, field, buf, options); err != nil {
return fmt.Errorf("import node: host=%s, err=%s", node.URI, err)
}
}
return nil
} | go | func (c *InternalClient) Import(ctx context.Context, index, field string, shard uint64, bits []pilosa.Bit, opts ...pilosa.ImportOption) error {
span, ctx := tracing.StartSpanFromContext(ctx, "InternalClient.Import")
defer span.Finish()
if index == "" {
return pilosa.ErrIndexRequired
} else if field == "" {
return pilosa.ErrFieldRequired
}
// Set up import options.
options := &pilosa.ImportOptions{}
for _, opt := range opts {
err := opt(options)
if err != nil {
return errors.Wrap(err, "applying option")
}
}
buf, err := c.marshalImportPayload(index, field, shard, bits)
if err != nil {
return fmt.Errorf("Error Creating Payload: %s", err)
}
// Retrieve a list of nodes that own the shard.
nodes, err := c.FragmentNodes(ctx, index, shard)
if err != nil {
return fmt.Errorf("shard nodes: %s", err)
}
// Import to each node.
for _, node := range nodes {
if err := c.importNode(ctx, node, index, field, buf, options); err != nil {
return fmt.Errorf("import node: host=%s, err=%s", node.URI, err)
}
}
return nil
} | [
"func",
"(",
"c",
"*",
"InternalClient",
")",
"Import",
"(",
"ctx",
"context",
".",
"Context",
",",
"index",
",",
"field",
"string",
",",
"shard",
"uint64",
",",
"bits",
"[",
"]",
"pilosa",
".",
"Bit",
",",
"opts",
"...",
"pilosa",
".",
"ImportOption",... | // Import bulk imports bits for a single shard to a host. | [
"Import",
"bulk",
"imports",
"bits",
"for",
"a",
"single",
"shard",
"to",
"a",
"host",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/client.go#L319-L357 | train |
pilosa/pilosa | http/client.go | ImportK | func (c *InternalClient) ImportK(ctx context.Context, index, field string, bits []pilosa.Bit, opts ...pilosa.ImportOption) error {
span, ctx := tracing.StartSpanFromContext(ctx, "InternalClient.ImportK")
defer span.Finish()
if index == "" {
return pilosa.ErrIndexRequired
} else if field == "" {
return pilosa.ErrFieldRequired
}
// Set up import options.
options := &pilosa.ImportOptions{}
for _, opt := range opts {
err := opt(options)
if err != nil {
return errors.Wrap(err, "applying option")
}
}
buf, err := c.marshalImportPayload(index, field, 0, bits)
if err != nil {
return fmt.Errorf("Error Creating Payload: %s", err)
}
// Get the coordinator node; all bits are sent to the
// primary translate store (i.e. coordinator).
nodes, err := c.Nodes(ctx)
if err != nil {
return fmt.Errorf("getting nodes: %s", err)
}
coord := getCoordinatorNode(nodes)
if coord == nil {
return fmt.Errorf("could not find the coordinator node")
}
// Import to node.
if err := c.importNode(ctx, coord, index, field, buf, options); err != nil {
return fmt.Errorf("import node: host=%s, err=%s", coord.URI, err)
}
return nil
} | go | func (c *InternalClient) ImportK(ctx context.Context, index, field string, bits []pilosa.Bit, opts ...pilosa.ImportOption) error {
span, ctx := tracing.StartSpanFromContext(ctx, "InternalClient.ImportK")
defer span.Finish()
if index == "" {
return pilosa.ErrIndexRequired
} else if field == "" {
return pilosa.ErrFieldRequired
}
// Set up import options.
options := &pilosa.ImportOptions{}
for _, opt := range opts {
err := opt(options)
if err != nil {
return errors.Wrap(err, "applying option")
}
}
buf, err := c.marshalImportPayload(index, field, 0, bits)
if err != nil {
return fmt.Errorf("Error Creating Payload: %s", err)
}
// Get the coordinator node; all bits are sent to the
// primary translate store (i.e. coordinator).
nodes, err := c.Nodes(ctx)
if err != nil {
return fmt.Errorf("getting nodes: %s", err)
}
coord := getCoordinatorNode(nodes)
if coord == nil {
return fmt.Errorf("could not find the coordinator node")
}
// Import to node.
if err := c.importNode(ctx, coord, index, field, buf, options); err != nil {
return fmt.Errorf("import node: host=%s, err=%s", coord.URI, err)
}
return nil
} | [
"func",
"(",
"c",
"*",
"InternalClient",
")",
"ImportK",
"(",
"ctx",
"context",
".",
"Context",
",",
"index",
",",
"field",
"string",
",",
"bits",
"[",
"]",
"pilosa",
".",
"Bit",
",",
"opts",
"...",
"pilosa",
".",
"ImportOption",
")",
"error",
"{",
"... | // ImportK bulk imports bits specified by string keys to a host. | [
"ImportK",
"bulk",
"imports",
"bits",
"specified",
"by",
"string",
"keys",
"to",
"a",
"host",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/client.go#L369-L410 | train |
pilosa/pilosa | http/client.go | marshalImportPayload | func (c *InternalClient) marshalImportPayload(index, field string, shard uint64, bits []pilosa.Bit) ([]byte, error) {
// Separate row and column IDs to reduce allocations.
rowIDs := Bits(bits).RowIDs()
rowKeys := Bits(bits).RowKeys()
columnIDs := Bits(bits).ColumnIDs()
columnKeys := Bits(bits).ColumnKeys()
timestamps := Bits(bits).Timestamps()
// Marshal data to protobuf.
buf, err := c.serializer.Marshal(&pilosa.ImportRequest{
Index: index,
Field: field,
Shard: shard,
RowIDs: rowIDs,
RowKeys: rowKeys,
ColumnIDs: columnIDs,
ColumnKeys: columnKeys,
Timestamps: timestamps,
})
if err != nil {
return nil, fmt.Errorf("marshal import request: %s", err)
}
return buf, nil
} | go | func (c *InternalClient) marshalImportPayload(index, field string, shard uint64, bits []pilosa.Bit) ([]byte, error) {
// Separate row and column IDs to reduce allocations.
rowIDs := Bits(bits).RowIDs()
rowKeys := Bits(bits).RowKeys()
columnIDs := Bits(bits).ColumnIDs()
columnKeys := Bits(bits).ColumnKeys()
timestamps := Bits(bits).Timestamps()
// Marshal data to protobuf.
buf, err := c.serializer.Marshal(&pilosa.ImportRequest{
Index: index,
Field: field,
Shard: shard,
RowIDs: rowIDs,
RowKeys: rowKeys,
ColumnIDs: columnIDs,
ColumnKeys: columnKeys,
Timestamps: timestamps,
})
if err != nil {
return nil, fmt.Errorf("marshal import request: %s", err)
}
return buf, nil
} | [
"func",
"(",
"c",
"*",
"InternalClient",
")",
"marshalImportPayload",
"(",
"index",
",",
"field",
"string",
",",
"shard",
"uint64",
",",
"bits",
"[",
"]",
"pilosa",
".",
"Bit",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"rowIDs",
":=",
"Bits... | // marshalImportPayload marshalls the import parameters into a protobuf byte slice. | [
"marshalImportPayload",
"marshalls",
"the",
"import",
"parameters",
"into",
"a",
"protobuf",
"byte",
"slice",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/client.go#L440-L463 | train |
pilosa/pilosa | http/client.go | importNode | func (c *InternalClient) importNode(ctx context.Context, node *pilosa.Node, index, field string, buf []byte, opts *pilosa.ImportOptions) error {
span, ctx := tracing.StartSpanFromContext(ctx, "InternalClient.importNode")
defer span.Finish()
// Create URL & HTTP request.
path := fmt.Sprintf("/index/%s/field/%s/import", index, field)
u := nodePathToURL(node, path)
vals := url.Values{}
if opts.Clear {
vals.Set("clear", "true")
}
if opts.IgnoreKeyCheck {
vals.Set("ignoreKeyCheck", "true")
}
url := fmt.Sprintf("%s?%s", u.String(), vals.Encode())
req, err := http.NewRequest("POST", url, bytes.NewReader(buf))
if err != nil {
return errors.Wrap(err, "creating request")
}
req.Header.Set("Content-Length", strconv.Itoa(len(buf)))
req.Header.Set("Content-Type", "application/x-protobuf")
req.Header.Set("Accept", "application/x-protobuf")
req.Header.Set("User-Agent", "pilosa/"+pilosa.Version)
// Execute request against the host.
resp, err := c.executeRequest(req.WithContext(ctx))
if err != nil {
return err
}
defer resp.Body.Close()
// Read body and unmarshal response.
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return errors.Wrap(err, "reading")
}
var isresp pilosa.ImportResponse
if err := c.serializer.Unmarshal(body, &isresp); err != nil {
return fmt.Errorf("unmarshal import response: %s", err)
} else if s := isresp.Err; s != "" {
return errors.New(s)
}
return nil
} | go | func (c *InternalClient) importNode(ctx context.Context, node *pilosa.Node, index, field string, buf []byte, opts *pilosa.ImportOptions) error {
span, ctx := tracing.StartSpanFromContext(ctx, "InternalClient.importNode")
defer span.Finish()
// Create URL & HTTP request.
path := fmt.Sprintf("/index/%s/field/%s/import", index, field)
u := nodePathToURL(node, path)
vals := url.Values{}
if opts.Clear {
vals.Set("clear", "true")
}
if opts.IgnoreKeyCheck {
vals.Set("ignoreKeyCheck", "true")
}
url := fmt.Sprintf("%s?%s", u.String(), vals.Encode())
req, err := http.NewRequest("POST", url, bytes.NewReader(buf))
if err != nil {
return errors.Wrap(err, "creating request")
}
req.Header.Set("Content-Length", strconv.Itoa(len(buf)))
req.Header.Set("Content-Type", "application/x-protobuf")
req.Header.Set("Accept", "application/x-protobuf")
req.Header.Set("User-Agent", "pilosa/"+pilosa.Version)
// Execute request against the host.
resp, err := c.executeRequest(req.WithContext(ctx))
if err != nil {
return err
}
defer resp.Body.Close()
// Read body and unmarshal response.
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return errors.Wrap(err, "reading")
}
var isresp pilosa.ImportResponse
if err := c.serializer.Unmarshal(body, &isresp); err != nil {
return fmt.Errorf("unmarshal import response: %s", err)
} else if s := isresp.Err; s != "" {
return errors.New(s)
}
return nil
} | [
"func",
"(",
"c",
"*",
"InternalClient",
")",
"importNode",
"(",
"ctx",
"context",
".",
"Context",
",",
"node",
"*",
"pilosa",
".",
"Node",
",",
"index",
",",
"field",
"string",
",",
"buf",
"[",
"]",
"byte",
",",
"opts",
"*",
"pilosa",
".",
"ImportOp... | // importNode sends a pre-marshaled import request to a node. | [
"importNode",
"sends",
"a",
"pre",
"-",
"marshaled",
"import",
"request",
"to",
"a",
"node",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/client.go#L466-L513 | train |
pilosa/pilosa | http/client.go | ImportValueK | func (c *InternalClient) ImportValueK(ctx context.Context, index, field string, vals []pilosa.FieldValue, opts ...pilosa.ImportOption) error {
span, ctx := tracing.StartSpanFromContext(ctx, "InternalClient.ImportValueK")
defer span.Finish()
buf, err := c.marshalImportValuePayload(index, field, 0, vals)
if err != nil {
return fmt.Errorf("Error Creating Payload: %s", err)
}
// Set up import options.
options := &pilosa.ImportOptions{}
for _, opt := range opts {
err := opt(options)
if err != nil {
return errors.Wrap(err, "applying option")
}
}
// Get the coordinator node; all bits are sent to the
// primary translate store (i.e. coordinator).
nodes, err := c.Nodes(ctx)
if err != nil {
return fmt.Errorf("getting nodes: %s", err)
}
coord := getCoordinatorNode(nodes)
if coord == nil {
return fmt.Errorf("could not find the coordinator node")
}
// Import to node.
if err := c.importNode(ctx, coord, index, field, buf, options); err != nil {
return fmt.Errorf("import node: host=%s, err=%s", coord.URI, err)
}
return nil
} | go | func (c *InternalClient) ImportValueK(ctx context.Context, index, field string, vals []pilosa.FieldValue, opts ...pilosa.ImportOption) error {
span, ctx := tracing.StartSpanFromContext(ctx, "InternalClient.ImportValueK")
defer span.Finish()
buf, err := c.marshalImportValuePayload(index, field, 0, vals)
if err != nil {
return fmt.Errorf("Error Creating Payload: %s", err)
}
// Set up import options.
options := &pilosa.ImportOptions{}
for _, opt := range opts {
err := opt(options)
if err != nil {
return errors.Wrap(err, "applying option")
}
}
// Get the coordinator node; all bits are sent to the
// primary translate store (i.e. coordinator).
nodes, err := c.Nodes(ctx)
if err != nil {
return fmt.Errorf("getting nodes: %s", err)
}
coord := getCoordinatorNode(nodes)
if coord == nil {
return fmt.Errorf("could not find the coordinator node")
}
// Import to node.
if err := c.importNode(ctx, coord, index, field, buf, options); err != nil {
return fmt.Errorf("import node: host=%s, err=%s", coord.URI, err)
}
return nil
} | [
"func",
"(",
"c",
"*",
"InternalClient",
")",
"ImportValueK",
"(",
"ctx",
"context",
".",
"Context",
",",
"index",
",",
"field",
"string",
",",
"vals",
"[",
"]",
"pilosa",
".",
"FieldValue",
",",
"opts",
"...",
"pilosa",
".",
"ImportOption",
")",
"error"... | // ImportValueK bulk imports keyed field values to a host. | [
"ImportValueK",
"bulk",
"imports",
"keyed",
"field",
"values",
"to",
"a",
"host",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/client.go#L557-L592 | train |
pilosa/pilosa | http/client.go | marshalImportValuePayload | func (c *InternalClient) marshalImportValuePayload(index, field string, shard uint64, vals []pilosa.FieldValue) ([]byte, error) {
// Separate row and column IDs to reduce allocations.
columnIDs := FieldValues(vals).ColumnIDs()
columnKeys := FieldValues(vals).ColumnKeys()
values := FieldValues(vals).Values()
// Marshal data to protobuf.
buf, err := c.serializer.Marshal(&pilosa.ImportValueRequest{
Index: index,
Field: field,
Shard: shard,
ColumnIDs: columnIDs,
ColumnKeys: columnKeys,
Values: values,
})
if err != nil {
return nil, fmt.Errorf("marshal import request: %s", err)
}
return buf, nil
} | go | func (c *InternalClient) marshalImportValuePayload(index, field string, shard uint64, vals []pilosa.FieldValue) ([]byte, error) {
// Separate row and column IDs to reduce allocations.
columnIDs := FieldValues(vals).ColumnIDs()
columnKeys := FieldValues(vals).ColumnKeys()
values := FieldValues(vals).Values()
// Marshal data to protobuf.
buf, err := c.serializer.Marshal(&pilosa.ImportValueRequest{
Index: index,
Field: field,
Shard: shard,
ColumnIDs: columnIDs,
ColumnKeys: columnKeys,
Values: values,
})
if err != nil {
return nil, fmt.Errorf("marshal import request: %s", err)
}
return buf, nil
} | [
"func",
"(",
"c",
"*",
"InternalClient",
")",
"marshalImportValuePayload",
"(",
"index",
",",
"field",
"string",
",",
"shard",
"uint64",
",",
"vals",
"[",
"]",
"pilosa",
".",
"FieldValue",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"columnIDs",
... | // marshalImportValuePayload marshalls the import parameters into a protobuf byte slice. | [
"marshalImportValuePayload",
"marshalls",
"the",
"import",
"parameters",
"into",
"a",
"protobuf",
"byte",
"slice",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/client.go#L595-L614 | train |
pilosa/pilosa | http/client.go | ExportCSV | func (c *InternalClient) ExportCSV(ctx context.Context, index, field string, shard uint64, w io.Writer) error {
span, ctx := tracing.StartSpanFromContext(ctx, "InternalClient.ExportCSV")
defer span.Finish()
if index == "" {
return pilosa.ErrIndexRequired
} else if field == "" {
return pilosa.ErrFieldRequired
}
// Retrieve a list of nodes that own the shard.
nodes, err := c.FragmentNodes(ctx, index, shard)
if err != nil {
return fmt.Errorf("shard nodes: %s", err)
}
// Attempt nodes in random order.
var e error
for _, i := range rand.Perm(len(nodes)) {
node := nodes[i]
if err := c.exportNodeCSV(ctx, node, index, field, shard, w); err != nil {
e = fmt.Errorf("export node: host=%s, err=%s", node.URI, err)
continue
} else {
return nil
}
}
return e
} | go | func (c *InternalClient) ExportCSV(ctx context.Context, index, field string, shard uint64, w io.Writer) error {
span, ctx := tracing.StartSpanFromContext(ctx, "InternalClient.ExportCSV")
defer span.Finish()
if index == "" {
return pilosa.ErrIndexRequired
} else if field == "" {
return pilosa.ErrFieldRequired
}
// Retrieve a list of nodes that own the shard.
nodes, err := c.FragmentNodes(ctx, index, shard)
if err != nil {
return fmt.Errorf("shard nodes: %s", err)
}
// Attempt nodes in random order.
var e error
for _, i := range rand.Perm(len(nodes)) {
node := nodes[i]
if err := c.exportNodeCSV(ctx, node, index, field, shard, w); err != nil {
e = fmt.Errorf("export node: host=%s, err=%s", node.URI, err)
continue
} else {
return nil
}
}
return e
} | [
"func",
"(",
"c",
"*",
"InternalClient",
")",
"ExportCSV",
"(",
"ctx",
"context",
".",
"Context",
",",
"index",
",",
"field",
"string",
",",
"shard",
"uint64",
",",
"w",
"io",
".",
"Writer",
")",
"error",
"{",
"span",
",",
"ctx",
":=",
"tracing",
"."... | // ExportCSV bulk exports data for a single shard from a host to CSV format. | [
"ExportCSV",
"bulk",
"exports",
"data",
"for",
"a",
"single",
"shard",
"from",
"a",
"host",
"to",
"CSV",
"format",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/client.go#L671-L701 | train |
pilosa/pilosa | http/client.go | exportNodeCSV | func (c *InternalClient) exportNodeCSV(ctx context.Context, node *pilosa.Node, index, field string, shard uint64, w io.Writer) error {
span, ctx := tracing.StartSpanFromContext(ctx, "InternalClient.exportNodeCSV")
defer span.Finish()
// Create URL.
u := nodePathToURL(node, "/export")
u.RawQuery = url.Values{
"index": {index},
"field": {field},
"shard": {strconv.FormatUint(shard, 10)},
}.Encode()
// Generate HTTP request.
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return errors.Wrap(err, "creating request")
}
req.Header.Set("Accept", "text/csv")
req.Header.Set("User-Agent", "pilosa/"+pilosa.Version)
// Execute request against the host.
resp, err := c.executeRequest(req.WithContext(ctx))
if err != nil {
return err
}
defer resp.Body.Close()
// Copy body to writer.
if _, err := io.Copy(w, resp.Body); err != nil {
return errors.Wrap(err, "copying")
}
return nil
} | go | func (c *InternalClient) exportNodeCSV(ctx context.Context, node *pilosa.Node, index, field string, shard uint64, w io.Writer) error {
span, ctx := tracing.StartSpanFromContext(ctx, "InternalClient.exportNodeCSV")
defer span.Finish()
// Create URL.
u := nodePathToURL(node, "/export")
u.RawQuery = url.Values{
"index": {index},
"field": {field},
"shard": {strconv.FormatUint(shard, 10)},
}.Encode()
// Generate HTTP request.
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return errors.Wrap(err, "creating request")
}
req.Header.Set("Accept", "text/csv")
req.Header.Set("User-Agent", "pilosa/"+pilosa.Version)
// Execute request against the host.
resp, err := c.executeRequest(req.WithContext(ctx))
if err != nil {
return err
}
defer resp.Body.Close()
// Copy body to writer.
if _, err := io.Copy(w, resp.Body); err != nil {
return errors.Wrap(err, "copying")
}
return nil
} | [
"func",
"(",
"c",
"*",
"InternalClient",
")",
"exportNodeCSV",
"(",
"ctx",
"context",
".",
"Context",
",",
"node",
"*",
"pilosa",
".",
"Node",
",",
"index",
",",
"field",
"string",
",",
"shard",
"uint64",
",",
"w",
"io",
".",
"Writer",
")",
"error",
... | // exportNode copies a CSV export from a node to w. | [
"exportNode",
"copies",
"a",
"CSV",
"export",
"from",
"a",
"node",
"to",
"w",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/client.go#L704-L737 | train |
pilosa/pilosa | http/client.go | CreateFieldWithOptions | func (c *InternalClient) CreateFieldWithOptions(ctx context.Context, index, field string, opt pilosa.FieldOptions) error {
span, ctx := tracing.StartSpanFromContext(ctx, "InternalClient.CreateFieldWithOptions")
defer span.Finish()
if index == "" {
return pilosa.ErrIndexRequired
}
// convert pilosa.FieldOptions to fieldOptions
fieldOpt := fieldOptions{
Type: opt.Type,
Keys: &opt.Keys,
}
if fieldOpt.Type == "set" {
fieldOpt.CacheType = &opt.CacheType
fieldOpt.CacheSize = &opt.CacheSize
} else if fieldOpt.Type == "int" {
fieldOpt.Min = &opt.Min
fieldOpt.Max = &opt.Max
} else if fieldOpt.Type == "time" {
fieldOpt.TimeQuantum = &opt.TimeQuantum
}
// TODO: remove buf completely? (depends on whether importer needs to create specific field types)
// Encode query request.
buf, err := json.Marshal(&postFieldRequest{
Options: fieldOpt,
})
if err != nil {
return errors.Wrap(err, "marshaling")
}
// Create URL & HTTP request.
u := uriPathToURL(c.defaultURI, fmt.Sprintf("/index/%s/field/%s", index, field))
req, err := http.NewRequest("POST", u.String(), bytes.NewReader(buf))
if err != nil {
return errors.Wrap(err, "creating request")
}
req.Header.Set("Content-Length", strconv.Itoa(len(buf)))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", "pilosa/"+pilosa.Version)
// Execute request against the host.
resp, err := c.executeRequest(req.WithContext(ctx))
if err != nil {
if resp != nil && resp.StatusCode == http.StatusConflict {
return pilosa.ErrFieldExists
}
return err
}
return errors.Wrap(resp.Body.Close(), "closing response body")
} | go | func (c *InternalClient) CreateFieldWithOptions(ctx context.Context, index, field string, opt pilosa.FieldOptions) error {
span, ctx := tracing.StartSpanFromContext(ctx, "InternalClient.CreateFieldWithOptions")
defer span.Finish()
if index == "" {
return pilosa.ErrIndexRequired
}
// convert pilosa.FieldOptions to fieldOptions
fieldOpt := fieldOptions{
Type: opt.Type,
Keys: &opt.Keys,
}
if fieldOpt.Type == "set" {
fieldOpt.CacheType = &opt.CacheType
fieldOpt.CacheSize = &opt.CacheSize
} else if fieldOpt.Type == "int" {
fieldOpt.Min = &opt.Min
fieldOpt.Max = &opt.Max
} else if fieldOpt.Type == "time" {
fieldOpt.TimeQuantum = &opt.TimeQuantum
}
// TODO: remove buf completely? (depends on whether importer needs to create specific field types)
// Encode query request.
buf, err := json.Marshal(&postFieldRequest{
Options: fieldOpt,
})
if err != nil {
return errors.Wrap(err, "marshaling")
}
// Create URL & HTTP request.
u := uriPathToURL(c.defaultURI, fmt.Sprintf("/index/%s/field/%s", index, field))
req, err := http.NewRequest("POST", u.String(), bytes.NewReader(buf))
if err != nil {
return errors.Wrap(err, "creating request")
}
req.Header.Set("Content-Length", strconv.Itoa(len(buf)))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", "pilosa/"+pilosa.Version)
// Execute request against the host.
resp, err := c.executeRequest(req.WithContext(ctx))
if err != nil {
if resp != nil && resp.StatusCode == http.StatusConflict {
return pilosa.ErrFieldExists
}
return err
}
return errors.Wrap(resp.Body.Close(), "closing response body")
} | [
"func",
"(",
"c",
"*",
"InternalClient",
")",
"CreateFieldWithOptions",
"(",
"ctx",
"context",
".",
"Context",
",",
"index",
",",
"field",
"string",
",",
"opt",
"pilosa",
".",
"FieldOptions",
")",
"error",
"{",
"span",
",",
"ctx",
":=",
"tracing",
".",
"... | // CreateField creates a new field on the server. | [
"CreateField",
"creates",
"a",
"new",
"field",
"on",
"the",
"server",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/client.go#L785-L838 | train |
pilosa/pilosa | http/client.go | FragmentBlocks | func (c *InternalClient) FragmentBlocks(ctx context.Context, uri *pilosa.URI, index, field, view string, shard uint64) ([]pilosa.FragmentBlock, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "InternalClient.FragmentBlocks")
defer span.Finish()
if uri == nil {
uri = c.defaultURI
}
u := uriPathToURL(uri, "/internal/fragment/blocks")
u.RawQuery = url.Values{
"index": {index},
"field": {field},
"view": {view},
"shard": {strconv.FormatUint(shard, 10)},
}.Encode()
// Build request.
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return nil, errors.Wrap(err, "creating request")
}
req.Header.Set("User-Agent", "pilosa/"+pilosa.Version)
req.Header.Set("Accept", "application/json")
// Execute request.
resp, err := c.executeRequest(req.WithContext(ctx))
if err != nil {
// Return the appropriate error.
if resp != nil && resp.StatusCode == http.StatusNotFound {
return nil, pilosa.ErrFragmentNotFound
}
return nil, err
}
defer resp.Body.Close()
// Decode response object.
var rsp getFragmentBlocksResponse
if err := json.NewDecoder(resp.Body).Decode(&rsp); err != nil {
return nil, errors.Wrap(err, "decoding")
}
return rsp.Blocks, nil
} | go | func (c *InternalClient) FragmentBlocks(ctx context.Context, uri *pilosa.URI, index, field, view string, shard uint64) ([]pilosa.FragmentBlock, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "InternalClient.FragmentBlocks")
defer span.Finish()
if uri == nil {
uri = c.defaultURI
}
u := uriPathToURL(uri, "/internal/fragment/blocks")
u.RawQuery = url.Values{
"index": {index},
"field": {field},
"view": {view},
"shard": {strconv.FormatUint(shard, 10)},
}.Encode()
// Build request.
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return nil, errors.Wrap(err, "creating request")
}
req.Header.Set("User-Agent", "pilosa/"+pilosa.Version)
req.Header.Set("Accept", "application/json")
// Execute request.
resp, err := c.executeRequest(req.WithContext(ctx))
if err != nil {
// Return the appropriate error.
if resp != nil && resp.StatusCode == http.StatusNotFound {
return nil, pilosa.ErrFragmentNotFound
}
return nil, err
}
defer resp.Body.Close()
// Decode response object.
var rsp getFragmentBlocksResponse
if err := json.NewDecoder(resp.Body).Decode(&rsp); err != nil {
return nil, errors.Wrap(err, "decoding")
}
return rsp.Blocks, nil
} | [
"func",
"(",
"c",
"*",
"InternalClient",
")",
"FragmentBlocks",
"(",
"ctx",
"context",
".",
"Context",
",",
"uri",
"*",
"pilosa",
".",
"URI",
",",
"index",
",",
"field",
",",
"view",
"string",
",",
"shard",
"uint64",
")",
"(",
"[",
"]",
"pilosa",
"."... | // FragmentBlocks returns a list of block checksums for a fragment on a host.
// Only returns blocks which contain data. | [
"FragmentBlocks",
"returns",
"a",
"list",
"of",
"block",
"checksums",
"for",
"a",
"fragment",
"on",
"a",
"host",
".",
"Only",
"returns",
"blocks",
"which",
"contain",
"data",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/client.go#L842-L883 | train |
pilosa/pilosa | http/client.go | RowAttrDiff | func (c *InternalClient) RowAttrDiff(ctx context.Context, uri *pilosa.URI, index, field string, blks []pilosa.AttrBlock) (map[uint64]map[string]interface{}, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "InternalClient.RowAttrDiff")
defer span.Finish()
if uri == nil {
uri = c.defaultURI
}
u := uriPathToURL(uri, fmt.Sprintf("/internal/index/%s/field/%s/attr/diff", index, field))
// Encode request.
buf, err := json.Marshal(postFieldAttrDiffRequest{Blocks: blks})
if err != nil {
return nil, errors.Wrap(err, "marshaling")
}
// Build request.
req, err := http.NewRequest("POST", u.String(), bytes.NewReader(buf))
if err != nil {
return nil, errors.Wrap(err, "creating request")
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", "pilosa/"+pilosa.Version)
req.Header.Set("Accept", "application/json")
// Execute request.
resp, err := c.executeRequest(req.WithContext(ctx))
if err != nil {
if resp != nil && resp.StatusCode == http.StatusNotFound {
return nil, pilosa.ErrFieldNotFound
}
return nil, err
}
defer resp.Body.Close()
// Decode response object.
var rsp postFieldAttrDiffResponse
if err := json.NewDecoder(resp.Body).Decode(&rsp); err != nil {
return nil, errors.Wrap(err, "decoding")
}
return rsp.Attrs, nil
} | go | func (c *InternalClient) RowAttrDiff(ctx context.Context, uri *pilosa.URI, index, field string, blks []pilosa.AttrBlock) (map[uint64]map[string]interface{}, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "InternalClient.RowAttrDiff")
defer span.Finish()
if uri == nil {
uri = c.defaultURI
}
u := uriPathToURL(uri, fmt.Sprintf("/internal/index/%s/field/%s/attr/diff", index, field))
// Encode request.
buf, err := json.Marshal(postFieldAttrDiffRequest{Blocks: blks})
if err != nil {
return nil, errors.Wrap(err, "marshaling")
}
// Build request.
req, err := http.NewRequest("POST", u.String(), bytes.NewReader(buf))
if err != nil {
return nil, errors.Wrap(err, "creating request")
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", "pilosa/"+pilosa.Version)
req.Header.Set("Accept", "application/json")
// Execute request.
resp, err := c.executeRequest(req.WithContext(ctx))
if err != nil {
if resp != nil && resp.StatusCode == http.StatusNotFound {
return nil, pilosa.ErrFieldNotFound
}
return nil, err
}
defer resp.Body.Close()
// Decode response object.
var rsp postFieldAttrDiffResponse
if err := json.NewDecoder(resp.Body).Decode(&rsp); err != nil {
return nil, errors.Wrap(err, "decoding")
}
return rsp.Attrs, nil
} | [
"func",
"(",
"c",
"*",
"InternalClient",
")",
"RowAttrDiff",
"(",
"ctx",
"context",
".",
"Context",
",",
"uri",
"*",
"pilosa",
".",
"URI",
",",
"index",
",",
"field",
"string",
",",
"blks",
"[",
"]",
"pilosa",
".",
"AttrBlock",
")",
"(",
"map",
"[",
... | // RowAttrDiff returns data from differing blocks on a remote host. | [
"RowAttrDiff",
"returns",
"data",
"from",
"differing",
"blocks",
"on",
"a",
"remote",
"host",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/client.go#L974-L1014 | train |
pilosa/pilosa | http/client.go | SendMessage | func (c *InternalClient) SendMessage(ctx context.Context, uri *pilosa.URI, msg []byte) error {
span, ctx := tracing.StartSpanFromContext(ctx, "InternalClient.SendMessage")
defer span.Finish()
u := uriPathToURL(uri, "/internal/cluster/message")
req, err := http.NewRequest("POST", u.String(), bytes.NewReader(msg))
if err != nil {
return errors.Wrap(err, "making new request")
}
req.Header.Set("Content-Type", "application/x-protobuf")
req.Header.Set("User-Agent", "pilosa/"+pilosa.Version)
req.Header.Set("Accept", "application/json")
// Execute request.
resp, err := c.executeRequest(req.WithContext(ctx))
if err != nil {
return errors.Wrap(err, "executing request")
}
return errors.Wrap(resp.Body.Close(), "closing response body")
} | go | func (c *InternalClient) SendMessage(ctx context.Context, uri *pilosa.URI, msg []byte) error {
span, ctx := tracing.StartSpanFromContext(ctx, "InternalClient.SendMessage")
defer span.Finish()
u := uriPathToURL(uri, "/internal/cluster/message")
req, err := http.NewRequest("POST", u.String(), bytes.NewReader(msg))
if err != nil {
return errors.Wrap(err, "making new request")
}
req.Header.Set("Content-Type", "application/x-protobuf")
req.Header.Set("User-Agent", "pilosa/"+pilosa.Version)
req.Header.Set("Accept", "application/json")
// Execute request.
resp, err := c.executeRequest(req.WithContext(ctx))
if err != nil {
return errors.Wrap(err, "executing request")
}
return errors.Wrap(resp.Body.Close(), "closing response body")
} | [
"func",
"(",
"c",
"*",
"InternalClient",
")",
"SendMessage",
"(",
"ctx",
"context",
".",
"Context",
",",
"uri",
"*",
"pilosa",
".",
"URI",
",",
"msg",
"[",
"]",
"byte",
")",
"error",
"{",
"span",
",",
"ctx",
":=",
"tracing",
".",
"StartSpanFromContext"... | // SendMessage posts a message synchronously. | [
"SendMessage",
"posts",
"a",
"message",
"synchronously",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/client.go#L1017-L1036 | train |
pilosa/pilosa | http/client.go | executeRequest | func (c *InternalClient) executeRequest(req *http.Request) (*http.Response, error) {
tracing.GlobalTracer.InjectHTTPHeaders(req)
resp, err := c.httpClient.Do(req)
if err != nil {
if resp != nil {
resp.Body.Close()
}
return nil, errors.Wrap(err, "getting response")
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
defer resp.Body.Close()
buf, err := ioutil.ReadAll(resp.Body)
if err != nil {
return resp, errors.Wrapf(err, "bad status '%s' and err reading body", resp.Status)
}
var msg string
// try to decode a JSON response
var sr successResponse
if err = json.Unmarshal(buf, &sr); err == nil {
msg = sr.Error.Error()
} else {
msg = string(buf)
}
return resp, errors.Errorf("server error %s: '%s'", resp.Status, msg)
}
return resp, nil
} | go | func (c *InternalClient) executeRequest(req *http.Request) (*http.Response, error) {
tracing.GlobalTracer.InjectHTTPHeaders(req)
resp, err := c.httpClient.Do(req)
if err != nil {
if resp != nil {
resp.Body.Close()
}
return nil, errors.Wrap(err, "getting response")
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
defer resp.Body.Close()
buf, err := ioutil.ReadAll(resp.Body)
if err != nil {
return resp, errors.Wrapf(err, "bad status '%s' and err reading body", resp.Status)
}
var msg string
// try to decode a JSON response
var sr successResponse
if err = json.Unmarshal(buf, &sr); err == nil {
msg = sr.Error.Error()
} else {
msg = string(buf)
}
return resp, errors.Errorf("server error %s: '%s'", resp.Status, msg)
}
return resp, nil
} | [
"func",
"(",
"c",
"*",
"InternalClient",
")",
"executeRequest",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"tracing",
".",
"GlobalTracer",
".",
"InjectHTTPHeaders",
"(",
"req",
")",
"\n",
"r... | // executeRequest executes the given request and checks the Response. For
// responses with non-2XX status, the body is read and closed, and an error is
// returned. If the error is nil, the caller must ensure that the response body
// is closed. | [
"executeRequest",
"executes",
"the",
"given",
"request",
"and",
"checks",
"the",
"Response",
".",
"For",
"responses",
"with",
"non",
"-",
"2XX",
"status",
"the",
"body",
"is",
"read",
"and",
"closed",
"and",
"an",
"error",
"is",
"returned",
".",
"If",
"the... | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/client.go#L1042-L1068 | train |
pilosa/pilosa | http/client.go | HasRowKeys | func (p Bits) HasRowKeys() bool {
for i := range p {
if p[i].RowKey != "" {
return true
}
}
return false
} | go | func (p Bits) HasRowKeys() bool {
for i := range p {
if p[i].RowKey != "" {
return true
}
}
return false
} | [
"func",
"(",
"p",
"Bits",
")",
"HasRowKeys",
"(",
")",
"bool",
"{",
"for",
"i",
":=",
"range",
"p",
"{",
"if",
"p",
"[",
"i",
"]",
".",
"RowKey",
"!=",
"\"\"",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // HasRowKeys returns true if any values use a row key. | [
"HasRowKeys",
"returns",
"true",
"if",
"any",
"values",
"use",
"a",
"row",
"key",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/client.go#L1087-L1094 | train |
pilosa/pilosa | http/client.go | RowIDs | func (p Bits) RowIDs() []uint64 {
if p.HasRowKeys() {
return nil
}
other := make([]uint64, len(p))
for i := range p {
other[i] = p[i].RowID
}
return other
} | go | func (p Bits) RowIDs() []uint64 {
if p.HasRowKeys() {
return nil
}
other := make([]uint64, len(p))
for i := range p {
other[i] = p[i].RowID
}
return other
} | [
"func",
"(",
"p",
"Bits",
")",
"RowIDs",
"(",
")",
"[",
"]",
"uint64",
"{",
"if",
"p",
".",
"HasRowKeys",
"(",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"other",
":=",
"make",
"(",
"[",
"]",
"uint64",
",",
"len",
"(",
"p",
")",
")",
"\n",
... | // RowIDs returns a slice of all the row IDs. | [
"RowIDs",
"returns",
"a",
"slice",
"of",
"all",
"the",
"row",
"IDs",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/client.go#L1107-L1116 | train |
pilosa/pilosa | http/client.go | ColumnIDs | func (p Bits) ColumnIDs() []uint64 {
if p.HasColumnKeys() {
return nil
}
other := make([]uint64, len(p))
for i := range p {
other[i] = p[i].ColumnID
}
return other
} | go | func (p Bits) ColumnIDs() []uint64 {
if p.HasColumnKeys() {
return nil
}
other := make([]uint64, len(p))
for i := range p {
other[i] = p[i].ColumnID
}
return other
} | [
"func",
"(",
"p",
"Bits",
")",
"ColumnIDs",
"(",
")",
"[",
"]",
"uint64",
"{",
"if",
"p",
".",
"HasColumnKeys",
"(",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"other",
":=",
"make",
"(",
"[",
"]",
"uint64",
",",
"len",
"(",
"p",
")",
")",
"... | // ColumnIDs returns a slice of all the column IDs. | [
"ColumnIDs",
"returns",
"a",
"slice",
"of",
"all",
"the",
"column",
"IDs",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/client.go#L1119-L1128 | train |
pilosa/pilosa | http/client.go | RowKeys | func (p Bits) RowKeys() []string {
if !p.HasRowKeys() {
return nil
}
other := make([]string, len(p))
for i := range p {
other[i] = p[i].RowKey
}
return other
} | go | func (p Bits) RowKeys() []string {
if !p.HasRowKeys() {
return nil
}
other := make([]string, len(p))
for i := range p {
other[i] = p[i].RowKey
}
return other
} | [
"func",
"(",
"p",
"Bits",
")",
"RowKeys",
"(",
")",
"[",
"]",
"string",
"{",
"if",
"!",
"p",
".",
"HasRowKeys",
"(",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"other",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"p",
")",
")",
... | // RowKeys returns a slice of all the row keys. | [
"RowKeys",
"returns",
"a",
"slice",
"of",
"all",
"the",
"row",
"keys",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/client.go#L1131-L1140 | train |
pilosa/pilosa | http/client.go | Timestamps | func (p Bits) Timestamps() []int64 {
other := make([]int64, len(p))
for i := range p {
other[i] = p[i].Timestamp
}
return other
} | go | func (p Bits) Timestamps() []int64 {
other := make([]int64, len(p))
for i := range p {
other[i] = p[i].Timestamp
}
return other
} | [
"func",
"(",
"p",
"Bits",
")",
"Timestamps",
"(",
")",
"[",
"]",
"int64",
"{",
"other",
":=",
"make",
"(",
"[",
"]",
"int64",
",",
"len",
"(",
"p",
")",
")",
"\n",
"for",
"i",
":=",
"range",
"p",
"{",
"other",
"[",
"i",
"]",
"=",
"p",
"[",
... | // Timestamps returns a slice of all the timestamps. | [
"Timestamps",
"returns",
"a",
"slice",
"of",
"all",
"the",
"timestamps",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/client.go#L1155-L1161 | train |
pilosa/pilosa | http/client.go | GroupByShard | func (p Bits) GroupByShard() map[uint64][]pilosa.Bit {
m := make(map[uint64][]pilosa.Bit)
for _, bit := range p {
shard := bit.ColumnID / pilosa.ShardWidth
m[shard] = append(m[shard], bit)
}
for shard, bits := range m {
sort.Sort(Bits(bits))
m[shard] = bits
}
return m
} | go | func (p Bits) GroupByShard() map[uint64][]pilosa.Bit {
m := make(map[uint64][]pilosa.Bit)
for _, bit := range p {
shard := bit.ColumnID / pilosa.ShardWidth
m[shard] = append(m[shard], bit)
}
for shard, bits := range m {
sort.Sort(Bits(bits))
m[shard] = bits
}
return m
} | [
"func",
"(",
"p",
"Bits",
")",
"GroupByShard",
"(",
")",
"map",
"[",
"uint64",
"]",
"[",
"]",
"pilosa",
".",
"Bit",
"{",
"m",
":=",
"make",
"(",
"map",
"[",
"uint64",
"]",
"[",
"]",
"pilosa",
".",
"Bit",
")",
"\n",
"for",
"_",
",",
"bit",
":=... | // GroupByShard returns a map of bits by shard. | [
"GroupByShard",
"returns",
"a",
"map",
"of",
"bits",
"by",
"shard",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/client.go#L1164-L1177 | train |
pilosa/pilosa | http/client.go | ColumnKeys | func (p FieldValues) ColumnKeys() []string {
if !p.HasColumnKeys() {
return nil
}
other := make([]string, len(p))
for i := range p {
other[i] = p[i].ColumnKey
}
return other
} | go | func (p FieldValues) ColumnKeys() []string {
if !p.HasColumnKeys() {
return nil
}
other := make([]string, len(p))
for i := range p {
other[i] = p[i].ColumnKey
}
return other
} | [
"func",
"(",
"p",
"FieldValues",
")",
"ColumnKeys",
"(",
")",
"[",
"]",
"string",
"{",
"if",
"!",
"p",
".",
"HasColumnKeys",
"(",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"other",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"p",
... | // ColumnKeys returns a slice of all the column keys. | [
"ColumnKeys",
"returns",
"a",
"slice",
"of",
"all",
"the",
"column",
"keys",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/client.go#L1212-L1221 | train |
pilosa/pilosa | http/client.go | Values | func (p FieldValues) Values() []int64 {
other := make([]int64, len(p))
for i := range p {
other[i] = p[i].Value
}
return other
} | go | func (p FieldValues) Values() []int64 {
other := make([]int64, len(p))
for i := range p {
other[i] = p[i].Value
}
return other
} | [
"func",
"(",
"p",
"FieldValues",
")",
"Values",
"(",
")",
"[",
"]",
"int64",
"{",
"other",
":=",
"make",
"(",
"[",
"]",
"int64",
",",
"len",
"(",
"p",
")",
")",
"\n",
"for",
"i",
":=",
"range",
"p",
"{",
"other",
"[",
"i",
"]",
"=",
"p",
"[... | // Values returns a slice of all the values. | [
"Values",
"returns",
"a",
"slice",
"of",
"all",
"the",
"values",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/client.go#L1224-L1230 | train |
pilosa/pilosa | http/client.go | GroupByShard | func (p FieldValues) GroupByShard() map[uint64][]pilosa.FieldValue {
m := make(map[uint64][]pilosa.FieldValue)
for _, val := range p {
shard := val.ColumnID / pilosa.ShardWidth
m[shard] = append(m[shard], val)
}
for shard, vals := range m {
sort.Sort(FieldValues(vals))
m[shard] = vals
}
return m
} | go | func (p FieldValues) GroupByShard() map[uint64][]pilosa.FieldValue {
m := make(map[uint64][]pilosa.FieldValue)
for _, val := range p {
shard := val.ColumnID / pilosa.ShardWidth
m[shard] = append(m[shard], val)
}
for shard, vals := range m {
sort.Sort(FieldValues(vals))
m[shard] = vals
}
return m
} | [
"func",
"(",
"p",
"FieldValues",
")",
"GroupByShard",
"(",
")",
"map",
"[",
"uint64",
"]",
"[",
"]",
"pilosa",
".",
"FieldValue",
"{",
"m",
":=",
"make",
"(",
"map",
"[",
"uint64",
"]",
"[",
"]",
"pilosa",
".",
"FieldValue",
")",
"\n",
"for",
"_",
... | // GroupByShard returns a map of field values by shard. | [
"GroupByShard",
"returns",
"a",
"map",
"of",
"field",
"values",
"by",
"shard",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/client.go#L1233-L1246 | train |
pilosa/pilosa | syswrap/os.go | OpenFile | func OpenFile(name string, flag int, perm os.FileMode) (file *os.File, mustClose bool, err error) {
file, err = os.OpenFile(name, flag, perm)
fileMu.RLock()
defer fileMu.RUnlock()
if newCount := atomic.AddUint64(&fileCount, 1); newCount > maxFileCount {
mustClose = true
}
return file, mustClose, err
} | go | func OpenFile(name string, flag int, perm os.FileMode) (file *os.File, mustClose bool, err error) {
file, err = os.OpenFile(name, flag, perm)
fileMu.RLock()
defer fileMu.RUnlock()
if newCount := atomic.AddUint64(&fileCount, 1); newCount > maxFileCount {
mustClose = true
}
return file, mustClose, err
} | [
"func",
"OpenFile",
"(",
"name",
"string",
",",
"flag",
"int",
",",
"perm",
"os",
".",
"FileMode",
")",
"(",
"file",
"*",
"os",
".",
"File",
",",
"mustClose",
"bool",
",",
"err",
"error",
")",
"{",
"file",
",",
"err",
"=",
"os",
".",
"OpenFile",
... | // OpenFile passes the arguments along to os.OpenFile while incrementing a
// counter. If the counter is above the maximum, it returns mustClose true to
// signal the calling function that it should not keep the file open
// indefinitely. Files opened with this function should be closed by
// syswrap.CloseFile. | [
"OpenFile",
"passes",
"the",
"arguments",
"along",
"to",
"os",
".",
"OpenFile",
"while",
"incrementing",
"a",
"counter",
".",
"If",
"the",
"counter",
"is",
"above",
"the",
"maximum",
"it",
"returns",
"mustClose",
"true",
"to",
"signal",
"the",
"calling",
"fu... | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/syswrap/os.go#L41-L49 | train |
pilosa/pilosa | syswrap/os.go | CloseFile | func CloseFile(f *os.File) error {
atomic.AddUint64(&fileCount, ^uint64(0)) // decrement
return f.Close()
} | go | func CloseFile(f *os.File) error {
atomic.AddUint64(&fileCount, ^uint64(0)) // decrement
return f.Close()
} | [
"func",
"CloseFile",
"(",
"f",
"*",
"os",
".",
"File",
")",
"error",
"{",
"atomic",
".",
"AddUint64",
"(",
"&",
"fileCount",
",",
"^",
"uint64",
"(",
"0",
")",
")",
"\n",
"return",
"f",
".",
"Close",
"(",
")",
"\n",
"}"
] | // CloseFile decrements the global count of open files and closes the file. | [
"CloseFile",
"decrements",
"the",
"global",
"count",
"of",
"open",
"files",
"and",
"closes",
"the",
"file",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/syswrap/os.go#L52-L55 | train |
pilosa/pilosa | syswrap/mmap.go | Mmap | func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) {
mu.RLock()
defer mu.RUnlock()
if newCount := atomic.AddUint64(&mapCount, 1); newCount > maxMapCount {
atomic.AddUint64(&mapCount, ^uint64(0)) // decrement
return nil, ErrMaxMapCountReached
}
data, err = syscall.Mmap(fd, offset, length, prot, flags)
if err != nil {
atomic.AddUint64(&mapCount, ^uint64(0)) // decrement
}
return data, err
} | go | func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) {
mu.RLock()
defer mu.RUnlock()
if newCount := atomic.AddUint64(&mapCount, 1); newCount > maxMapCount {
atomic.AddUint64(&mapCount, ^uint64(0)) // decrement
return nil, ErrMaxMapCountReached
}
data, err = syscall.Mmap(fd, offset, length, prot, flags)
if err != nil {
atomic.AddUint64(&mapCount, ^uint64(0)) // decrement
}
return data, err
} | [
"func",
"Mmap",
"(",
"fd",
"int",
",",
"offset",
"int64",
",",
"length",
"int",
",",
"prot",
"int",
",",
"flags",
"int",
")",
"(",
"data",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"mu",
".",
... | // Mmap increments the global map count, and then calls syscall.Mmap. It
// decrements the map count and returns an error if the count was over the
// limit. If syscall.Mmap returns an error it also decrements the count. | [
"Mmap",
"increments",
"the",
"global",
"map",
"count",
"and",
"then",
"calls",
"syscall",
".",
"Mmap",
".",
"It",
"decrements",
"the",
"map",
"count",
"and",
"returns",
"an",
"error",
"if",
"the",
"count",
"was",
"over",
"the",
"limit",
".",
"If",
"sysca... | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/syswrap/mmap.go#L46-L58 | train |
pilosa/pilosa | syswrap/mmap.go | Munmap | func Munmap(b []byte) (err error) {
err = syscall.Munmap(b)
if err == nil {
atomic.AddUint64(&mapCount, ^uint64(0)) // decrement
}
return err
} | go | func Munmap(b []byte) (err error) {
err = syscall.Munmap(b)
if err == nil {
atomic.AddUint64(&mapCount, ^uint64(0)) // decrement
}
return err
} | [
"func",
"Munmap",
"(",
"b",
"[",
"]",
"byte",
")",
"(",
"err",
"error",
")",
"{",
"err",
"=",
"syscall",
".",
"Munmap",
"(",
"b",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"atomic",
".",
"AddUint64",
"(",
"&",
"mapCount",
",",
"^",
"uint64",
"(... | // Munmap calls sycall.Munmap, and then decrements the global map count if there
// was no error. | [
"Munmap",
"calls",
"sycall",
".",
"Munmap",
"and",
"then",
"decrements",
"the",
"global",
"map",
"count",
"if",
"there",
"was",
"no",
"error",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/syswrap/mmap.go#L62-L68 | train |
pilosa/pilosa | time.go | Set | func (q *TimeQuantum) Set(value string) error {
*q = TimeQuantum(value)
return nil
} | go | func (q *TimeQuantum) Set(value string) error {
*q = TimeQuantum(value)
return nil
} | [
"func",
"(",
"q",
"*",
"TimeQuantum",
")",
"Set",
"(",
"value",
"string",
")",
"error",
"{",
"*",
"q",
"=",
"TimeQuantum",
"(",
"value",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // The following methods are required to implement pflag Value interface.
// Set sets the time quantum value. | [
"The",
"following",
"methods",
"are",
"required",
"to",
"implement",
"pflag",
"Value",
"interface",
".",
"Set",
"sets",
"the",
"time",
"quantum",
"value",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/time.go#L60-L63 | train |
pilosa/pilosa | time.go | viewByTimeUnit | func viewByTimeUnit(name string, t time.Time, unit rune) string {
switch unit {
case 'Y':
return fmt.Sprintf("%s_%s", name, t.Format("2006"))
case 'M':
return fmt.Sprintf("%s_%s", name, t.Format("200601"))
case 'D':
return fmt.Sprintf("%s_%s", name, t.Format("20060102"))
case 'H':
return fmt.Sprintf("%s_%s", name, t.Format("2006010215"))
default:
return ""
}
} | go | func viewByTimeUnit(name string, t time.Time, unit rune) string {
switch unit {
case 'Y':
return fmt.Sprintf("%s_%s", name, t.Format("2006"))
case 'M':
return fmt.Sprintf("%s_%s", name, t.Format("200601"))
case 'D':
return fmt.Sprintf("%s_%s", name, t.Format("20060102"))
case 'H':
return fmt.Sprintf("%s_%s", name, t.Format("2006010215"))
default:
return ""
}
} | [
"func",
"viewByTimeUnit",
"(",
"name",
"string",
",",
"t",
"time",
".",
"Time",
",",
"unit",
"rune",
")",
"string",
"{",
"switch",
"unit",
"{",
"case",
"'Y'",
":",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"%s_%s\"",
",",
"name",
",",
"t",
".",
"Format... | // viewByTimeUnit returns the view name for time with a given quantum unit. | [
"viewByTimeUnit",
"returns",
"the",
"view",
"name",
"for",
"time",
"with",
"a",
"given",
"quantum",
"unit",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/time.go#L75-L88 | train |
pilosa/pilosa | time.go | viewsByTime | func viewsByTime(name string, t time.Time, q TimeQuantum) []string { // nolint: unparam
a := make([]string, 0, len(q))
for _, unit := range q {
view := viewByTimeUnit(name, t, unit)
if view == "" {
continue
}
a = append(a, view)
}
return a
} | go | func viewsByTime(name string, t time.Time, q TimeQuantum) []string { // nolint: unparam
a := make([]string, 0, len(q))
for _, unit := range q {
view := viewByTimeUnit(name, t, unit)
if view == "" {
continue
}
a = append(a, view)
}
return a
} | [
"func",
"viewsByTime",
"(",
"name",
"string",
",",
"t",
"time",
".",
"Time",
",",
"q",
"TimeQuantum",
")",
"[",
"]",
"string",
"{",
"a",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"q",
")",
")",
"\n",
"for",
"_",
",",
"... | // viewsByTime returns a list of views for a given timestamp. | [
"viewsByTime",
"returns",
"a",
"list",
"of",
"views",
"for",
"a",
"given",
"timestamp",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/time.go#L91-L101 | train |
pilosa/pilosa | time.go | viewsByTimeRange | func viewsByTimeRange(name string, start, end time.Time, q TimeQuantum) []string { // nolint: unparam
t := start
// Save flags for performance.
hasYear := q.HasYear()
hasMonth := q.HasMonth()
hasDay := q.HasDay()
hasHour := q.HasHour()
var results []string
// Walk up from smallest units to largest units.
if hasHour || hasDay || hasMonth {
for t.Before(end) {
if hasHour {
if !nextDayGTE(t, end) {
break
} else if t.Hour() != 0 {
results = append(results, viewByTimeUnit(name, t, 'H'))
t = t.Add(time.Hour)
continue
}
}
if hasDay {
if !nextMonthGTE(t, end) {
break
} else if t.Day() != 1 {
results = append(results, viewByTimeUnit(name, t, 'D'))
t = t.AddDate(0, 0, 1)
continue
}
}
if hasMonth {
if !nextYearGTE(t, end) {
break
} else if t.Month() != 1 {
results = append(results, viewByTimeUnit(name, t, 'M'))
t = addMonth(t)
continue
}
}
// If a unit exists but isn't set and there are no larger units
// available then we need to exit the loop because we are no longer
// making progress.
break
}
}
// Walk back down from largest units to smallest units.
for t.Before(end) {
if hasYear && nextYearGTE(t, end) {
results = append(results, viewByTimeUnit(name, t, 'Y'))
t = t.AddDate(1, 0, 0)
} else if hasMonth && nextMonthGTE(t, end) {
results = append(results, viewByTimeUnit(name, t, 'M'))
t = addMonth(t)
} else if hasDay && nextDayGTE(t, end) {
results = append(results, viewByTimeUnit(name, t, 'D'))
t = t.AddDate(0, 0, 1)
} else if hasHour {
results = append(results, viewByTimeUnit(name, t, 'H'))
t = t.Add(time.Hour)
} else {
break
}
}
return results
} | go | func viewsByTimeRange(name string, start, end time.Time, q TimeQuantum) []string { // nolint: unparam
t := start
// Save flags for performance.
hasYear := q.HasYear()
hasMonth := q.HasMonth()
hasDay := q.HasDay()
hasHour := q.HasHour()
var results []string
// Walk up from smallest units to largest units.
if hasHour || hasDay || hasMonth {
for t.Before(end) {
if hasHour {
if !nextDayGTE(t, end) {
break
} else if t.Hour() != 0 {
results = append(results, viewByTimeUnit(name, t, 'H'))
t = t.Add(time.Hour)
continue
}
}
if hasDay {
if !nextMonthGTE(t, end) {
break
} else if t.Day() != 1 {
results = append(results, viewByTimeUnit(name, t, 'D'))
t = t.AddDate(0, 0, 1)
continue
}
}
if hasMonth {
if !nextYearGTE(t, end) {
break
} else if t.Month() != 1 {
results = append(results, viewByTimeUnit(name, t, 'M'))
t = addMonth(t)
continue
}
}
// If a unit exists but isn't set and there are no larger units
// available then we need to exit the loop because we are no longer
// making progress.
break
}
}
// Walk back down from largest units to smallest units.
for t.Before(end) {
if hasYear && nextYearGTE(t, end) {
results = append(results, viewByTimeUnit(name, t, 'Y'))
t = t.AddDate(1, 0, 0)
} else if hasMonth && nextMonthGTE(t, end) {
results = append(results, viewByTimeUnit(name, t, 'M'))
t = addMonth(t)
} else if hasDay && nextDayGTE(t, end) {
results = append(results, viewByTimeUnit(name, t, 'D'))
t = t.AddDate(0, 0, 1)
} else if hasHour {
results = append(results, viewByTimeUnit(name, t, 'H'))
t = t.Add(time.Hour)
} else {
break
}
}
return results
} | [
"func",
"viewsByTimeRange",
"(",
"name",
"string",
",",
"start",
",",
"end",
"time",
".",
"Time",
",",
"q",
"TimeQuantum",
")",
"[",
"]",
"string",
"{",
"t",
":=",
"start",
"\n",
"hasYear",
":=",
"q",
".",
"HasYear",
"(",
")",
"\n",
"hasMonth",
":=",... | // viewsByTimeRange returns a list of views to traverse to query a time range. | [
"viewsByTimeRange",
"returns",
"a",
"list",
"of",
"views",
"to",
"traverse",
"to",
"query",
"a",
"time",
"range",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/time.go#L104-L176 | train |
pilosa/pilosa | time.go | parseTime | func parseTime(t interface{}) (time.Time, error) {
var err error
var calcTime time.Time
switch v := t.(type) {
case string:
if calcTime, err = time.Parse(TimeFormat, v); err != nil {
return time.Time{}, errors.New("cannot parse string time")
}
case int64:
calcTime = time.Unix(v, 0).UTC()
default:
return time.Time{}, errors.New("arg must be a timestamp")
}
return calcTime, nil
} | go | func parseTime(t interface{}) (time.Time, error) {
var err error
var calcTime time.Time
switch v := t.(type) {
case string:
if calcTime, err = time.Parse(TimeFormat, v); err != nil {
return time.Time{}, errors.New("cannot parse string time")
}
case int64:
calcTime = time.Unix(v, 0).UTC()
default:
return time.Time{}, errors.New("arg must be a timestamp")
}
return calcTime, nil
} | [
"func",
"parseTime",
"(",
"t",
"interface",
"{",
"}",
")",
"(",
"time",
".",
"Time",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n",
"var",
"calcTime",
"time",
".",
"Time",
"\n",
"switch",
"v",
":=",
"t",
".",
"(",
"type",
")",
"{",
"case",
... | // parseTime parses a string or int64 into a time.Time value. | [
"parseTime",
"parses",
"a",
"string",
"or",
"int64",
"into",
"a",
"time",
".",
"Time",
"value",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/time.go#L220-L234 | train |
pilosa/pilosa | time.go | timeOfView | func timeOfView(v string, adj bool) (time.Time, error) {
if v == "" {
return time.Time{}, nil
}
layout := "2006010203"
timePart := viewTimePart(v)
switch len(timePart) {
case 4: // year
t, err := time.Parse(layout[:4], timePart)
if err != nil {
return time.Time{}, err
}
if adj {
t = t.AddDate(1, 0, 0)
}
return t, nil
case 6: // month
t, err := time.Parse(layout[:6], timePart)
if err != nil {
return time.Time{}, err
}
if adj {
t = addMonth(t)
}
return t, nil
case 8: // day
t, err := time.Parse(layout[:8], timePart)
if err != nil {
return time.Time{}, err
}
if adj {
t = t.AddDate(0, 0, 1)
}
return t, nil
case 10: // hour
t, err := time.Parse(layout[:10], timePart)
if err != nil {
return time.Time{}, err
}
if adj {
t = t.Add(time.Hour)
}
return t, nil
}
return time.Time{}, fmt.Errorf("invalid time format on view: %s", v)
} | go | func timeOfView(v string, adj bool) (time.Time, error) {
if v == "" {
return time.Time{}, nil
}
layout := "2006010203"
timePart := viewTimePart(v)
switch len(timePart) {
case 4: // year
t, err := time.Parse(layout[:4], timePart)
if err != nil {
return time.Time{}, err
}
if adj {
t = t.AddDate(1, 0, 0)
}
return t, nil
case 6: // month
t, err := time.Parse(layout[:6], timePart)
if err != nil {
return time.Time{}, err
}
if adj {
t = addMonth(t)
}
return t, nil
case 8: // day
t, err := time.Parse(layout[:8], timePart)
if err != nil {
return time.Time{}, err
}
if adj {
t = t.AddDate(0, 0, 1)
}
return t, nil
case 10: // hour
t, err := time.Parse(layout[:10], timePart)
if err != nil {
return time.Time{}, err
}
if adj {
t = t.Add(time.Hour)
}
return t, nil
}
return time.Time{}, fmt.Errorf("invalid time format on view: %s", v)
} | [
"func",
"timeOfView",
"(",
"v",
"string",
",",
"adj",
"bool",
")",
"(",
"time",
".",
"Time",
",",
"error",
")",
"{",
"if",
"v",
"==",
"\"\"",
"{",
"return",
"time",
".",
"Time",
"{",
"}",
",",
"nil",
"\n",
"}",
"\n",
"layout",
":=",
"\"2006010203... | // timeOfView returns a valid time.Time based on the view string.
// For upper bound use, the result can be adjusted by one by setting
// the `adj` argument to `true`. | [
"timeOfView",
"returns",
"a",
"valid",
"time",
".",
"Time",
"based",
"on",
"the",
"view",
"string",
".",
"For",
"upper",
"bound",
"use",
"the",
"result",
"can",
"be",
"adjusted",
"by",
"one",
"by",
"setting",
"the",
"adj",
"argument",
"to",
"true",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/time.go#L279-L327 | train |
pilosa/pilosa | cmd.go | NewCmdIO | func NewCmdIO(stdin io.Reader, stdout, stderr io.Writer) *CmdIO {
return &CmdIO{
Stdin: stdin,
Stdout: stdout,
Stderr: stderr,
}
} | go | func NewCmdIO(stdin io.Reader, stdout, stderr io.Writer) *CmdIO {
return &CmdIO{
Stdin: stdin,
Stdout: stdout,
Stderr: stderr,
}
} | [
"func",
"NewCmdIO",
"(",
"stdin",
"io",
".",
"Reader",
",",
"stdout",
",",
"stderr",
"io",
".",
"Writer",
")",
"*",
"CmdIO",
"{",
"return",
"&",
"CmdIO",
"{",
"Stdin",
":",
"stdin",
",",
"Stdout",
":",
"stdout",
",",
"Stderr",
":",
"stderr",
",",
"... | // NewCmdIO returns a new instance of CmdIO with inputs and outputs set to the
// arguments. | [
"NewCmdIO",
"returns",
"a",
"new",
"instance",
"of",
"CmdIO",
"with",
"inputs",
"and",
"outputs",
"set",
"to",
"the",
"arguments",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cmd.go#L28-L34 | train |
pilosa/pilosa | executor.go | newExecutor | func newExecutor(opts ...executorOption) *executor {
e := &executor{
client: newNopInternalQueryClient(),
}
for _, opt := range opts {
err := opt(e)
if err != nil {
panic(err)
}
}
return e
} | go | func newExecutor(opts ...executorOption) *executor {
e := &executor{
client: newNopInternalQueryClient(),
}
for _, opt := range opts {
err := opt(e)
if err != nil {
panic(err)
}
}
return e
} | [
"func",
"newExecutor",
"(",
"opts",
"...",
"executorOption",
")",
"*",
"executor",
"{",
"e",
":=",
"&",
"executor",
"{",
"client",
":",
"newNopInternalQueryClient",
"(",
")",
",",
"}",
"\n",
"for",
"_",
",",
"opt",
":=",
"range",
"opts",
"{",
"err",
":... | // newExecutor returns a new instance of Executor. | [
"newExecutor",
"returns",
"a",
"new",
"instance",
"of",
"Executor",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/executor.go#L71-L82 | train |
pilosa/pilosa | executor.go | Execute | func (e *executor) Execute(ctx context.Context, index string, q *pql.Query, shards []uint64, opt *execOptions) (QueryResponse, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "Executor.Execute")
defer span.Finish()
resp := QueryResponse{}
// Check for query cancellation.
if err := validateQueryContext(ctx); err != nil {
return resp, err
}
// Verify that an index is set.
if index == "" {
return resp, ErrIndexRequired
}
idx := e.Holder.Index(index)
if idx == nil {
return resp, ErrIndexNotFound
}
// Verify that the number of writes do not exceed the maximum.
if e.MaxWritesPerRequest > 0 && q.WriteCallN() > e.MaxWritesPerRequest {
return resp, ErrTooManyWrites
}
// Default options.
if opt == nil {
opt = &execOptions{}
}
// Translate query keys to ids, if necessary.
// No need to translate a remote call.
if !opt.Remote {
if err := e.translateCalls(ctx, index, idx, q.Calls); err != nil {
return resp, err
} else if err := validateQueryContext(ctx); err != nil {
return resp, err
}
}
results, err := e.execute(ctx, index, q, shards, opt)
if err != nil {
return resp, err
} else if err := validateQueryContext(ctx); err != nil {
return resp, err
}
resp.Results = results
// Fill column attributes if requested.
if opt.ColumnAttrs {
// Consolidate all column ids across all calls.
var columnIDs []uint64
for _, result := range results {
bm, ok := result.(*Row)
if !ok {
continue
}
columnIDs = uint64Slice(columnIDs).merge(bm.Columns())
}
// Retrieve column attributes across all calls.
columnAttrSets, err := e.readColumnAttrSets(e.Holder.Index(index), columnIDs)
if err != nil {
return resp, errors.Wrap(err, "reading column attrs")
}
// Translate column attributes, if necessary.
if idx.Keys() {
for _, col := range columnAttrSets {
v, err := e.Holder.translateFile.TranslateColumnToString(index, col.ID)
if err != nil {
return resp, err
}
col.Key, col.ID = v, 0
}
}
resp.ColumnAttrSets = columnAttrSets
}
// Translate response objects from ids to keys, if necessary.
// No need to translate a remote call.
if !opt.Remote {
if err := e.translateResults(ctx, index, idx, q.Calls, results); err != nil {
return resp, err
} else if err := validateQueryContext(ctx); err != nil {
return resp, err
}
}
return resp, nil
} | go | func (e *executor) Execute(ctx context.Context, index string, q *pql.Query, shards []uint64, opt *execOptions) (QueryResponse, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "Executor.Execute")
defer span.Finish()
resp := QueryResponse{}
// Check for query cancellation.
if err := validateQueryContext(ctx); err != nil {
return resp, err
}
// Verify that an index is set.
if index == "" {
return resp, ErrIndexRequired
}
idx := e.Holder.Index(index)
if idx == nil {
return resp, ErrIndexNotFound
}
// Verify that the number of writes do not exceed the maximum.
if e.MaxWritesPerRequest > 0 && q.WriteCallN() > e.MaxWritesPerRequest {
return resp, ErrTooManyWrites
}
// Default options.
if opt == nil {
opt = &execOptions{}
}
// Translate query keys to ids, if necessary.
// No need to translate a remote call.
if !opt.Remote {
if err := e.translateCalls(ctx, index, idx, q.Calls); err != nil {
return resp, err
} else if err := validateQueryContext(ctx); err != nil {
return resp, err
}
}
results, err := e.execute(ctx, index, q, shards, opt)
if err != nil {
return resp, err
} else if err := validateQueryContext(ctx); err != nil {
return resp, err
}
resp.Results = results
// Fill column attributes if requested.
if opt.ColumnAttrs {
// Consolidate all column ids across all calls.
var columnIDs []uint64
for _, result := range results {
bm, ok := result.(*Row)
if !ok {
continue
}
columnIDs = uint64Slice(columnIDs).merge(bm.Columns())
}
// Retrieve column attributes across all calls.
columnAttrSets, err := e.readColumnAttrSets(e.Holder.Index(index), columnIDs)
if err != nil {
return resp, errors.Wrap(err, "reading column attrs")
}
// Translate column attributes, if necessary.
if idx.Keys() {
for _, col := range columnAttrSets {
v, err := e.Holder.translateFile.TranslateColumnToString(index, col.ID)
if err != nil {
return resp, err
}
col.Key, col.ID = v, 0
}
}
resp.ColumnAttrSets = columnAttrSets
}
// Translate response objects from ids to keys, if necessary.
// No need to translate a remote call.
if !opt.Remote {
if err := e.translateResults(ctx, index, idx, q.Calls, results); err != nil {
return resp, err
} else if err := validateQueryContext(ctx); err != nil {
return resp, err
}
}
return resp, nil
} | [
"func",
"(",
"e",
"*",
"executor",
")",
"Execute",
"(",
"ctx",
"context",
".",
"Context",
",",
"index",
"string",
",",
"q",
"*",
"pql",
".",
"Query",
",",
"shards",
"[",
"]",
"uint64",
",",
"opt",
"*",
"execOptions",
")",
"(",
"QueryResponse",
",",
... | // Execute executes a PQL query. | [
"Execute",
"executes",
"a",
"PQL",
"query",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/executor.go#L85-L178 | train |
pilosa/pilosa | executor.go | readColumnAttrSets | func (e *executor) readColumnAttrSets(index *Index, ids []uint64) ([]*ColumnAttrSet, error) {
if index == nil {
return nil, nil
}
ax := make([]*ColumnAttrSet, 0, len(ids))
for _, id := range ids {
// Read attributes for column. Skip column if empty.
attrs, err := index.ColumnAttrStore().Attrs(id)
if err != nil {
return nil, errors.Wrap(err, "getting attrs")
} else if len(attrs) == 0 {
continue
}
// Append column with attributes.
ax = append(ax, &ColumnAttrSet{ID: id, Attrs: attrs})
}
return ax, nil
} | go | func (e *executor) readColumnAttrSets(index *Index, ids []uint64) ([]*ColumnAttrSet, error) {
if index == nil {
return nil, nil
}
ax := make([]*ColumnAttrSet, 0, len(ids))
for _, id := range ids {
// Read attributes for column. Skip column if empty.
attrs, err := index.ColumnAttrStore().Attrs(id)
if err != nil {
return nil, errors.Wrap(err, "getting attrs")
} else if len(attrs) == 0 {
continue
}
// Append column with attributes.
ax = append(ax, &ColumnAttrSet{ID: id, Attrs: attrs})
}
return ax, nil
} | [
"func",
"(",
"e",
"*",
"executor",
")",
"readColumnAttrSets",
"(",
"index",
"*",
"Index",
",",
"ids",
"[",
"]",
"uint64",
")",
"(",
"[",
"]",
"*",
"ColumnAttrSet",
",",
"error",
")",
"{",
"if",
"index",
"==",
"nil",
"{",
"return",
"nil",
",",
"nil"... | // readColumnAttrSets returns a list of column attribute objects by id. | [
"readColumnAttrSets",
"returns",
"a",
"list",
"of",
"column",
"attribute",
"objects",
"by",
"id",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/executor.go#L181-L201 | train |
pilosa/pilosa | executor.go | validateCallArgs | func (e *executor) validateCallArgs(c *pql.Call) error {
if _, ok := c.Args["ids"]; ok {
switch v := c.Args["ids"].(type) {
case []int64, []uint64:
// noop
case []interface{}:
b := make([]int64, len(v))
for i := range v {
b[i] = v[i].(int64)
}
c.Args["ids"] = b
default:
return fmt.Errorf("invalid call.Args[ids]: %s", v)
}
}
return nil
} | go | func (e *executor) validateCallArgs(c *pql.Call) error {
if _, ok := c.Args["ids"]; ok {
switch v := c.Args["ids"].(type) {
case []int64, []uint64:
// noop
case []interface{}:
b := make([]int64, len(v))
for i := range v {
b[i] = v[i].(int64)
}
c.Args["ids"] = b
default:
return fmt.Errorf("invalid call.Args[ids]: %s", v)
}
}
return nil
} | [
"func",
"(",
"e",
"*",
"executor",
")",
"validateCallArgs",
"(",
"c",
"*",
"pql",
".",
"Call",
")",
"error",
"{",
"if",
"_",
",",
"ok",
":=",
"c",
".",
"Args",
"[",
"\"ids\"",
"]",
";",
"ok",
"{",
"switch",
"v",
":=",
"c",
".",
"Args",
"[",
"... | // validateCallArgs ensures that the value types in call.Args are expected. | [
"validateCallArgs",
"ensures",
"that",
"the",
"value",
"types",
"in",
"call",
".",
"Args",
"are",
"expected",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/executor.go#L300-L316 | train |
pilosa/pilosa | executor.go | executeBitmapCall | func (e *executor) executeBitmapCall(ctx context.Context, index string, c *pql.Call, shards []uint64, opt *execOptions) (*Row, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeBitmapCall")
defer span.Finish()
// Execute calls in bulk on each remote node and merge.
mapFn := func(shard uint64) (interface{}, error) {
return e.executeBitmapCallShard(ctx, index, c, shard)
}
// Merge returned results at coordinating node.
reduceFn := func(prev, v interface{}) interface{} {
other, _ := prev.(*Row)
if other == nil {
other = NewRow()
}
other.Merge(v.(*Row))
return other
}
other, err := e.mapReduce(ctx, index, shards, c, opt, mapFn, reduceFn)
if err != nil {
return nil, errors.Wrap(err, "map reduce")
}
// Attach attributes for non-BSI Row() calls.
// If the column label is used then return column attributes.
// If the row label is used then return bitmap attributes.
row, _ := other.(*Row)
if c.Name == "Row" && !c.HasConditionArg() {
if opt.ExcludeRowAttrs {
row.Attrs = map[string]interface{}{}
} else {
idx := e.Holder.Index(index)
if idx != nil {
if columnID, ok, err := c.UintArg("_" + columnLabel); ok && err == nil {
attrs, err := idx.ColumnAttrStore().Attrs(columnID)
if err != nil {
return nil, errors.Wrap(err, "getting column attrs")
}
row.Attrs = attrs
} else if err != nil {
return nil, err
} else {
// field, _ := c.Args["field"].(string)
fieldName, _ := c.FieldArg()
if fr := idx.Field(fieldName); fr != nil {
rowID, _, err := c.UintArg(fieldName)
if err != nil {
return nil, errors.Wrap(err, "getting row")
}
attrs, err := fr.RowAttrStore().Attrs(rowID)
if err != nil {
return nil, errors.Wrap(err, "getting row attrs")
}
row.Attrs = attrs
}
}
}
}
}
if opt.ExcludeColumns {
row.segments = []rowSegment{}
}
return row, nil
} | go | func (e *executor) executeBitmapCall(ctx context.Context, index string, c *pql.Call, shards []uint64, opt *execOptions) (*Row, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeBitmapCall")
defer span.Finish()
// Execute calls in bulk on each remote node and merge.
mapFn := func(shard uint64) (interface{}, error) {
return e.executeBitmapCallShard(ctx, index, c, shard)
}
// Merge returned results at coordinating node.
reduceFn := func(prev, v interface{}) interface{} {
other, _ := prev.(*Row)
if other == nil {
other = NewRow()
}
other.Merge(v.(*Row))
return other
}
other, err := e.mapReduce(ctx, index, shards, c, opt, mapFn, reduceFn)
if err != nil {
return nil, errors.Wrap(err, "map reduce")
}
// Attach attributes for non-BSI Row() calls.
// If the column label is used then return column attributes.
// If the row label is used then return bitmap attributes.
row, _ := other.(*Row)
if c.Name == "Row" && !c.HasConditionArg() {
if opt.ExcludeRowAttrs {
row.Attrs = map[string]interface{}{}
} else {
idx := e.Holder.Index(index)
if idx != nil {
if columnID, ok, err := c.UintArg("_" + columnLabel); ok && err == nil {
attrs, err := idx.ColumnAttrStore().Attrs(columnID)
if err != nil {
return nil, errors.Wrap(err, "getting column attrs")
}
row.Attrs = attrs
} else if err != nil {
return nil, err
} else {
// field, _ := c.Args["field"].(string)
fieldName, _ := c.FieldArg()
if fr := idx.Field(fieldName); fr != nil {
rowID, _, err := c.UintArg(fieldName)
if err != nil {
return nil, errors.Wrap(err, "getting row")
}
attrs, err := fr.RowAttrStore().Attrs(rowID)
if err != nil {
return nil, errors.Wrap(err, "getting row attrs")
}
row.Attrs = attrs
}
}
}
}
}
if opt.ExcludeColumns {
row.segments = []rowSegment{}
}
return row, nil
} | [
"func",
"(",
"e",
"*",
"executor",
")",
"executeBitmapCall",
"(",
"ctx",
"context",
".",
"Context",
",",
"index",
"string",
",",
"c",
"*",
"pql",
".",
"Call",
",",
"shards",
"[",
"]",
"uint64",
",",
"opt",
"*",
"execOptions",
")",
"(",
"*",
"Row",
... | // executeBitmapCall executes a call that returns a bitmap. | [
"executeBitmapCall",
"executes",
"a",
"call",
"that",
"returns",
"a",
"bitmap",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/executor.go#L472-L538 | train |
pilosa/pilosa | executor.go | executeBitmapCallShard | func (e *executor) executeBitmapCallShard(ctx context.Context, index string, c *pql.Call, shard uint64) (*Row, error) {
if err := validateQueryContext(ctx); err != nil {
return nil, err
}
span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeBitmapCallShard")
defer span.Finish()
switch c.Name {
case "Row", "Range":
return e.executeRowShard(ctx, index, c, shard)
case "Difference":
return e.executeDifferenceShard(ctx, index, c, shard)
case "Intersect":
return e.executeIntersectShard(ctx, index, c, shard)
case "Union":
return e.executeUnionShard(ctx, index, c, shard)
case "Xor":
return e.executeXorShard(ctx, index, c, shard)
case "Not":
return e.executeNotShard(ctx, index, c, shard)
case "Shift":
return e.executeShiftShard(ctx, index, c, shard)
default:
return nil, fmt.Errorf("unknown call: %s", c.Name)
}
} | go | func (e *executor) executeBitmapCallShard(ctx context.Context, index string, c *pql.Call, shard uint64) (*Row, error) {
if err := validateQueryContext(ctx); err != nil {
return nil, err
}
span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeBitmapCallShard")
defer span.Finish()
switch c.Name {
case "Row", "Range":
return e.executeRowShard(ctx, index, c, shard)
case "Difference":
return e.executeDifferenceShard(ctx, index, c, shard)
case "Intersect":
return e.executeIntersectShard(ctx, index, c, shard)
case "Union":
return e.executeUnionShard(ctx, index, c, shard)
case "Xor":
return e.executeXorShard(ctx, index, c, shard)
case "Not":
return e.executeNotShard(ctx, index, c, shard)
case "Shift":
return e.executeShiftShard(ctx, index, c, shard)
default:
return nil, fmt.Errorf("unknown call: %s", c.Name)
}
} | [
"func",
"(",
"e",
"*",
"executor",
")",
"executeBitmapCallShard",
"(",
"ctx",
"context",
".",
"Context",
",",
"index",
"string",
",",
"c",
"*",
"pql",
".",
"Call",
",",
"shard",
"uint64",
")",
"(",
"*",
"Row",
",",
"error",
")",
"{",
"if",
"err",
"... | // executeBitmapCallShard executes a bitmap call for a single shard. | [
"executeBitmapCallShard",
"executes",
"a",
"bitmap",
"call",
"for",
"a",
"single",
"shard",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/executor.go#L541-L567 | train |
pilosa/pilosa | executor.go | executeSumCountShard | func (e *executor) executeSumCountShard(ctx context.Context, index string, c *pql.Call, shard uint64) (ValCount, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeSumCountShard")
defer span.Finish()
var filter *Row
if len(c.Children) == 1 {
row, err := e.executeBitmapCallShard(ctx, index, c.Children[0], shard)
if err != nil {
return ValCount{}, errors.Wrap(err, "executing bitmap call")
}
filter = row
}
fieldName, _ := c.Args["field"].(string)
field := e.Holder.Field(index, fieldName)
if field == nil {
return ValCount{}, nil
}
bsig := field.bsiGroup(fieldName)
if bsig == nil {
return ValCount{}, nil
}
fragment := e.Holder.fragment(index, fieldName, viewBSIGroupPrefix+fieldName, shard)
if fragment == nil {
return ValCount{}, nil
}
vsum, vcount, err := fragment.sum(filter, bsig.BitDepth())
if err != nil {
return ValCount{}, errors.Wrap(err, "computing sum")
}
return ValCount{
Val: int64(vsum) + (int64(vcount) * bsig.Min),
Count: int64(vcount),
}, nil
} | go | func (e *executor) executeSumCountShard(ctx context.Context, index string, c *pql.Call, shard uint64) (ValCount, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeSumCountShard")
defer span.Finish()
var filter *Row
if len(c.Children) == 1 {
row, err := e.executeBitmapCallShard(ctx, index, c.Children[0], shard)
if err != nil {
return ValCount{}, errors.Wrap(err, "executing bitmap call")
}
filter = row
}
fieldName, _ := c.Args["field"].(string)
field := e.Holder.Field(index, fieldName)
if field == nil {
return ValCount{}, nil
}
bsig := field.bsiGroup(fieldName)
if bsig == nil {
return ValCount{}, nil
}
fragment := e.Holder.fragment(index, fieldName, viewBSIGroupPrefix+fieldName, shard)
if fragment == nil {
return ValCount{}, nil
}
vsum, vcount, err := fragment.sum(filter, bsig.BitDepth())
if err != nil {
return ValCount{}, errors.Wrap(err, "computing sum")
}
return ValCount{
Val: int64(vsum) + (int64(vcount) * bsig.Min),
Count: int64(vcount),
}, nil
} | [
"func",
"(",
"e",
"*",
"executor",
")",
"executeSumCountShard",
"(",
"ctx",
"context",
".",
"Context",
",",
"index",
"string",
",",
"c",
"*",
"pql",
".",
"Call",
",",
"shard",
"uint64",
")",
"(",
"ValCount",
",",
"error",
")",
"{",
"span",
",",
"ctx"... | // executeSumCountShard calculates the sum and count for bsiGroups on a shard. | [
"executeSumCountShard",
"calculates",
"the",
"sum",
"and",
"count",
"for",
"bsiGroups",
"on",
"a",
"shard",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/executor.go#L570-L608 | train |
pilosa/pilosa | executor.go | executeTopNShard | func (e *executor) executeTopNShard(ctx context.Context, index string, c *pql.Call, shard uint64) ([]Pair, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeTopNShard")
defer span.Finish()
field, _ := c.Args["_field"].(string)
n, _, err := c.UintArg("n")
if err != nil {
return nil, fmt.Errorf("executeTopNShard: %v", err)
}
attrName, _ := c.Args["attrName"].(string)
rowIDs, _, err := c.UintSliceArg("ids")
if err != nil {
return nil, fmt.Errorf("executeTopNShard: %v", err)
}
minThreshold, _, err := c.UintArg("threshold")
if err != nil {
return nil, fmt.Errorf("executeTopNShard: %v", err)
}
attrValues, _ := c.Args["attrValues"].([]interface{})
tanimotoThreshold, _, err := c.UintArg("tanimotoThreshold")
if err != nil {
return nil, fmt.Errorf("executeTopNShard: %v", err)
}
// Retrieve bitmap used to intersect.
var src *Row
if len(c.Children) == 1 {
row, err := e.executeBitmapCallShard(ctx, index, c.Children[0], shard)
if err != nil {
return nil, err
}
src = row
} else if len(c.Children) > 1 {
return nil, errors.New("TopN() can only have one input bitmap")
}
// Set default field.
if field == "" {
field = defaultField
}
f := e.Holder.fragment(index, field, viewStandard, shard)
if f == nil {
return nil, nil
}
if minThreshold == 0 {
minThreshold = defaultMinThreshold
}
if tanimotoThreshold > 100 {
return nil, errors.New("Tanimoto Threshold is from 1 to 100 only")
}
return f.top(topOptions{
N: int(n),
Src: src,
RowIDs: rowIDs,
FilterName: attrName,
FilterValues: attrValues,
MinThreshold: minThreshold,
TanimotoThreshold: tanimotoThreshold,
})
} | go | func (e *executor) executeTopNShard(ctx context.Context, index string, c *pql.Call, shard uint64) ([]Pair, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeTopNShard")
defer span.Finish()
field, _ := c.Args["_field"].(string)
n, _, err := c.UintArg("n")
if err != nil {
return nil, fmt.Errorf("executeTopNShard: %v", err)
}
attrName, _ := c.Args["attrName"].(string)
rowIDs, _, err := c.UintSliceArg("ids")
if err != nil {
return nil, fmt.Errorf("executeTopNShard: %v", err)
}
minThreshold, _, err := c.UintArg("threshold")
if err != nil {
return nil, fmt.Errorf("executeTopNShard: %v", err)
}
attrValues, _ := c.Args["attrValues"].([]interface{})
tanimotoThreshold, _, err := c.UintArg("tanimotoThreshold")
if err != nil {
return nil, fmt.Errorf("executeTopNShard: %v", err)
}
// Retrieve bitmap used to intersect.
var src *Row
if len(c.Children) == 1 {
row, err := e.executeBitmapCallShard(ctx, index, c.Children[0], shard)
if err != nil {
return nil, err
}
src = row
} else if len(c.Children) > 1 {
return nil, errors.New("TopN() can only have one input bitmap")
}
// Set default field.
if field == "" {
field = defaultField
}
f := e.Holder.fragment(index, field, viewStandard, shard)
if f == nil {
return nil, nil
}
if minThreshold == 0 {
minThreshold = defaultMinThreshold
}
if tanimotoThreshold > 100 {
return nil, errors.New("Tanimoto Threshold is from 1 to 100 only")
}
return f.top(topOptions{
N: int(n),
Src: src,
RowIDs: rowIDs,
FilterName: attrName,
FilterValues: attrValues,
MinThreshold: minThreshold,
TanimotoThreshold: tanimotoThreshold,
})
} | [
"func",
"(",
"e",
"*",
"executor",
")",
"executeTopNShard",
"(",
"ctx",
"context",
".",
"Context",
",",
"index",
"string",
",",
"c",
"*",
"pql",
".",
"Call",
",",
"shard",
"uint64",
")",
"(",
"[",
"]",
"Pair",
",",
"error",
")",
"{",
"span",
",",
... | // executeTopNShard executes a TopN call for a single shard. | [
"executeTopNShard",
"executes",
"a",
"TopN",
"call",
"for",
"a",
"single",
"shard",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/executor.go#L765-L827 | train |
pilosa/pilosa | executor.go | MarshalJSON | func (fr FieldRow) MarshalJSON() ([]byte, error) {
if fr.RowKey != "" {
return json.Marshal(struct {
Field string `json:"field"`
RowKey string `json:"rowKey"`
}{
Field: fr.Field,
RowKey: fr.RowKey,
})
}
return json.Marshal(struct {
Field string `json:"field"`
RowID uint64 `json:"rowID"`
}{
Field: fr.Field,
RowID: fr.RowID,
})
} | go | func (fr FieldRow) MarshalJSON() ([]byte, error) {
if fr.RowKey != "" {
return json.Marshal(struct {
Field string `json:"field"`
RowKey string `json:"rowKey"`
}{
Field: fr.Field,
RowKey: fr.RowKey,
})
}
return json.Marshal(struct {
Field string `json:"field"`
RowID uint64 `json:"rowID"`
}{
Field: fr.Field,
RowID: fr.RowID,
})
} | [
"func",
"(",
"fr",
"FieldRow",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"fr",
".",
"RowKey",
"!=",
"\"\"",
"{",
"return",
"json",
".",
"Marshal",
"(",
"struct",
"{",
"Field",
"string",
"`json:\"field\"`",
"\n... | // MarshalJSON marshals FieldRow to JSON such that
// either a Key or an ID is included. | [
"MarshalJSON",
"marshals",
"FieldRow",
"to",
"JSON",
"such",
"that",
"either",
"a",
"Key",
"or",
"an",
"ID",
"is",
"included",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/executor.go#L992-L1009 | train |
pilosa/pilosa | executor.go | String | func (fr FieldRow) String() string {
return fmt.Sprintf("%s.%d.%s", fr.Field, fr.RowID, fr.RowKey)
} | go | func (fr FieldRow) String() string {
return fmt.Sprintf("%s.%d.%s", fr.Field, fr.RowID, fr.RowKey)
} | [
"func",
"(",
"fr",
"FieldRow",
")",
"String",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"%s.%d.%s\"",
",",
"fr",
".",
"Field",
",",
"fr",
".",
"RowID",
",",
"fr",
".",
"RowKey",
")",
"\n",
"}"
] | // String is the FieldRow stringer. | [
"String",
"is",
"the",
"FieldRow",
"stringer",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/executor.go#L1012-L1014 | train |
pilosa/pilosa | executor.go | mergeGroupCounts | func mergeGroupCounts(a, b []GroupCount, limit int) []GroupCount {
if limit > len(a)+len(b) {
limit = len(a) + len(b)
}
ret := make([]GroupCount, 0, limit)
i, j := 0, 0
for i < len(a) && j < len(b) && len(ret) < limit {
switch a[i].Compare(b[j]) {
case -1:
ret = append(ret, a[i])
i++
case 0:
a[i].Count += b[j].Count
ret = append(ret, a[i])
i++
j++
case 1:
ret = append(ret, b[j])
j++
}
}
for ; i < len(a) && len(ret) < limit; i++ {
ret = append(ret, a[i])
}
for ; j < len(b) && len(ret) < limit; j++ {
ret = append(ret, b[j])
}
return ret
} | go | func mergeGroupCounts(a, b []GroupCount, limit int) []GroupCount {
if limit > len(a)+len(b) {
limit = len(a) + len(b)
}
ret := make([]GroupCount, 0, limit)
i, j := 0, 0
for i < len(a) && j < len(b) && len(ret) < limit {
switch a[i].Compare(b[j]) {
case -1:
ret = append(ret, a[i])
i++
case 0:
a[i].Count += b[j].Count
ret = append(ret, a[i])
i++
j++
case 1:
ret = append(ret, b[j])
j++
}
}
for ; i < len(a) && len(ret) < limit; i++ {
ret = append(ret, a[i])
}
for ; j < len(b) && len(ret) < limit; j++ {
ret = append(ret, b[j])
}
return ret
} | [
"func",
"mergeGroupCounts",
"(",
"a",
",",
"b",
"[",
"]",
"GroupCount",
",",
"limit",
"int",
")",
"[",
"]",
"GroupCount",
"{",
"if",
"limit",
">",
"len",
"(",
"a",
")",
"+",
"len",
"(",
"b",
")",
"{",
"limit",
"=",
"len",
"(",
"a",
")",
"+",
... | // mergeGroupCounts merges two slices of GroupCounts throwing away any that go
// beyond the limit. It assume that the two slices are sorted by the row ids in
// the fields of the group counts. It may modify its arguments. | [
"mergeGroupCounts",
"merges",
"two",
"slices",
"of",
"GroupCounts",
"throwing",
"away",
"any",
"that",
"go",
"beyond",
"the",
"limit",
".",
"It",
"assume",
"that",
"the",
"two",
"slices",
"are",
"sorted",
"by",
"the",
"row",
"ids",
"in",
"the",
"fields",
"... | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/executor.go#L1025-L1053 | train |
pilosa/pilosa | executor.go | Compare | func (g GroupCount) Compare(o GroupCount) int {
for i := range g.Group {
if g.Group[i].RowID < o.Group[i].RowID {
return -1
}
if g.Group[i].RowID > o.Group[i].RowID {
return 1
}
}
return 0
} | go | func (g GroupCount) Compare(o GroupCount) int {
for i := range g.Group {
if g.Group[i].RowID < o.Group[i].RowID {
return -1
}
if g.Group[i].RowID > o.Group[i].RowID {
return 1
}
}
return 0
} | [
"func",
"(",
"g",
"GroupCount",
")",
"Compare",
"(",
"o",
"GroupCount",
")",
"int",
"{",
"for",
"i",
":=",
"range",
"g",
".",
"Group",
"{",
"if",
"g",
".",
"Group",
"[",
"i",
"]",
".",
"RowID",
"<",
"o",
".",
"Group",
"[",
"i",
"]",
".",
"Row... | // Compare is used in ordering two GroupCount objects. | [
"Compare",
"is",
"used",
"in",
"ordering",
"two",
"GroupCount",
"objects",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/executor.go#L1056-L1066 | train |
pilosa/pilosa | executor.go | remoteExec | func (e *executor) remoteExec(ctx context.Context, node *Node, index string, q *pql.Query, shards []uint64) (results []interface{}, err error) { // nolint: interfacer
span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeExec")
defer span.Finish()
// Encode request object.
pbreq := &QueryRequest{
Query: q.String(),
Shards: shards,
Remote: true,
}
pb, err := e.client.QueryNode(ctx, &node.URI, index, pbreq)
if err != nil {
return nil, err
}
return pb.Results, pb.Err
} | go | func (e *executor) remoteExec(ctx context.Context, node *Node, index string, q *pql.Query, shards []uint64) (results []interface{}, err error) { // nolint: interfacer
span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeExec")
defer span.Finish()
// Encode request object.
pbreq := &QueryRequest{
Query: q.String(),
Shards: shards,
Remote: true,
}
pb, err := e.client.QueryNode(ctx, &node.URI, index, pbreq)
if err != nil {
return nil, err
}
return pb.Results, pb.Err
} | [
"func",
"(",
"e",
"*",
"executor",
")",
"remoteExec",
"(",
"ctx",
"context",
".",
"Context",
",",
"node",
"*",
"Node",
",",
"index",
"string",
",",
"q",
"*",
"pql",
".",
"Query",
",",
"shards",
"[",
"]",
"uint64",
")",
"(",
"results",
"[",
"]",
"... | // remoteExec executes a PQL query remotely for a set of shards on a node. | [
"remoteExec",
"executes",
"a",
"PQL",
"query",
"remotely",
"for",
"a",
"set",
"of",
"shards",
"on",
"a",
"node",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/executor.go#L2242-L2259 | train |
pilosa/pilosa | executor.go | shardsByNode | func (e *executor) shardsByNode(nodes []*Node, index string, shards []uint64) (map[*Node][]uint64, error) {
m := make(map[*Node][]uint64)
loop:
for _, shard := range shards {
for _, node := range e.Cluster.ShardNodes(index, shard) {
if Nodes(nodes).Contains(node) {
m[node] = append(m[node], shard)
continue loop
}
}
return nil, errShardUnavailable
}
return m, nil
} | go | func (e *executor) shardsByNode(nodes []*Node, index string, shards []uint64) (map[*Node][]uint64, error) {
m := make(map[*Node][]uint64)
loop:
for _, shard := range shards {
for _, node := range e.Cluster.ShardNodes(index, shard) {
if Nodes(nodes).Contains(node) {
m[node] = append(m[node], shard)
continue loop
}
}
return nil, errShardUnavailable
}
return m, nil
} | [
"func",
"(",
"e",
"*",
"executor",
")",
"shardsByNode",
"(",
"nodes",
"[",
"]",
"*",
"Node",
",",
"index",
"string",
",",
"shards",
"[",
"]",
"uint64",
")",
"(",
"map",
"[",
"*",
"Node",
"]",
"[",
"]",
"uint64",
",",
"error",
")",
"{",
"m",
":=... | // shardsByNode returns a mapping of nodes to shards.
// Returns errShardUnavailable if a shard cannot be allocated to a node. | [
"shardsByNode",
"returns",
"a",
"mapping",
"of",
"nodes",
"to",
"shards",
".",
"Returns",
"errShardUnavailable",
"if",
"a",
"shard",
"cannot",
"be",
"allocated",
"to",
"a",
"node",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/executor.go#L2263-L2277 | train |
pilosa/pilosa | executor.go | mapReduce | func (e *executor) mapReduce(ctx context.Context, index string, shards []uint64, c *pql.Call, opt *execOptions, mapFn mapFunc, reduceFn reduceFunc) (interface{}, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "Executor.mapReduce")
defer span.Finish()
ch := make(chan mapResponse)
// Wrap context with a cancel to kill goroutines on exit.
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// If this is the coordinating node then start with all nodes in the cluster.
//
// However, if this request is being sent from the coordinator then all
// processing should be done locally so we start with just the local node.
var nodes []*Node
if !opt.Remote {
nodes = Nodes(e.Cluster.nodes).Clone()
} else {
nodes = []*Node{e.Cluster.nodeByID(e.Node.ID)}
}
// Start mapping across all primary owners.
if err := e.mapper(ctx, ch, nodes, index, shards, c, opt, mapFn, reduceFn); err != nil {
return nil, errors.Wrap(err, "starting mapper")
}
// Iterate over all map responses and reduce.
var result interface{}
var shardN int
for {
select {
case <-ctx.Done():
return nil, errors.Wrap(ctx.Err(), "context done")
case resp := <-ch:
// On error retry against remaining nodes. If an error returns then
// the context will cancel and cause all open goroutines to return.
if resp.err != nil {
// Filter out unavailable nodes.
nodes = Nodes(nodes).Filter(resp.node)
// Begin mapper against secondary nodes.
if err := e.mapper(ctx, ch, nodes, index, resp.shards, c, opt, mapFn, reduceFn); errors.Cause(err) == errShardUnavailable {
return nil, resp.err
} else if err != nil {
return nil, errors.Wrap(err, "calling mapper")
}
continue
}
// Reduce value.
result = reduceFn(result, resp.result)
// If all shards have been processed then return.
shardN += len(resp.shards)
if shardN >= len(shards) {
return result, nil
}
}
}
} | go | func (e *executor) mapReduce(ctx context.Context, index string, shards []uint64, c *pql.Call, opt *execOptions, mapFn mapFunc, reduceFn reduceFunc) (interface{}, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "Executor.mapReduce")
defer span.Finish()
ch := make(chan mapResponse)
// Wrap context with a cancel to kill goroutines on exit.
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// If this is the coordinating node then start with all nodes in the cluster.
//
// However, if this request is being sent from the coordinator then all
// processing should be done locally so we start with just the local node.
var nodes []*Node
if !opt.Remote {
nodes = Nodes(e.Cluster.nodes).Clone()
} else {
nodes = []*Node{e.Cluster.nodeByID(e.Node.ID)}
}
// Start mapping across all primary owners.
if err := e.mapper(ctx, ch, nodes, index, shards, c, opt, mapFn, reduceFn); err != nil {
return nil, errors.Wrap(err, "starting mapper")
}
// Iterate over all map responses and reduce.
var result interface{}
var shardN int
for {
select {
case <-ctx.Done():
return nil, errors.Wrap(ctx.Err(), "context done")
case resp := <-ch:
// On error retry against remaining nodes. If an error returns then
// the context will cancel and cause all open goroutines to return.
if resp.err != nil {
// Filter out unavailable nodes.
nodes = Nodes(nodes).Filter(resp.node)
// Begin mapper against secondary nodes.
if err := e.mapper(ctx, ch, nodes, index, resp.shards, c, opt, mapFn, reduceFn); errors.Cause(err) == errShardUnavailable {
return nil, resp.err
} else if err != nil {
return nil, errors.Wrap(err, "calling mapper")
}
continue
}
// Reduce value.
result = reduceFn(result, resp.result)
// If all shards have been processed then return.
shardN += len(resp.shards)
if shardN >= len(shards) {
return result, nil
}
}
}
} | [
"func",
"(",
"e",
"*",
"executor",
")",
"mapReduce",
"(",
"ctx",
"context",
".",
"Context",
",",
"index",
"string",
",",
"shards",
"[",
"]",
"uint64",
",",
"c",
"*",
"pql",
".",
"Call",
",",
"opt",
"*",
"execOptions",
",",
"mapFn",
"mapFunc",
",",
... | // mapReduce maps and reduces data across the cluster.
//
// If a mapping of shards to a node fails then the shards are resplit across
// secondary nodes and retried. This continues to occur until all nodes are exhausted. | [
"mapReduce",
"maps",
"and",
"reduces",
"data",
"across",
"the",
"cluster",
".",
"If",
"a",
"mapping",
"of",
"shards",
"to",
"a",
"node",
"fails",
"then",
"the",
"shards",
"are",
"resplit",
"across",
"secondary",
"nodes",
"and",
"retried",
".",
"This",
"con... | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/executor.go#L2283-L2343 | train |
pilosa/pilosa | executor.go | mapperLocal | func (e *executor) mapperLocal(ctx context.Context, shards []uint64, mapFn mapFunc, reduceFn reduceFunc) (interface{}, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "Executor.mapperLocal")
defer span.Finish()
ch := make(chan mapResponse, len(shards))
for _, shard := range shards {
go func(shard uint64) {
result, err := mapFn(shard)
// Return response to the channel.
select {
case <-ctx.Done():
case ch <- mapResponse{result: result, err: err}:
}
}(shard)
}
// Reduce results
var maxShard int
var result interface{}
for {
select {
case <-ctx.Done():
return nil, ctx.Err()
case resp := <-ch:
if resp.err != nil {
return nil, resp.err
}
result = reduceFn(result, resp.result)
maxShard++
}
// Exit once all shards are processed.
if maxShard == len(shards) {
return result, nil
}
}
} | go | func (e *executor) mapperLocal(ctx context.Context, shards []uint64, mapFn mapFunc, reduceFn reduceFunc) (interface{}, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "Executor.mapperLocal")
defer span.Finish()
ch := make(chan mapResponse, len(shards))
for _, shard := range shards {
go func(shard uint64) {
result, err := mapFn(shard)
// Return response to the channel.
select {
case <-ctx.Done():
case ch <- mapResponse{result: result, err: err}:
}
}(shard)
}
// Reduce results
var maxShard int
var result interface{}
for {
select {
case <-ctx.Done():
return nil, ctx.Err()
case resp := <-ch:
if resp.err != nil {
return nil, resp.err
}
result = reduceFn(result, resp.result)
maxShard++
}
// Exit once all shards are processed.
if maxShard == len(shards) {
return result, nil
}
}
} | [
"func",
"(",
"e",
"*",
"executor",
")",
"mapperLocal",
"(",
"ctx",
"context",
".",
"Context",
",",
"shards",
"[",
"]",
"uint64",
",",
"mapFn",
"mapFunc",
",",
"reduceFn",
"reduceFunc",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"span",
... | // mapperLocal performs map & reduce entirely on the local node. | [
"mapperLocal",
"performs",
"map",
"&",
"reduce",
"entirely",
"on",
"the",
"local",
"node",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/executor.go#L2383-L2421 | train |
pilosa/pilosa | executor.go | validateQueryContext | func validateQueryContext(ctx context.Context) error {
select {
case <-ctx.Done():
switch err := ctx.Err(); err {
case context.Canceled:
return ErrQueryCancelled
case context.DeadlineExceeded:
return ErrQueryTimeout
default:
return err
}
default:
return nil
}
} | go | func validateQueryContext(ctx context.Context) error {
select {
case <-ctx.Done():
switch err := ctx.Err(); err {
case context.Canceled:
return ErrQueryCancelled
case context.DeadlineExceeded:
return ErrQueryTimeout
default:
return err
}
default:
return nil
}
} | [
"func",
"validateQueryContext",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"select",
"{",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"switch",
"err",
":=",
"ctx",
".",
"Err",
"(",
")",
";",
"err",
"{",
"case",
"context",
".",
"... | // validateQueryContext returns a query-appropriate error if the context is done. | [
"validateQueryContext",
"returns",
"a",
"query",
"-",
"appropriate",
"error",
"if",
"the",
"context",
"is",
"done",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/executor.go#L2691-L2705 | train |
pilosa/pilosa | executor.go | smaller | func (vc *ValCount) smaller(other ValCount) ValCount {
if vc.Count == 0 || (other.Val < vc.Val && other.Count > 0) {
return other
}
return ValCount{
Val: vc.Val,
Count: vc.Count,
}
} | go | func (vc *ValCount) smaller(other ValCount) ValCount {
if vc.Count == 0 || (other.Val < vc.Val && other.Count > 0) {
return other
}
return ValCount{
Val: vc.Val,
Count: vc.Count,
}
} | [
"func",
"(",
"vc",
"*",
"ValCount",
")",
"smaller",
"(",
"other",
"ValCount",
")",
"ValCount",
"{",
"if",
"vc",
".",
"Count",
"==",
"0",
"||",
"(",
"other",
".",
"Val",
"<",
"vc",
".",
"Val",
"&&",
"other",
".",
"Count",
">",
"0",
")",
"{",
"re... | // smaller returns the smaller of the two ValCounts. | [
"smaller",
"returns",
"the",
"smaller",
"of",
"the",
"two",
"ValCounts",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/executor.go#L2776-L2784 | train |
pilosa/pilosa | executor.go | larger | func (vc *ValCount) larger(other ValCount) ValCount {
if vc.Count == 0 || (other.Val > vc.Val && other.Count > 0) {
return other
}
return ValCount{
Val: vc.Val,
Count: vc.Count,
}
} | go | func (vc *ValCount) larger(other ValCount) ValCount {
if vc.Count == 0 || (other.Val > vc.Val && other.Count > 0) {
return other
}
return ValCount{
Val: vc.Val,
Count: vc.Count,
}
} | [
"func",
"(",
"vc",
"*",
"ValCount",
")",
"larger",
"(",
"other",
"ValCount",
")",
"ValCount",
"{",
"if",
"vc",
".",
"Count",
"==",
"0",
"||",
"(",
"other",
".",
"Val",
">",
"vc",
".",
"Val",
"&&",
"other",
".",
"Count",
">",
"0",
")",
"{",
"ret... | // larger returns the larger of the two ValCounts. | [
"larger",
"returns",
"the",
"larger",
"of",
"the",
"two",
"ValCounts",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/executor.go#L2787-L2795 | train |
pilosa/pilosa | executor.go | nextAtIdx | func (gbi *groupByIterator) nextAtIdx(i int) {
// loop until we find a non-empty row. This is an optimization - the loop and if/break can be removed.
for {
nr, rowID, wrapped := gbi.rowIters[i].Next()
if nr == nil {
gbi.done = true
return
}
if wrapped && i != 0 {
gbi.nextAtIdx(i - 1)
}
if i == 0 && gbi.filter != nil {
gbi.rows[i].row = nr.Intersect(gbi.filter)
} else if i == 0 || i == len(gbi.rows)-1 {
gbi.rows[i].row = nr
} else {
gbi.rows[i].row = nr.Intersect(gbi.rows[i-1].row)
}
gbi.rows[i].id = rowID
if !gbi.rows[i].row.IsEmpty() {
break
}
}
} | go | func (gbi *groupByIterator) nextAtIdx(i int) {
// loop until we find a non-empty row. This is an optimization - the loop and if/break can be removed.
for {
nr, rowID, wrapped := gbi.rowIters[i].Next()
if nr == nil {
gbi.done = true
return
}
if wrapped && i != 0 {
gbi.nextAtIdx(i - 1)
}
if i == 0 && gbi.filter != nil {
gbi.rows[i].row = nr.Intersect(gbi.filter)
} else if i == 0 || i == len(gbi.rows)-1 {
gbi.rows[i].row = nr
} else {
gbi.rows[i].row = nr.Intersect(gbi.rows[i-1].row)
}
gbi.rows[i].id = rowID
if !gbi.rows[i].row.IsEmpty() {
break
}
}
} | [
"func",
"(",
"gbi",
"*",
"groupByIterator",
")",
"nextAtIdx",
"(",
"i",
"int",
")",
"{",
"for",
"{",
"nr",
",",
"rowID",
",",
"wrapped",
":=",
"gbi",
".",
"rowIters",
"[",
"i",
"]",
".",
"Next",
"(",
")",
"\n",
"if",
"nr",
"==",
"nil",
"{",
"gb... | // nextAtIdx is a recursive helper method for getting the next row for the field
// at index i, and then updating the rows in the "higher" fields if it wraps. | [
"nextAtIdx",
"is",
"a",
"recursive",
"helper",
"method",
"for",
"getting",
"the",
"next",
"row",
"for",
"the",
"field",
"at",
"index",
"i",
"and",
"then",
"updating",
"the",
"rows",
"in",
"the",
"higher",
"fields",
"if",
"it",
"wraps",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/executor.go#L2939-L2963 | train |
pilosa/pilosa | executor.go | Next | func (gbi *groupByIterator) Next() (ret GroupCount, done bool) {
// loop until we find a result with count > 0
for {
if gbi.done {
return ret, true
}
if len(gbi.rows) == 1 {
ret.Count = gbi.rows[len(gbi.rows)-1].row.Count()
} else {
ret.Count = gbi.rows[len(gbi.rows)-1].row.intersectionCount(gbi.rows[len(gbi.rows)-2].row)
}
if ret.Count == 0 {
gbi.nextAtIdx(len(gbi.rows) - 1)
continue
}
break
}
ret.Group = make([]FieldRow, len(gbi.rows))
copy(ret.Group, gbi.fields)
for i, r := range gbi.rows {
ret.Group[i].RowID = r.id
}
// set up for next call
gbi.nextAtIdx(len(gbi.rows) - 1)
return ret, false
} | go | func (gbi *groupByIterator) Next() (ret GroupCount, done bool) {
// loop until we find a result with count > 0
for {
if gbi.done {
return ret, true
}
if len(gbi.rows) == 1 {
ret.Count = gbi.rows[len(gbi.rows)-1].row.Count()
} else {
ret.Count = gbi.rows[len(gbi.rows)-1].row.intersectionCount(gbi.rows[len(gbi.rows)-2].row)
}
if ret.Count == 0 {
gbi.nextAtIdx(len(gbi.rows) - 1)
continue
}
break
}
ret.Group = make([]FieldRow, len(gbi.rows))
copy(ret.Group, gbi.fields)
for i, r := range gbi.rows {
ret.Group[i].RowID = r.id
}
// set up for next call
gbi.nextAtIdx(len(gbi.rows) - 1)
return ret, false
} | [
"func",
"(",
"gbi",
"*",
"groupByIterator",
")",
"Next",
"(",
")",
"(",
"ret",
"GroupCount",
",",
"done",
"bool",
")",
"{",
"for",
"{",
"if",
"gbi",
".",
"done",
"{",
"return",
"ret",
",",
"true",
"\n",
"}",
"\n",
"if",
"len",
"(",
"gbi",
".",
... | // Next returns a GroupCount representing the next group by record. When there
// are no more records it will return an empty GroupCount and done==true. | [
"Next",
"returns",
"a",
"GroupCount",
"representing",
"the",
"next",
"group",
"by",
"record",
".",
"When",
"there",
"are",
"no",
"more",
"records",
"it",
"will",
"return",
"an",
"empty",
"GroupCount",
"and",
"done",
"==",
"true",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/executor.go#L2967-L2996 | train |
pilosa/pilosa | diagnostics.go | SetVersion | func (d *diagnosticsCollector) SetVersion(v string) {
d.version = v
d.Set("Version", v)
} | go | func (d *diagnosticsCollector) SetVersion(v string) {
d.version = v
d.Set("Version", v)
} | [
"func",
"(",
"d",
"*",
"diagnosticsCollector",
")",
"SetVersion",
"(",
"v",
"string",
")",
"{",
"d",
".",
"version",
"=",
"v",
"\n",
"d",
".",
"Set",
"(",
"\"Version\"",
",",
"v",
")",
"\n",
"}"
] | // SetVersion of locally running Pilosa Cluster to check against master. | [
"SetVersion",
"of",
"locally",
"running",
"Pilosa",
"Cluster",
"to",
"check",
"against",
"master",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/diagnostics.go#L74-L77 | train |
pilosa/pilosa | diagnostics.go | Flush | func (d *diagnosticsCollector) Flush() error {
d.mu.Lock()
defer d.mu.Unlock()
d.metrics["Uptime"] = (time.Now().Unix() - d.startTime)
buf, err := d.encode()
if err != nil {
return errors.Wrap(err, "encoding")
}
req, err := http.NewRequest("POST", d.host, bytes.NewReader(buf))
if err != nil {
return errors.Wrap(err, "making new request")
}
req.Header.Set("Content-Type", "application/json")
resp, err := d.client.Do(req)
if err != nil {
return errors.Wrap(err, "posting")
}
// Intentionally ignoring response body, as user does not need to be notified of error.
defer resp.Body.Close()
return nil
} | go | func (d *diagnosticsCollector) Flush() error {
d.mu.Lock()
defer d.mu.Unlock()
d.metrics["Uptime"] = (time.Now().Unix() - d.startTime)
buf, err := d.encode()
if err != nil {
return errors.Wrap(err, "encoding")
}
req, err := http.NewRequest("POST", d.host, bytes.NewReader(buf))
if err != nil {
return errors.Wrap(err, "making new request")
}
req.Header.Set("Content-Type", "application/json")
resp, err := d.client.Do(req)
if err != nil {
return errors.Wrap(err, "posting")
}
// Intentionally ignoring response body, as user does not need to be notified of error.
defer resp.Body.Close()
return nil
} | [
"func",
"(",
"d",
"*",
"diagnosticsCollector",
")",
"Flush",
"(",
")",
"error",
"{",
"d",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"d",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"d",
".",
"metrics",
"[",
"\"Uptime\"",
"]",
"=",
"(",
"ti... | // Flush sends the current metrics. | [
"Flush",
"sends",
"the",
"current",
"metrics",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/diagnostics.go#L80-L100 | train |
pilosa/pilosa | diagnostics.go | CheckVersion | func (d *diagnosticsCollector) CheckVersion() error {
var rsp versionResponse
req, err := http.NewRequest("GET", d.VersionURL, nil)
if err != nil {
return errors.Wrap(err, "making request")
}
resp, err := d.client.Do(req)
if err != nil {
return errors.Wrap(err, "getting version")
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("http: status=%d", resp.StatusCode)
} else if err := json.NewDecoder(resp.Body).Decode(&rsp); err != nil {
return fmt.Errorf("json decode: %s", err)
}
// If version has not changed since the last check, return
if rsp.Version == d.lastVersion {
return nil
}
d.lastVersion = rsp.Version
if err := d.compareVersion(rsp.Version); err != nil {
d.Logger.Printf("%s\n", err.Error())
}
return nil
} | go | func (d *diagnosticsCollector) CheckVersion() error {
var rsp versionResponse
req, err := http.NewRequest("GET", d.VersionURL, nil)
if err != nil {
return errors.Wrap(err, "making request")
}
resp, err := d.client.Do(req)
if err != nil {
return errors.Wrap(err, "getting version")
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("http: status=%d", resp.StatusCode)
} else if err := json.NewDecoder(resp.Body).Decode(&rsp); err != nil {
return fmt.Errorf("json decode: %s", err)
}
// If version has not changed since the last check, return
if rsp.Version == d.lastVersion {
return nil
}
d.lastVersion = rsp.Version
if err := d.compareVersion(rsp.Version); err != nil {
d.Logger.Printf("%s\n", err.Error())
}
return nil
} | [
"func",
"(",
"d",
"*",
"diagnosticsCollector",
")",
"CheckVersion",
"(",
")",
"error",
"{",
"var",
"rsp",
"versionResponse",
"\n",
"req",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"\"GET\"",
",",
"d",
".",
"VersionURL",
",",
"nil",
")",
"\n",
"... | // CheckVersion of the local build against Pilosa master. | [
"CheckVersion",
"of",
"the",
"local",
"build",
"against",
"Pilosa",
"master",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/diagnostics.go#L103-L132 | train |
pilosa/pilosa | diagnostics.go | compareVersion | func (d *diagnosticsCollector) compareVersion(value string) error {
currentVersion := versionSegments(value)
localVersion := versionSegments(d.version)
if localVersion[0] < currentVersion[0] { //Major
return fmt.Errorf("you are running Pilosa %s, a newer version (%s) is available: https://github.com/pilosa/pilosa/releases", d.version, value)
} else if localVersion[1] < currentVersion[1] && localVersion[0] == currentVersion[0] { // Minor
return fmt.Errorf("you are running Pilosa %s, the latest minor release is %s: https://github.com/pilosa/pilosa/releases", d.version, value)
} else if localVersion[2] < currentVersion[2] && localVersion[0] == currentVersion[0] && localVersion[1] == currentVersion[1] { // Patch
return fmt.Errorf("there is a new patch release of Pilosa available: %s: https://github.com/pilosa/pilosa/releases", value)
}
return nil
} | go | func (d *diagnosticsCollector) compareVersion(value string) error {
currentVersion := versionSegments(value)
localVersion := versionSegments(d.version)
if localVersion[0] < currentVersion[0] { //Major
return fmt.Errorf("you are running Pilosa %s, a newer version (%s) is available: https://github.com/pilosa/pilosa/releases", d.version, value)
} else if localVersion[1] < currentVersion[1] && localVersion[0] == currentVersion[0] { // Minor
return fmt.Errorf("you are running Pilosa %s, the latest minor release is %s: https://github.com/pilosa/pilosa/releases", d.version, value)
} else if localVersion[2] < currentVersion[2] && localVersion[0] == currentVersion[0] && localVersion[1] == currentVersion[1] { // Patch
return fmt.Errorf("there is a new patch release of Pilosa available: %s: https://github.com/pilosa/pilosa/releases", value)
}
return nil
} | [
"func",
"(",
"d",
"*",
"diagnosticsCollector",
")",
"compareVersion",
"(",
"value",
"string",
")",
"error",
"{",
"currentVersion",
":=",
"versionSegments",
"(",
"value",
")",
"\n",
"localVersion",
":=",
"versionSegments",
"(",
"d",
".",
"version",
")",
"\n",
... | // compareVersion check version strings. | [
"compareVersion",
"check",
"version",
"strings",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/diagnostics.go#L135-L148 | train |
pilosa/pilosa | diagnostics.go | Set | func (d *diagnosticsCollector) Set(name string, value interface{}) {
switch v := value.(type) {
case string:
if v == "" {
// Do not set empty string
return
}
}
d.mu.Lock()
defer d.mu.Unlock()
d.metrics[name] = value
} | go | func (d *diagnosticsCollector) Set(name string, value interface{}) {
switch v := value.(type) {
case string:
if v == "" {
// Do not set empty string
return
}
}
d.mu.Lock()
defer d.mu.Unlock()
d.metrics[name] = value
} | [
"func",
"(",
"d",
"*",
"diagnosticsCollector",
")",
"Set",
"(",
"name",
"string",
",",
"value",
"interface",
"{",
"}",
")",
"{",
"switch",
"v",
":=",
"value",
".",
"(",
"type",
")",
"{",
"case",
"string",
":",
"if",
"v",
"==",
"\"\"",
"{",
"return"... | // Set adds a key value metric. | [
"Set",
"adds",
"a",
"key",
"value",
"metric",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/diagnostics.go#L156-L167 | train |
pilosa/pilosa | diagnostics.go | logErr | func (d *diagnosticsCollector) logErr(err error) bool {
if err != nil {
d.Logger.Printf("%v", err)
return true
}
return false
} | go | func (d *diagnosticsCollector) logErr(err error) bool {
if err != nil {
d.Logger.Printf("%v", err)
return true
}
return false
} | [
"func",
"(",
"d",
"*",
"diagnosticsCollector",
")",
"logErr",
"(",
"err",
"error",
")",
"bool",
"{",
"if",
"err",
"!=",
"nil",
"{",
"d",
".",
"Logger",
".",
"Printf",
"(",
"\"%v\"",
",",
"err",
")",
"\n",
"return",
"true",
"\n",
"}",
"\n",
"return"... | // logErr logs the error and returns true if an error exists | [
"logErr",
"logs",
"the",
"error",
"and",
"returns",
"true",
"if",
"an",
"error",
"exists"
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/diagnostics.go#L170-L176 | train |
pilosa/pilosa | diagnostics.go | EnrichWithOSInfo | func (d *diagnosticsCollector) EnrichWithOSInfo() {
uptime, err := d.server.systemInfo.Uptime()
if !d.logErr(err) {
d.Set("HostUptime", uptime)
}
platform, err := d.server.systemInfo.Platform()
if !d.logErr(err) {
d.Set("OSPlatform", platform)
}
family, err := d.server.systemInfo.Family()
if !d.logErr(err) {
d.Set("OSFamily", family)
}
version, err := d.server.systemInfo.OSVersion()
if !d.logErr(err) {
d.Set("OSVersion", version)
}
kernelVersion, err := d.server.systemInfo.KernelVersion()
if !d.logErr(err) {
d.Set("OSKernelVersion", kernelVersion)
}
} | go | func (d *diagnosticsCollector) EnrichWithOSInfo() {
uptime, err := d.server.systemInfo.Uptime()
if !d.logErr(err) {
d.Set("HostUptime", uptime)
}
platform, err := d.server.systemInfo.Platform()
if !d.logErr(err) {
d.Set("OSPlatform", platform)
}
family, err := d.server.systemInfo.Family()
if !d.logErr(err) {
d.Set("OSFamily", family)
}
version, err := d.server.systemInfo.OSVersion()
if !d.logErr(err) {
d.Set("OSVersion", version)
}
kernelVersion, err := d.server.systemInfo.KernelVersion()
if !d.logErr(err) {
d.Set("OSKernelVersion", kernelVersion)
}
} | [
"func",
"(",
"d",
"*",
"diagnosticsCollector",
")",
"EnrichWithOSInfo",
"(",
")",
"{",
"uptime",
",",
"err",
":=",
"d",
".",
"server",
".",
"systemInfo",
".",
"Uptime",
"(",
")",
"\n",
"if",
"!",
"d",
".",
"logErr",
"(",
"err",
")",
"{",
"d",
".",
... | // EnrichWithOSInfo adds OS information to the diagnostics payload. | [
"EnrichWithOSInfo",
"adds",
"OS",
"information",
"to",
"the",
"diagnostics",
"payload",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/diagnostics.go#L184-L205 | train |
pilosa/pilosa | diagnostics.go | EnrichWithMemoryInfo | func (d *diagnosticsCollector) EnrichWithMemoryInfo() {
memFree, err := d.server.systemInfo.MemFree()
if !d.logErr(err) {
d.Set("MemFree", memFree)
}
memTotal, err := d.server.systemInfo.MemTotal()
if !d.logErr(err) {
d.Set("MemTotal", memTotal)
}
memUsed, err := d.server.systemInfo.MemUsed()
if !d.logErr(err) {
d.Set("MemUsed", memUsed)
}
} | go | func (d *diagnosticsCollector) EnrichWithMemoryInfo() {
memFree, err := d.server.systemInfo.MemFree()
if !d.logErr(err) {
d.Set("MemFree", memFree)
}
memTotal, err := d.server.systemInfo.MemTotal()
if !d.logErr(err) {
d.Set("MemTotal", memTotal)
}
memUsed, err := d.server.systemInfo.MemUsed()
if !d.logErr(err) {
d.Set("MemUsed", memUsed)
}
} | [
"func",
"(",
"d",
"*",
"diagnosticsCollector",
")",
"EnrichWithMemoryInfo",
"(",
")",
"{",
"memFree",
",",
"err",
":=",
"d",
".",
"server",
".",
"systemInfo",
".",
"MemFree",
"(",
")",
"\n",
"if",
"!",
"d",
".",
"logErr",
"(",
"err",
")",
"{",
"d",
... | // EnrichWithMemoryInfo adds memory information to the diagnostics payload. | [
"EnrichWithMemoryInfo",
"adds",
"memory",
"information",
"to",
"the",
"diagnostics",
"payload",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/diagnostics.go#L208-L221 | train |
pilosa/pilosa | diagnostics.go | EnrichWithSchemaProperties | func (d *diagnosticsCollector) EnrichWithSchemaProperties() {
var numShards uint64
numFields := 0
numIndexes := 0
bsiFieldCount := 0
timeQuantumEnabled := false
for _, index := range d.server.holder.Indexes() {
numShards += index.AvailableShards().Count()
numIndexes++
for _, field := range index.Fields() {
numFields++
if field.Type() == FieldTypeInt {
bsiFieldCount++
}
if field.TimeQuantum() != "" {
timeQuantumEnabled = true
}
}
}
d.Set("NumIndexes", numIndexes)
d.Set("NumFields", numFields)
d.Set("NumShards", numShards)
d.Set("BSIFieldCount", bsiFieldCount)
d.Set("TimeQuantumEnabled", timeQuantumEnabled)
} | go | func (d *diagnosticsCollector) EnrichWithSchemaProperties() {
var numShards uint64
numFields := 0
numIndexes := 0
bsiFieldCount := 0
timeQuantumEnabled := false
for _, index := range d.server.holder.Indexes() {
numShards += index.AvailableShards().Count()
numIndexes++
for _, field := range index.Fields() {
numFields++
if field.Type() == FieldTypeInt {
bsiFieldCount++
}
if field.TimeQuantum() != "" {
timeQuantumEnabled = true
}
}
}
d.Set("NumIndexes", numIndexes)
d.Set("NumFields", numFields)
d.Set("NumShards", numShards)
d.Set("BSIFieldCount", bsiFieldCount)
d.Set("TimeQuantumEnabled", timeQuantumEnabled)
} | [
"func",
"(",
"d",
"*",
"diagnosticsCollector",
")",
"EnrichWithSchemaProperties",
"(",
")",
"{",
"var",
"numShards",
"uint64",
"\n",
"numFields",
":=",
"0",
"\n",
"numIndexes",
":=",
"0",
"\n",
"bsiFieldCount",
":=",
"0",
"\n",
"timeQuantumEnabled",
":=",
"fal... | // EnrichWithSchemaProperties adds schema info to the diagnostics payload. | [
"EnrichWithSchemaProperties",
"adds",
"schema",
"info",
"to",
"the",
"diagnostics",
"payload",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/diagnostics.go#L224-L250 | train |
pilosa/pilosa | diagnostics.go | versionSegments | func versionSegments(segments string) []int {
segments = strings.Trim(segments, "v")
segments = strings.Split(segments, "-")[0]
s := strings.Split(segments, ".")
segmentSlice := make([]int, len(s))
for i, v := range s {
segmentSlice[i], _ = strconv.Atoi(v)
}
return segmentSlice
} | go | func versionSegments(segments string) []int {
segments = strings.Trim(segments, "v")
segments = strings.Split(segments, "-")[0]
s := strings.Split(segments, ".")
segmentSlice := make([]int, len(s))
for i, v := range s {
segmentSlice[i], _ = strconv.Atoi(v)
}
return segmentSlice
} | [
"func",
"versionSegments",
"(",
"segments",
"string",
")",
"[",
"]",
"int",
"{",
"segments",
"=",
"strings",
".",
"Trim",
"(",
"segments",
",",
"\"v\"",
")",
"\n",
"segments",
"=",
"strings",
".",
"Split",
"(",
"segments",
",",
"\"-\"",
")",
"[",
"0",
... | // versionSegments returns the numeric segments of the version as a slice of ints. | [
"versionSegments",
"returns",
"the",
"numeric",
"segments",
"of",
"the",
"version",
"as",
"a",
"slice",
"of",
"ints",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/diagnostics.go#L253-L262 | train |
pilosa/pilosa | roaring/container_stash.go | NewContainer | func NewContainer() *Container {
statsHit("NewContainer")
c := &Container{typ: containerArray, len: 0, cap: stashedArraySize}
c.pointer = (*uint16)(unsafe.Pointer(&c.data[0]))
return c
} | go | func NewContainer() *Container {
statsHit("NewContainer")
c := &Container{typ: containerArray, len: 0, cap: stashedArraySize}
c.pointer = (*uint16)(unsafe.Pointer(&c.data[0]))
return c
} | [
"func",
"NewContainer",
"(",
")",
"*",
"Container",
"{",
"statsHit",
"(",
"\"NewContainer\"",
")",
"\n",
"c",
":=",
"&",
"Container",
"{",
"typ",
":",
"containerArray",
",",
"len",
":",
"0",
",",
"cap",
":",
"stashedArraySize",
"}",
"\n",
"c",
".",
"po... | // NewContainer returns a new instance of container. This trivial function
// may later become more interesting. | [
"NewContainer",
"returns",
"a",
"new",
"instance",
"of",
"container",
".",
"This",
"trivial",
"function",
"may",
"later",
"become",
"more",
"interesting",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/roaring/container_stash.go#L49-L54 | train |
pilosa/pilosa | roaring/container_stash.go | NewContainerBitmap | func NewContainerBitmap(n int32, bitmap []uint64) *Container {
if bitmap == nil {
bitmap = make([]uint64, bitmapN)
}
// pad to required length
if len(bitmap) < bitmapN {
bm2 := make([]uint64, bitmapN)
copy(bm2, bitmap)
bitmap = bm2
}
c := &Container{typ: containerBitmap, n: n}
c.setBitmap(bitmap)
return c
} | go | func NewContainerBitmap(n int32, bitmap []uint64) *Container {
if bitmap == nil {
bitmap = make([]uint64, bitmapN)
}
// pad to required length
if len(bitmap) < bitmapN {
bm2 := make([]uint64, bitmapN)
copy(bm2, bitmap)
bitmap = bm2
}
c := &Container{typ: containerBitmap, n: n}
c.setBitmap(bitmap)
return c
} | [
"func",
"NewContainerBitmap",
"(",
"n",
"int32",
",",
"bitmap",
"[",
"]",
"uint64",
")",
"*",
"Container",
"{",
"if",
"bitmap",
"==",
"nil",
"{",
"bitmap",
"=",
"make",
"(",
"[",
"]",
"uint64",
",",
"bitmapN",
")",
"\n",
"}",
"\n",
"if",
"len",
"("... | // NewContainerBitmap makes a bitmap container using the provided bitmap, or
// an empty one if provided bitmap is nil. If the provided bitmap is too short,
// it will be padded. | [
"NewContainerBitmap",
"makes",
"a",
"bitmap",
"container",
"using",
"the",
"provided",
"bitmap",
"or",
"an",
"empty",
"one",
"if",
"provided",
"bitmap",
"is",
"nil",
".",
"If",
"the",
"provided",
"bitmap",
"is",
"too",
"short",
"it",
"will",
"be",
"padded",
... | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/roaring/container_stash.go#L59-L72 | train |
pilosa/pilosa | roaring/container_stash.go | NewContainerArray | func NewContainerArray(set []uint16) *Container {
c := &Container{typ: containerArray, n: int32(len(set))}
c.setArray(set)
return c
} | go | func NewContainerArray(set []uint16) *Container {
c := &Container{typ: containerArray, n: int32(len(set))}
c.setArray(set)
return c
} | [
"func",
"NewContainerArray",
"(",
"set",
"[",
"]",
"uint16",
")",
"*",
"Container",
"{",
"c",
":=",
"&",
"Container",
"{",
"typ",
":",
"containerArray",
",",
"n",
":",
"int32",
"(",
"len",
"(",
"set",
")",
")",
"}",
"\n",
"c",
".",
"setArray",
"(",... | // NewContainerArray returns an array using the provided set of values. It's
// okay if the slice is nil; that's a length of zero. | [
"NewContainerArray",
"returns",
"an",
"array",
"using",
"the",
"provided",
"set",
"of",
"values",
".",
"It",
"s",
"okay",
"if",
"the",
"slice",
"is",
"nil",
";",
"that",
"s",
"a",
"length",
"of",
"zero",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/roaring/container_stash.go#L76-L80 | train |
pilosa/pilosa | roaring/container_stash.go | array | func (c *Container) array() []uint16 {
if roaringParanoia {
if c.typ != containerArray {
panic("attempt to read non-array's array")
}
}
return *(*[]uint16)(unsafe.Pointer(&reflect.SliceHeader{Data: uintptr(unsafe.Pointer(c.pointer)), Len: int(c.len), Cap: int(c.cap)}))
} | go | func (c *Container) array() []uint16 {
if roaringParanoia {
if c.typ != containerArray {
panic("attempt to read non-array's array")
}
}
return *(*[]uint16)(unsafe.Pointer(&reflect.SliceHeader{Data: uintptr(unsafe.Pointer(c.pointer)), Len: int(c.len), Cap: int(c.cap)}))
} | [
"func",
"(",
"c",
"*",
"Container",
")",
"array",
"(",
")",
"[",
"]",
"uint16",
"{",
"if",
"roaringParanoia",
"{",
"if",
"c",
".",
"typ",
"!=",
"containerArray",
"{",
"panic",
"(",
"\"attempt to read non-array's array\"",
")",
"\n",
"}",
"\n",
"}",
"\n",... | // array yields the data viewed as a slice of uint16 values. | [
"array",
"yields",
"the",
"data",
"viewed",
"as",
"a",
"slice",
"of",
"uint16",
"values",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/roaring/container_stash.go#L106-L113 | train |
pilosa/pilosa | roaring/container_stash.go | setArray | func (c *Container) setArray(array []uint16) {
if roaringParanoia {
if c.typ != containerArray {
panic("attempt to write non-array's array")
}
}
// no array: start with our default 5-value array
if array == nil {
c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(&c.data[0])), 0, stashedArraySize
return
}
h := (*reflect.SliceHeader)(unsafe.Pointer(&array))
if h.Data == uintptr(unsafe.Pointer(c.pointer)) {
// nothing to do but update length
c.len = int32(h.Len)
return
}
// array we can fit in data store:
if len(array) <= stashedArraySize {
copy(c.data[:stashedArraySize], array)
c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(&c.data[0])), int32(len(array)), stashedArraySize
c.mapped = false // this is no longer using a hypothetical mmapped input array
return
}
c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(h.Data)), int32(h.Len), int32(h.Cap)
runtime.KeepAlive(&array)
} | go | func (c *Container) setArray(array []uint16) {
if roaringParanoia {
if c.typ != containerArray {
panic("attempt to write non-array's array")
}
}
// no array: start with our default 5-value array
if array == nil {
c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(&c.data[0])), 0, stashedArraySize
return
}
h := (*reflect.SliceHeader)(unsafe.Pointer(&array))
if h.Data == uintptr(unsafe.Pointer(c.pointer)) {
// nothing to do but update length
c.len = int32(h.Len)
return
}
// array we can fit in data store:
if len(array) <= stashedArraySize {
copy(c.data[:stashedArraySize], array)
c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(&c.data[0])), int32(len(array)), stashedArraySize
c.mapped = false // this is no longer using a hypothetical mmapped input array
return
}
c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(h.Data)), int32(h.Len), int32(h.Cap)
runtime.KeepAlive(&array)
} | [
"func",
"(",
"c",
"*",
"Container",
")",
"setArray",
"(",
"array",
"[",
"]",
"uint16",
")",
"{",
"if",
"roaringParanoia",
"{",
"if",
"c",
".",
"typ",
"!=",
"containerArray",
"{",
"panic",
"(",
"\"attempt to write non-array's array\"",
")",
"\n",
"}",
"\n",... | // setArray stores a set of uint16s as data. | [
"setArray",
"stores",
"a",
"set",
"of",
"uint16s",
"as",
"data",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/roaring/container_stash.go#L116-L142 | train |
pilosa/pilosa | roaring/container_stash.go | bitmap | func (c *Container) bitmap() []uint64 {
if roaringParanoia {
if c.typ != containerBitmap {
panic("attempt to read non-bitmap's bitmap")
}
}
return *(*[]uint64)(unsafe.Pointer(&reflect.SliceHeader{Data: uintptr(unsafe.Pointer(c.pointer)), Len: int(c.len), Cap: int(c.cap)}))
} | go | func (c *Container) bitmap() []uint64 {
if roaringParanoia {
if c.typ != containerBitmap {
panic("attempt to read non-bitmap's bitmap")
}
}
return *(*[]uint64)(unsafe.Pointer(&reflect.SliceHeader{Data: uintptr(unsafe.Pointer(c.pointer)), Len: int(c.len), Cap: int(c.cap)}))
} | [
"func",
"(",
"c",
"*",
"Container",
")",
"bitmap",
"(",
")",
"[",
"]",
"uint64",
"{",
"if",
"roaringParanoia",
"{",
"if",
"c",
".",
"typ",
"!=",
"containerBitmap",
"{",
"panic",
"(",
"\"attempt to read non-bitmap's bitmap\"",
")",
"\n",
"}",
"\n",
"}",
"... | // bitmap yields the data viewed as a slice of uint64s holding bits. | [
"bitmap",
"yields",
"the",
"data",
"viewed",
"as",
"a",
"slice",
"of",
"uint64s",
"holding",
"bits",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/roaring/container_stash.go#L145-L152 | train |
pilosa/pilosa | roaring/container_stash.go | setBitmap | func (c *Container) setBitmap(bitmap []uint64) {
if roaringParanoia {
if c.typ != containerBitmap {
panic("attempt to write non-bitmap's bitmap")
}
}
h := (*reflect.SliceHeader)(unsafe.Pointer(&bitmap))
c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(h.Data)), int32(h.Len), int32(h.Cap)
runtime.KeepAlive(&bitmap)
} | go | func (c *Container) setBitmap(bitmap []uint64) {
if roaringParanoia {
if c.typ != containerBitmap {
panic("attempt to write non-bitmap's bitmap")
}
}
h := (*reflect.SliceHeader)(unsafe.Pointer(&bitmap))
c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(h.Data)), int32(h.Len), int32(h.Cap)
runtime.KeepAlive(&bitmap)
} | [
"func",
"(",
"c",
"*",
"Container",
")",
"setBitmap",
"(",
"bitmap",
"[",
"]",
"uint64",
")",
"{",
"if",
"roaringParanoia",
"{",
"if",
"c",
".",
"typ",
"!=",
"containerBitmap",
"{",
"panic",
"(",
"\"attempt to write non-bitmap's bitmap\"",
")",
"\n",
"}",
... | // setBitmap stores a set of uint64s as data. | [
"setBitmap",
"stores",
"a",
"set",
"of",
"uint64s",
"as",
"data",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/roaring/container_stash.go#L155-L164 | train |
pilosa/pilosa | roaring/container_stash.go | runs | func (c *Container) runs() []interval16 {
if roaringParanoia {
if c.typ != containerRun {
panic("attempt to read non-run's runs")
}
}
return *(*[]interval16)(unsafe.Pointer(&reflect.SliceHeader{Data: uintptr(unsafe.Pointer(c.pointer)), Len: int(c.len), Cap: int(c.cap)}))
} | go | func (c *Container) runs() []interval16 {
if roaringParanoia {
if c.typ != containerRun {
panic("attempt to read non-run's runs")
}
}
return *(*[]interval16)(unsafe.Pointer(&reflect.SliceHeader{Data: uintptr(unsafe.Pointer(c.pointer)), Len: int(c.len), Cap: int(c.cap)}))
} | [
"func",
"(",
"c",
"*",
"Container",
")",
"runs",
"(",
")",
"[",
"]",
"interval16",
"{",
"if",
"roaringParanoia",
"{",
"if",
"c",
".",
"typ",
"!=",
"containerRun",
"{",
"panic",
"(",
"\"attempt to read non-run's runs\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
... | // runs yields the data viewed as a slice of intervals. | [
"runs",
"yields",
"the",
"data",
"viewed",
"as",
"a",
"slice",
"of",
"intervals",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/roaring/container_stash.go#L167-L174 | train |
pilosa/pilosa | roaring/container_stash.go | setRuns | func (c *Container) setRuns(runs []interval16) {
if roaringParanoia {
if c.typ != containerRun {
panic("attempt to write non-run's runs")
}
}
// no array: start with our default 2-value array
if runs == nil {
c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(&c.data[0])), 0, stashedRunSize
return
}
h := (*reflect.SliceHeader)(unsafe.Pointer(&runs))
if h.Data == uintptr(unsafe.Pointer(c.pointer)) {
// nothing to do but update length
c.len = int32(h.Len)
return
}
// array we can fit in data store:
if len(runs) <= stashedRunSize {
newRuns := *(*[]interval16)(unsafe.Pointer(&reflect.SliceHeader{Data: uintptr(unsafe.Pointer(&c.data[0])), Len: stashedRunSize, Cap: stashedRunSize}))
copy(newRuns, runs)
c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(&c.data[0])), int32(len(runs)), stashedRunSize
c.mapped = false // this is no longer using a hypothetical mmapped input array
return
}
c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(h.Data)), int32(h.Len), int32(h.Cap)
runtime.KeepAlive(&runs)
} | go | func (c *Container) setRuns(runs []interval16) {
if roaringParanoia {
if c.typ != containerRun {
panic("attempt to write non-run's runs")
}
}
// no array: start with our default 2-value array
if runs == nil {
c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(&c.data[0])), 0, stashedRunSize
return
}
h := (*reflect.SliceHeader)(unsafe.Pointer(&runs))
if h.Data == uintptr(unsafe.Pointer(c.pointer)) {
// nothing to do but update length
c.len = int32(h.Len)
return
}
// array we can fit in data store:
if len(runs) <= stashedRunSize {
newRuns := *(*[]interval16)(unsafe.Pointer(&reflect.SliceHeader{Data: uintptr(unsafe.Pointer(&c.data[0])), Len: stashedRunSize, Cap: stashedRunSize}))
copy(newRuns, runs)
c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(&c.data[0])), int32(len(runs)), stashedRunSize
c.mapped = false // this is no longer using a hypothetical mmapped input array
return
}
c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(h.Data)), int32(h.Len), int32(h.Cap)
runtime.KeepAlive(&runs)
} | [
"func",
"(",
"c",
"*",
"Container",
")",
"setRuns",
"(",
"runs",
"[",
"]",
"interval16",
")",
"{",
"if",
"roaringParanoia",
"{",
"if",
"c",
".",
"typ",
"!=",
"containerRun",
"{",
"panic",
"(",
"\"attempt to write non-run's runs\"",
")",
"\n",
"}",
"\n",
... | // setRuns stores a set of intervals as data. | [
"setRuns",
"stores",
"a",
"set",
"of",
"intervals",
"as",
"data",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/roaring/container_stash.go#L177-L205 | train |
pilosa/pilosa | roaring/container_stash.go | Update | func (c *Container) Update(typ byte, n int32, mapped bool) {
c.typ = typ
c.n = n
c.mapped = mapped
// we don't know that any existing slice is usable, so let's ditch it
switch c.typ {
case containerArray:
c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(&c.data[0])), int32(0), stashedArraySize
case containerRun:
c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(&c.data[0])), 0, stashedRunSize
default:
c.pointer, c.len, c.cap = nil, 0, 0
}
} | go | func (c *Container) Update(typ byte, n int32, mapped bool) {
c.typ = typ
c.n = n
c.mapped = mapped
// we don't know that any existing slice is usable, so let's ditch it
switch c.typ {
case containerArray:
c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(&c.data[0])), int32(0), stashedArraySize
case containerRun:
c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(&c.data[0])), 0, stashedRunSize
default:
c.pointer, c.len, c.cap = nil, 0, 0
}
} | [
"func",
"(",
"c",
"*",
"Container",
")",
"Update",
"(",
"typ",
"byte",
",",
"n",
"int32",
",",
"mapped",
"bool",
")",
"{",
"c",
".",
"typ",
"=",
"typ",
"\n",
"c",
".",
"n",
"=",
"n",
"\n",
"c",
".",
"mapped",
"=",
"mapped",
"\n",
"switch",
"c... | // Update updates the container | [
"Update",
"updates",
"the",
"container"
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/roaring/container_stash.go#L208-L221 | train |
pilosa/pilosa | roaring/container_stash.go | unmapArray | func (c *Container) unmapArray() {
if !c.mapped {
return
}
array := c.array()
tmp := make([]uint16, c.len)
copy(tmp, array)
h := (*reflect.SliceHeader)(unsafe.Pointer(&tmp))
c.pointer, c.cap = (*uint16)(unsafe.Pointer(h.Data)), int32(h.Cap)
runtime.KeepAlive(&tmp)
c.mapped = false
} | go | func (c *Container) unmapArray() {
if !c.mapped {
return
}
array := c.array()
tmp := make([]uint16, c.len)
copy(tmp, array)
h := (*reflect.SliceHeader)(unsafe.Pointer(&tmp))
c.pointer, c.cap = (*uint16)(unsafe.Pointer(h.Data)), int32(h.Cap)
runtime.KeepAlive(&tmp)
c.mapped = false
} | [
"func",
"(",
"c",
"*",
"Container",
")",
"unmapArray",
"(",
")",
"{",
"if",
"!",
"c",
".",
"mapped",
"{",
"return",
"\n",
"}",
"\n",
"array",
":=",
"c",
".",
"array",
"(",
")",
"\n",
"tmp",
":=",
"make",
"(",
"[",
"]",
"uint16",
",",
"c",
"."... | // unmapArray ensures that the container is not using mmapped storage. | [
"unmapArray",
"ensures",
"that",
"the",
"container",
"is",
"not",
"using",
"mmapped",
"storage",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/roaring/container_stash.go#L239-L250 | train |
pilosa/pilosa | roaring/container_stash.go | unmapRun | func (c *Container) unmapRun() {
if !c.mapped {
return
}
runs := c.runs()
tmp := make([]interval16, c.len)
copy(tmp, runs)
h := (*reflect.SliceHeader)(unsafe.Pointer(&tmp))
c.pointer, c.cap = (*uint16)(unsafe.Pointer(h.Data)), int32(h.Cap)
c.mapped = false
} | go | func (c *Container) unmapRun() {
if !c.mapped {
return
}
runs := c.runs()
tmp := make([]interval16, c.len)
copy(tmp, runs)
h := (*reflect.SliceHeader)(unsafe.Pointer(&tmp))
c.pointer, c.cap = (*uint16)(unsafe.Pointer(h.Data)), int32(h.Cap)
c.mapped = false
} | [
"func",
"(",
"c",
"*",
"Container",
")",
"unmapRun",
"(",
")",
"{",
"if",
"!",
"c",
".",
"mapped",
"{",
"return",
"\n",
"}",
"\n",
"runs",
":=",
"c",
".",
"runs",
"(",
")",
"\n",
"tmp",
":=",
"make",
"(",
"[",
"]",
"interval16",
",",
"c",
"."... | // unmapRun ensures that the container is not using mmapped storage. | [
"unmapRun",
"ensures",
"that",
"the",
"container",
"is",
"not",
"using",
"mmapped",
"storage",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/roaring/container_stash.go#L267-L277 | train |
pilosa/pilosa | server/config.go | NewConfig | func NewConfig() *Config {
c := &Config{
DataDir: "~/.pilosa",
Bind: ":10101",
MaxWritesPerRequest: 5000,
// We default these Max File/Map counts very high. This is basically a
// backwards compatibility thing where we don't want to cause different
// behavior for those who had previously set their system limits high,
// and weren't experiencing any bad behavior. Ideally you want these set
// a bit below your system limits.
MaxMapCount: 1000000,
MaxFileCount: 1000000,
TLS: TLSConfig{},
}
// Cluster config.
c.Cluster.Disabled = false
c.Cluster.ReplicaN = 1
c.Cluster.Hosts = []string{}
c.Cluster.LongQueryTime = toml.Duration(time.Minute)
// Gossip config.
c.Gossip.Port = "14000"
c.Gossip.StreamTimeout = toml.Duration(10 * time.Second)
c.Gossip.SuspicionMult = 4
c.Gossip.PushPullInterval = toml.Duration(30 * time.Second)
c.Gossip.ProbeInterval = toml.Duration(1 * time.Second)
c.Gossip.ProbeTimeout = toml.Duration(500 * time.Millisecond)
c.Gossip.Interval = toml.Duration(200 * time.Millisecond)
c.Gossip.Nodes = 3
c.Gossip.ToTheDeadTime = toml.Duration(30 * time.Second)
// AntiEntropy config.
c.AntiEntropy.Interval = toml.Duration(10 * time.Minute)
// Metric config.
c.Metric.Service = "none"
c.Metric.PollInterval = toml.Duration(0 * time.Minute)
c.Metric.Diagnostics = true
// Tracing config.
c.Tracing.SamplerType = jaeger.SamplerTypeRemote
c.Tracing.SamplerParam = 0.001
c.Profile.BlockRate = 10000000 // 1 sample per 10 ms
c.Profile.MutexFraction = 100 // 1% sampling
return c
} | go | func NewConfig() *Config {
c := &Config{
DataDir: "~/.pilosa",
Bind: ":10101",
MaxWritesPerRequest: 5000,
// We default these Max File/Map counts very high. This is basically a
// backwards compatibility thing where we don't want to cause different
// behavior for those who had previously set their system limits high,
// and weren't experiencing any bad behavior. Ideally you want these set
// a bit below your system limits.
MaxMapCount: 1000000,
MaxFileCount: 1000000,
TLS: TLSConfig{},
}
// Cluster config.
c.Cluster.Disabled = false
c.Cluster.ReplicaN = 1
c.Cluster.Hosts = []string{}
c.Cluster.LongQueryTime = toml.Duration(time.Minute)
// Gossip config.
c.Gossip.Port = "14000"
c.Gossip.StreamTimeout = toml.Duration(10 * time.Second)
c.Gossip.SuspicionMult = 4
c.Gossip.PushPullInterval = toml.Duration(30 * time.Second)
c.Gossip.ProbeInterval = toml.Duration(1 * time.Second)
c.Gossip.ProbeTimeout = toml.Duration(500 * time.Millisecond)
c.Gossip.Interval = toml.Duration(200 * time.Millisecond)
c.Gossip.Nodes = 3
c.Gossip.ToTheDeadTime = toml.Duration(30 * time.Second)
// AntiEntropy config.
c.AntiEntropy.Interval = toml.Duration(10 * time.Minute)
// Metric config.
c.Metric.Service = "none"
c.Metric.PollInterval = toml.Duration(0 * time.Minute)
c.Metric.Diagnostics = true
// Tracing config.
c.Tracing.SamplerType = jaeger.SamplerTypeRemote
c.Tracing.SamplerParam = 0.001
c.Profile.BlockRate = 10000000 // 1 sample per 10 ms
c.Profile.MutexFraction = 100 // 1% sampling
return c
} | [
"func",
"NewConfig",
"(",
")",
"*",
"Config",
"{",
"c",
":=",
"&",
"Config",
"{",
"DataDir",
":",
"\"~/.pilosa\"",
",",
"Bind",
":",
"\":10101\"",
",",
"MaxWritesPerRequest",
":",
"5000",
",",
"MaxMapCount",
":",
"1000000",
",",
"MaxFileCount",
":",
"10000... | // NewConfig returns an instance of Config with default options. | [
"NewConfig",
"returns",
"an",
"instance",
"of",
"Config",
"with",
"default",
"options",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/server/config.go#L141-L190 | train |
pilosa/pilosa | server/config.go | validateAddrs | func (cfg *Config) validateAddrs(ctx context.Context) error {
// Validate the advertise address.
advScheme, advHost, advPort, err := validateAdvertiseAddr(ctx, cfg.Advertise, cfg.Bind)
if err != nil {
return errors.Wrapf(err, "validating advertise address")
}
cfg.Advertise = schemeHostPortString(advScheme, advHost, advPort)
// Validate the listen address.
listenScheme, listenHost, listenPort, err := validateListenAddr(ctx, cfg.Bind)
if err != nil {
return errors.Wrap(err, "validating listen address")
}
cfg.Bind = schemeHostPortString(listenScheme, listenHost, listenPort)
return nil
} | go | func (cfg *Config) validateAddrs(ctx context.Context) error {
// Validate the advertise address.
advScheme, advHost, advPort, err := validateAdvertiseAddr(ctx, cfg.Advertise, cfg.Bind)
if err != nil {
return errors.Wrapf(err, "validating advertise address")
}
cfg.Advertise = schemeHostPortString(advScheme, advHost, advPort)
// Validate the listen address.
listenScheme, listenHost, listenPort, err := validateListenAddr(ctx, cfg.Bind)
if err != nil {
return errors.Wrap(err, "validating listen address")
}
cfg.Bind = schemeHostPortString(listenScheme, listenHost, listenPort)
return nil
} | [
"func",
"(",
"cfg",
"*",
"Config",
")",
"validateAddrs",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"advScheme",
",",
"advHost",
",",
"advPort",
",",
"err",
":=",
"validateAdvertiseAddr",
"(",
"ctx",
",",
"cfg",
".",
"Advertise",
",",
"cfg... | // validateAddrs controls the address fields in the Config object
// and fills in any blanks.
// The addresses fields must be guaranteed by the caller to either be
// completely empty, or have both a host part and a port part
// separated by a colon. In the latter case either can be empty to
// indicate it's left unspecified. | [
"validateAddrs",
"controls",
"the",
"address",
"fields",
"in",
"the",
"Config",
"object",
"and",
"fills",
"in",
"any",
"blanks",
".",
"The",
"addresses",
"fields",
"must",
"be",
"guaranteed",
"by",
"the",
"caller",
"to",
"either",
"be",
"completely",
"empty",
... | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/server/config.go#L198-L214 | train |
pilosa/pilosa | server/config.go | validateAdvertiseAddr | func validateAdvertiseAddr(ctx context.Context, advAddr, listenAddr string) (string, string, string, error) {
listenScheme, listenHost, listenPort, err := splitAddr(listenAddr)
if err != nil {
return "", "", "", errors.Wrap(err, "getting listen address")
}
advScheme, advHostPort := splitScheme(advAddr)
advHost, advPort := "", ""
if advHostPort != "" {
var err error
advHost, advPort, err = net.SplitHostPort(advHostPort)
if err != nil {
return "", "", "", errors.Wrapf(err, "splitting host port: %s", advHostPort)
}
}
// If no advertise scheme was specified, use the one from
// the listen address.
if advScheme == "" {
advScheme = listenScheme
}
// If there was no port number, reuse the one from the listen
// address.
if advPort == "" || advPort == "0" {
advPort = listenPort
}
// Resolve non-numeric to numeric.
portNumber, err := net.DefaultResolver.LookupPort(ctx, "tcp", advPort)
if err != nil {
return "", "", "", errors.Wrapf(err, "looking up non-numeric port: %v", advPort)
}
advPort = strconv.Itoa(portNumber)
// If the advertise host is empty, then we have two cases.
if advHost == "" {
if listenHost == "0.0.0.0" {
advHost = outboundIP().String()
} else {
advHost = listenHost
}
}
return advScheme, advHost, advPort, nil
} | go | func validateAdvertiseAddr(ctx context.Context, advAddr, listenAddr string) (string, string, string, error) {
listenScheme, listenHost, listenPort, err := splitAddr(listenAddr)
if err != nil {
return "", "", "", errors.Wrap(err, "getting listen address")
}
advScheme, advHostPort := splitScheme(advAddr)
advHost, advPort := "", ""
if advHostPort != "" {
var err error
advHost, advPort, err = net.SplitHostPort(advHostPort)
if err != nil {
return "", "", "", errors.Wrapf(err, "splitting host port: %s", advHostPort)
}
}
// If no advertise scheme was specified, use the one from
// the listen address.
if advScheme == "" {
advScheme = listenScheme
}
// If there was no port number, reuse the one from the listen
// address.
if advPort == "" || advPort == "0" {
advPort = listenPort
}
// Resolve non-numeric to numeric.
portNumber, err := net.DefaultResolver.LookupPort(ctx, "tcp", advPort)
if err != nil {
return "", "", "", errors.Wrapf(err, "looking up non-numeric port: %v", advPort)
}
advPort = strconv.Itoa(portNumber)
// If the advertise host is empty, then we have two cases.
if advHost == "" {
if listenHost == "0.0.0.0" {
advHost = outboundIP().String()
} else {
advHost = listenHost
}
}
return advScheme, advHost, advPort, nil
} | [
"func",
"validateAdvertiseAddr",
"(",
"ctx",
"context",
".",
"Context",
",",
"advAddr",
",",
"listenAddr",
"string",
")",
"(",
"string",
",",
"string",
",",
"string",
",",
"error",
")",
"{",
"listenScheme",
",",
"listenHost",
",",
"listenPort",
",",
"err",
... | // validateAdvertiseAddr validates and normalizes an address accessible
// Ensures that if the "host" part is empty, it gets filled in with
// the configured listen address if any, otherwise it makes a best
// guess at the outbound IP address.
// Returns scheme, host, port as strings. | [
"validateAdvertiseAddr",
"validates",
"and",
"normalizes",
"an",
"address",
"accessible",
"Ensures",
"that",
"if",
"the",
"host",
"part",
"is",
"empty",
"it",
"gets",
"filled",
"in",
"with",
"the",
"configured",
"listen",
"address",
"if",
"any",
"otherwise",
"it... | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/server/config.go#L221-L262 | train |
pilosa/pilosa | server/config.go | outboundIP | func outboundIP() net.IP {
// This is not actually making a connection to 8.8.8.8.
// net.Dial() selects the IP address that would be used
// if an actual connection to 8.8.8.8 were made, so this
// choice of address is just meant to ensure that an
// external address is returned (as opposed to a local
// address like 127.0.0.1).
conn, err := net.Dial("udp", "8.8.8.8:80")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
localAddr := conn.LocalAddr().(*net.UDPAddr)
return localAddr.IP
} | go | func outboundIP() net.IP {
// This is not actually making a connection to 8.8.8.8.
// net.Dial() selects the IP address that would be used
// if an actual connection to 8.8.8.8 were made, so this
// choice of address is just meant to ensure that an
// external address is returned (as opposed to a local
// address like 127.0.0.1).
conn, err := net.Dial("udp", "8.8.8.8:80")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
localAddr := conn.LocalAddr().(*net.UDPAddr)
return localAddr.IP
} | [
"func",
"outboundIP",
"(",
")",
"net",
".",
"IP",
"{",
"conn",
",",
"err",
":=",
"net",
".",
"Dial",
"(",
"\"udp\"",
",",
"\"8.8.8.8:80\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatal",
"(",
"err",
")",
"\n",
"}",
"\n",
"defer",
... | // outboundIP gets the preferred outbound ip of this machine. | [
"outboundIP",
"gets",
"the",
"preferred",
"outbound",
"ip",
"of",
"this",
"machine",
"."
] | 67d53f6b48a43f7fe090f48e35518ca8d024747c | https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/server/config.go#L265-L281 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.