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
server/config.go
splitAddr
func splitAddr(addr string) (string, string, string, error) { scheme, hostPort := splitScheme(addr) host, port := "", "" if hostPort != "" { var err error host, port, err = net.SplitHostPort(hostPort) if err != nil { return "", "", "", errors.Wrapf(err, "splitting host port: %s", hostPort) } } // It's not ideal to have a default here, but the alterative // results in a port of 0, which causes Pilosa to listen on // a random port. if port == "" { port = "10101" } return scheme, host, port, nil }
go
func splitAddr(addr string) (string, string, string, error) { scheme, hostPort := splitScheme(addr) host, port := "", "" if hostPort != "" { var err error host, port, err = net.SplitHostPort(hostPort) if err != nil { return "", "", "", errors.Wrapf(err, "splitting host port: %s", hostPort) } } // It's not ideal to have a default here, but the alterative // results in a port of 0, which causes Pilosa to listen on // a random port. if port == "" { port = "10101" } return scheme, host, port, nil }
[ "func", "splitAddr", "(", "addr", "string", ")", "(", "string", ",", "string", ",", "string", ",", "error", ")", "{", "scheme", ",", "hostPort", ":=", "splitScheme", "(", "addr", ")", "\n", "host", ",", "port", ":=", "\"\"", ",", "\"\"", "\n", "if", ...
// splitAddr returns scheme, host, port as strings.
[ "splitAddr", "returns", "scheme", "host", "port", "as", "strings", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/server/config.go#L318-L335
train
pilosa/pilosa
ctl/generate_config.go
NewGenerateConfigCommand
func NewGenerateConfigCommand(stdin io.Reader, stdout, stderr io.Writer) *GenerateConfigCommand { return &GenerateConfigCommand{ CmdIO: pilosa.NewCmdIO(stdin, stdout, stderr), } }
go
func NewGenerateConfigCommand(stdin io.Reader, stdout, stderr io.Writer) *GenerateConfigCommand { return &GenerateConfigCommand{ CmdIO: pilosa.NewCmdIO(stdin, stdout, stderr), } }
[ "func", "NewGenerateConfigCommand", "(", "stdin", "io", ".", "Reader", ",", "stdout", ",", "stderr", "io", ".", "Writer", ")", "*", "GenerateConfigCommand", "{", "return", "&", "GenerateConfigCommand", "{", "CmdIO", ":", "pilosa", ".", "NewCmdIO", "(", "stdin"...
// NewGenerateConfigCommand returns a new instance of GenerateConfigCommand.
[ "NewGenerateConfigCommand", "returns", "a", "new", "instance", "of", "GenerateConfigCommand", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/ctl/generate_config.go#L34-L38
train
pilosa/pilosa
cmd/server.go
newServeCmd
func newServeCmd(stdin io.Reader, stdout, stderr io.Writer) *cobra.Command { Server = server.NewCommand(stdin, stdout, stderr) serveCmd := &cobra.Command{ Use: "server", Short: "Run Pilosa.", Long: `pilosa server runs Pilosa. It will load existing data from the configured directory and start listening for client connections on the configured port.`, RunE: func(cmd *cobra.Command, args []string) error { // Start & run the server. if err := Server.Start(); err != nil { return errors.Wrap(err, "running server") } // Initialize tracing in the command since it is global. var cfg jaegercfg.Configuration cfg.ServiceName = "pilosa" cfg.Sampler = &jaegercfg.SamplerConfig{ Type: Server.Config.Tracing.SamplerType, Param: Server.Config.Tracing.SamplerParam, } cfg.Reporter = &jaegercfg.ReporterConfig{ LocalAgentHostPort: Server.Config.Tracing.AgentHostPort, } tracer, closer, err := cfg.NewTracer() if err != nil { return errors.Wrap(err, "initializing jaeger tracer") } defer closer.Close() tracing.GlobalTracer = opentracing.NewTracer(tracer) return errors.Wrap(Server.Wait(), "waiting on Server") }, } // Attach flags to the command. ctl.BuildServerFlags(serveCmd, Server) return serveCmd }
go
func newServeCmd(stdin io.Reader, stdout, stderr io.Writer) *cobra.Command { Server = server.NewCommand(stdin, stdout, stderr) serveCmd := &cobra.Command{ Use: "server", Short: "Run Pilosa.", Long: `pilosa server runs Pilosa. It will load existing data from the configured directory and start listening for client connections on the configured port.`, RunE: func(cmd *cobra.Command, args []string) error { // Start & run the server. if err := Server.Start(); err != nil { return errors.Wrap(err, "running server") } // Initialize tracing in the command since it is global. var cfg jaegercfg.Configuration cfg.ServiceName = "pilosa" cfg.Sampler = &jaegercfg.SamplerConfig{ Type: Server.Config.Tracing.SamplerType, Param: Server.Config.Tracing.SamplerParam, } cfg.Reporter = &jaegercfg.ReporterConfig{ LocalAgentHostPort: Server.Config.Tracing.AgentHostPort, } tracer, closer, err := cfg.NewTracer() if err != nil { return errors.Wrap(err, "initializing jaeger tracer") } defer closer.Close() tracing.GlobalTracer = opentracing.NewTracer(tracer) return errors.Wrap(Server.Wait(), "waiting on Server") }, } // Attach flags to the command. ctl.BuildServerFlags(serveCmd, Server) return serveCmd }
[ "func", "newServeCmd", "(", "stdin", "io", ".", "Reader", ",", "stdout", ",", "stderr", "io", ".", "Writer", ")", "*", "cobra", ".", "Command", "{", "Server", "=", "server", ".", "NewCommand", "(", "stdin", ",", "stdout", ",", "stderr", ")", "\n", "s...
// newServeCmd creates a pilosa server and runs it with command line flags.
[ "newServeCmd", "creates", "a", "pilosa", "server", "and", "runs", "it", "with", "command", "line", "flags", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cmd/server.go#L33-L73
train
pilosa/pilosa
boltdb/attrstore.go
Get
func (c *attrCache) Get(id uint64) map[string]interface{} { c.mu.RLock() defer c.mu.RUnlock() attrs := c.attrs[id] if attrs == nil { return nil } // Make a copy for safety ret := make(map[string]interface{}) for k, v := range attrs { ret[k] = v } return ret }
go
func (c *attrCache) Get(id uint64) map[string]interface{} { c.mu.RLock() defer c.mu.RUnlock() attrs := c.attrs[id] if attrs == nil { return nil } // Make a copy for safety ret := make(map[string]interface{}) for k, v := range attrs { ret[k] = v } return ret }
[ "func", "(", "c", "*", "attrCache", ")", "Get", "(", "id", "uint64", ")", "map", "[", "string", "]", "interface", "{", "}", "{", "c", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "RUnlock", "(", ")", "\n", "attrs", "...
// Get returns the cached attributes for a given id.
[ "Get", "returns", "the", "cached", "attributes", "for", "a", "given", "id", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/boltdb/attrstore.go#L43-L57
train
pilosa/pilosa
boltdb/attrstore.go
Set
func (c *attrCache) Set(id uint64, attrs map[string]interface{}) { c.mu.Lock() defer c.mu.Unlock() c.attrs[id] = attrs }
go
func (c *attrCache) Set(id uint64, attrs map[string]interface{}) { c.mu.Lock() defer c.mu.Unlock() c.attrs[id] = attrs }
[ "func", "(", "c", "*", "attrCache", ")", "Set", "(", "id", "uint64", ",", "attrs", "map", "[", "string", "]", "interface", "{", "}", ")", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n"...
// Set updates the cached attributes for a given id.
[ "Set", "updates", "the", "cached", "attributes", "for", "a", "given", "id", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/boltdb/attrstore.go#L60-L64
train
pilosa/pilosa
boltdb/attrstore.go
NewAttrStore
func NewAttrStore(path string) pilosa.AttrStore { return &attrStore{ path: path, attrCache: newAttrCache(), } }
go
func NewAttrStore(path string) pilosa.AttrStore { return &attrStore{ path: path, attrCache: newAttrCache(), } }
[ "func", "NewAttrStore", "(", "path", "string", ")", "pilosa", ".", "AttrStore", "{", "return", "&", "attrStore", "{", "path", ":", "path", ",", "attrCache", ":", "newAttrCache", "(", ")", ",", "}", "\n", "}" ]
// NewAttrStore returns a new instance of AttrStore.
[ "NewAttrStore", "returns", "a", "new", "instance", "of", "AttrStore", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/boltdb/attrstore.go#L82-L87
train
pilosa/pilosa
boltdb/attrstore.go
Open
func (s *attrStore) Open() error { // Open storage. db, err := bolt.Open(s.path, 0666, &bolt.Options{Timeout: 1 * time.Second}) if err != nil { return errors.Wrap(err, "opening storage") } s.db = db // Initialize database. if err := s.db.Update(func(tx *bolt.Tx) error { _, err := tx.CreateBucketIfNotExists([]byte("attrs")) return err }); err != nil { return errors.Wrap(err, "initializing") } return nil }
go
func (s *attrStore) Open() error { // Open storage. db, err := bolt.Open(s.path, 0666, &bolt.Options{Timeout: 1 * time.Second}) if err != nil { return errors.Wrap(err, "opening storage") } s.db = db // Initialize database. if err := s.db.Update(func(tx *bolt.Tx) error { _, err := tx.CreateBucketIfNotExists([]byte("attrs")) return err }); err != nil { return errors.Wrap(err, "initializing") } return nil }
[ "func", "(", "s", "*", "attrStore", ")", "Open", "(", ")", "error", "{", "db", ",", "err", ":=", "bolt", ".", "Open", "(", "s", ".", "path", ",", "0666", ",", "&", "bolt", ".", "Options", "{", "Timeout", ":", "1", "*", "time", ".", "Second", ...
// Open opens and initializes the store.
[ "Open", "opens", "and", "initializes", "the", "store", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/boltdb/attrstore.go#L93-L110
train
pilosa/pilosa
boltdb/attrstore.go
Attrs
func (s *attrStore) Attrs(id uint64) (m map[string]interface{}, err error) { s.mu.RLock() defer s.mu.RUnlock() // Check cache for map. if m = s.attrCache.Get(id); m != nil { return m, nil } // Find attributes from storage. if err = s.db.View(func(tx *bolt.Tx) error { m, err = txAttrs(tx, id) return err }); err != nil { return nil, errors.Wrap(err, "finding attributes") } // Add to cache. s.attrCache.Set(id, m) return m, nil }
go
func (s *attrStore) Attrs(id uint64) (m map[string]interface{}, err error) { s.mu.RLock() defer s.mu.RUnlock() // Check cache for map. if m = s.attrCache.Get(id); m != nil { return m, nil } // Find attributes from storage. if err = s.db.View(func(tx *bolt.Tx) error { m, err = txAttrs(tx, id) return err }); err != nil { return nil, errors.Wrap(err, "finding attributes") } // Add to cache. s.attrCache.Set(id, m) return m, nil }
[ "func", "(", "s", "*", "attrStore", ")", "Attrs", "(", "id", "uint64", ")", "(", "m", "map", "[", "string", "]", "interface", "{", "}", ",", "err", "error", ")", "{", "s", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "mu", ".",...
// Attrs returns a set of attributes by ID.
[ "Attrs", "returns", "a", "set", "of", "attributes", "by", "ID", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/boltdb/attrstore.go#L121-L142
train
pilosa/pilosa
boltdb/attrstore.go
SetAttrs
func (s *attrStore) SetAttrs(id uint64, m map[string]interface{}) error { // Ignore empty maps. if len(m) == 0 { return nil } // Check if the attributes already exist under a read-only lock. if attr, err := s.Attrs(id); err != nil { return errors.Wrap(err, "checking attrs") } else if attr != nil && mapContains(attr, m) { return nil } // Obtain write lock. s.mu.Lock() defer s.mu.Unlock() var attr map[string]interface{} if err := s.db.Update(func(tx *bolt.Tx) error { tmp, err := txUpdateAttrs(tx, id, m) if err != nil { return err } attr = tmp return nil }); err != nil { return errors.Wrap(err, "updating store") } // Swap attributes map in cache. s.attrCache.Set(id, attr) return nil }
go
func (s *attrStore) SetAttrs(id uint64, m map[string]interface{}) error { // Ignore empty maps. if len(m) == 0 { return nil } // Check if the attributes already exist under a read-only lock. if attr, err := s.Attrs(id); err != nil { return errors.Wrap(err, "checking attrs") } else if attr != nil && mapContains(attr, m) { return nil } // Obtain write lock. s.mu.Lock() defer s.mu.Unlock() var attr map[string]interface{} if err := s.db.Update(func(tx *bolt.Tx) error { tmp, err := txUpdateAttrs(tx, id, m) if err != nil { return err } attr = tmp return nil }); err != nil { return errors.Wrap(err, "updating store") } // Swap attributes map in cache. s.attrCache.Set(id, attr) return nil }
[ "func", "(", "s", "*", "attrStore", ")", "SetAttrs", "(", "id", "uint64", ",", "m", "map", "[", "string", "]", "interface", "{", "}", ")", "error", "{", "if", "len", "(", "m", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "if", "attr",...
// SetAttrs sets attribute values for a given ID.
[ "SetAttrs", "sets", "attribute", "values", "for", "a", "given", "ID", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/boltdb/attrstore.go#L145-L179
train
pilosa/pilosa
boltdb/attrstore.go
SetBulkAttrs
func (s *attrStore) SetBulkAttrs(m map[uint64]map[string]interface{}) error { s.mu.Lock() defer s.mu.Unlock() attrs := make(map[uint64]map[string]interface{}) if err := s.db.Update(func(tx *bolt.Tx) error { // Collect and sort keys. ids := make([]uint64, 0, len(m)) for id := range m { ids = append(ids, id) } sort.Slice(ids, func(i, j int) bool { return ids[i] < ids[j] }) // Update attributes for each id. for _, id := range ids { attr, err := txUpdateAttrs(tx, id, m[id]) if err != nil { return err } attrs[id] = attr } return nil }); err != nil { return err } // Swap attributes map in cache. for id, attr := range attrs { s.attrCache.Set(id, attr) } return nil }
go
func (s *attrStore) SetBulkAttrs(m map[uint64]map[string]interface{}) error { s.mu.Lock() defer s.mu.Unlock() attrs := make(map[uint64]map[string]interface{}) if err := s.db.Update(func(tx *bolt.Tx) error { // Collect and sort keys. ids := make([]uint64, 0, len(m)) for id := range m { ids = append(ids, id) } sort.Slice(ids, func(i, j int) bool { return ids[i] < ids[j] }) // Update attributes for each id. for _, id := range ids { attr, err := txUpdateAttrs(tx, id, m[id]) if err != nil { return err } attrs[id] = attr } return nil }); err != nil { return err } // Swap attributes map in cache. for id, attr := range attrs { s.attrCache.Set(id, attr) } return nil }
[ "func", "(", "s", "*", "attrStore", ")", "SetBulkAttrs", "(", "m", "map", "[", "uint64", "]", "map", "[", "string", "]", "interface", "{", "}", ")", "error", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unloc...
// SetBulkAttrs sets attribute values for a set of ids.
[ "SetBulkAttrs", "sets", "attribute", "values", "for", "a", "set", "of", "ids", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/boltdb/attrstore.go#L182-L215
train
pilosa/pilosa
boltdb/attrstore.go
Blocks
func (s *attrStore) Blocks() (blocks []pilosa.AttrBlock, err error) { err = s.db.View(func(tx *bolt.Tx) error { // Wrap cursor to segment by block. cur := newBlockCursor(tx.Bucket([]byte("attrs")).Cursor(), attrBlockSize) // Iterate over each block. for cur.nextBlock() { block := pilosa.AttrBlock{ID: cur.blockID()} // Compute checksum of every key/value in block. h := xxhash.New() for k, v := cur.next(); k != nil; k, v = cur.next() { // hash function writes don't usually need to be checked _, _ = h.Write(k) _, _ = h.Write(v) } block.Checksum = h.Sum(nil) // Append block. blocks = append(blocks, block) } return nil }) if err != nil { return nil, errors.Wrap(err, "getting blocks") } return blocks, nil }
go
func (s *attrStore) Blocks() (blocks []pilosa.AttrBlock, err error) { err = s.db.View(func(tx *bolt.Tx) error { // Wrap cursor to segment by block. cur := newBlockCursor(tx.Bucket([]byte("attrs")).Cursor(), attrBlockSize) // Iterate over each block. for cur.nextBlock() { block := pilosa.AttrBlock{ID: cur.blockID()} // Compute checksum of every key/value in block. h := xxhash.New() for k, v := cur.next(); k != nil; k, v = cur.next() { // hash function writes don't usually need to be checked _, _ = h.Write(k) _, _ = h.Write(v) } block.Checksum = h.Sum(nil) // Append block. blocks = append(blocks, block) } return nil }) if err != nil { return nil, errors.Wrap(err, "getting blocks") } return blocks, nil }
[ "func", "(", "s", "*", "attrStore", ")", "Blocks", "(", ")", "(", "blocks", "[", "]", "pilosa", ".", "AttrBlock", ",", "err", "error", ")", "{", "err", "=", "s", ".", "db", ".", "View", "(", "func", "(", "tx", "*", "bolt", ".", "Tx", ")", "er...
// Blocks returns a list of all blocks in the store.
[ "Blocks", "returns", "a", "list", "of", "all", "blocks", "in", "the", "store", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/boltdb/attrstore.go#L218-L245
train
pilosa/pilosa
boltdb/attrstore.go
BlockData
func (s *attrStore) BlockData(i uint64) (m map[uint64]map[string]interface{}, err error) { m = make(map[uint64]map[string]interface{}) // Start read-only transaction. err = s.db.View(func(tx *bolt.Tx) error { // Move to the start of the block. min := u64tob(i * attrBlockSize) max := u64tob((i + 1) * attrBlockSize) cur := tx.Bucket([]byte("attrs")).Cursor() for k, v := cur.Seek(min); k != nil; k, v = cur.Next() { // Exit if we're past the end of the block. if bytes.Compare(k, max) != -1 { break } // Decode attribute map and associate with id. attrs, err := pilosa.DecodeAttrs(v) if err != nil { return errors.Wrap(err, "decoding attrs") } m[btou64(k)] = attrs } return nil }) if err != nil { return nil, errors.Wrap(err, "getting block data") } return m, nil }
go
func (s *attrStore) BlockData(i uint64) (m map[uint64]map[string]interface{}, err error) { m = make(map[uint64]map[string]interface{}) // Start read-only transaction. err = s.db.View(func(tx *bolt.Tx) error { // Move to the start of the block. min := u64tob(i * attrBlockSize) max := u64tob((i + 1) * attrBlockSize) cur := tx.Bucket([]byte("attrs")).Cursor() for k, v := cur.Seek(min); k != nil; k, v = cur.Next() { // Exit if we're past the end of the block. if bytes.Compare(k, max) != -1 { break } // Decode attribute map and associate with id. attrs, err := pilosa.DecodeAttrs(v) if err != nil { return errors.Wrap(err, "decoding attrs") } m[btou64(k)] = attrs } return nil }) if err != nil { return nil, errors.Wrap(err, "getting block data") } return m, nil }
[ "func", "(", "s", "*", "attrStore", ")", "BlockData", "(", "i", "uint64", ")", "(", "m", "map", "[", "uint64", "]", "map", "[", "string", "]", "interface", "{", "}", ",", "err", "error", ")", "{", "m", "=", "make", "(", "map", "[", "uint64", "]...
// BlockData returns all data for a single block.
[ "BlockData", "returns", "all", "data", "for", "a", "single", "block", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/boltdb/attrstore.go#L248-L277
train
pilosa/pilosa
boltdb/attrstore.go
txAttrs
func txAttrs(tx *bolt.Tx, id uint64) (map[string]interface{}, error) { v := tx.Bucket([]byte("attrs")).Get(u64tob(id)) if v == nil { return emptyMap, nil } return pilosa.DecodeAttrs(v) }
go
func txAttrs(tx *bolt.Tx, id uint64) (map[string]interface{}, error) { v := tx.Bucket([]byte("attrs")).Get(u64tob(id)) if v == nil { return emptyMap, nil } return pilosa.DecodeAttrs(v) }
[ "func", "txAttrs", "(", "tx", "*", "bolt", ".", "Tx", ",", "id", "uint64", ")", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "error", ")", "{", "v", ":=", "tx", ".", "Bucket", "(", "[", "]", "byte", "(", "\"attrs\"", ")", ")", ...
// txAttrs returns a map of attributes for an id.
[ "txAttrs", "returns", "a", "map", "of", "attributes", "for", "an", "id", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/boltdb/attrstore.go#L280-L286
train
pilosa/pilosa
boltdb/attrstore.go
txUpdateAttrs
func txUpdateAttrs(tx *bolt.Tx, id uint64, m map[string]interface{}) (map[string]interface{}, error) { attr, err := txAttrs(tx, id) if err != nil { return nil, err } // Create a new map if it is empty so we don't update emptyMap. if len(attr) == 0 { attr = make(map[string]interface{}, len(m)) } // Merge attributes with original values. // Nil values should delete keys. for k, v := range m { if v == nil { delete(attr, k) continue } switch v := v.(type) { case int: attr[k] = int64(v) case uint: attr[k] = int64(v) case uint64: attr[k] = int64(v) case string, int64, bool, float64: attr[k] = v default: return nil, fmt.Errorf("invalid attr type: %T", v) } } // Marshal and save new values. buf, err := pilosa.EncodeAttrs(attr) if err != nil { return nil, errors.Wrap(err, "encoding attrs") } if err := tx.Bucket([]byte("attrs")).Put(u64tob(id), buf); err != nil { return nil, errors.Wrap(err, "saving attrs") } return attr, nil }
go
func txUpdateAttrs(tx *bolt.Tx, id uint64, m map[string]interface{}) (map[string]interface{}, error) { attr, err := txAttrs(tx, id) if err != nil { return nil, err } // Create a new map if it is empty so we don't update emptyMap. if len(attr) == 0 { attr = make(map[string]interface{}, len(m)) } // Merge attributes with original values. // Nil values should delete keys. for k, v := range m { if v == nil { delete(attr, k) continue } switch v := v.(type) { case int: attr[k] = int64(v) case uint: attr[k] = int64(v) case uint64: attr[k] = int64(v) case string, int64, bool, float64: attr[k] = v default: return nil, fmt.Errorf("invalid attr type: %T", v) } } // Marshal and save new values. buf, err := pilosa.EncodeAttrs(attr) if err != nil { return nil, errors.Wrap(err, "encoding attrs") } if err := tx.Bucket([]byte("attrs")).Put(u64tob(id), buf); err != nil { return nil, errors.Wrap(err, "saving attrs") } return attr, nil }
[ "func", "txUpdateAttrs", "(", "tx", "*", "bolt", ".", "Tx", ",", "id", "uint64", ",", "m", "map", "[", "string", "]", "interface", "{", "}", ")", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "error", ")", "{", "attr", ",", "err", ...
// txUpdateAttrs updates the attributes for an id. // Returns the new combined set of attributes for the id.
[ "txUpdateAttrs", "updates", "the", "attributes", "for", "an", "id", ".", "Returns", "the", "new", "combined", "set", "of", "attributes", "for", "the", "id", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/boltdb/attrstore.go#L290-L332
train
pilosa/pilosa
boltdb/attrstore.go
mapContains
func mapContains(m, subset map[string]interface{}) bool { for k, v := range subset { value, ok := m[k] if !ok || value != v { return false } } return true }
go
func mapContains(m, subset map[string]interface{}) bool { for k, v := range subset { value, ok := m[k] if !ok || value != v { return false } } return true }
[ "func", "mapContains", "(", "m", ",", "subset", "map", "[", "string", "]", "interface", "{", "}", ")", "bool", "{", "for", "k", ",", "v", ":=", "range", "subset", "{", "value", ",", "ok", ":=", "m", "[", "k", "]", "\n", "if", "!", "ok", "||", ...
// mapContains returns true if all keys & values of subset are in m.
[ "mapContains", "returns", "true", "if", "all", "keys", "&", "values", "of", "subset", "are", "in", "m", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/boltdb/attrstore.go#L348-L356
train
pilosa/pilosa
boltdb/attrstore.go
newBlockCursor
func newBlockCursor(c *bolt.Cursor, n int) blockCursor { // nolint: unparam cur := blockCursor{ cur: c, n: uint64(n), } cur.buf.key, cur.buf.value = c.First() cur.buf.filled = true return cur }
go
func newBlockCursor(c *bolt.Cursor, n int) blockCursor { // nolint: unparam cur := blockCursor{ cur: c, n: uint64(n), } cur.buf.key, cur.buf.value = c.First() cur.buf.filled = true return cur }
[ "func", "newBlockCursor", "(", "c", "*", "bolt", ".", "Cursor", ",", "n", "int", ")", "blockCursor", "{", "cur", ":=", "blockCursor", "{", "cur", ":", "c", ",", "n", ":", "uint64", "(", "n", ")", ",", "}", "\n", "cur", ".", "buf", ".", "key", "...
// newBlockCursor returns a new block cursor that wraps cur using n sized blocks.
[ "newBlockCursor", "returns", "a", "new", "block", "cursor", "that", "wraps", "cur", "using", "n", "sized", "blocks", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/boltdb/attrstore.go#L372-L380
train
pilosa/pilosa
boltdb/attrstore.go
nextBlock
func (cur *blockCursor) nextBlock() bool { if cur.buf.key == nil { return false } cur.base = binary.BigEndian.Uint64(cur.buf.key) / cur.n return true }
go
func (cur *blockCursor) nextBlock() bool { if cur.buf.key == nil { return false } cur.base = binary.BigEndian.Uint64(cur.buf.key) / cur.n return true }
[ "func", "(", "cur", "*", "blockCursor", ")", "nextBlock", "(", ")", "bool", "{", "if", "cur", ".", "buf", ".", "key", "==", "nil", "{", "return", "false", "\n", "}", "\n", "cur", ".", "base", "=", "binary", ".", "BigEndian", ".", "Uint64", "(", "...
// nextBlock moves the cursor to the next block. // Returns true if another block exists, otherwise returns false.
[ "nextBlock", "moves", "the", "cursor", "to", "the", "next", "block", ".", "Returns", "true", "if", "another", "block", "exists", "otherwise", "returns", "false", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/boltdb/attrstore.go#L387-L394
train
pilosa/pilosa
ctl/import.go
NewImportCommand
func NewImportCommand(stdin io.Reader, stdout, stderr io.Writer) *ImportCommand { return &ImportCommand{ CmdIO: pilosa.NewCmdIO(stdin, stdout, stderr), BufferSize: 10000000, } }
go
func NewImportCommand(stdin io.Reader, stdout, stderr io.Writer) *ImportCommand { return &ImportCommand{ CmdIO: pilosa.NewCmdIO(stdin, stdout, stderr), BufferSize: 10000000, } }
[ "func", "NewImportCommand", "(", "stdin", "io", ".", "Reader", ",", "stdout", ",", "stderr", "io", ".", "Writer", ")", "*", "ImportCommand", "{", "return", "&", "ImportCommand", "{", "CmdIO", ":", "pilosa", ".", "NewCmdIO", "(", "stdin", ",", "stdout", "...
// NewImportCommand returns a new instance of ImportCommand.
[ "NewImportCommand", "returns", "a", "new", "instance", "of", "ImportCommand", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/ctl/import.go#L74-L79
train
pilosa/pilosa
ctl/import.go
Run
func (cmd *ImportCommand) Run(ctx context.Context) error { logger := log.New(cmd.Stderr, "", log.LstdFlags) // Validate arguments. // Index and field are validated early before the files are parsed. if cmd.Index == "" { return pilosa.ErrIndexRequired } else if cmd.Field == "" { return pilosa.ErrFieldRequired } else if len(cmd.Paths) == 0 { return errors.New("path required") } // Create a client to the server. client, err := commandClient(cmd) if err != nil { return errors.Wrap(err, "creating client") } cmd.client = client if cmd.CreateSchema { if cmd.FieldOptions.Type == "" { // set the correct type for the field if cmd.FieldOptions.TimeQuantum != "" { cmd.FieldOptions.Type = "time" } else if cmd.FieldOptions.Min != 0 || cmd.FieldOptions.Max != 0 { cmd.FieldOptions.Type = "int" } else { cmd.FieldOptions.Type = "set" } } err := cmd.ensureSchema(ctx) if err != nil { return errors.Wrap(err, "ensuring schema") } } // Determine the field type in order to correctly handle the input data. fieldType := pilosa.DefaultFieldType schema, err := cmd.client.Schema(ctx) if err != nil { return errors.Wrap(err, "getting schema") } var useColumnKeys, useRowKeys bool for _, index := range schema { if index.Name == cmd.Index { useColumnKeys = index.Options.Keys for _, field := range index.Fields { if field.Name == cmd.Field { useRowKeys = field.Options.Keys fieldType = field.Options.Type break } } break } } // Import each path and import by shard. for _, path := range cmd.Paths { logger.Printf("parsing: %s", path) if err := cmd.importPath(ctx, fieldType, useColumnKeys, useRowKeys, path); err != nil { return err } } return nil }
go
func (cmd *ImportCommand) Run(ctx context.Context) error { logger := log.New(cmd.Stderr, "", log.LstdFlags) // Validate arguments. // Index and field are validated early before the files are parsed. if cmd.Index == "" { return pilosa.ErrIndexRequired } else if cmd.Field == "" { return pilosa.ErrFieldRequired } else if len(cmd.Paths) == 0 { return errors.New("path required") } // Create a client to the server. client, err := commandClient(cmd) if err != nil { return errors.Wrap(err, "creating client") } cmd.client = client if cmd.CreateSchema { if cmd.FieldOptions.Type == "" { // set the correct type for the field if cmd.FieldOptions.TimeQuantum != "" { cmd.FieldOptions.Type = "time" } else if cmd.FieldOptions.Min != 0 || cmd.FieldOptions.Max != 0 { cmd.FieldOptions.Type = "int" } else { cmd.FieldOptions.Type = "set" } } err := cmd.ensureSchema(ctx) if err != nil { return errors.Wrap(err, "ensuring schema") } } // Determine the field type in order to correctly handle the input data. fieldType := pilosa.DefaultFieldType schema, err := cmd.client.Schema(ctx) if err != nil { return errors.Wrap(err, "getting schema") } var useColumnKeys, useRowKeys bool for _, index := range schema { if index.Name == cmd.Index { useColumnKeys = index.Options.Keys for _, field := range index.Fields { if field.Name == cmd.Field { useRowKeys = field.Options.Keys fieldType = field.Options.Type break } } break } } // Import each path and import by shard. for _, path := range cmd.Paths { logger.Printf("parsing: %s", path) if err := cmd.importPath(ctx, fieldType, useColumnKeys, useRowKeys, path); err != nil { return err } } return nil }
[ "func", "(", "cmd", "*", "ImportCommand", ")", "Run", "(", "ctx", "context", ".", "Context", ")", "error", "{", "logger", ":=", "log", ".", "New", "(", "cmd", ".", "Stderr", ",", "\"\"", ",", "log", ".", "LstdFlags", ")", "\n", "if", "cmd", ".", ...
// Run executes the main program execution.
[ "Run", "executes", "the", "main", "program", "execution", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/ctl/import.go#L82-L149
train
pilosa/pilosa
ctl/import.go
importPath
func (cmd *ImportCommand) importPath(ctx context.Context, fieldType string, useColumnKeys, useRowKeys bool, path string) error { // If fieldType is `int`, treat the import data as values to be range-encoded. if fieldType == pilosa.FieldTypeInt { return cmd.bufferValues(ctx, useColumnKeys, path) } return cmd.bufferBits(ctx, useColumnKeys, useRowKeys, path) }
go
func (cmd *ImportCommand) importPath(ctx context.Context, fieldType string, useColumnKeys, useRowKeys bool, path string) error { // If fieldType is `int`, treat the import data as values to be range-encoded. if fieldType == pilosa.FieldTypeInt { return cmd.bufferValues(ctx, useColumnKeys, path) } return cmd.bufferBits(ctx, useColumnKeys, useRowKeys, path) }
[ "func", "(", "cmd", "*", "ImportCommand", ")", "importPath", "(", "ctx", "context", ".", "Context", ",", "fieldType", "string", ",", "useColumnKeys", ",", "useRowKeys", "bool", ",", "path", "string", ")", "error", "{", "if", "fieldType", "==", "pilosa", "....
// importPath parses a path into bits and imports it to the server.
[ "importPath", "parses", "a", "path", "into", "bits", "and", "imports", "it", "to", "the", "server", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/ctl/import.go#L164-L170
train
pilosa/pilosa
ctl/import.go
bufferBits
func (cmd *ImportCommand) bufferBits(ctx context.Context, useColumnKeys, useRowKeys bool, path string) error { a := make([]pilosa.Bit, 0, cmd.BufferSize) var r *csv.Reader if path != "-" { // Open file for reading. f, err := os.Open(path) if err != nil { return errors.Wrap(err, "opening file") } defer f.Close() // Read rows as bits. r = csv.NewReader(f) } else { r = csv.NewReader(cmd.Stdin) } r.FieldsPerRecord = -1 rnum := 0 for { rnum++ // Read CSV row. record, err := r.Read() if err == io.EOF { break } else if err != nil { return errors.Wrap(err, "reading") } // Ignore blank rows. if record[0] == "" { continue } else if len(record) < 2 { return fmt.Errorf("bad column count on row %d: col=%d", rnum, len(record)) } var bit pilosa.Bit // Parse row id. if useRowKeys { bit.RowKey = record[0] } else { if bit.RowID, err = strconv.ParseUint(record[0], 10, 64); err != nil { return fmt.Errorf("invalid row id on row %d: %q", rnum, record[0]) } } // Parse column id. if useColumnKeys { bit.ColumnKey = record[1] } else { if bit.ColumnID, err = strconv.ParseUint(record[1], 10, 64); err != nil { return fmt.Errorf("invalid column id on row %d: %q", rnum, record[1]) } } // Parse time, if exists. if len(record) > 2 && record[2] != "" { t, err := time.Parse(pilosa.TimeFormat, record[2]) if err != nil { return fmt.Errorf("invalid timestamp on row %d: %q", rnum, record[2]) } bit.Timestamp = t.UnixNano() } a = append(a, bit) // If we've reached the buffer size then import bits. if len(a) == cmd.BufferSize { if err := cmd.importBits(ctx, useColumnKeys, useRowKeys, a); err != nil { return err } a = a[:0] } } // If there are still bits in the buffer then flush them. return cmd.importBits(ctx, useColumnKeys, useRowKeys, a) }
go
func (cmd *ImportCommand) bufferBits(ctx context.Context, useColumnKeys, useRowKeys bool, path string) error { a := make([]pilosa.Bit, 0, cmd.BufferSize) var r *csv.Reader if path != "-" { // Open file for reading. f, err := os.Open(path) if err != nil { return errors.Wrap(err, "opening file") } defer f.Close() // Read rows as bits. r = csv.NewReader(f) } else { r = csv.NewReader(cmd.Stdin) } r.FieldsPerRecord = -1 rnum := 0 for { rnum++ // Read CSV row. record, err := r.Read() if err == io.EOF { break } else if err != nil { return errors.Wrap(err, "reading") } // Ignore blank rows. if record[0] == "" { continue } else if len(record) < 2 { return fmt.Errorf("bad column count on row %d: col=%d", rnum, len(record)) } var bit pilosa.Bit // Parse row id. if useRowKeys { bit.RowKey = record[0] } else { if bit.RowID, err = strconv.ParseUint(record[0], 10, 64); err != nil { return fmt.Errorf("invalid row id on row %d: %q", rnum, record[0]) } } // Parse column id. if useColumnKeys { bit.ColumnKey = record[1] } else { if bit.ColumnID, err = strconv.ParseUint(record[1], 10, 64); err != nil { return fmt.Errorf("invalid column id on row %d: %q", rnum, record[1]) } } // Parse time, if exists. if len(record) > 2 && record[2] != "" { t, err := time.Parse(pilosa.TimeFormat, record[2]) if err != nil { return fmt.Errorf("invalid timestamp on row %d: %q", rnum, record[2]) } bit.Timestamp = t.UnixNano() } a = append(a, bit) // If we've reached the buffer size then import bits. if len(a) == cmd.BufferSize { if err := cmd.importBits(ctx, useColumnKeys, useRowKeys, a); err != nil { return err } a = a[:0] } } // If there are still bits in the buffer then flush them. return cmd.importBits(ctx, useColumnKeys, useRowKeys, a) }
[ "func", "(", "cmd", "*", "ImportCommand", ")", "bufferBits", "(", "ctx", "context", ".", "Context", ",", "useColumnKeys", ",", "useRowKeys", "bool", ",", "path", "string", ")", "error", "{", "a", ":=", "make", "(", "[", "]", "pilosa", ".", "Bit", ",", ...
// bufferBits buffers slices of bits to be imported as a batch.
[ "bufferBits", "buffers", "slices", "of", "bits", "to", "be", "imported", "as", "a", "batch", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/ctl/import.go#L173-L254
train
pilosa/pilosa
ctl/import.go
importBits
func (cmd *ImportCommand) importBits(ctx context.Context, useColumnKeys, useRowKeys bool, bits []pilosa.Bit) error { logger := log.New(cmd.Stderr, "", log.LstdFlags) // If keys are used, all bits are sent to the primary translate store (i.e. coordinator). if useColumnKeys || useRowKeys { logger.Printf("importing keys: n=%d", len(bits)) if err := cmd.client.ImportK(ctx, cmd.Index, cmd.Field, bits, pilosa.OptImportOptionsClear(cmd.Clear)); err != nil { return errors.Wrap(err, "importing keys") } return nil } // Group bits by shard. logger.Printf("grouping %d bits", len(bits)) bitsByShard := http.Bits(bits).GroupByShard() // Parse path into bits. for shard, chunk := range bitsByShard { if cmd.Sort { sort.Sort(http.BitsByPos(chunk)) } logger.Printf("importing shard: %d, n=%d", shard, len(chunk)) if err := cmd.client.Import(ctx, cmd.Index, cmd.Field, shard, chunk, pilosa.OptImportOptionsClear(cmd.Clear)); err != nil { return errors.Wrap(err, "importing") } } return nil }
go
func (cmd *ImportCommand) importBits(ctx context.Context, useColumnKeys, useRowKeys bool, bits []pilosa.Bit) error { logger := log.New(cmd.Stderr, "", log.LstdFlags) // If keys are used, all bits are sent to the primary translate store (i.e. coordinator). if useColumnKeys || useRowKeys { logger.Printf("importing keys: n=%d", len(bits)) if err := cmd.client.ImportK(ctx, cmd.Index, cmd.Field, bits, pilosa.OptImportOptionsClear(cmd.Clear)); err != nil { return errors.Wrap(err, "importing keys") } return nil } // Group bits by shard. logger.Printf("grouping %d bits", len(bits)) bitsByShard := http.Bits(bits).GroupByShard() // Parse path into bits. for shard, chunk := range bitsByShard { if cmd.Sort { sort.Sort(http.BitsByPos(chunk)) } logger.Printf("importing shard: %d, n=%d", shard, len(chunk)) if err := cmd.client.Import(ctx, cmd.Index, cmd.Field, shard, chunk, pilosa.OptImportOptionsClear(cmd.Clear)); err != nil { return errors.Wrap(err, "importing") } } return nil }
[ "func", "(", "cmd", "*", "ImportCommand", ")", "importBits", "(", "ctx", "context", ".", "Context", ",", "useColumnKeys", ",", "useRowKeys", "bool", ",", "bits", "[", "]", "pilosa", ".", "Bit", ")", "error", "{", "logger", ":=", "log", ".", "New", "(",...
// importBits sends batches of bits to the server.
[ "importBits", "sends", "batches", "of", "bits", "to", "the", "server", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/ctl/import.go#L257-L286
train
pilosa/pilosa
ctl/import.go
bufferValues
func (cmd *ImportCommand) bufferValues(ctx context.Context, useColumnKeys bool, path string) error { a := make([]pilosa.FieldValue, 0, cmd.BufferSize) var r *csv.Reader if path != "-" { // Open file for reading. f, err := os.Open(path) if err != nil { return errors.Wrap(err, "opening file") } defer f.Close() // Read rows as bits. r = csv.NewReader(f) } else { r = csv.NewReader(cmd.Stdin) } r.FieldsPerRecord = -1 rnum := 0 for { rnum++ // Read CSV row. record, err := r.Read() if err == io.EOF { break } else if err != nil { return errors.Wrap(err, "reading") } // Ignore blank rows. if record[0] == "" { continue } else if len(record) < 2 { return fmt.Errorf("bad column count on row %d: col=%d", rnum, len(record)) } var val pilosa.FieldValue // Parse column id. if useColumnKeys { val.ColumnKey = record[0] } else { if val.ColumnID, err = strconv.ParseUint(record[0], 10, 64); err != nil { return fmt.Errorf("invalid column id on row %d: %q", rnum, record[0]) } } // Parse FieldValue. value, err := strconv.ParseInt(record[1], 10, 64) if err != nil { return fmt.Errorf("invalid value on row %d: %q", rnum, record[1]) } val.Value = value a = append(a, val) // If we've reached the buffer size then import FieldValues. if len(a) == cmd.BufferSize { if err := cmd.importValues(ctx, useColumnKeys, a); err != nil { return err } a = a[:0] } } // If there are still values in the buffer then flush them. return cmd.importValues(ctx, useColumnKeys, a) }
go
func (cmd *ImportCommand) bufferValues(ctx context.Context, useColumnKeys bool, path string) error { a := make([]pilosa.FieldValue, 0, cmd.BufferSize) var r *csv.Reader if path != "-" { // Open file for reading. f, err := os.Open(path) if err != nil { return errors.Wrap(err, "opening file") } defer f.Close() // Read rows as bits. r = csv.NewReader(f) } else { r = csv.NewReader(cmd.Stdin) } r.FieldsPerRecord = -1 rnum := 0 for { rnum++ // Read CSV row. record, err := r.Read() if err == io.EOF { break } else if err != nil { return errors.Wrap(err, "reading") } // Ignore blank rows. if record[0] == "" { continue } else if len(record) < 2 { return fmt.Errorf("bad column count on row %d: col=%d", rnum, len(record)) } var val pilosa.FieldValue // Parse column id. if useColumnKeys { val.ColumnKey = record[0] } else { if val.ColumnID, err = strconv.ParseUint(record[0], 10, 64); err != nil { return fmt.Errorf("invalid column id on row %d: %q", rnum, record[0]) } } // Parse FieldValue. value, err := strconv.ParseInt(record[1], 10, 64) if err != nil { return fmt.Errorf("invalid value on row %d: %q", rnum, record[1]) } val.Value = value a = append(a, val) // If we've reached the buffer size then import FieldValues. if len(a) == cmd.BufferSize { if err := cmd.importValues(ctx, useColumnKeys, a); err != nil { return err } a = a[:0] } } // If there are still values in the buffer then flush them. return cmd.importValues(ctx, useColumnKeys, a) }
[ "func", "(", "cmd", "*", "ImportCommand", ")", "bufferValues", "(", "ctx", "context", ".", "Context", ",", "useColumnKeys", "bool", ",", "path", "string", ")", "error", "{", "a", ":=", "make", "(", "[", "]", "pilosa", ".", "FieldValue", ",", "0", ",", ...
// bufferValues buffers slices of FieldValues to be imported as a batch.
[ "bufferValues", "buffers", "slices", "of", "FieldValues", "to", "be", "imported", "as", "a", "batch", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/ctl/import.go#L289-L359
train
pilosa/pilosa
ctl/import.go
importValues
func (cmd *ImportCommand) importValues(ctx context.Context, useColumnKeys bool, vals []pilosa.FieldValue) error { logger := log.New(cmd.Stderr, "", log.LstdFlags) // If keys are used, all values are sent to the primary translate store (i.e. coordinator). if useColumnKeys { logger.Printf("importing keyed values: n=%d", len(vals)) if err := cmd.client.ImportValueK(ctx, cmd.Index, cmd.Field, vals); err != nil { return errors.Wrap(err, "importing keys") } return nil } // Group vals by shard. logger.Printf("grouping %d vals", len(vals)) valsByShard := http.FieldValues(vals).GroupByShard() // Parse path into FieldValues. for shard, vals := range valsByShard { if cmd.Sort { sort.Sort(http.FieldValues(vals)) } logger.Printf("importing shard: %d, n=%d", shard, len(vals)) if err := cmd.client.ImportValue(ctx, cmd.Index, cmd.Field, shard, vals, pilosa.OptImportOptionsClear(cmd.Clear)); err != nil { return errors.Wrap(err, "importing values") } } return nil }
go
func (cmd *ImportCommand) importValues(ctx context.Context, useColumnKeys bool, vals []pilosa.FieldValue) error { logger := log.New(cmd.Stderr, "", log.LstdFlags) // If keys are used, all values are sent to the primary translate store (i.e. coordinator). if useColumnKeys { logger.Printf("importing keyed values: n=%d", len(vals)) if err := cmd.client.ImportValueK(ctx, cmd.Index, cmd.Field, vals); err != nil { return errors.Wrap(err, "importing keys") } return nil } // Group vals by shard. logger.Printf("grouping %d vals", len(vals)) valsByShard := http.FieldValues(vals).GroupByShard() // Parse path into FieldValues. for shard, vals := range valsByShard { if cmd.Sort { sort.Sort(http.FieldValues(vals)) } logger.Printf("importing shard: %d, n=%d", shard, len(vals)) if err := cmd.client.ImportValue(ctx, cmd.Index, cmd.Field, shard, vals, pilosa.OptImportOptionsClear(cmd.Clear)); err != nil { return errors.Wrap(err, "importing values") } } return nil }
[ "func", "(", "cmd", "*", "ImportCommand", ")", "importValues", "(", "ctx", "context", ".", "Context", ",", "useColumnKeys", "bool", ",", "vals", "[", "]", "pilosa", ".", "FieldValue", ")", "error", "{", "logger", ":=", "log", ".", "New", "(", "cmd", "....
// importValues sends batches of FieldValues to the server.
[ "importValues", "sends", "batches", "of", "FieldValues", "to", "the", "server", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/ctl/import.go#L362-L391
train
pilosa/pilosa
pql/ast.go
endCall
func (q *Query) endCall() *Call { elem := q.callStack[len(q.callStack)-1] q.callStack[len(q.callStack)-1] = nil q.callStack = q.callStack[:len(q.callStack)-1] return elem.call }
go
func (q *Query) endCall() *Call { elem := q.callStack[len(q.callStack)-1] q.callStack[len(q.callStack)-1] = nil q.callStack = q.callStack[:len(q.callStack)-1] return elem.call }
[ "func", "(", "q", "*", "Query", ")", "endCall", "(", ")", "*", "Call", "{", "elem", ":=", "q", ".", "callStack", "[", "len", "(", "q", ".", "callStack", ")", "-", "1", "]", "\n", "q", ".", "callStack", "[", "len", "(", "q", ".", "callStack", ...
// endCall removes the last element from the call stack and returns the call.
[ "endCall", "removes", "the", "last", "element", "from", "the", "call", "stack", "and", "returns", "the", "call", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/pql/ast.go#L46-L51
train
pilosa/pilosa
pql/ast.go
WriteCallN
func (q *Query) WriteCallN() int { var n int for _, call := range q.Calls { switch call.Name { case "Set", "Clear", "SetRowAttrs", "SetColumnAttrs": n++ } } return n }
go
func (q *Query) WriteCallN() int { var n int for _, call := range q.Calls { switch call.Name { case "Set", "Clear", "SetRowAttrs", "SetColumnAttrs": n++ } } return n }
[ "func", "(", "q", "*", "Query", ")", "WriteCallN", "(", ")", "int", "{", "var", "n", "int", "\n", "for", "_", ",", "call", ":=", "range", "q", ".", "Calls", "{", "switch", "call", ".", "Name", "{", "case", "\"Set\"", ",", "\"Clear\"", ",", "\"Set...
// WriteCallN returns the number of mutating calls.
[ "WriteCallN", "returns", "the", "number", "of", "mutating", "calls", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/pql/ast.go#L235-L244
train
pilosa/pilosa
pql/ast.go
String
func (q *Query) String() string { a := make([]string, len(q.Calls)) for i, call := range q.Calls { a[i] = call.String() } return strings.Join(a, "\n") }
go
func (q *Query) String() string { a := make([]string, len(q.Calls)) for i, call := range q.Calls { a[i] = call.String() } return strings.Join(a, "\n") }
[ "func", "(", "q", "*", "Query", ")", "String", "(", ")", "string", "{", "a", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "q", ".", "Calls", ")", ")", "\n", "for", "i", ",", "call", ":=", "range", "q", ".", "Calls", "{", "a", "["...
// String returns a string representation of the query.
[ "String", "returns", "a", "string", "representation", "of", "the", "query", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/pql/ast.go#L247-L253
train
pilosa/pilosa
pql/ast.go
UintArg
func (c *Call) UintArg(key string) (uint64, bool, error) { val, ok := c.Args[key] if !ok { return 0, false, nil } switch tval := val.(type) { case int64: if tval < 0 { return 0, true, fmt.Errorf("value for '%s' must be positive, but got %v", key, tval) } return uint64(tval), true, nil case uint64: return tval, true, nil default: return 0, true, fmt.Errorf("could not convert %v of type %T to uint64 in Call.UintArg", tval, tval) } }
go
func (c *Call) UintArg(key string) (uint64, bool, error) { val, ok := c.Args[key] if !ok { return 0, false, nil } switch tval := val.(type) { case int64: if tval < 0 { return 0, true, fmt.Errorf("value for '%s' must be positive, but got %v", key, tval) } return uint64(tval), true, nil case uint64: return tval, true, nil default: return 0, true, fmt.Errorf("could not convert %v of type %T to uint64 in Call.UintArg", tval, tval) } }
[ "func", "(", "c", "*", "Call", ")", "UintArg", "(", "key", "string", ")", "(", "uint64", ",", "bool", ",", "error", ")", "{", "val", ",", "ok", ":=", "c", ".", "Args", "[", "key", "]", "\n", "if", "!", "ok", "{", "return", "0", ",", "false", ...
// UintArg is for reading the value at key from call.Args as a uint64. If the // key is not in Call.Args, the value of the returned bool will be false, and // the error will be nil. The value is assumed to be a uint64 or an int64 and // then cast to a uint64. An error is returned if the value is not an int64 or // uint64.
[ "UintArg", "is", "for", "reading", "the", "value", "at", "key", "from", "call", ".", "Args", "as", "a", "uint64", ".", "If", "the", "key", "is", "not", "in", "Call", ".", "Args", "the", "value", "of", "the", "returned", "bool", "will", "be", "false",...
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/pql/ast.go#L315-L331
train
pilosa/pilosa
pql/ast.go
CallArg
func (c *Call) CallArg(key string) (*Call, bool, error) { val, ok := c.Args[key] if !ok { return nil, false, nil } switch tval := val.(type) { case *Call: return tval, true, nil default: return nil, true, fmt.Errorf("could not convert %v of type %T to Call in Call.CallArg", tval, tval) } }
go
func (c *Call) CallArg(key string) (*Call, bool, error) { val, ok := c.Args[key] if !ok { return nil, false, nil } switch tval := val.(type) { case *Call: return tval, true, nil default: return nil, true, fmt.Errorf("could not convert %v of type %T to Call in Call.CallArg", tval, tval) } }
[ "func", "(", "c", "*", "Call", ")", "CallArg", "(", "key", "string", ")", "(", "*", "Call", ",", "bool", ",", "error", ")", "{", "val", ",", "ok", ":=", "c", ".", "Args", "[", "key", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "f...
// CallArg is for reading the value at key from call.Args as a Call. If the // key is not in Call.Args, the value of the returned value will be nil, and // the error will be nil. An error is returned if the value is not a Call.
[ "CallArg", "is", "for", "reading", "the", "value", "at", "key", "from", "call", ".", "Args", "as", "a", "Call", ".", "If", "the", "key", "is", "not", "in", "Call", ".", "Args", "the", "value", "of", "the", "returned", "value", "will", "be", "nil", ...
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/pql/ast.go#L380-L391
train
pilosa/pilosa
pql/ast.go
keys
func (c *Call) keys() []string { a := make([]string, 0, len(c.Args)) for k := range c.Args { a = append(a, k) } sort.Strings(a) return a }
go
func (c *Call) keys() []string { a := make([]string, 0, len(c.Args)) for k := range c.Args { a = append(a, k) } sort.Strings(a) return a }
[ "func", "(", "c", "*", "Call", ")", "keys", "(", ")", "[", "]", "string", "{", "a", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "c", ".", "Args", ")", ")", "\n", "for", "k", ":=", "range", "c", ".", "Args", "{", "a",...
// keys returns a list of argument keys in sorted order.
[ "keys", "returns", "a", "list", "of", "argument", "keys", "in", "sorted", "order", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/pql/ast.go#L394-L401
train
pilosa/pilosa
pql/ast.go
String
func (c *Call) String() string { var buf bytes.Buffer // Write name. if c.Name != "" { buf.WriteString(c.Name) } else { buf.WriteString("!UNNAMED") } // Write opening. buf.WriteByte('(') // Write child list. for i, child := range c.Children { if i > 0 { buf.WriteString(", ") } buf.WriteString(child.String()) } // Separate children and args, if necessary. if len(c.Children) > 0 && len(c.Args) > 0 { buf.WriteString(", ") } // Write arguments in key order. for i, key := range c.keys() { if i > 0 { buf.WriteString(", ") } // If the Arg value is a Condition, then don't include // the equal sign in the string representation. switch v := c.Args[key].(type) { case *Condition: fmt.Fprintf(&buf, "%v %s", key, v.String()) default: fmt.Fprintf(&buf, "%v=%s", key, formatValue(v)) } } // Write closing. buf.WriteByte(')') return buf.String() }
go
func (c *Call) String() string { var buf bytes.Buffer // Write name. if c.Name != "" { buf.WriteString(c.Name) } else { buf.WriteString("!UNNAMED") } // Write opening. buf.WriteByte('(') // Write child list. for i, child := range c.Children { if i > 0 { buf.WriteString(", ") } buf.WriteString(child.String()) } // Separate children and args, if necessary. if len(c.Children) > 0 && len(c.Args) > 0 { buf.WriteString(", ") } // Write arguments in key order. for i, key := range c.keys() { if i > 0 { buf.WriteString(", ") } // If the Arg value is a Condition, then don't include // the equal sign in the string representation. switch v := c.Args[key].(type) { case *Condition: fmt.Fprintf(&buf, "%v %s", key, v.String()) default: fmt.Fprintf(&buf, "%v=%s", key, formatValue(v)) } } // Write closing. buf.WriteByte(')') return buf.String() }
[ "func", "(", "c", "*", "Call", ")", "String", "(", ")", "string", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "if", "c", ".", "Name", "!=", "\"\"", "{", "buf", ".", "WriteString", "(", "c", ".", "Name", ")", "\n", "}", "else", "{", "buf", ...
// String returns the string representation of the call.
[ "String", "returns", "the", "string", "representation", "of", "the", "call", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/pql/ast.go#L423-L468
train
pilosa/pilosa
pql/ast.go
HasConditionArg
func (c *Call) HasConditionArg() bool { for _, v := range c.Args { if _, ok := v.(*Condition); ok { return true } } return false }
go
func (c *Call) HasConditionArg() bool { for _, v := range c.Args { if _, ok := v.(*Condition); ok { return true } } return false }
[ "func", "(", "c", "*", "Call", ")", "HasConditionArg", "(", ")", "bool", "{", "for", "_", ",", "v", ":=", "range", "c", ".", "Args", "{", "if", "_", ",", "ok", ":=", "v", ".", "(", "*", "Condition", ")", ";", "ok", "{", "return", "true", "\n"...
// HasConditionArg returns true if any arg is a conditional.
[ "HasConditionArg", "returns", "true", "if", "any", "arg", "is", "a", "conditional", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/pql/ast.go#L471-L478
train
pilosa/pilosa
pql/ast.go
String
func (cond *Condition) String() string { return fmt.Sprintf("%s %s", cond.Op.String(), formatValue(cond.Value)) }
go
func (cond *Condition) String() string { return fmt.Sprintf("%s %s", cond.Op.String(), formatValue(cond.Value)) }
[ "func", "(", "cond", "*", "Condition", ")", "String", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"%s %s\"", ",", "cond", ".", "Op", ".", "String", "(", ")", ",", "formatValue", "(", "cond", ".", "Value", ")", ")", "\n", "}" ]
// String returns the string representation of the condition.
[ "String", "returns", "the", "string", "representation", "of", "the", "condition", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/pql/ast.go#L488-L490
train
pilosa/pilosa
pql/ast.go
CopyArgs
func CopyArgs(m map[string]interface{}) map[string]interface{} { other := make(map[string]interface{}, len(m)) for k, v := range m { other[k] = v } return other }
go
func CopyArgs(m map[string]interface{}) map[string]interface{} { other := make(map[string]interface{}, len(m)) for k, v := range m { other[k] = v } return other }
[ "func", "CopyArgs", "(", "m", "map", "[", "string", "]", "interface", "{", "}", ")", "map", "[", "string", "]", "interface", "{", "}", "{", "other", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "len", "(", "m", ")", ...
// CopyArgs returns a copy of m.
[ "CopyArgs", "returns", "a", "copy", "of", "m", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/pql/ast.go#L535-L541
train
pilosa/pilosa
handler.go
MarshalJSON
func (resp *QueryResponse) MarshalJSON() ([]byte, error) { if resp.Err != nil { return json.Marshal(struct { Err string `json:"error"` }{Err: resp.Err.Error()}) } return json.Marshal(struct { Results []interface{} `json:"results"` ColumnAttrSets []*ColumnAttrSet `json:"columnAttrs,omitempty"` }{ Results: resp.Results, ColumnAttrSets: resp.ColumnAttrSets, }) }
go
func (resp *QueryResponse) MarshalJSON() ([]byte, error) { if resp.Err != nil { return json.Marshal(struct { Err string `json:"error"` }{Err: resp.Err.Error()}) } return json.Marshal(struct { Results []interface{} `json:"results"` ColumnAttrSets []*ColumnAttrSet `json:"columnAttrs,omitempty"` }{ Results: resp.Results, ColumnAttrSets: resp.ColumnAttrSets, }) }
[ "func", "(", "resp", "*", "QueryResponse", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "resp", ".", "Err", "!=", "nil", "{", "return", "json", ".", "Marshal", "(", "struct", "{", "Err", "string", "`json:\"error\...
// MarshalJSON marshals QueryResponse into a JSON-encoded byte slice
[ "MarshalJSON", "marshals", "QueryResponse", "into", "a", "JSON", "-", "encoded", "byte", "slice" ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/handler.go#L61-L75
train
pilosa/pilosa
pql/parser.go
ParseString
func ParseString(s string) (*Query, error) { return NewParser(strings.NewReader(s)).Parse() }
go
func ParseString(s string) (*Query, error) { return NewParser(strings.NewReader(s)).Parse() }
[ "func", "ParseString", "(", "s", "string", ")", "(", "*", "Query", ",", "error", ")", "{", "return", "NewParser", "(", "strings", ".", "NewReader", "(", "s", ")", ")", ".", "Parse", "(", ")", "\n", "}" ]
// ParseString parses s into a query.
[ "ParseString", "parses", "s", "into", "a", "query", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/pql/parser.go#L48-L50
train
pilosa/pilosa
pql/parser.go
Parse
func (p *parser) Parse() (*Query, error) { buf, err := ioutil.ReadAll(p.r) if err != nil { return nil, errors.Wrap(err, "reading buffer to parse") } p.PQL = PQL{ Buffer: string(buf), } p.Init() err = p.PQL.Parse() if err != nil { return nil, errors.Wrap(err, "parsing") } // Handle specific panics from the parser and return them as errors. var v interface{} func() { defer func() { v = recover() }() p.Execute() }() if v != nil { if strings.HasPrefix(v.(string), duplicateArgErrorMessage) { return nil, fmt.Errorf("%s", v) } else { panic(v) } } return &p.Query, nil }
go
func (p *parser) Parse() (*Query, error) { buf, err := ioutil.ReadAll(p.r) if err != nil { return nil, errors.Wrap(err, "reading buffer to parse") } p.PQL = PQL{ Buffer: string(buf), } p.Init() err = p.PQL.Parse() if err != nil { return nil, errors.Wrap(err, "parsing") } // Handle specific panics from the parser and return them as errors. var v interface{} func() { defer func() { v = recover() }() p.Execute() }() if v != nil { if strings.HasPrefix(v.(string), duplicateArgErrorMessage) { return nil, fmt.Errorf("%s", v) } else { panic(v) } } return &p.Query, nil }
[ "func", "(", "p", "*", "parser", ")", "Parse", "(", ")", "(", "*", "Query", ",", "error", ")", "{", "buf", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "p", ".", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors...
// Parse parses the next node in the query.
[ "Parse", "parses", "the", "next", "node", "in", "the", "query", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/pql/parser.go#L53-L82
train
pilosa/pilosa
http/handler.go
OptHandlerCloseTimeout
func OptHandlerCloseTimeout(d time.Duration) handlerOption { return func(h *Handler) error { h.closeTimeout = d return nil } }
go
func OptHandlerCloseTimeout(d time.Duration) handlerOption { return func(h *Handler) error { h.closeTimeout = d return nil } }
[ "func", "OptHandlerCloseTimeout", "(", "d", "time", ".", "Duration", ")", "handlerOption", "{", "return", "func", "(", "h", "*", "Handler", ")", "error", "{", "h", ".", "closeTimeout", "=", "d", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptHandlerCloseTimeout controls how long to wait for the http Server to // shutdown cleanly before forcibly destroying it. Default is 30 seconds.
[ "OptHandlerCloseTimeout", "controls", "how", "long", "to", "wait", "for", "the", "http", "Server", "to", "shutdown", "cleanly", "before", "forcibly", "destroying", "it", ".", "Default", "is", "30", "seconds", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/handler.go#L114-L119
train
pilosa/pilosa
http/handler.go
NewHandler
func NewHandler(opts ...handlerOption) (*Handler, error) { handler := &Handler{ logger: logger.NopLogger, closeTimeout: time.Second * 30, } handler.Handler = newRouter(handler) handler.populateValidators() for _, opt := range opts { err := opt(handler) if err != nil { return nil, errors.Wrap(err, "applying option") } } if handler.api == nil { return nil, errors.New("must pass OptHandlerAPI") } if handler.ln == nil { return nil, errors.New("must pass OptHandlerListener") } handler.server = &http.Server{Handler: handler} return handler, nil }
go
func NewHandler(opts ...handlerOption) (*Handler, error) { handler := &Handler{ logger: logger.NopLogger, closeTimeout: time.Second * 30, } handler.Handler = newRouter(handler) handler.populateValidators() for _, opt := range opts { err := opt(handler) if err != nil { return nil, errors.Wrap(err, "applying option") } } if handler.api == nil { return nil, errors.New("must pass OptHandlerAPI") } if handler.ln == nil { return nil, errors.New("must pass OptHandlerListener") } handler.server = &http.Server{Handler: handler} return handler, nil }
[ "func", "NewHandler", "(", "opts", "...", "handlerOption", ")", "(", "*", "Handler", ",", "error", ")", "{", "handler", ":=", "&", "Handler", "{", "logger", ":", "logger", ".", "NopLogger", ",", "closeTimeout", ":", "time", ".", "Second", "*", "30", ",...
// NewHandler returns a new instance of Handler with a default logger.
[ "NewHandler", "returns", "a", "new", "instance", "of", "Handler", "with", "a", "default", "logger", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/handler.go#L122-L148
train
pilosa/pilosa
http/handler.go
Close
func (h *Handler) Close() error { deadlineCtx, cancelFunc := context.WithDeadline(context.Background(), time.Now().Add(h.closeTimeout)) defer cancelFunc() err := h.server.Shutdown(deadlineCtx) if err != nil { err = h.server.Close() } return errors.Wrap(err, "shutdown/close http server") }
go
func (h *Handler) Close() error { deadlineCtx, cancelFunc := context.WithDeadline(context.Background(), time.Now().Add(h.closeTimeout)) defer cancelFunc() err := h.server.Shutdown(deadlineCtx) if err != nil { err = h.server.Close() } return errors.Wrap(err, "shutdown/close http server") }
[ "func", "(", "h", "*", "Handler", ")", "Close", "(", ")", "error", "{", "deadlineCtx", ",", "cancelFunc", ":=", "context", ".", "WithDeadline", "(", "context", ".", "Background", "(", ")", ",", "time", ".", "Now", "(", ")", ".", "Add", "(", "h", "....
// Close tries to cleanly shutdown the HTTP server, and failing that, after a // timeout, calls Server.Close.
[ "Close", "tries", "to", "cleanly", "shutdown", "the", "HTTP", "server", "and", "failing", "that", "after", "a", "timeout", "calls", "Server", ".", "Close", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/handler.go#L161-L169
train
pilosa/pilosa
http/handler.go
ServeHTTP
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { defer func() { if err := recover(); err != nil { w.WriteHeader(http.StatusInternalServerError) stack := debug.Stack() msg := "PANIC: %s\n%s" h.logger.Printf(msg, err, stack) fmt.Fprintf(w, msg, err, stack) } }() t := time.Now() h.Handler.ServeHTTP(w, r) dif := time.Since(t) // Calculate per request StatsD metrics when the handler is fully configured. statsTags := make([]string, 0, 3) longQueryTime := h.api.LongQueryTime() if longQueryTime > 0 && dif > longQueryTime { h.logger.Printf("%s %s %v", r.Method, r.URL.String(), dif) statsTags = append(statsTags, "slow_query") } pathParts := strings.Split(r.URL.Path, "/") endpointName := strings.Join(pathParts, "_") if externalPrefixFlag[pathParts[1]] { statsTags = append(statsTags, "external") } // useragent tag identifies internal/external endpoints statsTags = append(statsTags, "useragent:"+r.UserAgent()) stats := h.api.StatsWithTags(statsTags) if stats != nil { stats.Histogram("http."+endpointName, float64(dif), 0.1) } }
go
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { defer func() { if err := recover(); err != nil { w.WriteHeader(http.StatusInternalServerError) stack := debug.Stack() msg := "PANIC: %s\n%s" h.logger.Printf(msg, err, stack) fmt.Fprintf(w, msg, err, stack) } }() t := time.Now() h.Handler.ServeHTTP(w, r) dif := time.Since(t) // Calculate per request StatsD metrics when the handler is fully configured. statsTags := make([]string, 0, 3) longQueryTime := h.api.LongQueryTime() if longQueryTime > 0 && dif > longQueryTime { h.logger.Printf("%s %s %v", r.Method, r.URL.String(), dif) statsTags = append(statsTags, "slow_query") } pathParts := strings.Split(r.URL.Path, "/") endpointName := strings.Join(pathParts, "_") if externalPrefixFlag[pathParts[1]] { statsTags = append(statsTags, "external") } // useragent tag identifies internal/external endpoints statsTags = append(statsTags, "useragent:"+r.UserAgent()) stats := h.api.StatsWithTags(statsTags) if stats != nil { stats.Histogram("http."+endpointName, float64(dif), 0.1) } }
[ "func", "(", "h", "*", "Handler", ")", "ServeHTTP", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "defer", "func", "(", ")", "{", "if", "err", ":=", "recover", "(", ")", ";", "err", "!=", "nil", "{", ...
// ServeHTTP handles an HTTP request.
[ "ServeHTTP", "handles", "an", "HTTP", "request", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/handler.go#L284-L321
train
pilosa/pilosa
http/handler.go
check
func (r *successResponse) check(err error) (statusCode int) { if err == nil { r.Success = true return 0 } cause := errors.Cause(err) // Determine HTTP status code based on the error type. switch cause.(type) { case pilosa.BadRequestError: statusCode = http.StatusBadRequest case pilosa.ConflictError: statusCode = http.StatusConflict case pilosa.NotFoundError: statusCode = http.StatusNotFound default: statusCode = http.StatusInternalServerError } r.Success = false r.Error = &Error{Message: err.Error()} return statusCode }
go
func (r *successResponse) check(err error) (statusCode int) { if err == nil { r.Success = true return 0 } cause := errors.Cause(err) // Determine HTTP status code based on the error type. switch cause.(type) { case pilosa.BadRequestError: statusCode = http.StatusBadRequest case pilosa.ConflictError: statusCode = http.StatusConflict case pilosa.NotFoundError: statusCode = http.StatusNotFound default: statusCode = http.StatusInternalServerError } r.Success = false r.Error = &Error{Message: err.Error()} return statusCode }
[ "func", "(", "r", "*", "successResponse", ")", "check", "(", "err", "error", ")", "(", "statusCode", "int", ")", "{", "if", "err", "==", "nil", "{", "r", ".", "Success", "=", "true", "\n", "return", "0", "\n", "}", "\n", "cause", ":=", "errors", ...
// check determines success or failure based on the error. // It also returns the corresponding http status code.
[ "check", "determines", "success", "or", "failure", "based", "on", "the", "error", ".", "It", "also", "returns", "the", "corresponding", "http", "status", "code", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/handler.go#L332-L356
train
pilosa/pilosa
http/handler.go
write
func (r *successResponse) write(w http.ResponseWriter, err error) { // Apply the error and get the status code. statusCode := r.check(err) // Marshal the json response. msg, err := json.Marshal(r) if err != nil { http.Error(w, string(msg), http.StatusInternalServerError) return } // Write the response. if statusCode == 0 { _, err := w.Write(msg) if err != nil { r.h.logger.Printf("error writing response: %v", err) http.Error(w, string(msg), http.StatusInternalServerError) return } _, err = w.Write([]byte("\n")) if err != nil { r.h.logger.Printf("error writing newline after response: %v", err) http.Error(w, string(msg), http.StatusInternalServerError) return } } else { http.Error(w, string(msg), statusCode) } }
go
func (r *successResponse) write(w http.ResponseWriter, err error) { // Apply the error and get the status code. statusCode := r.check(err) // Marshal the json response. msg, err := json.Marshal(r) if err != nil { http.Error(w, string(msg), http.StatusInternalServerError) return } // Write the response. if statusCode == 0 { _, err := w.Write(msg) if err != nil { r.h.logger.Printf("error writing response: %v", err) http.Error(w, string(msg), http.StatusInternalServerError) return } _, err = w.Write([]byte("\n")) if err != nil { r.h.logger.Printf("error writing newline after response: %v", err) http.Error(w, string(msg), http.StatusInternalServerError) return } } else { http.Error(w, string(msg), statusCode) } }
[ "func", "(", "r", "*", "successResponse", ")", "write", "(", "w", "http", ".", "ResponseWriter", ",", "err", "error", ")", "{", "statusCode", ":=", "r", ".", "check", "(", "err", ")", "\n", "msg", ",", "err", ":=", "json", ".", "Marshal", "(", "r",...
// write sends a response to the http.ResponseWriter based on the success // status and the error.
[ "write", "sends", "a", "response", "to", "the", "http", ".", "ResponseWriter", "based", "on", "the", "success", "status", "and", "the", "error", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/handler.go#L360-L388
train
pilosa/pilosa
http/handler.go
UnmarshalJSON
func (p *postIndexRequest) UnmarshalJSON(b []byte) error { // m is an overflow map used to capture additional, unexpected keys. m := make(map[string]interface{}) if err := json.Unmarshal(b, &m); err != nil { return errors.Wrap(err, "unmarshalling unexpected values") } validIndexOptions := getValidOptions(pilosa.IndexOptions{}) err := validateOptions(m, validIndexOptions) if err != nil { return err } // Unmarshal expected values. _p := _postIndexRequest{ Options: pilosa.IndexOptions{ Keys: false, TrackExistence: true, }, } if err := json.Unmarshal(b, &_p); err != nil { return errors.Wrap(err, "unmarshalling expected values") } p.Options = _p.Options return nil }
go
func (p *postIndexRequest) UnmarshalJSON(b []byte) error { // m is an overflow map used to capture additional, unexpected keys. m := make(map[string]interface{}) if err := json.Unmarshal(b, &m); err != nil { return errors.Wrap(err, "unmarshalling unexpected values") } validIndexOptions := getValidOptions(pilosa.IndexOptions{}) err := validateOptions(m, validIndexOptions) if err != nil { return err } // Unmarshal expected values. _p := _postIndexRequest{ Options: pilosa.IndexOptions{ Keys: false, TrackExistence: true, }, } if err := json.Unmarshal(b, &_p); err != nil { return errors.Wrap(err, "unmarshalling expected values") } p.Options = _p.Options return nil }
[ "func", "(", "p", "*", "postIndexRequest", ")", "UnmarshalJSON", "(", "b", "[", "]", "byte", ")", "error", "{", "m", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", ...
// Custom Unmarshal JSON to validate request body when creating a new index.
[ "Custom", "Unmarshal", "JSON", "to", "validate", "request", "body", "when", "creating", "a", "new", "index", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/handler.go#L576-L603
train
pilosa/pilosa
http/handler.go
validateOptions
func validateOptions(data map[string]interface{}, validIndexOptions []string) error { for k, v := range data { switch k { case "options": options, ok := v.(map[string]interface{}) if !ok { return errors.New("options is not map[string]interface{}") } for kk, vv := range options { if !foundItem(validIndexOptions, kk) { return fmt.Errorf("unknown key: %v:%v", kk, vv) } } default: return fmt.Errorf("unknown key: %v:%v", k, v) } } return nil }
go
func validateOptions(data map[string]interface{}, validIndexOptions []string) error { for k, v := range data { switch k { case "options": options, ok := v.(map[string]interface{}) if !ok { return errors.New("options is not map[string]interface{}") } for kk, vv := range options { if !foundItem(validIndexOptions, kk) { return fmt.Errorf("unknown key: %v:%v", kk, vv) } } default: return fmt.Errorf("unknown key: %v:%v", k, v) } } return nil }
[ "func", "validateOptions", "(", "data", "map", "[", "string", "]", "interface", "{", "}", ",", "validIndexOptions", "[", "]", "string", ")", "error", "{", "for", "k", ",", "v", ":=", "range", "data", "{", "switch", "k", "{", "case", "\"options\"", ":",...
// Raise errors for any unknown key
[ "Raise", "errors", "for", "any", "unknown", "key" ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/handler.go#L617-L635
train
pilosa/pilosa
http/handler.go
readQueryRequest
func (h *Handler) readQueryRequest(r *http.Request) (*pilosa.QueryRequest, error) { switch r.Header.Get("Content-Type") { case "application/x-protobuf": return h.readProtobufQueryRequest(r) default: return h.readURLQueryRequest(r) } }
go
func (h *Handler) readQueryRequest(r *http.Request) (*pilosa.QueryRequest, error) { switch r.Header.Get("Content-Type") { case "application/x-protobuf": return h.readProtobufQueryRequest(r) default: return h.readURLQueryRequest(r) } }
[ "func", "(", "h", "*", "Handler", ")", "readQueryRequest", "(", "r", "*", "http", ".", "Request", ")", "(", "*", "pilosa", ".", "QueryRequest", ",", "error", ")", "{", "switch", "r", ".", "Header", ".", "Get", "(", "\"Content-Type\"", ")", "{", "case...
// readQueryRequest parses an query parameters from r.
[ "readQueryRequest", "parses", "an", "query", "parameters", "from", "r", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/handler.go#L955-L962
train
pilosa/pilosa
http/handler.go
readProtobufQueryRequest
func (h *Handler) readProtobufQueryRequest(r *http.Request) (*pilosa.QueryRequest, error) { // Slurp the body. body, err := ioutil.ReadAll(r.Body) if err != nil { return nil, errors.Wrap(err, "reading") } qreq := &pilosa.QueryRequest{} err = h.api.Serializer.Unmarshal(body, qreq) if err != nil { return nil, errors.Wrap(err, "unmarshalling query request") } return qreq, nil }
go
func (h *Handler) readProtobufQueryRequest(r *http.Request) (*pilosa.QueryRequest, error) { // Slurp the body. body, err := ioutil.ReadAll(r.Body) if err != nil { return nil, errors.Wrap(err, "reading") } qreq := &pilosa.QueryRequest{} err = h.api.Serializer.Unmarshal(body, qreq) if err != nil { return nil, errors.Wrap(err, "unmarshalling query request") } return qreq, nil }
[ "func", "(", "h", "*", "Handler", ")", "readProtobufQueryRequest", "(", "r", "*", "http", ".", "Request", ")", "(", "*", "pilosa", ".", "QueryRequest", ",", "error", ")", "{", "body", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ".", "Body",...
// readProtobufQueryRequest parses query parameters in protobuf from r.
[ "readProtobufQueryRequest", "parses", "query", "parameters", "in", "protobuf", "from", "r", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/handler.go#L965-L978
train
pilosa/pilosa
http/handler.go
readURLQueryRequest
func (h *Handler) readURLQueryRequest(r *http.Request) (*pilosa.QueryRequest, error) { q := r.URL.Query() // Parse query string. buf, err := ioutil.ReadAll(r.Body) if err != nil { return nil, errors.Wrap(err, "reading") } query := string(buf) // Parse list of shards. shards, err := parseUint64Slice(q.Get("shards")) if err != nil { return nil, errors.New("invalid shard argument") } return &pilosa.QueryRequest{ Query: query, Shards: shards, ColumnAttrs: q.Get("columnAttrs") == "true", ExcludeRowAttrs: q.Get("excludeRowAttrs") == "true", ExcludeColumns: q.Get("excludeColumns") == "true", }, nil }
go
func (h *Handler) readURLQueryRequest(r *http.Request) (*pilosa.QueryRequest, error) { q := r.URL.Query() // Parse query string. buf, err := ioutil.ReadAll(r.Body) if err != nil { return nil, errors.Wrap(err, "reading") } query := string(buf) // Parse list of shards. shards, err := parseUint64Slice(q.Get("shards")) if err != nil { return nil, errors.New("invalid shard argument") } return &pilosa.QueryRequest{ Query: query, Shards: shards, ColumnAttrs: q.Get("columnAttrs") == "true", ExcludeRowAttrs: q.Get("excludeRowAttrs") == "true", ExcludeColumns: q.Get("excludeColumns") == "true", }, nil }
[ "func", "(", "h", "*", "Handler", ")", "readURLQueryRequest", "(", "r", "*", "http", ".", "Request", ")", "(", "*", "pilosa", ".", "QueryRequest", ",", "error", ")", "{", "q", ":=", "r", ".", "URL", ".", "Query", "(", ")", "\n", "buf", ",", "err"...
// readURLQueryRequest parses query parameters from URL parameters from r.
[ "readURLQueryRequest", "parses", "query", "parameters", "from", "URL", "parameters", "from", "r", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/handler.go#L981-L1004
train
pilosa/pilosa
http/handler.go
writeQueryResponse
func (h *Handler) writeQueryResponse(w http.ResponseWriter, r *http.Request, resp *pilosa.QueryResponse) error { if !validHeaderAcceptJSON(r.Header) { w.Header().Set("Content-Type", "application/protobuf") return h.writeProtobufQueryResponse(w, resp) } w.Header().Set("Content-Type", "application/json") return h.writeJSONQueryResponse(w, resp) }
go
func (h *Handler) writeQueryResponse(w http.ResponseWriter, r *http.Request, resp *pilosa.QueryResponse) error { if !validHeaderAcceptJSON(r.Header) { w.Header().Set("Content-Type", "application/protobuf") return h.writeProtobufQueryResponse(w, resp) } w.Header().Set("Content-Type", "application/json") return h.writeJSONQueryResponse(w, resp) }
[ "func", "(", "h", "*", "Handler", ")", "writeQueryResponse", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "resp", "*", "pilosa", ".", "QueryResponse", ")", "error", "{", "if", "!", "validHeaderAcceptJSON", "(", "r"...
// writeQueryResponse writes the response from the executor to w.
[ "writeQueryResponse", "writes", "the", "response", "from", "the", "executor", "to", "w", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/handler.go#L1007-L1014
train
pilosa/pilosa
http/handler.go
writeProtobufQueryResponse
func (h *Handler) writeProtobufQueryResponse(w io.Writer, resp *pilosa.QueryResponse) error { if buf, err := h.api.Serializer.Marshal(resp); err != nil { return errors.Wrap(err, "marshalling") } else if _, err := w.Write(buf); err != nil { return errors.Wrap(err, "writing") } return nil }
go
func (h *Handler) writeProtobufQueryResponse(w io.Writer, resp *pilosa.QueryResponse) error { if buf, err := h.api.Serializer.Marshal(resp); err != nil { return errors.Wrap(err, "marshalling") } else if _, err := w.Write(buf); err != nil { return errors.Wrap(err, "writing") } return nil }
[ "func", "(", "h", "*", "Handler", ")", "writeProtobufQueryResponse", "(", "w", "io", ".", "Writer", ",", "resp", "*", "pilosa", ".", "QueryResponse", ")", "error", "{", "if", "buf", ",", "err", ":=", "h", ".", "api", ".", "Serializer", ".", "Marshal", ...
// writeProtobufQueryResponse writes the response from the executor to w as protobuf.
[ "writeProtobufQueryResponse", "writes", "the", "response", "from", "the", "executor", "to", "w", "as", "protobuf", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/handler.go#L1017-L1024
train
pilosa/pilosa
http/handler.go
writeJSONQueryResponse
func (h *Handler) writeJSONQueryResponse(w io.Writer, resp *pilosa.QueryResponse) error { return json.NewEncoder(w).Encode(resp) }
go
func (h *Handler) writeJSONQueryResponse(w io.Writer, resp *pilosa.QueryResponse) error { return json.NewEncoder(w).Encode(resp) }
[ "func", "(", "h", "*", "Handler", ")", "writeJSONQueryResponse", "(", "w", "io", ".", "Writer", ",", "resp", "*", "pilosa", ".", "QueryResponse", ")", "error", "{", "return", "json", ".", "NewEncoder", "(", "w", ")", ".", "Encode", "(", "resp", ")", ...
// writeJSONQueryResponse writes the response from the executor to w as JSON.
[ "writeJSONQueryResponse", "writes", "the", "response", "from", "the", "executor", "to", "w", "as", "JSON", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/handler.go#L1027-L1029
train
pilosa/pilosa
http/handler.go
parseUint64Slice
func parseUint64Slice(s string) ([]uint64, error) { var a []uint64 for _, str := range strings.Split(s, ",") { // Ignore blanks. if str == "" { continue } // Parse number. num, err := strconv.ParseUint(str, 10, 64) if err != nil { return nil, errors.Wrap(err, "parsing int") } a = append(a, num) } return a, nil }
go
func parseUint64Slice(s string) ([]uint64, error) { var a []uint64 for _, str := range strings.Split(s, ",") { // Ignore blanks. if str == "" { continue } // Parse number. num, err := strconv.ParseUint(str, 10, 64) if err != nil { return nil, errors.Wrap(err, "parsing int") } a = append(a, num) } return a, nil }
[ "func", "parseUint64Slice", "(", "s", "string", ")", "(", "[", "]", "uint64", ",", "error", ")", "{", "var", "a", "[", "]", "uint64", "\n", "for", "_", ",", "str", ":=", "range", "strings", ".", "Split", "(", "s", ",", "\",\"", ")", "{", "if", ...
// parseUint64Slice returns a slice of uint64s from a comma-delimited string.
[ "parseUint64Slice", "returns", "a", "slice", "of", "uint64s", "from", "a", "comma", "-", "delimited", "string", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/handler.go#L1312-L1328
train
pilosa/pilosa
http/translator.go
TranslateColumnsToUint64
func (s *translateStore) TranslateColumnsToUint64(index string, values []string) ([]uint64, error) { return nil, pilosa.ErrNotImplemented }
go
func (s *translateStore) TranslateColumnsToUint64(index string, values []string) ([]uint64, error) { return nil, pilosa.ErrNotImplemented }
[ "func", "(", "s", "*", "translateStore", ")", "TranslateColumnsToUint64", "(", "index", "string", ",", "values", "[", "]", "string", ")", "(", "[", "]", "uint64", ",", "error", ")", "{", "return", "nil", ",", "pilosa", ".", "ErrNotImplemented", "\n", "}"...
// TranslateColumnsToUint64 is not currently implemented.
[ "TranslateColumnsToUint64", "is", "not", "currently", "implemented", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/translator.go#L64-L66
train
pilosa/pilosa
http/translator.go
TranslateColumnToString
func (s *translateStore) TranslateColumnToString(index string, values uint64) (string, error) { return "", pilosa.ErrNotImplemented }
go
func (s *translateStore) TranslateColumnToString(index string, values uint64) (string, error) { return "", pilosa.ErrNotImplemented }
[ "func", "(", "s", "*", "translateStore", ")", "TranslateColumnToString", "(", "index", "string", ",", "values", "uint64", ")", "(", "string", ",", "error", ")", "{", "return", "\"\"", ",", "pilosa", ".", "ErrNotImplemented", "\n", "}" ]
// TranslateColumnToString is not currently implemented.
[ "TranslateColumnToString", "is", "not", "currently", "implemented", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/translator.go#L69-L71
train
pilosa/pilosa
http/translator.go
TranslateRowsToUint64
func (s *translateStore) TranslateRowsToUint64(index, frame string, values []string) ([]uint64, error) { return nil, pilosa.ErrNotImplemented }
go
func (s *translateStore) TranslateRowsToUint64(index, frame string, values []string) ([]uint64, error) { return nil, pilosa.ErrNotImplemented }
[ "func", "(", "s", "*", "translateStore", ")", "TranslateRowsToUint64", "(", "index", ",", "frame", "string", ",", "values", "[", "]", "string", ")", "(", "[", "]", "uint64", ",", "error", ")", "{", "return", "nil", ",", "pilosa", ".", "ErrNotImplemented"...
// TranslateRowsToUint64 is not currently implemented.
[ "TranslateRowsToUint64", "is", "not", "currently", "implemented", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/translator.go#L74-L76
train
pilosa/pilosa
http/translator.go
TranslateRowToString
func (s *translateStore) TranslateRowToString(index, frame string, values uint64) (string, error) { return "", pilosa.ErrNotImplemented }
go
func (s *translateStore) TranslateRowToString(index, frame string, values uint64) (string, error) { return "", pilosa.ErrNotImplemented }
[ "func", "(", "s", "*", "translateStore", ")", "TranslateRowToString", "(", "index", ",", "frame", "string", ",", "values", "uint64", ")", "(", "string", ",", "error", ")", "{", "return", "\"\"", ",", "pilosa", ".", "ErrNotImplemented", "\n", "}" ]
// TranslateRowToString is not currently implemented.
[ "TranslateRowToString", "is", "not", "currently", "implemented", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/translator.go#L79-L81
train
pilosa/pilosa
http/translator.go
Reader
func (s *translateStore) Reader(ctx context.Context, off int64) (io.ReadCloser, error) { // Generate remote URL. u, err := url.Parse(s.node.URI.String()) if err != nil { return nil, err } u.Path = "/internal/translate/data" u.RawQuery = (url.Values{ "offset": {strconv.FormatInt(off, 10)}, }).Encode() // Connect a stream to the remote server. req, err := http.NewRequest("GET", u.String(), nil) if err != nil { return nil, err } req = req.WithContext(ctx) // Connect a stream to the remote server. resp, err := http.DefaultClient.Do(req) if err != nil { return nil, fmt.Errorf("http: cannot connect to translate store endpoint: %s", err) } // Handle error codes or return body as stream. switch resp.StatusCode { case http.StatusOK: return resp.Body, nil case http.StatusNotImplemented: resp.Body.Close() return nil, pilosa.ErrNotImplemented default: body, _ := ioutil.ReadAll(resp.Body) resp.Body.Close() return nil, fmt.Errorf("http: invalid translate store endpoint status: code=%d url=%s body=%q", resp.StatusCode, u.String(), bytes.TrimSpace(body)) } }
go
func (s *translateStore) Reader(ctx context.Context, off int64) (io.ReadCloser, error) { // Generate remote URL. u, err := url.Parse(s.node.URI.String()) if err != nil { return nil, err } u.Path = "/internal/translate/data" u.RawQuery = (url.Values{ "offset": {strconv.FormatInt(off, 10)}, }).Encode() // Connect a stream to the remote server. req, err := http.NewRequest("GET", u.String(), nil) if err != nil { return nil, err } req = req.WithContext(ctx) // Connect a stream to the remote server. resp, err := http.DefaultClient.Do(req) if err != nil { return nil, fmt.Errorf("http: cannot connect to translate store endpoint: %s", err) } // Handle error codes or return body as stream. switch resp.StatusCode { case http.StatusOK: return resp.Body, nil case http.StatusNotImplemented: resp.Body.Close() return nil, pilosa.ErrNotImplemented default: body, _ := ioutil.ReadAll(resp.Body) resp.Body.Close() return nil, fmt.Errorf("http: invalid translate store endpoint status: code=%d url=%s body=%q", resp.StatusCode, u.String(), bytes.TrimSpace(body)) } }
[ "func", "(", "s", "*", "translateStore", ")", "Reader", "(", "ctx", "context", ".", "Context", ",", "off", "int64", ")", "(", "io", ".", "ReadCloser", ",", "error", ")", "{", "u", ",", "err", ":=", "url", ".", "Parse", "(", "s", ".", "node", ".",...
// Reader returns a reader that can stream data from a remote store.
[ "Reader", "returns", "a", "reader", "that", "can", "stream", "data", "from", "a", "remote", "store", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/translator.go#L84-L120
train
pilosa/pilosa
gossip/gossip.go
Open
func (g *memberSet) Open() (err error) { g.mu.Lock() g.memberlist, err = memberlist.Create(g.config.memberlistConfig) g.mu.Unlock() if err != nil { return errors.Wrap(err, "creating memberlist") } g.broadcasts = &memberlist.TransmitLimitedQueue{ NumNodes: func() int { g.mu.RLock() defer g.mu.RUnlock() return g.memberlist.NumMembers() }, RetransmitMult: 3, } var uris = make([]*pilosa.URI, len(g.config.gossipSeeds)) for i, addr := range g.config.gossipSeeds { uris[i], err = pilosa.NewURIFromAddress(addr) if err != nil { return fmt.Errorf("new uri from address: %s", err) } } var nodes = make([]*pilosa.Node, len(uris)) for i, uri := range uris { nodes[i] = &pilosa.Node{URI: *uri} } g.mu.RLock() err = g.joinWithRetry(pilosa.URIs(pilosa.Nodes(nodes).URIs()).HostPortStrings()) g.mu.RUnlock() if err != nil { return errors.Wrap(err, "joinWithRetry") } return nil }
go
func (g *memberSet) Open() (err error) { g.mu.Lock() g.memberlist, err = memberlist.Create(g.config.memberlistConfig) g.mu.Unlock() if err != nil { return errors.Wrap(err, "creating memberlist") } g.broadcasts = &memberlist.TransmitLimitedQueue{ NumNodes: func() int { g.mu.RLock() defer g.mu.RUnlock() return g.memberlist.NumMembers() }, RetransmitMult: 3, } var uris = make([]*pilosa.URI, len(g.config.gossipSeeds)) for i, addr := range g.config.gossipSeeds { uris[i], err = pilosa.NewURIFromAddress(addr) if err != nil { return fmt.Errorf("new uri from address: %s", err) } } var nodes = make([]*pilosa.Node, len(uris)) for i, uri := range uris { nodes[i] = &pilosa.Node{URI: *uri} } g.mu.RLock() err = g.joinWithRetry(pilosa.URIs(pilosa.Nodes(nodes).URIs()).HostPortStrings()) g.mu.RUnlock() if err != nil { return errors.Wrap(err, "joinWithRetry") } return nil }
[ "func", "(", "g", "*", "memberSet", ")", "Open", "(", ")", "(", "err", "error", ")", "{", "g", ".", "mu", ".", "Lock", "(", ")", "\n", "g", ".", "memberlist", ",", "err", "=", "memberlist", ".", "Create", "(", "g", ".", "config", ".", "memberli...
// Open implements the MemberSet interface to start network activity.
[ "Open", "implements", "the", "MemberSet", "interface", "to", "start", "network", "activity", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/gossip/gossip.go#L65-L102
train
pilosa/pilosa
gossip/gossip.go
joinWithRetry
func (g *memberSet) joinWithRetry(hosts []string) error { err := retry(60, 2*time.Second, func() error { _, err := g.memberlist.Join(hosts) return err }) return err }
go
func (g *memberSet) joinWithRetry(hosts []string) error { err := retry(60, 2*time.Second, func() error { _, err := g.memberlist.Join(hosts) return err }) return err }
[ "func", "(", "g", "*", "memberSet", ")", "joinWithRetry", "(", "hosts", "[", "]", "string", ")", "error", "{", "err", ":=", "retry", "(", "60", ",", "2", "*", "time", ".", "Second", ",", "func", "(", ")", "error", "{", "_", ",", "err", ":=", "g...
// joinWithRetry wraps the standard memberlist Join function in a retry.
[ "joinWithRetry", "wraps", "the", "standard", "memberlist", "Join", "function", "in", "a", "retry", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/gossip/gossip.go#L116-L122
train
pilosa/pilosa
gossip/gossip.go
retry
func retry(attempts int, sleep time.Duration, fn func() error) (err error) { // nolint: unparam for i := 0; ; i++ { err = fn() if err == nil { return } if i >= (attempts - 1) { break } time.Sleep(sleep) log.Println("retrying after error:", err) } return fmt.Errorf("after %d attempts, last error: %s", attempts, err) }
go
func retry(attempts int, sleep time.Duration, fn func() error) (err error) { // nolint: unparam for i := 0; ; i++ { err = fn() if err == nil { return } if i >= (attempts - 1) { break } time.Sleep(sleep) log.Println("retrying after error:", err) } return fmt.Errorf("after %d attempts, last error: %s", attempts, err) }
[ "func", "retry", "(", "attempts", "int", ",", "sleep", "time", ".", "Duration", ",", "fn", "func", "(", ")", "error", ")", "(", "err", "error", ")", "{", "for", "i", ":=", "0", ";", ";", "i", "++", "{", "err", "=", "fn", "(", ")", "\n", "if",...
// retry periodically retries function fn a specified number of attempts.
[ "retry", "periodically", "retries", "function", "fn", "a", "specified", "number", "of", "attempts", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/gossip/gossip.go#L125-L138
train
pilosa/pilosa
gossip/gossip.go
WithTransport
func WithTransport(transport *Transport) memberSetOption { return func(g *memberSet) error { g.transport = transport return nil } }
go
func WithTransport(transport *Transport) memberSetOption { return func(g *memberSet) error { g.transport = transport return nil } }
[ "func", "WithTransport", "(", "transport", "*", "Transport", ")", "memberSetOption", "{", "return", "func", "(", "g", "*", "memberSet", ")", "error", "{", "g", ".", "transport", "=", "transport", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// WithTransport is a functional option for providing a transport to NewMemberSet.
[ "WithTransport", "is", "a", "functional", "option", "for", "providing", "a", "transport", "to", "NewMemberSet", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/gossip/gossip.go#L151-L156
train
pilosa/pilosa
gossip/gossip.go
WithLogOutput
func WithLogOutput(o io.Writer) memberSetOption { return func(g *memberSet) error { g.logOutput = o return nil } }
go
func WithLogOutput(o io.Writer) memberSetOption { return func(g *memberSet) error { g.logOutput = o return nil } }
[ "func", "WithLogOutput", "(", "o", "io", ".", "Writer", ")", "memberSetOption", "{", "return", "func", "(", "g", "*", "memberSet", ")", "error", "{", "g", ".", "logOutput", "=", "o", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// WithLogOutput allows one to pass a Writer which will in turn be passed to // memberlist for use in logging.
[ "WithLogOutput", "allows", "one", "to", "pass", "a", "Writer", "which", "will", "in", "turn", "be", "passed", "to", "memberlist", "for", "use", "in", "logging", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/gossip/gossip.go#L172-L177
train
pilosa/pilosa
gossip/gossip.go
WithPilosaLogger
func WithPilosaLogger(l logger.Logger) memberSetOption { return func(g *memberSet) error { g.Logger = l return nil } }
go
func WithPilosaLogger(l logger.Logger) memberSetOption { return func(g *memberSet) error { g.Logger = l return nil } }
[ "func", "WithPilosaLogger", "(", "l", "logger", ".", "Logger", ")", "memberSetOption", "{", "return", "func", "(", "g", "*", "memberSet", ")", "error", "{", "g", ".", "Logger", "=", "l", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// WithPilosaLogger allows one to configure a memberSet with a logger of their // choice which satisfies the pilosa logger interface.
[ "WithPilosaLogger", "allows", "one", "to", "configure", "a", "memberSet", "with", "a", "logger", "of", "their", "choice", "which", "satisfies", "the", "pilosa", "logger", "interface", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/gossip/gossip.go#L181-L186
train
pilosa/pilosa
gossip/gossip.go
NodeMeta
func (g *memberSet) NodeMeta(limit int) []byte { buf, err := g.papi.Serializer.Marshal(g.papi.Node()) if err != nil { g.Logger.Printf("marshal message error: %s", err) return []byte{} } return buf }
go
func (g *memberSet) NodeMeta(limit int) []byte { buf, err := g.papi.Serializer.Marshal(g.papi.Node()) if err != nil { g.Logger.Printf("marshal message error: %s", err) return []byte{} } return buf }
[ "func", "(", "g", "*", "memberSet", ")", "NodeMeta", "(", "limit", "int", ")", "[", "]", "byte", "{", "buf", ",", "err", ":=", "g", ".", "papi", ".", "Serializer", ".", "Marshal", "(", "g", ".", "papi", ".", "Node", "(", ")", ")", "\n", "if", ...
// NodeMeta implementation of the memberlist.Delegate interface.
[ "NodeMeta", "implementation", "of", "the", "memberlist", ".", "Delegate", "interface", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/gossip/gossip.go#L295-L302
train
pilosa/pilosa
gossip/gossip.go
NotifyMsg
func (g *memberSet) NotifyMsg(b []byte) { err := g.papi.ClusterMessage(context.Background(), bytes.NewBuffer(b)) if err != nil { g.Logger.Printf("cluster message error: %s", err) } }
go
func (g *memberSet) NotifyMsg(b []byte) { err := g.papi.ClusterMessage(context.Background(), bytes.NewBuffer(b)) if err != nil { g.Logger.Printf("cluster message error: %s", err) } }
[ "func", "(", "g", "*", "memberSet", ")", "NotifyMsg", "(", "b", "[", "]", "byte", ")", "{", "err", ":=", "g", ".", "papi", ".", "ClusterMessage", "(", "context", ".", "Background", "(", ")", ",", "bytes", ".", "NewBuffer", "(", "b", ")", ")", "\n...
// NotifyMsg implementation of the memberlist.Delegate interface // called when a user-data message is received.
[ "NotifyMsg", "implementation", "of", "the", "memberlist", ".", "Delegate", "interface", "called", "when", "a", "user", "-", "data", "message", "is", "received", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/gossip/gossip.go#L306-L311
train
pilosa/pilosa
gossip/gossip.go
GetBroadcasts
func (g *memberSet) GetBroadcasts(overhead, limit int) [][]byte { return g.broadcasts.GetBroadcasts(overhead, limit) }
go
func (g *memberSet) GetBroadcasts(overhead, limit int) [][]byte { return g.broadcasts.GetBroadcasts(overhead, limit) }
[ "func", "(", "g", "*", "memberSet", ")", "GetBroadcasts", "(", "overhead", ",", "limit", "int", ")", "[", "]", "[", "]", "byte", "{", "return", "g", ".", "broadcasts", ".", "GetBroadcasts", "(", "overhead", ",", "limit", ")", "\n", "}" ]
// GetBroadcasts implementation of the memberlist.Delegate interface // called when user data messages can be broadcast.
[ "GetBroadcasts", "implementation", "of", "the", "memberlist", ".", "Delegate", "interface", "called", "when", "user", "data", "messages", "can", "be", "broadcast", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/gossip/gossip.go#L315-L317
train
pilosa/pilosa
gossip/gossip.go
LocalState
func (g *memberSet) LocalState(join bool) []byte { m := &pilosa.NodeStatus{ Node: g.papi.Node(), Schema: &pilosa.Schema{Indexes: g.papi.Schema(context.Background())}, } for _, idx := range m.Schema.Indexes { is := &pilosa.IndexStatus{Name: idx.Name} for _, f := range idx.Fields { availableShards := roaring.NewBitmap() if field, _ := g.papi.Field(context.Background(), idx.Name, f.Name); field != nil { availableShards = field.AvailableShards() } is.Fields = append(is.Fields, &pilosa.FieldStatus{ Name: f.Name, AvailableShards: availableShards, }) } m.Indexes = append(m.Indexes, is) } // Marshal nodestate data to bytes. buf, err := pilosa.MarshalInternalMessage(m, g.papi.Serializer) if err != nil { g.Logger.Printf("error marshalling nodestate data, err=%s", err) return []byte{} } return buf }
go
func (g *memberSet) LocalState(join bool) []byte { m := &pilosa.NodeStatus{ Node: g.papi.Node(), Schema: &pilosa.Schema{Indexes: g.papi.Schema(context.Background())}, } for _, idx := range m.Schema.Indexes { is := &pilosa.IndexStatus{Name: idx.Name} for _, f := range idx.Fields { availableShards := roaring.NewBitmap() if field, _ := g.papi.Field(context.Background(), idx.Name, f.Name); field != nil { availableShards = field.AvailableShards() } is.Fields = append(is.Fields, &pilosa.FieldStatus{ Name: f.Name, AvailableShards: availableShards, }) } m.Indexes = append(m.Indexes, is) } // Marshal nodestate data to bytes. buf, err := pilosa.MarshalInternalMessage(m, g.papi.Serializer) if err != nil { g.Logger.Printf("error marshalling nodestate data, err=%s", err) return []byte{} } return buf }
[ "func", "(", "g", "*", "memberSet", ")", "LocalState", "(", "join", "bool", ")", "[", "]", "byte", "{", "m", ":=", "&", "pilosa", ".", "NodeStatus", "{", "Node", ":", "g", ".", "papi", ".", "Node", "(", ")", ",", "Schema", ":", "&", "pilosa", "...
// LocalState implementation of the memberlist.Delegate interface // sends this Node's state data.
[ "LocalState", "implementation", "of", "the", "memberlist", ".", "Delegate", "interface", "sends", "this", "Node", "s", "state", "data", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/gossip/gossip.go#L321-L348
train
pilosa/pilosa
gossip/gossip.go
MergeRemoteState
func (g *memberSet) MergeRemoteState(buf []byte, join bool) { err := g.papi.ClusterMessage(context.Background(), bytes.NewBuffer(buf)) if err != nil { g.Logger.Printf("merge state error: %s", err) } }
go
func (g *memberSet) MergeRemoteState(buf []byte, join bool) { err := g.papi.ClusterMessage(context.Background(), bytes.NewBuffer(buf)) if err != nil { g.Logger.Printf("merge state error: %s", err) } }
[ "func", "(", "g", "*", "memberSet", ")", "MergeRemoteState", "(", "buf", "[", "]", "byte", ",", "join", "bool", ")", "{", "err", ":=", "g", ".", "papi", ".", "ClusterMessage", "(", "context", ".", "Background", "(", ")", ",", "bytes", ".", "NewBuffer...
// MergeRemoteState implementation of the memberlist.Delegate interface // receive and process the remote side's LocalState.
[ "MergeRemoteState", "implementation", "of", "the", "memberlist", ".", "Delegate", "interface", "receive", "and", "process", "the", "remote", "side", "s", "LocalState", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/gossip/gossip.go#L352-L357
train
pilosa/pilosa
gossip/gossip.go
newEventReceiver
func newEventReceiver(logger logger.Logger, papi *pilosa.API) *eventReceiver { ger := &eventReceiver{ ch: make(chan memberlist.NodeEvent, 1), logger: logger, papi: papi, } go ger.listen() return ger }
go
func newEventReceiver(logger logger.Logger, papi *pilosa.API) *eventReceiver { ger := &eventReceiver{ ch: make(chan memberlist.NodeEvent, 1), logger: logger, papi: papi, } go ger.listen() return ger }
[ "func", "newEventReceiver", "(", "logger", "logger", ".", "Logger", ",", "papi", "*", "pilosa", ".", "API", ")", "*", "eventReceiver", "{", "ger", ":=", "&", "eventReceiver", "{", "ch", ":", "make", "(", "chan", "memberlist", ".", "NodeEvent", ",", "1", ...
// newEventReceiver returns a new instance of GossipEventReceiver.
[ "newEventReceiver", "returns", "a", "new", "instance", "of", "GossipEventReceiver", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/gossip/gossip.go#L372-L380
train
pilosa/pilosa
gossip/gossip.go
newTransport
func newTransport(conf *memberlist.Config) (*memberlist.NetTransport, error) { nc := &memberlist.NetTransportConfig{ BindAddrs: []string{conf.BindAddr}, BindPort: conf.BindPort, Logger: conf.Logger, } // See comment below for details about the retry in here. makeNetRetry := func(limit int) (*memberlist.NetTransport, error) { var err error for try := 0; try < limit; try++ { var nt *memberlist.NetTransport if nt, err = memberlist.NewNetTransport(nc); err == nil { return nt, nil } if strings.Contains(err.Error(), "address already in use") { conf.Logger.Printf("[DEBUG] Got bind error: %v", err) continue } } return nil, fmt.Errorf("failed to obtain an address: %v", err) } // The dynamic bind port operation is inherently racy because // even though we are using the kernel to find a port for us, we // are attempting to bind multiple protocols (and potentially // multiple addresses) with the same port number. We build in a // few retries here since this often gets transient errors in // busy unit tests. limit := 1 if conf.BindPort == 0 { limit = 10 } nt, err := makeNetRetry(limit) if err != nil { return nil, errors.Wrap(err, "could not set up network transport") } return nt, nil }
go
func newTransport(conf *memberlist.Config) (*memberlist.NetTransport, error) { nc := &memberlist.NetTransportConfig{ BindAddrs: []string{conf.BindAddr}, BindPort: conf.BindPort, Logger: conf.Logger, } // See comment below for details about the retry in here. makeNetRetry := func(limit int) (*memberlist.NetTransport, error) { var err error for try := 0; try < limit; try++ { var nt *memberlist.NetTransport if nt, err = memberlist.NewNetTransport(nc); err == nil { return nt, nil } if strings.Contains(err.Error(), "address already in use") { conf.Logger.Printf("[DEBUG] Got bind error: %v", err) continue } } return nil, fmt.Errorf("failed to obtain an address: %v", err) } // The dynamic bind port operation is inherently racy because // even though we are using the kernel to find a port for us, we // are attempting to bind multiple protocols (and potentially // multiple addresses) with the same port number. We build in a // few retries here since this often gets transient errors in // busy unit tests. limit := 1 if conf.BindPort == 0 { limit = 10 } nt, err := makeNetRetry(limit) if err != nil { return nil, errors.Wrap(err, "could not set up network transport") } return nt, nil }
[ "func", "newTransport", "(", "conf", "*", "memberlist", ".", "Config", ")", "(", "*", "memberlist", ".", "NetTransport", ",", "error", ")", "{", "nc", ":=", "&", "memberlist", ".", "NetTransportConfig", "{", "BindAddrs", ":", "[", "]", "string", "{", "co...
// newTransport returns a NetTransport based on the memberlist configuration. // It will dynamically bind to a port if conf.BindPort is 0.
[ "newTransport", "returns", "a", "NetTransport", "based", "on", "the", "memberlist", "configuration", ".", "It", "will", "dynamically", "bind", "to", "a", "port", "if", "conf", ".", "BindPort", "is", "0", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/gossip/gossip.go#L481-L522
train
pilosa/pilosa
pilosa.go
MarshalJSON
func (cas ColumnAttrSet) MarshalJSON() ([]byte, error) { if cas.Key != "" { return json.Marshal(struct { Key string `json:"key,omitempty"` Attrs map[string]interface{} `json:"attrs,omitempty"` }{ Key: cas.Key, Attrs: cas.Attrs, }) } return json.Marshal(struct { ID uint64 `json:"id"` Attrs map[string]interface{} `json:"attrs,omitempty"` }{ ID: cas.ID, Attrs: cas.Attrs, }) }
go
func (cas ColumnAttrSet) MarshalJSON() ([]byte, error) { if cas.Key != "" { return json.Marshal(struct { Key string `json:"key,omitempty"` Attrs map[string]interface{} `json:"attrs,omitempty"` }{ Key: cas.Key, Attrs: cas.Attrs, }) } return json.Marshal(struct { ID uint64 `json:"id"` Attrs map[string]interface{} `json:"attrs,omitempty"` }{ ID: cas.ID, Attrs: cas.Attrs, }) }
[ "func", "(", "cas", "ColumnAttrSet", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "cas", ".", "Key", "!=", "\"\"", "{", "return", "json", ".", "Marshal", "(", "struct", "{", "Key", "string", "`json:\"key,omitempty\...
// MarshalJSON marshals the ColumnAttrSet to JSON such that // either a Key or an ID is included.
[ "MarshalJSON", "marshals", "the", "ColumnAttrSet", "to", "JSON", "such", "that", "either", "a", "Key", "or", "an", "ID", "is", "included", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/pilosa.go#L133-L150
train
pilosa/pilosa
pilosa.go
validateName
func validateName(name string) error { if !nameRegexp.Match([]byte(name)) { return errors.Wrapf(ErrName, "'%s'", name) } return nil }
go
func validateName(name string) error { if !nameRegexp.Match([]byte(name)) { return errors.Wrapf(ErrName, "'%s'", name) } return nil }
[ "func", "validateName", "(", "name", "string", ")", "error", "{", "if", "!", "nameRegexp", ".", "Match", "(", "[", "]", "byte", "(", "name", ")", ")", "{", "return", "errors", ".", "Wrapf", "(", "ErrName", ",", "\"'%s'\"", ",", "name", ")", "\n", "...
// validateName ensures that the name is a valid format.
[ "validateName", "ensures", "that", "the", "name", "is", "a", "valid", "format", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/pilosa.go#L156-L161
train
pilosa/pilosa
pilosa.go
AddressWithDefaults
func AddressWithDefaults(addr string) (*URI, error) { if addr == "" { return defaultURI(), nil } return NewURIFromAddress(addr) }
go
func AddressWithDefaults(addr string) (*URI, error) { if addr == "" { return defaultURI(), nil } return NewURIFromAddress(addr) }
[ "func", "AddressWithDefaults", "(", "addr", "string", ")", "(", "*", "URI", ",", "error", ")", "{", "if", "addr", "==", "\"\"", "{", "return", "defaultURI", "(", ")", ",", "nil", "\n", "}", "\n", "return", "NewURIFromAddress", "(", "addr", ")", "\n", ...
// AddressWithDefaults converts addr into a valid address, // using defaults when necessary.
[ "AddressWithDefaults", "converts", "addr", "into", "a", "valid", "address", "using", "defaults", "when", "necessary", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/pilosa.go#L189-L194
train
pilosa/pilosa
lru/lru.go
clear
func (c *Cache) clear() { // nolint: staticcheck,unused if c.OnEvicted != nil { for _, e := range c.cache { kv := e.Value.(*entry) c.OnEvicted(kv.key, kv.value) } } c.ll = nil c.cache = nil }
go
func (c *Cache) clear() { // nolint: staticcheck,unused if c.OnEvicted != nil { for _, e := range c.cache { kv := e.Value.(*entry) c.OnEvicted(kv.key, kv.value) } } c.ll = nil c.cache = nil }
[ "func", "(", "c", "*", "Cache", ")", "clear", "(", ")", "{", "if", "c", ".", "OnEvicted", "!=", "nil", "{", "for", "_", ",", "e", ":=", "range", "c", ".", "cache", "{", "kv", ":=", "e", ".", "Value", ".", "(", "*", "entry", ")", "\n", "c", ...
// clear purges all stored items from the cache.
[ "clear", "purges", "all", "stored", "items", "from", "the", "cache", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/lru/lru.go#L124-L133
train
pilosa/pilosa
ctl/common.go
SetTLSConfig
func SetTLSConfig(flags *pflag.FlagSet, certificatePath *string, certificateKeyPath *string, skipVerify *bool) { flags.StringVarP(certificatePath, "tls.certificate", "", "", "TLS certificate path (usually has the .crt or .pem extension") flags.StringVarP(certificateKeyPath, "tls.key", "", "", "TLS certificate key path (usually has the .key extension") flags.BoolVarP(skipVerify, "tls.skip-verify", "", false, "Skip TLS certificate verification (not secure)") }
go
func SetTLSConfig(flags *pflag.FlagSet, certificatePath *string, certificateKeyPath *string, skipVerify *bool) { flags.StringVarP(certificatePath, "tls.certificate", "", "", "TLS certificate path (usually has the .crt or .pem extension") flags.StringVarP(certificateKeyPath, "tls.key", "", "", "TLS certificate key path (usually has the .key extension") flags.BoolVarP(skipVerify, "tls.skip-verify", "", false, "Skip TLS certificate verification (not secure)") }
[ "func", "SetTLSConfig", "(", "flags", "*", "pflag", ".", "FlagSet", ",", "certificatePath", "*", "string", ",", "certificateKeyPath", "*", "string", ",", "skipVerify", "*", "bool", ")", "{", "flags", ".", "StringVarP", "(", "certificatePath", ",", "\"tls.certi...
// SetTLSConfig creates common TLS flags
[ "SetTLSConfig", "creates", "common", "TLS", "flags" ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/ctl/common.go#L33-L37
train
pilosa/pilosa
ctl/common.go
commandClient
func commandClient(cmd CommandWithTLSSupport) (*http.InternalClient, error) { tlsConfig := cmd.TLSConfiguration() var TLSConfig *tls.Config if tlsConfig.CertificatePath != "" && tlsConfig.CertificateKeyPath != "" { cert, err := tls.LoadX509KeyPair(tlsConfig.CertificatePath, tlsConfig.CertificateKeyPath) if err != nil { return nil, errors.Wrap(err, "loading keypair") } TLSConfig = &tls.Config{ Certificates: []tls.Certificate{cert}, InsecureSkipVerify: tlsConfig.SkipVerify, } } client, err := http.NewInternalClient(cmd.TLSHost(), http.GetHTTPClient(TLSConfig)) if err != nil { return nil, errors.Wrap(err, "getting internal client") } return client, err }
go
func commandClient(cmd CommandWithTLSSupport) (*http.InternalClient, error) { tlsConfig := cmd.TLSConfiguration() var TLSConfig *tls.Config if tlsConfig.CertificatePath != "" && tlsConfig.CertificateKeyPath != "" { cert, err := tls.LoadX509KeyPair(tlsConfig.CertificatePath, tlsConfig.CertificateKeyPath) if err != nil { return nil, errors.Wrap(err, "loading keypair") } TLSConfig = &tls.Config{ Certificates: []tls.Certificate{cert}, InsecureSkipVerify: tlsConfig.SkipVerify, } } client, err := http.NewInternalClient(cmd.TLSHost(), http.GetHTTPClient(TLSConfig)) if err != nil { return nil, errors.Wrap(err, "getting internal client") } return client, err }
[ "func", "commandClient", "(", "cmd", "CommandWithTLSSupport", ")", "(", "*", "http", ".", "InternalClient", ",", "error", ")", "{", "tlsConfig", ":=", "cmd", ".", "TLSConfiguration", "(", ")", "\n", "var", "TLSConfig", "*", "tls", ".", "Config", "\n", "if"...
// commandClient returns a pilosa.InternalHTTPClient for the command
[ "commandClient", "returns", "a", "pilosa", ".", "InternalHTTPClient", "for", "the", "command" ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/ctl/common.go#L40-L58
train
pilosa/pilosa
cache.go
newLRUCache
func newLRUCache(maxEntries uint32) *lruCache { c := &lruCache{ cache: lru.New(int(maxEntries)), counts: make(map[uint64]uint64), stats: stats.NopStatsClient, } c.cache.OnEvicted = c.onEvicted return c }
go
func newLRUCache(maxEntries uint32) *lruCache { c := &lruCache{ cache: lru.New(int(maxEntries)), counts: make(map[uint64]uint64), stats: stats.NopStatsClient, } c.cache.OnEvicted = c.onEvicted return c }
[ "func", "newLRUCache", "(", "maxEntries", "uint32", ")", "*", "lruCache", "{", "c", ":=", "&", "lruCache", "{", "cache", ":", "lru", ".", "New", "(", "int", "(", "maxEntries", ")", ")", ",", "counts", ":", "make", "(", "map", "[", "uint64", "]", "u...
// newLRUCache returns a new instance of LRUCache.
[ "newLRUCache", "returns", "a", "new", "instance", "of", "LRUCache", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cache.go#L65-L73
train
pilosa/pilosa
cache.go
Top
func (c *lruCache) Top() []bitmapPair { a := make([]bitmapPair, 0, len(c.counts)) for id, n := range c.counts { a = append(a, bitmapPair{ ID: id, Count: n, }) } sort.Sort(bitmapPairs(a)) return a }
go
func (c *lruCache) Top() []bitmapPair { a := make([]bitmapPair, 0, len(c.counts)) for id, n := range c.counts { a = append(a, bitmapPair{ ID: id, Count: n, }) } sort.Sort(bitmapPairs(a)) return a }
[ "func", "(", "c", "*", "lruCache", ")", "Top", "(", ")", "[", "]", "bitmapPair", "{", "a", ":=", "make", "(", "[", "]", "bitmapPair", ",", "0", ",", "len", "(", "c", ".", "counts", ")", ")", "\n", "for", "id", ",", "n", ":=", "range", "c", ...
// Top returns all counts in the cache.
[ "Top", "returns", "all", "counts", "in", "the", "cache", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cache.go#L113-L123
train
pilosa/pilosa
cache.go
NewRankCache
func NewRankCache(maxEntries uint32) *rankCache { return &rankCache{ maxEntries: maxEntries, thresholdBuffer: int(thresholdFactor * float64(maxEntries)), entries: make(map[uint64]uint64), stats: stats.NopStatsClient, } }
go
func NewRankCache(maxEntries uint32) *rankCache { return &rankCache{ maxEntries: maxEntries, thresholdBuffer: int(thresholdFactor * float64(maxEntries)), entries: make(map[uint64]uint64), stats: stats.NopStatsClient, } }
[ "func", "NewRankCache", "(", "maxEntries", "uint32", ")", "*", "rankCache", "{", "return", "&", "rankCache", "{", "maxEntries", ":", "maxEntries", ",", "thresholdBuffer", ":", "int", "(", "thresholdFactor", "*", "float64", "(", "maxEntries", ")", ")", ",", "...
// NewRankCache returns a new instance of RankCache.
[ "NewRankCache", "returns", "a", "new", "instance", "of", "RankCache", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cache.go#L158-L165
train
pilosa/pilosa
cache.go
Invalidate
func (c *rankCache) Invalidate() { c.mu.Lock() defer c.mu.Unlock() c.invalidate() }
go
func (c *rankCache) Invalidate() { c.mu.Lock() defer c.mu.Unlock() c.invalidate() }
[ "func", "(", "c", "*", "rankCache", ")", "Invalidate", "(", ")", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n", "c", ".", "invalidate", "(", ")", "\n", "}" ]
// Invalidate recalculates the entries by rank.
[ "Invalidate", "recalculates", "the", "entries", "by", "rank", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cache.go#L221-L225
train
pilosa/pilosa
cache.go
Recalculate
func (c *rankCache) Recalculate() { c.mu.Lock() defer c.mu.Unlock() c.stats.Count("cache.recalculate", 1, 1.0) c.recalculate() }
go
func (c *rankCache) Recalculate() { c.mu.Lock() defer c.mu.Unlock() c.stats.Count("cache.recalculate", 1, 1.0) c.recalculate() }
[ "func", "(", "c", "*", "rankCache", ")", "Recalculate", "(", ")", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n", "c", ".", "stats", ".", "Count", "(", "\"cache.recalculate\"", ",", "1", ...
// Recalculate rebuilds the cache.
[ "Recalculate", "rebuilds", "the", "cache", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cache.go#L228-L233
train
pilosa/pilosa
cache.go
WriteTo
func (c *rankCache) WriteTo(w io.Writer) (n int64, err error) { panic("FIXME: TODO") }
go
func (c *rankCache) WriteTo(w io.Writer) (n int64, err error) { panic("FIXME: TODO") }
[ "func", "(", "c", "*", "rankCache", ")", "WriteTo", "(", "w", "io", ".", "Writer", ")", "(", "n", "int64", ",", "err", "error", ")", "{", "panic", "(", "\"FIXME: TODO\"", ")", "\n", "}" ]
// WriteTo writes the cache to w.
[ "WriteTo", "writes", "the", "cache", "to", "w", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cache.go#L291-L293
train
pilosa/pilosa
cache.go
ReadFrom
func (c *rankCache) ReadFrom(r io.Reader) (n int64, err error) { panic("FIXME: TODO") }
go
func (c *rankCache) ReadFrom(r io.Reader) (n int64, err error) { panic("FIXME: TODO") }
[ "func", "(", "c", "*", "rankCache", ")", "ReadFrom", "(", "r", "io", ".", "Reader", ")", "(", "n", "int64", ",", "err", "error", ")", "{", "panic", "(", "\"FIXME: TODO\"", ")", "\n", "}" ]
// ReadFrom read from r into the cache.
[ "ReadFrom", "read", "from", "r", "into", "the", "cache", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cache.go#L296-L298
train
pilosa/pilosa
cache.go
Pop
func (p *Pairs) Pop() interface{} { old := *p n := len(old) x := old[n-1] *p = old[0 : n-1] return x }
go
func (p *Pairs) Pop() interface{} { old := *p n := len(old) x := old[n-1] *p = old[0 : n-1] return x }
[ "func", "(", "p", "*", "Pairs", ")", "Pop", "(", ")", "interface", "{", "}", "{", "old", ":=", "*", "p", "\n", "n", ":=", "len", "(", "old", ")", "\n", "x", ":=", "old", "[", "n", "-", "1", "]", "\n", "*", "p", "=", "old", "[", "0", ":"...
// Pop removes the minimum element from the Pair slice.
[ "Pop", "removes", "the", "minimum", "element", "from", "the", "Pair", "slice", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cache.go#L347-L353
train
pilosa/pilosa
cache.go
Add
func (p Pairs) Add(other []Pair) []Pair { // Create lookup of key/counts. m := make(map[uint64]uint64, len(p)) for _, pair := range p { m[pair.ID] = pair.Count } // Add/merge from other. for _, pair := range other { m[pair.ID] += pair.Count } // Convert back to slice. a := make([]Pair, 0, len(m)) for k, v := range m { a = append(a, Pair{ID: k, Count: v}) } return a }
go
func (p Pairs) Add(other []Pair) []Pair { // Create lookup of key/counts. m := make(map[uint64]uint64, len(p)) for _, pair := range p { m[pair.ID] = pair.Count } // Add/merge from other. for _, pair := range other { m[pair.ID] += pair.Count } // Convert back to slice. a := make([]Pair, 0, len(m)) for k, v := range m { a = append(a, Pair{ID: k, Count: v}) } return a }
[ "func", "(", "p", "Pairs", ")", "Add", "(", "other", "[", "]", "Pair", ")", "[", "]", "Pair", "{", "m", ":=", "make", "(", "map", "[", "uint64", "]", "uint64", ",", "len", "(", "p", ")", ")", "\n", "for", "_", ",", "pair", ":=", "range", "p...
// Add merges other into p and returns a new slice.
[ "Add", "merges", "other", "into", "p", "and", "returns", "a", "new", "slice", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cache.go#L356-L374
train
pilosa/pilosa
cache.go
Keys
func (p Pairs) Keys() []uint64 { a := make([]uint64, len(p)) for i := range p { a[i] = p[i].ID } return a }
go
func (p Pairs) Keys() []uint64 { a := make([]uint64, len(p)) for i := range p { a[i] = p[i].ID } return a }
[ "func", "(", "p", "Pairs", ")", "Keys", "(", ")", "[", "]", "uint64", "{", "a", ":=", "make", "(", "[", "]", "uint64", ",", "len", "(", "p", ")", ")", "\n", "for", "i", ":=", "range", "p", "{", "a", "[", "i", "]", "=", "p", "[", "i", "]...
// Keys returns a slice of all keys in p.
[ "Keys", "returns", "a", "slice", "of", "all", "keys", "in", "p", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cache.go#L377-L383
train
pilosa/pilosa
cache.go
merge
func (p uint64Slice) merge(other []uint64) []uint64 { ret := make([]uint64, 0, len(p)) i, j := 0, 0 for i < len(p) && j < len(other) { a, b := p[i], other[j] if a == b { ret = append(ret, a) i, j = i+1, j+1 } else if a < b { ret = append(ret, a) i++ } else { ret = append(ret, b) j++ } } if i < len(p) { ret = append(ret, p[i:]...) } else if j < len(other) { ret = append(ret, other[j:]...) } return ret }
go
func (p uint64Slice) merge(other []uint64) []uint64 { ret := make([]uint64, 0, len(p)) i, j := 0, 0 for i < len(p) && j < len(other) { a, b := p[i], other[j] if a == b { ret = append(ret, a) i, j = i+1, j+1 } else if a < b { ret = append(ret, a) i++ } else { ret = append(ret, b) j++ } } if i < len(p) { ret = append(ret, p[i:]...) } else if j < len(other) { ret = append(ret, other[j:]...) } return ret }
[ "func", "(", "p", "uint64Slice", ")", "merge", "(", "other", "[", "]", "uint64", ")", "[", "]", "uint64", "{", "ret", ":=", "make", "(", "[", "]", "uint64", ",", "0", ",", "len", "(", "p", ")", ")", "\n", "i", ",", "j", ":=", "0", ",", "0",...
// merge combines p and other to a unique sorted set of values. // p and other must both have unique sets and be sorted.
[ "merge", "combines", "p", "and", "other", "to", "a", "unique", "sorted", "set", "of", "values", ".", "p", "and", "other", "must", "both", "have", "unique", "sets", "and", "be", "sorted", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cache.go#L407-L432
train
pilosa/pilosa
cache.go
Fetch
func (s *simpleCache) Fetch(id uint64) (*Row, bool) { m, ok := s.cache[id] return m, ok }
go
func (s *simpleCache) Fetch(id uint64) (*Row, bool) { m, ok := s.cache[id] return m, ok }
[ "func", "(", "s", "*", "simpleCache", ")", "Fetch", "(", "id", "uint64", ")", "(", "*", "Row", ",", "bool", ")", "{", "m", ",", "ok", ":=", "s", ".", "cache", "[", "id", "]", "\n", "return", "m", ",", "ok", "\n", "}" ]
// Fetch retrieves the bitmap at the id in the cache.
[ "Fetch", "retrieves", "the", "bitmap", "at", "the", "id", "in", "the", "cache", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cache.go#L450-L453
train
pilosa/pilosa
cache.go
Add
func (s *simpleCache) Add(id uint64, b *Row) { s.cache[id] = b }
go
func (s *simpleCache) Add(id uint64, b *Row) { s.cache[id] = b }
[ "func", "(", "s", "*", "simpleCache", ")", "Add", "(", "id", "uint64", ",", "b", "*", "Row", ")", "{", "s", ".", "cache", "[", "id", "]", "=", "b", "\n", "}" ]
// Add adds the bitmap to the cache, keyed on the id.
[ "Add", "adds", "the", "bitmap", "to", "the", "cache", "keyed", "on", "the", "id", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cache.go#L456-L458
train
pilosa/pilosa
cluster.go
Contains
func (a Nodes) Contains(n *Node) bool { for i := range a { if a[i] == n { return true } } return false }
go
func (a Nodes) Contains(n *Node) bool { for i := range a { if a[i] == n { return true } } return false }
[ "func", "(", "a", "Nodes", ")", "Contains", "(", "n", "*", "Node", ")", "bool", "{", "for", "i", ":=", "range", "a", "{", "if", "a", "[", "i", "]", "==", "n", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Contains returns true if a node exists in the list.
[ "Contains", "returns", "true", "if", "a", "node", "exists", "in", "the", "list", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L80-L87
train
pilosa/pilosa
cluster.go
ContainsID
func (a Nodes) ContainsID(id string) bool { for _, n := range a { if n.ID == id { return true } } return false }
go
func (a Nodes) ContainsID(id string) bool { for _, n := range a { if n.ID == id { return true } } return false }
[ "func", "(", "a", "Nodes", ")", "ContainsID", "(", "id", "string", ")", "bool", "{", "for", "_", ",", "n", ":=", "range", "a", "{", "if", "n", ".", "ID", "==", "id", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", ...
// ContainsID returns true if host matches one of the node's id.
[ "ContainsID", "returns", "true", "if", "host", "matches", "one", "of", "the", "node", "s", "id", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L90-L97
train
pilosa/pilosa
cluster.go
Filter
func (a Nodes) Filter(n *Node) []*Node { other := make([]*Node, 0, len(a)) for i := range a { if a[i] != n { other = append(other, a[i]) } } return other }
go
func (a Nodes) Filter(n *Node) []*Node { other := make([]*Node, 0, len(a)) for i := range a { if a[i] != n { other = append(other, a[i]) } } return other }
[ "func", "(", "a", "Nodes", ")", "Filter", "(", "n", "*", "Node", ")", "[", "]", "*", "Node", "{", "other", ":=", "make", "(", "[", "]", "*", "Node", ",", "0", ",", "len", "(", "a", ")", ")", "\n", "for", "i", ":=", "range", "a", "{", "if"...
// Filter returns a new list of nodes with node removed.
[ "Filter", "returns", "a", "new", "list", "of", "nodes", "with", "node", "removed", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L100-L108
train
pilosa/pilosa
cluster.go
FilterID
func (a Nodes) FilterID(id string) []*Node { other := make([]*Node, 0, len(a)) for _, node := range a { if node.ID != id { other = append(other, node) } } return other }
go
func (a Nodes) FilterID(id string) []*Node { other := make([]*Node, 0, len(a)) for _, node := range a { if node.ID != id { other = append(other, node) } } return other }
[ "func", "(", "a", "Nodes", ")", "FilterID", "(", "id", "string", ")", "[", "]", "*", "Node", "{", "other", ":=", "make", "(", "[", "]", "*", "Node", ",", "0", ",", "len", "(", "a", ")", ")", "\n", "for", "_", ",", "node", ":=", "range", "a"...
// FilterID returns a new list of nodes with ID removed.
[ "FilterID", "returns", "a", "new", "list", "of", "nodes", "with", "ID", "removed", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L111-L119
train
pilosa/pilosa
cluster.go
FilterURI
func (a Nodes) FilterURI(uri URI) []*Node { other := make([]*Node, 0, len(a)) for _, node := range a { if node.URI != uri { other = append(other, node) } } return other }
go
func (a Nodes) FilterURI(uri URI) []*Node { other := make([]*Node, 0, len(a)) for _, node := range a { if node.URI != uri { other = append(other, node) } } return other }
[ "func", "(", "a", "Nodes", ")", "FilterURI", "(", "uri", "URI", ")", "[", "]", "*", "Node", "{", "other", ":=", "make", "(", "[", "]", "*", "Node", ",", "0", ",", "len", "(", "a", ")", ")", "\n", "for", "_", ",", "node", ":=", "range", "a",...
// FilterURI returns a new list of nodes with URI removed.
[ "FilterURI", "returns", "a", "new", "list", "of", "nodes", "with", "URI", "removed", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L122-L130
train
pilosa/pilosa
cluster.go
IDs
func (a Nodes) IDs() []string { ids := make([]string, len(a)) for i, n := range a { ids[i] = n.ID } return ids }
go
func (a Nodes) IDs() []string { ids := make([]string, len(a)) for i, n := range a { ids[i] = n.ID } return ids }
[ "func", "(", "a", "Nodes", ")", "IDs", "(", ")", "[", "]", "string", "{", "ids", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "a", ")", ")", "\n", "for", "i", ",", "n", ":=", "range", "a", "{", "ids", "[", "i", "]", "=", "n", ...
// IDs returns a list of all node IDs.
[ "IDs", "returns", "a", "list", "of", "all", "node", "IDs", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L133-L139
train
pilosa/pilosa
cluster.go
URIs
func (a Nodes) URIs() []URI { uris := make([]URI, len(a)) for i, n := range a { uris[i] = n.URI } return uris }
go
func (a Nodes) URIs() []URI { uris := make([]URI, len(a)) for i, n := range a { uris[i] = n.URI } return uris }
[ "func", "(", "a", "Nodes", ")", "URIs", "(", ")", "[", "]", "URI", "{", "uris", ":=", "make", "(", "[", "]", "URI", ",", "len", "(", "a", ")", ")", "\n", "for", "i", ",", "n", ":=", "range", "a", "{", "uris", "[", "i", "]", "=", "n", "....
// URIs returns a list of all uris.
[ "URIs", "returns", "a", "list", "of", "all", "uris", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L142-L148
train
pilosa/pilosa
cluster.go
Clone
func (a Nodes) Clone() []*Node { other := make([]*Node, len(a)) copy(other, a) return other }
go
func (a Nodes) Clone() []*Node { other := make([]*Node, len(a)) copy(other, a) return other }
[ "func", "(", "a", "Nodes", ")", "Clone", "(", ")", "[", "]", "*", "Node", "{", "other", ":=", "make", "(", "[", "]", "*", "Node", ",", "len", "(", "a", ")", ")", "\n", "copy", "(", "other", ",", "a", ")", "\n", "return", "other", "\n", "}" ...
// Clone returns a shallow copy of nodes.
[ "Clone", "returns", "a", "shallow", "copy", "of", "nodes", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L151-L155
train
pilosa/pilosa
cluster.go
newCluster
func newCluster() *cluster { return &cluster{ Hasher: &jmphasher{}, partitionN: defaultPartitionN, ReplicaN: 1, joiningLeavingNodes: make(chan nodeAction, 10), // buffered channel jobs: make(map[int64]*resizeJob), closing: make(chan struct{}), joining: make(chan struct{}), InternalClient: newNopInternalClient(), logger: logger.NopLogger, } }
go
func newCluster() *cluster { return &cluster{ Hasher: &jmphasher{}, partitionN: defaultPartitionN, ReplicaN: 1, joiningLeavingNodes: make(chan nodeAction, 10), // buffered channel jobs: make(map[int64]*resizeJob), closing: make(chan struct{}), joining: make(chan struct{}), InternalClient: newNopInternalClient(), logger: logger.NopLogger, } }
[ "func", "newCluster", "(", ")", "*", "cluster", "{", "return", "&", "cluster", "{", "Hasher", ":", "&", "jmphasher", "{", "}", ",", "partitionN", ":", "defaultPartitionN", ",", "ReplicaN", ":", "1", ",", "joiningLeavingNodes", ":", "make", "(", "chan", "...
// newCluster returns a new instance of Cluster with defaults.
[ "newCluster", "returns", "a", "new", "instance", "of", "Cluster", "with", "defaults", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L227-L242
train
pilosa/pilosa
cluster.go
isCoordinator
func (c *cluster) isCoordinator() bool { c.mu.RLock() defer c.mu.RUnlock() return c.unprotectedIsCoordinator() }
go
func (c *cluster) isCoordinator() bool { c.mu.RLock() defer c.mu.RUnlock() return c.unprotectedIsCoordinator() }
[ "func", "(", "c", "*", "cluster", ")", "isCoordinator", "(", ")", "bool", "{", "c", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "RUnlock", "(", ")", "\n", "return", "c", ".", "unprotectedIsCoordinator", "(", ")", "\n", ...
// isCoordinator is true if this node is the coordinator.
[ "isCoordinator", "is", "true", "if", "this", "node", "is", "the", "coordinator", "." ]
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L283-L287
train
pilosa/pilosa
cluster.go
setCoordinator
func (c *cluster) setCoordinator(n *Node) error { c.mu.Lock() defer c.mu.Unlock() // Verify that the new Coordinator value matches // this node. if c.Node.ID != n.ID { return fmt.Errorf("coordinator node does not match this node") } // Update IsCoordinator on all nodes (locally). _ = c.unprotectedUpdateCoordinator(n) // Send the update coordinator message to all nodes. err := c.unprotectedSendSync( &UpdateCoordinatorMessage{ New: n, }) if err != nil { return fmt.Errorf("problem sending UpdateCoordinator message: %v", err) } // Broadcast cluster status. return c.unprotectedSendSync(c.unprotectedStatus()) }
go
func (c *cluster) setCoordinator(n *Node) error { c.mu.Lock() defer c.mu.Unlock() // Verify that the new Coordinator value matches // this node. if c.Node.ID != n.ID { return fmt.Errorf("coordinator node does not match this node") } // Update IsCoordinator on all nodes (locally). _ = c.unprotectedUpdateCoordinator(n) // Send the update coordinator message to all nodes. err := c.unprotectedSendSync( &UpdateCoordinatorMessage{ New: n, }) if err != nil { return fmt.Errorf("problem sending UpdateCoordinator message: %v", err) } // Broadcast cluster status. return c.unprotectedSendSync(c.unprotectedStatus()) }
[ "func", "(", "c", "*", "cluster", ")", "setCoordinator", "(", "n", "*", "Node", ")", "error", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "c", ".", "Node", ".", "ID", "!=", ...
// setCoordinator tells the current node to become the // Coordinator. In response to this, the current node // will consider itself coordinator and update the other // nodes with its version of Cluster.Status.
[ "setCoordinator", "tells", "the", "current", "node", "to", "become", "the", "Coordinator", ".", "In", "response", "to", "this", "the", "current", "node", "will", "consider", "itself", "coordinator", "and", "update", "the", "other", "nodes", "with", "its", "ver...
67d53f6b48a43f7fe090f48e35518ca8d024747c
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L297-L320
train