ReadLabels reads up to n label sets in a JSON formatted file fn. It is mostly useful to load testing data.
(fn string, n int)
| 43 | // ReadLabels reads up to n label sets in a JSON formatted file fn. It is mostly useful |
| 44 | // to load testing data. |
| 45 | func ReadLabels(fn string, n int) ([]Labels, error) { |
| 46 | f, err := os.Open(fn) |
| 47 | if err != nil { |
| 48 | return nil, err |
| 49 | } |
| 50 | defer f.Close() |
| 51 | |
| 52 | scanner := bufio.NewScanner(f) |
| 53 | b := NewScratchBuilder(0) |
| 54 | |
| 55 | var mets []Labels |
| 56 | hashes := map[uint64]struct{}{} |
| 57 | i := 0 |
| 58 | |
| 59 | for scanner.Scan() && i < n { |
| 60 | b.Reset() |
| 61 | |
| 62 | r := strings.NewReplacer("\"", "", "{", "", "}", "") |
| 63 | s := r.Replace(scanner.Text()) |
| 64 | |
| 65 | for labelChunk := range strings.SplitSeq(s, ",") { |
| 66 | split := strings.Split(labelChunk, ":") |
| 67 | b.Add(split[0], split[1]) |
| 68 | } |
| 69 | // Order of the k/v labels matters, don't assume we'll always receive them already sorted. |
| 70 | b.Sort() |
| 71 | m := b.Labels() |
| 72 | |
| 73 | h := m.Hash() |
| 74 | if _, ok := hashes[h]; ok { |
| 75 | continue |
| 76 | } |
| 77 | mets = append(mets, m) |
| 78 | hashes[h] = struct{}{} |
| 79 | i++ |
| 80 | } |
| 81 | |
| 82 | if i != n { |
| 83 | return mets, fmt.Errorf("requested %d metrics but found %d", n, i) |
| 84 | } |
| 85 | return mets, nil |
| 86 | } |