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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
awslabs/goformation | cloudformation/resources/aws-efs-filesystem.go | MarshalJSON | func (r AWSEFSFileSystem) MarshalJSON() ([]byte, error) {
type Properties AWSEFSFileSystem
return json.Marshal(&struct {
Type string
Properties Properties
DependsOn []string `json:"DependsOn,omitempty"`
Metadata map[string]interface{} `json:"Metadata,omitempty"`
DeletionPolicy policies.DeletionPolicy `json:"DeletionPolicy,omitempty"`
}{
Type: r.AWSCloudFormationType(),
Properties: (Properties)(r),
DependsOn: r._dependsOn,
Metadata: r._metadata,
DeletionPolicy: r._deletionPolicy,
})
} | go | func (r AWSEFSFileSystem) MarshalJSON() ([]byte, error) {
type Properties AWSEFSFileSystem
return json.Marshal(&struct {
Type string
Properties Properties
DependsOn []string `json:"DependsOn,omitempty"`
Metadata map[string]interface{} `json:"Metadata,omitempty"`
DeletionPolicy policies.DeletionPolicy `json:"DeletionPolicy,omitempty"`
}{
Type: r.AWSCloudFormationType(),
Properties: (Properties)(r),
DependsOn: r._dependsOn,
Metadata: r._metadata,
DeletionPolicy: r._deletionPolicy,
})
} | [
"func",
"(",
"r",
"AWSEFSFileSystem",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"type",
"Properties",
"AWSEFSFileSystem",
"\n",
"return",
"json",
".",
"Marshal",
"(",
"&",
"struct",
"{",
"Type",
"string",
"\n",
"Propert... | // MarshalJSON is a custom JSON marshalling hook that embeds this object into
// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. | [
"MarshalJSON",
"is",
"a",
"custom",
"JSON",
"marshalling",
"hook",
"that",
"embeds",
"this",
"object",
"into",
"an",
"AWS",
"CloudFormation",
"JSON",
"resource",
"s",
"Properties",
"field",
"and",
"adds",
"a",
"Type",
"."
] | 8898b813a27809556420fcf0427a32765a567302 | https://github.com/awslabs/goformation/blob/8898b813a27809556420fcf0427a32765a567302/cloudformation/resources/aws-efs-filesystem.go#L91-L106 | train |
awslabs/goformation | cloudformation/resources/aws-efs-filesystem.go | UnmarshalJSON | func (r *AWSEFSFileSystem) UnmarshalJSON(b []byte) error {
type Properties AWSEFSFileSystem
res := &struct {
Type string
Properties *Properties
DependsOn []string
Metadata map[string]interface{}
}{}
dec := json.NewDecoder(bytes.NewReader(b))
dec.DisallowUnknownFields() // Force error if unknown field is found
if err := dec.Decode(&res); err != nil {
fmt.Printf("ERROR: %s\n", err)
return err
}
// If the resource has no Properties set, it could be nil
if res.Properties != nil {
*r = AWSEFSFileSystem(*res.Properties)
}
if res.DependsOn != nil {
r._dependsOn = res.DependsOn
}
if res.Metadata != nil {
r._metadata = res.Metadata
}
return nil
} | go | func (r *AWSEFSFileSystem) UnmarshalJSON(b []byte) error {
type Properties AWSEFSFileSystem
res := &struct {
Type string
Properties *Properties
DependsOn []string
Metadata map[string]interface{}
}{}
dec := json.NewDecoder(bytes.NewReader(b))
dec.DisallowUnknownFields() // Force error if unknown field is found
if err := dec.Decode(&res); err != nil {
fmt.Printf("ERROR: %s\n", err)
return err
}
// If the resource has no Properties set, it could be nil
if res.Properties != nil {
*r = AWSEFSFileSystem(*res.Properties)
}
if res.DependsOn != nil {
r._dependsOn = res.DependsOn
}
if res.Metadata != nil {
r._metadata = res.Metadata
}
return nil
} | [
"func",
"(",
"r",
"*",
"AWSEFSFileSystem",
")",
"UnmarshalJSON",
"(",
"b",
"[",
"]",
"byte",
")",
"error",
"{",
"type",
"Properties",
"AWSEFSFileSystem",
"\n",
"res",
":=",
"&",
"struct",
"{",
"Type",
"string",
"\n",
"Properties",
"*",
"Properties",
"\n",
... | // UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer
// AWS CloudFormation resource object, and just keeps the 'Properties' field. | [
"UnmarshalJSON",
"is",
"a",
"custom",
"JSON",
"unmarshalling",
"hook",
"that",
"strips",
"the",
"outer",
"AWS",
"CloudFormation",
"resource",
"object",
"and",
"just",
"keeps",
"the",
"Properties",
"field",
"."
] | 8898b813a27809556420fcf0427a32765a567302 | https://github.com/awslabs/goformation/blob/8898b813a27809556420fcf0427a32765a567302/cloudformation/resources/aws-efs-filesystem.go#L110-L139 | train |
awslabs/goformation | intrinsics/conditions.go | condition | func condition(name string, input interface{}, template interface{}, options *ProcessorOptions) interface{} {
if v, ok := input.(string); ok {
if v, ok := retrieveCondition(input, template); ok {
return v
}
if c := getCondition(v, template); c != nil {
res := search(c, template, options)
// replace the value in the template so the value can be reused
setCondition(v, res, template)
return res
}
}
return nil
} | go | func condition(name string, input interface{}, template interface{}, options *ProcessorOptions) interface{} {
if v, ok := input.(string); ok {
if v, ok := retrieveCondition(input, template); ok {
return v
}
if c := getCondition(v, template); c != nil {
res := search(c, template, options)
// replace the value in the template so the value can be reused
setCondition(v, res, template)
return res
}
}
return nil
} | [
"func",
"condition",
"(",
"name",
"string",
",",
"input",
"interface",
"{",
"}",
",",
"template",
"interface",
"{",
"}",
",",
"options",
"*",
"ProcessorOptions",
")",
"interface",
"{",
"}",
"{",
"if",
"v",
",",
"ok",
":=",
"input",
".",
"(",
"string",
... | // condition evaluates a condition | [
"condition",
"evaluates",
"a",
"condition"
] | 8898b813a27809556420fcf0427a32765a567302 | https://github.com/awslabs/goformation/blob/8898b813a27809556420fcf0427a32765a567302/intrinsics/conditions.go#L4-L21 | train |
awslabs/goformation | intrinsics/fnsub.go | Sub | func Sub(value string) string {
i := `{ "Fn::Sub" : "` + value + `" }`
return base64.StdEncoding.EncodeToString([]byte(i))
} | go | func Sub(value string) string {
i := `{ "Fn::Sub" : "` + value + `" }`
return base64.StdEncoding.EncodeToString([]byte(i))
} | [
"func",
"Sub",
"(",
"value",
"string",
")",
"string",
"{",
"i",
":=",
"`{ \"Fn::Sub\" : \"`",
"+",
"value",
"+",
"`\" }`",
"\n",
"return",
"base64",
".",
"StdEncoding",
".",
"EncodeToString",
"(",
"[",
"]",
"byte",
"(",
"i",
")",
")",
"\n",
"}"
] | // NewSub substitutes variables in an input string with values that you specify. In your templates, you can use this function to construct commands or outputs that include values that aren't available until you create or update a stack. | [
"NewSub",
"substitutes",
"variables",
"in",
"an",
"input",
"string",
"with",
"values",
"that",
"you",
"specify",
".",
"In",
"your",
"templates",
"you",
"can",
"use",
"this",
"function",
"to",
"construct",
"commands",
"or",
"outputs",
"that",
"include",
"values... | 8898b813a27809556420fcf0427a32765a567302 | https://github.com/awslabs/goformation/blob/8898b813a27809556420fcf0427a32765a567302/intrinsics/fnsub.go#L70-L73 | train |
awslabs/goformation | generate/generate.go | Generate | func (rg *ResourceGenerator) Generate() error {
// Process the primary template first, since the primary template resources
// are added to the JSON schema for fragment transform specs
fmt.Printf("Downloading cloudformation specification from %s\n", rg.primaryUrl)
primaryData, err := rg.downloadSpec(rg.primaryUrl)
if err != nil {
return err
}
primarySpec, err := rg.processSpec("cloudformation", primaryData)
if err != nil {
return err
}
if err := rg.generateJSONSchema("cloudformation", primarySpec); err != nil {
return err
}
for name, url := range rg.fragmentUrls {
fmt.Printf("Downloading %s specification from %s\n", name, url)
data, err := rg.downloadSpec(url)
if err != nil {
return err
}
spec, err := rg.processSpec(name, data)
if err != nil {
return err
}
// Append main CloudFormation schema resource types and property types to this fragment
for k, v := range primarySpec.Resources {
spec.Resources[k] = v
}
for k, v := range primarySpec.Properties {
spec.Properties[k] = v
}
if err := rg.generateJSONSchema(name, spec); err != nil {
return err
}
}
if err := rg.generateAllResourcesMap(rg.Results.AllResources); err != nil {
return err
}
return nil
} | go | func (rg *ResourceGenerator) Generate() error {
// Process the primary template first, since the primary template resources
// are added to the JSON schema for fragment transform specs
fmt.Printf("Downloading cloudformation specification from %s\n", rg.primaryUrl)
primaryData, err := rg.downloadSpec(rg.primaryUrl)
if err != nil {
return err
}
primarySpec, err := rg.processSpec("cloudformation", primaryData)
if err != nil {
return err
}
if err := rg.generateJSONSchema("cloudformation", primarySpec); err != nil {
return err
}
for name, url := range rg.fragmentUrls {
fmt.Printf("Downloading %s specification from %s\n", name, url)
data, err := rg.downloadSpec(url)
if err != nil {
return err
}
spec, err := rg.processSpec(name, data)
if err != nil {
return err
}
// Append main CloudFormation schema resource types and property types to this fragment
for k, v := range primarySpec.Resources {
spec.Resources[k] = v
}
for k, v := range primarySpec.Properties {
spec.Properties[k] = v
}
if err := rg.generateJSONSchema(name, spec); err != nil {
return err
}
}
if err := rg.generateAllResourcesMap(rg.Results.AllResources); err != nil {
return err
}
return nil
} | [
"func",
"(",
"rg",
"*",
"ResourceGenerator",
")",
"Generate",
"(",
")",
"error",
"{",
"fmt",
".",
"Printf",
"(",
"\"Downloading cloudformation specification from %s\\n\"",
",",
"\\n",
")",
"\n",
"rg",
".",
"primaryUrl",
"\n",
"primaryData",
",",
"err",
":=",
"... | // Generate generates Go structs and a JSON Schema from the AWS CloudFormation
// Resource Specifications provided to NewResourceGenerator | [
"Generate",
"generates",
"Go",
"structs",
"and",
"a",
"JSON",
"Schema",
"from",
"the",
"AWS",
"CloudFormation",
"Resource",
"Specifications",
"provided",
"to",
"NewResourceGenerator"
] | 8898b813a27809556420fcf0427a32765a567302 | https://github.com/awslabs/goformation/blob/8898b813a27809556420fcf0427a32765a567302/generate/generate.go#L71-L115 | train |
awslabs/goformation | cloudformation/intrinsics.go | FindInMap | func FindInMap(mapName, topLevelKey, secondLevelKey interface{}) string {
return encode(fmt.Sprintf(`{ "Fn::FindInMap" : [ "%v", "%v", "%v" ] }`, mapName, topLevelKey, secondLevelKey))
} | go | func FindInMap(mapName, topLevelKey, secondLevelKey interface{}) string {
return encode(fmt.Sprintf(`{ "Fn::FindInMap" : [ "%v", "%v", "%v" ] }`, mapName, topLevelKey, secondLevelKey))
} | [
"func",
"FindInMap",
"(",
"mapName",
",",
"topLevelKey",
",",
"secondLevelKey",
"interface",
"{",
"}",
")",
"string",
"{",
"return",
"encode",
"(",
"fmt",
".",
"Sprintf",
"(",
"`{ \"Fn::FindInMap\" : [ \"%v\", \"%v\", \"%v\" ] }`",
",",
"mapName",
",",
"topLevelKey"... | // FindInMap returns the value corresponding to keys in a two-level map that is declared in the Mappings section. | [
"FindInMap",
"returns",
"the",
"value",
"corresponding",
"to",
"keys",
"in",
"a",
"two",
"-",
"level",
"map",
"that",
"is",
"declared",
"in",
"the",
"Mappings",
"section",
"."
] | 8898b813a27809556420fcf0427a32765a567302 | https://github.com/awslabs/goformation/blob/8898b813a27809556420fcf0427a32765a567302/cloudformation/intrinsics.go#L141-L143 | train |
awslabs/goformation | cloudformation/intrinsics.go | Select | func Select(index interface{}, list []string) string {
return encode(fmt.Sprintf(`{ "Fn::Select": [ "%v", [ "%v" ] ] }`, index, strings.Trim(strings.Join(list, `", "`), `, "`)))
} | go | func Select(index interface{}, list []string) string {
return encode(fmt.Sprintf(`{ "Fn::Select": [ "%v", [ "%v" ] ] }`, index, strings.Trim(strings.Join(list, `", "`), `, "`)))
} | [
"func",
"Select",
"(",
"index",
"interface",
"{",
"}",
",",
"list",
"[",
"]",
"string",
")",
"string",
"{",
"return",
"encode",
"(",
"fmt",
".",
"Sprintf",
"(",
"`{ \"Fn::Select\": [ \"%v\", [ \"%v\" ] ] }`",
",",
"index",
",",
"strings",
".",
"Trim",
"(",
... | // Select returns a single object from a list of objects by index. | [
"Select",
"returns",
"a",
"single",
"object",
"from",
"a",
"list",
"of",
"objects",
"by",
"index",
"."
] | 8898b813a27809556420fcf0427a32765a567302 | https://github.com/awslabs/goformation/blob/8898b813a27809556420fcf0427a32765a567302/cloudformation/intrinsics.go#L158-L160 | train |
grafana/metrictank | idx/memory/partitioned_idx.go | Init | func (p *PartitionedMemoryIdx) Init() error {
for _, m := range p.Partition {
err := m.Init()
if err != nil {
return err
}
}
return nil
} | go | func (p *PartitionedMemoryIdx) Init() error {
for _, m := range p.Partition {
err := m.Init()
if err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"p",
"*",
"PartitionedMemoryIdx",
")",
"Init",
"(",
")",
"error",
"{",
"for",
"_",
",",
"m",
":=",
"range",
"p",
".",
"Partition",
"{",
"err",
":=",
"m",
".",
"Init",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
... | // Init initializes the index at startup and
// blocks until the index is ready for use. | [
"Init",
"initializes",
"the",
"index",
"at",
"startup",
"and",
"blocks",
"until",
"the",
"index",
"is",
"ready",
"for",
"use",
"."
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/idx/memory/partitioned_idx.go#L35-L43 | train |
grafana/metrictank | idx/memory/partitioned_idx.go | AddOrUpdate | func (p *PartitionedMemoryIdx) AddOrUpdate(mkey schema.MKey, data *schema.MetricData, partition int32) (idx.Archive, int32, bool) {
return p.Partition[partition].AddOrUpdate(mkey, data, partition)
} | go | func (p *PartitionedMemoryIdx) AddOrUpdate(mkey schema.MKey, data *schema.MetricData, partition int32) (idx.Archive, int32, bool) {
return p.Partition[partition].AddOrUpdate(mkey, data, partition)
} | [
"func",
"(",
"p",
"*",
"PartitionedMemoryIdx",
")",
"AddOrUpdate",
"(",
"mkey",
"schema",
".",
"MKey",
",",
"data",
"*",
"schema",
".",
"MetricData",
",",
"partition",
"int32",
")",
"(",
"idx",
".",
"Archive",
",",
"int32",
",",
"bool",
")",
"{",
"retu... | // AddOrUpdate makes sure a metric is known in the index,
// and should be called for every received metric. | [
"AddOrUpdate",
"makes",
"sure",
"a",
"metric",
"is",
"known",
"in",
"the",
"index",
"and",
"should",
"be",
"called",
"for",
"every",
"received",
"metric",
"."
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/idx/memory/partitioned_idx.go#L60-L62 | train |
grafana/metrictank | idx/memory/partitioned_idx.go | Get | func (p *PartitionedMemoryIdx) Get(key schema.MKey) (idx.Archive, bool) {
g, _ := errgroup.WithContext(context.Background())
resultChan := make(chan *idx.Archive, len(p.Partition))
for _, m := range p.Partition {
m := m
g.Go(func() error {
if a, ok := m.Get(key); ok {
resultChan <- &a
}
return nil
})
}
var err atomic.Value
go func() {
if e := g.Wait(); e != nil {
err.Store(e)
}
close(resultChan)
}()
result, ok := <-resultChan
if !ok {
e := err.Load()
if e != nil {
log.Errorf("memory-idx: failed to get Archive with key %v. %s", key, e)
}
return idx.Archive{}, false
}
return *result, true
} | go | func (p *PartitionedMemoryIdx) Get(key schema.MKey) (idx.Archive, bool) {
g, _ := errgroup.WithContext(context.Background())
resultChan := make(chan *idx.Archive, len(p.Partition))
for _, m := range p.Partition {
m := m
g.Go(func() error {
if a, ok := m.Get(key); ok {
resultChan <- &a
}
return nil
})
}
var err atomic.Value
go func() {
if e := g.Wait(); e != nil {
err.Store(e)
}
close(resultChan)
}()
result, ok := <-resultChan
if !ok {
e := err.Load()
if e != nil {
log.Errorf("memory-idx: failed to get Archive with key %v. %s", key, e)
}
return idx.Archive{}, false
}
return *result, true
} | [
"func",
"(",
"p",
"*",
"PartitionedMemoryIdx",
")",
"Get",
"(",
"key",
"schema",
".",
"MKey",
")",
"(",
"idx",
".",
"Archive",
",",
"bool",
")",
"{",
"g",
",",
"_",
":=",
"errgroup",
".",
"WithContext",
"(",
"context",
".",
"Background",
"(",
")",
... | // Get returns the archive for the requested id. | [
"Get",
"returns",
"the",
"archive",
"for",
"the",
"requested",
"id",
"."
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/idx/memory/partitioned_idx.go#L70-L101 | train |
grafana/metrictank | idx/memory/partitioned_idx.go | GetPath | func (p *PartitionedMemoryIdx) GetPath(orgId uint32, path string) []idx.Archive {
g, _ := errgroup.WithContext(context.Background())
result := make([][]idx.Archive, len(p.Partition))
var i int
for _, m := range p.Partition {
pos, m := i, m
g.Go(func() error {
result[pos] = m.GetPath(orgId, path)
return nil
})
i++
}
if err := g.Wait(); err != nil {
log.Errorf("memory-idx: failed to getPath: orgId=%d path=%s. %s", orgId, path, err)
return nil
}
// get our total count, so we can allocate our response in one go.
items := 0
for _, r := range result {
items += len(r)
}
response := make([]idx.Archive, 0, items)
for _, r := range result {
response = append(response, r...)
}
return response
} | go | func (p *PartitionedMemoryIdx) GetPath(orgId uint32, path string) []idx.Archive {
g, _ := errgroup.WithContext(context.Background())
result := make([][]idx.Archive, len(p.Partition))
var i int
for _, m := range p.Partition {
pos, m := i, m
g.Go(func() error {
result[pos] = m.GetPath(orgId, path)
return nil
})
i++
}
if err := g.Wait(); err != nil {
log.Errorf("memory-idx: failed to getPath: orgId=%d path=%s. %s", orgId, path, err)
return nil
}
// get our total count, so we can allocate our response in one go.
items := 0
for _, r := range result {
items += len(r)
}
response := make([]idx.Archive, 0, items)
for _, r := range result {
response = append(response, r...)
}
return response
} | [
"func",
"(",
"p",
"*",
"PartitionedMemoryIdx",
")",
"GetPath",
"(",
"orgId",
"uint32",
",",
"path",
"string",
")",
"[",
"]",
"idx",
".",
"Archive",
"{",
"g",
",",
"_",
":=",
"errgroup",
".",
"WithContext",
"(",
"context",
".",
"Background",
"(",
")",
... | // GetPath returns the archives under the given path. | [
"GetPath",
"returns",
"the",
"archives",
"under",
"the",
"given",
"path",
"."
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/idx/memory/partitioned_idx.go#L104-L131 | train |
grafana/metrictank | idx/memory/partitioned_idx.go | Prune | func (p *PartitionedMemoryIdx) Prune(oldest time.Time) ([]idx.Archive, error) {
// Prune each partition sequentially.
result := []idx.Archive{}
for _, m := range p.Partition {
found, err := m.Prune(oldest)
if err != nil {
return result, err
}
result = append(result, found...)
}
return result, nil
} | go | func (p *PartitionedMemoryIdx) Prune(oldest time.Time) ([]idx.Archive, error) {
// Prune each partition sequentially.
result := []idx.Archive{}
for _, m := range p.Partition {
found, err := m.Prune(oldest)
if err != nil {
return result, err
}
result = append(result, found...)
}
return result, nil
} | [
"func",
"(",
"p",
"*",
"PartitionedMemoryIdx",
")",
"Prune",
"(",
"oldest",
"time",
".",
"Time",
")",
"(",
"[",
"]",
"idx",
".",
"Archive",
",",
"error",
")",
"{",
"result",
":=",
"[",
"]",
"idx",
".",
"Archive",
"{",
"}",
"\n",
"for",
"_",
",",
... | // Prune deletes all metrics that haven't been seen since the given timestamp.
// It returns all Archives deleted and any error encountered. | [
"Prune",
"deletes",
"all",
"metrics",
"that",
"haven",
"t",
"been",
"seen",
"since",
"the",
"given",
"timestamp",
".",
"It",
"returns",
"all",
"Archives",
"deleted",
"and",
"any",
"error",
"encountered",
"."
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/idx/memory/partitioned_idx.go#L259-L270 | train |
grafana/metrictank | idx/memory/partitioned_idx.go | FindTagValues | func (p *PartitionedMemoryIdx) FindTagValues(orgId uint32, tag string, prefix string, expressions []string, from int64, limit uint) ([]string, error) {
g, _ := errgroup.WithContext(context.Background())
result := make([][]string, len(p.Partition))
var i int
for _, m := range p.Partition {
pos, m := i, m
g.Go(func() error {
found, err := m.FindTagValues(orgId, tag, prefix, expressions, from, limit)
if err != nil {
return err
}
result[pos] = found
return nil
})
i++
}
if err := g.Wait(); err != nil {
log.Errorf("memory-idx: failed to FindTagValues: orgId=%d tag=%s prefix=%s expressions=%v from=%d limit=%d. %s", orgId, tag, prefix, expressions, from, limit, err)
return nil, err
}
// merge our results into the unique set of tags
merged := map[string]struct{}{}
for _, tags := range result {
for _, t := range tags {
merged[t] = struct{}{}
}
}
response := make([]string, 0, len(merged))
for tag := range merged {
response = append(response, tag)
}
return response, nil
} | go | func (p *PartitionedMemoryIdx) FindTagValues(orgId uint32, tag string, prefix string, expressions []string, from int64, limit uint) ([]string, error) {
g, _ := errgroup.WithContext(context.Background())
result := make([][]string, len(p.Partition))
var i int
for _, m := range p.Partition {
pos, m := i, m
g.Go(func() error {
found, err := m.FindTagValues(orgId, tag, prefix, expressions, from, limit)
if err != nil {
return err
}
result[pos] = found
return nil
})
i++
}
if err := g.Wait(); err != nil {
log.Errorf("memory-idx: failed to FindTagValues: orgId=%d tag=%s prefix=%s expressions=%v from=%d limit=%d. %s", orgId, tag, prefix, expressions, from, limit, err)
return nil, err
}
// merge our results into the unique set of tags
merged := map[string]struct{}{}
for _, tags := range result {
for _, t := range tags {
merged[t] = struct{}{}
}
}
response := make([]string, 0, len(merged))
for tag := range merged {
response = append(response, tag)
}
return response, nil
} | [
"func",
"(",
"p",
"*",
"PartitionedMemoryIdx",
")",
"FindTagValues",
"(",
"orgId",
"uint32",
",",
"tag",
"string",
",",
"prefix",
"string",
",",
"expressions",
"[",
"]",
"string",
",",
"from",
"int64",
",",
"limit",
"uint",
")",
"(",
"[",
"]",
"string",
... | // FindTagValues generates a list of possible values that could
// complete a given value prefix. It requires a tag to be specified and only values
// of the given tag will be returned. It also accepts additional conditions to
// further narrow down the result set in the format of graphite's tag queries | [
"FindTagValues",
"generates",
"a",
"list",
"of",
"possible",
"values",
"that",
"could",
"complete",
"a",
"given",
"value",
"prefix",
".",
"It",
"requires",
"a",
"tag",
"to",
"be",
"specified",
"and",
"only",
"values",
"of",
"the",
"given",
"tag",
"will",
"... | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/idx/memory/partitioned_idx.go#L402-L436 | train |
grafana/metrictank | idx/memory/partitioned_idx.go | TagDetails | func (p *PartitionedMemoryIdx) TagDetails(orgId uint32, key string, filter string, from int64) (map[string]uint64, error) {
g, _ := errgroup.WithContext(context.Background())
result := make([]map[string]uint64, len(p.Partition))
var i int
for _, m := range p.Partition {
pos, m := i, m
g.Go(func() error {
found, err := m.TagDetails(orgId, key, filter, from)
if err != nil {
return err
}
result[pos] = found
return nil
})
i++
}
if err := g.Wait(); err != nil {
log.Errorf("memory-idx: failed to get TagDetails: orgId=%d key=%s filter=%s from=%d. %s", orgId, key, filter, from, err)
return nil, err
}
// merge our results into the unique set of tags
merged := map[string]uint64{}
for _, tagCounts := range result {
for tag, count := range tagCounts {
merged[tag] = merged[tag] + count
}
}
return merged, nil
} | go | func (p *PartitionedMemoryIdx) TagDetails(orgId uint32, key string, filter string, from int64) (map[string]uint64, error) {
g, _ := errgroup.WithContext(context.Background())
result := make([]map[string]uint64, len(p.Partition))
var i int
for _, m := range p.Partition {
pos, m := i, m
g.Go(func() error {
found, err := m.TagDetails(orgId, key, filter, from)
if err != nil {
return err
}
result[pos] = found
return nil
})
i++
}
if err := g.Wait(); err != nil {
log.Errorf("memory-idx: failed to get TagDetails: orgId=%d key=%s filter=%s from=%d. %s", orgId, key, filter, from, err)
return nil, err
}
// merge our results into the unique set of tags
merged := map[string]uint64{}
for _, tagCounts := range result {
for tag, count := range tagCounts {
merged[tag] = merged[tag] + count
}
}
return merged, nil
} | [
"func",
"(",
"p",
"*",
"PartitionedMemoryIdx",
")",
"TagDetails",
"(",
"orgId",
"uint32",
",",
"key",
"string",
",",
"filter",
"string",
",",
"from",
"int64",
")",
"(",
"map",
"[",
"string",
"]",
"uint64",
",",
"error",
")",
"{",
"g",
",",
"_",
":=",... | // TagDetails returns a list of all values associated with a given tag key in the
// given org. The occurrences of each value is counted and the count is referred to by
// the metric names in the returned map.
// If the third parameter is not "" it will be used as a regular expression to filter
// the values before accounting for them.
// If the fourth parameter is > 0 then only those metrics of which the LastUpdate
// time is >= the from timestamp will be included. | [
"TagDetails",
"returns",
"a",
"list",
"of",
"all",
"values",
"associated",
"with",
"a",
"given",
"tag",
"key",
"in",
"the",
"given",
"org",
".",
"The",
"occurrences",
"of",
"each",
"value",
"is",
"counted",
"and",
"the",
"count",
"is",
"referred",
"to",
... | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/idx/memory/partitioned_idx.go#L445-L475 | train |
grafana/metrictank | expr/parse.go | Parse | func Parse(e string) (*expr, string, error) {
// skip whitespace
for len(e) > 1 && e[0] == ' ' {
e = e[1:]
}
if len(e) == 0 {
return nil, "", ErrMissingExpr
}
if '0' <= e[0] && e[0] <= '9' || e[0] == '-' || e[0] == '+' {
return parseConst(e)
}
if val, ok := strToBool(e); ok {
// 'false' is 5 chars, 'true' is 4
size := 5
if val {
size = 4
}
return &expr{bool: val, str: e[:size], etype: etBool}, e[size:], nil
}
if e[0] == '\'' || e[0] == '"' {
val, e, err := parseString(e)
return &expr{str: val, etype: etString}, e, err
}
name, e := parseName(e)
if name == "" {
return nil, e, ErrMissingArg
}
if e != "" && e[0] == '(' {
for i := range name {
if !isFnChar(name[i]) {
return nil, "", ErrIllegalCharacter
}
}
exp := &expr{str: name, etype: etFunc}
ArgString, posArgs, namedArgs, e, err := parseArgList(e)
exp.argsStr = ArgString
exp.args = posArgs
exp.namedArgs = namedArgs
return exp, e, err
}
return &expr{str: name, etype: etName}, e, nil
} | go | func Parse(e string) (*expr, string, error) {
// skip whitespace
for len(e) > 1 && e[0] == ' ' {
e = e[1:]
}
if len(e) == 0 {
return nil, "", ErrMissingExpr
}
if '0' <= e[0] && e[0] <= '9' || e[0] == '-' || e[0] == '+' {
return parseConst(e)
}
if val, ok := strToBool(e); ok {
// 'false' is 5 chars, 'true' is 4
size := 5
if val {
size = 4
}
return &expr{bool: val, str: e[:size], etype: etBool}, e[size:], nil
}
if e[0] == '\'' || e[0] == '"' {
val, e, err := parseString(e)
return &expr{str: val, etype: etString}, e, err
}
name, e := parseName(e)
if name == "" {
return nil, e, ErrMissingArg
}
if e != "" && e[0] == '(' {
for i := range name {
if !isFnChar(name[i]) {
return nil, "", ErrIllegalCharacter
}
}
exp := &expr{str: name, etype: etFunc}
ArgString, posArgs, namedArgs, e, err := parseArgList(e)
exp.argsStr = ArgString
exp.args = posArgs
exp.namedArgs = namedArgs
return exp, e, err
}
return &expr{str: name, etype: etName}, e, nil
} | [
"func",
"Parse",
"(",
"e",
"string",
")",
"(",
"*",
"expr",
",",
"string",
",",
"error",
")",
"{",
"for",
"len",
"(",
"e",
")",
">",
"1",
"&&",
"e",
"[",
"0",
"]",
"==",
"' '",
"{",
"e",
"=",
"e",
"[",
"1",
":",
"]",
"\n",
"}",
"\n",
"i... | // Parses an expression string and turns it into an expression
// also returns any leftover data that could not be parsed | [
"Parses",
"an",
"expression",
"string",
"and",
"turns",
"it",
"into",
"an",
"expression",
"also",
"returns",
"any",
"leftover",
"data",
"that",
"could",
"not",
"be",
"parsed"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/expr/parse.go#L102-L154 | train |
grafana/metrictank | expr/parse.go | parseArgList | func parseArgList(e string) (string, []*expr, map[string]*expr, string, error) {
var (
posArgs []*expr
namedArgs map[string]*expr
)
if e[0] != '(' {
panic("arg list should start with paren. calling code should have asserted this")
}
ArgString := e[1:]
e = e[1:]
for {
var arg *expr
var err error
arg, e, err = Parse(e)
if err != nil {
return "", nil, nil, e, err
}
if e == "" {
return "", nil, nil, "", ErrMissingComma
}
// we now know we're parsing a key-value pair
// in the future we should probably add validation here that the key
// can't contain otherwise-valid-name chars like {, }, etc
if arg.etype == etName && e[0] == '=' {
e = e[1:]
argCont, eCont, errCont := Parse(e)
if errCont != nil {
return "", nil, nil, eCont, errCont
}
if eCont == "" {
return "", nil, nil, "", ErrMissingComma
}
if argCont.etype != etInt && argCont.etype != etFloat && argCont.etype != etName && argCont.etype != etString && argCont.etype != etBool {
return "", nil, nil, eCont, ErrBadArgumentStr{"int, float, name, bool or string", string(argCont.etype)}
}
if namedArgs == nil {
namedArgs = make(map[string]*expr)
}
namedArgs[arg.str] = argCont
e = eCont
} else {
posArgs = append(posArgs, arg)
}
// after the argument, trim any trailing spaces
for len(e) > 0 && e[0] == ' ' {
e = e[1:]
}
if e[0] == ')' {
return ArgString[:len(ArgString)-len(e)], posArgs, namedArgs, e[1:], nil
}
if e[0] != ',' && e[0] != ' ' {
return "", nil, nil, "", ErrUnexpectedCharacter
}
e = e[1:]
}
} | go | func parseArgList(e string) (string, []*expr, map[string]*expr, string, error) {
var (
posArgs []*expr
namedArgs map[string]*expr
)
if e[0] != '(' {
panic("arg list should start with paren. calling code should have asserted this")
}
ArgString := e[1:]
e = e[1:]
for {
var arg *expr
var err error
arg, e, err = Parse(e)
if err != nil {
return "", nil, nil, e, err
}
if e == "" {
return "", nil, nil, "", ErrMissingComma
}
// we now know we're parsing a key-value pair
// in the future we should probably add validation here that the key
// can't contain otherwise-valid-name chars like {, }, etc
if arg.etype == etName && e[0] == '=' {
e = e[1:]
argCont, eCont, errCont := Parse(e)
if errCont != nil {
return "", nil, nil, eCont, errCont
}
if eCont == "" {
return "", nil, nil, "", ErrMissingComma
}
if argCont.etype != etInt && argCont.etype != etFloat && argCont.etype != etName && argCont.etype != etString && argCont.etype != etBool {
return "", nil, nil, eCont, ErrBadArgumentStr{"int, float, name, bool or string", string(argCont.etype)}
}
if namedArgs == nil {
namedArgs = make(map[string]*expr)
}
namedArgs[arg.str] = argCont
e = eCont
} else {
posArgs = append(posArgs, arg)
}
// after the argument, trim any trailing spaces
for len(e) > 0 && e[0] == ' ' {
e = e[1:]
}
if e[0] == ')' {
return ArgString[:len(ArgString)-len(e)], posArgs, namedArgs, e[1:], nil
}
if e[0] != ',' && e[0] != ' ' {
return "", nil, nil, "", ErrUnexpectedCharacter
}
e = e[1:]
}
} | [
"func",
"parseArgList",
"(",
"e",
"string",
")",
"(",
"string",
",",
"[",
"]",
"*",
"expr",
",",
"map",
"[",
"string",
"]",
"*",
"expr",
",",
"string",
",",
"error",
")",
"{",
"var",
"(",
"posArgs",
"[",
"]",
"*",
"expr",
"\n",
"namedArgs",
"map"... | // caller must assure s starts with opening paren | [
"caller",
"must",
"assure",
"s",
"starts",
"with",
"opening",
"paren"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/expr/parse.go#L169-L240 | train |
grafana/metrictank | expr/parse.go | parseString | func parseString(s string) (string, string, error) {
if s[0] != '\'' && s[0] != '"' {
panic("string should start with open quote. calling code should have asserted this")
}
match := s[0]
s = s[1:]
var i int
for i < len(s) && s[i] != match {
i++
}
if i == len(s) {
return "", "", ErrMissingQuote
}
return s[:i], s[i+1:], nil
} | go | func parseString(s string) (string, string, error) {
if s[0] != '\'' && s[0] != '"' {
panic("string should start with open quote. calling code should have asserted this")
}
match := s[0]
s = s[1:]
var i int
for i < len(s) && s[i] != match {
i++
}
if i == len(s) {
return "", "", ErrMissingQuote
}
return s[:i], s[i+1:], nil
} | [
"func",
"parseString",
"(",
"s",
"string",
")",
"(",
"string",
",",
"string",
",",
"error",
")",
"{",
"if",
"s",
"[",
"0",
"]",
"!=",
"'\\''",
"&&",
"s",
"[",
"0",
"]",
"!=",
"'\"'",
"{",
"panic",
"(",
"\"string should start with open quote. calling code... | // caller must assure s starts with a single or double quote | [
"caller",
"must",
"assure",
"s",
"starts",
"with",
"a",
"single",
"or",
"double",
"quote"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/expr/parse.go#L330-L351 | train |
grafana/metrictank | expr/parse.go | aggKey | func aggKey(serie models.Series, nodes []expr) string {
metric := extractMetric(serie.Target)
if len(metric) == 0 {
metric = serie.Tags["name"]
}
// Trim off tags (if they are there) and split on '.'
parts := strings.Split(strings.SplitN(metric, ";", 2)[0], ".")
var name []string
for _, n := range nodes {
if n.etype == etInt {
idx := int(n.int)
if idx < 0 {
idx += len(parts)
}
if idx >= len(parts) || idx < 0 {
continue
}
name = append(name, parts[idx])
} else if n.etype == etString {
s := n.str
name = append(name, serie.Tags[s])
}
}
return strings.Join(name, ".")
} | go | func aggKey(serie models.Series, nodes []expr) string {
metric := extractMetric(serie.Target)
if len(metric) == 0 {
metric = serie.Tags["name"]
}
// Trim off tags (if they are there) and split on '.'
parts := strings.Split(strings.SplitN(metric, ";", 2)[0], ".")
var name []string
for _, n := range nodes {
if n.etype == etInt {
idx := int(n.int)
if idx < 0 {
idx += len(parts)
}
if idx >= len(parts) || idx < 0 {
continue
}
name = append(name, parts[idx])
} else if n.etype == etString {
s := n.str
name = append(name, serie.Tags[s])
}
}
return strings.Join(name, ".")
} | [
"func",
"aggKey",
"(",
"serie",
"models",
".",
"Series",
",",
"nodes",
"[",
"]",
"expr",
")",
"string",
"{",
"metric",
":=",
"extractMetric",
"(",
"serie",
".",
"Target",
")",
"\n",
"if",
"len",
"(",
"metric",
")",
"==",
"0",
"{",
"metric",
"=",
"s... | // aggKey creates a key for a serie based on its target metric as well
// as a list of nodes which need to be extracted
// returns a single string | [
"aggKey",
"creates",
"a",
"key",
"for",
"a",
"serie",
"based",
"on",
"its",
"target",
"metric",
"as",
"well",
"as",
"a",
"list",
"of",
"nodes",
"which",
"need",
"to",
"be",
"extracted",
"returns",
"a",
"single",
"string"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/expr/parse.go#L406-L430 | train |
grafana/metrictank | expr/funcs.go | summarizeCons | func summarizeCons(series []models.Series) (consolidation.Consolidator, consolidation.Consolidator) {
for _, serie := range series {
if serie.QueryCons != 0 {
return serie.Consolidator, serie.QueryCons
}
}
return series[0].Consolidator, series[0].QueryCons
} | go | func summarizeCons(series []models.Series) (consolidation.Consolidator, consolidation.Consolidator) {
for _, serie := range series {
if serie.QueryCons != 0 {
return serie.Consolidator, serie.QueryCons
}
}
return series[0].Consolidator, series[0].QueryCons
} | [
"func",
"summarizeCons",
"(",
"series",
"[",
"]",
"models",
".",
"Series",
")",
"(",
"consolidation",
".",
"Consolidator",
",",
"consolidation",
".",
"Consolidator",
")",
"{",
"for",
"_",
",",
"serie",
":=",
"range",
"series",
"{",
"if",
"serie",
".",
"Q... | // summarizeCons returns the first explicitly specified Consolidator, QueryCons for the given set of input series,
// or the first one, otherwise. | [
"summarizeCons",
"returns",
"the",
"first",
"explicitly",
"specified",
"Consolidator",
"QueryCons",
"for",
"the",
"given",
"set",
"of",
"input",
"series",
"or",
"the",
"first",
"one",
"otherwise",
"."
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/expr/funcs.go#L107-L114 | train |
grafana/metrictank | mdata/cache/ccache.go | NewCCache | func NewCCache() *CCache {
if maxSize == 0 {
return nil
}
cc := &CCache{
metricCache: make(map[schema.AMKey]*CCacheMetric),
metricRawKeys: make(map[schema.MKey]map[schema.Archive]struct{}),
accnt: accnt.NewFlatAccnt(maxSize),
stop: make(chan interface{}),
tracer: opentracing.NoopTracer{},
}
go cc.evictLoop()
return cc
} | go | func NewCCache() *CCache {
if maxSize == 0 {
return nil
}
cc := &CCache{
metricCache: make(map[schema.AMKey]*CCacheMetric),
metricRawKeys: make(map[schema.MKey]map[schema.Archive]struct{}),
accnt: accnt.NewFlatAccnt(maxSize),
stop: make(chan interface{}),
tracer: opentracing.NoopTracer{},
}
go cc.evictLoop()
return cc
} | [
"func",
"NewCCache",
"(",
")",
"*",
"CCache",
"{",
"if",
"maxSize",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"cc",
":=",
"&",
"CCache",
"{",
"metricCache",
":",
"make",
"(",
"map",
"[",
"schema",
".",
"AMKey",
"]",
"*",
"CCacheMetric",
")"... | // NewCCache creates a new chunk cache.
// When cache is disabled, this will return nil
// but the caller doesn't have to worry about this and can call methods as usual on a nil cache | [
"NewCCache",
"creates",
"a",
"new",
"chunk",
"cache",
".",
"When",
"cache",
"is",
"disabled",
"this",
"will",
"return",
"nil",
"but",
"the",
"caller",
"doesn",
"t",
"have",
"to",
"worry",
"about",
"this",
"and",
"can",
"call",
"methods",
"as",
"usual",
"... | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/mdata/cache/ccache.go#L55-L69 | train |
grafana/metrictank | mdata/cache/ccache.go | DelMetric | func (c *CCache) DelMetric(rawMetric schema.MKey) (int, int) {
if c == nil {
return 0, 0
}
archives, series := 0, 0
c.Lock()
defer c.Unlock()
archs, ok := c.metricRawKeys[rawMetric]
if !ok {
return archives, series
}
metric := schema.AMKey{MKey: rawMetric}
for arch := range archs {
metric.Archive = arch
delete(c.metricCache, metric)
c.accnt.DelMetric(metric)
archives++
}
delete(c.metricRawKeys, rawMetric)
series++
return series, archives
} | go | func (c *CCache) DelMetric(rawMetric schema.MKey) (int, int) {
if c == nil {
return 0, 0
}
archives, series := 0, 0
c.Lock()
defer c.Unlock()
archs, ok := c.metricRawKeys[rawMetric]
if !ok {
return archives, series
}
metric := schema.AMKey{MKey: rawMetric}
for arch := range archs {
metric.Archive = arch
delete(c.metricCache, metric)
c.accnt.DelMetric(metric)
archives++
}
delete(c.metricRawKeys, rawMetric)
series++
return series, archives
} | [
"func",
"(",
"c",
"*",
"CCache",
")",
"DelMetric",
"(",
"rawMetric",
"schema",
".",
"MKey",
")",
"(",
"int",
",",
"int",
")",
"{",
"if",
"c",
"==",
"nil",
"{",
"return",
"0",
",",
"0",
"\n",
"}",
"\n",
"archives",
",",
"series",
":=",
"0",
",",... | // takes a raw key and deletes all archives associated with it from cache | [
"takes",
"a",
"raw",
"key",
"and",
"deletes",
"all",
"archives",
"associated",
"with",
"it",
"from",
"cache"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/mdata/cache/ccache.go#L90-L116 | train |
grafana/metrictank | mdata/cache/ccache.go | AddIfHot | func (c *CCache) AddIfHot(metric schema.AMKey, prev uint32, itergen chunk.IterGen) {
if c == nil {
return
}
c.RLock()
var met *CCacheMetric
var ok bool
// if this metric is not cached at all it is not hot
if met, ok = c.metricCache[metric]; !ok {
c.RUnlock()
return
}
// if the previous chunk is not cached we consider the metric not hot enough to cache this chunk
// only works reliably if the last chunk of that metric is span aware, otherwise lastTs() will be guessed
// conservatively which means that the returned value will probably be lower than the real last ts
if met.lastTs() < itergen.T0 {
c.RUnlock()
return
}
accnt.CacheChunkPushHot.Inc()
c.RUnlock()
met.Add(prev, itergen)
} | go | func (c *CCache) AddIfHot(metric schema.AMKey, prev uint32, itergen chunk.IterGen) {
if c == nil {
return
}
c.RLock()
var met *CCacheMetric
var ok bool
// if this metric is not cached at all it is not hot
if met, ok = c.metricCache[metric]; !ok {
c.RUnlock()
return
}
// if the previous chunk is not cached we consider the metric not hot enough to cache this chunk
// only works reliably if the last chunk of that metric is span aware, otherwise lastTs() will be guessed
// conservatively which means that the returned value will probably be lower than the real last ts
if met.lastTs() < itergen.T0 {
c.RUnlock()
return
}
accnt.CacheChunkPushHot.Inc()
c.RUnlock()
met.Add(prev, itergen)
} | [
"func",
"(",
"c",
"*",
"CCache",
")",
"AddIfHot",
"(",
"metric",
"schema",
".",
"AMKey",
",",
"prev",
"uint32",
",",
"itergen",
"chunk",
".",
"IterGen",
")",
"{",
"if",
"c",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"c",
".",
"RLock",
"(",
")"... | // adds the given chunk to the cache, but only if the metric is sufficiently hot | [
"adds",
"the",
"given",
"chunk",
"to",
"the",
"cache",
"but",
"only",
"if",
"the",
"metric",
"is",
"sufficiently",
"hot"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/mdata/cache/ccache.go#L119-L146 | train |
grafana/metrictank | mdata/cache/ccache.go | Search | func (c *CCache) Search(ctx context.Context, metric schema.AMKey, from, until uint32) (*CCSearchResult, error) {
if from >= until {
return nil, ErrInvalidRange
}
res := &CCSearchResult{
From: from,
Until: until,
}
if c == nil {
accnt.CacheMetricMiss.Inc()
return res, nil
}
ctx, span := tracing.NewSpan(ctx, c.tracer, "CCache.Search")
defer span.Finish()
c.RLock()
defer c.RUnlock()
cm, ok := c.metricCache[metric]
if !ok {
span.SetTag("cache", "miss")
accnt.CacheMetricMiss.Inc()
return res, nil
}
cm.Search(ctx, metric, res, from, until)
if len(res.Start) == 0 && len(res.End) == 0 {
span.SetTag("cache", "miss")
accnt.CacheMetricMiss.Inc()
} else {
accnt.CacheChunkHit.Add(len(res.Start) + len(res.End))
go func() {
c.accnt.HitChunks(metric, res.Start)
c.accnt.HitChunks(metric, res.End)
}()
if res.Complete {
span.SetTag("cache", "hit-full")
accnt.CacheMetricHitFull.Inc()
} else {
span.SetTag("cache", "hit-partial")
accnt.CacheMetricHitPartial.Inc()
}
}
return res, nil
} | go | func (c *CCache) Search(ctx context.Context, metric schema.AMKey, from, until uint32) (*CCSearchResult, error) {
if from >= until {
return nil, ErrInvalidRange
}
res := &CCSearchResult{
From: from,
Until: until,
}
if c == nil {
accnt.CacheMetricMiss.Inc()
return res, nil
}
ctx, span := tracing.NewSpan(ctx, c.tracer, "CCache.Search")
defer span.Finish()
c.RLock()
defer c.RUnlock()
cm, ok := c.metricCache[metric]
if !ok {
span.SetTag("cache", "miss")
accnt.CacheMetricMiss.Inc()
return res, nil
}
cm.Search(ctx, metric, res, from, until)
if len(res.Start) == 0 && len(res.End) == 0 {
span.SetTag("cache", "miss")
accnt.CacheMetricMiss.Inc()
} else {
accnt.CacheChunkHit.Add(len(res.Start) + len(res.End))
go func() {
c.accnt.HitChunks(metric, res.Start)
c.accnt.HitChunks(metric, res.End)
}()
if res.Complete {
span.SetTag("cache", "hit-full")
accnt.CacheMetricHitFull.Inc()
} else {
span.SetTag("cache", "hit-partial")
accnt.CacheMetricHitPartial.Inc()
}
}
return res, nil
} | [
"func",
"(",
"c",
"*",
"CCache",
")",
"Search",
"(",
"ctx",
"context",
".",
"Context",
",",
"metric",
"schema",
".",
"AMKey",
",",
"from",
",",
"until",
"uint32",
")",
"(",
"*",
"CCSearchResult",
",",
"error",
")",
"{",
"if",
"from",
">=",
"until",
... | // Search looks for the requested metric and returns a complete-as-possible CCSearchResult
// from is inclusive, until is exclusive | [
"Search",
"looks",
"for",
"the",
"requested",
"metric",
"and",
"returns",
"a",
"complete",
"-",
"as",
"-",
"possible",
"CCSearchResult",
"from",
"is",
"inclusive",
"until",
"is",
"exclusive"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/mdata/cache/ccache.go#L258-L308 | train |
grafana/metrictank | mdata/aggmetrics.go | GC | func (ms *AggMetrics) GC() {
for {
unix := time.Duration(time.Now().UnixNano())
diff := ms.gcInterval - (unix % ms.gcInterval)
time.Sleep(diff + time.Minute)
log.Info("checking for stale chunks that need persisting.")
now := uint32(time.Now().Unix())
chunkMinTs := now - uint32(ms.chunkMaxStale)
metricMinTs := now - uint32(ms.metricMaxStale)
// as this is the only goroutine that can delete from ms.Metrics
// we only need to lock long enough to get the list of orgs, then for each org
// get the list of active metrics.
// It doesn't matter if new orgs or metrics are added while we iterate these lists.
ms.RLock()
orgs := make([]uint32, 0, len(ms.Metrics))
for o := range ms.Metrics {
orgs = append(orgs, o)
}
ms.RUnlock()
for _, org := range orgs {
orgActiveMetrics := promActiveMetrics.WithLabelValues(strconv.Itoa(int(org)))
keys := make([]schema.Key, 0, len(ms.Metrics[org]))
ms.RLock()
for k := range ms.Metrics[org] {
keys = append(keys, k)
}
ms.RUnlock()
for _, key := range keys {
gcMetric.Inc()
ms.RLock()
a := ms.Metrics[org][key]
ms.RUnlock()
points, stale := a.GC(now, chunkMinTs, metricMinTs)
if stale {
log.Debugf("metric %s is stale. Purging data from memory.", key)
ms.Lock()
delete(ms.Metrics[org], key)
orgActiveMetrics.Set(float64(len(ms.Metrics[org])))
// note: this is racey. if a metric has just become unstale, it may have created a new chunk,
// pruning an older one. in which case we double-subtract those points
// hard to fix and super rare. see https://github.com/grafana/metrictank/pull/1242
totalPoints.DecUint64(uint64(points))
ms.Unlock()
}
}
ms.RLock()
orgActive := len(ms.Metrics[org])
orgActiveMetrics.Set(float64(orgActive))
ms.RUnlock()
// If this org has no keys, then delete the org from the map
if orgActive == 0 {
// To prevent races, we need to check that there are still no metrics for the org while holding a write lock
ms.Lock()
orgActive = len(ms.Metrics[org])
if orgActive == 0 {
delete(ms.Metrics, org)
}
ms.Unlock()
}
}
// Get the totalActive across all orgs.
totalActive := 0
ms.RLock()
for o := range ms.Metrics {
totalActive += len(ms.Metrics[o])
}
ms.RUnlock()
metricsActive.Set(totalActive)
}
} | go | func (ms *AggMetrics) GC() {
for {
unix := time.Duration(time.Now().UnixNano())
diff := ms.gcInterval - (unix % ms.gcInterval)
time.Sleep(diff + time.Minute)
log.Info("checking for stale chunks that need persisting.")
now := uint32(time.Now().Unix())
chunkMinTs := now - uint32(ms.chunkMaxStale)
metricMinTs := now - uint32(ms.metricMaxStale)
// as this is the only goroutine that can delete from ms.Metrics
// we only need to lock long enough to get the list of orgs, then for each org
// get the list of active metrics.
// It doesn't matter if new orgs or metrics are added while we iterate these lists.
ms.RLock()
orgs := make([]uint32, 0, len(ms.Metrics))
for o := range ms.Metrics {
orgs = append(orgs, o)
}
ms.RUnlock()
for _, org := range orgs {
orgActiveMetrics := promActiveMetrics.WithLabelValues(strconv.Itoa(int(org)))
keys := make([]schema.Key, 0, len(ms.Metrics[org]))
ms.RLock()
for k := range ms.Metrics[org] {
keys = append(keys, k)
}
ms.RUnlock()
for _, key := range keys {
gcMetric.Inc()
ms.RLock()
a := ms.Metrics[org][key]
ms.RUnlock()
points, stale := a.GC(now, chunkMinTs, metricMinTs)
if stale {
log.Debugf("metric %s is stale. Purging data from memory.", key)
ms.Lock()
delete(ms.Metrics[org], key)
orgActiveMetrics.Set(float64(len(ms.Metrics[org])))
// note: this is racey. if a metric has just become unstale, it may have created a new chunk,
// pruning an older one. in which case we double-subtract those points
// hard to fix and super rare. see https://github.com/grafana/metrictank/pull/1242
totalPoints.DecUint64(uint64(points))
ms.Unlock()
}
}
ms.RLock()
orgActive := len(ms.Metrics[org])
orgActiveMetrics.Set(float64(orgActive))
ms.RUnlock()
// If this org has no keys, then delete the org from the map
if orgActive == 0 {
// To prevent races, we need to check that there are still no metrics for the org while holding a write lock
ms.Lock()
orgActive = len(ms.Metrics[org])
if orgActive == 0 {
delete(ms.Metrics, org)
}
ms.Unlock()
}
}
// Get the totalActive across all orgs.
totalActive := 0
ms.RLock()
for o := range ms.Metrics {
totalActive += len(ms.Metrics[o])
}
ms.RUnlock()
metricsActive.Set(totalActive)
}
} | [
"func",
"(",
"ms",
"*",
"AggMetrics",
")",
"GC",
"(",
")",
"{",
"for",
"{",
"unix",
":=",
"time",
".",
"Duration",
"(",
"time",
".",
"Now",
"(",
")",
".",
"UnixNano",
"(",
")",
")",
"\n",
"diff",
":=",
"ms",
".",
"gcInterval",
"-",
"(",
"unix",... | // periodically scan chunks and close any that have not received data in a while | [
"periodically",
"scan",
"chunks",
"and",
"close",
"any",
"that",
"have",
"not",
"received",
"data",
"in",
"a",
"while"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/mdata/aggmetrics.go#L47-L119 | train |
grafana/metrictank | cmd/mt-store-cat/chunk.go | printChunkSummary | func printChunkSummary(ctx context.Context, store *cassandra.CassandraStore, tables []cassandra.Table, metrics []Metric, groupTTL string) error {
now := uint32(time.Now().Unix())
endMonth := now / cassandra.Month_sec
for _, tbl := range tables {
// per store.FindExistingTables(), actual TTL may be up to 2x what's in tablename.
// we query up to 4x so that we also include data that should have been dropped already but still sticks around for whatever reason.
start := now - uint32(4*tbl.TTL*3600)
startMonth := start / cassandra.Month_sec
fmt.Println("## Table", tbl.Name)
if len(metrics) == 0 {
query := fmt.Sprintf("select key, ttl(data) from %s", tbl.Name)
iter := store.Session.Query(query).Iter()
showKeyTTL(iter, groupTTL)
} else {
for _, metric := range metrics {
for num := startMonth; num <= endMonth; num += 1 {
row_key := fmt.Sprintf("%s_%d", metric.AMKey.String(), num)
query := fmt.Sprintf("select key, ttl(data) from %s where key=?", tbl.Name)
iter := store.Session.Query(query, row_key).Iter()
showKeyTTL(iter, groupTTL)
}
}
}
}
return nil
} | go | func printChunkSummary(ctx context.Context, store *cassandra.CassandraStore, tables []cassandra.Table, metrics []Metric, groupTTL string) error {
now := uint32(time.Now().Unix())
endMonth := now / cassandra.Month_sec
for _, tbl := range tables {
// per store.FindExistingTables(), actual TTL may be up to 2x what's in tablename.
// we query up to 4x so that we also include data that should have been dropped already but still sticks around for whatever reason.
start := now - uint32(4*tbl.TTL*3600)
startMonth := start / cassandra.Month_sec
fmt.Println("## Table", tbl.Name)
if len(metrics) == 0 {
query := fmt.Sprintf("select key, ttl(data) from %s", tbl.Name)
iter := store.Session.Query(query).Iter()
showKeyTTL(iter, groupTTL)
} else {
for _, metric := range metrics {
for num := startMonth; num <= endMonth; num += 1 {
row_key := fmt.Sprintf("%s_%d", metric.AMKey.String(), num)
query := fmt.Sprintf("select key, ttl(data) from %s where key=?", tbl.Name)
iter := store.Session.Query(query, row_key).Iter()
showKeyTTL(iter, groupTTL)
}
}
}
}
return nil
} | [
"func",
"printChunkSummary",
"(",
"ctx",
"context",
".",
"Context",
",",
"store",
"*",
"cassandra",
".",
"CassandraStore",
",",
"tables",
"[",
"]",
"cassandra",
".",
"Table",
",",
"metrics",
"[",
"]",
"Metric",
",",
"groupTTL",
"string",
")",
"error",
"{",... | // printChunkSummary prints a summary of chunks in the store matching the given conditions, grouped in buckets of groupTTL size by their TTL | [
"printChunkSummary",
"prints",
"a",
"summary",
"of",
"chunks",
"in",
"the",
"store",
"matching",
"the",
"given",
"conditions",
"grouped",
"in",
"buckets",
"of",
"groupTTL",
"size",
"by",
"their",
"TTL"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/cmd/mt-store-cat/chunk.go#L13-L39 | train |
grafana/metrictank | cmd/mt-whisper-importer-reader/main.go | getMetricName | func getMetricName(file string) string {
// remove all leading '/' from file name
file = strings.TrimPrefix(file, *whisperDirectory)
for file[0] == '/' {
file = file[1:]
}
return *namePrefix + strings.Replace(strings.TrimSuffix(file, ".wsp"), "/", ".", -1)
} | go | func getMetricName(file string) string {
// remove all leading '/' from file name
file = strings.TrimPrefix(file, *whisperDirectory)
for file[0] == '/' {
file = file[1:]
}
return *namePrefix + strings.Replace(strings.TrimSuffix(file, ".wsp"), "/", ".", -1)
} | [
"func",
"getMetricName",
"(",
"file",
"string",
")",
"string",
"{",
"file",
"=",
"strings",
".",
"TrimPrefix",
"(",
"file",
",",
"*",
"whisperDirectory",
")",
"\n",
"for",
"file",
"[",
"0",
"]",
"==",
"'/'",
"{",
"file",
"=",
"file",
"[",
"1",
":",
... | // generate the metric name based on the file name and given prefix | [
"generate",
"the",
"metric",
"name",
"based",
"on",
"the",
"file",
"name",
"and",
"given",
"prefix"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/cmd/mt-whisper-importer-reader/main.go#L231-L239 | train |
grafana/metrictank | cmd/mt-whisper-importer-reader/main.go | getFileListIntoChan | func getFileListIntoChan(pos *posTracker, fileChan chan string) {
filepath.Walk(
*whisperDirectory,
func(path string, info os.FileInfo, err error) error {
if path == *whisperDirectory {
return nil
}
name := getMetricName(path)
if !nameFilter.Match([]byte(getMetricName(name))) {
log.Debugf("Skipping file %s with name %s", path, name)
atomic.AddUint32(&skippedCount, 1)
return nil
}
if len(path) < 4 || path[len(path)-4:] != ".wsp" {
return nil
}
if pos != nil && pos.IsDone(path) {
log.Debugf("Skipping file %s because it was listed as already done", path)
return nil
}
fileChan <- path
return nil
},
)
close(fileChan)
} | go | func getFileListIntoChan(pos *posTracker, fileChan chan string) {
filepath.Walk(
*whisperDirectory,
func(path string, info os.FileInfo, err error) error {
if path == *whisperDirectory {
return nil
}
name := getMetricName(path)
if !nameFilter.Match([]byte(getMetricName(name))) {
log.Debugf("Skipping file %s with name %s", path, name)
atomic.AddUint32(&skippedCount, 1)
return nil
}
if len(path) < 4 || path[len(path)-4:] != ".wsp" {
return nil
}
if pos != nil && pos.IsDone(path) {
log.Debugf("Skipping file %s because it was listed as already done", path)
return nil
}
fileChan <- path
return nil
},
)
close(fileChan)
} | [
"func",
"getFileListIntoChan",
"(",
"pos",
"*",
"posTracker",
",",
"fileChan",
"chan",
"string",
")",
"{",
"filepath",
".",
"Walk",
"(",
"*",
"whisperDirectory",
",",
"func",
"(",
"path",
"string",
",",
"info",
"os",
".",
"FileInfo",
",",
"err",
"error",
... | // scan a directory and feed the list of whisper files relative to base into the given channel | [
"scan",
"a",
"directory",
"and",
"feed",
"the",
"list",
"of",
"whisper",
"files",
"relative",
"to",
"base",
"into",
"the",
"given",
"channel"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/cmd/mt-whisper-importer-reader/main.go#L399-L426 | train |
grafana/metrictank | store/cassandra/cassandra.go | ConvertTimeout | func ConvertTimeout(timeout string, defaultUnit time.Duration) time.Duration {
if timeoutI, err := strconv.Atoi(timeout); err == nil {
log.Warn("cassandra_store: specifying the timeout as integer is deprecated, please use a duration value")
return time.Duration(timeoutI) * defaultUnit
}
timeoutD, err := time.ParseDuration(timeout)
if err != nil {
log.Fatalf("cassandra_store: invalid duration value %q", timeout)
}
return timeoutD
} | go | func ConvertTimeout(timeout string, defaultUnit time.Duration) time.Duration {
if timeoutI, err := strconv.Atoi(timeout); err == nil {
log.Warn("cassandra_store: specifying the timeout as integer is deprecated, please use a duration value")
return time.Duration(timeoutI) * defaultUnit
}
timeoutD, err := time.ParseDuration(timeout)
if err != nil {
log.Fatalf("cassandra_store: invalid duration value %q", timeout)
}
return timeoutD
} | [
"func",
"ConvertTimeout",
"(",
"timeout",
"string",
",",
"defaultUnit",
"time",
".",
"Duration",
")",
"time",
".",
"Duration",
"{",
"if",
"timeoutI",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"timeout",
")",
";",
"err",
"==",
"nil",
"{",
"log",
".... | // ConvertTimeout provides backwards compatibility for values that used to be specified as integers,
// while also allowing them to be specified as durations. | [
"ConvertTimeout",
"provides",
"backwards",
"compatibility",
"for",
"values",
"that",
"used",
"to",
"be",
"specified",
"as",
"integers",
"while",
"also",
"allowing",
"them",
"to",
"be",
"specified",
"as",
"durations",
"."
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/store/cassandra/cassandra.go#L96-L106 | train |
grafana/metrictank | store/cassandra/cassandra.go | Search | func (c *CassandraStore) Search(ctx context.Context, key schema.AMKey, ttl, start, end uint32) ([]chunk.IterGen, error) {
table, ok := c.TTLTables[ttl]
if !ok {
return nil, errTableNotFound
}
return c.SearchTable(ctx, key, table, start, end)
} | go | func (c *CassandraStore) Search(ctx context.Context, key schema.AMKey, ttl, start, end uint32) ([]chunk.IterGen, error) {
table, ok := c.TTLTables[ttl]
if !ok {
return nil, errTableNotFound
}
return c.SearchTable(ctx, key, table, start, end)
} | [
"func",
"(",
"c",
"*",
"CassandraStore",
")",
"Search",
"(",
"ctx",
"context",
".",
"Context",
",",
"key",
"schema",
".",
"AMKey",
",",
"ttl",
",",
"start",
",",
"end",
"uint32",
")",
"(",
"[",
"]",
"chunk",
".",
"IterGen",
",",
"error",
")",
"{",
... | // Basic search of cassandra in the table for given ttl
// start inclusive, end exclusive | [
"Basic",
"search",
"of",
"cassandra",
"in",
"the",
"table",
"for",
"given",
"ttl",
"start",
"inclusive",
"end",
"exclusive"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/store/cassandra/cassandra.go#L411-L417 | train |
grafana/metrictank | conf/indexrules.go | ReadIndexRules | func ReadIndexRules(file string) (IndexRules, error) {
config, err := configparser.Read(file)
if err != nil {
return IndexRules{}, err
}
sections, err := config.AllSections()
if err != nil {
return IndexRules{}, err
}
result := NewIndexRules()
for _, s := range sections {
item := IndexRule{}
item.Name = strings.Trim(strings.SplitN(s.String(), "\n", 2)[0], " []")
if item.Name == "" || strings.HasPrefix(item.Name, "#") {
continue
}
item.Pattern, err = regexp.Compile(s.ValueOf("pattern"))
if err != nil {
return IndexRules{}, fmt.Errorf("[%s]: failed to parse pattern %q: %s", item.Name, s.ValueOf("pattern"), err.Error())
}
duration, err := dur.ParseDuration(s.ValueOf("max-stale"))
if err != nil {
return IndexRules{}, fmt.Errorf("[%s]: failed to parse max-stale %q: %s", item.Name, s.ValueOf("max-stale"), err.Error())
}
item.MaxStale = time.Duration(duration) * time.Second
result.Rules = append(result.Rules, item)
}
return result, nil
} | go | func ReadIndexRules(file string) (IndexRules, error) {
config, err := configparser.Read(file)
if err != nil {
return IndexRules{}, err
}
sections, err := config.AllSections()
if err != nil {
return IndexRules{}, err
}
result := NewIndexRules()
for _, s := range sections {
item := IndexRule{}
item.Name = strings.Trim(strings.SplitN(s.String(), "\n", 2)[0], " []")
if item.Name == "" || strings.HasPrefix(item.Name, "#") {
continue
}
item.Pattern, err = regexp.Compile(s.ValueOf("pattern"))
if err != nil {
return IndexRules{}, fmt.Errorf("[%s]: failed to parse pattern %q: %s", item.Name, s.ValueOf("pattern"), err.Error())
}
duration, err := dur.ParseDuration(s.ValueOf("max-stale"))
if err != nil {
return IndexRules{}, fmt.Errorf("[%s]: failed to parse max-stale %q: %s", item.Name, s.ValueOf("max-stale"), err.Error())
}
item.MaxStale = time.Duration(duration) * time.Second
result.Rules = append(result.Rules, item)
}
return result, nil
} | [
"func",
"ReadIndexRules",
"(",
"file",
"string",
")",
"(",
"IndexRules",
",",
"error",
")",
"{",
"config",
",",
"err",
":=",
"configparser",
".",
"Read",
"(",
"file",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"IndexRules",
"{",
"}",
",",
"e... | // ReadIndexRules returns the defined index rule from a index-rules.conf file
// and adds the default | [
"ReadIndexRules",
"returns",
"the",
"defined",
"index",
"rule",
"from",
"a",
"index",
"-",
"rules",
".",
"conf",
"file",
"and",
"adds",
"the",
"default"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/conf/indexrules.go#L38-L71 | train |
grafana/metrictank | conf/indexrules.go | Match | func (a IndexRules) Match(metric string) (uint16, IndexRule) {
for i, s := range a.Rules {
if s.Pattern.MatchString(metric) {
return uint16(i), s
}
}
return uint16(len(a.Rules)), a.Default
} | go | func (a IndexRules) Match(metric string) (uint16, IndexRule) {
for i, s := range a.Rules {
if s.Pattern.MatchString(metric) {
return uint16(i), s
}
}
return uint16(len(a.Rules)), a.Default
} | [
"func",
"(",
"a",
"IndexRules",
")",
"Match",
"(",
"metric",
"string",
")",
"(",
"uint16",
",",
"IndexRule",
")",
"{",
"for",
"i",
",",
"s",
":=",
"range",
"a",
".",
"Rules",
"{",
"if",
"s",
".",
"Pattern",
".",
"MatchString",
"(",
"metric",
")",
... | // Match returns the correct index rule setting for the given metric
// it can always find a valid setting, because there's a default catch all
// also returns the index of the setting, to efficiently reference it | [
"Match",
"returns",
"the",
"correct",
"index",
"rule",
"setting",
"for",
"the",
"given",
"metric",
"it",
"can",
"always",
"find",
"a",
"valid",
"setting",
"because",
"there",
"s",
"a",
"default",
"catch",
"all",
"also",
"returns",
"the",
"index",
"of",
"th... | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/conf/indexrules.go#L76-L83 | train |
grafana/metrictank | conf/indexrules.go | Get | func (a IndexRules) Get(i uint16) IndexRule {
if i >= uint16(len(a.Rules)) {
return a.Default
}
return a.Rules[i]
} | go | func (a IndexRules) Get(i uint16) IndexRule {
if i >= uint16(len(a.Rules)) {
return a.Default
}
return a.Rules[i]
} | [
"func",
"(",
"a",
"IndexRules",
")",
"Get",
"(",
"i",
"uint16",
")",
"IndexRule",
"{",
"if",
"i",
">=",
"uint16",
"(",
"len",
"(",
"a",
".",
"Rules",
")",
")",
"{",
"return",
"a",
".",
"Default",
"\n",
"}",
"\n",
"return",
"a",
".",
"Rules",
"[... | // Get returns the index rule setting corresponding to the given index | [
"Get",
"returns",
"the",
"index",
"rule",
"setting",
"corresponding",
"to",
"the",
"given",
"index"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/conf/indexrules.go#L86-L91 | train |
grafana/metrictank | conf/indexrules.go | Prunable | func (a IndexRules) Prunable() bool {
for _, r := range a.Rules {
if r.MaxStale > 0 {
return true
}
}
return (a.Default.MaxStale > 0)
} | go | func (a IndexRules) Prunable() bool {
for _, r := range a.Rules {
if r.MaxStale > 0 {
return true
}
}
return (a.Default.MaxStale > 0)
} | [
"func",
"(",
"a",
"IndexRules",
")",
"Prunable",
"(",
")",
"bool",
"{",
"for",
"_",
",",
"r",
":=",
"range",
"a",
".",
"Rules",
"{",
"if",
"r",
".",
"MaxStale",
">",
"0",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"(",
"a",
... | // Prunable returns whether there's any entries that require pruning | [
"Prunable",
"returns",
"whether",
"there",
"s",
"any",
"entries",
"that",
"require",
"pruning"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/conf/indexrules.go#L94-L101 | train |
grafana/metrictank | conf/indexrules.go | Cutoffs | func (a IndexRules) Cutoffs(now time.Time) []int64 {
out := make([]int64, len(a.Rules)+1)
for i := 0; i <= len(a.Rules); i++ {
var rule IndexRule
if i < len(a.Rules) {
rule = a.Rules[i]
} else {
rule = a.Default
}
if rule.MaxStale == 0 {
out[i] = 0
} else {
out[i] = int64(now.Add(rule.MaxStale * -1).Unix())
}
}
return out
} | go | func (a IndexRules) Cutoffs(now time.Time) []int64 {
out := make([]int64, len(a.Rules)+1)
for i := 0; i <= len(a.Rules); i++ {
var rule IndexRule
if i < len(a.Rules) {
rule = a.Rules[i]
} else {
rule = a.Default
}
if rule.MaxStale == 0 {
out[i] = 0
} else {
out[i] = int64(now.Add(rule.MaxStale * -1).Unix())
}
}
return out
} | [
"func",
"(",
"a",
"IndexRules",
")",
"Cutoffs",
"(",
"now",
"time",
".",
"Time",
")",
"[",
"]",
"int64",
"{",
"out",
":=",
"make",
"(",
"[",
"]",
"int64",
",",
"len",
"(",
"a",
".",
"Rules",
")",
"+",
"1",
")",
"\n",
"for",
"i",
":=",
"0",
... | // Cutoffs returns a set of cutoffs corresponding to a given timestamp and the set of all rules | [
"Cutoffs",
"returns",
"a",
"set",
"of",
"cutoffs",
"corresponding",
"to",
"a",
"given",
"timestamp",
"and",
"the",
"set",
"of",
"all",
"rules"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/conf/indexrules.go#L104-L120 | train |
grafana/metrictank | expr/plan.go | newplan | func newplan(e *expr, context Context, stable bool, reqs []Req) (GraphiteFunc, []Req, error) {
if e.etype != etFunc && e.etype != etName {
return nil, nil, errors.New("request must be a function call or metric pattern")
}
if e.etype == etName {
req := NewReq(e.str, context.from, context.to, context.consol)
reqs = append(reqs, req)
return NewGet(req), reqs, nil
} else if e.etype == etFunc && e.str == "seriesByTag" {
// `seriesByTag` function requires resolving expressions to series
// (similar to path expressions handled above). Since we need the
// arguments of seriesByTag to do the resolution, we store the function
// string back into the Query member of a new request to be parsed later.
// TODO - find a way to prevent this parse/encode/parse/encode loop
expressionStr := "seriesByTag(" + e.argsStr + ")"
req := NewReq(expressionStr, context.from, context.to, context.consol)
reqs = append(reqs, req)
return NewGet(req), reqs, nil
}
// here e.type is guaranteed to be etFunc
fdef, ok := funcs[e.str]
if !ok {
return nil, nil, ErrUnknownFunction(e.str)
}
if stable && !fdef.stable {
return nil, nil, ErrUnknownFunction(e.str)
}
fn := fdef.constr()
reqs, err := newplanFunc(e, fn, context, stable, reqs)
return fn, reqs, err
} | go | func newplan(e *expr, context Context, stable bool, reqs []Req) (GraphiteFunc, []Req, error) {
if e.etype != etFunc && e.etype != etName {
return nil, nil, errors.New("request must be a function call or metric pattern")
}
if e.etype == etName {
req := NewReq(e.str, context.from, context.to, context.consol)
reqs = append(reqs, req)
return NewGet(req), reqs, nil
} else if e.etype == etFunc && e.str == "seriesByTag" {
// `seriesByTag` function requires resolving expressions to series
// (similar to path expressions handled above). Since we need the
// arguments of seriesByTag to do the resolution, we store the function
// string back into the Query member of a new request to be parsed later.
// TODO - find a way to prevent this parse/encode/parse/encode loop
expressionStr := "seriesByTag(" + e.argsStr + ")"
req := NewReq(expressionStr, context.from, context.to, context.consol)
reqs = append(reqs, req)
return NewGet(req), reqs, nil
}
// here e.type is guaranteed to be etFunc
fdef, ok := funcs[e.str]
if !ok {
return nil, nil, ErrUnknownFunction(e.str)
}
if stable && !fdef.stable {
return nil, nil, ErrUnknownFunction(e.str)
}
fn := fdef.constr()
reqs, err := newplanFunc(e, fn, context, stable, reqs)
return fn, reqs, err
} | [
"func",
"newplan",
"(",
"e",
"*",
"expr",
",",
"context",
"Context",
",",
"stable",
"bool",
",",
"reqs",
"[",
"]",
"Req",
")",
"(",
"GraphiteFunc",
",",
"[",
"]",
"Req",
",",
"error",
")",
"{",
"if",
"e",
".",
"etype",
"!=",
"etFunc",
"&&",
"e",
... | // newplan adds requests as needed for the given expr, resolving function calls as needed | [
"newplan",
"adds",
"requests",
"as",
"needed",
"for",
"the",
"given",
"expr",
"resolving",
"function",
"calls",
"as",
"needed"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/expr/plan.go#L92-L123 | train |
grafana/metrictank | expr/plan.go | newplanFunc | func newplanFunc(e *expr, fn GraphiteFunc, context Context, stable bool, reqs []Req) ([]Req, error) {
// first comes the interesting task of validating the arguments as specified by the function,
// against the arguments that were parsed.
argsExp, _ := fn.Signature()
var err error
// note:
// * signature may have seriesLists in it, which means one or more args of type seriesList
// so it's legal to have more e.args than signature args in that case.
// * we can't do extensive, accurate validation of the type here because what the output from a function we depend on
// might be dynamically typed. e.g. movingAvg returns 1..N series depending on how many it got as input
// first validate the mandatory args
pos := 0 // e.args[pos] : next given arg to process
cutoff := 0 // argsExp[cutoff] : will be first optional arg (if any)
var argExp Arg
for cutoff, argExp = range argsExp {
if argExp.Optional() {
break
}
if len(e.args) <= pos {
return nil, ErrMissingArg
}
pos, err = e.consumeBasicArg(pos, argExp)
if err != nil {
return nil, err
}
}
if !argExp.Optional() {
cutoff++
}
// we stopped iterating the mandatory args.
// any remaining args should be due to optional args otherwise there's too many
// we also track here which keywords can also be used for the given optional args
// so that those args should not be specified via their keys anymore.
seenKwargs := make(map[string]struct{})
for _, argOpt := range argsExp[cutoff:] {
if len(e.args) <= pos {
break // no more args specified. we're done.
}
pos, err = e.consumeBasicArg(pos, argOpt)
if err != nil {
return nil, err
}
seenKwargs[argOpt.Key()] = struct{}{}
}
if len(e.args) > pos {
return nil, ErrTooManyArg
}
// for any provided keyword args, verify that they are what the function stipulated
// and that they have not already been specified via their position
for key := range e.namedArgs {
_, ok := seenKwargs[key]
if ok {
return nil, ErrKwargSpecifiedTwice{key}
}
err = e.consumeKwarg(key, argsExp[cutoff:])
if err != nil {
return nil, err
}
seenKwargs[key] = struct{}{}
}
// functions now have their non-series input args set,
// so they should now be able to specify any context alterations
context = fn.Context(context)
// now that we know the needed context for the data coming into
// this function, we can set up the input arguments for the function
// that are series
pos = 0
for _, argExp = range argsExp {
if pos >= len(e.args) {
break // no more args specified. we're done.
}
switch argExp.(type) {
case ArgSeries, ArgSeriesList, ArgSeriesLists, ArgIn:
pos, reqs, err = e.consumeSeriesArg(pos, argExp, context, stable, reqs)
if err != nil {
return nil, err
}
default:
pos++
}
}
return reqs, err
} | go | func newplanFunc(e *expr, fn GraphiteFunc, context Context, stable bool, reqs []Req) ([]Req, error) {
// first comes the interesting task of validating the arguments as specified by the function,
// against the arguments that were parsed.
argsExp, _ := fn.Signature()
var err error
// note:
// * signature may have seriesLists in it, which means one or more args of type seriesList
// so it's legal to have more e.args than signature args in that case.
// * we can't do extensive, accurate validation of the type here because what the output from a function we depend on
// might be dynamically typed. e.g. movingAvg returns 1..N series depending on how many it got as input
// first validate the mandatory args
pos := 0 // e.args[pos] : next given arg to process
cutoff := 0 // argsExp[cutoff] : will be first optional arg (if any)
var argExp Arg
for cutoff, argExp = range argsExp {
if argExp.Optional() {
break
}
if len(e.args) <= pos {
return nil, ErrMissingArg
}
pos, err = e.consumeBasicArg(pos, argExp)
if err != nil {
return nil, err
}
}
if !argExp.Optional() {
cutoff++
}
// we stopped iterating the mandatory args.
// any remaining args should be due to optional args otherwise there's too many
// we also track here which keywords can also be used for the given optional args
// so that those args should not be specified via their keys anymore.
seenKwargs := make(map[string]struct{})
for _, argOpt := range argsExp[cutoff:] {
if len(e.args) <= pos {
break // no more args specified. we're done.
}
pos, err = e.consumeBasicArg(pos, argOpt)
if err != nil {
return nil, err
}
seenKwargs[argOpt.Key()] = struct{}{}
}
if len(e.args) > pos {
return nil, ErrTooManyArg
}
// for any provided keyword args, verify that they are what the function stipulated
// and that they have not already been specified via their position
for key := range e.namedArgs {
_, ok := seenKwargs[key]
if ok {
return nil, ErrKwargSpecifiedTwice{key}
}
err = e.consumeKwarg(key, argsExp[cutoff:])
if err != nil {
return nil, err
}
seenKwargs[key] = struct{}{}
}
// functions now have their non-series input args set,
// so they should now be able to specify any context alterations
context = fn.Context(context)
// now that we know the needed context for the data coming into
// this function, we can set up the input arguments for the function
// that are series
pos = 0
for _, argExp = range argsExp {
if pos >= len(e.args) {
break // no more args specified. we're done.
}
switch argExp.(type) {
case ArgSeries, ArgSeriesList, ArgSeriesLists, ArgIn:
pos, reqs, err = e.consumeSeriesArg(pos, argExp, context, stable, reqs)
if err != nil {
return nil, err
}
default:
pos++
}
}
return reqs, err
} | [
"func",
"newplanFunc",
"(",
"e",
"*",
"expr",
",",
"fn",
"GraphiteFunc",
",",
"context",
"Context",
",",
"stable",
"bool",
",",
"reqs",
"[",
"]",
"Req",
")",
"(",
"[",
"]",
"Req",
",",
"error",
")",
"{",
"argsExp",
",",
"_",
":=",
"fn",
".",
"Sig... | // newplanFunc adds requests as needed for the given expr, and validates the function input
// provided you already know the expression is a function call to the given function | [
"newplanFunc",
"adds",
"requests",
"as",
"needed",
"for",
"the",
"given",
"expr",
"and",
"validates",
"the",
"function",
"input",
"provided",
"you",
"already",
"know",
"the",
"expression",
"is",
"a",
"function",
"call",
"to",
"the",
"given",
"function"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/expr/plan.go#L127-L216 | train |
grafana/metrictank | mdata/aggregator.go | AggBoundary | func AggBoundary(ts uint32, span uint32) uint32 {
return ts + span - ((ts-1)%span + 1)
} | go | func AggBoundary(ts uint32, span uint32) uint32 {
return ts + span - ((ts-1)%span + 1)
} | [
"func",
"AggBoundary",
"(",
"ts",
"uint32",
",",
"span",
"uint32",
")",
"uint32",
"{",
"return",
"ts",
"+",
"span",
"-",
"(",
"(",
"ts",
"-",
"1",
")",
"%",
"span",
"+",
"1",
")",
"\n",
"}"
] | // AggBoundary returns ts if it is a boundary, or the next boundary otherwise.
// see description for Aggregator and unit tests, for more details | [
"AggBoundary",
"returns",
"ts",
"if",
"it",
"is",
"a",
"boundary",
"or",
"the",
"next",
"boundary",
"otherwise",
".",
"see",
"description",
"for",
"Aggregator",
"and",
"unit",
"tests",
"for",
"more",
"details"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/mdata/aggregator.go#L11-L13 | train |
grafana/metrictank | mdata/aggregator.go | flush | func (agg *Aggregator) flush() {
if agg.minMetric != nil {
agg.minMetric.Add(agg.currentBoundary, agg.agg.Min)
}
if agg.maxMetric != nil {
agg.maxMetric.Add(agg.currentBoundary, agg.agg.Max)
}
if agg.sumMetric != nil {
agg.sumMetric.Add(agg.currentBoundary, agg.agg.Sum)
}
if agg.cntMetric != nil {
agg.cntMetric.Add(agg.currentBoundary, agg.agg.Cnt)
}
if agg.lstMetric != nil {
agg.lstMetric.Add(agg.currentBoundary, agg.agg.Lst)
}
//msg := fmt.Sprintf("flushed cnt %v sum %f min %f max %f, reset the block", agg.agg.cnt, agg.agg.sum, agg.agg.min, agg.agg.max)
agg.agg.Reset()
} | go | func (agg *Aggregator) flush() {
if agg.minMetric != nil {
agg.minMetric.Add(agg.currentBoundary, agg.agg.Min)
}
if agg.maxMetric != nil {
agg.maxMetric.Add(agg.currentBoundary, agg.agg.Max)
}
if agg.sumMetric != nil {
agg.sumMetric.Add(agg.currentBoundary, agg.agg.Sum)
}
if agg.cntMetric != nil {
agg.cntMetric.Add(agg.currentBoundary, agg.agg.Cnt)
}
if agg.lstMetric != nil {
agg.lstMetric.Add(agg.currentBoundary, agg.agg.Lst)
}
//msg := fmt.Sprintf("flushed cnt %v sum %f min %f max %f, reset the block", agg.agg.cnt, agg.agg.sum, agg.agg.min, agg.agg.max)
agg.agg.Reset()
} | [
"func",
"(",
"agg",
"*",
"Aggregator",
")",
"flush",
"(",
")",
"{",
"if",
"agg",
".",
"minMetric",
"!=",
"nil",
"{",
"agg",
".",
"minMetric",
".",
"Add",
"(",
"agg",
".",
"currentBoundary",
",",
"agg",
".",
"agg",
".",
"Min",
")",
"\n",
"}",
"\n"... | // flush adds points to the aggregation-series and resets aggregation state | [
"flush",
"adds",
"points",
"to",
"the",
"aggregation",
"-",
"series",
"and",
"resets",
"aggregation",
"state"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/mdata/aggregator.go#L78-L96 | train |
grafana/metrictank | mdata/aggregator.go | GC | func (agg *Aggregator) GC(now, chunkMinTs, metricMinTs, lastWriteTime uint32) (uint32, bool) {
var points uint32
stale := true
if lastWriteTime+agg.span > chunkMinTs {
// Last datapoint was less than one aggregation window before chunkMinTs, hold out for more data
return 0, false
}
// Haven't seen datapoints in an entire aggregation window before chunkMinTs, time to flush
if agg.agg.Cnt != 0 {
agg.flush()
}
if agg.minMetric != nil {
p, s := agg.minMetric.GC(now, chunkMinTs, metricMinTs)
stale = stale && s
points += p
}
if agg.maxMetric != nil {
p, s := agg.maxMetric.GC(now, chunkMinTs, metricMinTs)
stale = stale && s
points += p
}
if agg.sumMetric != nil {
p, s := agg.sumMetric.GC(now, chunkMinTs, metricMinTs)
stale = stale && s
points += p
}
if agg.cntMetric != nil {
p, s := agg.cntMetric.GC(now, chunkMinTs, metricMinTs)
stale = stale && s
points += p
}
if agg.lstMetric != nil {
p, s := agg.lstMetric.GC(now, chunkMinTs, metricMinTs)
stale = stale && s
points += p
}
return points, stale
} | go | func (agg *Aggregator) GC(now, chunkMinTs, metricMinTs, lastWriteTime uint32) (uint32, bool) {
var points uint32
stale := true
if lastWriteTime+agg.span > chunkMinTs {
// Last datapoint was less than one aggregation window before chunkMinTs, hold out for more data
return 0, false
}
// Haven't seen datapoints in an entire aggregation window before chunkMinTs, time to flush
if agg.agg.Cnt != 0 {
agg.flush()
}
if agg.minMetric != nil {
p, s := agg.minMetric.GC(now, chunkMinTs, metricMinTs)
stale = stale && s
points += p
}
if agg.maxMetric != nil {
p, s := agg.maxMetric.GC(now, chunkMinTs, metricMinTs)
stale = stale && s
points += p
}
if agg.sumMetric != nil {
p, s := agg.sumMetric.GC(now, chunkMinTs, metricMinTs)
stale = stale && s
points += p
}
if agg.cntMetric != nil {
p, s := agg.cntMetric.GC(now, chunkMinTs, metricMinTs)
stale = stale && s
points += p
}
if agg.lstMetric != nil {
p, s := agg.lstMetric.GC(now, chunkMinTs, metricMinTs)
stale = stale && s
points += p
}
return points, stale
} | [
"func",
"(",
"agg",
"*",
"Aggregator",
")",
"GC",
"(",
"now",
",",
"chunkMinTs",
",",
"metricMinTs",
",",
"lastWriteTime",
"uint32",
")",
"(",
"uint32",
",",
"bool",
")",
"{",
"var",
"points",
"uint32",
"\n",
"stale",
":=",
"true",
"\n",
"if",
"lastWri... | // GC returns whether all of the associated series are stale and can be removed, and their combined pointcount if so | [
"GC",
"returns",
"whether",
"all",
"of",
"the",
"associated",
"series",
"are",
"stale",
"and",
"can",
"be",
"removed",
"and",
"their",
"combined",
"pointcount",
"if",
"so"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/mdata/aggregator.go#L120-L162 | train |
grafana/metrictank | expr/func_aspercent.go | getTotalSeries | func getTotalSeries(totalSeriesLists, include map[string][]models.Series, cache map[Req][]models.Series) map[string]models.Series {
totalSeries := make(map[string]models.Series, len(totalSeriesLists))
for key := range totalSeriesLists {
if _, ok := include[key]; ok {
totalSeries[key] = sumSeries(totalSeriesLists[key], cache)
} else {
totalSeries[key] = totalSeriesLists[key][0]
}
}
return totalSeries
} | go | func getTotalSeries(totalSeriesLists, include map[string][]models.Series, cache map[Req][]models.Series) map[string]models.Series {
totalSeries := make(map[string]models.Series, len(totalSeriesLists))
for key := range totalSeriesLists {
if _, ok := include[key]; ok {
totalSeries[key] = sumSeries(totalSeriesLists[key], cache)
} else {
totalSeries[key] = totalSeriesLists[key][0]
}
}
return totalSeries
} | [
"func",
"getTotalSeries",
"(",
"totalSeriesLists",
",",
"include",
"map",
"[",
"string",
"]",
"[",
"]",
"models",
".",
"Series",
",",
"cache",
"map",
"[",
"Req",
"]",
"[",
"]",
"models",
".",
"Series",
")",
"map",
"[",
"string",
"]",
"models",
".",
"... | // Sums each seriesList in map of seriesLists | [
"Sums",
"each",
"seriesList",
"in",
"map",
"of",
"seriesLists"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/expr/func_aspercent.go#L229-L240 | train |
grafana/metrictank | expr/func_aspercent.go | sumSeries | func sumSeries(series []models.Series, cache map[Req][]models.Series) models.Series {
if len(series) == 1 {
return series[0]
}
out := pointSlicePool.Get().([]schema.Point)
crossSeriesSum(series, &out)
var queryPatts []string
Loop:
for _, v := range series {
// avoid duplicates
for _, qp := range queryPatts {
if qp == v.QueryPatt {
continue Loop
}
}
queryPatts = append(queryPatts, v.QueryPatt)
}
name := fmt.Sprintf("sumSeries(%s)", strings.Join(queryPatts, ","))
cons, queryCons := summarizeCons(series)
sum := models.Series{
Target: name,
QueryPatt: name,
Datapoints: out,
Interval: series[0].Interval,
Consolidator: cons,
QueryCons: queryCons,
Tags: map[string]string{"name": name},
}
cache[Req{}] = append(cache[Req{}], sum)
return sum
} | go | func sumSeries(series []models.Series, cache map[Req][]models.Series) models.Series {
if len(series) == 1 {
return series[0]
}
out := pointSlicePool.Get().([]schema.Point)
crossSeriesSum(series, &out)
var queryPatts []string
Loop:
for _, v := range series {
// avoid duplicates
for _, qp := range queryPatts {
if qp == v.QueryPatt {
continue Loop
}
}
queryPatts = append(queryPatts, v.QueryPatt)
}
name := fmt.Sprintf("sumSeries(%s)", strings.Join(queryPatts, ","))
cons, queryCons := summarizeCons(series)
sum := models.Series{
Target: name,
QueryPatt: name,
Datapoints: out,
Interval: series[0].Interval,
Consolidator: cons,
QueryCons: queryCons,
Tags: map[string]string{"name": name},
}
cache[Req{}] = append(cache[Req{}], sum)
return sum
} | [
"func",
"sumSeries",
"(",
"series",
"[",
"]",
"models",
".",
"Series",
",",
"cache",
"map",
"[",
"Req",
"]",
"[",
"]",
"models",
".",
"Series",
")",
"models",
".",
"Series",
"{",
"if",
"len",
"(",
"series",
")",
"==",
"1",
"{",
"return",
"series",
... | // sumSeries returns a copy-on-write series that is the sum of the inputs | [
"sumSeries",
"returns",
"a",
"copy",
"-",
"on",
"-",
"write",
"series",
"that",
"is",
"the",
"sum",
"of",
"the",
"inputs"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/expr/func_aspercent.go#L243-L274 | train |
grafana/metrictank | expr/func_removeabovebelowpercentile.go | getPercentileValue | func getPercentileValue(datapoints []schema.Point, n float64, sortedDatapointVals []float64) float64 {
sortedDatapointVals = sortedDatapointVals[:0]
for _, p := range datapoints {
if !math.IsNaN(p.Val) {
sortedDatapointVals = append(sortedDatapointVals, p.Val)
}
}
sort.Float64s(sortedDatapointVals)
index := math.Min(math.Ceil(n/100.0*float64(len(sortedDatapointVals)+1)), float64(len(sortedDatapointVals))) - 1
return sortedDatapointVals[int(index)]
} | go | func getPercentileValue(datapoints []schema.Point, n float64, sortedDatapointVals []float64) float64 {
sortedDatapointVals = sortedDatapointVals[:0]
for _, p := range datapoints {
if !math.IsNaN(p.Val) {
sortedDatapointVals = append(sortedDatapointVals, p.Val)
}
}
sort.Float64s(sortedDatapointVals)
index := math.Min(math.Ceil(n/100.0*float64(len(sortedDatapointVals)+1)), float64(len(sortedDatapointVals))) - 1
return sortedDatapointVals[int(index)]
} | [
"func",
"getPercentileValue",
"(",
"datapoints",
"[",
"]",
"schema",
".",
"Point",
",",
"n",
"float64",
",",
"sortedDatapointVals",
"[",
"]",
"float64",
")",
"float64",
"{",
"sortedDatapointVals",
"=",
"sortedDatapointVals",
"[",
":",
"0",
"]",
"\n",
"for",
... | // sortedDatapointVals is an empty slice to be used for sorting datapoints.
// n must be > 0. if n > 100, the largest value is returned. | [
"sortedDatapointVals",
"is",
"an",
"empty",
"slice",
"to",
"be",
"used",
"for",
"sorting",
"datapoints",
".",
"n",
"must",
"be",
">",
"0",
".",
"if",
"n",
">",
"100",
"the",
"largest",
"value",
"is",
"returned",
"."
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/expr/func_removeabovebelowpercentile.go#L92-L105 | train |
grafana/metrictank | cluster/node.go | MarshalJSON | func (n NodeMode) MarshalJSON() ([]byte, error) {
buffer := bytes.NewBufferString(`"`)
buffer.WriteString(n.String())
buffer.WriteString(`"`)
return buffer.Bytes(), nil
} | go | func (n NodeMode) MarshalJSON() ([]byte, error) {
buffer := bytes.NewBufferString(`"`)
buffer.WriteString(n.String())
buffer.WriteString(`"`)
return buffer.Bytes(), nil
} | [
"func",
"(",
"n",
"NodeMode",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"buffer",
":=",
"bytes",
".",
"NewBufferString",
"(",
"`\"`",
")",
"\n",
"buffer",
".",
"WriteString",
"(",
"n",
".",
"String",
"(",
")",
")"... | // MarshalJSON marshals a NodeMode | [
"MarshalJSON",
"marshals",
"a",
"NodeMode"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/cluster/node.go#L58-L63 | train |
grafana/metrictank | cluster/node.go | UnmarshalJSON | func (n *NodeMode) UnmarshalJSON(b []byte) error {
var j string
err := json.Unmarshal(b, &j)
if err != nil {
return err
}
*n, err = NodeModeFromString(j)
return err
} | go | func (n *NodeMode) UnmarshalJSON(b []byte) error {
var j string
err := json.Unmarshal(b, &j)
if err != nil {
return err
}
*n, err = NodeModeFromString(j)
return err
} | [
"func",
"(",
"n",
"*",
"NodeMode",
")",
"UnmarshalJSON",
"(",
"b",
"[",
"]",
"byte",
")",
"error",
"{",
"var",
"j",
"string",
"\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"b",
",",
"&",
"j",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"retur... | // UnmarshalJSON unmashals a NodeMode | [
"UnmarshalJSON",
"unmashals",
"a",
"NodeMode"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/cluster/node.go#L66-L74 | train |
grafana/metrictank | cluster/node.go | UnmarshalJSON | func (n *NodeState) UnmarshalJSON(data []byte) error {
s := string(data)
switch s {
case "0", `"NodeNotReady"`:
*n = NodeNotReady
case "1", `"NodeReady"`:
*n = NodeReady
case "2", `"NodeUnreachable"`:
*n = NodeUnreachable
default:
return fmt.Errorf("unrecognized NodeState %q", s)
}
return nil
} | go | func (n *NodeState) UnmarshalJSON(data []byte) error {
s := string(data)
switch s {
case "0", `"NodeNotReady"`:
*n = NodeNotReady
case "1", `"NodeReady"`:
*n = NodeReady
case "2", `"NodeUnreachable"`:
*n = NodeUnreachable
default:
return fmt.Errorf("unrecognized NodeState %q", s)
}
return nil
} | [
"func",
"(",
"n",
"*",
"NodeState",
")",
"UnmarshalJSON",
"(",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"s",
":=",
"string",
"(",
"data",
")",
"\n",
"switch",
"s",
"{",
"case",
"\"0\"",
",",
"`\"NodeNotReady\"`",
":",
"*",
"n",
"=",
"NodeNotReady... | // UnmarshalJSON supports unmarshalling according to the older
// integer based, as well as the new string based, representation | [
"UnmarshalJSON",
"supports",
"unmarshalling",
"according",
"to",
"the",
"older",
"integer",
"based",
"as",
"well",
"as",
"the",
"new",
"string",
"based",
"representation"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/cluster/node.go#L100-L113 | train |
grafana/metrictank | cluster/node.go | readyStateGCHandler | func (n HTTPNode) readyStateGCHandler() {
if gcPercent == gcPercentNotReady {
return
}
var err error
if n.IsReady() {
prev := debug.SetGCPercent(gcPercent)
if prev != gcPercent {
log.Infof("CLU: node is ready. changing GOGC from %d to %d", prev, gcPercent)
err = os.Setenv("GOGC", strconv.Itoa(gcPercent))
}
} else {
prev := debug.SetGCPercent(gcPercentNotReady)
if prev != gcPercentNotReady {
log.Infof("CLU: node is not ready. changing GOGC from %d to %d", prev, gcPercentNotReady)
err = os.Setenv("GOGC", strconv.Itoa(gcPercentNotReady))
}
}
if err != nil {
log.Warnf("CLU: could not set GOGC environment variable. gcPercent metric will be incorrect. %s", err.Error())
}
} | go | func (n HTTPNode) readyStateGCHandler() {
if gcPercent == gcPercentNotReady {
return
}
var err error
if n.IsReady() {
prev := debug.SetGCPercent(gcPercent)
if prev != gcPercent {
log.Infof("CLU: node is ready. changing GOGC from %d to %d", prev, gcPercent)
err = os.Setenv("GOGC", strconv.Itoa(gcPercent))
}
} else {
prev := debug.SetGCPercent(gcPercentNotReady)
if prev != gcPercentNotReady {
log.Infof("CLU: node is not ready. changing GOGC from %d to %d", prev, gcPercentNotReady)
err = os.Setenv("GOGC", strconv.Itoa(gcPercentNotReady))
}
}
if err != nil {
log.Warnf("CLU: could not set GOGC environment variable. gcPercent metric will be incorrect. %s", err.Error())
}
} | [
"func",
"(",
"n",
"HTTPNode",
")",
"readyStateGCHandler",
"(",
")",
"{",
"if",
"gcPercent",
"==",
"gcPercentNotReady",
"{",
"return",
"\n",
"}",
"\n",
"var",
"err",
"error",
"\n",
"if",
"n",
".",
"IsReady",
"(",
")",
"{",
"prev",
":=",
"debug",
".",
... | // readyStateGCHandler adjusts the gcPercent value based on the node ready state | [
"readyStateGCHandler",
"adjusts",
"the",
"gcPercent",
"value",
"based",
"on",
"the",
"node",
"ready",
"state"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/cluster/node.go#L192-L213 | train |
grafana/metrictank | cluster/node.go | SetState | func (n *HTTPNode) SetState(state NodeState) bool {
if n.State == state {
return false
}
n.State = state
now := time.Now()
n.Updated = now
n.StateChange = now
n.readyStateGCHandler()
return true
} | go | func (n *HTTPNode) SetState(state NodeState) bool {
if n.State == state {
return false
}
n.State = state
now := time.Now()
n.Updated = now
n.StateChange = now
n.readyStateGCHandler()
return true
} | [
"func",
"(",
"n",
"*",
"HTTPNode",
")",
"SetState",
"(",
"state",
"NodeState",
")",
"bool",
"{",
"if",
"n",
".",
"State",
"==",
"state",
"{",
"return",
"false",
"\n",
"}",
"\n",
"n",
".",
"State",
"=",
"state",
"\n",
"now",
":=",
"time",
".",
"No... | // SetState sets the state of the node and returns whether the state changed | [
"SetState",
"sets",
"the",
"state",
"of",
"the",
"node",
"and",
"returns",
"whether",
"the",
"state",
"changed"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/cluster/node.go#L216-L226 | train |
grafana/metrictank | cluster/node.go | SetPriority | func (n *HTTPNode) SetPriority(prio int) bool {
if n.Priority == prio {
return false
}
n.Priority = prio
n.Updated = time.Now()
n.readyStateGCHandler()
return true
} | go | func (n *HTTPNode) SetPriority(prio int) bool {
if n.Priority == prio {
return false
}
n.Priority = prio
n.Updated = time.Now()
n.readyStateGCHandler()
return true
} | [
"func",
"(",
"n",
"*",
"HTTPNode",
")",
"SetPriority",
"(",
"prio",
"int",
")",
"bool",
"{",
"if",
"n",
".",
"Priority",
"==",
"prio",
"{",
"return",
"false",
"\n",
"}",
"\n",
"n",
".",
"Priority",
"=",
"prio",
"\n",
"n",
".",
"Updated",
"=",
"ti... | // SetPriority sets the priority of the node and returns whether it changed | [
"SetPriority",
"sets",
"the",
"priority",
"of",
"the",
"node",
"and",
"returns",
"whether",
"it",
"changed"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/cluster/node.go#L229-L237 | train |
grafana/metrictank | cluster/node.go | SetPrimary | func (n *HTTPNode) SetPrimary(primary bool) bool {
if n.Primary == primary {
return false
}
now := time.Now()
n.Primary = primary
n.Updated = now
n.PrimaryChange = now
return true
} | go | func (n *HTTPNode) SetPrimary(primary bool) bool {
if n.Primary == primary {
return false
}
now := time.Now()
n.Primary = primary
n.Updated = now
n.PrimaryChange = now
return true
} | [
"func",
"(",
"n",
"*",
"HTTPNode",
")",
"SetPrimary",
"(",
"primary",
"bool",
")",
"bool",
"{",
"if",
"n",
".",
"Primary",
"==",
"primary",
"{",
"return",
"false",
"\n",
"}",
"\n",
"now",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"n",
".",
"Prima... | // SetPrimary sets the primary state of the node and returns whether it changed | [
"SetPrimary",
"sets",
"the",
"primary",
"state",
"of",
"the",
"node",
"and",
"returns",
"whether",
"it",
"changed"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/cluster/node.go#L240-L249 | train |
grafana/metrictank | cluster/node.go | SetPartitions | func (n *HTTPNode) SetPartitions(part []int32) {
n.Partitions = part
n.Updated = time.Now()
} | go | func (n *HTTPNode) SetPartitions(part []int32) {
n.Partitions = part
n.Updated = time.Now()
} | [
"func",
"(",
"n",
"*",
"HTTPNode",
")",
"SetPartitions",
"(",
"part",
"[",
"]",
"int32",
")",
"{",
"n",
".",
"Partitions",
"=",
"part",
"\n",
"n",
".",
"Updated",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"}"
] | // SetPartitions sets the partitions that this node is handling | [
"SetPartitions",
"sets",
"the",
"partitions",
"that",
"this",
"node",
"is",
"handling"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/cluster/node.go#L252-L255 | train |
grafana/metrictank | kafka/partitions.go | DiffPartitions | func DiffPartitions(a []int32, b []int32) []int32 {
var diff []int32
Iter:
for _, eA := range a {
for _, eB := range b {
if eA == eB {
continue Iter
}
}
diff = append(diff, eA)
}
return diff
} | go | func DiffPartitions(a []int32, b []int32) []int32 {
var diff []int32
Iter:
for _, eA := range a {
for _, eB := range b {
if eA == eB {
continue Iter
}
}
diff = append(diff, eA)
}
return diff
} | [
"func",
"DiffPartitions",
"(",
"a",
"[",
"]",
"int32",
",",
"b",
"[",
"]",
"int32",
")",
"[",
"]",
"int32",
"{",
"var",
"diff",
"[",
"]",
"int32",
"\n",
"Iter",
":",
"for",
"_",
",",
"eA",
":=",
"range",
"a",
"{",
"for",
"_",
",",
"eB",
":=",... | // returns elements that are in a but not in b | [
"returns",
"elements",
"that",
"are",
"in",
"a",
"but",
"not",
"in",
"b"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/kafka/partitions.go#L10-L22 | train |
grafana/metrictank | api/models/series.go | MarshalJSONFast | func (series SeriesByTarget) MarshalJSONFast(b []byte) ([]byte, error) {
b = append(b, '[')
for _, s := range series {
b = append(b, `{"target":`...)
b = strconv.AppendQuoteToASCII(b, s.Target)
if len(s.Tags) != 0 {
b = append(b, `,"tags":{`...)
for name, value := range s.Tags {
b = strconv.AppendQuoteToASCII(b, name)
b = append(b, ':')
b = strconv.AppendQuoteToASCII(b, value)
b = append(b, ',')
}
// Replace trailing comma with a closing bracket
b[len(b)-1] = '}'
}
b = append(b, `,"datapoints":[`...)
for _, p := range s.Datapoints {
b = append(b, '[')
if math.IsNaN(p.Val) {
b = append(b, `null,`...)
} else {
b = strconv.AppendFloat(b, p.Val, 'f', -1, 64)
b = append(b, ',')
}
b = strconv.AppendUint(b, uint64(p.Ts), 10)
b = append(b, `],`...)
}
if len(s.Datapoints) != 0 {
b = b[:len(b)-1] // cut last comma
}
b = append(b, `]},`...)
}
if len(series) != 0 {
b = b[:len(b)-1] // cut last comma
}
b = append(b, ']')
return b, nil
} | go | func (series SeriesByTarget) MarshalJSONFast(b []byte) ([]byte, error) {
b = append(b, '[')
for _, s := range series {
b = append(b, `{"target":`...)
b = strconv.AppendQuoteToASCII(b, s.Target)
if len(s.Tags) != 0 {
b = append(b, `,"tags":{`...)
for name, value := range s.Tags {
b = strconv.AppendQuoteToASCII(b, name)
b = append(b, ':')
b = strconv.AppendQuoteToASCII(b, value)
b = append(b, ',')
}
// Replace trailing comma with a closing bracket
b[len(b)-1] = '}'
}
b = append(b, `,"datapoints":[`...)
for _, p := range s.Datapoints {
b = append(b, '[')
if math.IsNaN(p.Val) {
b = append(b, `null,`...)
} else {
b = strconv.AppendFloat(b, p.Val, 'f', -1, 64)
b = append(b, ',')
}
b = strconv.AppendUint(b, uint64(p.Ts), 10)
b = append(b, `],`...)
}
if len(s.Datapoints) != 0 {
b = b[:len(b)-1] // cut last comma
}
b = append(b, `]},`...)
}
if len(series) != 0 {
b = b[:len(b)-1] // cut last comma
}
b = append(b, ']')
return b, nil
} | [
"func",
"(",
"series",
"SeriesByTarget",
")",
"MarshalJSONFast",
"(",
"b",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"b",
"=",
"append",
"(",
"b",
",",
"'['",
")",
"\n",
"for",
"_",
",",
"s",
":=",
"range",
"series",
... | // regular graphite output | [
"regular",
"graphite",
"output"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/api/models/series.go#L100-L138 | train |
grafana/metrictank | idx/memory/time_limit.go | NewTimeLimiter | func NewTimeLimiter(window, limit time.Duration, now time.Time) *TimeLimiter {
l := TimeLimiter{
since: now,
next: now.Add(window),
window: window,
limit: limit,
factor: float64(window) / float64(limit),
}
return &l
} | go | func NewTimeLimiter(window, limit time.Duration, now time.Time) *TimeLimiter {
l := TimeLimiter{
since: now,
next: now.Add(window),
window: window,
limit: limit,
factor: float64(window) / float64(limit),
}
return &l
} | [
"func",
"NewTimeLimiter",
"(",
"window",
",",
"limit",
"time",
".",
"Duration",
",",
"now",
"time",
".",
"Time",
")",
"*",
"TimeLimiter",
"{",
"l",
":=",
"TimeLimiter",
"{",
"since",
":",
"now",
",",
"next",
":",
"now",
".",
"Add",
"(",
"window",
")"... | // NewTimeLimiter creates a new TimeLimiter.
// limit must <= window | [
"NewTimeLimiter",
"creates",
"a",
"new",
"TimeLimiter",
".",
"limit",
"must",
"<",
"=",
"window"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/idx/memory/time_limit.go#L25-L34 | train |
grafana/metrictank | idx/memory/time_limit.go | Add | func (l *TimeLimiter) Add(d time.Duration) {
l.add(time.Now(), d)
} | go | func (l *TimeLimiter) Add(d time.Duration) {
l.add(time.Now(), d)
} | [
"func",
"(",
"l",
"*",
"TimeLimiter",
")",
"Add",
"(",
"d",
"time",
".",
"Duration",
")",
"{",
"l",
".",
"add",
"(",
"time",
".",
"Now",
"(",
")",
",",
"d",
")",
"\n",
"}"
] | // Add increments the "time spent" counter by "d" | [
"Add",
"increments",
"the",
"time",
"spent",
"counter",
"by",
"d"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/idx/memory/time_limit.go#L37-L39 | train |
grafana/metrictank | idx/memory/time_limit.go | add | func (l *TimeLimiter) add(now time.Time, d time.Duration) {
if now.After(l.next) {
l.timeSpent = d
l.since = now.Add(-d)
l.next = l.since.Add(l.window)
return
}
l.timeSpent += d
} | go | func (l *TimeLimiter) add(now time.Time, d time.Duration) {
if now.After(l.next) {
l.timeSpent = d
l.since = now.Add(-d)
l.next = l.since.Add(l.window)
return
}
l.timeSpent += d
} | [
"func",
"(",
"l",
"*",
"TimeLimiter",
")",
"add",
"(",
"now",
"time",
".",
"Time",
",",
"d",
"time",
".",
"Duration",
")",
"{",
"if",
"now",
".",
"After",
"(",
"l",
".",
"next",
")",
"{",
"l",
".",
"timeSpent",
"=",
"d",
"\n",
"l",
".",
"sinc... | // add increments the "time spent" counter by "d" at a given time | [
"add",
"increments",
"the",
"time",
"spent",
"counter",
"by",
"d",
"at",
"a",
"given",
"time"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/idx/memory/time_limit.go#L42-L50 | train |
grafana/metrictank | idx/memory/memory.go | AddOrUpdate | func (m *UnpartitionedMemoryIdx) AddOrUpdate(mkey schema.MKey, data *schema.MetricData, partition int32) (idx.Archive, int32, bool) {
pre := time.Now()
// Optimistically read lock
m.RLock()
existing, ok := m.defById[mkey]
if ok {
if log.IsLevelEnabled(log.DebugLevel) {
log.Debugf("memory-idx: metricDef with id %s already in index.", mkey)
}
bumpLastUpdate(&existing.LastUpdate, data.Time)
oldPart := atomic.SwapInt32(&existing.Partition, partition)
statUpdate.Inc()
statUpdateDuration.Value(time.Since(pre))
m.RUnlock()
return *existing, oldPart, ok
}
m.RUnlock()
m.Lock()
defer m.Unlock()
def := schema.MetricDefinitionFromMetricData(data)
def.Partition = partition
archive := m.add(def)
statMetricsActive.Inc()
statAddDuration.Value(time.Since(pre))
if TagSupport {
m.indexTags(def)
}
return archive, 0, false
} | go | func (m *UnpartitionedMemoryIdx) AddOrUpdate(mkey schema.MKey, data *schema.MetricData, partition int32) (idx.Archive, int32, bool) {
pre := time.Now()
// Optimistically read lock
m.RLock()
existing, ok := m.defById[mkey]
if ok {
if log.IsLevelEnabled(log.DebugLevel) {
log.Debugf("memory-idx: metricDef with id %s already in index.", mkey)
}
bumpLastUpdate(&existing.LastUpdate, data.Time)
oldPart := atomic.SwapInt32(&existing.Partition, partition)
statUpdate.Inc()
statUpdateDuration.Value(time.Since(pre))
m.RUnlock()
return *existing, oldPart, ok
}
m.RUnlock()
m.Lock()
defer m.Unlock()
def := schema.MetricDefinitionFromMetricData(data)
def.Partition = partition
archive := m.add(def)
statMetricsActive.Inc()
statAddDuration.Value(time.Since(pre))
if TagSupport {
m.indexTags(def)
}
return archive, 0, false
} | [
"func",
"(",
"m",
"*",
"UnpartitionedMemoryIdx",
")",
"AddOrUpdate",
"(",
"mkey",
"schema",
".",
"MKey",
",",
"data",
"*",
"schema",
".",
"MetricData",
",",
"partition",
"int32",
")",
"(",
"idx",
".",
"Archive",
",",
"int32",
",",
"bool",
")",
"{",
"pr... | // AddOrUpdate returns the corresponding Archive for the MetricData.
// if it is existing -> updates lastUpdate based on .Time, and partition
// if was new -> adds new MetricDefinition to index | [
"AddOrUpdate",
"returns",
"the",
"corresponding",
"Archive",
"for",
"the",
"MetricData",
".",
"if",
"it",
"is",
"existing",
"-",
">",
"updates",
"lastUpdate",
"based",
"on",
".",
"Time",
"and",
"partition",
"if",
"was",
"new",
"-",
">",
"adds",
"new",
"Met... | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/idx/memory/memory.go#L320-L354 | train |
grafana/metrictank | idx/memory/memory.go | indexTags | func (m *UnpartitionedMemoryIdx) indexTags(def *schema.MetricDefinition) {
tags, ok := m.tags[def.OrgId]
if !ok {
tags = make(TagIndex)
m.tags[def.OrgId] = tags
}
for _, tag := range def.Tags {
tagSplits := strings.SplitN(tag, "=", 2)
if len(tagSplits) < 2 {
// should never happen because every tag in the index
// must have a valid format
invalidTag.Inc()
log.Errorf("memory-idx: Tag %q of id %q has an invalid format", tag, def.Id)
continue
}
tagName := tagSplits[0]
tagValue := tagSplits[1]
tags.addTagId(tagName, tagValue, def.Id)
}
tags.addTagId("name", def.Name, def.Id)
m.defByTagSet.add(def)
} | go | func (m *UnpartitionedMemoryIdx) indexTags(def *schema.MetricDefinition) {
tags, ok := m.tags[def.OrgId]
if !ok {
tags = make(TagIndex)
m.tags[def.OrgId] = tags
}
for _, tag := range def.Tags {
tagSplits := strings.SplitN(tag, "=", 2)
if len(tagSplits) < 2 {
// should never happen because every tag in the index
// must have a valid format
invalidTag.Inc()
log.Errorf("memory-idx: Tag %q of id %q has an invalid format", tag, def.Id)
continue
}
tagName := tagSplits[0]
tagValue := tagSplits[1]
tags.addTagId(tagName, tagValue, def.Id)
}
tags.addTagId("name", def.Name, def.Id)
m.defByTagSet.add(def)
} | [
"func",
"(",
"m",
"*",
"UnpartitionedMemoryIdx",
")",
"indexTags",
"(",
"def",
"*",
"schema",
".",
"MetricDefinition",
")",
"{",
"tags",
",",
"ok",
":=",
"m",
".",
"tags",
"[",
"def",
".",
"OrgId",
"]",
"\n",
"if",
"!",
"ok",
"{",
"tags",
"=",
"mak... | // indexTags reads the tags of a given metric definition and creates the
// corresponding tag index entries to refer to it. It assumes a lock is
// already held. | [
"indexTags",
"reads",
"the",
"tags",
"of",
"a",
"given",
"metric",
"definition",
"and",
"creates",
"the",
"corresponding",
"tag",
"index",
"entries",
"to",
"refer",
"to",
"it",
".",
"It",
"assumes",
"a",
"lock",
"is",
"already",
"held",
"."
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/idx/memory/memory.go#L369-L393 | train |
grafana/metrictank | idx/memory/memory.go | deindexTags | func (m *UnpartitionedMemoryIdx) deindexTags(tags TagIndex, def *schema.MetricDefinition) bool {
for _, tag := range def.Tags {
tagSplits := strings.SplitN(tag, "=", 2)
if len(tagSplits) < 2 {
// should never happen because every tag in the index
// must have a valid format
invalidTag.Inc()
log.Errorf("memory-idx: Tag %q of id %q has an invalid format", tag, def.Id)
continue
}
tagName := tagSplits[0]
tagValue := tagSplits[1]
tags.delTagId(tagName, tagValue, def.Id)
}
tags.delTagId("name", def.Name, def.Id)
m.defByTagSet.del(def)
return true
} | go | func (m *UnpartitionedMemoryIdx) deindexTags(tags TagIndex, def *schema.MetricDefinition) bool {
for _, tag := range def.Tags {
tagSplits := strings.SplitN(tag, "=", 2)
if len(tagSplits) < 2 {
// should never happen because every tag in the index
// must have a valid format
invalidTag.Inc()
log.Errorf("memory-idx: Tag %q of id %q has an invalid format", tag, def.Id)
continue
}
tagName := tagSplits[0]
tagValue := tagSplits[1]
tags.delTagId(tagName, tagValue, def.Id)
}
tags.delTagId("name", def.Name, def.Id)
m.defByTagSet.del(def)
return true
} | [
"func",
"(",
"m",
"*",
"UnpartitionedMemoryIdx",
")",
"deindexTags",
"(",
"tags",
"TagIndex",
",",
"def",
"*",
"schema",
".",
"MetricDefinition",
")",
"bool",
"{",
"for",
"_",
",",
"tag",
":=",
"range",
"def",
".",
"Tags",
"{",
"tagSplits",
":=",
"string... | // deindexTags takes a given metric definition and removes all references
// to it from the tag index. It assumes a lock is already held.
// a return value of "false" means there was an error and the deindexing was
// unsuccessful, "true" means the indexing was at least partially or completely
// successful | [
"deindexTags",
"takes",
"a",
"given",
"metric",
"definition",
"and",
"removes",
"all",
"references",
"to",
"it",
"from",
"the",
"tag",
"index",
".",
"It",
"assumes",
"a",
"lock",
"is",
"already",
"held",
".",
"a",
"return",
"value",
"of",
"false",
"means",... | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/idx/memory/memory.go#L400-L421 | train |
grafana/metrictank | idx/memory/memory.go | LoadPartition | func (m *UnpartitionedMemoryIdx) LoadPartition(partition int32, defs []schema.MetricDefinition) int {
// UnpartitionedMemoryIdx isnt partitioned, so just ignore the partition passed and call Load()
return m.Load(defs)
} | go | func (m *UnpartitionedMemoryIdx) LoadPartition(partition int32, defs []schema.MetricDefinition) int {
// UnpartitionedMemoryIdx isnt partitioned, so just ignore the partition passed and call Load()
return m.Load(defs)
} | [
"func",
"(",
"m",
"*",
"UnpartitionedMemoryIdx",
")",
"LoadPartition",
"(",
"partition",
"int32",
",",
"defs",
"[",
"]",
"schema",
".",
"MetricDefinition",
")",
"int",
"{",
"return",
"m",
".",
"Load",
"(",
"defs",
")",
"\n",
"}"
] | // Used to rebuild the index from an existing set of metricDefinitions for a specific paritition. | [
"Used",
"to",
"rebuild",
"the",
"index",
"from",
"an",
"existing",
"set",
"of",
"metricDefinitions",
"for",
"a",
"specific",
"paritition",
"."
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/idx/memory/memory.go#L424-L427 | train |
grafana/metrictank | idx/memory/memory.go | GetPath | func (m *UnpartitionedMemoryIdx) GetPath(orgId uint32, path string) []idx.Archive {
m.RLock()
defer m.RUnlock()
tree, ok := m.tree[orgId]
if !ok {
return nil
}
node := tree.Items[path]
if node == nil {
return nil
}
archives := make([]idx.Archive, len(node.Defs))
for i, def := range node.Defs {
archive := m.defById[def]
archives[i] = *archive
}
return archives
} | go | func (m *UnpartitionedMemoryIdx) GetPath(orgId uint32, path string) []idx.Archive {
m.RLock()
defer m.RUnlock()
tree, ok := m.tree[orgId]
if !ok {
return nil
}
node := tree.Items[path]
if node == nil {
return nil
}
archives := make([]idx.Archive, len(node.Defs))
for i, def := range node.Defs {
archive := m.defById[def]
archives[i] = *archive
}
return archives
} | [
"func",
"(",
"m",
"*",
"UnpartitionedMemoryIdx",
")",
"GetPath",
"(",
"orgId",
"uint32",
",",
"path",
"string",
")",
"[",
"]",
"idx",
".",
"Archive",
"{",
"m",
".",
"RLock",
"(",
")",
"\n",
"defer",
"m",
".",
"RUnlock",
"(",
")",
"\n",
"tree",
",",... | // GetPath returns the node under the given org and path.
// this is an alternative to Find for when you have a path, not a pattern, and want to lookup in a specific org tree only. | [
"GetPath",
"returns",
"the",
"node",
"under",
"the",
"given",
"org",
"and",
"path",
".",
"this",
"is",
"an",
"alternative",
"to",
"Find",
"for",
"when",
"you",
"have",
"a",
"path",
"not",
"a",
"pattern",
"and",
"want",
"to",
"lookup",
"in",
"a",
"speci... | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/idx/memory/memory.go#L575-L592 | train |
grafana/metrictank | idx/memory/memory.go | Tags | func (m *UnpartitionedMemoryIdx) Tags(orgId uint32, filter string, from int64) ([]string, error) {
if !TagSupport {
log.Warn("memory-idx: received tag query, but tag support is disabled")
return nil, nil
}
var re *regexp.Regexp
if len(filter) > 0 {
if filter[0] != byte('^') {
filter = "^(?:" + filter + ")"
}
var err error
re, err = regexp.Compile(filter)
if err != nil {
return nil, err
}
}
m.RLock()
defer m.RUnlock()
tags, ok := m.tags[orgId]
if !ok {
return nil, nil
}
var res []string
// if there is no filter/from given we know how much space we'll need
// and can preallocate it
if re == nil && from == 0 {
res = make([]string, 0, len(tags))
}
for tag := range tags {
// filter by pattern if one was given
if re != nil && !re.MatchString(tag) {
continue
}
// if from is > 0 we need to find at least one metric definition where
// LastUpdate >= from before we add the tag to the result set
if (from > 0 && m.hasOneMetricFrom(tags, tag, from)) || from == 0 {
res = append(res, tag)
}
}
return res, nil
} | go | func (m *UnpartitionedMemoryIdx) Tags(orgId uint32, filter string, from int64) ([]string, error) {
if !TagSupport {
log.Warn("memory-idx: received tag query, but tag support is disabled")
return nil, nil
}
var re *regexp.Regexp
if len(filter) > 0 {
if filter[0] != byte('^') {
filter = "^(?:" + filter + ")"
}
var err error
re, err = regexp.Compile(filter)
if err != nil {
return nil, err
}
}
m.RLock()
defer m.RUnlock()
tags, ok := m.tags[orgId]
if !ok {
return nil, nil
}
var res []string
// if there is no filter/from given we know how much space we'll need
// and can preallocate it
if re == nil && from == 0 {
res = make([]string, 0, len(tags))
}
for tag := range tags {
// filter by pattern if one was given
if re != nil && !re.MatchString(tag) {
continue
}
// if from is > 0 we need to find at least one metric definition where
// LastUpdate >= from before we add the tag to the result set
if (from > 0 && m.hasOneMetricFrom(tags, tag, from)) || from == 0 {
res = append(res, tag)
}
}
return res, nil
} | [
"func",
"(",
"m",
"*",
"UnpartitionedMemoryIdx",
")",
"Tags",
"(",
"orgId",
"uint32",
",",
"filter",
"string",
",",
"from",
"int64",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"if",
"!",
"TagSupport",
"{",
"log",
".",
"Warn",
"(",
"\"memor... | // Tags returns a list of all tag keys associated with the metrics of a given
// organization. The return values are filtered by the regex in the second parameter.
// If the third parameter is >0 then only metrics will be accounted of which the
// LastUpdate time is >= the given value. | [
"Tags",
"returns",
"a",
"list",
"of",
"all",
"tag",
"keys",
"associated",
"with",
"the",
"metrics",
"of",
"a",
"given",
"organization",
".",
"The",
"return",
"values",
"are",
"filtered",
"by",
"the",
"regex",
"in",
"the",
"second",
"parameter",
".",
"If",
... | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/idx/memory/memory.go#L852-L900 | train |
grafana/metrictank | idx/memory/memory.go | deleteTaggedByIdSet | func (m *UnpartitionedMemoryIdx) deleteTaggedByIdSet(orgId uint32, ids IdSet) []idx.Archive {
tags, ok := m.tags[orgId]
if !ok {
return nil
}
deletedDefs := make([]idx.Archive, 0, len(ids))
for id := range ids {
idStr := id
def, ok := m.defById[idStr]
if !ok {
// not necessarily a corruption, the id could have been deleted
// while we switched from read to write lock
continue
}
if !m.deindexTags(tags, &def.MetricDefinition) {
continue
}
deletedDefs = append(deletedDefs, *def)
delete(m.defById, idStr)
}
statMetricsActive.Set(len(m.defById))
return deletedDefs
} | go | func (m *UnpartitionedMemoryIdx) deleteTaggedByIdSet(orgId uint32, ids IdSet) []idx.Archive {
tags, ok := m.tags[orgId]
if !ok {
return nil
}
deletedDefs := make([]idx.Archive, 0, len(ids))
for id := range ids {
idStr := id
def, ok := m.defById[idStr]
if !ok {
// not necessarily a corruption, the id could have been deleted
// while we switched from read to write lock
continue
}
if !m.deindexTags(tags, &def.MetricDefinition) {
continue
}
deletedDefs = append(deletedDefs, *def)
delete(m.defById, idStr)
}
statMetricsActive.Set(len(m.defById))
return deletedDefs
} | [
"func",
"(",
"m",
"*",
"UnpartitionedMemoryIdx",
")",
"deleteTaggedByIdSet",
"(",
"orgId",
"uint32",
",",
"ids",
"IdSet",
")",
"[",
"]",
"idx",
".",
"Archive",
"{",
"tags",
",",
"ok",
":=",
"m",
".",
"tags",
"[",
"orgId",
"]",
"\n",
"if",
"!",
"ok",
... | // deleteTaggedByIdSet deletes a map of ids from the tag index and also the DefByIds
// it is important that only IDs of series with tags get passed in here, because
// otherwise the result might be inconsistencies between DefByIDs and the tree index. | [
"deleteTaggedByIdSet",
"deletes",
"a",
"map",
"of",
"ids",
"from",
"the",
"tag",
"index",
"and",
"also",
"the",
"DefByIds",
"it",
"is",
"important",
"that",
"only",
"IDs",
"of",
"series",
"with",
"tags",
"get",
"passed",
"in",
"here",
"because",
"otherwise",... | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/idx/memory/memory.go#L1212-L1237 | train |
grafana/metrictank | util/util.go | Lcm | func Lcm(vals []uint32) uint32 {
out := vals[0]
for i := 1; i < len(vals); i++ {
max := Max(uint32(vals[i]), out)
min := Min(uint32(vals[i]), out)
r := max % min
if r != 0 {
for j := uint32(2); j <= min; j++ {
if (j*max)%min == 0 {
out = j * max
break
}
}
} else {
out = max
}
}
return out
} | go | func Lcm(vals []uint32) uint32 {
out := vals[0]
for i := 1; i < len(vals); i++ {
max := Max(uint32(vals[i]), out)
min := Min(uint32(vals[i]), out)
r := max % min
if r != 0 {
for j := uint32(2); j <= min; j++ {
if (j*max)%min == 0 {
out = j * max
break
}
}
} else {
out = max
}
}
return out
} | [
"func",
"Lcm",
"(",
"vals",
"[",
"]",
"uint32",
")",
"uint32",
"{",
"out",
":=",
"vals",
"[",
"0",
"]",
"\n",
"for",
"i",
":=",
"1",
";",
"i",
"<",
"len",
"(",
"vals",
")",
";",
"i",
"++",
"{",
"max",
":=",
"Max",
"(",
"uint32",
"(",
"vals"... | // Lcm returns the least common multiple | [
"Lcm",
"returns",
"the",
"least",
"common",
"multiple"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/util/util.go#L25-L43 | train |
grafana/metrictank | input/input.go | ProcessMetricPoint | func (in DefaultHandler) ProcessMetricPoint(point schema.MetricPoint, format msg.Format, partition int32) {
if format == msg.FormatMetricPoint {
in.receivedMP.Inc()
} else {
in.receivedMPNO.Inc()
}
// in cassandra we store timestamps as 32bit signed integers.
// math.MaxInt32 = Jan 19 03:14:07 UTC 2038
if !point.Valid() || point.Time >= math.MaxInt32 {
in.invalidMP.Inc()
mdata.PromDiscardedSamples.WithLabelValues(invalidTimestamp, strconv.Itoa(int(point.MKey.Org))).Inc()
log.Debugf("in: Invalid metric %v", point)
return
}
archive, _, ok := in.metricIndex.Update(point, partition)
if !ok {
in.unknownMP.Inc()
mdata.PromDiscardedSamples.WithLabelValues(unknownPointId, strconv.Itoa(int(point.MKey.Org))).Inc()
return
}
m := in.metrics.GetOrCreate(point.MKey, archive.SchemaId, archive.AggId, uint32(archive.Interval))
m.Add(point.Time, point.Value)
} | go | func (in DefaultHandler) ProcessMetricPoint(point schema.MetricPoint, format msg.Format, partition int32) {
if format == msg.FormatMetricPoint {
in.receivedMP.Inc()
} else {
in.receivedMPNO.Inc()
}
// in cassandra we store timestamps as 32bit signed integers.
// math.MaxInt32 = Jan 19 03:14:07 UTC 2038
if !point.Valid() || point.Time >= math.MaxInt32 {
in.invalidMP.Inc()
mdata.PromDiscardedSamples.WithLabelValues(invalidTimestamp, strconv.Itoa(int(point.MKey.Org))).Inc()
log.Debugf("in: Invalid metric %v", point)
return
}
archive, _, ok := in.metricIndex.Update(point, partition)
if !ok {
in.unknownMP.Inc()
mdata.PromDiscardedSamples.WithLabelValues(unknownPointId, strconv.Itoa(int(point.MKey.Org))).Inc()
return
}
m := in.metrics.GetOrCreate(point.MKey, archive.SchemaId, archive.AggId, uint32(archive.Interval))
m.Add(point.Time, point.Value)
} | [
"func",
"(",
"in",
"DefaultHandler",
")",
"ProcessMetricPoint",
"(",
"point",
"schema",
".",
"MetricPoint",
",",
"format",
"msg",
".",
"Format",
",",
"partition",
"int32",
")",
"{",
"if",
"format",
"==",
"msg",
".",
"FormatMetricPoint",
"{",
"in",
".",
"re... | // ProcessMetricPoint updates the index if possible, and stores the data if we have an index entry
// concurrency-safe. | [
"ProcessMetricPoint",
"updates",
"the",
"index",
"if",
"possible",
"and",
"stores",
"the",
"data",
"if",
"we",
"have",
"an",
"index",
"entry",
"concurrency",
"-",
"safe",
"."
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/input/input.go#L72-L97 | train |
grafana/metrictank | input/input.go | ProcessMetricData | func (in DefaultHandler) ProcessMetricData(md *schema.MetricData, partition int32) {
in.receivedMD.Inc()
err := md.Validate()
if err != nil {
in.invalidMD.Inc()
log.Debugf("in: Invalid metric %v: %s", md, err)
var reason string
switch err {
case schema.ErrInvalidIntervalzero:
reason = invalidInterval
case schema.ErrInvalidOrgIdzero:
reason = invalidOrgId
case schema.ErrInvalidEmptyName:
reason = invalidName
case schema.ErrInvalidMtype:
reason = invalidMtype
case schema.ErrInvalidTagFormat:
reason = invalidTagFormat
default:
reason = "unknown"
}
mdata.PromDiscardedSamples.WithLabelValues(reason, strconv.Itoa(md.OrgId)).Inc()
return
}
// in cassandra we store timestamps and interval as 32bit signed integers.
// math.MaxInt32 = Jan 19 03:14:07 UTC 2038
if md.Time <= 0 || md.Time >= math.MaxInt32 {
in.invalidMD.Inc()
mdata.PromDiscardedSamples.WithLabelValues(invalidTimestamp, strconv.Itoa(md.OrgId)).Inc()
log.Warnf("in: invalid metric %q: .Time %d out of range", md.Id, md.Time)
return
}
if md.Interval <= 0 || md.Interval >= math.MaxInt32 {
in.invalidMD.Inc()
mdata.PromDiscardedSamples.WithLabelValues(invalidInterval, strconv.Itoa(md.OrgId)).Inc()
log.Warnf("in: invalid metric %q. .Interval %d out of range", md.Id, md.Interval)
return
}
mkey, err := schema.MKeyFromString(md.Id)
if err != nil {
log.Errorf("in: Invalid metric %v: could not parse ID: %s", md, err)
return
}
archive, _, _ := in.metricIndex.AddOrUpdate(mkey, md, partition)
m := in.metrics.GetOrCreate(mkey, archive.SchemaId, archive.AggId, uint32(md.Interval))
m.Add(uint32(md.Time), md.Value)
} | go | func (in DefaultHandler) ProcessMetricData(md *schema.MetricData, partition int32) {
in.receivedMD.Inc()
err := md.Validate()
if err != nil {
in.invalidMD.Inc()
log.Debugf("in: Invalid metric %v: %s", md, err)
var reason string
switch err {
case schema.ErrInvalidIntervalzero:
reason = invalidInterval
case schema.ErrInvalidOrgIdzero:
reason = invalidOrgId
case schema.ErrInvalidEmptyName:
reason = invalidName
case schema.ErrInvalidMtype:
reason = invalidMtype
case schema.ErrInvalidTagFormat:
reason = invalidTagFormat
default:
reason = "unknown"
}
mdata.PromDiscardedSamples.WithLabelValues(reason, strconv.Itoa(md.OrgId)).Inc()
return
}
// in cassandra we store timestamps and interval as 32bit signed integers.
// math.MaxInt32 = Jan 19 03:14:07 UTC 2038
if md.Time <= 0 || md.Time >= math.MaxInt32 {
in.invalidMD.Inc()
mdata.PromDiscardedSamples.WithLabelValues(invalidTimestamp, strconv.Itoa(md.OrgId)).Inc()
log.Warnf("in: invalid metric %q: .Time %d out of range", md.Id, md.Time)
return
}
if md.Interval <= 0 || md.Interval >= math.MaxInt32 {
in.invalidMD.Inc()
mdata.PromDiscardedSamples.WithLabelValues(invalidInterval, strconv.Itoa(md.OrgId)).Inc()
log.Warnf("in: invalid metric %q. .Interval %d out of range", md.Id, md.Interval)
return
}
mkey, err := schema.MKeyFromString(md.Id)
if err != nil {
log.Errorf("in: Invalid metric %v: could not parse ID: %s", md, err)
return
}
archive, _, _ := in.metricIndex.AddOrUpdate(mkey, md, partition)
m := in.metrics.GetOrCreate(mkey, archive.SchemaId, archive.AggId, uint32(md.Interval))
m.Add(uint32(md.Time), md.Value)
} | [
"func",
"(",
"in",
"DefaultHandler",
")",
"ProcessMetricData",
"(",
"md",
"*",
"schema",
".",
"MetricData",
",",
"partition",
"int32",
")",
"{",
"in",
".",
"receivedMD",
".",
"Inc",
"(",
")",
"\n",
"err",
":=",
"md",
".",
"Validate",
"(",
")",
"\n",
... | // ProcessMetricData assures the data is stored and the metadata is in the index
// concurrency-safe. | [
"ProcessMetricData",
"assures",
"the",
"data",
"is",
"stored",
"and",
"the",
"metadata",
"is",
"in",
"the",
"index",
"concurrency",
"-",
"safe",
"."
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/input/input.go#L101-L152 | train |
grafana/metrictank | idx/bigtable/schema.go | FormatRowKey | func FormatRowKey(mkey schema.MKey, partition int32) string {
return strconv.Itoa(int(partition)) + "_" + mkey.String()
} | go | func FormatRowKey(mkey schema.MKey, partition int32) string {
return strconv.Itoa(int(partition)) + "_" + mkey.String()
} | [
"func",
"FormatRowKey",
"(",
"mkey",
"schema",
".",
"MKey",
",",
"partition",
"int32",
")",
"string",
"{",
"return",
"strconv",
".",
"Itoa",
"(",
"int",
"(",
"partition",
")",
")",
"+",
"\"_\"",
"+",
"mkey",
".",
"String",
"(",
")",
"\n",
"}"
] | // FormatRowKey formats an MKey and partition into a rowKey | [
"FormatRowKey",
"formats",
"an",
"MKey",
"and",
"partition",
"into",
"a",
"rowKey"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/idx/bigtable/schema.go#L16-L18 | train |
grafana/metrictank | idx/bigtable/schema.go | SchemaToRow | func SchemaToRow(def *schema.MetricDefinition) (string, map[string][]byte) {
row := map[string][]byte{
//"Id" omitted as it is part of the rowKey
"OrgId": make([]byte, 8),
"Name": []byte(def.Name),
"Interval": make([]byte, 8),
"Unit": []byte(def.Unit),
"Mtype": []byte(def.Mtype),
"Tags": []byte(strings.Join(def.Tags, ";")),
"LastUpdate": make([]byte, 8),
//"Partition" omitted as it is part of te rowKey
}
binary.PutVarint(row["OrgId"], int64(def.OrgId))
binary.PutVarint(row["Interval"], int64(def.Interval))
binary.PutVarint(row["LastUpdate"], def.LastUpdate)
return FormatRowKey(def.Id, def.Partition), row
} | go | func SchemaToRow(def *schema.MetricDefinition) (string, map[string][]byte) {
row := map[string][]byte{
//"Id" omitted as it is part of the rowKey
"OrgId": make([]byte, 8),
"Name": []byte(def.Name),
"Interval": make([]byte, 8),
"Unit": []byte(def.Unit),
"Mtype": []byte(def.Mtype),
"Tags": []byte(strings.Join(def.Tags, ";")),
"LastUpdate": make([]byte, 8),
//"Partition" omitted as it is part of te rowKey
}
binary.PutVarint(row["OrgId"], int64(def.OrgId))
binary.PutVarint(row["Interval"], int64(def.Interval))
binary.PutVarint(row["LastUpdate"], def.LastUpdate)
return FormatRowKey(def.Id, def.Partition), row
} | [
"func",
"SchemaToRow",
"(",
"def",
"*",
"schema",
".",
"MetricDefinition",
")",
"(",
"string",
",",
"map",
"[",
"string",
"]",
"[",
"]",
"byte",
")",
"{",
"row",
":=",
"map",
"[",
"string",
"]",
"[",
"]",
"byte",
"{",
"\"OrgId\"",
":",
"make",
"(",... | // SchemaToRow takes a metricDefintion and returns a rowKey and column data. | [
"SchemaToRow",
"takes",
"a",
"metricDefintion",
"and",
"returns",
"a",
"rowKey",
"and",
"column",
"data",
"."
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/idx/bigtable/schema.go#L21-L37 | train |
grafana/metrictank | idx/bigtable/schema.go | DecodeRowKey | func DecodeRowKey(key string) (schema.MKey, int32, error) {
parts := strings.SplitN(key, "_", 2)
partition, err := strconv.Atoi(parts[0])
if err != nil {
return schema.MKey{}, 0, err
}
mkey, err := schema.MKeyFromString(parts[1])
if err != nil {
return schema.MKey{}, 0, err
}
return mkey, int32(partition), nil
} | go | func DecodeRowKey(key string) (schema.MKey, int32, error) {
parts := strings.SplitN(key, "_", 2)
partition, err := strconv.Atoi(parts[0])
if err != nil {
return schema.MKey{}, 0, err
}
mkey, err := schema.MKeyFromString(parts[1])
if err != nil {
return schema.MKey{}, 0, err
}
return mkey, int32(partition), nil
} | [
"func",
"DecodeRowKey",
"(",
"key",
"string",
")",
"(",
"schema",
".",
"MKey",
",",
"int32",
",",
"error",
")",
"{",
"parts",
":=",
"strings",
".",
"SplitN",
"(",
"key",
",",
"\"_\"",
",",
"2",
")",
"\n",
"partition",
",",
"err",
":=",
"strconv",
"... | // DecodeRowKey takes a rowKey string and returns the corresponding MKey and partition | [
"DecodeRowKey",
"takes",
"a",
"rowKey",
"string",
"and",
"returns",
"the",
"corresponding",
"MKey",
"and",
"partition"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/idx/bigtable/schema.go#L40-L51 | train |
grafana/metrictank | idx/bigtable/schema.go | RowToSchema | func RowToSchema(row bigtable.Row, def *schema.MetricDefinition) error {
if def == nil {
return fmt.Errorf("cant write row to nil MetricDefinition")
}
columns, ok := row[COLUMN_FAMILY]
if !ok {
return fmt.Errorf("no columns in columnFamly %s", COLUMN_FAMILY)
}
*def = schema.MetricDefinition{}
var err error
var val int64
def.Id, def.Partition, err = DecodeRowKey(row.Key())
if err != nil {
return err
}
for _, col := range columns {
switch strings.SplitN(col.Column, ":", 2)[1] {
case "OrgId":
val, err = binary.ReadVarint(bytes.NewReader(col.Value))
if err != nil {
return err
}
if val < 0 {
def.OrgId = idx.OrgIdPublic
} else {
def.OrgId = uint32(val)
}
case "Name":
def.Name = string(col.Value)
case "Interval":
val, err = binary.ReadVarint(bytes.NewReader(col.Value))
if err != nil {
return err
}
def.Interval = int(val)
case "Unit":
def.Unit = string(col.Value)
case "Mtype":
def.Mtype = string(col.Value)
case "Tags":
if len(col.Value) == 0 {
def.Tags = nil
} else {
def.Tags = strings.Split(string(col.Value), ";")
}
case "LastUpdate":
def.LastUpdate, err = binary.ReadVarint(bytes.NewReader(col.Value))
if err != nil {
return err
}
default:
return fmt.Errorf("unknown column: %s", col.Column)
}
}
return nil
} | go | func RowToSchema(row bigtable.Row, def *schema.MetricDefinition) error {
if def == nil {
return fmt.Errorf("cant write row to nil MetricDefinition")
}
columns, ok := row[COLUMN_FAMILY]
if !ok {
return fmt.Errorf("no columns in columnFamly %s", COLUMN_FAMILY)
}
*def = schema.MetricDefinition{}
var err error
var val int64
def.Id, def.Partition, err = DecodeRowKey(row.Key())
if err != nil {
return err
}
for _, col := range columns {
switch strings.SplitN(col.Column, ":", 2)[1] {
case "OrgId":
val, err = binary.ReadVarint(bytes.NewReader(col.Value))
if err != nil {
return err
}
if val < 0 {
def.OrgId = idx.OrgIdPublic
} else {
def.OrgId = uint32(val)
}
case "Name":
def.Name = string(col.Value)
case "Interval":
val, err = binary.ReadVarint(bytes.NewReader(col.Value))
if err != nil {
return err
}
def.Interval = int(val)
case "Unit":
def.Unit = string(col.Value)
case "Mtype":
def.Mtype = string(col.Value)
case "Tags":
if len(col.Value) == 0 {
def.Tags = nil
} else {
def.Tags = strings.Split(string(col.Value), ";")
}
case "LastUpdate":
def.LastUpdate, err = binary.ReadVarint(bytes.NewReader(col.Value))
if err != nil {
return err
}
default:
return fmt.Errorf("unknown column: %s", col.Column)
}
}
return nil
} | [
"func",
"RowToSchema",
"(",
"row",
"bigtable",
".",
"Row",
",",
"def",
"*",
"schema",
".",
"MetricDefinition",
")",
"error",
"{",
"if",
"def",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"cant write row to nil MetricDefinition\"",
")",
"\n",
"}"... | // RowToSchema takes a row and unmarshals the data into the provided MetricDefinition. | [
"RowToSchema",
"takes",
"a",
"row",
"and",
"unmarshals",
"the",
"data",
"into",
"the",
"provided",
"MetricDefinition",
"."
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/idx/bigtable/schema.go#L54-L110 | train |
grafana/metrictank | consolidation/consolidation.go | String | func (c Consolidator) String() string {
switch c {
case None:
return "NoneConsolidator"
case Avg:
return "AverageConsolidator"
case Cnt:
return "CountConsolidator"
case Lst:
return "LastConsolidator"
case Min:
return "MinimumConsolidator"
case Max:
return "MaximumConsolidator"
case Mult:
return "MultiplyConsolidator"
case Med:
return "MedianConsolidator"
case Diff:
return "DifferenceConsolidator"
case StdDev:
return "StdDevConsolidator"
case Range:
return "RangeConsolidator"
case Sum:
return "SumConsolidator"
}
panic(fmt.Sprintf("Consolidator.String(): unknown consolidator %d", c))
} | go | func (c Consolidator) String() string {
switch c {
case None:
return "NoneConsolidator"
case Avg:
return "AverageConsolidator"
case Cnt:
return "CountConsolidator"
case Lst:
return "LastConsolidator"
case Min:
return "MinimumConsolidator"
case Max:
return "MaximumConsolidator"
case Mult:
return "MultiplyConsolidator"
case Med:
return "MedianConsolidator"
case Diff:
return "DifferenceConsolidator"
case StdDev:
return "StdDevConsolidator"
case Range:
return "RangeConsolidator"
case Sum:
return "SumConsolidator"
}
panic(fmt.Sprintf("Consolidator.String(): unknown consolidator %d", c))
} | [
"func",
"(",
"c",
"Consolidator",
")",
"String",
"(",
")",
"string",
"{",
"switch",
"c",
"{",
"case",
"None",
":",
"return",
"\"NoneConsolidator\"",
"\n",
"case",
"Avg",
":",
"return",
"\"AverageConsolidator\"",
"\n",
"case",
"Cnt",
":",
"return",
"\"CountCo... | // String provides human friendly names | [
"String",
"provides",
"human",
"friendly",
"names"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/consolidation/consolidation.go#L36-L64 | train |
grafana/metrictank | consolidation/consolidation.go | Archive | func (c Consolidator) Archive() schema.Method {
switch c {
case None:
panic("cannot get an archive for no consolidation")
case Avg:
panic("avg consolidator has no matching Archive(). you need sum and cnt")
case Cnt:
return schema.Cnt
case Lst:
return schema.Lst
case Min:
return schema.Min
case Max:
return schema.Max
case Sum:
return schema.Sum
}
panic(fmt.Sprintf("Consolidator.Archive(): unknown consolidator %q", c))
} | go | func (c Consolidator) Archive() schema.Method {
switch c {
case None:
panic("cannot get an archive for no consolidation")
case Avg:
panic("avg consolidator has no matching Archive(). you need sum and cnt")
case Cnt:
return schema.Cnt
case Lst:
return schema.Lst
case Min:
return schema.Min
case Max:
return schema.Max
case Sum:
return schema.Sum
}
panic(fmt.Sprintf("Consolidator.Archive(): unknown consolidator %q", c))
} | [
"func",
"(",
"c",
"Consolidator",
")",
"Archive",
"(",
")",
"schema",
".",
"Method",
"{",
"switch",
"c",
"{",
"case",
"None",
":",
"panic",
"(",
"\"cannot get an archive for no consolidation\"",
")",
"\n",
"case",
"Avg",
":",
"panic",
"(",
"\"avg consolidator ... | // provide the name of a stored archive
// see aggregator.go for which archives are available | [
"provide",
"the",
"name",
"of",
"a",
"stored",
"archive",
"see",
"aggregator",
".",
"go",
"for",
"which",
"archives",
"are",
"available"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/consolidation/consolidation.go#L68-L86 | train |
grafana/metrictank | consolidation/consolidation.go | GetAggFunc | func GetAggFunc(consolidator Consolidator) batch.AggFunc {
var consFunc batch.AggFunc
switch consolidator {
case Avg:
consFunc = batch.Avg
case Cnt:
consFunc = batch.Cnt
case Lst:
consFunc = batch.Lst
case Min:
consFunc = batch.Min
case Max:
consFunc = batch.Max
case Mult:
consFunc = batch.Mult
case Med:
consFunc = batch.Med
case Diff:
consFunc = batch.Diff
case StdDev:
consFunc = batch.StdDev
case Range:
consFunc = batch.Range
case Sum:
consFunc = batch.Sum
}
return consFunc
} | go | func GetAggFunc(consolidator Consolidator) batch.AggFunc {
var consFunc batch.AggFunc
switch consolidator {
case Avg:
consFunc = batch.Avg
case Cnt:
consFunc = batch.Cnt
case Lst:
consFunc = batch.Lst
case Min:
consFunc = batch.Min
case Max:
consFunc = batch.Max
case Mult:
consFunc = batch.Mult
case Med:
consFunc = batch.Med
case Diff:
consFunc = batch.Diff
case StdDev:
consFunc = batch.StdDev
case Range:
consFunc = batch.Range
case Sum:
consFunc = batch.Sum
}
return consFunc
} | [
"func",
"GetAggFunc",
"(",
"consolidator",
"Consolidator",
")",
"batch",
".",
"AggFunc",
"{",
"var",
"consFunc",
"batch",
".",
"AggFunc",
"\n",
"switch",
"consolidator",
"{",
"case",
"Avg",
":",
"consFunc",
"=",
"batch",
".",
"Avg",
"\n",
"case",
"Cnt",
":... | // map the consolidation to the respective aggregation function, if applicable. | [
"map",
"the",
"consolidation",
"to",
"the",
"respective",
"aggregation",
"function",
"if",
"applicable",
"."
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/consolidation/consolidation.go#L133-L160 | train |
grafana/metrictank | idx/bigtable/bigtable.go | updateBigtable | func (b *BigtableIdx) updateBigtable(now uint32, inMemory bool, archive idx.Archive, partition int32) idx.Archive {
// if the entry has not been saved for 1.5x updateInterval
// then perform a blocking save.
if archive.LastSave < (now - b.cfg.updateInterval32 - (b.cfg.updateInterval32 / 2)) {
log.Debugf("bigtable-idx: updating def %s in index.", archive.MetricDefinition.Id)
b.writeQueue <- writeReq{recvTime: time.Now(), def: &archive.MetricDefinition}
archive.LastSave = now
b.MemoryIndex.UpdateArchive(archive)
} else {
// perform a non-blocking write to the writeQueue. If the queue is full, then
// this will fail and we won't update the LastSave timestamp. The next time
// the metric is seen, the previous lastSave timestamp will still be in place and so
// we will try and save again. This will continue until we are successful or the
// lastSave timestamp become more then 1.5 x UpdateInterval, in which case we will
// do a blocking write to the queue.
select {
case b.writeQueue <- writeReq{recvTime: time.Now(), def: &archive.MetricDefinition}:
archive.LastSave = now
b.MemoryIndex.UpdateArchive(archive)
default:
statSaveSkipped.Inc()
log.Debugf("bigtable-idx: writeQueue is full, update of %s not saved this time", archive.MetricDefinition.Id)
}
}
return archive
} | go | func (b *BigtableIdx) updateBigtable(now uint32, inMemory bool, archive idx.Archive, partition int32) idx.Archive {
// if the entry has not been saved for 1.5x updateInterval
// then perform a blocking save.
if archive.LastSave < (now - b.cfg.updateInterval32 - (b.cfg.updateInterval32 / 2)) {
log.Debugf("bigtable-idx: updating def %s in index.", archive.MetricDefinition.Id)
b.writeQueue <- writeReq{recvTime: time.Now(), def: &archive.MetricDefinition}
archive.LastSave = now
b.MemoryIndex.UpdateArchive(archive)
} else {
// perform a non-blocking write to the writeQueue. If the queue is full, then
// this will fail and we won't update the LastSave timestamp. The next time
// the metric is seen, the previous lastSave timestamp will still be in place and so
// we will try and save again. This will continue until we are successful or the
// lastSave timestamp become more then 1.5 x UpdateInterval, in which case we will
// do a blocking write to the queue.
select {
case b.writeQueue <- writeReq{recvTime: time.Now(), def: &archive.MetricDefinition}:
archive.LastSave = now
b.MemoryIndex.UpdateArchive(archive)
default:
statSaveSkipped.Inc()
log.Debugf("bigtable-idx: writeQueue is full, update of %s not saved this time", archive.MetricDefinition.Id)
}
}
return archive
} | [
"func",
"(",
"b",
"*",
"BigtableIdx",
")",
"updateBigtable",
"(",
"now",
"uint32",
",",
"inMemory",
"bool",
",",
"archive",
"idx",
".",
"Archive",
",",
"partition",
"int32",
")",
"idx",
".",
"Archive",
"{",
"if",
"archive",
".",
"LastSave",
"<",
"(",
"... | // updateBigtable saves the archive to bigtable and
// updates the memory index with the updated fields. | [
"updateBigtable",
"saves",
"the",
"archive",
"to",
"bigtable",
"and",
"updates",
"the",
"memory",
"index",
"with",
"the",
"updated",
"fields",
"."
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/idx/bigtable/bigtable.go#L282-L308 | train |
grafana/metrictank | mdata/cache/ccache_metric.go | NewCCacheMetric | func NewCCacheMetric(mkey schema.MKey) *CCacheMetric {
return &CCacheMetric{
MKey: mkey,
chunks: make(map[uint32]*CCacheChunk),
}
} | go | func NewCCacheMetric(mkey schema.MKey) *CCacheMetric {
return &CCacheMetric{
MKey: mkey,
chunks: make(map[uint32]*CCacheChunk),
}
} | [
"func",
"NewCCacheMetric",
"(",
"mkey",
"schema",
".",
"MKey",
")",
"*",
"CCacheMetric",
"{",
"return",
"&",
"CCacheMetric",
"{",
"MKey",
":",
"mkey",
",",
"chunks",
":",
"make",
"(",
"map",
"[",
"uint32",
"]",
"*",
"CCacheChunk",
")",
",",
"}",
"\n",
... | // NewCCacheMetric creates a CCacheMetric | [
"NewCCacheMetric",
"creates",
"a",
"CCacheMetric"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/mdata/cache/ccache_metric.go#L29-L34 | train |
grafana/metrictank | mdata/cache/ccache_metric.go | Del | func (mc *CCacheMetric) Del(ts uint32) int {
mc.Lock()
defer mc.Unlock()
if _, ok := mc.chunks[ts]; !ok {
return len(mc.chunks)
}
prev := mc.chunks[ts].Prev
next := mc.chunks[ts].Next
if prev != 0 {
if _, ok := mc.chunks[prev]; ok {
mc.chunks[prev].Next = 0
}
}
if next != 0 {
if _, ok := mc.chunks[next]; ok {
mc.chunks[next].Prev = 0
}
}
delete(mc.chunks, ts)
// regenerate the list of sorted keys after deleting a chunk
// NOTE: we can improve perf by just taking out the ts (partially rewriting
// the slice in one go), can we also batch deletes?
mc.generateKeys()
return len(mc.chunks)
} | go | func (mc *CCacheMetric) Del(ts uint32) int {
mc.Lock()
defer mc.Unlock()
if _, ok := mc.chunks[ts]; !ok {
return len(mc.chunks)
}
prev := mc.chunks[ts].Prev
next := mc.chunks[ts].Next
if prev != 0 {
if _, ok := mc.chunks[prev]; ok {
mc.chunks[prev].Next = 0
}
}
if next != 0 {
if _, ok := mc.chunks[next]; ok {
mc.chunks[next].Prev = 0
}
}
delete(mc.chunks, ts)
// regenerate the list of sorted keys after deleting a chunk
// NOTE: we can improve perf by just taking out the ts (partially rewriting
// the slice in one go), can we also batch deletes?
mc.generateKeys()
return len(mc.chunks)
} | [
"func",
"(",
"mc",
"*",
"CCacheMetric",
")",
"Del",
"(",
"ts",
"uint32",
")",
"int",
"{",
"mc",
".",
"Lock",
"(",
")",
"\n",
"defer",
"mc",
".",
"Unlock",
"(",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"mc",
".",
"chunks",
"[",
"ts",
"]",
";",
... | // Del deletes chunks for the given timestamp | [
"Del",
"deletes",
"chunks",
"for",
"the",
"given",
"timestamp"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/mdata/cache/ccache_metric.go#L37-L68 | train |
grafana/metrictank | mdata/cache/ccache_metric.go | Add | func (mc *CCacheMetric) Add(prev uint32, itergen chunk.IterGen) {
ts := itergen.T0
mc.Lock()
defer mc.Unlock()
if _, ok := mc.chunks[ts]; ok {
// chunk is already present. no need to error on that, just ignore it
return
}
mc.chunks[ts] = &CCacheChunk{
Ts: ts,
Prev: 0,
Next: 0,
Itgen: itergen,
}
nextTs := mc.nextTs(ts)
log.Debugf("CCacheMetric Add: caching chunk ts %d, nextTs %d", ts, nextTs)
// if previous chunk has not been passed we try to be smart and figure it out.
// this is common in a scenario where a metric continuously gets queried
// for a range that starts less than one chunkspan before now().
res, ok := mc.seekDesc(ts - 1)
if ok {
if prev == 0 {
prev = res
} else if prev != res {
log.Warnf("CCacheMetric Add: 'prev' param disagrees with seek: key = %s, prev = %d, seek = %d",
mc.MKey.String(), prev, res)
}
}
// if the previous chunk is cached, link in both directions
if _, ok := mc.chunks[prev]; ok {
mc.chunks[prev].Next = ts
mc.chunks[ts].Prev = prev
}
// if nextTs() can't figure out the end date it returns ts
if nextTs > ts {
// if the next chunk is cached, link in both directions
if _, ok := mc.chunks[nextTs]; ok {
mc.chunks[nextTs].Prev = ts
mc.chunks[ts].Next = nextTs
}
}
// assure key is added to mc.keys
// if no keys yet, just add it and it's sorted
if len(mc.keys) == 0 {
mc.keys = append(mc.keys, ts)
return
}
// add the ts, and sort if necessary
mc.keys = append(mc.keys, ts)
if mc.keys[len(mc.keys)-1] < mc.keys[len(mc.keys)-2] {
sort.Sort(accnt.Uint32Asc(mc.keys))
}
} | go | func (mc *CCacheMetric) Add(prev uint32, itergen chunk.IterGen) {
ts := itergen.T0
mc.Lock()
defer mc.Unlock()
if _, ok := mc.chunks[ts]; ok {
// chunk is already present. no need to error on that, just ignore it
return
}
mc.chunks[ts] = &CCacheChunk{
Ts: ts,
Prev: 0,
Next: 0,
Itgen: itergen,
}
nextTs := mc.nextTs(ts)
log.Debugf("CCacheMetric Add: caching chunk ts %d, nextTs %d", ts, nextTs)
// if previous chunk has not been passed we try to be smart and figure it out.
// this is common in a scenario where a metric continuously gets queried
// for a range that starts less than one chunkspan before now().
res, ok := mc.seekDesc(ts - 1)
if ok {
if prev == 0 {
prev = res
} else if prev != res {
log.Warnf("CCacheMetric Add: 'prev' param disagrees with seek: key = %s, prev = %d, seek = %d",
mc.MKey.String(), prev, res)
}
}
// if the previous chunk is cached, link in both directions
if _, ok := mc.chunks[prev]; ok {
mc.chunks[prev].Next = ts
mc.chunks[ts].Prev = prev
}
// if nextTs() can't figure out the end date it returns ts
if nextTs > ts {
// if the next chunk is cached, link in both directions
if _, ok := mc.chunks[nextTs]; ok {
mc.chunks[nextTs].Prev = ts
mc.chunks[ts].Next = nextTs
}
}
// assure key is added to mc.keys
// if no keys yet, just add it and it's sorted
if len(mc.keys) == 0 {
mc.keys = append(mc.keys, ts)
return
}
// add the ts, and sort if necessary
mc.keys = append(mc.keys, ts)
if mc.keys[len(mc.keys)-1] < mc.keys[len(mc.keys)-2] {
sort.Sort(accnt.Uint32Asc(mc.keys))
}
} | [
"func",
"(",
"mc",
"*",
"CCacheMetric",
")",
"Add",
"(",
"prev",
"uint32",
",",
"itergen",
"chunk",
".",
"IterGen",
")",
"{",
"ts",
":=",
"itergen",
".",
"T0",
"\n",
"mc",
".",
"Lock",
"(",
")",
"\n",
"defer",
"mc",
".",
"Unlock",
"(",
")",
"\n",... | // Add adds a chunk to the cache | [
"Add",
"adds",
"a",
"chunk",
"to",
"the",
"cache"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/mdata/cache/ccache_metric.go#L192-L255 | train |
grafana/metrictank | mdata/cache/ccache_metric.go | generateKeys | func (mc *CCacheMetric) generateKeys() {
keys := make([]uint32, 0, len(mc.chunks))
for k := range mc.chunks {
keys = append(keys, k)
}
sort.Sort(accnt.Uint32Asc(keys))
mc.keys = keys
} | go | func (mc *CCacheMetric) generateKeys() {
keys := make([]uint32, 0, len(mc.chunks))
for k := range mc.chunks {
keys = append(keys, k)
}
sort.Sort(accnt.Uint32Asc(keys))
mc.keys = keys
} | [
"func",
"(",
"mc",
"*",
"CCacheMetric",
")",
"generateKeys",
"(",
")",
"{",
"keys",
":=",
"make",
"(",
"[",
"]",
"uint32",
",",
"0",
",",
"len",
"(",
"mc",
".",
"chunks",
")",
")",
"\n",
"for",
"k",
":=",
"range",
"mc",
".",
"chunks",
"{",
"key... | // generateKeys generates sorted slice of all chunk timestamps
// assumes we have at least read lock | [
"generateKeys",
"generates",
"sorted",
"slice",
"of",
"all",
"chunk",
"timestamps",
"assumes",
"we",
"have",
"at",
"least",
"read",
"lock"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/mdata/cache/ccache_metric.go#L259-L266 | train |
grafana/metrictank | mdata/cache/ccache_metric.go | lastTs | func (mc *CCacheMetric) lastTs() uint32 {
mc.RLock()
defer mc.RUnlock()
return mc.nextTs(mc.keys[len(mc.keys)-1])
} | go | func (mc *CCacheMetric) lastTs() uint32 {
mc.RLock()
defer mc.RUnlock()
return mc.nextTs(mc.keys[len(mc.keys)-1])
} | [
"func",
"(",
"mc",
"*",
"CCacheMetric",
")",
"lastTs",
"(",
")",
"uint32",
"{",
"mc",
".",
"RLock",
"(",
")",
"\n",
"defer",
"mc",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"mc",
".",
"nextTs",
"(",
"mc",
".",
"keys",
"[",
"len",
"(",
"mc",
"."... | // lastTs returns the last Ts of this metric cache
// since ranges are exclusive at the end this is actually the first Ts that is not cached | [
"lastTs",
"returns",
"the",
"last",
"Ts",
"of",
"this",
"metric",
"cache",
"since",
"ranges",
"are",
"exclusive",
"at",
"the",
"end",
"this",
"is",
"actually",
"the",
"first",
"Ts",
"that",
"is",
"not",
"cached"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/mdata/cache/ccache_metric.go#L299-L303 | train |
grafana/metrictank | mdata/cache/ccache_metric.go | seekAsc | func (mc *CCacheMetric) seekAsc(ts uint32) (uint32, bool) {
log.Debugf("CCacheMetric seekAsc: seeking for %d in the keys %+d", ts, mc.keys)
for i := 0; i < len(mc.keys) && mc.keys[i] <= ts; i++ {
if mc.nextTs(mc.keys[i]) > ts {
log.Debugf("CCacheMetric seekAsc: seek found ts %d is between %d and %d", ts, mc.keys[i], mc.nextTs(mc.keys[i]))
return mc.keys[i], true
}
}
log.Debug("CCacheMetric seekAsc: seekAsc unsuccessful")
return 0, false
} | go | func (mc *CCacheMetric) seekAsc(ts uint32) (uint32, bool) {
log.Debugf("CCacheMetric seekAsc: seeking for %d in the keys %+d", ts, mc.keys)
for i := 0; i < len(mc.keys) && mc.keys[i] <= ts; i++ {
if mc.nextTs(mc.keys[i]) > ts {
log.Debugf("CCacheMetric seekAsc: seek found ts %d is between %d and %d", ts, mc.keys[i], mc.nextTs(mc.keys[i]))
return mc.keys[i], true
}
}
log.Debug("CCacheMetric seekAsc: seekAsc unsuccessful")
return 0, false
} | [
"func",
"(",
"mc",
"*",
"CCacheMetric",
")",
"seekAsc",
"(",
"ts",
"uint32",
")",
"(",
"uint32",
",",
"bool",
")",
"{",
"log",
".",
"Debugf",
"(",
"\"CCacheMetric seekAsc: seeking for %d in the keys %+d\"",
",",
"ts",
",",
"mc",
".",
"keys",
")",
"\n",
"fo... | // seekAsc finds the t0 of the chunk that contains ts, by searching from old to recent
// if not found or can't be sure returns 0, false
// assumes we already have at least a read lock | [
"seekAsc",
"finds",
"the",
"t0",
"of",
"the",
"chunk",
"that",
"contains",
"ts",
"by",
"searching",
"from",
"old",
"to",
"recent",
"if",
"not",
"found",
"or",
"can",
"t",
"be",
"sure",
"returns",
"0",
"false",
"assumes",
"we",
"already",
"have",
"at",
... | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/mdata/cache/ccache_metric.go#L308-L320 | train |
grafana/metrictank | stats/out_graphite.go | writer | func (g *Graphite) writer() {
var conn net.Conn
var err error
var wg sync.WaitGroup
assureConn := func() {
connected.Set(conn != nil)
for conn == nil {
time.Sleep(time.Second)
conn, err = net.Dial("tcp", g.addr)
if err == nil {
log.Infof("stats now connected to %s", g.addr)
wg.Add(1)
go g.checkEOF(conn, &wg)
} else {
log.Warnf("stats dialing %s failed: %s. will retry", g.addr, err.Error())
}
connected.Set(conn != nil)
}
}
for buf := range g.toGraphite {
queueItems.Value(len(g.toGraphite))
var ok bool
for !ok {
assureConn()
conn.SetWriteDeadline(time.Now().Add(g.timeout))
pre := time.Now()
_, err = conn.Write(buf)
if err == nil {
ok = true
flushDuration.Value(time.Since(pre))
} else {
log.Warnf("stats failed to write to graphite: %s (took %s). will retry...", err, time.Now().Sub(pre))
conn.Close()
wg.Wait()
conn = nil
}
}
}
} | go | func (g *Graphite) writer() {
var conn net.Conn
var err error
var wg sync.WaitGroup
assureConn := func() {
connected.Set(conn != nil)
for conn == nil {
time.Sleep(time.Second)
conn, err = net.Dial("tcp", g.addr)
if err == nil {
log.Infof("stats now connected to %s", g.addr)
wg.Add(1)
go g.checkEOF(conn, &wg)
} else {
log.Warnf("stats dialing %s failed: %s. will retry", g.addr, err.Error())
}
connected.Set(conn != nil)
}
}
for buf := range g.toGraphite {
queueItems.Value(len(g.toGraphite))
var ok bool
for !ok {
assureConn()
conn.SetWriteDeadline(time.Now().Add(g.timeout))
pre := time.Now()
_, err = conn.Write(buf)
if err == nil {
ok = true
flushDuration.Value(time.Since(pre))
} else {
log.Warnf("stats failed to write to graphite: %s (took %s). will retry...", err, time.Now().Sub(pre))
conn.Close()
wg.Wait()
conn = nil
}
}
}
} | [
"func",
"(",
"g",
"*",
"Graphite",
")",
"writer",
"(",
")",
"{",
"var",
"conn",
"net",
".",
"Conn",
"\n",
"var",
"err",
"error",
"\n",
"var",
"wg",
"sync",
".",
"WaitGroup",
"\n",
"assureConn",
":=",
"func",
"(",
")",
"{",
"connected",
".",
"Set",
... | // writer connects to graphite and submits all pending data to it | [
"writer",
"connects",
"to",
"graphite",
"and",
"submits",
"all",
"pending",
"data",
"to",
"it"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/stats/out_graphite.go#L87-L127 | train |
grafana/metrictank | mdata/reorder_buffer.go | Add | func (rob *ReorderBuffer) Add(ts uint32, val float64) ([]schema.Point, error) {
ts = AggBoundary(ts, rob.interval)
// out of order and too old
if rob.buf[rob.newest].Ts != 0 && ts <= rob.buf[rob.newest].Ts-(uint32(cap(rob.buf))*rob.interval) {
return nil, errors.ErrMetricTooOld
}
var res []schema.Point
oldest := (rob.newest + 1) % uint32(cap(rob.buf))
index := (ts / rob.interval) % uint32(cap(rob.buf))
if ts == rob.buf[index].Ts {
return nil, errors.ErrMetricNewValueForTimestamp
} else if ts > rob.buf[rob.newest].Ts {
flushCount := (ts - rob.buf[rob.newest].Ts) / rob.interval
if flushCount > uint32(cap(rob.buf)) {
flushCount = uint32(cap(rob.buf))
}
for i := uint32(0); i < flushCount; i++ {
if rob.buf[oldest].Ts != 0 {
res = append(res, rob.buf[oldest])
rob.buf[oldest].Ts = 0
}
oldest = (oldest + 1) % uint32(cap(rob.buf))
}
rob.buf[index].Ts = ts
rob.buf[index].Val = val
rob.newest = index
} else {
metricsReordered.Inc()
rob.buf[index].Ts = ts
rob.buf[index].Val = val
}
return res, nil
} | go | func (rob *ReorderBuffer) Add(ts uint32, val float64) ([]schema.Point, error) {
ts = AggBoundary(ts, rob.interval)
// out of order and too old
if rob.buf[rob.newest].Ts != 0 && ts <= rob.buf[rob.newest].Ts-(uint32(cap(rob.buf))*rob.interval) {
return nil, errors.ErrMetricTooOld
}
var res []schema.Point
oldest := (rob.newest + 1) % uint32(cap(rob.buf))
index := (ts / rob.interval) % uint32(cap(rob.buf))
if ts == rob.buf[index].Ts {
return nil, errors.ErrMetricNewValueForTimestamp
} else if ts > rob.buf[rob.newest].Ts {
flushCount := (ts - rob.buf[rob.newest].Ts) / rob.interval
if flushCount > uint32(cap(rob.buf)) {
flushCount = uint32(cap(rob.buf))
}
for i := uint32(0); i < flushCount; i++ {
if rob.buf[oldest].Ts != 0 {
res = append(res, rob.buf[oldest])
rob.buf[oldest].Ts = 0
}
oldest = (oldest + 1) % uint32(cap(rob.buf))
}
rob.buf[index].Ts = ts
rob.buf[index].Val = val
rob.newest = index
} else {
metricsReordered.Inc()
rob.buf[index].Ts = ts
rob.buf[index].Val = val
}
return res, nil
} | [
"func",
"(",
"rob",
"*",
"ReorderBuffer",
")",
"Add",
"(",
"ts",
"uint32",
",",
"val",
"float64",
")",
"(",
"[",
"]",
"schema",
".",
"Point",
",",
"error",
")",
"{",
"ts",
"=",
"AggBoundary",
"(",
"ts",
",",
"rob",
".",
"interval",
")",
"\n",
"if... | // Add adds the point if it falls within the window.
// it returns points that have been purged out of the buffer, as well as whether the add succeeded. | [
"Add",
"adds",
"the",
"point",
"if",
"it",
"falls",
"within",
"the",
"window",
".",
"it",
"returns",
"points",
"that",
"have",
"been",
"purged",
"out",
"of",
"the",
"buffer",
"as",
"well",
"as",
"whether",
"the",
"add",
"succeeded",
"."
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/mdata/reorder_buffer.go#L31-L67 | train |
grafana/metrictank | mdata/reorder_buffer.go | Get | func (rob *ReorderBuffer) Get() []schema.Point {
res := make([]schema.Point, 0, cap(rob.buf))
oldest := (rob.newest + 1) % uint32(cap(rob.buf))
for {
if rob.buf[oldest].Ts != 0 {
res = append(res, rob.buf[oldest])
}
if oldest == rob.newest {
break
}
oldest = (oldest + 1) % uint32(cap(rob.buf))
}
return res
} | go | func (rob *ReorderBuffer) Get() []schema.Point {
res := make([]schema.Point, 0, cap(rob.buf))
oldest := (rob.newest + 1) % uint32(cap(rob.buf))
for {
if rob.buf[oldest].Ts != 0 {
res = append(res, rob.buf[oldest])
}
if oldest == rob.newest {
break
}
oldest = (oldest + 1) % uint32(cap(rob.buf))
}
return res
} | [
"func",
"(",
"rob",
"*",
"ReorderBuffer",
")",
"Get",
"(",
")",
"[",
"]",
"schema",
".",
"Point",
"{",
"res",
":=",
"make",
"(",
"[",
"]",
"schema",
".",
"Point",
",",
"0",
",",
"cap",
"(",
"rob",
".",
"buf",
")",
")",
"\n",
"oldest",
":=",
"... | // Get returns the points in the buffer | [
"Get",
"returns",
"the",
"points",
"in",
"the",
"buffer"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/mdata/reorder_buffer.go#L70-L85 | train |
grafana/metrictank | cmd/mt-whisper-importer-reader/conversion.go | incResolution | func incResolution(points []whisper.Point, method string, inRes, outRes, rawRes uint32) map[string][]whisper.Point {
out := make(map[string][]whisper.Point)
resFactor := float64(outRes) / float64(rawRes)
for _, inPoint := range points {
if inPoint.Timestamp == 0 {
continue
}
// inPoints are guaranteed to be quantized by whisper
// outRes is < inRes, otherwise this function should never be called
// rangeEnd is the the TS of the last datapoint that will be generated based on inPoint
rangeEnd := inPoint.Timestamp - (inPoint.Timestamp % outRes)
// generate datapoints based on inPoint in reverse order
var outPoints []whisper.Point
for ts := rangeEnd; ts > inPoint.Timestamp-inRes; ts = ts - outRes {
if ts > uint32(*importUpTo) || ts < uint32(*importAfter) {
continue
}
outPoints = append(outPoints, whisper.Point{Timestamp: ts})
}
for _, outPoint := range outPoints {
if method == "sum" {
outPoint.Value = inPoint.Value / float64(len(outPoints))
out["sum"] = append(out["sum"], outPoint)
out["cnt"] = append(out["cnt"], whisper.Point{Timestamp: outPoint.Timestamp, Value: resFactor})
} else if method == "fakeavg" {
outPoint.Value = inPoint.Value * resFactor
out["sum"] = append(out["sum"], outPoint)
out["cnt"] = append(out["cnt"], whisper.Point{Timestamp: outPoint.Timestamp, Value: resFactor})
} else {
outPoint.Value = inPoint.Value
out[method] = append(out[method], outPoint)
}
}
}
for m := range out {
out[m] = sortPoints(out[m])
}
return out
} | go | func incResolution(points []whisper.Point, method string, inRes, outRes, rawRes uint32) map[string][]whisper.Point {
out := make(map[string][]whisper.Point)
resFactor := float64(outRes) / float64(rawRes)
for _, inPoint := range points {
if inPoint.Timestamp == 0 {
continue
}
// inPoints are guaranteed to be quantized by whisper
// outRes is < inRes, otherwise this function should never be called
// rangeEnd is the the TS of the last datapoint that will be generated based on inPoint
rangeEnd := inPoint.Timestamp - (inPoint.Timestamp % outRes)
// generate datapoints based on inPoint in reverse order
var outPoints []whisper.Point
for ts := rangeEnd; ts > inPoint.Timestamp-inRes; ts = ts - outRes {
if ts > uint32(*importUpTo) || ts < uint32(*importAfter) {
continue
}
outPoints = append(outPoints, whisper.Point{Timestamp: ts})
}
for _, outPoint := range outPoints {
if method == "sum" {
outPoint.Value = inPoint.Value / float64(len(outPoints))
out["sum"] = append(out["sum"], outPoint)
out["cnt"] = append(out["cnt"], whisper.Point{Timestamp: outPoint.Timestamp, Value: resFactor})
} else if method == "fakeavg" {
outPoint.Value = inPoint.Value * resFactor
out["sum"] = append(out["sum"], outPoint)
out["cnt"] = append(out["cnt"], whisper.Point{Timestamp: outPoint.Timestamp, Value: resFactor})
} else {
outPoint.Value = inPoint.Value
out[method] = append(out[method], outPoint)
}
}
}
for m := range out {
out[m] = sortPoints(out[m])
}
return out
} | [
"func",
"incResolution",
"(",
"points",
"[",
"]",
"whisper",
".",
"Point",
",",
"method",
"string",
",",
"inRes",
",",
"outRes",
",",
"rawRes",
"uint32",
")",
"map",
"[",
"string",
"]",
"[",
"]",
"whisper",
".",
"Point",
"{",
"out",
":=",
"make",
"("... | // increase resolution of given points according to defined specs by generating
// additional datapoints to bridge the gaps between the given points. depending
// on what aggregation method is specified, those datapoints may be generated in
// slightly different ways. | [
"increase",
"resolution",
"of",
"given",
"points",
"according",
"to",
"defined",
"specs",
"by",
"generating",
"additional",
"datapoints",
"to",
"bridge",
"the",
"gaps",
"between",
"the",
"given",
"points",
".",
"depending",
"on",
"what",
"aggregation",
"method",
... | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/cmd/mt-whisper-importer-reader/conversion.go#L135-L176 | train |
grafana/metrictank | cmd/mt-whisper-importer-reader/conversion.go | decResolution | func decResolution(points []whisper.Point, method string, inRes, outRes, rawRes uint32) map[string][]whisper.Point {
out := make(map[string][]whisper.Point)
agg := mdata.NewAggregation()
currentBoundary := uint32(0)
flush := func() {
if agg.Cnt == 0 {
return
}
var value float64
switch method {
case "min":
value = agg.Min
case "max":
value = agg.Max
case "lst":
value = agg.Lst
case "avg":
value = agg.Sum / agg.Cnt
case "sum":
out["cnt"] = append(out["cnt"], whisper.Point{
Timestamp: currentBoundary,
Value: agg.Cnt * float64(inRes) / float64(rawRes),
})
out["sum"] = append(out["sum"], whisper.Point{
Timestamp: currentBoundary,
Value: agg.Sum,
})
agg.Reset()
return
case "fakeavg":
cnt := agg.Cnt * float64(inRes) / float64(rawRes)
out["cnt"] = append(out["cnt"], whisper.Point{
Timestamp: currentBoundary,
Value: cnt,
})
out["sum"] = append(out["sum"], whisper.Point{
Timestamp: currentBoundary,
Value: (agg.Sum / agg.Cnt) * cnt,
})
agg.Reset()
return
default:
return
}
out[method] = append(out[method], whisper.Point{
Timestamp: currentBoundary,
Value: value,
})
agg.Reset()
}
for _, inPoint := range sortPoints(points) {
if inPoint.Timestamp == 0 {
continue
}
boundary := mdata.AggBoundary(inPoint.Timestamp, outRes)
if boundary > uint32(*importUpTo) {
break
}
if boundary < uint32(*importAfter) {
continue
}
if boundary == currentBoundary {
agg.Add(inPoint.Value)
if inPoint.Timestamp == boundary {
flush()
}
} else {
flush()
currentBoundary = boundary
agg.Add(inPoint.Value)
}
}
return out
} | go | func decResolution(points []whisper.Point, method string, inRes, outRes, rawRes uint32) map[string][]whisper.Point {
out := make(map[string][]whisper.Point)
agg := mdata.NewAggregation()
currentBoundary := uint32(0)
flush := func() {
if agg.Cnt == 0 {
return
}
var value float64
switch method {
case "min":
value = agg.Min
case "max":
value = agg.Max
case "lst":
value = agg.Lst
case "avg":
value = agg.Sum / agg.Cnt
case "sum":
out["cnt"] = append(out["cnt"], whisper.Point{
Timestamp: currentBoundary,
Value: agg.Cnt * float64(inRes) / float64(rawRes),
})
out["sum"] = append(out["sum"], whisper.Point{
Timestamp: currentBoundary,
Value: agg.Sum,
})
agg.Reset()
return
case "fakeavg":
cnt := agg.Cnt * float64(inRes) / float64(rawRes)
out["cnt"] = append(out["cnt"], whisper.Point{
Timestamp: currentBoundary,
Value: cnt,
})
out["sum"] = append(out["sum"], whisper.Point{
Timestamp: currentBoundary,
Value: (agg.Sum / agg.Cnt) * cnt,
})
agg.Reset()
return
default:
return
}
out[method] = append(out[method], whisper.Point{
Timestamp: currentBoundary,
Value: value,
})
agg.Reset()
}
for _, inPoint := range sortPoints(points) {
if inPoint.Timestamp == 0 {
continue
}
boundary := mdata.AggBoundary(inPoint.Timestamp, outRes)
if boundary > uint32(*importUpTo) {
break
}
if boundary < uint32(*importAfter) {
continue
}
if boundary == currentBoundary {
agg.Add(inPoint.Value)
if inPoint.Timestamp == boundary {
flush()
}
} else {
flush()
currentBoundary = boundary
agg.Add(inPoint.Value)
}
}
return out
} | [
"func",
"decResolution",
"(",
"points",
"[",
"]",
"whisper",
".",
"Point",
",",
"method",
"string",
",",
"inRes",
",",
"outRes",
",",
"rawRes",
"uint32",
")",
"map",
"[",
"string",
"]",
"[",
"]",
"whisper",
".",
"Point",
"{",
"out",
":=",
"make",
"("... | // decreases the resolution of given points by using the aggregation method specified
// in the second argument. emulates the way metrictank aggregates data when it generates
// rollups of the raw data. | [
"decreases",
"the",
"resolution",
"of",
"given",
"points",
"by",
"using",
"the",
"aggregation",
"method",
"specified",
"in",
"the",
"second",
"argument",
".",
"emulates",
"the",
"way",
"metrictank",
"aggregates",
"data",
"when",
"it",
"generates",
"rollups",
"of... | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/cmd/mt-whisper-importer-reader/conversion.go#L181-L259 | train |
grafana/metrictank | mdata/store_mock.go | Add | func (c *MockStore) Add(cwr *ChunkWriteRequest) {
if !c.Drop {
intervalHint := cwr.Key.Archive.Span()
itgen, err := chunk.NewIterGen(cwr.Chunk.Series.T0, intervalHint, cwr.Chunk.Encode(cwr.Span))
if err != nil {
panic(err)
}
c.results[cwr.Key] = append(c.results[cwr.Key], itgen)
c.items++
}
} | go | func (c *MockStore) Add(cwr *ChunkWriteRequest) {
if !c.Drop {
intervalHint := cwr.Key.Archive.Span()
itgen, err := chunk.NewIterGen(cwr.Chunk.Series.T0, intervalHint, cwr.Chunk.Encode(cwr.Span))
if err != nil {
panic(err)
}
c.results[cwr.Key] = append(c.results[cwr.Key], itgen)
c.items++
}
} | [
"func",
"(",
"c",
"*",
"MockStore",
")",
"Add",
"(",
"cwr",
"*",
"ChunkWriteRequest",
")",
"{",
"if",
"!",
"c",
".",
"Drop",
"{",
"intervalHint",
":=",
"cwr",
".",
"Key",
".",
"Archive",
".",
"Span",
"(",
")",
"\n",
"itgen",
",",
"err",
":=",
"ch... | // Add adds a chunk to the store | [
"Add",
"adds",
"a",
"chunk",
"to",
"the",
"store"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/mdata/store_mock.go#L40-L50 | train |
grafana/metrictank | mdata/chunk/encode.go | encode | func encode(span uint32, format Format, data []byte) []byte {
switch format {
case FormatStandardGoTszWithSpan, FormatGoTszLongWithSpan:
buf := new(bytes.Buffer)
binary.Write(buf, binary.LittleEndian, format)
spanCode, ok := RevChunkSpans[span]
if !ok {
// it's probably better to panic than to persist the chunk with a wrong length
panic(fmt.Sprintf("Chunk span invalid: %d", span))
}
binary.Write(buf, binary.LittleEndian, spanCode)
buf.Write(data)
return buf.Bytes()
case FormatStandardGoTsz:
buf := new(bytes.Buffer)
binary.Write(buf, binary.LittleEndian, format)
buf.Write(data)
return buf.Bytes()
}
return nil
} | go | func encode(span uint32, format Format, data []byte) []byte {
switch format {
case FormatStandardGoTszWithSpan, FormatGoTszLongWithSpan:
buf := new(bytes.Buffer)
binary.Write(buf, binary.LittleEndian, format)
spanCode, ok := RevChunkSpans[span]
if !ok {
// it's probably better to panic than to persist the chunk with a wrong length
panic(fmt.Sprintf("Chunk span invalid: %d", span))
}
binary.Write(buf, binary.LittleEndian, spanCode)
buf.Write(data)
return buf.Bytes()
case FormatStandardGoTsz:
buf := new(bytes.Buffer)
binary.Write(buf, binary.LittleEndian, format)
buf.Write(data)
return buf.Bytes()
}
return nil
} | [
"func",
"encode",
"(",
"span",
"uint32",
",",
"format",
"Format",
",",
"data",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"switch",
"format",
"{",
"case",
"FormatStandardGoTszWithSpan",
",",
"FormatGoTszLongWithSpan",
":",
"buf",
":=",
"new",
"(",
"byte... | // encode is a helper function to encode a chunk of data into various formats
// input data is copied | [
"encode",
"is",
"a",
"helper",
"function",
"to",
"encode",
"a",
"chunk",
"of",
"data",
"into",
"various",
"formats",
"input",
"data",
"is",
"copied"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/mdata/chunk/encode.go#L11-L32 | train |
grafana/metrictank | idx/memory/tag_query.go | parseExpression | func parseExpression(expr string) (expression, error) {
var pos int
prefix, regex, not := false, false, false
res := expression{}
// scan up to operator to get key
FIND_OPERATOR:
for ; pos < len(expr); pos++ {
switch expr[pos] {
case '=':
break FIND_OPERATOR
case '!':
not = true
break FIND_OPERATOR
case '^':
prefix = true
break FIND_OPERATOR
case ';':
return res, errInvalidQuery
}
}
// key must not be empty
if pos == 0 {
return res, errInvalidQuery
}
res.key = expr[:pos]
// shift over the !/^ characters
if not || prefix {
pos++
}
if len(expr) <= pos || expr[pos] != '=' {
return res, errInvalidQuery
}
pos++
if len(expr) > pos && expr[pos] == '~' {
// ^=~ is not a valid operator
if prefix {
return res, errInvalidQuery
}
regex = true
pos++
}
valuePos := pos
for ; pos < len(expr); pos++ {
// disallow ; in value
if expr[pos] == 59 {
return res, errInvalidQuery
}
}
res.value = expr[valuePos:]
// special key to match on tag instead of a value
if res.key == "__tag" {
// currently ! (not) queries on tags are not supported
// and unlike normal queries a value must be set
if not || len(res.value) == 0 {
return res, errInvalidQuery
}
if regex {
res.operator = MATCH_TAG
} else if prefix {
res.operator = PREFIX_TAG
} else {
// currently only match & prefix operator are supported on tag
return res, errInvalidQuery
}
return res, nil
}
if not {
if regex {
res.operator = NOT_MATCH
} else {
res.operator = NOT_EQUAL
}
} else {
if regex {
res.operator = MATCH
} else if prefix {
res.operator = PREFIX
} else {
res.operator = EQUAL
}
}
return res, nil
} | go | func parseExpression(expr string) (expression, error) {
var pos int
prefix, regex, not := false, false, false
res := expression{}
// scan up to operator to get key
FIND_OPERATOR:
for ; pos < len(expr); pos++ {
switch expr[pos] {
case '=':
break FIND_OPERATOR
case '!':
not = true
break FIND_OPERATOR
case '^':
prefix = true
break FIND_OPERATOR
case ';':
return res, errInvalidQuery
}
}
// key must not be empty
if pos == 0 {
return res, errInvalidQuery
}
res.key = expr[:pos]
// shift over the !/^ characters
if not || prefix {
pos++
}
if len(expr) <= pos || expr[pos] != '=' {
return res, errInvalidQuery
}
pos++
if len(expr) > pos && expr[pos] == '~' {
// ^=~ is not a valid operator
if prefix {
return res, errInvalidQuery
}
regex = true
pos++
}
valuePos := pos
for ; pos < len(expr); pos++ {
// disallow ; in value
if expr[pos] == 59 {
return res, errInvalidQuery
}
}
res.value = expr[valuePos:]
// special key to match on tag instead of a value
if res.key == "__tag" {
// currently ! (not) queries on tags are not supported
// and unlike normal queries a value must be set
if not || len(res.value) == 0 {
return res, errInvalidQuery
}
if regex {
res.operator = MATCH_TAG
} else if prefix {
res.operator = PREFIX_TAG
} else {
// currently only match & prefix operator are supported on tag
return res, errInvalidQuery
}
return res, nil
}
if not {
if regex {
res.operator = NOT_MATCH
} else {
res.operator = NOT_EQUAL
}
} else {
if regex {
res.operator = MATCH
} else if prefix {
res.operator = PREFIX
} else {
res.operator = EQUAL
}
}
return res, nil
} | [
"func",
"parseExpression",
"(",
"expr",
"string",
")",
"(",
"expression",
",",
"error",
")",
"{",
"var",
"pos",
"int",
"\n",
"prefix",
",",
"regex",
",",
"not",
":=",
"false",
",",
"false",
",",
"false",
"\n",
"res",
":=",
"expression",
"{",
"}",
"\n... | // parseExpression returns an expression that's been generated from the given
// string, in case of error the operator will be PARSING_ERROR. | [
"parseExpression",
"returns",
"an",
"expression",
"that",
"s",
"been",
"generated",
"from",
"the",
"given",
"string",
"in",
"case",
"of",
"error",
"the",
"operator",
"will",
"be",
"PARSING_ERROR",
"."
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/idx/memory/tag_query.go#L125-L218 | train |
grafana/metrictank | idx/memory/tag_query.go | getInitialByEqual | func (q *TagQuery) getInitialByEqual(expr kv, idCh chan schema.MKey, stopCh chan struct{}) {
defer q.wg.Done()
KEYS:
for k := range q.index[expr.key][expr.value] {
select {
case <-stopCh:
break KEYS
case idCh <- k:
}
}
close(idCh)
} | go | func (q *TagQuery) getInitialByEqual(expr kv, idCh chan schema.MKey, stopCh chan struct{}) {
defer q.wg.Done()
KEYS:
for k := range q.index[expr.key][expr.value] {
select {
case <-stopCh:
break KEYS
case idCh <- k:
}
}
close(idCh)
} | [
"func",
"(",
"q",
"*",
"TagQuery",
")",
"getInitialByEqual",
"(",
"expr",
"kv",
",",
"idCh",
"chan",
"schema",
".",
"MKey",
",",
"stopCh",
"chan",
"struct",
"{",
"}",
")",
"{",
"defer",
"q",
".",
"wg",
".",
"Done",
"(",
")",
"\n",
"KEYS",
":",
"f... | // getInitialByEqual generates the initial resultset by executing the given equal expression | [
"getInitialByEqual",
"generates",
"the",
"initial",
"resultset",
"by",
"executing",
"the",
"given",
"equal",
"expression"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/idx/memory/tag_query.go#L338-L351 | train |
grafana/metrictank | idx/memory/tag_query.go | getInitialByPrefix | func (q *TagQuery) getInitialByPrefix(expr kv, idCh chan schema.MKey, stopCh chan struct{}) {
defer q.wg.Done()
VALUES:
for v, ids := range q.index[expr.key] {
if !strings.HasPrefix(v, expr.value) {
continue
}
for id := range ids {
select {
case <-stopCh:
break VALUES
case idCh <- id:
}
}
}
close(idCh)
} | go | func (q *TagQuery) getInitialByPrefix(expr kv, idCh chan schema.MKey, stopCh chan struct{}) {
defer q.wg.Done()
VALUES:
for v, ids := range q.index[expr.key] {
if !strings.HasPrefix(v, expr.value) {
continue
}
for id := range ids {
select {
case <-stopCh:
break VALUES
case idCh <- id:
}
}
}
close(idCh)
} | [
"func",
"(",
"q",
"*",
"TagQuery",
")",
"getInitialByPrefix",
"(",
"expr",
"kv",
",",
"idCh",
"chan",
"schema",
".",
"MKey",
",",
"stopCh",
"chan",
"struct",
"{",
"}",
")",
"{",
"defer",
"q",
".",
"wg",
".",
"Done",
"(",
")",
"\n",
"VALUES",
":",
... | // getInitialByPrefix generates the initial resultset by executing the given prefix match expression | [
"getInitialByPrefix",
"generates",
"the",
"initial",
"resultset",
"by",
"executing",
"the",
"given",
"prefix",
"match",
"expression"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/idx/memory/tag_query.go#L354-L373 | train |
grafana/metrictank | idx/memory/tag_query.go | getInitialByMatch | func (q *TagQuery) getInitialByMatch(expr kvRe, idCh chan schema.MKey, stopCh chan struct{}) {
defer q.wg.Done()
// shortcut if value == nil.
// this will simply match any value, like ^.+. since we know that every value
// in the index must not be empty, we can skip the matching.
if expr.value == nil {
VALUES1:
for _, ids := range q.index[expr.key] {
for id := range ids {
select {
case <-stopCh:
break VALUES1
case idCh <- id:
}
}
}
close(idCh)
return
}
VALUES2:
for v, ids := range q.index[expr.key] {
if !expr.value.MatchString(v) {
continue
}
for id := range ids {
select {
case <-stopCh:
break VALUES2
case idCh <- id:
}
}
}
close(idCh)
} | go | func (q *TagQuery) getInitialByMatch(expr kvRe, idCh chan schema.MKey, stopCh chan struct{}) {
defer q.wg.Done()
// shortcut if value == nil.
// this will simply match any value, like ^.+. since we know that every value
// in the index must not be empty, we can skip the matching.
if expr.value == nil {
VALUES1:
for _, ids := range q.index[expr.key] {
for id := range ids {
select {
case <-stopCh:
break VALUES1
case idCh <- id:
}
}
}
close(idCh)
return
}
VALUES2:
for v, ids := range q.index[expr.key] {
if !expr.value.MatchString(v) {
continue
}
for id := range ids {
select {
case <-stopCh:
break VALUES2
case idCh <- id:
}
}
}
close(idCh)
} | [
"func",
"(",
"q",
"*",
"TagQuery",
")",
"getInitialByMatch",
"(",
"expr",
"kvRe",
",",
"idCh",
"chan",
"schema",
".",
"MKey",
",",
"stopCh",
"chan",
"struct",
"{",
"}",
")",
"{",
"defer",
"q",
".",
"wg",
".",
"Done",
"(",
")",
"\n",
"if",
"expr",
... | // getInitialByMatch generates the initial resultset by executing the given match expression | [
"getInitialByMatch",
"generates",
"the",
"initial",
"resultset",
"by",
"executing",
"the",
"given",
"match",
"expression"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/idx/memory/tag_query.go#L376-L413 | train |
grafana/metrictank | idx/memory/tag_query.go | getInitialByTagPrefix | func (q *TagQuery) getInitialByTagPrefix(idCh chan schema.MKey, stopCh chan struct{}) {
defer q.wg.Done()
TAGS:
for tag, values := range q.index {
if !strings.HasPrefix(tag, q.tagPrefix) {
continue
}
for _, ids := range values {
for id := range ids {
select {
case <-stopCh:
break TAGS
case idCh <- id:
}
}
}
}
close(idCh)
} | go | func (q *TagQuery) getInitialByTagPrefix(idCh chan schema.MKey, stopCh chan struct{}) {
defer q.wg.Done()
TAGS:
for tag, values := range q.index {
if !strings.HasPrefix(tag, q.tagPrefix) {
continue
}
for _, ids := range values {
for id := range ids {
select {
case <-stopCh:
break TAGS
case idCh <- id:
}
}
}
}
close(idCh)
} | [
"func",
"(",
"q",
"*",
"TagQuery",
")",
"getInitialByTagPrefix",
"(",
"idCh",
"chan",
"schema",
".",
"MKey",
",",
"stopCh",
"chan",
"struct",
"{",
"}",
")",
"{",
"defer",
"q",
".",
"wg",
".",
"Done",
"(",
")",
"\n",
"TAGS",
":",
"for",
"tag",
",",
... | // getInitialByTagPrefix generates the initial resultset by creating a list of
// metric IDs of which at least one tag starts with the defined prefix | [
"getInitialByTagPrefix",
"generates",
"the",
"initial",
"resultset",
"by",
"creating",
"a",
"list",
"of",
"metric",
"IDs",
"of",
"which",
"at",
"least",
"one",
"tag",
"starts",
"with",
"the",
"defined",
"prefix"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/idx/memory/tag_query.go#L417-L438 | train |
grafana/metrictank | idx/memory/tag_query.go | getInitialByTagMatch | func (q *TagQuery) getInitialByTagMatch(idCh chan schema.MKey, stopCh chan struct{}) {
defer q.wg.Done()
TAGS:
for tag, values := range q.index {
if q.tagMatch.value.MatchString(tag) {
for _, ids := range values {
for id := range ids {
select {
case <-stopCh:
break TAGS
case idCh <- id:
}
}
}
}
}
close(idCh)
} | go | func (q *TagQuery) getInitialByTagMatch(idCh chan schema.MKey, stopCh chan struct{}) {
defer q.wg.Done()
TAGS:
for tag, values := range q.index {
if q.tagMatch.value.MatchString(tag) {
for _, ids := range values {
for id := range ids {
select {
case <-stopCh:
break TAGS
case idCh <- id:
}
}
}
}
}
close(idCh)
} | [
"func",
"(",
"q",
"*",
"TagQuery",
")",
"getInitialByTagMatch",
"(",
"idCh",
"chan",
"schema",
".",
"MKey",
",",
"stopCh",
"chan",
"struct",
"{",
"}",
")",
"{",
"defer",
"q",
".",
"wg",
".",
"Done",
"(",
")",
"\n",
"TAGS",
":",
"for",
"tag",
",",
... | // getInitialByTagMatch generates the initial resultset by creating a list of
// metric IDs of which at least one tag matches the defined regex | [
"getInitialByTagMatch",
"generates",
"the",
"initial",
"resultset",
"by",
"creating",
"a",
"list",
"of",
"metric",
"IDs",
"of",
"which",
"at",
"least",
"one",
"tag",
"matches",
"the",
"defined",
"regex"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/idx/memory/tag_query.go#L442-L461 | train |
grafana/metrictank | idx/memory/tag_query.go | filterIdsFromChan | func (q *TagQuery) filterIdsFromChan(idCh, resCh chan schema.MKey) {
for id := range idCh {
var def *idx.Archive
var ok bool
if def, ok = q.byId[id]; !ok {
// should never happen because every ID in the tag index
// must be present in the byId lookup table
corruptIndex.Inc()
log.Errorf("memory-idx: ID %q is in tag index but not in the byId lookup table", id)
continue
}
// we always omit tag filters because Run() does not support filtering by tags
if q.testByAllExpressions(id, def, false) {
resCh <- id
}
}
q.wg.Done()
} | go | func (q *TagQuery) filterIdsFromChan(idCh, resCh chan schema.MKey) {
for id := range idCh {
var def *idx.Archive
var ok bool
if def, ok = q.byId[id]; !ok {
// should never happen because every ID in the tag index
// must be present in the byId lookup table
corruptIndex.Inc()
log.Errorf("memory-idx: ID %q is in tag index but not in the byId lookup table", id)
continue
}
// we always omit tag filters because Run() does not support filtering by tags
if q.testByAllExpressions(id, def, false) {
resCh <- id
}
}
q.wg.Done()
} | [
"func",
"(",
"q",
"*",
"TagQuery",
")",
"filterIdsFromChan",
"(",
"idCh",
",",
"resCh",
"chan",
"schema",
".",
"MKey",
")",
"{",
"for",
"id",
":=",
"range",
"idCh",
"{",
"var",
"def",
"*",
"idx",
".",
"Archive",
"\n",
"var",
"ok",
"bool",
"\n",
"if... | // filterIdsFromChan takes a channel of metric ids and runs them through the
// required tests to decide whether a metric should be part of the final
// result set or not
// it returns the final result set via the given resCh parameter | [
"filterIdsFromChan",
"takes",
"a",
"channel",
"of",
"metric",
"ids",
"and",
"runs",
"them",
"through",
"the",
"required",
"tests",
"to",
"decide",
"whether",
"a",
"metric",
"should",
"be",
"part",
"of",
"the",
"final",
"result",
"set",
"or",
"not",
"it",
"... | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/idx/memory/tag_query.go#L727-L747 | train |
grafana/metrictank | idx/memory/tag_query.go | sortByCost | func (q *TagQuery) sortByCost() {
for i, kv := range q.equal {
q.equal[i].cost = uint(len(q.index[kv.key][kv.value]))
}
// for prefix and match clauses we can't determine the actual cost
// without actually evaluating them, so we estimate based on
// cardinality of the key
for i, kv := range q.prefix {
q.prefix[i].cost = uint(len(q.index[kv.key]))
}
for i, kvRe := range q.match {
q.match[i].cost = uint(len(q.index[kvRe.key]))
}
sort.Sort(KvByCost(q.equal))
sort.Sort(KvByCost(q.notEqual))
sort.Sort(KvByCost(q.prefix))
sort.Sort(KvReByCost(q.match))
sort.Sort(KvReByCost(q.notMatch))
} | go | func (q *TagQuery) sortByCost() {
for i, kv := range q.equal {
q.equal[i].cost = uint(len(q.index[kv.key][kv.value]))
}
// for prefix and match clauses we can't determine the actual cost
// without actually evaluating them, so we estimate based on
// cardinality of the key
for i, kv := range q.prefix {
q.prefix[i].cost = uint(len(q.index[kv.key]))
}
for i, kvRe := range q.match {
q.match[i].cost = uint(len(q.index[kvRe.key]))
}
sort.Sort(KvByCost(q.equal))
sort.Sort(KvByCost(q.notEqual))
sort.Sort(KvByCost(q.prefix))
sort.Sort(KvReByCost(q.match))
sort.Sort(KvReByCost(q.notMatch))
} | [
"func",
"(",
"q",
"*",
"TagQuery",
")",
"sortByCost",
"(",
")",
"{",
"for",
"i",
",",
"kv",
":=",
"range",
"q",
".",
"equal",
"{",
"q",
".",
"equal",
"[",
"i",
"]",
".",
"cost",
"=",
"uint",
"(",
"len",
"(",
"q",
".",
"index",
"[",
"kv",
".... | // sortByCost tries to estimate the cost of different expressions and sort them
// in increasing order
// this is to reduce the result set cheaply and only apply expensive tests to an
// already reduced set of results | [
"sortByCost",
"tries",
"to",
"estimate",
"the",
"cost",
"of",
"different",
"expressions",
"and",
"sort",
"them",
"in",
"increasing",
"order",
"this",
"is",
"to",
"reduce",
"the",
"result",
"set",
"cheaply",
"and",
"only",
"apply",
"expensive",
"tests",
"to",
... | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/idx/memory/tag_query.go#L753-L774 | train |
grafana/metrictank | idx/memory/tag_query.go | Run | func (q *TagQuery) Run(index TagIndex, byId map[schema.MKey]*idx.Archive) IdSet {
q.index = index
q.byId = byId
q.sortByCost()
idCh, _ := q.getInitialIds()
resCh := make(chan schema.MKey)
// start the tag query workers. they'll consume the ids on the idCh and
// evaluate for each of them whether it satisfies all the conditions
// defined in the query expressions. those that satisfy all conditions
// will be pushed into the resCh
q.wg.Add(TagQueryWorkers)
for i := 0; i < TagQueryWorkers; i++ {
go q.filterIdsFromChan(idCh, resCh)
}
go func() {
q.wg.Wait()
close(resCh)
}()
result := make(IdSet)
for id := range resCh {
result[id] = struct{}{}
}
return result
} | go | func (q *TagQuery) Run(index TagIndex, byId map[schema.MKey]*idx.Archive) IdSet {
q.index = index
q.byId = byId
q.sortByCost()
idCh, _ := q.getInitialIds()
resCh := make(chan schema.MKey)
// start the tag query workers. they'll consume the ids on the idCh and
// evaluate for each of them whether it satisfies all the conditions
// defined in the query expressions. those that satisfy all conditions
// will be pushed into the resCh
q.wg.Add(TagQueryWorkers)
for i := 0; i < TagQueryWorkers; i++ {
go q.filterIdsFromChan(idCh, resCh)
}
go func() {
q.wg.Wait()
close(resCh)
}()
result := make(IdSet)
for id := range resCh {
result[id] = struct{}{}
}
return result
} | [
"func",
"(",
"q",
"*",
"TagQuery",
")",
"Run",
"(",
"index",
"TagIndex",
",",
"byId",
"map",
"[",
"schema",
".",
"MKey",
"]",
"*",
"idx",
".",
"Archive",
")",
"IdSet",
"{",
"q",
".",
"index",
"=",
"index",
"\n",
"q",
".",
"byId",
"=",
"byId",
"... | // Run executes the tag query on the given index and returns a list of ids | [
"Run",
"executes",
"the",
"tag",
"query",
"on",
"the",
"given",
"index",
"and",
"returns",
"a",
"list",
"of",
"ids"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/idx/memory/tag_query.go#L777-L807 | train |
grafana/metrictank | idx/memory/tag_query.go | filterTagsFromChan | func (q *TagQuery) filterTagsFromChan(idCh chan schema.MKey, tagCh chan string, stopCh chan struct{}, omitTagFilters bool) {
// used to prevent that this worker thread will push the same result into
// the chan twice
resultsCache := make(map[string]struct{})
IDS:
for id := range idCh {
var def *idx.Archive
var ok bool
if def, ok = q.byId[id]; !ok {
// should never happen because every ID in the tag index
// must be present in the byId lookup table
corruptIndex.Inc()
log.Errorf("memory-idx: ID %q is in tag index but not in the byId lookup table", id)
continue
}
// generate a set of all tags of the current metric that satisfy the
// tag filter condition
metricTags := make(map[string]struct{}, 0)
for _, tag := range def.Tags {
equal := strings.Index(tag, "=")
if equal < 0 {
corruptIndex.Inc()
log.Errorf("memory-idx: ID %q has tag %q in index without '=' sign", id, tag)
continue
}
key := tag[:equal]
// this tag has already been pushed into tagCh, so we can stop evaluating
if _, ok := resultsCache[key]; ok {
continue
}
if q.tagClause == PREFIX_TAG {
if !strings.HasPrefix(key, q.tagPrefix) {
continue
}
} else if q.tagClause == MATCH_TAG {
if _, ok := q.tagMatch.missCache.Load(key); ok || !q.tagMatch.value.MatchString(tag) {
if !ok {
q.tagMatch.missCache.Store(key, struct{}{})
}
continue
}
}
metricTags[key] = struct{}{}
}
// if we don't filter tags, then we can assume that "name" should always be part of the result set
if omitTagFilters {
if _, ok := resultsCache["name"]; !ok {
metricTags["name"] = struct{}{}
}
}
// if some tags satisfy the current tag filter condition then we run
// the metric through all tag expression tests in order to decide
// whether those tags should be part of the final result set
if len(metricTags) > 0 {
if q.testByAllExpressions(id, def, omitTagFilters) {
for key := range metricTags {
select {
case tagCh <- key:
case <-stopCh:
// if execution of query has stopped because the max tag
// count has been reached then tagCh <- might block
// because that channel will not be consumed anymore. in
// that case the stop channel will have been closed so
// we so we exit here
break IDS
}
resultsCache[key] = struct{}{}
}
} else {
// check if we need to stop
select {
case <-stopCh:
break IDS
default:
}
}
}
}
q.wg.Done()
} | go | func (q *TagQuery) filterTagsFromChan(idCh chan schema.MKey, tagCh chan string, stopCh chan struct{}, omitTagFilters bool) {
// used to prevent that this worker thread will push the same result into
// the chan twice
resultsCache := make(map[string]struct{})
IDS:
for id := range idCh {
var def *idx.Archive
var ok bool
if def, ok = q.byId[id]; !ok {
// should never happen because every ID in the tag index
// must be present in the byId lookup table
corruptIndex.Inc()
log.Errorf("memory-idx: ID %q is in tag index but not in the byId lookup table", id)
continue
}
// generate a set of all tags of the current metric that satisfy the
// tag filter condition
metricTags := make(map[string]struct{}, 0)
for _, tag := range def.Tags {
equal := strings.Index(tag, "=")
if equal < 0 {
corruptIndex.Inc()
log.Errorf("memory-idx: ID %q has tag %q in index without '=' sign", id, tag)
continue
}
key := tag[:equal]
// this tag has already been pushed into tagCh, so we can stop evaluating
if _, ok := resultsCache[key]; ok {
continue
}
if q.tagClause == PREFIX_TAG {
if !strings.HasPrefix(key, q.tagPrefix) {
continue
}
} else if q.tagClause == MATCH_TAG {
if _, ok := q.tagMatch.missCache.Load(key); ok || !q.tagMatch.value.MatchString(tag) {
if !ok {
q.tagMatch.missCache.Store(key, struct{}{})
}
continue
}
}
metricTags[key] = struct{}{}
}
// if we don't filter tags, then we can assume that "name" should always be part of the result set
if omitTagFilters {
if _, ok := resultsCache["name"]; !ok {
metricTags["name"] = struct{}{}
}
}
// if some tags satisfy the current tag filter condition then we run
// the metric through all tag expression tests in order to decide
// whether those tags should be part of the final result set
if len(metricTags) > 0 {
if q.testByAllExpressions(id, def, omitTagFilters) {
for key := range metricTags {
select {
case tagCh <- key:
case <-stopCh:
// if execution of query has stopped because the max tag
// count has been reached then tagCh <- might block
// because that channel will not be consumed anymore. in
// that case the stop channel will have been closed so
// we so we exit here
break IDS
}
resultsCache[key] = struct{}{}
}
} else {
// check if we need to stop
select {
case <-stopCh:
break IDS
default:
}
}
}
}
q.wg.Done()
} | [
"func",
"(",
"q",
"*",
"TagQuery",
")",
"filterTagsFromChan",
"(",
"idCh",
"chan",
"schema",
".",
"MKey",
",",
"tagCh",
"chan",
"string",
",",
"stopCh",
"chan",
"struct",
"{",
"}",
",",
"omitTagFilters",
"bool",
")",
"{",
"resultsCache",
":=",
"make",
"(... | // filterTagsFromChan takes a channel of metric IDs and evaluates each of them
// according to the criteria associated with this query
// those that pass all the tests will have their relevant tags extracted, which
// are then pushed into the given tag channel | [
"filterTagsFromChan",
"takes",
"a",
"channel",
"of",
"metric",
"IDs",
"and",
"evaluates",
"each",
"of",
"them",
"according",
"to",
"the",
"criteria",
"associated",
"with",
"this",
"query",
"those",
"that",
"pass",
"all",
"the",
"tests",
"will",
"have",
"their"... | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/idx/memory/tag_query.go#L841-L928 | train |
grafana/metrictank | idx/memory/tag_query.go | RunGetTags | func (q *TagQuery) RunGetTags(index TagIndex, byId map[schema.MKey]*idx.Archive) map[string]struct{} {
q.index = index
q.byId = byId
maxTagCount := int32(math.MaxInt32)
// start a thread to calculate the maximum possible number of tags.
// this might not always complete before the query execution, but in most
// cases it likely will. when it does end before the execution of the query,
// the value of maxTagCount will be used to abort the query execution once
// the max number of possible tags has been reached
q.wg.Add(1)
go atomic.StoreInt32(&maxTagCount, int32(q.getMaxTagCount()))
q.sortByCost()
idCh, stopCh := q.getInitialIds()
tagCh := make(chan string)
// we know there can only be 1 tag filter, so if we detect that the given
// tag condition matches the special tag "name", we can omit the filtering
// because every metric has a name.
matchName := q.tagFilterMatchesName()
// start the tag query workers. they'll consume the ids on the idCh and
// evaluate for each of them whether it satisfies all the conditions
// defined in the query expressions. then they will extract the tags of
// those that satisfy all conditions and push them into tagCh.
q.wg.Add(TagQueryWorkers)
for i := 0; i < TagQueryWorkers; i++ {
go q.filterTagsFromChan(idCh, tagCh, stopCh, matchName)
}
go func() {
q.wg.Wait()
close(tagCh)
}()
result := make(map[string]struct{})
for tag := range tagCh {
result[tag] = struct{}{}
// if we know that there can't be more results than what we have
// abort the query execution
if int32(len(result)) >= atomic.LoadInt32(&maxTagCount) {
break
}
}
// abort query execution and wait for all workers to end
close(stopCh)
q.wg.Wait()
return result
} | go | func (q *TagQuery) RunGetTags(index TagIndex, byId map[schema.MKey]*idx.Archive) map[string]struct{} {
q.index = index
q.byId = byId
maxTagCount := int32(math.MaxInt32)
// start a thread to calculate the maximum possible number of tags.
// this might not always complete before the query execution, but in most
// cases it likely will. when it does end before the execution of the query,
// the value of maxTagCount will be used to abort the query execution once
// the max number of possible tags has been reached
q.wg.Add(1)
go atomic.StoreInt32(&maxTagCount, int32(q.getMaxTagCount()))
q.sortByCost()
idCh, stopCh := q.getInitialIds()
tagCh := make(chan string)
// we know there can only be 1 tag filter, so if we detect that the given
// tag condition matches the special tag "name", we can omit the filtering
// because every metric has a name.
matchName := q.tagFilterMatchesName()
// start the tag query workers. they'll consume the ids on the idCh and
// evaluate for each of them whether it satisfies all the conditions
// defined in the query expressions. then they will extract the tags of
// those that satisfy all conditions and push them into tagCh.
q.wg.Add(TagQueryWorkers)
for i := 0; i < TagQueryWorkers; i++ {
go q.filterTagsFromChan(idCh, tagCh, stopCh, matchName)
}
go func() {
q.wg.Wait()
close(tagCh)
}()
result := make(map[string]struct{})
for tag := range tagCh {
result[tag] = struct{}{}
// if we know that there can't be more results than what we have
// abort the query execution
if int32(len(result)) >= atomic.LoadInt32(&maxTagCount) {
break
}
}
// abort query execution and wait for all workers to end
close(stopCh)
q.wg.Wait()
return result
} | [
"func",
"(",
"q",
"*",
"TagQuery",
")",
"RunGetTags",
"(",
"index",
"TagIndex",
",",
"byId",
"map",
"[",
"schema",
".",
"MKey",
"]",
"*",
"idx",
".",
"Archive",
")",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
"{",
"q",
".",
"index",
"=",
"ind... | // RunGetTags executes the tag query and returns all the tags of the
// resulting metrics | [
"RunGetTags",
"executes",
"the",
"tag",
"query",
"and",
"returns",
"all",
"the",
"tags",
"of",
"the",
"resulting",
"metrics"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/idx/memory/tag_query.go#L958-L1012 | train |
grafana/metrictank | mdata/chunk/tsz/tsz.go | NewSeries4h | func NewSeries4h(t0 uint32) *Series4h {
s := Series4h{
T0: t0,
leading: ^uint8(0),
}
// block header
s.bw.writeBits(uint64(t0), 32)
return &s
} | go | func NewSeries4h(t0 uint32) *Series4h {
s := Series4h{
T0: t0,
leading: ^uint8(0),
}
// block header
s.bw.writeBits(uint64(t0), 32)
return &s
} | [
"func",
"NewSeries4h",
"(",
"t0",
"uint32",
")",
"*",
"Series4h",
"{",
"s",
":=",
"Series4h",
"{",
"T0",
":",
"t0",
",",
"leading",
":",
"^",
"uint8",
"(",
"0",
")",
",",
"}",
"\n",
"s",
".",
"bw",
".",
"writeBits",
"(",
"uint64",
"(",
"t0",
")... | // NewSeries4h creates a new Series4h | [
"NewSeries4h",
"creates",
"a",
"new",
"Series4h"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/mdata/chunk/tsz/tsz.go#L39-L50 | train |
grafana/metrictank | mdata/chunk/tsz/tsz.go | Push | func (s *Series4h) Push(t uint32, v float64) {
s.Lock()
defer s.Unlock()
if s.t == 0 {
// first point
s.t = t
s.val = v
s.tDelta = t - s.T0
s.bw.writeBits(uint64(s.tDelta), 14)
s.bw.writeBits(math.Float64bits(v), 64)
return
}
tDelta := t - s.t
dod := int32(tDelta - s.tDelta)
switch {
case dod == 0:
s.bw.writeBit(zero)
case -63 <= dod && dod <= 64:
s.bw.writeBits(0x02, 2) // '10'
s.bw.writeBits(uint64(dod), 7)
case -255 <= dod && dod <= 256:
s.bw.writeBits(0x06, 3) // '110'
s.bw.writeBits(uint64(dod), 9)
case -2047 <= dod && dod <= 2048:
s.bw.writeBits(0x0e, 4) // '1110'
s.bw.writeBits(uint64(dod), 12)
default:
s.bw.writeBits(0x0f, 4) // '1111'
s.bw.writeBits(uint64(dod), 32)
}
vDelta := math.Float64bits(v) ^ math.Float64bits(s.val)
if vDelta == 0 {
s.bw.writeBit(zero)
} else {
s.bw.writeBit(one)
leading := uint8(bits.LeadingZeros64(vDelta))
trailing := uint8(bits.TrailingZeros64(vDelta))
// clamp number of leading zeros to avoid overflow when encoding
if leading >= 32 {
leading = 31
}
// TODO(dgryski): check if it's 'cheaper' to reset the leading/trailing bits instead
if s.leading != ^uint8(0) && leading >= s.leading && trailing >= s.trailing {
s.bw.writeBit(zero)
s.bw.writeBits(vDelta>>s.trailing, 64-int(s.leading)-int(s.trailing))
} else {
s.leading, s.trailing = leading, trailing
s.bw.writeBit(one)
s.bw.writeBits(uint64(leading), 5)
// Note that if leading == trailing == 0, then sigbits == 64. But that value doesn't actually fit into the 6 bits we have.
// Luckily, we never need to encode 0 significant bits, since that would put us in the other case (vdelta == 0).
// So instead we write out a 0 and adjust it back to 64 on unpacking.
sigbits := 64 - leading - trailing
s.bw.writeBits(uint64(sigbits), 6)
s.bw.writeBits(vDelta>>trailing, int(sigbits))
}
}
s.tDelta = tDelta
s.t = t
s.val = v
} | go | func (s *Series4h) Push(t uint32, v float64) {
s.Lock()
defer s.Unlock()
if s.t == 0 {
// first point
s.t = t
s.val = v
s.tDelta = t - s.T0
s.bw.writeBits(uint64(s.tDelta), 14)
s.bw.writeBits(math.Float64bits(v), 64)
return
}
tDelta := t - s.t
dod := int32(tDelta - s.tDelta)
switch {
case dod == 0:
s.bw.writeBit(zero)
case -63 <= dod && dod <= 64:
s.bw.writeBits(0x02, 2) // '10'
s.bw.writeBits(uint64(dod), 7)
case -255 <= dod && dod <= 256:
s.bw.writeBits(0x06, 3) // '110'
s.bw.writeBits(uint64(dod), 9)
case -2047 <= dod && dod <= 2048:
s.bw.writeBits(0x0e, 4) // '1110'
s.bw.writeBits(uint64(dod), 12)
default:
s.bw.writeBits(0x0f, 4) // '1111'
s.bw.writeBits(uint64(dod), 32)
}
vDelta := math.Float64bits(v) ^ math.Float64bits(s.val)
if vDelta == 0 {
s.bw.writeBit(zero)
} else {
s.bw.writeBit(one)
leading := uint8(bits.LeadingZeros64(vDelta))
trailing := uint8(bits.TrailingZeros64(vDelta))
// clamp number of leading zeros to avoid overflow when encoding
if leading >= 32 {
leading = 31
}
// TODO(dgryski): check if it's 'cheaper' to reset the leading/trailing bits instead
if s.leading != ^uint8(0) && leading >= s.leading && trailing >= s.trailing {
s.bw.writeBit(zero)
s.bw.writeBits(vDelta>>s.trailing, 64-int(s.leading)-int(s.trailing))
} else {
s.leading, s.trailing = leading, trailing
s.bw.writeBit(one)
s.bw.writeBits(uint64(leading), 5)
// Note that if leading == trailing == 0, then sigbits == 64. But that value doesn't actually fit into the 6 bits we have.
// Luckily, we never need to encode 0 significant bits, since that would put us in the other case (vdelta == 0).
// So instead we write out a 0 and adjust it back to 64 on unpacking.
sigbits := 64 - leading - trailing
s.bw.writeBits(uint64(sigbits), 6)
s.bw.writeBits(vDelta>>trailing, int(sigbits))
}
}
s.tDelta = tDelta
s.t = t
s.val = v
} | [
"func",
"(",
"s",
"*",
"Series4h",
")",
"Push",
"(",
"t",
"uint32",
",",
"v",
"float64",
")",
"{",
"s",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"Unlock",
"(",
")",
"\n",
"if",
"s",
".",
"t",
"==",
"0",
"{",
"s",
".",
"t",
"=",
"t"... | // Push a timestamp and value to the series | [
"Push",
"a",
"timestamp",
"and",
"value",
"to",
"the",
"series"
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/mdata/chunk/tsz/tsz.go#L70-L142 | train |
grafana/metrictank | mdata/chunk/tsz/tsz.go | Iter | func (s *Series4h) Iter(intervalHint uint32) *Iter4h {
s.Lock()
w := s.bw.clone()
s.Unlock()
finishV1(w)
iter, _ := bstreamIterator4h(w, intervalHint)
return iter
} | go | func (s *Series4h) Iter(intervalHint uint32) *Iter4h {
s.Lock()
w := s.bw.clone()
s.Unlock()
finishV1(w)
iter, _ := bstreamIterator4h(w, intervalHint)
return iter
} | [
"func",
"(",
"s",
"*",
"Series4h",
")",
"Iter",
"(",
"intervalHint",
"uint32",
")",
"*",
"Iter4h",
"{",
"s",
".",
"Lock",
"(",
")",
"\n",
"w",
":=",
"s",
".",
"bw",
".",
"clone",
"(",
")",
"\n",
"s",
".",
"Unlock",
"(",
")",
"\n",
"finishV1",
... | // Iter4h lets you iterate over a series. It is not concurrency-safe. | [
"Iter4h",
"lets",
"you",
"iterate",
"over",
"a",
"series",
".",
"It",
"is",
"not",
"concurrency",
"-",
"safe",
"."
] | dd9b92db72d27553d9a8214bff5f01d2531f63b0 | https://github.com/grafana/metrictank/blob/dd9b92db72d27553d9a8214bff5f01d2531f63b0/mdata/chunk/tsz/tsz.go#L145-L153 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.