_id
stringlengths
2
7
title
stringlengths
1
118
partition
stringclasses
3 values
text
stringlengths
52
85.5k
language
stringclasses
1 value
meta_information
dict
q35700
SetState
train
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
{ "resource": "" }
q35701
SetPriority
train
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
{ "resource": "" }
q35702
SetPrimary
train
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
{ "resource": "" }
q35703
SetPartitions
train
func (n *HTTPNode) SetPartitions(part []int32) { n.Partitions = part n.Updated = time.Now() }
go
{ "resource": "" }
q35704
DiffPartitions
train
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
{ "resource": "" }
q35705
MarshalJSONFast
train
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.AppendQuot...
go
{ "resource": "" }
q35706
NewTimeLimiter
train
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
{ "resource": "" }
q35707
Add
train
func (l *TimeLimiter) Add(d time.Duration) { l.add(time.Now(), d) }
go
{ "resource": "" }
q35708
add
train
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
{ "resource": "" }
q35709
AddOrUpdate
train
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...
go
{ "resource": "" }
q35710
indexTags
train
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 t...
go
{ "resource": "" }
q35711
deindexTags
train
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(...
go
{ "resource": "" }
q35712
LoadPartition
train
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
{ "resource": "" }
q35713
GetPath
train
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 :...
go
{ "resource": "" }
q35714
Tags
train
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 + ")...
go
{ "resource": "" }
q35715
deleteTaggedByIdSet
train
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 co...
go
{ "resource": "" }
q35716
Lcm
train
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 } }...
go
{ "resource": "" }
q35717
ProcessMetricPoint
train
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 !po...
go
{ "resource": "" }
q35718
ProcessMetricData
train
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 ...
go
{ "resource": "" }
q35719
FormatRowKey
train
func FormatRowKey(mkey schema.MKey, partition int32) string { return strconv.Itoa(int(partition)) + "_" + mkey.String() }
go
{ "resource": "" }
q35720
SchemaToRow
train
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), ...
go
{ "resource": "" }
q35721
DecodeRowKey
train
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), ...
go
{ "resource": "" }
q35722
RowToSchema
train
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 ...
go
{ "resource": "" }
q35723
String
train
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 "M...
go
{ "resource": "" }
q35724
Archive
train
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: r...
go
{ "resource": "" }
q35725
GetAggFunc
train
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 cas...
go
{ "resource": "" }
q35726
updateBigtable
train
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-...
go
{ "resource": "" }
q35727
NewCCacheMetric
train
func NewCCacheMetric(mkey schema.MKey) *CCacheMetric { return &CCacheMetric{ MKey: mkey, chunks: make(map[uint32]*CCacheChunk), } }
go
{ "resource": "" }
q35728
Del
train
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.chun...
go
{ "resource": "" }
q35729
Add
train
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, ...
go
{ "resource": "" }
q35730
generateKeys
train
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
{ "resource": "" }
q35731
lastTs
train
func (mc *CCacheMetric) lastTs() uint32 { mc.RLock() defer mc.RUnlock() return mc.nextTs(mc.keys[len(mc.keys)-1]) }
go
{ "resource": "" }
q35732
seekAsc
train
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.key...
go
{ "resource": "" }
q35733
writer
train
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....
go
{ "resource": "" }
q35734
Add
train
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...
go
{ "resource": "" }
q35735
Get
train
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)) } ...
go
{ "resource": "" }
q35736
incResolution
train
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 b...
go
{ "resource": "" }
q35737
decResolution
train
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 "...
go
{ "resource": "" }
q35738
Add
train
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
{ "resource": "" }
q35739
encode
train
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...
go
{ "resource": "" }
q35740
parseExpression
train
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...
go
{ "resource": "" }
q35741
getInitialByEqual
train
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
{ "resource": "" }
q35742
getInitialByPrefix
train
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: } }...
go
{ "resource": "" }
q35743
getInitialByMatch
train
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: ...
go
{ "resource": "" }
q35744
getInitialByTagPrefix
train
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 c...
go
{ "resource": "" }
q35745
getInitialByTagMatch
train
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:...
go
{ "resource": "" }
q35746
filterIdsFromChan
train
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: ...
go
{ "resource": "" }
q35747
sortByCost
train
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.pre...
go
{ "resource": "" }
q35748
Run
train
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 ...
go
{ "resource": "" }
q35749
filterTagsFromChan
train
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...
go
{ "resource": "" }
q35750
RunGetTags
train
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 /...
go
{ "resource": "" }
q35751
NewSeries4h
train
func NewSeries4h(t0 uint32) *Series4h { s := Series4h{ T0: t0, leading: ^uint8(0), } // block header s.bw.writeBits(uint64(t0), 32) return &s }
go
{ "resource": "" }
q35752
Push
train
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 =...
go
{ "resource": "" }
q35753
Iter
train
func (s *Series4h) Iter(intervalHint uint32) *Iter4h { s.Lock() w := s.bw.clone() s.Unlock() finishV1(w) iter, _ := bstreamIterator4h(w, intervalHint) return iter }
go
{ "resource": "" }
q35754
NewIterator4h
train
func NewIterator4h(b []byte, intervalHint uint32) (*Iter4h, error) { return bstreamIterator4h(newBReader(b), intervalHint) }
go
{ "resource": "" }
q35755
clusterStats
train
func (c *MemberlistManager) clusterStats() { primReady := 0 primNotReady := 0 secReady := 0 secNotReady := 0 queryReady := 0 queryNotReady := 0 partitions := make(map[int32]int) for _, p := range c.members { if p.Primary { if p.IsReady() { primReady++ } else { primNotReady++ } } else if p.M...
go
{ "resource": "" }
q35756
NodeMeta
train
func (c *MemberlistManager) NodeMeta(limit int) []byte { c.RLock() meta, err := json.Marshal(c.members[c.nodeName]) c.RUnlock() if err != nil { log.Fatalf("CLU manager: %s", err.Error()) } return meta }
go
{ "resource": "" }
q35757
IsReady
train
func (c *MemberlistManager) IsReady() bool { c.RLock() defer c.RUnlock() return c.members[c.nodeName].IsReady() }
go
{ "resource": "" }
q35758
SetState
train
func (c *MemberlistManager) SetState(state NodeState) { c.Lock() node := c.members[c.nodeName] if !node.SetState(state) { c.Unlock() return } c.members[c.nodeName] = node c.Unlock() nodeReady.Set(state == NodeReady) c.BroadcastUpdate() }
go
{ "resource": "" }
q35759
IsPrimary
train
func (c *MemberlistManager) IsPrimary() bool { c.RLock() defer c.RUnlock() return c.members[c.nodeName].Primary }
go
{ "resource": "" }
q35760
SetPrimary
train
func (c *MemberlistManager) SetPrimary(primary bool) { c.Lock() node := c.members[c.nodeName] if !node.SetPrimary(primary) { c.Unlock() return } c.members[c.nodeName] = node c.Unlock() nodePrimary.Set(primary) c.BroadcastUpdate() }
go
{ "resource": "" }
q35761
Signature
train
func (s *FuncMovingAverage) Signature() ([]Arg, []Arg) { return []Arg{ ArgSeriesList{val: &s.in}, // this could be an int OR a string. // we need to figure out the interval of the data we will consume // and request from -= interval * points // interestingly the from adjustment might mean the archive TTL is ...
go
{ "resource": "" }
q35762
NewAggregateConstructor
train
func NewAggregateConstructor(aggDescription string, aggFunc crossSeriesAggFunc) func() GraphiteFunc { return func() GraphiteFunc { return &FuncAggregate{agg: seriesAggregator{function: aggFunc, name: aggDescription}} } }
go
{ "resource": "" }
q35763
tryGetOffset
train
func (k *KafkaMdm) tryGetOffset(topic string, partition int32, offset int64, attempts int, sleep time.Duration) (int64, error) { var val int64 var err error var offsetStr string switch offset { case sarama.OffsetNewest: offsetStr = "newest" case sarama.OffsetOldest: offsetStr = "oldest" default: offsetSt...
go
{ "resource": "" }
q35764
consumePartition
train
func (k *KafkaMdm) consumePartition(topic string, partition int32, currentOffset int64) { defer k.wg.Done() // determine the pos of the topic and the initial offset of our consumer newest, err := k.tryGetOffset(topic, partition, sarama.OffsetNewest, 7, time.Second*10) if err != nil { log.Errorf("kafkamdm: %s", e...
go
{ "resource": "" }
q35765
InitBare
train
func (c *CasIdx) InitBare() error { var err error tmpSession, err := c.cluster.CreateSession() if err != nil { return fmt.Errorf("failed to create cassandra session: %s", err) } // read templates schemaKeyspace := util.ReadEntry(c.cfg.schemaFile, "schema_keyspace").(string) schemaTable := util.ReadEntry(c.cfg...
go
{ "resource": "" }
q35766
EnsureArchiveTableExists
train
func (c *CasIdx) EnsureArchiveTableExists(session *gocql.Session) error { var err error if session == nil { session, err = c.cluster.CreateSession() if err != nil { return fmt.Errorf("failed to create cassandra session: %s", err) } } schemaArchiveTable := util.ReadEntry(c.cfg.schemaFile, "schema_archive_t...
go
{ "resource": "" }
q35767
Init
train
func (c *CasIdx) Init() error { log.Infof("initializing cassandra-idx. Hosts=%s", c.cfg.hosts) if err := c.MemoryIndex.Init(); err != nil { return err } if err := c.InitBare(); err != nil { return err } if c.cfg.updateCassIdx { c.wg.Add(c.cfg.numConns) for i := 0; i < c.cfg.numConns; i++ { go c.proce...
go
{ "resource": "" }
q35768
updateCassandra
train
func (c *CasIdx) updateCassandra(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 - c.updateInterval32 - c.updateInterval32/2) { log.Debugf("cassandra-idx: updating d...
go
{ "resource": "" }
q35769
LoadPartitions
train
func (c *CasIdx) LoadPartitions(partitions []int32, defs []schema.MetricDefinition, now time.Time) []schema.MetricDefinition { placeholders := make([]string, len(partitions)) for i, p := range partitions { placeholders[i] = strconv.Itoa(int(p)) } q := fmt.Sprintf("SELECT id, orgid, partition, name, interval, unit...
go
{ "resource": "" }
q35770
load
train
func (c *CasIdx) load(defs []schema.MetricDefinition, iter cqlIterator, now time.Time) []schema.MetricDefinition { defsByNames := make(map[string][]*schema.MetricDefinition) var id, name, unit, mtype string var orgId, interval int var partition int32 var lastupdate int64 var tags []string for iter.Scan(&id, &org...
go
{ "resource": "" }
q35771
ArchiveDefs
train
func (c *CasIdx) ArchiveDefs(defs []schema.MetricDefinition) (int, error) { defChan := make(chan *schema.MetricDefinition, c.cfg.numConns) g, ctx := errgroup.WithContext(context.Background()) // keep track of how many defs were successfully archived. success := make([]int, c.cfg.numConns) for i := 0; i < c.cfg.n...
go
{ "resource": "" }
q35772
flush
train
func (c *NotifierKafka) flush() { if len(c.buf) == 0 { return } // In order to correctly route the saveMessages to the correct partition, // we can't send them in batches anymore. payload := make([]*sarama.ProducerMessage, 0, len(c.buf)) var pMsg mdata.PersistMessageBatch for i, msg := range c.buf { amkey, ...
go
{ "resource": "" }
q35773
indexFind
train
func (s *Server) indexFind(ctx *middleware.Context, req models.IndexFind) { resp := models.NewIndexFindResp() // query nodes don't own any data if s.MetricIndex == nil { response.Write(ctx, response.NewMsgp(200, resp)) return } for _, pattern := range req.Patterns { nodes, err := s.MetricIndex.Find(req.Org...
go
{ "resource": "" }
q35774
indexGet
train
func (s *Server) indexGet(ctx *middleware.Context, req models.IndexGet) { // query nodes don't own any data. if s.MetricIndex == nil { response.Write(ctx, response.NewMsgp(404, nil)) return } def, ok := s.MetricIndex.Get(req.MKey) if !ok { response.Write(ctx, response.NewError(http.StatusNotFound, "Not Fou...
go
{ "resource": "" }
q35775
indexList
train
func (s *Server) indexList(ctx *middleware.Context, req models.IndexList) { // query nodes don't own any data. if s.MetricIndex == nil { response.Write(ctx, response.NewMsgpArray(200, nil)) return } defs := s.MetricIndex.List(req.OrgId) resp := make([]msgp.Marshaler, len(defs)) for i := range defs { d := ...
go
{ "resource": "" }
q35776
Error
train
func Error(span opentracing.Span, err error) { span.LogFields(log.Error(err)) }
go
{ "resource": "" }
q35777
Errorf
train
func Errorf(span opentracing.Span, format string, a ...interface{}) { span.LogFields(log.Error(fmt.Errorf(format, a...))) }
go
{ "resource": "" }
q35778
AlignedTick
train
func AlignedTick(period time.Duration) <-chan time.Time { // note that time.Ticker is not an interface, // and that if we instantiate one, we can't write to its channel // hence we can't leverage that type. c := make(chan time.Time) go func() { for { unix := time.Now().UnixNano() diff := time.Duration(peri...
go
{ "resource": "" }
q35779
Tracer
train
func Tracer(tracer opentracing.Tracer) macaron.Handler { return func(macCtx *macaron.Context) { path := pathSlug(macCtx.Req.URL.Path) // graphite cluster requests use local=1 // this way we can differentiate "full" render requests from client to MT (encompassing data processing, proxing to graphite, etc) // fr...
go
{ "resource": "" }
q35780
Get
train
func (s Schemas) Get(i uint16) Schema { if i+1 > uint16(len(s.index)) { return s.DefaultSchema } return s.index[i] }
go
{ "resource": "" }
q35781
TTLs
train
func (schemas Schemas) TTLs() []uint32 { ttls := make(map[uint32]struct{}) for _, s := range schemas.raw { for _, r := range s.Retentions { ttls[uint32(r.MaxRetention())] = struct{}{} } } for _, r := range schemas.DefaultSchema.Retentions { ttls[uint32(r.MaxRetention())] = struct{}{} } var ttlSlice []uin...
go
{ "resource": "" }
q35782
MaxChunkSpan
train
func (schemas Schemas) MaxChunkSpan() uint32 { max := uint32(0) for _, s := range schemas.raw { for _, r := range s.Retentions { max = util.Max(max, r.ChunkSpan) } } for _, r := range schemas.DefaultSchema.Retentions { max = util.Max(max, r.ChunkSpan) } return max }
go
{ "resource": "" }
q35783
patternCustom
train
func patternCustom(in ...interface{}) string { usage := func() { PatternCustomUsage("") os.Exit(-1) } // one or more of "<chance> <operation>" followed by an input string at the end. if len(in) < 3 || len(in)%2 != 1 { usage() } input, ok := in[len(in)-1].(string) if !ok { usage() } var buckets []bucke...
go
{ "resource": "" }
q35784
ReplaceRandomConsecutiveNodesWildcard
train
func ReplaceRandomConsecutiveNodesWildcard(num int) func(in string) string { return func(in string) string { parts := strings.Split(in, ".") if len(parts) < num { log.Fatalf("metric %q has not enough nodes to replace %d nodes", in, num) } pos := rand.Intn(len(parts) - num + 1) for i := pos; i < pos+num; i...
go
{ "resource": "" }
q35785
printPointSummary
train
func printPointSummary(ctx context.Context, store *cassandra.CassandraStore, tables []cassandra.Table, metrics []Metric, fromUnix, toUnix, fix uint32) { for _, metric := range metrics { fmt.Println("## Metric", metric) for _, table := range tables { fmt.Println("### Table", table.Name) if fix != 0 { poin...
go
{ "resource": "" }
q35786
pattern
train
func pattern(in string) string { mode := rand.Intn(3) if mode == 0 { // in this mode, replaces a node with a wildcard parts := strings.Split(in, ".") parts[rand.Intn(len(parts))] = "*" return strings.Join(parts, ".") } else if mode == 1 { // randomly replace chars with a * // note that in 1/5 cases, noth...
go
{ "resource": "" }
q35787
roundDuration
train
func roundDuration(in int64) int64 { abs := in if abs < 0 { abs = -abs } if abs <= 10 { // 10s -> don't round return in } else if abs <= 60 { // 1min -> round to 10s return round(in, 10) } else if abs <= 600 { // 10min -> round to 1min return round(in, 60) } else if abs <= 3600 { // 1h -> round to 10min ...
go
{ "resource": "" }
q35788
round
train
func round(d, r int64) int64 { neg := d < 0 if neg { d = -d } if m := d % r; m+m < r { d = d - m } else { d = d + r - m } if neg { return -d } return d }
go
{ "resource": "" }
q35789
showKeyTTL
train
func showKeyTTL(iter *gocql.Iter, groupTTL string) { roundTTL := 1 switch groupTTL { case "m": roundTTL = 60 case "h": roundTTL = 60 * 60 case "d": roundTTL = 60 * 60 * 24 } var b bucket bucketMap := make(map[bucket]int) for iter.Scan(&b.key, &b.ttl) { b.ttl /= roundTTL bucketMap[b] += 1 } var bu...
go
{ "resource": "" }
q35790
ParseRetentions
train
func ParseRetentions(defs string) (Retentions, error) { retentions := make(Retentions, 0) for i, def := range strings.Split(defs, ",") { def = strings.TrimSpace(def) parts := strings.Split(def, ":") if len(parts) < 2 || len(parts) > 5 { return nil, fmt.Errorf("bad retentions spec %q", def) } // try old ...
go
{ "resource": "" }
q35791
getMetrics
train
func getMetrics(store *cassandra.CassandraStore, prefix, substr, glob string, archive schema.Archive) ([]Metric, error) { var metrics []Metric iter := store.Session.Query("select id, name from metric_idx").Iter() var m Metric var idString string for iter.Scan(&idString, &m.name) { if match(prefix, substr, glob, ...
go
{ "resource": "" }
q35792
getMetric
train
func getMetric(store *cassandra.CassandraStore, amkey schema.AMKey) ([]Metric, error) { var metrics []Metric // index only stores MKey's, not AMKey's. iter := store.Session.Query("select name from metric_idx where id=? ALLOW FILTERING", amkey.MKey.String()).Iter() var m Metric for iter.Scan(&m.name) { m.AMKey = ...
go
{ "resource": "" }
q35793
ConsolidateStable
train
func ConsolidateStable(points []schema.Point, interval, maxDataPoints uint32, consolidator Consolidator) ([]schema.Point, uint32) { aggNum := AggEvery(uint32(len(points)), maxDataPoints) // note that the amount of points to strip is always < 1 postAggInterval's worth. // there's 2 important considerations here: // ...
go
{ "resource": "" }
q35794
doRecover
train
func doRecover(errp *error) { e := recover() if e != nil { if _, ok := e.(runtime.Error); ok { panic(e) } if err, ok := e.(error); ok { *errp = err } else if errStr, ok := e.(string); ok { *errp = errors.New(errStr) } else { *errp = fmt.Errorf("%v", e) } } return }
go
{ "resource": "" }
q35795
getTargetsRemote
train
func (s *Server) getTargetsRemote(ctx context.Context, remoteReqs map[string][]models.Req) ([]models.Series, error) { responses := make(chan getTargetsResp, len(remoteReqs)) rCtx, cancel := context.WithCancel(ctx) defer cancel() wg := sync.WaitGroup{} wg.Add(len(remoteReqs)) for _, nodeReqs := range remoteReqs { ...
go
{ "resource": "" }
q35796
getTargetsLocal
train
func (s *Server) getTargetsLocal(ctx context.Context, reqs []models.Req) ([]models.Series, error) { log.Debugf("DP getTargetsLocal: handling %d reqs locally", len(reqs)) responses := make(chan getTargetsResp, len(reqs)) var wg sync.WaitGroup reqLimiter := util.NewLimiter(getTargetsConcurrency) rCtx, cancel := co...
go
{ "resource": "" }
q35797
mergeSeries
train
func mergeSeries(in []models.Series) []models.Series { type segment struct { target string query string from uint32 to uint32 con consolidation.Consolidator } seriesByTarget := make(map[segment][]models.Series) for _, series := range in { s := segment{ series.Target, series.QueryPatt, ...
go
{ "resource": "" }
q35798
NewChunkWriteRequest
train
func NewChunkWriteRequest(metric *AggMetric, key schema.AMKey, chunk *chunk.Chunk, ttl, span uint32, ts time.Time) ChunkWriteRequest { return ChunkWriteRequest{metric, key, chunk, ttl, span, ts} }
go
{ "resource": "" }
q35799
Iter
train
func (s *SeriesLong) Iter() *IterLong { s.Lock() w := s.bw.clone() s.Unlock() finishV2(w) iter, _ := bstreamIteratorLong(s.T0, w) return iter }
go
{ "resource": "" }