repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
list | docstring
stringlengths 6
2.61k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 85
252
| partition
stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
golang/tour
|
tour.go
|
findPlayCode
|
func findPlayCode(e present.Elem) []*present.Code {
var r []*present.Code
switch v := e.(type) {
case present.Code:
if v.Play {
r = append(r, &v)
}
case present.Section:
for _, s := range v.Elem {
r = append(r, findPlayCode(s)...)
}
}
return r
}
|
go
|
func findPlayCode(e present.Elem) []*present.Code {
var r []*present.Code
switch v := e.(type) {
case present.Code:
if v.Play {
r = append(r, &v)
}
case present.Section:
for _, s := range v.Elem {
r = append(r, findPlayCode(s)...)
}
}
return r
}
|
[
"func",
"findPlayCode",
"(",
"e",
"present",
".",
"Elem",
")",
"[",
"]",
"*",
"present",
".",
"Code",
"{",
"var",
"r",
"[",
"]",
"*",
"present",
".",
"Code",
"\n",
"switch",
"v",
":=",
"e",
".",
"(",
"type",
")",
"{",
"case",
"present",
".",
"Code",
":",
"if",
"v",
".",
"Play",
"{",
"r",
"=",
"append",
"(",
"r",
",",
"&",
"v",
")",
"\n",
"}",
"\n",
"case",
"present",
".",
"Section",
":",
"for",
"_",
",",
"s",
":=",
"range",
"v",
".",
"Elem",
"{",
"r",
"=",
"append",
"(",
"r",
",",
"findPlayCode",
"(",
"s",
")",
"...",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"r",
"\n",
"}"
] |
// findPlayCode returns a slide with all the Code elements in the given
// Elem with Play set to true.
|
[
"findPlayCode",
"returns",
"a",
"slide",
"with",
"all",
"the",
"Code",
"elements",
"in",
"the",
"given",
"Elem",
"with",
"Play",
"set",
"to",
"true",
"."
] |
db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77
|
https://github.com/golang/tour/blob/db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77/tour.go#L165-L178
|
train
|
golang/tour
|
tour.go
|
writeLesson
|
func writeLesson(name string, w io.Writer) error {
if uiContent == nil {
panic("writeLesson called before successful initTour")
}
if len(name) == 0 {
return writeAllLessons(w)
}
l, ok := lessons[name]
if !ok {
return lessonNotFound
}
_, err := w.Write(l)
return err
}
|
go
|
func writeLesson(name string, w io.Writer) error {
if uiContent == nil {
panic("writeLesson called before successful initTour")
}
if len(name) == 0 {
return writeAllLessons(w)
}
l, ok := lessons[name]
if !ok {
return lessonNotFound
}
_, err := w.Write(l)
return err
}
|
[
"func",
"writeLesson",
"(",
"name",
"string",
",",
"w",
"io",
".",
"Writer",
")",
"error",
"{",
"if",
"uiContent",
"==",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"name",
")",
"==",
"0",
"{",
"return",
"writeAllLessons",
"(",
"w",
")",
"\n",
"}",
"\n",
"l",
",",
"ok",
":=",
"lessons",
"[",
"name",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"lessonNotFound",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"l",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// writeLesson writes the tour content to the provided Writer.
|
[
"writeLesson",
"writes",
"the",
"tour",
"content",
"to",
"the",
"provided",
"Writer",
"."
] |
db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77
|
https://github.com/golang/tour/blob/db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77/tour.go#L181-L194
|
train
|
golang/tour
|
tour.go
|
renderUI
|
func renderUI(w io.Writer) error {
if uiContent == nil {
panic("renderUI called before successful initTour")
}
_, err := w.Write(uiContent)
return err
}
|
go
|
func renderUI(w io.Writer) error {
if uiContent == nil {
panic("renderUI called before successful initTour")
}
_, err := w.Write(uiContent)
return err
}
|
[
"func",
"renderUI",
"(",
"w",
"io",
".",
"Writer",
")",
"error",
"{",
"if",
"uiContent",
"==",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"uiContent",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// renderUI writes the tour UI to the provided Writer.
|
[
"renderUI",
"writes",
"the",
"tour",
"UI",
"to",
"the",
"provided",
"Writer",
"."
] |
db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77
|
https://github.com/golang/tour/blob/db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77/tour.go#L217-L223
|
train
|
golang/tour
|
tour.go
|
nocode
|
func nocode(s present.Section) bool {
for _, e := range s.Elem {
if c, ok := e.(present.Code); ok && c.Play {
return false
}
}
return true
}
|
go
|
func nocode(s present.Section) bool {
for _, e := range s.Elem {
if c, ok := e.(present.Code); ok && c.Play {
return false
}
}
return true
}
|
[
"func",
"nocode",
"(",
"s",
"present",
".",
"Section",
")",
"bool",
"{",
"for",
"_",
",",
"e",
":=",
"range",
"s",
".",
"Elem",
"{",
"if",
"c",
",",
"ok",
":=",
"e",
".",
"(",
"present",
".",
"Code",
")",
";",
"ok",
"&&",
"c",
".",
"Play",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] |
// nocode returns true if the provided Section contains
// no Code elements with Play enabled.
|
[
"nocode",
"returns",
"true",
"if",
"the",
"provided",
"Section",
"contains",
"no",
"Code",
"elements",
"with",
"Play",
"enabled",
"."
] |
db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77
|
https://github.com/golang/tour/blob/db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77/tour.go#L227-L234
|
train
|
kahing/goofys
|
internal/goofys.go
|
GetFullName
|
func (fs *Goofys) GetFullName(id fuseops.InodeID) *string {
fs.mu.Lock()
inode := fs.inodes[id]
fs.mu.Unlock()
if inode == nil {
return nil
}
return inode.FullName()
}
|
go
|
func (fs *Goofys) GetFullName(id fuseops.InodeID) *string {
fs.mu.Lock()
inode := fs.inodes[id]
fs.mu.Unlock()
if inode == nil {
return nil
}
return inode.FullName()
}
|
[
"func",
"(",
"fs",
"*",
"Goofys",
")",
"GetFullName",
"(",
"id",
"fuseops",
".",
"InodeID",
")",
"*",
"string",
"{",
"fs",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"inode",
":=",
"fs",
".",
"inodes",
"[",
"id",
"]",
"\n",
"fs",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"inode",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"inode",
".",
"FullName",
"(",
")",
"\n\n",
"}"
] |
// GetFullName returns full name of the given inode
|
[
"GetFullName",
"returns",
"full",
"name",
"of",
"the",
"given",
"inode"
] |
224a69530a8fefa8f07e51582b928739127134f2
|
https://github.com/kahing/goofys/blob/224a69530a8fefa8f07e51582b928739127134f2/internal/goofys.go#L1174-L1183
|
train
|
kahing/goofys
|
internal/flags.go
|
filterCategory
|
func filterCategory(flags []cli.Flag, category string) (ret []cli.Flag) {
for _, f := range flags {
if flagCategories[f.GetName()] == category {
ret = append(ret, f)
}
}
return
}
|
go
|
func filterCategory(flags []cli.Flag, category string) (ret []cli.Flag) {
for _, f := range flags {
if flagCategories[f.GetName()] == category {
ret = append(ret, f)
}
}
return
}
|
[
"func",
"filterCategory",
"(",
"flags",
"[",
"]",
"cli",
".",
"Flag",
",",
"category",
"string",
")",
"(",
"ret",
"[",
"]",
"cli",
".",
"Flag",
")",
"{",
"for",
"_",
",",
"f",
":=",
"range",
"flags",
"{",
"if",
"flagCategories",
"[",
"f",
".",
"GetName",
"(",
")",
"]",
"==",
"category",
"{",
"ret",
"=",
"append",
"(",
"ret",
",",
"f",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Set up custom help text for goofys; in particular the usage section.
|
[
"Set",
"up",
"custom",
"help",
"text",
"for",
"goofys",
";",
"in",
"particular",
"the",
"usage",
"section",
"."
] |
224a69530a8fefa8f07e51582b928739127134f2
|
https://github.com/kahing/goofys/blob/224a69530a8fefa8f07e51582b928739127134f2/internal/flags.go#L35-L42
|
train
|
kahing/goofys
|
main.go
|
mount
|
func mount(
ctx context.Context,
bucketName string,
flags *FlagStorage) (fs *Goofys, mfs *fuse.MountedFileSystem, err error) {
// XXX really silly copy here! in goofys.Mount we will copy it
// back to FlagStorage. But I don't see a easier way to expose
// Config in the api package
var config goofys.Config
copier.Copy(&config, *flags)
return goofys.Mount(ctx, bucketName, &config)
}
|
go
|
func mount(
ctx context.Context,
bucketName string,
flags *FlagStorage) (fs *Goofys, mfs *fuse.MountedFileSystem, err error) {
// XXX really silly copy here! in goofys.Mount we will copy it
// back to FlagStorage. But I don't see a easier way to expose
// Config in the api package
var config goofys.Config
copier.Copy(&config, *flags)
return goofys.Mount(ctx, bucketName, &config)
}
|
[
"func",
"mount",
"(",
"ctx",
"context",
".",
"Context",
",",
"bucketName",
"string",
",",
"flags",
"*",
"FlagStorage",
")",
"(",
"fs",
"*",
"Goofys",
",",
"mfs",
"*",
"fuse",
".",
"MountedFileSystem",
",",
"err",
"error",
")",
"{",
"// XXX really silly copy here! in goofys.Mount we will copy it",
"// back to FlagStorage. But I don't see a easier way to expose",
"// Config in the api package",
"var",
"config",
"goofys",
".",
"Config",
"\n",
"copier",
".",
"Copy",
"(",
"&",
"config",
",",
"*",
"flags",
")",
"\n\n",
"return",
"goofys",
".",
"Mount",
"(",
"ctx",
",",
"bucketName",
",",
"&",
"config",
")",
"\n",
"}"
] |
// Mount the file system based on the supplied arguments, returning a
// fuse.MountedFileSystem that can be joined to wait for unmounting.
|
[
"Mount",
"the",
"file",
"system",
"based",
"on",
"the",
"supplied",
"arguments",
"returning",
"a",
"fuse",
".",
"MountedFileSystem",
"that",
"can",
"be",
"joined",
"to",
"wait",
"for",
"unmounting",
"."
] |
224a69530a8fefa8f07e51582b928739127134f2
|
https://github.com/kahing/goofys/blob/224a69530a8fefa8f07e51582b928739127134f2/main.go#L106-L118
|
train
|
kahing/goofys
|
internal/perms.go
|
MyUserAndGroup
|
func MyUserAndGroup() (uid int, gid int) {
// Ask for the current user.
user, err := user.Current()
if err != nil {
panic(err)
}
// Parse UID.
uid64, err := strconv.ParseInt(user.Uid, 10, 32)
if err != nil {
log.Fatalf("Parsing UID (%s): %v", user.Uid, err)
return
}
// Parse GID.
gid64, err := strconv.ParseInt(user.Gid, 10, 32)
if err != nil {
log.Fatalf("Parsing GID (%s): %v", user.Gid, err)
return
}
uid = int(uid64)
gid = int(gid64)
return
}
|
go
|
func MyUserAndGroup() (uid int, gid int) {
// Ask for the current user.
user, err := user.Current()
if err != nil {
panic(err)
}
// Parse UID.
uid64, err := strconv.ParseInt(user.Uid, 10, 32)
if err != nil {
log.Fatalf("Parsing UID (%s): %v", user.Uid, err)
return
}
// Parse GID.
gid64, err := strconv.ParseInt(user.Gid, 10, 32)
if err != nil {
log.Fatalf("Parsing GID (%s): %v", user.Gid, err)
return
}
uid = int(uid64)
gid = int(gid64)
return
}
|
[
"func",
"MyUserAndGroup",
"(",
")",
"(",
"uid",
"int",
",",
"gid",
"int",
")",
"{",
"// Ask for the current user.",
"user",
",",
"err",
":=",
"user",
".",
"Current",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// Parse UID.",
"uid64",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"user",
".",
"Uid",
",",
"10",
",",
"32",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"user",
".",
"Uid",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Parse GID.",
"gid64",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"user",
".",
"Gid",
",",
"10",
",",
"32",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"user",
".",
"Gid",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"uid",
"=",
"int",
"(",
"uid64",
")",
"\n",
"gid",
"=",
"int",
"(",
"gid64",
")",
"\n\n",
"return",
"\n",
"}"
] |
// MyUserAndGroup returns the UID and GID of this process.
|
[
"MyUserAndGroup",
"returns",
"the",
"UID",
"and",
"GID",
"of",
"this",
"process",
"."
] |
224a69530a8fefa8f07e51582b928739127134f2
|
https://github.com/kahing/goofys/blob/224a69530a8fefa8f07e51582b928739127134f2/internal/perms.go#L25-L50
|
train
|
kahing/goofys
|
internal/buffer_pool.go
|
Seek
|
func (mb *MBuf) Seek(offset int64, whence int) (int64, error) {
switch whence {
case 0: // relative to beginning
if offset == 0 {
mb.rbuf = 0
mb.rp = 0
return 0, nil
}
case 1: // relative to current position
if offset == 0 {
for i := 0; i < mb.rbuf; i++ {
offset += int64(len(mb.buffers[i]))
}
offset += int64(mb.rp)
return offset, nil
}
case 2: // relative to the end
if offset == 0 {
for i := 0; i < len(mb.buffers); i++ {
offset += int64(len(mb.buffers[i]))
}
mb.rbuf = len(mb.buffers)
mb.rp = 0
return offset, nil
}
}
log.Errorf("Seek %d %d", offset, whence)
panic(fuse.EINVAL)
return 0, fuse.EINVAL
}
|
go
|
func (mb *MBuf) Seek(offset int64, whence int) (int64, error) {
switch whence {
case 0: // relative to beginning
if offset == 0 {
mb.rbuf = 0
mb.rp = 0
return 0, nil
}
case 1: // relative to current position
if offset == 0 {
for i := 0; i < mb.rbuf; i++ {
offset += int64(len(mb.buffers[i]))
}
offset += int64(mb.rp)
return offset, nil
}
case 2: // relative to the end
if offset == 0 {
for i := 0; i < len(mb.buffers); i++ {
offset += int64(len(mb.buffers[i]))
}
mb.rbuf = len(mb.buffers)
mb.rp = 0
return offset, nil
}
}
log.Errorf("Seek %d %d", offset, whence)
panic(fuse.EINVAL)
return 0, fuse.EINVAL
}
|
[
"func",
"(",
"mb",
"*",
"MBuf",
")",
"Seek",
"(",
"offset",
"int64",
",",
"whence",
"int",
")",
"(",
"int64",
",",
"error",
")",
"{",
"switch",
"whence",
"{",
"case",
"0",
":",
"// relative to beginning",
"if",
"offset",
"==",
"0",
"{",
"mb",
".",
"rbuf",
"=",
"0",
"\n",
"mb",
".",
"rp",
"=",
"0",
"\n",
"return",
"0",
",",
"nil",
"\n",
"}",
"\n",
"case",
"1",
":",
"// relative to current position",
"if",
"offset",
"==",
"0",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"mb",
".",
"rbuf",
";",
"i",
"++",
"{",
"offset",
"+=",
"int64",
"(",
"len",
"(",
"mb",
".",
"buffers",
"[",
"i",
"]",
")",
")",
"\n",
"}",
"\n",
"offset",
"+=",
"int64",
"(",
"mb",
".",
"rp",
")",
"\n",
"return",
"offset",
",",
"nil",
"\n",
"}",
"\n\n",
"case",
"2",
":",
"// relative to the end",
"if",
"offset",
"==",
"0",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"mb",
".",
"buffers",
")",
";",
"i",
"++",
"{",
"offset",
"+=",
"int64",
"(",
"len",
"(",
"mb",
".",
"buffers",
"[",
"i",
"]",
")",
")",
"\n",
"}",
"\n",
"mb",
".",
"rbuf",
"=",
"len",
"(",
"mb",
".",
"buffers",
")",
"\n",
"mb",
".",
"rp",
"=",
"0",
"\n",
"return",
"offset",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"offset",
",",
"whence",
")",
"\n",
"panic",
"(",
"fuse",
".",
"EINVAL",
")",
"\n\n",
"return",
"0",
",",
"fuse",
".",
"EINVAL",
"\n",
"}"
] |
// seek only seeks the reader
|
[
"seek",
"only",
"seeks",
"the",
"reader"
] |
224a69530a8fefa8f07e51582b928739127134f2
|
https://github.com/kahing/goofys/blob/224a69530a8fefa8f07e51582b928739127134f2/internal/buffer_pool.go#L210-L242
|
train
|
cloudflare/cloudflare-go
|
duration.go
|
UnmarshalJSON
|
func (d *Duration) UnmarshalJSON(buf []byte) error {
var str string
err := json.Unmarshal(buf, &str)
if err != nil {
return err
}
dur, err := time.ParseDuration(str)
if err != nil {
return err
}
d.Duration = dur
return nil
}
|
go
|
func (d *Duration) UnmarshalJSON(buf []byte) error {
var str string
err := json.Unmarshal(buf, &str)
if err != nil {
return err
}
dur, err := time.ParseDuration(str)
if err != nil {
return err
}
d.Duration = dur
return nil
}
|
[
"func",
"(",
"d",
"*",
"Duration",
")",
"UnmarshalJSON",
"(",
"buf",
"[",
"]",
"byte",
")",
"error",
"{",
"var",
"str",
"string",
"\n\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"buf",
",",
"&",
"str",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"dur",
",",
"err",
":=",
"time",
".",
"ParseDuration",
"(",
"str",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"d",
".",
"Duration",
"=",
"dur",
"\n",
"return",
"nil",
"\n",
"}"
] |
// UnmarshalJSON decodes a Duration from a JSON string parsed using time.ParseDuration.
|
[
"UnmarshalJSON",
"decodes",
"a",
"Duration",
"from",
"a",
"JSON",
"string",
"parsed",
"using",
"time",
".",
"ParseDuration",
"."
] |
024278eb1b129df5cf9fdaf301c08b99283e81bc
|
https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/duration.go#L20-L35
|
train
|
cloudflare/cloudflare-go
|
cmd/flarectl/misc.go
|
writeTable
|
func writeTable(data [][]string, cols ...string) {
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader(cols)
table.SetBorder(false)
table.AppendBulk(data)
table.Render()
}
|
go
|
func writeTable(data [][]string, cols ...string) {
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader(cols)
table.SetBorder(false)
table.AppendBulk(data)
table.Render()
}
|
[
"func",
"writeTable",
"(",
"data",
"[",
"]",
"[",
"]",
"string",
",",
"cols",
"...",
"string",
")",
"{",
"table",
":=",
"tablewriter",
".",
"NewWriter",
"(",
"os",
".",
"Stdout",
")",
"\n",
"table",
".",
"SetHeader",
"(",
"cols",
")",
"\n",
"table",
".",
"SetBorder",
"(",
"false",
")",
"\n",
"table",
".",
"AppendBulk",
"(",
"data",
")",
"\n\n",
"table",
".",
"Render",
"(",
")",
"\n",
"}"
] |
// writeTable outputs tabular data to stdout.
|
[
"writeTable",
"outputs",
"tabular",
"data",
"to",
"stdout",
"."
] |
024278eb1b129df5cf9fdaf301c08b99283e81bc
|
https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/cmd/flarectl/misc.go#L16-L23
|
train
|
cloudflare/cloudflare-go
|
cmd/flarectl/misc.go
|
checkFlags
|
func checkFlags(c *cli.Context, flags ...string) error {
for _, flag := range flags {
if c.String(flag) == "" {
cli.ShowSubcommandHelp(c)
err := errors.Errorf("error: the required flag %q was empty or not provided", flag)
fmt.Fprintln(os.Stderr, err)
return err
}
}
return nil
}
|
go
|
func checkFlags(c *cli.Context, flags ...string) error {
for _, flag := range flags {
if c.String(flag) == "" {
cli.ShowSubcommandHelp(c)
err := errors.Errorf("error: the required flag %q was empty or not provided", flag)
fmt.Fprintln(os.Stderr, err)
return err
}
}
return nil
}
|
[
"func",
"checkFlags",
"(",
"c",
"*",
"cli",
".",
"Context",
",",
"flags",
"...",
"string",
")",
"error",
"{",
"for",
"_",
",",
"flag",
":=",
"range",
"flags",
"{",
"if",
"c",
".",
"String",
"(",
"flag",
")",
"==",
"\"",
"\"",
"{",
"cli",
".",
"ShowSubcommandHelp",
"(",
"c",
")",
"\n",
"err",
":=",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"flag",
")",
"\n",
"fmt",
".",
"Fprintln",
"(",
"os",
".",
"Stderr",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Utility function to check if CLI flags were given.
|
[
"Utility",
"function",
"to",
"check",
"if",
"CLI",
"flags",
"were",
"given",
"."
] |
024278eb1b129df5cf9fdaf301c08b99283e81bc
|
https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/cmd/flarectl/misc.go#L45-L56
|
train
|
cloudflare/cloudflare-go
|
cmd/flarectl/misc.go
|
_getIps
|
func _getIps(ipType string, showMsgType bool) {
ips, _ := cloudflare.IPs()
switch ipType {
case "ipv4":
if showMsgType != true {
fmt.Println("IPv4 ranges:")
}
for _, r := range ips.IPv4CIDRs {
fmt.Println(" ", r)
}
case "ipv6":
if showMsgType != true {
fmt.Println("IPv6 ranges:")
}
for _, r := range ips.IPv6CIDRs {
fmt.Println(" ", r)
}
}
}
|
go
|
func _getIps(ipType string, showMsgType bool) {
ips, _ := cloudflare.IPs()
switch ipType {
case "ipv4":
if showMsgType != true {
fmt.Println("IPv4 ranges:")
}
for _, r := range ips.IPv4CIDRs {
fmt.Println(" ", r)
}
case "ipv6":
if showMsgType != true {
fmt.Println("IPv6 ranges:")
}
for _, r := range ips.IPv6CIDRs {
fmt.Println(" ", r)
}
}
}
|
[
"func",
"_getIps",
"(",
"ipType",
"string",
",",
"showMsgType",
"bool",
")",
"{",
"ips",
",",
"_",
":=",
"cloudflare",
".",
"IPs",
"(",
")",
"\n\n",
"switch",
"ipType",
"{",
"case",
"\"",
"\"",
":",
"if",
"showMsgType",
"!=",
"true",
"{",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"ips",
".",
"IPv4CIDRs",
"{",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
",",
"r",
")",
"\n",
"}",
"\n",
"case",
"\"",
"\"",
":",
"if",
"showMsgType",
"!=",
"true",
"{",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"ips",
".",
"IPv6CIDRs",
"{",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
",",
"r",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
//
// gets type of IPs to retrieve and returns results
//
|
[
"gets",
"type",
"of",
"IPs",
"to",
"retrieve",
"and",
"returns",
"results"
] |
024278eb1b129df5cf9fdaf301c08b99283e81bc
|
https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/cmd/flarectl/misc.go#L71-L90
|
train
|
cloudflare/cloudflare-go
|
auditlogs.go
|
String
|
func (a AuditLogFilter) String() string {
params := "?"
if a.ID != "" {
params += "&id=" + a.ID
}
if a.ActorIP != "" {
params += "&actor.ip=" + a.ActorIP
}
if a.ActorEmail != "" {
params += "&actor.email=" + a.ActorEmail
}
if a.ZoneName != "" {
params += "&zone.name=" + a.ZoneName
}
if a.Direction != "" {
params += "&direction=" + a.Direction
}
if a.Since != "" {
params += "&since=" + a.Since
}
if a.Before != "" {
params += "&before=" + a.Before
}
if a.PerPage > 0 {
params += "&per_page=" + fmt.Sprintf("%d", a.PerPage)
}
if a.Page > 0 {
params += "&page=" + fmt.Sprintf("%d", a.Page)
}
return params
}
|
go
|
func (a AuditLogFilter) String() string {
params := "?"
if a.ID != "" {
params += "&id=" + a.ID
}
if a.ActorIP != "" {
params += "&actor.ip=" + a.ActorIP
}
if a.ActorEmail != "" {
params += "&actor.email=" + a.ActorEmail
}
if a.ZoneName != "" {
params += "&zone.name=" + a.ZoneName
}
if a.Direction != "" {
params += "&direction=" + a.Direction
}
if a.Since != "" {
params += "&since=" + a.Since
}
if a.Before != "" {
params += "&before=" + a.Before
}
if a.PerPage > 0 {
params += "&per_page=" + fmt.Sprintf("%d", a.PerPage)
}
if a.Page > 0 {
params += "&page=" + fmt.Sprintf("%d", a.Page)
}
return params
}
|
[
"func",
"(",
"a",
"AuditLogFilter",
")",
"String",
"(",
")",
"string",
"{",
"params",
":=",
"\"",
"\"",
"\n",
"if",
"a",
".",
"ID",
"!=",
"\"",
"\"",
"{",
"params",
"+=",
"\"",
"\"",
"+",
"a",
".",
"ID",
"\n",
"}",
"\n",
"if",
"a",
".",
"ActorIP",
"!=",
"\"",
"\"",
"{",
"params",
"+=",
"\"",
"\"",
"+",
"a",
".",
"ActorIP",
"\n",
"}",
"\n",
"if",
"a",
".",
"ActorEmail",
"!=",
"\"",
"\"",
"{",
"params",
"+=",
"\"",
"\"",
"+",
"a",
".",
"ActorEmail",
"\n",
"}",
"\n",
"if",
"a",
".",
"ZoneName",
"!=",
"\"",
"\"",
"{",
"params",
"+=",
"\"",
"\"",
"+",
"a",
".",
"ZoneName",
"\n",
"}",
"\n",
"if",
"a",
".",
"Direction",
"!=",
"\"",
"\"",
"{",
"params",
"+=",
"\"",
"\"",
"+",
"a",
".",
"Direction",
"\n",
"}",
"\n",
"if",
"a",
".",
"Since",
"!=",
"\"",
"\"",
"{",
"params",
"+=",
"\"",
"\"",
"+",
"a",
".",
"Since",
"\n",
"}",
"\n",
"if",
"a",
".",
"Before",
"!=",
"\"",
"\"",
"{",
"params",
"+=",
"\"",
"\"",
"+",
"a",
".",
"Before",
"\n",
"}",
"\n",
"if",
"a",
".",
"PerPage",
">",
"0",
"{",
"params",
"+=",
"\"",
"\"",
"+",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"a",
".",
"PerPage",
")",
"\n",
"}",
"\n",
"if",
"a",
".",
"Page",
">",
"0",
"{",
"params",
"+=",
"\"",
"\"",
"+",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"a",
".",
"Page",
")",
"\n",
"}",
"\n",
"return",
"params",
"\n",
"}"
] |
// String turns an audit log filter in to an HTTP Query Param
// list. It will not inclue empty members of the struct in the
// query parameters.
|
[
"String",
"turns",
"an",
"audit",
"log",
"filter",
"in",
"to",
"an",
"HTTP",
"Query",
"Param",
"list",
".",
"It",
"will",
"not",
"inclue",
"empty",
"members",
"of",
"the",
"struct",
"in",
"the",
"query",
"parameters",
"."
] |
024278eb1b129df5cf9fdaf301c08b99283e81bc
|
https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/auditlogs.go#L71-L101
|
train
|
cloudflare/cloudflare-go
|
auditlogs.go
|
unmarshalReturn
|
func unmarshalReturn(res []byte) (AuditLogResponse, error) {
var auditResponse AuditLogResponse
err := json.Unmarshal(res, &auditResponse)
if err != nil {
return auditResponse, err
}
return auditResponse, nil
}
|
go
|
func unmarshalReturn(res []byte) (AuditLogResponse, error) {
var auditResponse AuditLogResponse
err := json.Unmarshal(res, &auditResponse)
if err != nil {
return auditResponse, err
}
return auditResponse, nil
}
|
[
"func",
"unmarshalReturn",
"(",
"res",
"[",
"]",
"byte",
")",
"(",
"AuditLogResponse",
",",
"error",
")",
"{",
"var",
"auditResponse",
"AuditLogResponse",
"\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"res",
",",
"&",
"auditResponse",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"auditResponse",
",",
"err",
"\n",
"}",
"\n",
"return",
"auditResponse",
",",
"nil",
"\n",
"}"
] |
// unmarshalReturn will unmarshal bytes and return an auditlogresponse
|
[
"unmarshalReturn",
"will",
"unmarshal",
"bytes",
"and",
"return",
"an",
"auditlogresponse"
] |
024278eb1b129df5cf9fdaf301c08b99283e81bc
|
https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/auditlogs.go#L123-L130
|
train
|
cloudflare/cloudflare-go
|
zone.go
|
ListZonesContext
|
func (api *API) ListZonesContext(ctx context.Context, opts ...ReqOption) (r ZonesResponse, err error) {
var res []byte
opt := reqOption{
params: url.Values{},
}
for _, of := range opts {
of(&opt)
}
res, err = api.makeRequestContext(ctx, "GET", "/zones?"+opt.params.Encode(), nil)
if err != nil {
return ZonesResponse{}, errors.Wrap(err, errMakeRequestError)
}
err = json.Unmarshal(res, &r)
if err != nil {
return ZonesResponse{}, errors.Wrap(err, errUnmarshalError)
}
return r, nil
}
|
go
|
func (api *API) ListZonesContext(ctx context.Context, opts ...ReqOption) (r ZonesResponse, err error) {
var res []byte
opt := reqOption{
params: url.Values{},
}
for _, of := range opts {
of(&opt)
}
res, err = api.makeRequestContext(ctx, "GET", "/zones?"+opt.params.Encode(), nil)
if err != nil {
return ZonesResponse{}, errors.Wrap(err, errMakeRequestError)
}
err = json.Unmarshal(res, &r)
if err != nil {
return ZonesResponse{}, errors.Wrap(err, errUnmarshalError)
}
return r, nil
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"ListZonesContext",
"(",
"ctx",
"context",
".",
"Context",
",",
"opts",
"...",
"ReqOption",
")",
"(",
"r",
"ZonesResponse",
",",
"err",
"error",
")",
"{",
"var",
"res",
"[",
"]",
"byte",
"\n",
"opt",
":=",
"reqOption",
"{",
"params",
":",
"url",
".",
"Values",
"{",
"}",
",",
"}",
"\n",
"for",
"_",
",",
"of",
":=",
"range",
"opts",
"{",
"of",
"(",
"&",
"opt",
")",
"\n",
"}",
"\n\n",
"res",
",",
"err",
"=",
"api",
".",
"makeRequestContext",
"(",
"ctx",
",",
"\"",
"\"",
",",
"\"",
"\"",
"+",
"opt",
".",
"params",
".",
"Encode",
"(",
")",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"ZonesResponse",
"{",
"}",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"errMakeRequestError",
")",
"\n",
"}",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"res",
",",
"&",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"ZonesResponse",
"{",
"}",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"errUnmarshalError",
")",
"\n",
"}",
"\n\n",
"return",
"r",
",",
"nil",
"\n",
"}"
] |
// ListZonesContext lists zones on an account. Optionally takes a list of ReqOptions.
|
[
"ListZonesContext",
"lists",
"zones",
"on",
"an",
"account",
".",
"Optionally",
"takes",
"a",
"list",
"of",
"ReqOptions",
"."
] |
024278eb1b129df5cf9fdaf301c08b99283e81bc
|
https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/zone.go#L401-L420
|
train
|
cloudflare/cloudflare-go
|
zone.go
|
ZoneSetPaused
|
func (api *API) ZoneSetPaused(zoneID string, paused bool) (Zone, error) {
zoneopts := ZoneOptions{Paused: &paused}
zone, err := api.EditZone(zoneID, zoneopts)
if err != nil {
return Zone{}, err
}
return zone, nil
}
|
go
|
func (api *API) ZoneSetPaused(zoneID string, paused bool) (Zone, error) {
zoneopts := ZoneOptions{Paused: &paused}
zone, err := api.EditZone(zoneID, zoneopts)
if err != nil {
return Zone{}, err
}
return zone, nil
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"ZoneSetPaused",
"(",
"zoneID",
"string",
",",
"paused",
"bool",
")",
"(",
"Zone",
",",
"error",
")",
"{",
"zoneopts",
":=",
"ZoneOptions",
"{",
"Paused",
":",
"&",
"paused",
"}",
"\n",
"zone",
",",
"err",
":=",
"api",
".",
"EditZone",
"(",
"zoneID",
",",
"zoneopts",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"Zone",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"zone",
",",
"nil",
"\n",
"}"
] |
// ZoneSetPaused pauses Cloudflare service for the entire zone, sending all
// traffic direct to the origin.
|
[
"ZoneSetPaused",
"pauses",
"Cloudflare",
"service",
"for",
"the",
"entire",
"zone",
"sending",
"all",
"traffic",
"direct",
"to",
"the",
"origin",
"."
] |
024278eb1b129df5cf9fdaf301c08b99283e81bc
|
https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/zone.go#L447-L455
|
train
|
cloudflare/cloudflare-go
|
zone.go
|
ZoneSetVanityNS
|
func (api *API) ZoneSetVanityNS(zoneID string, ns []string) (Zone, error) {
zoneopts := ZoneOptions{VanityNS: ns}
zone, err := api.EditZone(zoneID, zoneopts)
if err != nil {
return Zone{}, err
}
return zone, nil
}
|
go
|
func (api *API) ZoneSetVanityNS(zoneID string, ns []string) (Zone, error) {
zoneopts := ZoneOptions{VanityNS: ns}
zone, err := api.EditZone(zoneID, zoneopts)
if err != nil {
return Zone{}, err
}
return zone, nil
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"ZoneSetVanityNS",
"(",
"zoneID",
"string",
",",
"ns",
"[",
"]",
"string",
")",
"(",
"Zone",
",",
"error",
")",
"{",
"zoneopts",
":=",
"ZoneOptions",
"{",
"VanityNS",
":",
"ns",
"}",
"\n",
"zone",
",",
"err",
":=",
"api",
".",
"EditZone",
"(",
"zoneID",
",",
"zoneopts",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"Zone",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"zone",
",",
"nil",
"\n",
"}"
] |
// ZoneSetVanityNS sets custom nameservers for the zone.
// These names must be within the same zone.
|
[
"ZoneSetVanityNS",
"sets",
"custom",
"nameservers",
"for",
"the",
"zone",
".",
"These",
"names",
"must",
"be",
"within",
"the",
"same",
"zone",
"."
] |
024278eb1b129df5cf9fdaf301c08b99283e81bc
|
https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/zone.go#L459-L467
|
train
|
cloudflare/cloudflare-go
|
zone.go
|
ZoneSetPlan
|
func (api *API) ZoneSetPlan(zoneID string, plan ZonePlan) (Zone, error) {
zoneopts := ZoneOptions{Plan: &plan}
zone, err := api.EditZone(zoneID, zoneopts)
if err != nil {
return Zone{}, err
}
return zone, nil
}
|
go
|
func (api *API) ZoneSetPlan(zoneID string, plan ZonePlan) (Zone, error) {
zoneopts := ZoneOptions{Plan: &plan}
zone, err := api.EditZone(zoneID, zoneopts)
if err != nil {
return Zone{}, err
}
return zone, nil
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"ZoneSetPlan",
"(",
"zoneID",
"string",
",",
"plan",
"ZonePlan",
")",
"(",
"Zone",
",",
"error",
")",
"{",
"zoneopts",
":=",
"ZoneOptions",
"{",
"Plan",
":",
"&",
"plan",
"}",
"\n",
"zone",
",",
"err",
":=",
"api",
".",
"EditZone",
"(",
"zoneID",
",",
"zoneopts",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"Zone",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"zone",
",",
"nil",
"\n",
"}"
] |
// ZoneSetPlan changes the zone plan.
|
[
"ZoneSetPlan",
"changes",
"the",
"zone",
"plan",
"."
] |
024278eb1b129df5cf9fdaf301c08b99283e81bc
|
https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/zone.go#L470-L478
|
train
|
cloudflare/cloudflare-go
|
options.go
|
UsingRateLimit
|
func UsingRateLimit(rps float64) Option {
return func(api *API) error {
// because ratelimiter doesnt do any windowing
// setting burst makes it difficult to enforce a fixed rate
// so setting it equal to 1 this effectively disables bursting
// this doesn't check for sensible values, ultimately the api will enforce that the value is ok
api.rateLimiter = rate.NewLimiter(rate.Limit(rps), 1)
return nil
}
}
|
go
|
func UsingRateLimit(rps float64) Option {
return func(api *API) error {
// because ratelimiter doesnt do any windowing
// setting burst makes it difficult to enforce a fixed rate
// so setting it equal to 1 this effectively disables bursting
// this doesn't check for sensible values, ultimately the api will enforce that the value is ok
api.rateLimiter = rate.NewLimiter(rate.Limit(rps), 1)
return nil
}
}
|
[
"func",
"UsingRateLimit",
"(",
"rps",
"float64",
")",
"Option",
"{",
"return",
"func",
"(",
"api",
"*",
"API",
")",
"error",
"{",
"// because ratelimiter doesnt do any windowing",
"// setting burst makes it difficult to enforce a fixed rate",
"// so setting it equal to 1 this effectively disables bursting",
"// this doesn't check for sensible values, ultimately the api will enforce that the value is ok",
"api",
".",
"rateLimiter",
"=",
"rate",
".",
"NewLimiter",
"(",
"rate",
".",
"Limit",
"(",
"rps",
")",
",",
"1",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] |
// UsingRateLimit applies a non-default rate limit to client API requests
// If not specified the default of 4rps will be applied
|
[
"UsingRateLimit",
"applies",
"a",
"non",
"-",
"default",
"rate",
"limit",
"to",
"client",
"API",
"requests",
"If",
"not",
"specified",
"the",
"default",
"of",
"4rps",
"will",
"be",
"applied"
] |
024278eb1b129df5cf9fdaf301c08b99283e81bc
|
https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/options.go#L42-L51
|
train
|
cloudflare/cloudflare-go
|
options.go
|
UsingLogger
|
func UsingLogger(logger Logger) Option {
return func(api *API) error {
api.logger = logger
return nil
}
}
|
go
|
func UsingLogger(logger Logger) Option {
return func(api *API) error {
api.logger = logger
return nil
}
}
|
[
"func",
"UsingLogger",
"(",
"logger",
"Logger",
")",
"Option",
"{",
"return",
"func",
"(",
"api",
"*",
"API",
")",
"error",
"{",
"api",
".",
"logger",
"=",
"logger",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] |
// UsingLogger can be set if you want to get log output from this API instance
// By default no log output is emitted
|
[
"UsingLogger",
"can",
"be",
"set",
"if",
"you",
"want",
"to",
"get",
"log",
"output",
"from",
"this",
"API",
"instance",
"By",
"default",
"no",
"log",
"output",
"is",
"emitted"
] |
024278eb1b129df5cf9fdaf301c08b99283e81bc
|
https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/options.go#L69-L74
|
train
|
cloudflare/cloudflare-go
|
virtualdns.go
|
VirtualDNSUserAnalytics
|
func (api *API) VirtualDNSUserAnalytics(virtualDNSID string, o VirtualDNSUserAnalyticsOptions) (VirtualDNSAnalytics, error) {
uri := "/user/virtual_dns/" + virtualDNSID + "/dns_analytics/report?" + o.encode()
res, err := api.makeRequest("GET", uri, nil)
if err != nil {
return VirtualDNSAnalytics{}, errors.Wrap(err, errMakeRequestError)
}
response := VirtualDNSAnalyticsResponse{}
err = json.Unmarshal(res, &response)
if err != nil {
return VirtualDNSAnalytics{}, errors.Wrap(err, errUnmarshalError)
}
return response.Result, nil
}
|
go
|
func (api *API) VirtualDNSUserAnalytics(virtualDNSID string, o VirtualDNSUserAnalyticsOptions) (VirtualDNSAnalytics, error) {
uri := "/user/virtual_dns/" + virtualDNSID + "/dns_analytics/report?" + o.encode()
res, err := api.makeRequest("GET", uri, nil)
if err != nil {
return VirtualDNSAnalytics{}, errors.Wrap(err, errMakeRequestError)
}
response := VirtualDNSAnalyticsResponse{}
err = json.Unmarshal(res, &response)
if err != nil {
return VirtualDNSAnalytics{}, errors.Wrap(err, errUnmarshalError)
}
return response.Result, nil
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"VirtualDNSUserAnalytics",
"(",
"virtualDNSID",
"string",
",",
"o",
"VirtualDNSUserAnalyticsOptions",
")",
"(",
"VirtualDNSAnalytics",
",",
"error",
")",
"{",
"uri",
":=",
"\"",
"\"",
"+",
"virtualDNSID",
"+",
"\"",
"\"",
"+",
"o",
".",
"encode",
"(",
")",
"\n",
"res",
",",
"err",
":=",
"api",
".",
"makeRequest",
"(",
"\"",
"\"",
",",
"uri",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"VirtualDNSAnalytics",
"{",
"}",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"errMakeRequestError",
")",
"\n",
"}",
"\n\n",
"response",
":=",
"VirtualDNSAnalyticsResponse",
"{",
"}",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"res",
",",
"&",
"response",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"VirtualDNSAnalytics",
"{",
"}",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"errUnmarshalError",
")",
"\n",
"}",
"\n\n",
"return",
"response",
".",
"Result",
",",
"nil",
"\n",
"}"
] |
// VirtualDNSUserAnalytics retrieves analytics report for a specified dimension and time range
|
[
"VirtualDNSUserAnalytics",
"retrieves",
"analytics",
"report",
"for",
"a",
"specified",
"dimension",
"and",
"time",
"range"
] |
024278eb1b129df5cf9fdaf301c08b99283e81bc
|
https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/virtualdns.go#L178-L192
|
train
|
cloudflare/cloudflare-go
|
custom_hostname.go
|
CustomHostnameIDByName
|
func (api *API) CustomHostnameIDByName(zoneID string, hostname string) (string, error) {
customHostnames, _, err := api.CustomHostnames(zoneID, 1, CustomHostname{Hostname: hostname})
if err != nil {
return "", errors.Wrap(err, "CustomHostnames command failed")
}
for _, ch := range customHostnames {
if ch.Hostname == hostname {
return ch.ID, nil
}
}
return "", errors.New("CustomHostname could not be found")
}
|
go
|
func (api *API) CustomHostnameIDByName(zoneID string, hostname string) (string, error) {
customHostnames, _, err := api.CustomHostnames(zoneID, 1, CustomHostname{Hostname: hostname})
if err != nil {
return "", errors.Wrap(err, "CustomHostnames command failed")
}
for _, ch := range customHostnames {
if ch.Hostname == hostname {
return ch.ID, nil
}
}
return "", errors.New("CustomHostname could not be found")
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"CustomHostnameIDByName",
"(",
"zoneID",
"string",
",",
"hostname",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"customHostnames",
",",
"_",
",",
"err",
":=",
"api",
".",
"CustomHostnames",
"(",
"zoneID",
",",
"1",
",",
"CustomHostname",
"{",
"Hostname",
":",
"hostname",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"ch",
":=",
"range",
"customHostnames",
"{",
"if",
"ch",
".",
"Hostname",
"==",
"hostname",
"{",
"return",
"ch",
".",
"ID",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}"
] |
// CustomHostnameIDByName retrieves the ID for the given hostname in the given zone.
|
[
"CustomHostnameIDByName",
"retrieves",
"the",
"ID",
"for",
"the",
"given",
"hostname",
"in",
"the",
"given",
"zone",
"."
] |
024278eb1b129df5cf9fdaf301c08b99283e81bc
|
https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/custom_hostname.go#L149-L160
|
train
|
cloudflare/cloudflare-go
|
cloudflare.go
|
newClient
|
func newClient(opts ...Option) (*API, error) {
silentLogger := log.New(ioutil.Discard, "", log.LstdFlags)
api := &API{
BaseURL: apiURL,
headers: make(http.Header),
rateLimiter: rate.NewLimiter(rate.Limit(4), 1), // 4rps equates to default api limit (1200 req/5 min)
retryPolicy: RetryPolicy{
MaxRetries: 3,
MinRetryDelay: time.Duration(1) * time.Second,
MaxRetryDelay: time.Duration(30) * time.Second,
},
logger: silentLogger,
}
err := api.parseOptions(opts...)
if err != nil {
return nil, errors.Wrap(err, "options parsing failed")
}
// Fall back to http.DefaultClient if the package user does not provide
// their own.
if api.httpClient == nil {
api.httpClient = http.DefaultClient
}
return api, nil
}
|
go
|
func newClient(opts ...Option) (*API, error) {
silentLogger := log.New(ioutil.Discard, "", log.LstdFlags)
api := &API{
BaseURL: apiURL,
headers: make(http.Header),
rateLimiter: rate.NewLimiter(rate.Limit(4), 1), // 4rps equates to default api limit (1200 req/5 min)
retryPolicy: RetryPolicy{
MaxRetries: 3,
MinRetryDelay: time.Duration(1) * time.Second,
MaxRetryDelay: time.Duration(30) * time.Second,
},
logger: silentLogger,
}
err := api.parseOptions(opts...)
if err != nil {
return nil, errors.Wrap(err, "options parsing failed")
}
// Fall back to http.DefaultClient if the package user does not provide
// their own.
if api.httpClient == nil {
api.httpClient = http.DefaultClient
}
return api, nil
}
|
[
"func",
"newClient",
"(",
"opts",
"...",
"Option",
")",
"(",
"*",
"API",
",",
"error",
")",
"{",
"silentLogger",
":=",
"log",
".",
"New",
"(",
"ioutil",
".",
"Discard",
",",
"\"",
"\"",
",",
"log",
".",
"LstdFlags",
")",
"\n\n",
"api",
":=",
"&",
"API",
"{",
"BaseURL",
":",
"apiURL",
",",
"headers",
":",
"make",
"(",
"http",
".",
"Header",
")",
",",
"rateLimiter",
":",
"rate",
".",
"NewLimiter",
"(",
"rate",
".",
"Limit",
"(",
"4",
")",
",",
"1",
")",
",",
"// 4rps equates to default api limit (1200 req/5 min)",
"retryPolicy",
":",
"RetryPolicy",
"{",
"MaxRetries",
":",
"3",
",",
"MinRetryDelay",
":",
"time",
".",
"Duration",
"(",
"1",
")",
"*",
"time",
".",
"Second",
",",
"MaxRetryDelay",
":",
"time",
".",
"Duration",
"(",
"30",
")",
"*",
"time",
".",
"Second",
",",
"}",
",",
"logger",
":",
"silentLogger",
",",
"}",
"\n\n",
"err",
":=",
"api",
".",
"parseOptions",
"(",
"opts",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Fall back to http.DefaultClient if the package user does not provide",
"// their own.",
"if",
"api",
".",
"httpClient",
"==",
"nil",
"{",
"api",
".",
"httpClient",
"=",
"http",
".",
"DefaultClient",
"\n",
"}",
"\n\n",
"return",
"api",
",",
"nil",
"\n",
"}"
] |
// newClient provides shared logic for New and NewWithUserServiceKey
|
[
"newClient",
"provides",
"shared",
"logic",
"for",
"New",
"and",
"NewWithUserServiceKey"
] |
024278eb1b129df5cf9fdaf301c08b99283e81bc
|
https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/cloudflare.go#L48-L75
|
train
|
cloudflare/cloudflare-go
|
cloudflare.go
|
New
|
func New(key, email string, opts ...Option) (*API, error) {
if key == "" || email == "" {
return nil, errors.New(errEmptyCredentials)
}
api, err := newClient(opts...)
if err != nil {
return nil, err
}
api.APIKey = key
api.APIEmail = email
api.authType = AuthKeyEmail
return api, nil
}
|
go
|
func New(key, email string, opts ...Option) (*API, error) {
if key == "" || email == "" {
return nil, errors.New(errEmptyCredentials)
}
api, err := newClient(opts...)
if err != nil {
return nil, err
}
api.APIKey = key
api.APIEmail = email
api.authType = AuthKeyEmail
return api, nil
}
|
[
"func",
"New",
"(",
"key",
",",
"email",
"string",
",",
"opts",
"...",
"Option",
")",
"(",
"*",
"API",
",",
"error",
")",
"{",
"if",
"key",
"==",
"\"",
"\"",
"||",
"email",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"errEmptyCredentials",
")",
"\n",
"}",
"\n\n",
"api",
",",
"err",
":=",
"newClient",
"(",
"opts",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"api",
".",
"APIKey",
"=",
"key",
"\n",
"api",
".",
"APIEmail",
"=",
"email",
"\n",
"api",
".",
"authType",
"=",
"AuthKeyEmail",
"\n\n",
"return",
"api",
",",
"nil",
"\n",
"}"
] |
// New creates a new Cloudflare v4 API client.
|
[
"New",
"creates",
"a",
"new",
"Cloudflare",
"v4",
"API",
"client",
"."
] |
024278eb1b129df5cf9fdaf301c08b99283e81bc
|
https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/cloudflare.go#L78-L93
|
train
|
cloudflare/cloudflare-go
|
cloudflare.go
|
NewWithUserServiceKey
|
func NewWithUserServiceKey(key string, opts ...Option) (*API, error) {
if key == "" {
return nil, errors.New(errEmptyCredentials)
}
api, err := newClient(opts...)
if err != nil {
return nil, err
}
api.APIUserServiceKey = key
api.authType = AuthUserService
return api, nil
}
|
go
|
func NewWithUserServiceKey(key string, opts ...Option) (*API, error) {
if key == "" {
return nil, errors.New(errEmptyCredentials)
}
api, err := newClient(opts...)
if err != nil {
return nil, err
}
api.APIUserServiceKey = key
api.authType = AuthUserService
return api, nil
}
|
[
"func",
"NewWithUserServiceKey",
"(",
"key",
"string",
",",
"opts",
"...",
"Option",
")",
"(",
"*",
"API",
",",
"error",
")",
"{",
"if",
"key",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"errEmptyCredentials",
")",
"\n",
"}",
"\n\n",
"api",
",",
"err",
":=",
"newClient",
"(",
"opts",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"api",
".",
"APIUserServiceKey",
"=",
"key",
"\n",
"api",
".",
"authType",
"=",
"AuthUserService",
"\n\n",
"return",
"api",
",",
"nil",
"\n",
"}"
] |
// NewWithUserServiceKey creates a new Cloudflare v4 API client using service key authentication.
|
[
"NewWithUserServiceKey",
"creates",
"a",
"new",
"Cloudflare",
"v4",
"API",
"client",
"using",
"service",
"key",
"authentication",
"."
] |
024278eb1b129df5cf9fdaf301c08b99283e81bc
|
https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/cloudflare.go#L96-L110
|
train
|
cloudflare/cloudflare-go
|
cloudflare.go
|
ZoneIDByName
|
func (api *API) ZoneIDByName(zoneName string) (string, error) {
res, err := api.ListZonesContext(context.TODO(), WithZoneFilter(zoneName))
if err != nil {
return "", errors.Wrap(err, "ListZonesContext command failed")
}
if len(res.Result) > 1 && api.OrganizationID == "" {
return "", errors.New("ambiguous zone name used without an account ID")
}
for _, zone := range res.Result {
if api.OrganizationID != "" {
if zone.Name == zoneName && api.OrganizationID == zone.Account.ID {
return zone.ID, nil
}
} else {
if zone.Name == zoneName {
return zone.ID, nil
}
}
}
return "", errors.New("Zone could not be found")
}
|
go
|
func (api *API) ZoneIDByName(zoneName string) (string, error) {
res, err := api.ListZonesContext(context.TODO(), WithZoneFilter(zoneName))
if err != nil {
return "", errors.Wrap(err, "ListZonesContext command failed")
}
if len(res.Result) > 1 && api.OrganizationID == "" {
return "", errors.New("ambiguous zone name used without an account ID")
}
for _, zone := range res.Result {
if api.OrganizationID != "" {
if zone.Name == zoneName && api.OrganizationID == zone.Account.ID {
return zone.ID, nil
}
} else {
if zone.Name == zoneName {
return zone.ID, nil
}
}
}
return "", errors.New("Zone could not be found")
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"ZoneIDByName",
"(",
"zoneName",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"res",
",",
"err",
":=",
"api",
".",
"ListZonesContext",
"(",
"context",
".",
"TODO",
"(",
")",
",",
"WithZoneFilter",
"(",
"zoneName",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"res",
".",
"Result",
")",
">",
"1",
"&&",
"api",
".",
"OrganizationID",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"zone",
":=",
"range",
"res",
".",
"Result",
"{",
"if",
"api",
".",
"OrganizationID",
"!=",
"\"",
"\"",
"{",
"if",
"zone",
".",
"Name",
"==",
"zoneName",
"&&",
"api",
".",
"OrganizationID",
"==",
"zone",
".",
"Account",
".",
"ID",
"{",
"return",
"zone",
".",
"ID",
",",
"nil",
"\n",
"}",
"\n",
"}",
"else",
"{",
"if",
"zone",
".",
"Name",
"==",
"zoneName",
"{",
"return",
"zone",
".",
"ID",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"\"",
"\"",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}"
] |
// ZoneIDByName retrieves a zone's ID from the name.
|
[
"ZoneIDByName",
"retrieves",
"a",
"zone",
"s",
"ID",
"from",
"the",
"name",
"."
] |
024278eb1b129df5cf9fdaf301c08b99283e81bc
|
https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/cloudflare.go#L118-L141
|
train
|
cloudflare/cloudflare-go
|
cloudflare.go
|
makeRequest
|
func (api *API) makeRequest(method, uri string, params interface{}) ([]byte, error) {
return api.makeRequestWithAuthType(context.TODO(), method, uri, params, api.authType)
}
|
go
|
func (api *API) makeRequest(method, uri string, params interface{}) ([]byte, error) {
return api.makeRequestWithAuthType(context.TODO(), method, uri, params, api.authType)
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"makeRequest",
"(",
"method",
",",
"uri",
"string",
",",
"params",
"interface",
"{",
"}",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"api",
".",
"makeRequestWithAuthType",
"(",
"context",
".",
"TODO",
"(",
")",
",",
"method",
",",
"uri",
",",
"params",
",",
"api",
".",
"authType",
")",
"\n",
"}"
] |
// makeRequest makes a HTTP request and returns the body as a byte slice,
// closing it before returnng. params will be serialized to JSON.
|
[
"makeRequest",
"makes",
"a",
"HTTP",
"request",
"and",
"returns",
"the",
"body",
"as",
"a",
"byte",
"slice",
"closing",
"it",
"before",
"returnng",
".",
"params",
"will",
"be",
"serialized",
"to",
"JSON",
"."
] |
024278eb1b129df5cf9fdaf301c08b99283e81bc
|
https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/cloudflare.go#L145-L147
|
train
|
cloudflare/cloudflare-go
|
cloudflare.go
|
userBaseURL
|
func (api *API) userBaseURL(accountBase string) string {
if api.OrganizationID != "" {
return "/accounts/" + api.OrganizationID
}
return accountBase
}
|
go
|
func (api *API) userBaseURL(accountBase string) string {
if api.OrganizationID != "" {
return "/accounts/" + api.OrganizationID
}
return accountBase
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"userBaseURL",
"(",
"accountBase",
"string",
")",
"string",
"{",
"if",
"api",
".",
"OrganizationID",
"!=",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
"+",
"api",
".",
"OrganizationID",
"\n",
"}",
"\n",
"return",
"accountBase",
"\n",
"}"
] |
// Returns the base URL to use for API endpoints that exist for both accounts and organizations.
// If an Organization option was used when creating the API instance, returns the org URL.
//
// accountBase is the base URL for endpoints referring to the current user. It exists as a
// parameter because it is not consistent across APIs.
|
[
"Returns",
"the",
"base",
"URL",
"to",
"use",
"for",
"API",
"endpoints",
"that",
"exist",
"for",
"both",
"accounts",
"and",
"organizations",
".",
"If",
"an",
"Organization",
"option",
"was",
"used",
"when",
"creating",
"the",
"API",
"instance",
"returns",
"the",
"org",
"URL",
".",
"accountBase",
"is",
"the",
"base",
"URL",
"for",
"endpoints",
"referring",
"to",
"the",
"current",
"user",
".",
"It",
"exists",
"as",
"a",
"parameter",
"because",
"it",
"is",
"not",
"consistent",
"across",
"APIs",
"."
] |
024278eb1b129df5cf9fdaf301c08b99283e81bc
|
https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/cloudflare.go#L308-L313
|
train
|
cloudflare/cloudflare-go
|
cloudflare.go
|
Raw
|
func (api *API) Raw(method, endpoint string, data interface{}) (json.RawMessage, error) {
res, err := api.makeRequest(method, endpoint, data)
if err != nil {
return nil, errors.Wrap(err, errMakeRequestError)
}
var r RawResponse
if err := json.Unmarshal(res, &r); err != nil {
return nil, errors.Wrap(err, errUnmarshalError)
}
return r.Result, nil
}
|
go
|
func (api *API) Raw(method, endpoint string, data interface{}) (json.RawMessage, error) {
res, err := api.makeRequest(method, endpoint, data)
if err != nil {
return nil, errors.Wrap(err, errMakeRequestError)
}
var r RawResponse
if err := json.Unmarshal(res, &r); err != nil {
return nil, errors.Wrap(err, errUnmarshalError)
}
return r.Result, nil
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"Raw",
"(",
"method",
",",
"endpoint",
"string",
",",
"data",
"interface",
"{",
"}",
")",
"(",
"json",
".",
"RawMessage",
",",
"error",
")",
"{",
"res",
",",
"err",
":=",
"api",
".",
"makeRequest",
"(",
"method",
",",
"endpoint",
",",
"data",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"errMakeRequestError",
")",
"\n",
"}",
"\n\n",
"var",
"r",
"RawResponse",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"res",
",",
"&",
"r",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"errUnmarshalError",
")",
"\n",
"}",
"\n",
"return",
"r",
".",
"Result",
",",
"nil",
"\n",
"}"
] |
// Raw makes a HTTP request with user provided params and returns the
// result as untouched JSON.
|
[
"Raw",
"makes",
"a",
"HTTP",
"request",
"with",
"user",
"provided",
"params",
"and",
"returns",
"the",
"result",
"as",
"untouched",
"JSON",
"."
] |
024278eb1b129df5cf9fdaf301c08b99283e81bc
|
https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/cloudflare.go#L355-L366
|
train
|
cloudflare/cloudflare-go
|
cloudflare.go
|
WithZoneFilter
|
func WithZoneFilter(zone string) ReqOption {
return func(opt *reqOption) {
opt.params.Set("name", zone)
}
}
|
go
|
func WithZoneFilter(zone string) ReqOption {
return func(opt *reqOption) {
opt.params.Set("name", zone)
}
}
|
[
"func",
"WithZoneFilter",
"(",
"zone",
"string",
")",
"ReqOption",
"{",
"return",
"func",
"(",
"opt",
"*",
"reqOption",
")",
"{",
"opt",
".",
"params",
".",
"Set",
"(",
"\"",
"\"",
",",
"zone",
")",
"\n",
"}",
"\n",
"}"
] |
// WithZoneFilter applies a filter based on zone name.
|
[
"WithZoneFilter",
"applies",
"a",
"filter",
"based",
"on",
"zone",
"name",
"."
] |
024278eb1b129df5cf9fdaf301c08b99283e81bc
|
https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/cloudflare.go#L396-L400
|
train
|
cloudflare/cloudflare-go
|
cloudflare.go
|
WithPagination
|
func WithPagination(opts PaginationOptions) ReqOption {
return func(opt *reqOption) {
opt.params.Set("page", strconv.Itoa(opts.Page))
opt.params.Set("per_page", strconv.Itoa(opts.PerPage))
}
}
|
go
|
func WithPagination(opts PaginationOptions) ReqOption {
return func(opt *reqOption) {
opt.params.Set("page", strconv.Itoa(opts.Page))
opt.params.Set("per_page", strconv.Itoa(opts.PerPage))
}
}
|
[
"func",
"WithPagination",
"(",
"opts",
"PaginationOptions",
")",
"ReqOption",
"{",
"return",
"func",
"(",
"opt",
"*",
"reqOption",
")",
"{",
"opt",
".",
"params",
".",
"Set",
"(",
"\"",
"\"",
",",
"strconv",
".",
"Itoa",
"(",
"opts",
".",
"Page",
")",
")",
"\n",
"opt",
".",
"params",
".",
"Set",
"(",
"\"",
"\"",
",",
"strconv",
".",
"Itoa",
"(",
"opts",
".",
"PerPage",
")",
")",
"\n",
"}",
"\n",
"}"
] |
// WithPagination configures the pagination for a response.
|
[
"WithPagination",
"configures",
"the",
"pagination",
"for",
"a",
"response",
"."
] |
024278eb1b129df5cf9fdaf301c08b99283e81bc
|
https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/cloudflare.go#L403-L408
|
train
|
prometheus/tsdb
|
record.go
|
Type
|
func (d *RecordDecoder) Type(rec []byte) RecordType {
if len(rec) < 1 {
return RecordInvalid
}
switch t := RecordType(rec[0]); t {
case RecordSeries, RecordSamples, RecordTombstones:
return t
}
return RecordInvalid
}
|
go
|
func (d *RecordDecoder) Type(rec []byte) RecordType {
if len(rec) < 1 {
return RecordInvalid
}
switch t := RecordType(rec[0]); t {
case RecordSeries, RecordSamples, RecordTombstones:
return t
}
return RecordInvalid
}
|
[
"func",
"(",
"d",
"*",
"RecordDecoder",
")",
"Type",
"(",
"rec",
"[",
"]",
"byte",
")",
"RecordType",
"{",
"if",
"len",
"(",
"rec",
")",
"<",
"1",
"{",
"return",
"RecordInvalid",
"\n",
"}",
"\n",
"switch",
"t",
":=",
"RecordType",
"(",
"rec",
"[",
"0",
"]",
")",
";",
"t",
"{",
"case",
"RecordSeries",
",",
"RecordSamples",
",",
"RecordTombstones",
":",
"return",
"t",
"\n",
"}",
"\n",
"return",
"RecordInvalid",
"\n",
"}"
] |
// Type returns the type of the record.
// Return RecordInvalid if no valid record type is found.
|
[
"Type",
"returns",
"the",
"type",
"of",
"the",
"record",
".",
"Return",
"RecordInvalid",
"if",
"no",
"valid",
"record",
"type",
"is",
"found",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/record.go#L47-L56
|
train
|
prometheus/tsdb
|
record.go
|
Series
|
func (d *RecordDecoder) Series(rec []byte, series []RefSeries) ([]RefSeries, error) {
dec := encoding.Decbuf{B: rec}
if RecordType(dec.Byte()) != RecordSeries {
return nil, errors.New("invalid record type")
}
for len(dec.B) > 0 && dec.Err() == nil {
ref := dec.Be64()
lset := make(labels.Labels, dec.Uvarint())
for i := range lset {
lset[i].Name = dec.UvarintStr()
lset[i].Value = dec.UvarintStr()
}
sort.Sort(lset)
series = append(series, RefSeries{
Ref: ref,
Labels: lset,
})
}
if dec.Err() != nil {
return nil, dec.Err()
}
if len(dec.B) > 0 {
return nil, errors.Errorf("unexpected %d bytes left in entry", len(dec.B))
}
return series, nil
}
|
go
|
func (d *RecordDecoder) Series(rec []byte, series []RefSeries) ([]RefSeries, error) {
dec := encoding.Decbuf{B: rec}
if RecordType(dec.Byte()) != RecordSeries {
return nil, errors.New("invalid record type")
}
for len(dec.B) > 0 && dec.Err() == nil {
ref := dec.Be64()
lset := make(labels.Labels, dec.Uvarint())
for i := range lset {
lset[i].Name = dec.UvarintStr()
lset[i].Value = dec.UvarintStr()
}
sort.Sort(lset)
series = append(series, RefSeries{
Ref: ref,
Labels: lset,
})
}
if dec.Err() != nil {
return nil, dec.Err()
}
if len(dec.B) > 0 {
return nil, errors.Errorf("unexpected %d bytes left in entry", len(dec.B))
}
return series, nil
}
|
[
"func",
"(",
"d",
"*",
"RecordDecoder",
")",
"Series",
"(",
"rec",
"[",
"]",
"byte",
",",
"series",
"[",
"]",
"RefSeries",
")",
"(",
"[",
"]",
"RefSeries",
",",
"error",
")",
"{",
"dec",
":=",
"encoding",
".",
"Decbuf",
"{",
"B",
":",
"rec",
"}",
"\n\n",
"if",
"RecordType",
"(",
"dec",
".",
"Byte",
"(",
")",
")",
"!=",
"RecordSeries",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"len",
"(",
"dec",
".",
"B",
")",
">",
"0",
"&&",
"dec",
".",
"Err",
"(",
")",
"==",
"nil",
"{",
"ref",
":=",
"dec",
".",
"Be64",
"(",
")",
"\n\n",
"lset",
":=",
"make",
"(",
"labels",
".",
"Labels",
",",
"dec",
".",
"Uvarint",
"(",
")",
")",
"\n\n",
"for",
"i",
":=",
"range",
"lset",
"{",
"lset",
"[",
"i",
"]",
".",
"Name",
"=",
"dec",
".",
"UvarintStr",
"(",
")",
"\n",
"lset",
"[",
"i",
"]",
".",
"Value",
"=",
"dec",
".",
"UvarintStr",
"(",
")",
"\n",
"}",
"\n",
"sort",
".",
"Sort",
"(",
"lset",
")",
"\n\n",
"series",
"=",
"append",
"(",
"series",
",",
"RefSeries",
"{",
"Ref",
":",
"ref",
",",
"Labels",
":",
"lset",
",",
"}",
")",
"\n",
"}",
"\n",
"if",
"dec",
".",
"Err",
"(",
")",
"!=",
"nil",
"{",
"return",
"nil",
",",
"dec",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"dec",
".",
"B",
")",
">",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"len",
"(",
"dec",
".",
"B",
")",
")",
"\n",
"}",
"\n",
"return",
"series",
",",
"nil",
"\n",
"}"
] |
// Series appends series in rec to the given slice.
|
[
"Series",
"appends",
"series",
"in",
"rec",
"to",
"the",
"given",
"slice",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/record.go#L59-L88
|
train
|
prometheus/tsdb
|
record.go
|
Samples
|
func (d *RecordDecoder) Samples(rec []byte, samples []RefSample) ([]RefSample, error) {
dec := encoding.Decbuf{B: rec}
if RecordType(dec.Byte()) != RecordSamples {
return nil, errors.New("invalid record type")
}
if dec.Len() == 0 {
return samples, nil
}
var (
baseRef = dec.Be64()
baseTime = dec.Be64int64()
)
for len(dec.B) > 0 && dec.Err() == nil {
dref := dec.Varint64()
dtime := dec.Varint64()
val := dec.Be64()
samples = append(samples, RefSample{
Ref: uint64(int64(baseRef) + dref),
T: baseTime + dtime,
V: math.Float64frombits(val),
})
}
if dec.Err() != nil {
return nil, errors.Wrapf(dec.Err(), "decode error after %d samples", len(samples))
}
if len(dec.B) > 0 {
return nil, errors.Errorf("unexpected %d bytes left in entry", len(dec.B))
}
return samples, nil
}
|
go
|
func (d *RecordDecoder) Samples(rec []byte, samples []RefSample) ([]RefSample, error) {
dec := encoding.Decbuf{B: rec}
if RecordType(dec.Byte()) != RecordSamples {
return nil, errors.New("invalid record type")
}
if dec.Len() == 0 {
return samples, nil
}
var (
baseRef = dec.Be64()
baseTime = dec.Be64int64()
)
for len(dec.B) > 0 && dec.Err() == nil {
dref := dec.Varint64()
dtime := dec.Varint64()
val := dec.Be64()
samples = append(samples, RefSample{
Ref: uint64(int64(baseRef) + dref),
T: baseTime + dtime,
V: math.Float64frombits(val),
})
}
if dec.Err() != nil {
return nil, errors.Wrapf(dec.Err(), "decode error after %d samples", len(samples))
}
if len(dec.B) > 0 {
return nil, errors.Errorf("unexpected %d bytes left in entry", len(dec.B))
}
return samples, nil
}
|
[
"func",
"(",
"d",
"*",
"RecordDecoder",
")",
"Samples",
"(",
"rec",
"[",
"]",
"byte",
",",
"samples",
"[",
"]",
"RefSample",
")",
"(",
"[",
"]",
"RefSample",
",",
"error",
")",
"{",
"dec",
":=",
"encoding",
".",
"Decbuf",
"{",
"B",
":",
"rec",
"}",
"\n\n",
"if",
"RecordType",
"(",
"dec",
".",
"Byte",
"(",
")",
")",
"!=",
"RecordSamples",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"dec",
".",
"Len",
"(",
")",
"==",
"0",
"{",
"return",
"samples",
",",
"nil",
"\n",
"}",
"\n",
"var",
"(",
"baseRef",
"=",
"dec",
".",
"Be64",
"(",
")",
"\n",
"baseTime",
"=",
"dec",
".",
"Be64int64",
"(",
")",
"\n",
")",
"\n",
"for",
"len",
"(",
"dec",
".",
"B",
")",
">",
"0",
"&&",
"dec",
".",
"Err",
"(",
")",
"==",
"nil",
"{",
"dref",
":=",
"dec",
".",
"Varint64",
"(",
")",
"\n",
"dtime",
":=",
"dec",
".",
"Varint64",
"(",
")",
"\n",
"val",
":=",
"dec",
".",
"Be64",
"(",
")",
"\n\n",
"samples",
"=",
"append",
"(",
"samples",
",",
"RefSample",
"{",
"Ref",
":",
"uint64",
"(",
"int64",
"(",
"baseRef",
")",
"+",
"dref",
")",
",",
"T",
":",
"baseTime",
"+",
"dtime",
",",
"V",
":",
"math",
".",
"Float64frombits",
"(",
"val",
")",
",",
"}",
")",
"\n",
"}",
"\n\n",
"if",
"dec",
".",
"Err",
"(",
")",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrapf",
"(",
"dec",
".",
"Err",
"(",
")",
",",
"\"",
"\"",
",",
"len",
"(",
"samples",
")",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"dec",
".",
"B",
")",
">",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"len",
"(",
"dec",
".",
"B",
")",
")",
"\n",
"}",
"\n",
"return",
"samples",
",",
"nil",
"\n",
"}"
] |
// Samples appends samples in rec to the given slice.
|
[
"Samples",
"appends",
"samples",
"in",
"rec",
"to",
"the",
"given",
"slice",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/record.go#L91-L123
|
train
|
prometheus/tsdb
|
record.go
|
Tombstones
|
func (d *RecordDecoder) Tombstones(rec []byte, tstones []Stone) ([]Stone, error) {
dec := encoding.Decbuf{B: rec}
if RecordType(dec.Byte()) != RecordTombstones {
return nil, errors.New("invalid record type")
}
for dec.Len() > 0 && dec.Err() == nil {
tstones = append(tstones, Stone{
ref: dec.Be64(),
intervals: Intervals{
{Mint: dec.Varint64(), Maxt: dec.Varint64()},
},
})
}
if dec.Err() != nil {
return nil, dec.Err()
}
if len(dec.B) > 0 {
return nil, errors.Errorf("unexpected %d bytes left in entry", len(dec.B))
}
return tstones, nil
}
|
go
|
func (d *RecordDecoder) Tombstones(rec []byte, tstones []Stone) ([]Stone, error) {
dec := encoding.Decbuf{B: rec}
if RecordType(dec.Byte()) != RecordTombstones {
return nil, errors.New("invalid record type")
}
for dec.Len() > 0 && dec.Err() == nil {
tstones = append(tstones, Stone{
ref: dec.Be64(),
intervals: Intervals{
{Mint: dec.Varint64(), Maxt: dec.Varint64()},
},
})
}
if dec.Err() != nil {
return nil, dec.Err()
}
if len(dec.B) > 0 {
return nil, errors.Errorf("unexpected %d bytes left in entry", len(dec.B))
}
return tstones, nil
}
|
[
"func",
"(",
"d",
"*",
"RecordDecoder",
")",
"Tombstones",
"(",
"rec",
"[",
"]",
"byte",
",",
"tstones",
"[",
"]",
"Stone",
")",
"(",
"[",
"]",
"Stone",
",",
"error",
")",
"{",
"dec",
":=",
"encoding",
".",
"Decbuf",
"{",
"B",
":",
"rec",
"}",
"\n\n",
"if",
"RecordType",
"(",
"dec",
".",
"Byte",
"(",
")",
")",
"!=",
"RecordTombstones",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"dec",
".",
"Len",
"(",
")",
">",
"0",
"&&",
"dec",
".",
"Err",
"(",
")",
"==",
"nil",
"{",
"tstones",
"=",
"append",
"(",
"tstones",
",",
"Stone",
"{",
"ref",
":",
"dec",
".",
"Be64",
"(",
")",
",",
"intervals",
":",
"Intervals",
"{",
"{",
"Mint",
":",
"dec",
".",
"Varint64",
"(",
")",
",",
"Maxt",
":",
"dec",
".",
"Varint64",
"(",
")",
"}",
",",
"}",
",",
"}",
")",
"\n",
"}",
"\n",
"if",
"dec",
".",
"Err",
"(",
")",
"!=",
"nil",
"{",
"return",
"nil",
",",
"dec",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"dec",
".",
"B",
")",
">",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"len",
"(",
"dec",
".",
"B",
")",
")",
"\n",
"}",
"\n",
"return",
"tstones",
",",
"nil",
"\n",
"}"
] |
// Tombstones appends tombstones in rec to the given slice.
|
[
"Tombstones",
"appends",
"tombstones",
"in",
"rec",
"to",
"the",
"given",
"slice",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/record.go#L126-L147
|
train
|
prometheus/tsdb
|
record.go
|
Series
|
func (e *RecordEncoder) Series(series []RefSeries, b []byte) []byte {
buf := encoding.Encbuf{B: b}
buf.PutByte(byte(RecordSeries))
for _, s := range series {
buf.PutBE64(s.Ref)
buf.PutUvarint(len(s.Labels))
for _, l := range s.Labels {
buf.PutUvarintStr(l.Name)
buf.PutUvarintStr(l.Value)
}
}
return buf.Get()
}
|
go
|
func (e *RecordEncoder) Series(series []RefSeries, b []byte) []byte {
buf := encoding.Encbuf{B: b}
buf.PutByte(byte(RecordSeries))
for _, s := range series {
buf.PutBE64(s.Ref)
buf.PutUvarint(len(s.Labels))
for _, l := range s.Labels {
buf.PutUvarintStr(l.Name)
buf.PutUvarintStr(l.Value)
}
}
return buf.Get()
}
|
[
"func",
"(",
"e",
"*",
"RecordEncoder",
")",
"Series",
"(",
"series",
"[",
"]",
"RefSeries",
",",
"b",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"buf",
":=",
"encoding",
".",
"Encbuf",
"{",
"B",
":",
"b",
"}",
"\n",
"buf",
".",
"PutByte",
"(",
"byte",
"(",
"RecordSeries",
")",
")",
"\n\n",
"for",
"_",
",",
"s",
":=",
"range",
"series",
"{",
"buf",
".",
"PutBE64",
"(",
"s",
".",
"Ref",
")",
"\n",
"buf",
".",
"PutUvarint",
"(",
"len",
"(",
"s",
".",
"Labels",
")",
")",
"\n\n",
"for",
"_",
",",
"l",
":=",
"range",
"s",
".",
"Labels",
"{",
"buf",
".",
"PutUvarintStr",
"(",
"l",
".",
"Name",
")",
"\n",
"buf",
".",
"PutUvarintStr",
"(",
"l",
".",
"Value",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"buf",
".",
"Get",
"(",
")",
"\n",
"}"
] |
// Series appends the encoded series to b and returns the resulting slice.
|
[
"Series",
"appends",
"the",
"encoded",
"series",
"to",
"b",
"and",
"returns",
"the",
"resulting",
"slice",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/record.go#L155-L169
|
train
|
prometheus/tsdb
|
record.go
|
Samples
|
func (e *RecordEncoder) Samples(samples []RefSample, b []byte) []byte {
buf := encoding.Encbuf{B: b}
buf.PutByte(byte(RecordSamples))
if len(samples) == 0 {
return buf.Get()
}
// Store base timestamp and base reference number of first sample.
// All samples encode their timestamp and ref as delta to those.
first := samples[0]
buf.PutBE64(first.Ref)
buf.PutBE64int64(first.T)
for _, s := range samples {
buf.PutVarint64(int64(s.Ref) - int64(first.Ref))
buf.PutVarint64(s.T - first.T)
buf.PutBE64(math.Float64bits(s.V))
}
return buf.Get()
}
|
go
|
func (e *RecordEncoder) Samples(samples []RefSample, b []byte) []byte {
buf := encoding.Encbuf{B: b}
buf.PutByte(byte(RecordSamples))
if len(samples) == 0 {
return buf.Get()
}
// Store base timestamp and base reference number of first sample.
// All samples encode their timestamp and ref as delta to those.
first := samples[0]
buf.PutBE64(first.Ref)
buf.PutBE64int64(first.T)
for _, s := range samples {
buf.PutVarint64(int64(s.Ref) - int64(first.Ref))
buf.PutVarint64(s.T - first.T)
buf.PutBE64(math.Float64bits(s.V))
}
return buf.Get()
}
|
[
"func",
"(",
"e",
"*",
"RecordEncoder",
")",
"Samples",
"(",
"samples",
"[",
"]",
"RefSample",
",",
"b",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"buf",
":=",
"encoding",
".",
"Encbuf",
"{",
"B",
":",
"b",
"}",
"\n",
"buf",
".",
"PutByte",
"(",
"byte",
"(",
"RecordSamples",
")",
")",
"\n\n",
"if",
"len",
"(",
"samples",
")",
"==",
"0",
"{",
"return",
"buf",
".",
"Get",
"(",
")",
"\n",
"}",
"\n\n",
"// Store base timestamp and base reference number of first sample.",
"// All samples encode their timestamp and ref as delta to those.",
"first",
":=",
"samples",
"[",
"0",
"]",
"\n\n",
"buf",
".",
"PutBE64",
"(",
"first",
".",
"Ref",
")",
"\n",
"buf",
".",
"PutBE64int64",
"(",
"first",
".",
"T",
")",
"\n\n",
"for",
"_",
",",
"s",
":=",
"range",
"samples",
"{",
"buf",
".",
"PutVarint64",
"(",
"int64",
"(",
"s",
".",
"Ref",
")",
"-",
"int64",
"(",
"first",
".",
"Ref",
")",
")",
"\n",
"buf",
".",
"PutVarint64",
"(",
"s",
".",
"T",
"-",
"first",
".",
"T",
")",
"\n",
"buf",
".",
"PutBE64",
"(",
"math",
".",
"Float64bits",
"(",
"s",
".",
"V",
")",
")",
"\n",
"}",
"\n",
"return",
"buf",
".",
"Get",
"(",
")",
"\n",
"}"
] |
// Samples appends the encoded samples to b and returns the resulting slice.
|
[
"Samples",
"appends",
"the",
"encoded",
"samples",
"to",
"b",
"and",
"returns",
"the",
"resulting",
"slice",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/record.go#L172-L193
|
train
|
prometheus/tsdb
|
record.go
|
Tombstones
|
func (e *RecordEncoder) Tombstones(tstones []Stone, b []byte) []byte {
buf := encoding.Encbuf{B: b}
buf.PutByte(byte(RecordTombstones))
for _, s := range tstones {
for _, iv := range s.intervals {
buf.PutBE64(s.ref)
buf.PutVarint64(iv.Mint)
buf.PutVarint64(iv.Maxt)
}
}
return buf.Get()
}
|
go
|
func (e *RecordEncoder) Tombstones(tstones []Stone, b []byte) []byte {
buf := encoding.Encbuf{B: b}
buf.PutByte(byte(RecordTombstones))
for _, s := range tstones {
for _, iv := range s.intervals {
buf.PutBE64(s.ref)
buf.PutVarint64(iv.Mint)
buf.PutVarint64(iv.Maxt)
}
}
return buf.Get()
}
|
[
"func",
"(",
"e",
"*",
"RecordEncoder",
")",
"Tombstones",
"(",
"tstones",
"[",
"]",
"Stone",
",",
"b",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"buf",
":=",
"encoding",
".",
"Encbuf",
"{",
"B",
":",
"b",
"}",
"\n",
"buf",
".",
"PutByte",
"(",
"byte",
"(",
"RecordTombstones",
")",
")",
"\n\n",
"for",
"_",
",",
"s",
":=",
"range",
"tstones",
"{",
"for",
"_",
",",
"iv",
":=",
"range",
"s",
".",
"intervals",
"{",
"buf",
".",
"PutBE64",
"(",
"s",
".",
"ref",
")",
"\n",
"buf",
".",
"PutVarint64",
"(",
"iv",
".",
"Mint",
")",
"\n",
"buf",
".",
"PutVarint64",
"(",
"iv",
".",
"Maxt",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"buf",
".",
"Get",
"(",
")",
"\n",
"}"
] |
// Tombstones appends the encoded tombstones to b and returns the resulting slice.
|
[
"Tombstones",
"appends",
"the",
"encoded",
"tombstones",
"to",
"b",
"and",
"returns",
"the",
"resulting",
"slice",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/record.go#L196-L208
|
train
|
prometheus/tsdb
|
tsdbutil/buffer.go
|
NewBuffer
|
func NewBuffer(it SeriesIterator, delta int64) *BufferedSeriesIterator {
return &BufferedSeriesIterator{
it: it,
buf: newSampleRing(delta, 16),
lastTime: math.MinInt64,
}
}
|
go
|
func NewBuffer(it SeriesIterator, delta int64) *BufferedSeriesIterator {
return &BufferedSeriesIterator{
it: it,
buf: newSampleRing(delta, 16),
lastTime: math.MinInt64,
}
}
|
[
"func",
"NewBuffer",
"(",
"it",
"SeriesIterator",
",",
"delta",
"int64",
")",
"*",
"BufferedSeriesIterator",
"{",
"return",
"&",
"BufferedSeriesIterator",
"{",
"it",
":",
"it",
",",
"buf",
":",
"newSampleRing",
"(",
"delta",
",",
"16",
")",
",",
"lastTime",
":",
"math",
".",
"MinInt64",
",",
"}",
"\n",
"}"
] |
// NewBuffer returns a new iterator that buffers the values within the time range
// of the current element and the duration of delta before.
|
[
"NewBuffer",
"returns",
"a",
"new",
"iterator",
"that",
"buffers",
"the",
"values",
"within",
"the",
"time",
"range",
"of",
"the",
"current",
"element",
"and",
"the",
"duration",
"of",
"delta",
"before",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/tsdbutil/buffer.go#L44-L50
|
train
|
prometheus/tsdb
|
tsdbutil/buffer.go
|
PeekBack
|
func (b *BufferedSeriesIterator) PeekBack() (t int64, v float64, ok bool) {
return b.buf.last()
}
|
go
|
func (b *BufferedSeriesIterator) PeekBack() (t int64, v float64, ok bool) {
return b.buf.last()
}
|
[
"func",
"(",
"b",
"*",
"BufferedSeriesIterator",
")",
"PeekBack",
"(",
")",
"(",
"t",
"int64",
",",
"v",
"float64",
",",
"ok",
"bool",
")",
"{",
"return",
"b",
".",
"buf",
".",
"last",
"(",
")",
"\n",
"}"
] |
// PeekBack returns the previous element of the iterator. If there is none buffered,
// ok is false.
|
[
"PeekBack",
"returns",
"the",
"previous",
"element",
"of",
"the",
"iterator",
".",
"If",
"there",
"is",
"none",
"buffered",
"ok",
"is",
"false",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/tsdbutil/buffer.go#L54-L56
|
train
|
prometheus/tsdb
|
tsdbutil/buffer.go
|
add
|
func (r *sampleRing) add(t int64, v float64) {
l := len(r.buf)
// Grow the ring buffer if it fits no more elements.
if l == r.l {
buf := make([]sample, 2*l)
copy(buf[l+r.f:], r.buf[r.f:])
copy(buf, r.buf[:r.f])
r.buf = buf
r.i = r.f
r.f += l
} else {
r.i++
if r.i >= l {
r.i -= l
}
}
r.buf[r.i] = sample{t: t, v: v}
r.l++
// Free head of the buffer of samples that just fell out of the range.
for r.buf[r.f].t < t-r.delta {
r.f++
if r.f >= l {
r.f -= l
}
r.l--
}
}
|
go
|
func (r *sampleRing) add(t int64, v float64) {
l := len(r.buf)
// Grow the ring buffer if it fits no more elements.
if l == r.l {
buf := make([]sample, 2*l)
copy(buf[l+r.f:], r.buf[r.f:])
copy(buf, r.buf[:r.f])
r.buf = buf
r.i = r.f
r.f += l
} else {
r.i++
if r.i >= l {
r.i -= l
}
}
r.buf[r.i] = sample{t: t, v: v}
r.l++
// Free head of the buffer of samples that just fell out of the range.
for r.buf[r.f].t < t-r.delta {
r.f++
if r.f >= l {
r.f -= l
}
r.l--
}
}
|
[
"func",
"(",
"r",
"*",
"sampleRing",
")",
"add",
"(",
"t",
"int64",
",",
"v",
"float64",
")",
"{",
"l",
":=",
"len",
"(",
"r",
".",
"buf",
")",
"\n",
"// Grow the ring buffer if it fits no more elements.",
"if",
"l",
"==",
"r",
".",
"l",
"{",
"buf",
":=",
"make",
"(",
"[",
"]",
"sample",
",",
"2",
"*",
"l",
")",
"\n",
"copy",
"(",
"buf",
"[",
"l",
"+",
"r",
".",
"f",
":",
"]",
",",
"r",
".",
"buf",
"[",
"r",
".",
"f",
":",
"]",
")",
"\n",
"copy",
"(",
"buf",
",",
"r",
".",
"buf",
"[",
":",
"r",
".",
"f",
"]",
")",
"\n\n",
"r",
".",
"buf",
"=",
"buf",
"\n",
"r",
".",
"i",
"=",
"r",
".",
"f",
"\n",
"r",
".",
"f",
"+=",
"l",
"\n",
"}",
"else",
"{",
"r",
".",
"i",
"++",
"\n",
"if",
"r",
".",
"i",
">=",
"l",
"{",
"r",
".",
"i",
"-=",
"l",
"\n",
"}",
"\n",
"}",
"\n\n",
"r",
".",
"buf",
"[",
"r",
".",
"i",
"]",
"=",
"sample",
"{",
"t",
":",
"t",
",",
"v",
":",
"v",
"}",
"\n",
"r",
".",
"l",
"++",
"\n\n",
"// Free head of the buffer of samples that just fell out of the range.",
"for",
"r",
".",
"buf",
"[",
"r",
".",
"f",
"]",
".",
"t",
"<",
"t",
"-",
"r",
".",
"delta",
"{",
"r",
".",
"f",
"++",
"\n",
"if",
"r",
".",
"f",
">=",
"l",
"{",
"r",
".",
"f",
"-=",
"l",
"\n",
"}",
"\n",
"r",
".",
"l",
"--",
"\n",
"}",
"\n",
"}"
] |
// add adds a sample to the ring buffer and frees all samples that fall
// out of the delta range.
|
[
"add",
"adds",
"a",
"sample",
"to",
"the",
"ring",
"buffer",
"and",
"frees",
"all",
"samples",
"that",
"fall",
"out",
"of",
"the",
"delta",
"range",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/tsdbutil/buffer.go#L182-L211
|
train
|
prometheus/tsdb
|
tsdbutil/buffer.go
|
last
|
func (r *sampleRing) last() (int64, float64, bool) {
if r.l == 0 {
return 0, 0, false
}
s := r.buf[r.i]
return s.t, s.v, true
}
|
go
|
func (r *sampleRing) last() (int64, float64, bool) {
if r.l == 0 {
return 0, 0, false
}
s := r.buf[r.i]
return s.t, s.v, true
}
|
[
"func",
"(",
"r",
"*",
"sampleRing",
")",
"last",
"(",
")",
"(",
"int64",
",",
"float64",
",",
"bool",
")",
"{",
"if",
"r",
".",
"l",
"==",
"0",
"{",
"return",
"0",
",",
"0",
",",
"false",
"\n",
"}",
"\n",
"s",
":=",
"r",
".",
"buf",
"[",
"r",
".",
"i",
"]",
"\n",
"return",
"s",
".",
"t",
",",
"s",
".",
"v",
",",
"true",
"\n",
"}"
] |
// last returns the most recent element added to the ring.
|
[
"last",
"returns",
"the",
"most",
"recent",
"element",
"added",
"to",
"the",
"ring",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/tsdbutil/buffer.go#L214-L220
|
train
|
prometheus/tsdb
|
labels/labels.go
|
Equals
|
func (ls Labels) Equals(o Labels) bool {
if len(ls) != len(o) {
return false
}
for i, l := range ls {
if o[i] != l {
return false
}
}
return true
}
|
go
|
func (ls Labels) Equals(o Labels) bool {
if len(ls) != len(o) {
return false
}
for i, l := range ls {
if o[i] != l {
return false
}
}
return true
}
|
[
"func",
"(",
"ls",
"Labels",
")",
"Equals",
"(",
"o",
"Labels",
")",
"bool",
"{",
"if",
"len",
"(",
"ls",
")",
"!=",
"len",
"(",
"o",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"for",
"i",
",",
"l",
":=",
"range",
"ls",
"{",
"if",
"o",
"[",
"i",
"]",
"!=",
"l",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] |
// Equals returns whether the two label sets are equal.
|
[
"Equals",
"returns",
"whether",
"the",
"two",
"label",
"sets",
"are",
"equal",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/labels/labels.go#L85-L95
|
train
|
prometheus/tsdb
|
labels/labels.go
|
FromMap
|
func FromMap(m map[string]string) Labels {
l := make(Labels, 0, len(m))
for k, v := range m {
l = append(l, Label{Name: k, Value: v})
}
sort.Sort(l)
return l
}
|
go
|
func FromMap(m map[string]string) Labels {
l := make(Labels, 0, len(m))
for k, v := range m {
l = append(l, Label{Name: k, Value: v})
}
sort.Sort(l)
return l
}
|
[
"func",
"FromMap",
"(",
"m",
"map",
"[",
"string",
"]",
"string",
")",
"Labels",
"{",
"l",
":=",
"make",
"(",
"Labels",
",",
"0",
",",
"len",
"(",
"m",
")",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"m",
"{",
"l",
"=",
"append",
"(",
"l",
",",
"Label",
"{",
"Name",
":",
"k",
",",
"Value",
":",
"v",
"}",
")",
"\n",
"}",
"\n",
"sort",
".",
"Sort",
"(",
"l",
")",
"\n\n",
"return",
"l",
"\n",
"}"
] |
// FromMap returns new sorted Labels from the given map.
|
[
"FromMap",
"returns",
"new",
"sorted",
"Labels",
"from",
"the",
"given",
"map",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/labels/labels.go#L119-L127
|
train
|
prometheus/tsdb
|
labels/labels.go
|
ReadLabels
|
func ReadLabels(fn string, n int) ([]Labels, error) {
f, err := os.Open(fn)
if err != nil {
return nil, err
}
defer f.Close()
scanner := bufio.NewScanner(f)
var mets []Labels
hashes := map[uint64]struct{}{}
i := 0
for scanner.Scan() && i < n {
m := make(Labels, 0, 10)
r := strings.NewReplacer("\"", "", "{", "", "}", "")
s := r.Replace(scanner.Text())
labelChunks := strings.Split(s, ",")
for _, labelChunk := range labelChunks {
split := strings.Split(labelChunk, ":")
m = append(m, Label{Name: split[0], Value: split[1]})
}
// Order of the k/v labels matters, don't assume we'll always receive them already sorted.
sort.Sort(m)
h := m.Hash()
if _, ok := hashes[h]; ok {
continue
}
mets = append(mets, m)
hashes[h] = struct{}{}
i++
}
if i != n {
return mets, errors.Errorf("requested %d metrics but found %d", n, i)
}
return mets, nil
}
|
go
|
func ReadLabels(fn string, n int) ([]Labels, error) {
f, err := os.Open(fn)
if err != nil {
return nil, err
}
defer f.Close()
scanner := bufio.NewScanner(f)
var mets []Labels
hashes := map[uint64]struct{}{}
i := 0
for scanner.Scan() && i < n {
m := make(Labels, 0, 10)
r := strings.NewReplacer("\"", "", "{", "", "}", "")
s := r.Replace(scanner.Text())
labelChunks := strings.Split(s, ",")
for _, labelChunk := range labelChunks {
split := strings.Split(labelChunk, ":")
m = append(m, Label{Name: split[0], Value: split[1]})
}
// Order of the k/v labels matters, don't assume we'll always receive them already sorted.
sort.Sort(m)
h := m.Hash()
if _, ok := hashes[h]; ok {
continue
}
mets = append(mets, m)
hashes[h] = struct{}{}
i++
}
if i != n {
return mets, errors.Errorf("requested %d metrics but found %d", n, i)
}
return mets, nil
}
|
[
"func",
"ReadLabels",
"(",
"fn",
"string",
",",
"n",
"int",
")",
"(",
"[",
"]",
"Labels",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"fn",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n\n",
"scanner",
":=",
"bufio",
".",
"NewScanner",
"(",
"f",
")",
"\n\n",
"var",
"mets",
"[",
"]",
"Labels",
"\n",
"hashes",
":=",
"map",
"[",
"uint64",
"]",
"struct",
"{",
"}",
"{",
"}",
"\n",
"i",
":=",
"0",
"\n\n",
"for",
"scanner",
".",
"Scan",
"(",
")",
"&&",
"i",
"<",
"n",
"{",
"m",
":=",
"make",
"(",
"Labels",
",",
"0",
",",
"10",
")",
"\n\n",
"r",
":=",
"strings",
".",
"NewReplacer",
"(",
"\"",
"\\\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"s",
":=",
"r",
".",
"Replace",
"(",
"scanner",
".",
"Text",
"(",
")",
")",
"\n\n",
"labelChunks",
":=",
"strings",
".",
"Split",
"(",
"s",
",",
"\"",
"\"",
")",
"\n",
"for",
"_",
",",
"labelChunk",
":=",
"range",
"labelChunks",
"{",
"split",
":=",
"strings",
".",
"Split",
"(",
"labelChunk",
",",
"\"",
"\"",
")",
"\n",
"m",
"=",
"append",
"(",
"m",
",",
"Label",
"{",
"Name",
":",
"split",
"[",
"0",
"]",
",",
"Value",
":",
"split",
"[",
"1",
"]",
"}",
")",
"\n",
"}",
"\n",
"// Order of the k/v labels matters, don't assume we'll always receive them already sorted.",
"sort",
".",
"Sort",
"(",
"m",
")",
"\n\n",
"h",
":=",
"m",
".",
"Hash",
"(",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"hashes",
"[",
"h",
"]",
";",
"ok",
"{",
"continue",
"\n",
"}",
"\n",
"mets",
"=",
"append",
"(",
"mets",
",",
"m",
")",
"\n",
"hashes",
"[",
"h",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"i",
"++",
"\n",
"}",
"\n\n",
"if",
"i",
"!=",
"n",
"{",
"return",
"mets",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"n",
",",
"i",
")",
"\n",
"}",
"\n",
"return",
"mets",
",",
"nil",
"\n",
"}"
] |
// ReadLabels reads up to n label sets in a JSON formatted file fn. It is mostly useful
// to load testing data.
|
[
"ReadLabels",
"reads",
"up",
"to",
"n",
"label",
"sets",
"in",
"a",
"JSON",
"formatted",
"file",
"fn",
".",
"It",
"is",
"mostly",
"useful",
"to",
"load",
"testing",
"data",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/labels/labels.go#L172-L212
|
train
|
prometheus/tsdb
|
head.go
|
NewHead
|
func NewHead(r prometheus.Registerer, l log.Logger, wal *wal.WAL, chunkRange int64) (*Head, error) {
if l == nil {
l = log.NewNopLogger()
}
if chunkRange < 1 {
return nil, errors.Errorf("invalid chunk range %d", chunkRange)
}
h := &Head{
wal: wal,
logger: l,
chunkRange: chunkRange,
minTime: math.MaxInt64,
maxTime: math.MinInt64,
series: newStripeSeries(),
values: map[string]stringset{},
symbols: map[string]struct{}{},
postings: index.NewUnorderedMemPostings(),
deleted: map[uint64]int{},
}
h.metrics = newHeadMetrics(h, r)
return h, nil
}
|
go
|
func NewHead(r prometheus.Registerer, l log.Logger, wal *wal.WAL, chunkRange int64) (*Head, error) {
if l == nil {
l = log.NewNopLogger()
}
if chunkRange < 1 {
return nil, errors.Errorf("invalid chunk range %d", chunkRange)
}
h := &Head{
wal: wal,
logger: l,
chunkRange: chunkRange,
minTime: math.MaxInt64,
maxTime: math.MinInt64,
series: newStripeSeries(),
values: map[string]stringset{},
symbols: map[string]struct{}{},
postings: index.NewUnorderedMemPostings(),
deleted: map[uint64]int{},
}
h.metrics = newHeadMetrics(h, r)
return h, nil
}
|
[
"func",
"NewHead",
"(",
"r",
"prometheus",
".",
"Registerer",
",",
"l",
"log",
".",
"Logger",
",",
"wal",
"*",
"wal",
".",
"WAL",
",",
"chunkRange",
"int64",
")",
"(",
"*",
"Head",
",",
"error",
")",
"{",
"if",
"l",
"==",
"nil",
"{",
"l",
"=",
"log",
".",
"NewNopLogger",
"(",
")",
"\n",
"}",
"\n",
"if",
"chunkRange",
"<",
"1",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"chunkRange",
")",
"\n",
"}",
"\n",
"h",
":=",
"&",
"Head",
"{",
"wal",
":",
"wal",
",",
"logger",
":",
"l",
",",
"chunkRange",
":",
"chunkRange",
",",
"minTime",
":",
"math",
".",
"MaxInt64",
",",
"maxTime",
":",
"math",
".",
"MinInt64",
",",
"series",
":",
"newStripeSeries",
"(",
")",
",",
"values",
":",
"map",
"[",
"string",
"]",
"stringset",
"{",
"}",
",",
"symbols",
":",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
"{",
"}",
",",
"postings",
":",
"index",
".",
"NewUnorderedMemPostings",
"(",
")",
",",
"deleted",
":",
"map",
"[",
"uint64",
"]",
"int",
"{",
"}",
",",
"}",
"\n",
"h",
".",
"metrics",
"=",
"newHeadMetrics",
"(",
"h",
",",
"r",
")",
"\n\n",
"return",
"h",
",",
"nil",
"\n",
"}"
] |
// NewHead opens the head block in dir.
|
[
"NewHead",
"opens",
"the",
"head",
"block",
"in",
"dir",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L223-L245
|
train
|
prometheus/tsdb
|
head.go
|
processWALSamples
|
func (h *Head) processWALSamples(
minValidTime int64,
input <-chan []RefSample, output chan<- []RefSample,
) (unknownRefs uint64) {
defer close(output)
// Mitigate lock contention in getByID.
refSeries := map[uint64]*memSeries{}
mint, maxt := int64(math.MaxInt64), int64(math.MinInt64)
for samples := range input {
for _, s := range samples {
if s.T < minValidTime {
continue
}
ms := refSeries[s.Ref]
if ms == nil {
ms = h.series.getByID(s.Ref)
if ms == nil {
unknownRefs++
continue
}
refSeries[s.Ref] = ms
}
_, chunkCreated := ms.append(s.T, s.V)
if chunkCreated {
h.metrics.chunksCreated.Inc()
h.metrics.chunks.Inc()
}
if s.T > maxt {
maxt = s.T
}
if s.T < mint {
mint = s.T
}
}
output <- samples
}
h.updateMinMaxTime(mint, maxt)
return unknownRefs
}
|
go
|
func (h *Head) processWALSamples(
minValidTime int64,
input <-chan []RefSample, output chan<- []RefSample,
) (unknownRefs uint64) {
defer close(output)
// Mitigate lock contention in getByID.
refSeries := map[uint64]*memSeries{}
mint, maxt := int64(math.MaxInt64), int64(math.MinInt64)
for samples := range input {
for _, s := range samples {
if s.T < minValidTime {
continue
}
ms := refSeries[s.Ref]
if ms == nil {
ms = h.series.getByID(s.Ref)
if ms == nil {
unknownRefs++
continue
}
refSeries[s.Ref] = ms
}
_, chunkCreated := ms.append(s.T, s.V)
if chunkCreated {
h.metrics.chunksCreated.Inc()
h.metrics.chunks.Inc()
}
if s.T > maxt {
maxt = s.T
}
if s.T < mint {
mint = s.T
}
}
output <- samples
}
h.updateMinMaxTime(mint, maxt)
return unknownRefs
}
|
[
"func",
"(",
"h",
"*",
"Head",
")",
"processWALSamples",
"(",
"minValidTime",
"int64",
",",
"input",
"<-",
"chan",
"[",
"]",
"RefSample",
",",
"output",
"chan",
"<-",
"[",
"]",
"RefSample",
",",
")",
"(",
"unknownRefs",
"uint64",
")",
"{",
"defer",
"close",
"(",
"output",
")",
"\n\n",
"// Mitigate lock contention in getByID.",
"refSeries",
":=",
"map",
"[",
"uint64",
"]",
"*",
"memSeries",
"{",
"}",
"\n\n",
"mint",
",",
"maxt",
":=",
"int64",
"(",
"math",
".",
"MaxInt64",
")",
",",
"int64",
"(",
"math",
".",
"MinInt64",
")",
"\n\n",
"for",
"samples",
":=",
"range",
"input",
"{",
"for",
"_",
",",
"s",
":=",
"range",
"samples",
"{",
"if",
"s",
".",
"T",
"<",
"minValidTime",
"{",
"continue",
"\n",
"}",
"\n",
"ms",
":=",
"refSeries",
"[",
"s",
".",
"Ref",
"]",
"\n",
"if",
"ms",
"==",
"nil",
"{",
"ms",
"=",
"h",
".",
"series",
".",
"getByID",
"(",
"s",
".",
"Ref",
")",
"\n",
"if",
"ms",
"==",
"nil",
"{",
"unknownRefs",
"++",
"\n",
"continue",
"\n",
"}",
"\n",
"refSeries",
"[",
"s",
".",
"Ref",
"]",
"=",
"ms",
"\n",
"}",
"\n",
"_",
",",
"chunkCreated",
":=",
"ms",
".",
"append",
"(",
"s",
".",
"T",
",",
"s",
".",
"V",
")",
"\n",
"if",
"chunkCreated",
"{",
"h",
".",
"metrics",
".",
"chunksCreated",
".",
"Inc",
"(",
")",
"\n",
"h",
".",
"metrics",
".",
"chunks",
".",
"Inc",
"(",
")",
"\n",
"}",
"\n",
"if",
"s",
".",
"T",
">",
"maxt",
"{",
"maxt",
"=",
"s",
".",
"T",
"\n",
"}",
"\n",
"if",
"s",
".",
"T",
"<",
"mint",
"{",
"mint",
"=",
"s",
".",
"T",
"\n",
"}",
"\n",
"}",
"\n",
"output",
"<-",
"samples",
"\n",
"}",
"\n",
"h",
".",
"updateMinMaxTime",
"(",
"mint",
",",
"maxt",
")",
"\n\n",
"return",
"unknownRefs",
"\n",
"}"
] |
// processWALSamples adds a partition of samples it receives to the head and passes
// them on to other workers.
// Samples before the mint timestamp are discarded.
|
[
"processWALSamples",
"adds",
"a",
"partition",
"of",
"samples",
"it",
"receives",
"to",
"the",
"head",
"and",
"passes",
"them",
"on",
"to",
"other",
"workers",
".",
"Samples",
"before",
"the",
"mint",
"timestamp",
"are",
"discarded",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L250-L292
|
train
|
prometheus/tsdb
|
head.go
|
Init
|
func (h *Head) Init(minValidTime int64) error {
h.minValidTime = minValidTime
defer h.postings.EnsureOrder()
defer h.gc() // After loading the wal remove the obsolete data from the head.
if h.wal == nil {
return nil
}
// Backfill the checkpoint first if it exists.
dir, startFrom, err := LastCheckpoint(h.wal.Dir())
if err != nil && err != ErrNotFound {
return errors.Wrap(err, "find last checkpoint")
}
if err == nil {
sr, err := wal.NewSegmentsReader(dir)
if err != nil {
return errors.Wrap(err, "open checkpoint")
}
defer sr.Close()
// A corrupted checkpoint is a hard error for now and requires user
// intervention. There's likely little data that can be recovered anyway.
if err := h.loadWAL(wal.NewReader(sr)); err != nil {
return errors.Wrap(err, "backfill checkpoint")
}
startFrom++
}
// Backfill segments from the last checkpoint onwards
sr, err := wal.NewSegmentsRangeReader(wal.SegmentRange{Dir: h.wal.Dir(), First: startFrom, Last: -1})
if err != nil {
return errors.Wrap(err, "open WAL segments")
}
err = h.loadWAL(wal.NewReader(sr))
sr.Close() // Close the reader so that if there was an error the repair can remove the corrupted file under Windows.
if err == nil {
return nil
}
level.Warn(h.logger).Log("msg", "encountered WAL error, attempting repair", "err", err)
h.metrics.walCorruptionsTotal.Inc()
if err := h.wal.Repair(err); err != nil {
return errors.Wrap(err, "repair corrupted WAL")
}
return nil
}
|
go
|
func (h *Head) Init(minValidTime int64) error {
h.minValidTime = minValidTime
defer h.postings.EnsureOrder()
defer h.gc() // After loading the wal remove the obsolete data from the head.
if h.wal == nil {
return nil
}
// Backfill the checkpoint first if it exists.
dir, startFrom, err := LastCheckpoint(h.wal.Dir())
if err != nil && err != ErrNotFound {
return errors.Wrap(err, "find last checkpoint")
}
if err == nil {
sr, err := wal.NewSegmentsReader(dir)
if err != nil {
return errors.Wrap(err, "open checkpoint")
}
defer sr.Close()
// A corrupted checkpoint is a hard error for now and requires user
// intervention. There's likely little data that can be recovered anyway.
if err := h.loadWAL(wal.NewReader(sr)); err != nil {
return errors.Wrap(err, "backfill checkpoint")
}
startFrom++
}
// Backfill segments from the last checkpoint onwards
sr, err := wal.NewSegmentsRangeReader(wal.SegmentRange{Dir: h.wal.Dir(), First: startFrom, Last: -1})
if err != nil {
return errors.Wrap(err, "open WAL segments")
}
err = h.loadWAL(wal.NewReader(sr))
sr.Close() // Close the reader so that if there was an error the repair can remove the corrupted file under Windows.
if err == nil {
return nil
}
level.Warn(h.logger).Log("msg", "encountered WAL error, attempting repair", "err", err)
h.metrics.walCorruptionsTotal.Inc()
if err := h.wal.Repair(err); err != nil {
return errors.Wrap(err, "repair corrupted WAL")
}
return nil
}
|
[
"func",
"(",
"h",
"*",
"Head",
")",
"Init",
"(",
"minValidTime",
"int64",
")",
"error",
"{",
"h",
".",
"minValidTime",
"=",
"minValidTime",
"\n",
"defer",
"h",
".",
"postings",
".",
"EnsureOrder",
"(",
")",
"\n",
"defer",
"h",
".",
"gc",
"(",
")",
"// After loading the wal remove the obsolete data from the head.",
"\n\n",
"if",
"h",
".",
"wal",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Backfill the checkpoint first if it exists.",
"dir",
",",
"startFrom",
",",
"err",
":=",
"LastCheckpoint",
"(",
"h",
".",
"wal",
".",
"Dir",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"err",
"!=",
"ErrNotFound",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"err",
"==",
"nil",
"{",
"sr",
",",
"err",
":=",
"wal",
".",
"NewSegmentsReader",
"(",
"dir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"defer",
"sr",
".",
"Close",
"(",
")",
"\n\n",
"// A corrupted checkpoint is a hard error for now and requires user",
"// intervention. There's likely little data that can be recovered anyway.",
"if",
"err",
":=",
"h",
".",
"loadWAL",
"(",
"wal",
".",
"NewReader",
"(",
"sr",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"startFrom",
"++",
"\n",
"}",
"\n\n",
"// Backfill segments from the last checkpoint onwards",
"sr",
",",
"err",
":=",
"wal",
".",
"NewSegmentsRangeReader",
"(",
"wal",
".",
"SegmentRange",
"{",
"Dir",
":",
"h",
".",
"wal",
".",
"Dir",
"(",
")",
",",
"First",
":",
"startFrom",
",",
"Last",
":",
"-",
"1",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"err",
"=",
"h",
".",
"loadWAL",
"(",
"wal",
".",
"NewReader",
"(",
"sr",
")",
")",
"\n",
"sr",
".",
"Close",
"(",
")",
"// Close the reader so that if there was an error the repair can remove the corrupted file under Windows.",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"level",
".",
"Warn",
"(",
"h",
".",
"logger",
")",
".",
"Log",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"h",
".",
"metrics",
".",
"walCorruptionsTotal",
".",
"Inc",
"(",
")",
"\n",
"if",
"err",
":=",
"h",
".",
"wal",
".",
"Repair",
"(",
"err",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Init loads data from the write ahead log and prepares the head for writes.
// It should be called before using an appender so that
// limits the ingested samples to the head min valid time.
|
[
"Init",
"loads",
"data",
"from",
"the",
"write",
"ahead",
"log",
"and",
"prepares",
"the",
"head",
"for",
"writes",
".",
"It",
"should",
"be",
"called",
"before",
"using",
"an",
"appender",
"so",
"that",
"limits",
"the",
"ingested",
"samples",
"to",
"the",
"head",
"min",
"valid",
"time",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L462-L508
|
train
|
prometheus/tsdb
|
head.go
|
initTime
|
func (h *Head) initTime(t int64) (initialized bool) {
if !atomic.CompareAndSwapInt64(&h.minTime, math.MaxInt64, t) {
return false
}
// Ensure that max time is initialized to at least the min time we just set.
// Concurrent appenders may already have set it to a higher value.
atomic.CompareAndSwapInt64(&h.maxTime, math.MinInt64, t)
return true
}
|
go
|
func (h *Head) initTime(t int64) (initialized bool) {
if !atomic.CompareAndSwapInt64(&h.minTime, math.MaxInt64, t) {
return false
}
// Ensure that max time is initialized to at least the min time we just set.
// Concurrent appenders may already have set it to a higher value.
atomic.CompareAndSwapInt64(&h.maxTime, math.MinInt64, t)
return true
}
|
[
"func",
"(",
"h",
"*",
"Head",
")",
"initTime",
"(",
"t",
"int64",
")",
"(",
"initialized",
"bool",
")",
"{",
"if",
"!",
"atomic",
".",
"CompareAndSwapInt64",
"(",
"&",
"h",
".",
"minTime",
",",
"math",
".",
"MaxInt64",
",",
"t",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"// Ensure that max time is initialized to at least the min time we just set.",
"// Concurrent appenders may already have set it to a higher value.",
"atomic",
".",
"CompareAndSwapInt64",
"(",
"&",
"h",
".",
"maxTime",
",",
"math",
".",
"MinInt64",
",",
"t",
")",
"\n\n",
"return",
"true",
"\n",
"}"
] |
// initTime initializes a head with the first timestamp. This only needs to be called
// for a completely fresh head with an empty WAL.
// Returns true if the initialization took an effect.
|
[
"initTime",
"initializes",
"a",
"head",
"with",
"the",
"first",
"timestamp",
".",
"This",
"only",
"needs",
"to",
"be",
"called",
"for",
"a",
"completely",
"fresh",
"head",
"with",
"an",
"empty",
"WAL",
".",
"Returns",
"true",
"if",
"the",
"initialization",
"took",
"an",
"effect",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L613-L622
|
train
|
prometheus/tsdb
|
head.go
|
Appender
|
func (h *Head) Appender() Appender {
h.metrics.activeAppenders.Inc()
// The head cache might not have a starting point yet. The init appender
// picks up the first appended timestamp as the base.
if h.MinTime() == math.MaxInt64 {
return &initAppender{head: h}
}
return h.appender()
}
|
go
|
func (h *Head) Appender() Appender {
h.metrics.activeAppenders.Inc()
// The head cache might not have a starting point yet. The init appender
// picks up the first appended timestamp as the base.
if h.MinTime() == math.MaxInt64 {
return &initAppender{head: h}
}
return h.appender()
}
|
[
"func",
"(",
"h",
"*",
"Head",
")",
"Appender",
"(",
")",
"Appender",
"{",
"h",
".",
"metrics",
".",
"activeAppenders",
".",
"Inc",
"(",
")",
"\n\n",
"// The head cache might not have a starting point yet. The init appender",
"// picks up the first appended timestamp as the base.",
"if",
"h",
".",
"MinTime",
"(",
")",
"==",
"math",
".",
"MaxInt64",
"{",
"return",
"&",
"initAppender",
"{",
"head",
":",
"h",
"}",
"\n",
"}",
"\n",
"return",
"h",
".",
"appender",
"(",
")",
"\n",
"}"
] |
// Appender returns a new Appender on the database.
|
[
"Appender",
"returns",
"a",
"new",
"Appender",
"on",
"the",
"database",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L688-L697
|
train
|
prometheus/tsdb
|
head.go
|
chunkRewrite
|
func (h *Head) chunkRewrite(ref uint64, dranges Intervals) (err error) {
if len(dranges) == 0 {
return nil
}
ms := h.series.getByID(ref)
ms.Lock()
defer ms.Unlock()
if len(ms.chunks) == 0 {
return nil
}
metas := ms.chunksMetas()
mint, maxt := metas[0].MinTime, metas[len(metas)-1].MaxTime
it := newChunkSeriesIterator(metas, dranges, mint, maxt)
ms.reset()
for it.Next() {
t, v := it.At()
ok, _ := ms.append(t, v)
if !ok {
level.Warn(h.logger).Log("msg", "failed to add sample during delete")
}
}
return nil
}
|
go
|
func (h *Head) chunkRewrite(ref uint64, dranges Intervals) (err error) {
if len(dranges) == 0 {
return nil
}
ms := h.series.getByID(ref)
ms.Lock()
defer ms.Unlock()
if len(ms.chunks) == 0 {
return nil
}
metas := ms.chunksMetas()
mint, maxt := metas[0].MinTime, metas[len(metas)-1].MaxTime
it := newChunkSeriesIterator(metas, dranges, mint, maxt)
ms.reset()
for it.Next() {
t, v := it.At()
ok, _ := ms.append(t, v)
if !ok {
level.Warn(h.logger).Log("msg", "failed to add sample during delete")
}
}
return nil
}
|
[
"func",
"(",
"h",
"*",
"Head",
")",
"chunkRewrite",
"(",
"ref",
"uint64",
",",
"dranges",
"Intervals",
")",
"(",
"err",
"error",
")",
"{",
"if",
"len",
"(",
"dranges",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"ms",
":=",
"h",
".",
"series",
".",
"getByID",
"(",
"ref",
")",
"\n",
"ms",
".",
"Lock",
"(",
")",
"\n",
"defer",
"ms",
".",
"Unlock",
"(",
")",
"\n",
"if",
"len",
"(",
"ms",
".",
"chunks",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"metas",
":=",
"ms",
".",
"chunksMetas",
"(",
")",
"\n",
"mint",
",",
"maxt",
":=",
"metas",
"[",
"0",
"]",
".",
"MinTime",
",",
"metas",
"[",
"len",
"(",
"metas",
")",
"-",
"1",
"]",
".",
"MaxTime",
"\n",
"it",
":=",
"newChunkSeriesIterator",
"(",
"metas",
",",
"dranges",
",",
"mint",
",",
"maxt",
")",
"\n\n",
"ms",
".",
"reset",
"(",
")",
"\n",
"for",
"it",
".",
"Next",
"(",
")",
"{",
"t",
",",
"v",
":=",
"it",
".",
"At",
"(",
")",
"\n",
"ok",
",",
"_",
":=",
"ms",
".",
"append",
"(",
"t",
",",
"v",
")",
"\n",
"if",
"!",
"ok",
"{",
"level",
".",
"Warn",
"(",
"h",
".",
"logger",
")",
".",
"Log",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// chunkRewrite re-writes the chunks which overlaps with deleted ranges
// and removes the samples in the deleted ranges.
// Chunks is deleted if no samples are left at the end.
|
[
"chunkRewrite",
"re",
"-",
"writes",
"the",
"chunks",
"which",
"overlaps",
"with",
"deleted",
"ranges",
"and",
"removes",
"the",
"samples",
"in",
"the",
"deleted",
"ranges",
".",
"Chunks",
"is",
"deleted",
"if",
"no",
"samples",
"are",
"left",
"at",
"the",
"end",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L931-L957
|
train
|
prometheus/tsdb
|
head.go
|
gc
|
func (h *Head) gc() {
// Only data strictly lower than this timestamp must be deleted.
mint := h.MinTime()
// Drop old chunks and remember series IDs and hashes if they can be
// deleted entirely.
deleted, chunksRemoved := h.series.gc(mint)
seriesRemoved := len(deleted)
h.metrics.seriesRemoved.Add(float64(seriesRemoved))
h.metrics.series.Sub(float64(seriesRemoved))
h.metrics.chunksRemoved.Add(float64(chunksRemoved))
h.metrics.chunks.Sub(float64(chunksRemoved))
// Remove deleted series IDs from the postings lists.
h.postings.Delete(deleted)
if h.wal != nil {
_, last, _ := h.wal.Segments()
h.deletedMtx.Lock()
// Keep series records until we're past segment 'last'
// because the WAL will still have samples records with
// this ref ID. If we didn't keep these series records then
// on start up when we replay the WAL, or any other code
// that reads the WAL, wouldn't be able to use those
// samples since we would have no labels for that ref ID.
for ref := range deleted {
h.deleted[ref] = last
}
h.deletedMtx.Unlock()
}
// Rebuild symbols and label value indices from what is left in the postings terms.
symbols := make(map[string]struct{}, len(h.symbols))
values := make(map[string]stringset, len(h.values))
if err := h.postings.Iter(func(t labels.Label, _ index.Postings) error {
symbols[t.Name] = struct{}{}
symbols[t.Value] = struct{}{}
ss, ok := values[t.Name]
if !ok {
ss = stringset{}
values[t.Name] = ss
}
ss.set(t.Value)
return nil
}); err != nil {
// This should never happen, as the iteration function only returns nil.
panic(err)
}
h.symMtx.Lock()
h.symbols = symbols
h.values = values
h.symMtx.Unlock()
}
|
go
|
func (h *Head) gc() {
// Only data strictly lower than this timestamp must be deleted.
mint := h.MinTime()
// Drop old chunks and remember series IDs and hashes if they can be
// deleted entirely.
deleted, chunksRemoved := h.series.gc(mint)
seriesRemoved := len(deleted)
h.metrics.seriesRemoved.Add(float64(seriesRemoved))
h.metrics.series.Sub(float64(seriesRemoved))
h.metrics.chunksRemoved.Add(float64(chunksRemoved))
h.metrics.chunks.Sub(float64(chunksRemoved))
// Remove deleted series IDs from the postings lists.
h.postings.Delete(deleted)
if h.wal != nil {
_, last, _ := h.wal.Segments()
h.deletedMtx.Lock()
// Keep series records until we're past segment 'last'
// because the WAL will still have samples records with
// this ref ID. If we didn't keep these series records then
// on start up when we replay the WAL, or any other code
// that reads the WAL, wouldn't be able to use those
// samples since we would have no labels for that ref ID.
for ref := range deleted {
h.deleted[ref] = last
}
h.deletedMtx.Unlock()
}
// Rebuild symbols and label value indices from what is left in the postings terms.
symbols := make(map[string]struct{}, len(h.symbols))
values := make(map[string]stringset, len(h.values))
if err := h.postings.Iter(func(t labels.Label, _ index.Postings) error {
symbols[t.Name] = struct{}{}
symbols[t.Value] = struct{}{}
ss, ok := values[t.Name]
if !ok {
ss = stringset{}
values[t.Name] = ss
}
ss.set(t.Value)
return nil
}); err != nil {
// This should never happen, as the iteration function only returns nil.
panic(err)
}
h.symMtx.Lock()
h.symbols = symbols
h.values = values
h.symMtx.Unlock()
}
|
[
"func",
"(",
"h",
"*",
"Head",
")",
"gc",
"(",
")",
"{",
"// Only data strictly lower than this timestamp must be deleted.",
"mint",
":=",
"h",
".",
"MinTime",
"(",
")",
"\n\n",
"// Drop old chunks and remember series IDs and hashes if they can be",
"// deleted entirely.",
"deleted",
",",
"chunksRemoved",
":=",
"h",
".",
"series",
".",
"gc",
"(",
"mint",
")",
"\n",
"seriesRemoved",
":=",
"len",
"(",
"deleted",
")",
"\n\n",
"h",
".",
"metrics",
".",
"seriesRemoved",
".",
"Add",
"(",
"float64",
"(",
"seriesRemoved",
")",
")",
"\n",
"h",
".",
"metrics",
".",
"series",
".",
"Sub",
"(",
"float64",
"(",
"seriesRemoved",
")",
")",
"\n",
"h",
".",
"metrics",
".",
"chunksRemoved",
".",
"Add",
"(",
"float64",
"(",
"chunksRemoved",
")",
")",
"\n",
"h",
".",
"metrics",
".",
"chunks",
".",
"Sub",
"(",
"float64",
"(",
"chunksRemoved",
")",
")",
"\n\n",
"// Remove deleted series IDs from the postings lists.",
"h",
".",
"postings",
".",
"Delete",
"(",
"deleted",
")",
"\n\n",
"if",
"h",
".",
"wal",
"!=",
"nil",
"{",
"_",
",",
"last",
",",
"_",
":=",
"h",
".",
"wal",
".",
"Segments",
"(",
")",
"\n",
"h",
".",
"deletedMtx",
".",
"Lock",
"(",
")",
"\n",
"// Keep series records until we're past segment 'last'",
"// because the WAL will still have samples records with",
"// this ref ID. If we didn't keep these series records then",
"// on start up when we replay the WAL, or any other code",
"// that reads the WAL, wouldn't be able to use those",
"// samples since we would have no labels for that ref ID.",
"for",
"ref",
":=",
"range",
"deleted",
"{",
"h",
".",
"deleted",
"[",
"ref",
"]",
"=",
"last",
"\n",
"}",
"\n",
"h",
".",
"deletedMtx",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n\n",
"// Rebuild symbols and label value indices from what is left in the postings terms.",
"symbols",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
",",
"len",
"(",
"h",
".",
"symbols",
")",
")",
"\n",
"values",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"stringset",
",",
"len",
"(",
"h",
".",
"values",
")",
")",
"\n\n",
"if",
"err",
":=",
"h",
".",
"postings",
".",
"Iter",
"(",
"func",
"(",
"t",
"labels",
".",
"Label",
",",
"_",
"index",
".",
"Postings",
")",
"error",
"{",
"symbols",
"[",
"t",
".",
"Name",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"symbols",
"[",
"t",
".",
"Value",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n\n",
"ss",
",",
"ok",
":=",
"values",
"[",
"t",
".",
"Name",
"]",
"\n",
"if",
"!",
"ok",
"{",
"ss",
"=",
"stringset",
"{",
"}",
"\n",
"values",
"[",
"t",
".",
"Name",
"]",
"=",
"ss",
"\n",
"}",
"\n",
"ss",
".",
"set",
"(",
"t",
".",
"Value",
")",
"\n",
"return",
"nil",
"\n",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"// This should never happen, as the iteration function only returns nil.",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"h",
".",
"symMtx",
".",
"Lock",
"(",
")",
"\n\n",
"h",
".",
"symbols",
"=",
"symbols",
"\n",
"h",
".",
"values",
"=",
"values",
"\n\n",
"h",
".",
"symMtx",
".",
"Unlock",
"(",
")",
"\n",
"}"
] |
// gc removes data before the minimum timestamp from the head.
|
[
"gc",
"removes",
"data",
"before",
"the",
"minimum",
"timestamp",
"from",
"the",
"head",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L960-L1018
|
train
|
prometheus/tsdb
|
head.go
|
Index
|
func (h *Head) Index() (IndexReader, error) {
return h.indexRange(math.MinInt64, math.MaxInt64), nil
}
|
go
|
func (h *Head) Index() (IndexReader, error) {
return h.indexRange(math.MinInt64, math.MaxInt64), nil
}
|
[
"func",
"(",
"h",
"*",
"Head",
")",
"Index",
"(",
")",
"(",
"IndexReader",
",",
"error",
")",
"{",
"return",
"h",
".",
"indexRange",
"(",
"math",
".",
"MinInt64",
",",
"math",
".",
"MaxInt64",
")",
",",
"nil",
"\n",
"}"
] |
// Index returns an IndexReader against the block.
|
[
"Index",
"returns",
"an",
"IndexReader",
"against",
"the",
"block",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L1026-L1028
|
train
|
prometheus/tsdb
|
head.go
|
Chunks
|
func (h *Head) Chunks() (ChunkReader, error) {
return h.chunksRange(math.MinInt64, math.MaxInt64), nil
}
|
go
|
func (h *Head) Chunks() (ChunkReader, error) {
return h.chunksRange(math.MinInt64, math.MaxInt64), nil
}
|
[
"func",
"(",
"h",
"*",
"Head",
")",
"Chunks",
"(",
")",
"(",
"ChunkReader",
",",
"error",
")",
"{",
"return",
"h",
".",
"chunksRange",
"(",
"math",
".",
"MinInt64",
",",
"math",
".",
"MaxInt64",
")",
",",
"nil",
"\n",
"}"
] |
// Chunks returns a ChunkReader against the block.
|
[
"Chunks",
"returns",
"a",
"ChunkReader",
"against",
"the",
"block",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L1038-L1040
|
train
|
prometheus/tsdb
|
head.go
|
compactable
|
func (h *Head) compactable() bool {
return h.MaxTime()-h.MinTime() > h.chunkRange/2*3
}
|
go
|
func (h *Head) compactable() bool {
return h.MaxTime()-h.MinTime() > h.chunkRange/2*3
}
|
[
"func",
"(",
"h",
"*",
"Head",
")",
"compactable",
"(",
")",
"bool",
"{",
"return",
"h",
".",
"MaxTime",
"(",
")",
"-",
"h",
".",
"MinTime",
"(",
")",
">",
"h",
".",
"chunkRange",
"/",
"2",
"*",
"3",
"\n",
"}"
] |
// compactable returns whether the head has a compactable range.
// The head has a compactable range when the head time range is 1.5 times the chunk range.
// The 0.5 acts as a buffer of the appendable window.
|
[
"compactable",
"returns",
"whether",
"the",
"head",
"has",
"a",
"compactable",
"range",
".",
"The",
"head",
"has",
"a",
"compactable",
"range",
"when",
"the",
"head",
"time",
"range",
"is",
"1",
".",
"5",
"times",
"the",
"chunk",
"range",
".",
"The",
"0",
".",
"5",
"acts",
"as",
"a",
"buffer",
"of",
"the",
"appendable",
"window",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L1062-L1064
|
train
|
prometheus/tsdb
|
head.go
|
Close
|
func (h *Head) Close() error {
if h.wal == nil {
return nil
}
return h.wal.Close()
}
|
go
|
func (h *Head) Close() error {
if h.wal == nil {
return nil
}
return h.wal.Close()
}
|
[
"func",
"(",
"h",
"*",
"Head",
")",
"Close",
"(",
")",
"error",
"{",
"if",
"h",
".",
"wal",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"h",
".",
"wal",
".",
"Close",
"(",
")",
"\n",
"}"
] |
// Close flushes the WAL and closes the head.
|
[
"Close",
"flushes",
"the",
"WAL",
"and",
"closes",
"the",
"head",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L1067-L1072
|
train
|
prometheus/tsdb
|
head.go
|
packChunkID
|
func packChunkID(seriesID, chunkID uint64) uint64 {
if seriesID > (1<<40)-1 {
panic("series ID exceeds 5 bytes")
}
if chunkID > (1<<24)-1 {
panic("chunk ID exceeds 3 bytes")
}
return (seriesID << 24) | chunkID
}
|
go
|
func packChunkID(seriesID, chunkID uint64) uint64 {
if seriesID > (1<<40)-1 {
panic("series ID exceeds 5 bytes")
}
if chunkID > (1<<24)-1 {
panic("chunk ID exceeds 3 bytes")
}
return (seriesID << 24) | chunkID
}
|
[
"func",
"packChunkID",
"(",
"seriesID",
",",
"chunkID",
"uint64",
")",
"uint64",
"{",
"if",
"seriesID",
">",
"(",
"1",
"<<",
"40",
")",
"-",
"1",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"chunkID",
">",
"(",
"1",
"<<",
"24",
")",
"-",
"1",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"(",
"seriesID",
"<<",
"24",
")",
"|",
"chunkID",
"\n",
"}"
] |
// packChunkID packs a seriesID and a chunkID within it into a global 8 byte ID.
// It panicks if the seriesID exceeds 5 bytes or the chunk ID 3 bytes.
|
[
"packChunkID",
"packs",
"a",
"seriesID",
"and",
"a",
"chunkID",
"within",
"it",
"into",
"a",
"global",
"8",
"byte",
"ID",
".",
"It",
"panicks",
"if",
"the",
"seriesID",
"exceeds",
"5",
"bytes",
"or",
"the",
"chunk",
"ID",
"3",
"bytes",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L1085-L1093
|
train
|
prometheus/tsdb
|
head.go
|
Chunk
|
func (h *headChunkReader) Chunk(ref uint64) (chunkenc.Chunk, error) {
sid, cid := unpackChunkID(ref)
s := h.head.series.getByID(sid)
// This means that the series has been garbage collected.
if s == nil {
return nil, ErrNotFound
}
s.Lock()
c := s.chunk(int(cid))
// This means that the chunk has been garbage collected or is outside
// the specified range.
if c == nil || !c.OverlapsClosedInterval(h.mint, h.maxt) {
s.Unlock()
return nil, ErrNotFound
}
s.Unlock()
return &safeChunk{
Chunk: c.chunk,
s: s,
cid: int(cid),
}, nil
}
|
go
|
func (h *headChunkReader) Chunk(ref uint64) (chunkenc.Chunk, error) {
sid, cid := unpackChunkID(ref)
s := h.head.series.getByID(sid)
// This means that the series has been garbage collected.
if s == nil {
return nil, ErrNotFound
}
s.Lock()
c := s.chunk(int(cid))
// This means that the chunk has been garbage collected or is outside
// the specified range.
if c == nil || !c.OverlapsClosedInterval(h.mint, h.maxt) {
s.Unlock()
return nil, ErrNotFound
}
s.Unlock()
return &safeChunk{
Chunk: c.chunk,
s: s,
cid: int(cid),
}, nil
}
|
[
"func",
"(",
"h",
"*",
"headChunkReader",
")",
"Chunk",
"(",
"ref",
"uint64",
")",
"(",
"chunkenc",
".",
"Chunk",
",",
"error",
")",
"{",
"sid",
",",
"cid",
":=",
"unpackChunkID",
"(",
"ref",
")",
"\n\n",
"s",
":=",
"h",
".",
"head",
".",
"series",
".",
"getByID",
"(",
"sid",
")",
"\n",
"// This means that the series has been garbage collected.",
"if",
"s",
"==",
"nil",
"{",
"return",
"nil",
",",
"ErrNotFound",
"\n",
"}",
"\n\n",
"s",
".",
"Lock",
"(",
")",
"\n",
"c",
":=",
"s",
".",
"chunk",
"(",
"int",
"(",
"cid",
")",
")",
"\n\n",
"// This means that the chunk has been garbage collected or is outside",
"// the specified range.",
"if",
"c",
"==",
"nil",
"||",
"!",
"c",
".",
"OverlapsClosedInterval",
"(",
"h",
".",
"mint",
",",
"h",
".",
"maxt",
")",
"{",
"s",
".",
"Unlock",
"(",
")",
"\n",
"return",
"nil",
",",
"ErrNotFound",
"\n",
"}",
"\n",
"s",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"&",
"safeChunk",
"{",
"Chunk",
":",
"c",
".",
"chunk",
",",
"s",
":",
"s",
",",
"cid",
":",
"int",
"(",
"cid",
")",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// Chunk returns the chunk for the reference number.
|
[
"Chunk",
"returns",
"the",
"chunk",
"for",
"the",
"reference",
"number",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L1100-L1125
|
train
|
prometheus/tsdb
|
head.go
|
LabelValues
|
func (h *headIndexReader) LabelValues(names ...string) (index.StringTuples, error) {
if len(names) != 1 {
return nil, encoding.ErrInvalidSize
}
h.head.symMtx.RLock()
sl := make([]string, 0, len(h.head.values[names[0]]))
for s := range h.head.values[names[0]] {
sl = append(sl, s)
}
h.head.symMtx.RUnlock()
sort.Strings(sl)
return index.NewStringTuples(sl, len(names))
}
|
go
|
func (h *headIndexReader) LabelValues(names ...string) (index.StringTuples, error) {
if len(names) != 1 {
return nil, encoding.ErrInvalidSize
}
h.head.symMtx.RLock()
sl := make([]string, 0, len(h.head.values[names[0]]))
for s := range h.head.values[names[0]] {
sl = append(sl, s)
}
h.head.symMtx.RUnlock()
sort.Strings(sl)
return index.NewStringTuples(sl, len(names))
}
|
[
"func",
"(",
"h",
"*",
"headIndexReader",
")",
"LabelValues",
"(",
"names",
"...",
"string",
")",
"(",
"index",
".",
"StringTuples",
",",
"error",
")",
"{",
"if",
"len",
"(",
"names",
")",
"!=",
"1",
"{",
"return",
"nil",
",",
"encoding",
".",
"ErrInvalidSize",
"\n",
"}",
"\n\n",
"h",
".",
"head",
".",
"symMtx",
".",
"RLock",
"(",
")",
"\n",
"sl",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"h",
".",
"head",
".",
"values",
"[",
"names",
"[",
"0",
"]",
"]",
")",
")",
"\n",
"for",
"s",
":=",
"range",
"h",
".",
"head",
".",
"values",
"[",
"names",
"[",
"0",
"]",
"]",
"{",
"sl",
"=",
"append",
"(",
"sl",
",",
"s",
")",
"\n",
"}",
"\n",
"h",
".",
"head",
".",
"symMtx",
".",
"RUnlock",
"(",
")",
"\n",
"sort",
".",
"Strings",
"(",
"sl",
")",
"\n\n",
"return",
"index",
".",
"NewStringTuples",
"(",
"sl",
",",
"len",
"(",
"names",
")",
")",
"\n",
"}"
] |
// LabelValues returns the possible label values
|
[
"LabelValues",
"returns",
"the",
"possible",
"label",
"values"
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L1162-L1176
|
train
|
prometheus/tsdb
|
head.go
|
LabelNames
|
func (h *headIndexReader) LabelNames() ([]string, error) {
h.head.symMtx.RLock()
defer h.head.symMtx.RUnlock()
labelNames := make([]string, 0, len(h.head.values))
for name := range h.head.values {
if name == "" {
continue
}
labelNames = append(labelNames, name)
}
sort.Strings(labelNames)
return labelNames, nil
}
|
go
|
func (h *headIndexReader) LabelNames() ([]string, error) {
h.head.symMtx.RLock()
defer h.head.symMtx.RUnlock()
labelNames := make([]string, 0, len(h.head.values))
for name := range h.head.values {
if name == "" {
continue
}
labelNames = append(labelNames, name)
}
sort.Strings(labelNames)
return labelNames, nil
}
|
[
"func",
"(",
"h",
"*",
"headIndexReader",
")",
"LabelNames",
"(",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"h",
".",
"head",
".",
"symMtx",
".",
"RLock",
"(",
")",
"\n",
"defer",
"h",
".",
"head",
".",
"symMtx",
".",
"RUnlock",
"(",
")",
"\n",
"labelNames",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"h",
".",
"head",
".",
"values",
")",
")",
"\n",
"for",
"name",
":=",
"range",
"h",
".",
"head",
".",
"values",
"{",
"if",
"name",
"==",
"\"",
"\"",
"{",
"continue",
"\n",
"}",
"\n",
"labelNames",
"=",
"append",
"(",
"labelNames",
",",
"name",
")",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"labelNames",
")",
"\n",
"return",
"labelNames",
",",
"nil",
"\n",
"}"
] |
// LabelNames returns all the unique label names present in the head.
|
[
"LabelNames",
"returns",
"all",
"the",
"unique",
"label",
"names",
"present",
"in",
"the",
"head",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L1179-L1191
|
train
|
prometheus/tsdb
|
head.go
|
Postings
|
func (h *headIndexReader) Postings(name, value string) (index.Postings, error) {
return h.head.postings.Get(name, value), nil
}
|
go
|
func (h *headIndexReader) Postings(name, value string) (index.Postings, error) {
return h.head.postings.Get(name, value), nil
}
|
[
"func",
"(",
"h",
"*",
"headIndexReader",
")",
"Postings",
"(",
"name",
",",
"value",
"string",
")",
"(",
"index",
".",
"Postings",
",",
"error",
")",
"{",
"return",
"h",
".",
"head",
".",
"postings",
".",
"Get",
"(",
"name",
",",
"value",
")",
",",
"nil",
"\n",
"}"
] |
// Postings returns the postings list iterator for the label pair.
|
[
"Postings",
"returns",
"the",
"postings",
"list",
"iterator",
"for",
"the",
"label",
"pair",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L1194-L1196
|
train
|
prometheus/tsdb
|
head.go
|
Series
|
func (h *headIndexReader) Series(ref uint64, lbls *labels.Labels, chks *[]chunks.Meta) error {
s := h.head.series.getByID(ref)
if s == nil {
h.head.metrics.seriesNotFound.Inc()
return ErrNotFound
}
*lbls = append((*lbls)[:0], s.lset...)
s.Lock()
defer s.Unlock()
*chks = (*chks)[:0]
for i, c := range s.chunks {
// Do not expose chunks that are outside of the specified range.
if !c.OverlapsClosedInterval(h.mint, h.maxt) {
continue
}
*chks = append(*chks, chunks.Meta{
MinTime: c.minTime,
MaxTime: c.maxTime,
Ref: packChunkID(s.ref, uint64(s.chunkID(i))),
})
}
return nil
}
|
go
|
func (h *headIndexReader) Series(ref uint64, lbls *labels.Labels, chks *[]chunks.Meta) error {
s := h.head.series.getByID(ref)
if s == nil {
h.head.metrics.seriesNotFound.Inc()
return ErrNotFound
}
*lbls = append((*lbls)[:0], s.lset...)
s.Lock()
defer s.Unlock()
*chks = (*chks)[:0]
for i, c := range s.chunks {
// Do not expose chunks that are outside of the specified range.
if !c.OverlapsClosedInterval(h.mint, h.maxt) {
continue
}
*chks = append(*chks, chunks.Meta{
MinTime: c.minTime,
MaxTime: c.maxTime,
Ref: packChunkID(s.ref, uint64(s.chunkID(i))),
})
}
return nil
}
|
[
"func",
"(",
"h",
"*",
"headIndexReader",
")",
"Series",
"(",
"ref",
"uint64",
",",
"lbls",
"*",
"labels",
".",
"Labels",
",",
"chks",
"*",
"[",
"]",
"chunks",
".",
"Meta",
")",
"error",
"{",
"s",
":=",
"h",
".",
"head",
".",
"series",
".",
"getByID",
"(",
"ref",
")",
"\n\n",
"if",
"s",
"==",
"nil",
"{",
"h",
".",
"head",
".",
"metrics",
".",
"seriesNotFound",
".",
"Inc",
"(",
")",
"\n",
"return",
"ErrNotFound",
"\n",
"}",
"\n",
"*",
"lbls",
"=",
"append",
"(",
"(",
"*",
"lbls",
")",
"[",
":",
"0",
"]",
",",
"s",
".",
"lset",
"...",
")",
"\n\n",
"s",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"Unlock",
"(",
")",
"\n\n",
"*",
"chks",
"=",
"(",
"*",
"chks",
")",
"[",
":",
"0",
"]",
"\n\n",
"for",
"i",
",",
"c",
":=",
"range",
"s",
".",
"chunks",
"{",
"// Do not expose chunks that are outside of the specified range.",
"if",
"!",
"c",
".",
"OverlapsClosedInterval",
"(",
"h",
".",
"mint",
",",
"h",
".",
"maxt",
")",
"{",
"continue",
"\n",
"}",
"\n",
"*",
"chks",
"=",
"append",
"(",
"*",
"chks",
",",
"chunks",
".",
"Meta",
"{",
"MinTime",
":",
"c",
".",
"minTime",
",",
"MaxTime",
":",
"c",
".",
"maxTime",
",",
"Ref",
":",
"packChunkID",
"(",
"s",
".",
"ref",
",",
"uint64",
"(",
"s",
".",
"chunkID",
"(",
"i",
")",
")",
")",
",",
"}",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Series returns the series for the given reference.
|
[
"Series",
"returns",
"the",
"series",
"for",
"the",
"given",
"reference",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L1227-L1254
|
train
|
prometheus/tsdb
|
head.go
|
gc
|
func (s *stripeSeries) gc(mint int64) (map[uint64]struct{}, int) {
var (
deleted = map[uint64]struct{}{}
rmChunks = 0
)
// Run through all series and truncate old chunks. Mark those with no
// chunks left as deleted and store their ID.
for i := 0; i < stripeSize; i++ {
s.locks[i].Lock()
for hash, all := range s.hashes[i] {
for _, series := range all {
series.Lock()
rmChunks += series.truncateChunksBefore(mint)
if len(series.chunks) > 0 || series.pendingCommit {
series.Unlock()
continue
}
// The series is gone entirely. We need to keep the series lock
// and make sure we have acquired the stripe locks for hash and ID of the
// series alike.
// If we don't hold them all, there's a very small chance that a series receives
// samples again while we are half-way into deleting it.
j := int(series.ref & stripeMask)
if i != j {
s.locks[j].Lock()
}
deleted[series.ref] = struct{}{}
s.hashes[i].del(hash, series.lset)
delete(s.series[j], series.ref)
if i != j {
s.locks[j].Unlock()
}
series.Unlock()
}
}
s.locks[i].Unlock()
}
return deleted, rmChunks
}
|
go
|
func (s *stripeSeries) gc(mint int64) (map[uint64]struct{}, int) {
var (
deleted = map[uint64]struct{}{}
rmChunks = 0
)
// Run through all series and truncate old chunks. Mark those with no
// chunks left as deleted and store their ID.
for i := 0; i < stripeSize; i++ {
s.locks[i].Lock()
for hash, all := range s.hashes[i] {
for _, series := range all {
series.Lock()
rmChunks += series.truncateChunksBefore(mint)
if len(series.chunks) > 0 || series.pendingCommit {
series.Unlock()
continue
}
// The series is gone entirely. We need to keep the series lock
// and make sure we have acquired the stripe locks for hash and ID of the
// series alike.
// If we don't hold them all, there's a very small chance that a series receives
// samples again while we are half-way into deleting it.
j := int(series.ref & stripeMask)
if i != j {
s.locks[j].Lock()
}
deleted[series.ref] = struct{}{}
s.hashes[i].del(hash, series.lset)
delete(s.series[j], series.ref)
if i != j {
s.locks[j].Unlock()
}
series.Unlock()
}
}
s.locks[i].Unlock()
}
return deleted, rmChunks
}
|
[
"func",
"(",
"s",
"*",
"stripeSeries",
")",
"gc",
"(",
"mint",
"int64",
")",
"(",
"map",
"[",
"uint64",
"]",
"struct",
"{",
"}",
",",
"int",
")",
"{",
"var",
"(",
"deleted",
"=",
"map",
"[",
"uint64",
"]",
"struct",
"{",
"}",
"{",
"}",
"\n",
"rmChunks",
"=",
"0",
"\n",
")",
"\n",
"// Run through all series and truncate old chunks. Mark those with no",
"// chunks left as deleted and store their ID.",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"stripeSize",
";",
"i",
"++",
"{",
"s",
".",
"locks",
"[",
"i",
"]",
".",
"Lock",
"(",
")",
"\n\n",
"for",
"hash",
",",
"all",
":=",
"range",
"s",
".",
"hashes",
"[",
"i",
"]",
"{",
"for",
"_",
",",
"series",
":=",
"range",
"all",
"{",
"series",
".",
"Lock",
"(",
")",
"\n",
"rmChunks",
"+=",
"series",
".",
"truncateChunksBefore",
"(",
"mint",
")",
"\n\n",
"if",
"len",
"(",
"series",
".",
"chunks",
")",
">",
"0",
"||",
"series",
".",
"pendingCommit",
"{",
"series",
".",
"Unlock",
"(",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"// The series is gone entirely. We need to keep the series lock",
"// and make sure we have acquired the stripe locks for hash and ID of the",
"// series alike.",
"// If we don't hold them all, there's a very small chance that a series receives",
"// samples again while we are half-way into deleting it.",
"j",
":=",
"int",
"(",
"series",
".",
"ref",
"&",
"stripeMask",
")",
"\n\n",
"if",
"i",
"!=",
"j",
"{",
"s",
".",
"locks",
"[",
"j",
"]",
".",
"Lock",
"(",
")",
"\n",
"}",
"\n\n",
"deleted",
"[",
"series",
".",
"ref",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"s",
".",
"hashes",
"[",
"i",
"]",
".",
"del",
"(",
"hash",
",",
"series",
".",
"lset",
")",
"\n",
"delete",
"(",
"s",
".",
"series",
"[",
"j",
"]",
",",
"series",
".",
"ref",
")",
"\n\n",
"if",
"i",
"!=",
"j",
"{",
"s",
".",
"locks",
"[",
"j",
"]",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n\n",
"series",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"s",
".",
"locks",
"[",
"i",
"]",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"deleted",
",",
"rmChunks",
"\n",
"}"
] |
// gc garbage collects old chunks that are strictly before mint and removes
// series entirely that have no chunks left.
|
[
"gc",
"garbage",
"collects",
"old",
"chunks",
"that",
"are",
"strictly",
"before",
"mint",
"and",
"removes",
"series",
"entirely",
"that",
"have",
"no",
"chunks",
"left",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L1387-L1434
|
train
|
prometheus/tsdb
|
head.go
|
appendable
|
func (s *memSeries) appendable(t int64, v float64) error {
c := s.head()
if c == nil {
return nil
}
if t > c.maxTime {
return nil
}
if t < c.maxTime {
return ErrOutOfOrderSample
}
// We are allowing exact duplicates as we can encounter them in valid cases
// like federation and erroring out at that time would be extremely noisy.
if math.Float64bits(s.sampleBuf[3].v) != math.Float64bits(v) {
return ErrAmendSample
}
return nil
}
|
go
|
func (s *memSeries) appendable(t int64, v float64) error {
c := s.head()
if c == nil {
return nil
}
if t > c.maxTime {
return nil
}
if t < c.maxTime {
return ErrOutOfOrderSample
}
// We are allowing exact duplicates as we can encounter them in valid cases
// like federation and erroring out at that time would be extremely noisy.
if math.Float64bits(s.sampleBuf[3].v) != math.Float64bits(v) {
return ErrAmendSample
}
return nil
}
|
[
"func",
"(",
"s",
"*",
"memSeries",
")",
"appendable",
"(",
"t",
"int64",
",",
"v",
"float64",
")",
"error",
"{",
"c",
":=",
"s",
".",
"head",
"(",
")",
"\n",
"if",
"c",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"if",
"t",
">",
"c",
".",
"maxTime",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"t",
"<",
"c",
".",
"maxTime",
"{",
"return",
"ErrOutOfOrderSample",
"\n",
"}",
"\n",
"// We are allowing exact duplicates as we can encounter them in valid cases",
"// like federation and erroring out at that time would be extremely noisy.",
"if",
"math",
".",
"Float64bits",
"(",
"s",
".",
"sampleBuf",
"[",
"3",
"]",
".",
"v",
")",
"!=",
"math",
".",
"Float64bits",
"(",
"v",
")",
"{",
"return",
"ErrAmendSample",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// appendable checks whether the given sample is valid for appending to the series.
|
[
"appendable",
"checks",
"whether",
"the",
"given",
"sample",
"is",
"valid",
"for",
"appending",
"to",
"the",
"series",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L1576-L1594
|
train
|
prometheus/tsdb
|
head.go
|
truncateChunksBefore
|
func (s *memSeries) truncateChunksBefore(mint int64) (removed int) {
var k int
for i, c := range s.chunks {
if c.maxTime >= mint {
break
}
k = i + 1
}
s.chunks = append(s.chunks[:0], s.chunks[k:]...)
s.firstChunkID += k
if len(s.chunks) == 0 {
s.headChunk = nil
} else {
s.headChunk = s.chunks[len(s.chunks)-1]
}
return k
}
|
go
|
func (s *memSeries) truncateChunksBefore(mint int64) (removed int) {
var k int
for i, c := range s.chunks {
if c.maxTime >= mint {
break
}
k = i + 1
}
s.chunks = append(s.chunks[:0], s.chunks[k:]...)
s.firstChunkID += k
if len(s.chunks) == 0 {
s.headChunk = nil
} else {
s.headChunk = s.chunks[len(s.chunks)-1]
}
return k
}
|
[
"func",
"(",
"s",
"*",
"memSeries",
")",
"truncateChunksBefore",
"(",
"mint",
"int64",
")",
"(",
"removed",
"int",
")",
"{",
"var",
"k",
"int",
"\n",
"for",
"i",
",",
"c",
":=",
"range",
"s",
".",
"chunks",
"{",
"if",
"c",
".",
"maxTime",
">=",
"mint",
"{",
"break",
"\n",
"}",
"\n",
"k",
"=",
"i",
"+",
"1",
"\n",
"}",
"\n",
"s",
".",
"chunks",
"=",
"append",
"(",
"s",
".",
"chunks",
"[",
":",
"0",
"]",
",",
"s",
".",
"chunks",
"[",
"k",
":",
"]",
"...",
")",
"\n",
"s",
".",
"firstChunkID",
"+=",
"k",
"\n",
"if",
"len",
"(",
"s",
".",
"chunks",
")",
"==",
"0",
"{",
"s",
".",
"headChunk",
"=",
"nil",
"\n",
"}",
"else",
"{",
"s",
".",
"headChunk",
"=",
"s",
".",
"chunks",
"[",
"len",
"(",
"s",
".",
"chunks",
")",
"-",
"1",
"]",
"\n",
"}",
"\n\n",
"return",
"k",
"\n",
"}"
] |
// truncateChunksBefore removes all chunks from the series that have not timestamp
// at or after mint. Chunk IDs remain unchanged.
|
[
"truncateChunksBefore",
"removes",
"all",
"chunks",
"from",
"the",
"series",
"that",
"have",
"not",
"timestamp",
"at",
"or",
"after",
"mint",
".",
"Chunk",
"IDs",
"remain",
"unchanged",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L1610-L1627
|
train
|
prometheus/tsdb
|
wal/reader.go
|
Next
|
func (r *Reader) Next() bool {
err := r.next()
if errors.Cause(err) == io.EOF {
// The last WAL segment record shouldn't be torn(should be full or last).
// The last record would be torn after a crash just before
// the last record part could be persisted to disk.
if recType(r.curRecTyp) == recFirst || recType(r.curRecTyp) == recMiddle {
r.err = errors.New("last record is torn")
}
return false
}
r.err = err
return r.err == nil
}
|
go
|
func (r *Reader) Next() bool {
err := r.next()
if errors.Cause(err) == io.EOF {
// The last WAL segment record shouldn't be torn(should be full or last).
// The last record would be torn after a crash just before
// the last record part could be persisted to disk.
if recType(r.curRecTyp) == recFirst || recType(r.curRecTyp) == recMiddle {
r.err = errors.New("last record is torn")
}
return false
}
r.err = err
return r.err == nil
}
|
[
"func",
"(",
"r",
"*",
"Reader",
")",
"Next",
"(",
")",
"bool",
"{",
"err",
":=",
"r",
".",
"next",
"(",
")",
"\n",
"if",
"errors",
".",
"Cause",
"(",
"err",
")",
"==",
"io",
".",
"EOF",
"{",
"// The last WAL segment record shouldn't be torn(should be full or last).",
"// The last record would be torn after a crash just before",
"// the last record part could be persisted to disk.",
"if",
"recType",
"(",
"r",
".",
"curRecTyp",
")",
"==",
"recFirst",
"||",
"recType",
"(",
"r",
".",
"curRecTyp",
")",
"==",
"recMiddle",
"{",
"r",
".",
"err",
"=",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"r",
".",
"err",
"=",
"err",
"\n",
"return",
"r",
".",
"err",
"==",
"nil",
"\n",
"}"
] |
// Next advances the reader to the next records and returns true if it exists.
// It must not be called again after it returned false.
|
[
"Next",
"advances",
"the",
"reader",
"to",
"the",
"next",
"records",
"and",
"returns",
"true",
"if",
"it",
"exists",
".",
"It",
"must",
"not",
"be",
"called",
"again",
"after",
"it",
"returned",
"false",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/wal/reader.go#L42-L55
|
train
|
prometheus/tsdb
|
wal/reader.go
|
Err
|
func (r *Reader) Err() error {
if r.err == nil {
return nil
}
if b, ok := r.rdr.(*segmentBufReader); ok {
return &CorruptionErr{
Err: r.err,
Dir: b.segs[b.cur].Dir(),
Segment: b.segs[b.cur].Index(),
Offset: int64(b.off),
}
}
return &CorruptionErr{
Err: r.err,
Segment: -1,
Offset: r.total,
}
}
|
go
|
func (r *Reader) Err() error {
if r.err == nil {
return nil
}
if b, ok := r.rdr.(*segmentBufReader); ok {
return &CorruptionErr{
Err: r.err,
Dir: b.segs[b.cur].Dir(),
Segment: b.segs[b.cur].Index(),
Offset: int64(b.off),
}
}
return &CorruptionErr{
Err: r.err,
Segment: -1,
Offset: r.total,
}
}
|
[
"func",
"(",
"r",
"*",
"Reader",
")",
"Err",
"(",
")",
"error",
"{",
"if",
"r",
".",
"err",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"b",
",",
"ok",
":=",
"r",
".",
"rdr",
".",
"(",
"*",
"segmentBufReader",
")",
";",
"ok",
"{",
"return",
"&",
"CorruptionErr",
"{",
"Err",
":",
"r",
".",
"err",
",",
"Dir",
":",
"b",
".",
"segs",
"[",
"b",
".",
"cur",
"]",
".",
"Dir",
"(",
")",
",",
"Segment",
":",
"b",
".",
"segs",
"[",
"b",
".",
"cur",
"]",
".",
"Index",
"(",
")",
",",
"Offset",
":",
"int64",
"(",
"b",
".",
"off",
")",
",",
"}",
"\n",
"}",
"\n",
"return",
"&",
"CorruptionErr",
"{",
"Err",
":",
"r",
".",
"err",
",",
"Segment",
":",
"-",
"1",
",",
"Offset",
":",
"r",
".",
"total",
",",
"}",
"\n",
"}"
] |
// Err returns the last encountered error wrapped in a corruption error.
// If the reader does not allow to infer a segment index and offset, a total
// offset in the reader stream will be provided.
|
[
"Err",
"returns",
"the",
"last",
"encountered",
"error",
"wrapped",
"in",
"a",
"corruption",
"error",
".",
"If",
"the",
"reader",
"does",
"not",
"allow",
"to",
"infer",
"a",
"segment",
"index",
"and",
"offset",
"a",
"total",
"offset",
"in",
"the",
"reader",
"stream",
"will",
"be",
"provided",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/wal/reader.go#L144-L161
|
train
|
prometheus/tsdb
|
wal/reader.go
|
Segment
|
func (r *Reader) Segment() int {
if b, ok := r.rdr.(*segmentBufReader); ok {
return b.segs[b.cur].Index()
}
return -1
}
|
go
|
func (r *Reader) Segment() int {
if b, ok := r.rdr.(*segmentBufReader); ok {
return b.segs[b.cur].Index()
}
return -1
}
|
[
"func",
"(",
"r",
"*",
"Reader",
")",
"Segment",
"(",
")",
"int",
"{",
"if",
"b",
",",
"ok",
":=",
"r",
".",
"rdr",
".",
"(",
"*",
"segmentBufReader",
")",
";",
"ok",
"{",
"return",
"b",
".",
"segs",
"[",
"b",
".",
"cur",
"]",
".",
"Index",
"(",
")",
"\n",
"}",
"\n",
"return",
"-",
"1",
"\n",
"}"
] |
// Segment returns the current segment being read.
|
[
"Segment",
"returns",
"the",
"current",
"segment",
"being",
"read",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/wal/reader.go#L170-L175
|
train
|
prometheus/tsdb
|
wal/reader.go
|
Offset
|
func (r *Reader) Offset() int64 {
if b, ok := r.rdr.(*segmentBufReader); ok {
return int64(b.off)
}
return r.total
}
|
go
|
func (r *Reader) Offset() int64 {
if b, ok := r.rdr.(*segmentBufReader); ok {
return int64(b.off)
}
return r.total
}
|
[
"func",
"(",
"r",
"*",
"Reader",
")",
"Offset",
"(",
")",
"int64",
"{",
"if",
"b",
",",
"ok",
":=",
"r",
".",
"rdr",
".",
"(",
"*",
"segmentBufReader",
")",
";",
"ok",
"{",
"return",
"int64",
"(",
"b",
".",
"off",
")",
"\n",
"}",
"\n",
"return",
"r",
".",
"total",
"\n",
"}"
] |
// Offset returns the current position of the segment being read.
|
[
"Offset",
"returns",
"the",
"current",
"position",
"of",
"the",
"segment",
"being",
"read",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/wal/reader.go#L178-L183
|
train
|
prometheus/tsdb
|
querier.go
|
NewBlockQuerier
|
func NewBlockQuerier(b BlockReader, mint, maxt int64) (Querier, error) {
indexr, err := b.Index()
if err != nil {
return nil, errors.Wrapf(err, "open index reader")
}
chunkr, err := b.Chunks()
if err != nil {
indexr.Close()
return nil, errors.Wrapf(err, "open chunk reader")
}
tombsr, err := b.Tombstones()
if err != nil {
indexr.Close()
chunkr.Close()
return nil, errors.Wrapf(err, "open tombstone reader")
}
return &blockQuerier{
mint: mint,
maxt: maxt,
index: indexr,
chunks: chunkr,
tombstones: tombsr,
}, nil
}
|
go
|
func NewBlockQuerier(b BlockReader, mint, maxt int64) (Querier, error) {
indexr, err := b.Index()
if err != nil {
return nil, errors.Wrapf(err, "open index reader")
}
chunkr, err := b.Chunks()
if err != nil {
indexr.Close()
return nil, errors.Wrapf(err, "open chunk reader")
}
tombsr, err := b.Tombstones()
if err != nil {
indexr.Close()
chunkr.Close()
return nil, errors.Wrapf(err, "open tombstone reader")
}
return &blockQuerier{
mint: mint,
maxt: maxt,
index: indexr,
chunks: chunkr,
tombstones: tombsr,
}, nil
}
|
[
"func",
"NewBlockQuerier",
"(",
"b",
"BlockReader",
",",
"mint",
",",
"maxt",
"int64",
")",
"(",
"Querier",
",",
"error",
")",
"{",
"indexr",
",",
"err",
":=",
"b",
".",
"Index",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"chunkr",
",",
"err",
":=",
"b",
".",
"Chunks",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"indexr",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"tombsr",
",",
"err",
":=",
"b",
".",
"Tombstones",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"indexr",
".",
"Close",
"(",
")",
"\n",
"chunkr",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"&",
"blockQuerier",
"{",
"mint",
":",
"mint",
",",
"maxt",
":",
"maxt",
",",
"index",
":",
"indexr",
",",
"chunks",
":",
"chunkr",
",",
"tombstones",
":",
"tombsr",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// NewBlockQuerier returns a querier against the reader.
|
[
"NewBlockQuerier",
"returns",
"a",
"querier",
"against",
"the",
"reader",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/querier.go#L177-L200
|
train
|
prometheus/tsdb
|
querier.go
|
PostingsForMatchers
|
func PostingsForMatchers(ix IndexReader, ms ...labels.Matcher) (index.Postings, error) {
var its, notIts []index.Postings
// See which label must be non-empty.
labelMustBeSet := make(map[string]bool, len(ms))
for _, m := range ms {
if !m.Matches("") {
labelMustBeSet[m.Name()] = true
}
}
for _, m := range ms {
matchesEmpty := m.Matches("")
if labelMustBeSet[m.Name()] || !matchesEmpty {
// If this matcher must be non-empty, we can be smarter.
nm, isNot := m.(*labels.NotMatcher)
if isNot && matchesEmpty { // l!="foo"
// If the label can't be empty and is a Not and the inner matcher
// doesn't match empty, then subtract it out at the end.
it, err := postingsForMatcher(ix, nm.Matcher)
if err != nil {
return nil, err
}
notIts = append(notIts, it)
} else if isNot && !matchesEmpty { // l!=""
// If the label can't be empty and is a Not, but the inner matcher can
// be empty we need to use inversePostingsForMatcher.
it, err := inversePostingsForMatcher(ix, nm.Matcher)
if err != nil {
return nil, err
}
its = append(its, it)
} else { // l="a"
// Non-Not matcher, use normal postingsForMatcher.
it, err := postingsForMatcher(ix, m)
if err != nil {
return nil, err
}
its = append(its, it)
}
} else { // l=""
// If the matchers for a labelname selects an empty value, it selects all
// the series which don't have the label name set too. See:
// https://github.com/prometheus/prometheus/issues/3575 and
// https://github.com/prometheus/prometheus/pull/3578#issuecomment-351653555
it, err := inversePostingsForMatcher(ix, m)
if err != nil {
return nil, err
}
notIts = append(notIts, it)
}
}
// If there's nothing to subtract from, add in everything and remove the notIts later.
if len(its) == 0 && len(notIts) != 0 {
allPostings, err := ix.Postings(index.AllPostingsKey())
if err != nil {
return nil, err
}
its = append(its, allPostings)
}
it := index.Intersect(its...)
for _, n := range notIts {
if _, ok := n.(*index.ListPostings); !ok {
// Best to pre-calculate the merged lists via next rather than have a ton
// of seeks in Without.
pl, err := index.ExpandPostings(n)
if err != nil {
return nil, err
}
n = index.NewListPostings(pl)
}
it = index.Without(it, n)
}
return ix.SortedPostings(it), nil
}
|
go
|
func PostingsForMatchers(ix IndexReader, ms ...labels.Matcher) (index.Postings, error) {
var its, notIts []index.Postings
// See which label must be non-empty.
labelMustBeSet := make(map[string]bool, len(ms))
for _, m := range ms {
if !m.Matches("") {
labelMustBeSet[m.Name()] = true
}
}
for _, m := range ms {
matchesEmpty := m.Matches("")
if labelMustBeSet[m.Name()] || !matchesEmpty {
// If this matcher must be non-empty, we can be smarter.
nm, isNot := m.(*labels.NotMatcher)
if isNot && matchesEmpty { // l!="foo"
// If the label can't be empty and is a Not and the inner matcher
// doesn't match empty, then subtract it out at the end.
it, err := postingsForMatcher(ix, nm.Matcher)
if err != nil {
return nil, err
}
notIts = append(notIts, it)
} else if isNot && !matchesEmpty { // l!=""
// If the label can't be empty and is a Not, but the inner matcher can
// be empty we need to use inversePostingsForMatcher.
it, err := inversePostingsForMatcher(ix, nm.Matcher)
if err != nil {
return nil, err
}
its = append(its, it)
} else { // l="a"
// Non-Not matcher, use normal postingsForMatcher.
it, err := postingsForMatcher(ix, m)
if err != nil {
return nil, err
}
its = append(its, it)
}
} else { // l=""
// If the matchers for a labelname selects an empty value, it selects all
// the series which don't have the label name set too. See:
// https://github.com/prometheus/prometheus/issues/3575 and
// https://github.com/prometheus/prometheus/pull/3578#issuecomment-351653555
it, err := inversePostingsForMatcher(ix, m)
if err != nil {
return nil, err
}
notIts = append(notIts, it)
}
}
// If there's nothing to subtract from, add in everything and remove the notIts later.
if len(its) == 0 && len(notIts) != 0 {
allPostings, err := ix.Postings(index.AllPostingsKey())
if err != nil {
return nil, err
}
its = append(its, allPostings)
}
it := index.Intersect(its...)
for _, n := range notIts {
if _, ok := n.(*index.ListPostings); !ok {
// Best to pre-calculate the merged lists via next rather than have a ton
// of seeks in Without.
pl, err := index.ExpandPostings(n)
if err != nil {
return nil, err
}
n = index.NewListPostings(pl)
}
it = index.Without(it, n)
}
return ix.SortedPostings(it), nil
}
|
[
"func",
"PostingsForMatchers",
"(",
"ix",
"IndexReader",
",",
"ms",
"...",
"labels",
".",
"Matcher",
")",
"(",
"index",
".",
"Postings",
",",
"error",
")",
"{",
"var",
"its",
",",
"notIts",
"[",
"]",
"index",
".",
"Postings",
"\n",
"// See which label must be non-empty.",
"labelMustBeSet",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"bool",
",",
"len",
"(",
"ms",
")",
")",
"\n",
"for",
"_",
",",
"m",
":=",
"range",
"ms",
"{",
"if",
"!",
"m",
".",
"Matches",
"(",
"\"",
"\"",
")",
"{",
"labelMustBeSet",
"[",
"m",
".",
"Name",
"(",
")",
"]",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"m",
":=",
"range",
"ms",
"{",
"matchesEmpty",
":=",
"m",
".",
"Matches",
"(",
"\"",
"\"",
")",
"\n",
"if",
"labelMustBeSet",
"[",
"m",
".",
"Name",
"(",
")",
"]",
"||",
"!",
"matchesEmpty",
"{",
"// If this matcher must be non-empty, we can be smarter.",
"nm",
",",
"isNot",
":=",
"m",
".",
"(",
"*",
"labels",
".",
"NotMatcher",
")",
"\n",
"if",
"isNot",
"&&",
"matchesEmpty",
"{",
"// l!=\"foo\"",
"// If the label can't be empty and is a Not and the inner matcher",
"// doesn't match empty, then subtract it out at the end.",
"it",
",",
"err",
":=",
"postingsForMatcher",
"(",
"ix",
",",
"nm",
".",
"Matcher",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"notIts",
"=",
"append",
"(",
"notIts",
",",
"it",
")",
"\n",
"}",
"else",
"if",
"isNot",
"&&",
"!",
"matchesEmpty",
"{",
"// l!=\"\"",
"// If the label can't be empty and is a Not, but the inner matcher can",
"// be empty we need to use inversePostingsForMatcher.",
"it",
",",
"err",
":=",
"inversePostingsForMatcher",
"(",
"ix",
",",
"nm",
".",
"Matcher",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"its",
"=",
"append",
"(",
"its",
",",
"it",
")",
"\n",
"}",
"else",
"{",
"// l=\"a\"",
"// Non-Not matcher, use normal postingsForMatcher.",
"it",
",",
"err",
":=",
"postingsForMatcher",
"(",
"ix",
",",
"m",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"its",
"=",
"append",
"(",
"its",
",",
"it",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"// l=\"\"",
"// If the matchers for a labelname selects an empty value, it selects all",
"// the series which don't have the label name set too. See:",
"// https://github.com/prometheus/prometheus/issues/3575 and",
"// https://github.com/prometheus/prometheus/pull/3578#issuecomment-351653555",
"it",
",",
"err",
":=",
"inversePostingsForMatcher",
"(",
"ix",
",",
"m",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"notIts",
"=",
"append",
"(",
"notIts",
",",
"it",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// If there's nothing to subtract from, add in everything and remove the notIts later.",
"if",
"len",
"(",
"its",
")",
"==",
"0",
"&&",
"len",
"(",
"notIts",
")",
"!=",
"0",
"{",
"allPostings",
",",
"err",
":=",
"ix",
".",
"Postings",
"(",
"index",
".",
"AllPostingsKey",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"its",
"=",
"append",
"(",
"its",
",",
"allPostings",
")",
"\n",
"}",
"\n\n",
"it",
":=",
"index",
".",
"Intersect",
"(",
"its",
"...",
")",
"\n\n",
"for",
"_",
",",
"n",
":=",
"range",
"notIts",
"{",
"if",
"_",
",",
"ok",
":=",
"n",
".",
"(",
"*",
"index",
".",
"ListPostings",
")",
";",
"!",
"ok",
"{",
"// Best to pre-calculate the merged lists via next rather than have a ton",
"// of seeks in Without.",
"pl",
",",
"err",
":=",
"index",
".",
"ExpandPostings",
"(",
"n",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"n",
"=",
"index",
".",
"NewListPostings",
"(",
"pl",
")",
"\n",
"}",
"\n",
"it",
"=",
"index",
".",
"Without",
"(",
"it",
",",
"n",
")",
"\n",
"}",
"\n\n",
"return",
"ix",
".",
"SortedPostings",
"(",
"it",
")",
",",
"nil",
"\n",
"}"
] |
// PostingsForMatchers assembles a single postings iterator against the index reader
// based on the given matchers.
|
[
"PostingsForMatchers",
"assembles",
"a",
"single",
"postings",
"iterator",
"against",
"the",
"index",
"reader",
"based",
"on",
"the",
"given",
"matchers",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/querier.go#L271-L348
|
train
|
prometheus/tsdb
|
querier.go
|
inversePostingsForMatcher
|
func inversePostingsForMatcher(ix IndexReader, m labels.Matcher) (index.Postings, error) {
tpls, err := ix.LabelValues(m.Name())
if err != nil {
return nil, err
}
var res []string
for i := 0; i < tpls.Len(); i++ {
vals, err := tpls.At(i)
if err != nil {
return nil, err
}
if !m.Matches(vals[0]) {
res = append(res, vals[0])
}
}
var rit []index.Postings
for _, v := range res {
it, err := ix.Postings(m.Name(), v)
if err != nil {
return nil, err
}
rit = append(rit, it)
}
return index.Merge(rit...), nil
}
|
go
|
func inversePostingsForMatcher(ix IndexReader, m labels.Matcher) (index.Postings, error) {
tpls, err := ix.LabelValues(m.Name())
if err != nil {
return nil, err
}
var res []string
for i := 0; i < tpls.Len(); i++ {
vals, err := tpls.At(i)
if err != nil {
return nil, err
}
if !m.Matches(vals[0]) {
res = append(res, vals[0])
}
}
var rit []index.Postings
for _, v := range res {
it, err := ix.Postings(m.Name(), v)
if err != nil {
return nil, err
}
rit = append(rit, it)
}
return index.Merge(rit...), nil
}
|
[
"func",
"inversePostingsForMatcher",
"(",
"ix",
"IndexReader",
",",
"m",
"labels",
".",
"Matcher",
")",
"(",
"index",
".",
"Postings",
",",
"error",
")",
"{",
"tpls",
",",
"err",
":=",
"ix",
".",
"LabelValues",
"(",
"m",
".",
"Name",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"res",
"[",
"]",
"string",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"tpls",
".",
"Len",
"(",
")",
";",
"i",
"++",
"{",
"vals",
",",
"err",
":=",
"tpls",
".",
"At",
"(",
"i",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"!",
"m",
".",
"Matches",
"(",
"vals",
"[",
"0",
"]",
")",
"{",
"res",
"=",
"append",
"(",
"res",
",",
"vals",
"[",
"0",
"]",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"var",
"rit",
"[",
"]",
"index",
".",
"Postings",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"res",
"{",
"it",
",",
"err",
":=",
"ix",
".",
"Postings",
"(",
"m",
".",
"Name",
"(",
")",
",",
"v",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"rit",
"=",
"append",
"(",
"rit",
",",
"it",
")",
"\n",
"}",
"\n\n",
"return",
"index",
".",
"Merge",
"(",
"rit",
"...",
")",
",",
"nil",
"\n",
"}"
] |
// inversePostingsForMatcher eeturns the postings for the series with the label name set but not matching the matcher.
|
[
"inversePostingsForMatcher",
"eeturns",
"the",
"postings",
"for",
"the",
"series",
"with",
"the",
"label",
"name",
"set",
"but",
"not",
"matching",
"the",
"matcher",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/querier.go#L392-L421
|
train
|
prometheus/tsdb
|
querier.go
|
LookupChunkSeries
|
func LookupChunkSeries(ir IndexReader, tr TombstoneReader, ms ...labels.Matcher) (ChunkSeriesSet, error) {
if tr == nil {
tr = newMemTombstones()
}
p, err := PostingsForMatchers(ir, ms...)
if err != nil {
return nil, err
}
return &baseChunkSeries{
p: p,
index: ir,
tombstones: tr,
}, nil
}
|
go
|
func LookupChunkSeries(ir IndexReader, tr TombstoneReader, ms ...labels.Matcher) (ChunkSeriesSet, error) {
if tr == nil {
tr = newMemTombstones()
}
p, err := PostingsForMatchers(ir, ms...)
if err != nil {
return nil, err
}
return &baseChunkSeries{
p: p,
index: ir,
tombstones: tr,
}, nil
}
|
[
"func",
"LookupChunkSeries",
"(",
"ir",
"IndexReader",
",",
"tr",
"TombstoneReader",
",",
"ms",
"...",
"labels",
".",
"Matcher",
")",
"(",
"ChunkSeriesSet",
",",
"error",
")",
"{",
"if",
"tr",
"==",
"nil",
"{",
"tr",
"=",
"newMemTombstones",
"(",
")",
"\n",
"}",
"\n",
"p",
",",
"err",
":=",
"PostingsForMatchers",
"(",
"ir",
",",
"ms",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"baseChunkSeries",
"{",
"p",
":",
"p",
",",
"index",
":",
"ir",
",",
"tombstones",
":",
"tr",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// LookupChunkSeries retrieves all series for the given matchers and returns a ChunkSeriesSet
// over them. It drops chunks based on tombstones in the given reader.
|
[
"LookupChunkSeries",
"retrieves",
"all",
"series",
"for",
"the",
"given",
"matchers",
"and",
"returns",
"a",
"ChunkSeriesSet",
"over",
"them",
".",
"It",
"drops",
"chunks",
"based",
"on",
"tombstones",
"in",
"the",
"given",
"reader",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/querier.go#L624-L637
|
train
|
prometheus/tsdb
|
index/postings.go
|
NewMemPostings
|
func NewMemPostings() *MemPostings {
return &MemPostings{
m: make(map[string]map[string][]uint64, 512),
ordered: true,
}
}
|
go
|
func NewMemPostings() *MemPostings {
return &MemPostings{
m: make(map[string]map[string][]uint64, 512),
ordered: true,
}
}
|
[
"func",
"NewMemPostings",
"(",
")",
"*",
"MemPostings",
"{",
"return",
"&",
"MemPostings",
"{",
"m",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"map",
"[",
"string",
"]",
"[",
"]",
"uint64",
",",
"512",
")",
",",
"ordered",
":",
"true",
",",
"}",
"\n",
"}"
] |
// NewMemPostings returns a memPostings that's ready for reads and writes.
|
[
"NewMemPostings",
"returns",
"a",
"memPostings",
"that",
"s",
"ready",
"for",
"reads",
"and",
"writes",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/index/postings.go#L45-L50
|
train
|
prometheus/tsdb
|
index/postings.go
|
NewUnorderedMemPostings
|
func NewUnorderedMemPostings() *MemPostings {
return &MemPostings{
m: make(map[string]map[string][]uint64, 512),
ordered: false,
}
}
|
go
|
func NewUnorderedMemPostings() *MemPostings {
return &MemPostings{
m: make(map[string]map[string][]uint64, 512),
ordered: false,
}
}
|
[
"func",
"NewUnorderedMemPostings",
"(",
")",
"*",
"MemPostings",
"{",
"return",
"&",
"MemPostings",
"{",
"m",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"map",
"[",
"string",
"]",
"[",
"]",
"uint64",
",",
"512",
")",
",",
"ordered",
":",
"false",
",",
"}",
"\n",
"}"
] |
// NewUnorderedMemPostings returns a memPostings that is not safe to be read from
// until ensureOrder was called once.
|
[
"NewUnorderedMemPostings",
"returns",
"a",
"memPostings",
"that",
"is",
"not",
"safe",
"to",
"be",
"read",
"from",
"until",
"ensureOrder",
"was",
"called",
"once",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/index/postings.go#L54-L59
|
train
|
prometheus/tsdb
|
index/postings.go
|
SortedKeys
|
func (p *MemPostings) SortedKeys() []labels.Label {
p.mtx.RLock()
keys := make([]labels.Label, 0, len(p.m))
for n, e := range p.m {
for v := range e {
keys = append(keys, labels.Label{Name: n, Value: v})
}
}
p.mtx.RUnlock()
sort.Slice(keys, func(i, j int) bool {
if d := strings.Compare(keys[i].Name, keys[j].Name); d != 0 {
return d < 0
}
return keys[i].Value < keys[j].Value
})
return keys
}
|
go
|
func (p *MemPostings) SortedKeys() []labels.Label {
p.mtx.RLock()
keys := make([]labels.Label, 0, len(p.m))
for n, e := range p.m {
for v := range e {
keys = append(keys, labels.Label{Name: n, Value: v})
}
}
p.mtx.RUnlock()
sort.Slice(keys, func(i, j int) bool {
if d := strings.Compare(keys[i].Name, keys[j].Name); d != 0 {
return d < 0
}
return keys[i].Value < keys[j].Value
})
return keys
}
|
[
"func",
"(",
"p",
"*",
"MemPostings",
")",
"SortedKeys",
"(",
")",
"[",
"]",
"labels",
".",
"Label",
"{",
"p",
".",
"mtx",
".",
"RLock",
"(",
")",
"\n",
"keys",
":=",
"make",
"(",
"[",
"]",
"labels",
".",
"Label",
",",
"0",
",",
"len",
"(",
"p",
".",
"m",
")",
")",
"\n\n",
"for",
"n",
",",
"e",
":=",
"range",
"p",
".",
"m",
"{",
"for",
"v",
":=",
"range",
"e",
"{",
"keys",
"=",
"append",
"(",
"keys",
",",
"labels",
".",
"Label",
"{",
"Name",
":",
"n",
",",
"Value",
":",
"v",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n",
"p",
".",
"mtx",
".",
"RUnlock",
"(",
")",
"\n\n",
"sort",
".",
"Slice",
"(",
"keys",
",",
"func",
"(",
"i",
",",
"j",
"int",
")",
"bool",
"{",
"if",
"d",
":=",
"strings",
".",
"Compare",
"(",
"keys",
"[",
"i",
"]",
".",
"Name",
",",
"keys",
"[",
"j",
"]",
".",
"Name",
")",
";",
"d",
"!=",
"0",
"{",
"return",
"d",
"<",
"0",
"\n",
"}",
"\n",
"return",
"keys",
"[",
"i",
"]",
".",
"Value",
"<",
"keys",
"[",
"j",
"]",
".",
"Value",
"\n",
"}",
")",
"\n",
"return",
"keys",
"\n",
"}"
] |
// SortedKeys returns a list of sorted label keys of the postings.
|
[
"SortedKeys",
"returns",
"a",
"list",
"of",
"sorted",
"label",
"keys",
"of",
"the",
"postings",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/index/postings.go#L62-L80
|
train
|
prometheus/tsdb
|
index/postings.go
|
Get
|
func (p *MemPostings) Get(name, value string) Postings {
var lp []uint64
p.mtx.RLock()
l := p.m[name]
if l != nil {
lp = l[value]
}
p.mtx.RUnlock()
if lp == nil {
return EmptyPostings()
}
return newListPostings(lp...)
}
|
go
|
func (p *MemPostings) Get(name, value string) Postings {
var lp []uint64
p.mtx.RLock()
l := p.m[name]
if l != nil {
lp = l[value]
}
p.mtx.RUnlock()
if lp == nil {
return EmptyPostings()
}
return newListPostings(lp...)
}
|
[
"func",
"(",
"p",
"*",
"MemPostings",
")",
"Get",
"(",
"name",
",",
"value",
"string",
")",
"Postings",
"{",
"var",
"lp",
"[",
"]",
"uint64",
"\n",
"p",
".",
"mtx",
".",
"RLock",
"(",
")",
"\n",
"l",
":=",
"p",
".",
"m",
"[",
"name",
"]",
"\n",
"if",
"l",
"!=",
"nil",
"{",
"lp",
"=",
"l",
"[",
"value",
"]",
"\n",
"}",
"\n",
"p",
".",
"mtx",
".",
"RUnlock",
"(",
")",
"\n\n",
"if",
"lp",
"==",
"nil",
"{",
"return",
"EmptyPostings",
"(",
")",
"\n",
"}",
"\n",
"return",
"newListPostings",
"(",
"lp",
"...",
")",
"\n",
"}"
] |
// Get returns a postings list for the given label pair.
|
[
"Get",
"returns",
"a",
"postings",
"list",
"for",
"the",
"given",
"label",
"pair",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/index/postings.go#L83-L96
|
train
|
prometheus/tsdb
|
index/postings.go
|
EnsureOrder
|
func (p *MemPostings) EnsureOrder() {
p.mtx.Lock()
defer p.mtx.Unlock()
if p.ordered {
return
}
n := runtime.GOMAXPROCS(0)
workc := make(chan []uint64)
var wg sync.WaitGroup
wg.Add(n)
for i := 0; i < n; i++ {
go func() {
for l := range workc {
sort.Slice(l, func(i, j int) bool { return l[i] < l[j] })
}
wg.Done()
}()
}
for _, e := range p.m {
for _, l := range e {
workc <- l
}
}
close(workc)
wg.Wait()
p.ordered = true
}
|
go
|
func (p *MemPostings) EnsureOrder() {
p.mtx.Lock()
defer p.mtx.Unlock()
if p.ordered {
return
}
n := runtime.GOMAXPROCS(0)
workc := make(chan []uint64)
var wg sync.WaitGroup
wg.Add(n)
for i := 0; i < n; i++ {
go func() {
for l := range workc {
sort.Slice(l, func(i, j int) bool { return l[i] < l[j] })
}
wg.Done()
}()
}
for _, e := range p.m {
for _, l := range e {
workc <- l
}
}
close(workc)
wg.Wait()
p.ordered = true
}
|
[
"func",
"(",
"p",
"*",
"MemPostings",
")",
"EnsureOrder",
"(",
")",
"{",
"p",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"p",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"p",
".",
"ordered",
"{",
"return",
"\n",
"}",
"\n\n",
"n",
":=",
"runtime",
".",
"GOMAXPROCS",
"(",
"0",
")",
"\n",
"workc",
":=",
"make",
"(",
"chan",
"[",
"]",
"uint64",
")",
"\n\n",
"var",
"wg",
"sync",
".",
"WaitGroup",
"\n",
"wg",
".",
"Add",
"(",
"n",
")",
"\n\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"n",
";",
"i",
"++",
"{",
"go",
"func",
"(",
")",
"{",
"for",
"l",
":=",
"range",
"workc",
"{",
"sort",
".",
"Slice",
"(",
"l",
",",
"func",
"(",
"i",
",",
"j",
"int",
")",
"bool",
"{",
"return",
"l",
"[",
"i",
"]",
"<",
"l",
"[",
"j",
"]",
"}",
")",
"\n",
"}",
"\n",
"wg",
".",
"Done",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"e",
":=",
"range",
"p",
".",
"m",
"{",
"for",
"_",
",",
"l",
":=",
"range",
"e",
"{",
"workc",
"<-",
"l",
"\n",
"}",
"\n",
"}",
"\n",
"close",
"(",
"workc",
")",
"\n",
"wg",
".",
"Wait",
"(",
")",
"\n\n",
"p",
".",
"ordered",
"=",
"true",
"\n",
"}"
] |
// EnsureOrder ensures that all postings lists are sorted. After it returns all further
// calls to add and addFor will insert new IDs in a sorted manner.
|
[
"EnsureOrder",
"ensures",
"that",
"all",
"postings",
"lists",
"are",
"sorted",
".",
"After",
"it",
"returns",
"all",
"further",
"calls",
"to",
"add",
"and",
"addFor",
"will",
"insert",
"new",
"IDs",
"in",
"a",
"sorted",
"manner",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/index/postings.go#L105-L137
|
train
|
prometheus/tsdb
|
index/postings.go
|
Delete
|
func (p *MemPostings) Delete(deleted map[uint64]struct{}) {
var keys, vals []string
// Collect all keys relevant for deletion once. New keys added afterwards
// can by definition not be affected by any of the given deletes.
p.mtx.RLock()
for n := range p.m {
keys = append(keys, n)
}
p.mtx.RUnlock()
for _, n := range keys {
p.mtx.RLock()
vals = vals[:0]
for v := range p.m[n] {
vals = append(vals, v)
}
p.mtx.RUnlock()
// For each posting we first analyse whether the postings list is affected by the deletes.
// If yes, we actually reallocate a new postings list.
for _, l := range vals {
// Only lock for processing one postings list so we don't block reads for too long.
p.mtx.Lock()
found := false
for _, id := range p.m[n][l] {
if _, ok := deleted[id]; ok {
found = true
break
}
}
if !found {
p.mtx.Unlock()
continue
}
repl := make([]uint64, 0, len(p.m[n][l]))
for _, id := range p.m[n][l] {
if _, ok := deleted[id]; !ok {
repl = append(repl, id)
}
}
if len(repl) > 0 {
p.m[n][l] = repl
} else {
delete(p.m[n], l)
}
p.mtx.Unlock()
}
p.mtx.Lock()
if len(p.m[n]) == 0 {
delete(p.m, n)
}
p.mtx.Unlock()
}
}
|
go
|
func (p *MemPostings) Delete(deleted map[uint64]struct{}) {
var keys, vals []string
// Collect all keys relevant for deletion once. New keys added afterwards
// can by definition not be affected by any of the given deletes.
p.mtx.RLock()
for n := range p.m {
keys = append(keys, n)
}
p.mtx.RUnlock()
for _, n := range keys {
p.mtx.RLock()
vals = vals[:0]
for v := range p.m[n] {
vals = append(vals, v)
}
p.mtx.RUnlock()
// For each posting we first analyse whether the postings list is affected by the deletes.
// If yes, we actually reallocate a new postings list.
for _, l := range vals {
// Only lock for processing one postings list so we don't block reads for too long.
p.mtx.Lock()
found := false
for _, id := range p.m[n][l] {
if _, ok := deleted[id]; ok {
found = true
break
}
}
if !found {
p.mtx.Unlock()
continue
}
repl := make([]uint64, 0, len(p.m[n][l]))
for _, id := range p.m[n][l] {
if _, ok := deleted[id]; !ok {
repl = append(repl, id)
}
}
if len(repl) > 0 {
p.m[n][l] = repl
} else {
delete(p.m[n], l)
}
p.mtx.Unlock()
}
p.mtx.Lock()
if len(p.m[n]) == 0 {
delete(p.m, n)
}
p.mtx.Unlock()
}
}
|
[
"func",
"(",
"p",
"*",
"MemPostings",
")",
"Delete",
"(",
"deleted",
"map",
"[",
"uint64",
"]",
"struct",
"{",
"}",
")",
"{",
"var",
"keys",
",",
"vals",
"[",
"]",
"string",
"\n\n",
"// Collect all keys relevant for deletion once. New keys added afterwards",
"// can by definition not be affected by any of the given deletes.",
"p",
".",
"mtx",
".",
"RLock",
"(",
")",
"\n",
"for",
"n",
":=",
"range",
"p",
".",
"m",
"{",
"keys",
"=",
"append",
"(",
"keys",
",",
"n",
")",
"\n",
"}",
"\n",
"p",
".",
"mtx",
".",
"RUnlock",
"(",
")",
"\n\n",
"for",
"_",
",",
"n",
":=",
"range",
"keys",
"{",
"p",
".",
"mtx",
".",
"RLock",
"(",
")",
"\n",
"vals",
"=",
"vals",
"[",
":",
"0",
"]",
"\n",
"for",
"v",
":=",
"range",
"p",
".",
"m",
"[",
"n",
"]",
"{",
"vals",
"=",
"append",
"(",
"vals",
",",
"v",
")",
"\n",
"}",
"\n",
"p",
".",
"mtx",
".",
"RUnlock",
"(",
")",
"\n\n",
"// For each posting we first analyse whether the postings list is affected by the deletes.",
"// If yes, we actually reallocate a new postings list.",
"for",
"_",
",",
"l",
":=",
"range",
"vals",
"{",
"// Only lock for processing one postings list so we don't block reads for too long.",
"p",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n\n",
"found",
":=",
"false",
"\n",
"for",
"_",
",",
"id",
":=",
"range",
"p",
".",
"m",
"[",
"n",
"]",
"[",
"l",
"]",
"{",
"if",
"_",
",",
"ok",
":=",
"deleted",
"[",
"id",
"]",
";",
"ok",
"{",
"found",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"found",
"{",
"p",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"repl",
":=",
"make",
"(",
"[",
"]",
"uint64",
",",
"0",
",",
"len",
"(",
"p",
".",
"m",
"[",
"n",
"]",
"[",
"l",
"]",
")",
")",
"\n\n",
"for",
"_",
",",
"id",
":=",
"range",
"p",
".",
"m",
"[",
"n",
"]",
"[",
"l",
"]",
"{",
"if",
"_",
",",
"ok",
":=",
"deleted",
"[",
"id",
"]",
";",
"!",
"ok",
"{",
"repl",
"=",
"append",
"(",
"repl",
",",
"id",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"repl",
")",
">",
"0",
"{",
"p",
".",
"m",
"[",
"n",
"]",
"[",
"l",
"]",
"=",
"repl",
"\n",
"}",
"else",
"{",
"delete",
"(",
"p",
".",
"m",
"[",
"n",
"]",
",",
"l",
")",
"\n",
"}",
"\n",
"p",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"p",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"if",
"len",
"(",
"p",
".",
"m",
"[",
"n",
"]",
")",
"==",
"0",
"{",
"delete",
"(",
"p",
".",
"m",
",",
"n",
")",
"\n",
"}",
"\n",
"p",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"}"
] |
// Delete removes all ids in the given map from the postings lists.
|
[
"Delete",
"removes",
"all",
"ids",
"in",
"the",
"given",
"map",
"from",
"the",
"postings",
"lists",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/index/postings.go#L140-L196
|
train
|
prometheus/tsdb
|
index/postings.go
|
Iter
|
func (p *MemPostings) Iter(f func(labels.Label, Postings) error) error {
p.mtx.RLock()
defer p.mtx.RUnlock()
for n, e := range p.m {
for v, p := range e {
if err := f(labels.Label{Name: n, Value: v}, newListPostings(p...)); err != nil {
return err
}
}
}
return nil
}
|
go
|
func (p *MemPostings) Iter(f func(labels.Label, Postings) error) error {
p.mtx.RLock()
defer p.mtx.RUnlock()
for n, e := range p.m {
for v, p := range e {
if err := f(labels.Label{Name: n, Value: v}, newListPostings(p...)); err != nil {
return err
}
}
}
return nil
}
|
[
"func",
"(",
"p",
"*",
"MemPostings",
")",
"Iter",
"(",
"f",
"func",
"(",
"labels",
".",
"Label",
",",
"Postings",
")",
"error",
")",
"error",
"{",
"p",
".",
"mtx",
".",
"RLock",
"(",
")",
"\n",
"defer",
"p",
".",
"mtx",
".",
"RUnlock",
"(",
")",
"\n\n",
"for",
"n",
",",
"e",
":=",
"range",
"p",
".",
"m",
"{",
"for",
"v",
",",
"p",
":=",
"range",
"e",
"{",
"if",
"err",
":=",
"f",
"(",
"labels",
".",
"Label",
"{",
"Name",
":",
"n",
",",
"Value",
":",
"v",
"}",
",",
"newListPostings",
"(",
"p",
"...",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Iter calls f for each postings list. It aborts if f returns an error and returns it.
|
[
"Iter",
"calls",
"f",
"for",
"each",
"postings",
"list",
".",
"It",
"aborts",
"if",
"f",
"returns",
"an",
"error",
"and",
"returns",
"it",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/index/postings.go#L199-L211
|
train
|
prometheus/tsdb
|
index/postings.go
|
Add
|
func (p *MemPostings) Add(id uint64, lset labels.Labels) {
p.mtx.Lock()
for _, l := range lset {
p.addFor(id, l)
}
p.addFor(id, allPostingsKey)
p.mtx.Unlock()
}
|
go
|
func (p *MemPostings) Add(id uint64, lset labels.Labels) {
p.mtx.Lock()
for _, l := range lset {
p.addFor(id, l)
}
p.addFor(id, allPostingsKey)
p.mtx.Unlock()
}
|
[
"func",
"(",
"p",
"*",
"MemPostings",
")",
"Add",
"(",
"id",
"uint64",
",",
"lset",
"labels",
".",
"Labels",
")",
"{",
"p",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n\n",
"for",
"_",
",",
"l",
":=",
"range",
"lset",
"{",
"p",
".",
"addFor",
"(",
"id",
",",
"l",
")",
"\n",
"}",
"\n",
"p",
".",
"addFor",
"(",
"id",
",",
"allPostingsKey",
")",
"\n\n",
"p",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n",
"}"
] |
// Add a label set to the postings index.
|
[
"Add",
"a",
"label",
"set",
"to",
"the",
"postings",
"index",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/index/postings.go#L214-L223
|
train
|
prometheus/tsdb
|
index/postings.go
|
ExpandPostings
|
func ExpandPostings(p Postings) (res []uint64, err error) {
for p.Next() {
res = append(res, p.At())
}
return res, p.Err()
}
|
go
|
func ExpandPostings(p Postings) (res []uint64, err error) {
for p.Next() {
res = append(res, p.At())
}
return res, p.Err()
}
|
[
"func",
"ExpandPostings",
"(",
"p",
"Postings",
")",
"(",
"res",
"[",
"]",
"uint64",
",",
"err",
"error",
")",
"{",
"for",
"p",
".",
"Next",
"(",
")",
"{",
"res",
"=",
"append",
"(",
"res",
",",
"p",
".",
"At",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"res",
",",
"p",
".",
"Err",
"(",
")",
"\n",
"}"
] |
// ExpandPostings returns the postings expanded as a slice.
|
[
"ExpandPostings",
"returns",
"the",
"postings",
"expanded",
"as",
"a",
"slice",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/index/postings.go#L250-L255
|
train
|
prometheus/tsdb
|
index/postings.go
|
Intersect
|
func Intersect(its ...Postings) Postings {
if len(its) == 0 {
return EmptyPostings()
}
if len(its) == 1 {
return its[0]
}
l := len(its) / 2
a := Intersect(its[:l]...)
b := Intersect(its[l:]...)
if a == EmptyPostings() || b == EmptyPostings() {
return EmptyPostings()
}
return newIntersectPostings(a, b)
}
|
go
|
func Intersect(its ...Postings) Postings {
if len(its) == 0 {
return EmptyPostings()
}
if len(its) == 1 {
return its[0]
}
l := len(its) / 2
a := Intersect(its[:l]...)
b := Intersect(its[l:]...)
if a == EmptyPostings() || b == EmptyPostings() {
return EmptyPostings()
}
return newIntersectPostings(a, b)
}
|
[
"func",
"Intersect",
"(",
"its",
"...",
"Postings",
")",
"Postings",
"{",
"if",
"len",
"(",
"its",
")",
"==",
"0",
"{",
"return",
"EmptyPostings",
"(",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"its",
")",
"==",
"1",
"{",
"return",
"its",
"[",
"0",
"]",
"\n",
"}",
"\n\n",
"l",
":=",
"len",
"(",
"its",
")",
"/",
"2",
"\n",
"a",
":=",
"Intersect",
"(",
"its",
"[",
":",
"l",
"]",
"...",
")",
"\n",
"b",
":=",
"Intersect",
"(",
"its",
"[",
"l",
":",
"]",
"...",
")",
"\n\n",
"if",
"a",
"==",
"EmptyPostings",
"(",
")",
"||",
"b",
"==",
"EmptyPostings",
"(",
")",
"{",
"return",
"EmptyPostings",
"(",
")",
"\n",
"}",
"\n",
"return",
"newIntersectPostings",
"(",
"a",
",",
"b",
")",
"\n",
"}"
] |
// Intersect returns a new postings list over the intersection of the
// input postings.
|
[
"Intersect",
"returns",
"a",
"new",
"postings",
"list",
"over",
"the",
"intersection",
"of",
"the",
"input",
"postings",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/index/postings.go#L299-L315
|
train
|
prometheus/tsdb
|
index/postings.go
|
Merge
|
func Merge(its ...Postings) Postings {
if len(its) == 0 {
return EmptyPostings()
}
if len(its) == 1 {
return its[0]
}
p, ok := newMergedPostings(its)
if !ok {
return EmptyPostings()
}
return p
}
|
go
|
func Merge(its ...Postings) Postings {
if len(its) == 0 {
return EmptyPostings()
}
if len(its) == 1 {
return its[0]
}
p, ok := newMergedPostings(its)
if !ok {
return EmptyPostings()
}
return p
}
|
[
"func",
"Merge",
"(",
"its",
"...",
"Postings",
")",
"Postings",
"{",
"if",
"len",
"(",
"its",
")",
"==",
"0",
"{",
"return",
"EmptyPostings",
"(",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"its",
")",
"==",
"1",
"{",
"return",
"its",
"[",
"0",
"]",
"\n",
"}",
"\n\n",
"p",
",",
"ok",
":=",
"newMergedPostings",
"(",
"its",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"EmptyPostings",
"(",
")",
"\n",
"}",
"\n",
"return",
"p",
"\n",
"}"
] |
// Merge returns a new iterator over the union of the input iterators.
|
[
"Merge",
"returns",
"a",
"new",
"iterator",
"over",
"the",
"union",
"of",
"the",
"input",
"iterators",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/index/postings.go#L371-L384
|
train
|
prometheus/tsdb
|
index/postings.go
|
Without
|
func Without(full, drop Postings) Postings {
if full == EmptyPostings() {
return EmptyPostings()
}
if drop == EmptyPostings() {
return full
}
return newRemovedPostings(full, drop)
}
|
go
|
func Without(full, drop Postings) Postings {
if full == EmptyPostings() {
return EmptyPostings()
}
if drop == EmptyPostings() {
return full
}
return newRemovedPostings(full, drop)
}
|
[
"func",
"Without",
"(",
"full",
",",
"drop",
"Postings",
")",
"Postings",
"{",
"if",
"full",
"==",
"EmptyPostings",
"(",
")",
"{",
"return",
"EmptyPostings",
"(",
")",
"\n",
"}",
"\n\n",
"if",
"drop",
"==",
"EmptyPostings",
"(",
")",
"{",
"return",
"full",
"\n",
"}",
"\n",
"return",
"newRemovedPostings",
"(",
"full",
",",
"drop",
")",
"\n",
"}"
] |
// Without returns a new postings list that contains all elements from the full list that
// are not in the drop list.
|
[
"Without",
"returns",
"a",
"new",
"postings",
"list",
"that",
"contains",
"all",
"elements",
"from",
"the",
"full",
"list",
"that",
"are",
"not",
"in",
"the",
"drop",
"list",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/index/postings.go#L520-L529
|
train
|
prometheus/tsdb
|
fileutil/flock.go
|
Flock
|
func Flock(fileName string) (r Releaser, existed bool, err error) {
if err = os.MkdirAll(filepath.Dir(fileName), 0755); err != nil {
return nil, false, err
}
_, err = os.Stat(fileName)
existed = err == nil
r, err = newLock(fileName)
return r, existed, err
}
|
go
|
func Flock(fileName string) (r Releaser, existed bool, err error) {
if err = os.MkdirAll(filepath.Dir(fileName), 0755); err != nil {
return nil, false, err
}
_, err = os.Stat(fileName)
existed = err == nil
r, err = newLock(fileName)
return r, existed, err
}
|
[
"func",
"Flock",
"(",
"fileName",
"string",
")",
"(",
"r",
"Releaser",
",",
"existed",
"bool",
",",
"err",
"error",
")",
"{",
"if",
"err",
"=",
"os",
".",
"MkdirAll",
"(",
"filepath",
".",
"Dir",
"(",
"fileName",
")",
",",
"0755",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"_",
",",
"err",
"=",
"os",
".",
"Stat",
"(",
"fileName",
")",
"\n",
"existed",
"=",
"err",
"==",
"nil",
"\n\n",
"r",
",",
"err",
"=",
"newLock",
"(",
"fileName",
")",
"\n",
"return",
"r",
",",
"existed",
",",
"err",
"\n",
"}"
] |
// Flock locks the file with the provided name. If the file does not exist, it is
// created. The returned Releaser is used to release the lock. existed is true
// if the file to lock already existed. A non-nil error is returned if the
// locking has failed. Neither this function nor the returned Releaser is
// goroutine-safe.
|
[
"Flock",
"locks",
"the",
"file",
"with",
"the",
"provided",
"name",
".",
"If",
"the",
"file",
"does",
"not",
"exist",
"it",
"is",
"created",
".",
"The",
"returned",
"Releaser",
"is",
"used",
"to",
"release",
"the",
"lock",
".",
"existed",
"is",
"true",
"if",
"the",
"file",
"to",
"lock",
"already",
"existed",
".",
"A",
"non",
"-",
"nil",
"error",
"is",
"returned",
"if",
"the",
"locking",
"has",
"failed",
".",
"Neither",
"this",
"function",
"nor",
"the",
"returned",
"Releaser",
"is",
"goroutine",
"-",
"safe",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/fileutil/flock.go#L31-L41
|
train
|
prometheus/tsdb
|
tsdbutil/chunks.go
|
PopulatedChunk
|
func PopulatedChunk(numSamples int, minTime int64) chunks.Meta {
samples := make([]Sample, numSamples)
for i := 0; i < numSamples; i++ {
samples[i] = sample{minTime + int64(i*1000), 1.0}
}
return ChunkFromSamples(samples)
}
|
go
|
func PopulatedChunk(numSamples int, minTime int64) chunks.Meta {
samples := make([]Sample, numSamples)
for i := 0; i < numSamples; i++ {
samples[i] = sample{minTime + int64(i*1000), 1.0}
}
return ChunkFromSamples(samples)
}
|
[
"func",
"PopulatedChunk",
"(",
"numSamples",
"int",
",",
"minTime",
"int64",
")",
"chunks",
".",
"Meta",
"{",
"samples",
":=",
"make",
"(",
"[",
"]",
"Sample",
",",
"numSamples",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"numSamples",
";",
"i",
"++",
"{",
"samples",
"[",
"i",
"]",
"=",
"sample",
"{",
"minTime",
"+",
"int64",
"(",
"i",
"*",
"1000",
")",
",",
"1.0",
"}",
"\n",
"}",
"\n",
"return",
"ChunkFromSamples",
"(",
"samples",
")",
"\n",
"}"
] |
// PopulatedChunk creates a chunk populated with samples every second starting at minTime
|
[
"PopulatedChunk",
"creates",
"a",
"chunk",
"populated",
"with",
"samples",
"every",
"second",
"starting",
"at",
"minTime"
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/tsdbutil/chunks.go#L47-L53
|
train
|
prometheus/tsdb
|
encoding/encoding.go
|
PutHash
|
func (e *Encbuf) PutHash(h hash.Hash) {
h.Reset()
_, err := h.Write(e.B)
if err != nil {
panic(err) // The CRC32 implementation does not error
}
e.B = h.Sum(e.B)
}
|
go
|
func (e *Encbuf) PutHash(h hash.Hash) {
h.Reset()
_, err := h.Write(e.B)
if err != nil {
panic(err) // The CRC32 implementation does not error
}
e.B = h.Sum(e.B)
}
|
[
"func",
"(",
"e",
"*",
"Encbuf",
")",
"PutHash",
"(",
"h",
"hash",
".",
"Hash",
")",
"{",
"h",
".",
"Reset",
"(",
")",
"\n",
"_",
",",
"err",
":=",
"h",
".",
"Write",
"(",
"e",
".",
"B",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"// The CRC32 implementation does not error",
"\n",
"}",
"\n",
"e",
".",
"B",
"=",
"h",
".",
"Sum",
"(",
"e",
".",
"B",
")",
"\n",
"}"
] |
// PutHash appends a hash over the buffers current contents to the buffer.
|
[
"PutHash",
"appends",
"a",
"hash",
"over",
"the",
"buffers",
"current",
"contents",
"to",
"the",
"buffer",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/encoding/encoding.go#L76-L83
|
train
|
prometheus/tsdb
|
encoding/encoding.go
|
NewDecbufAt
|
func NewDecbufAt(bs ByteSlice, off int, castagnoliTable *crc32.Table) Decbuf {
if bs.Len() < off+4 {
return Decbuf{E: ErrInvalidSize}
}
b := bs.Range(off, off+4)
l := int(binary.BigEndian.Uint32(b))
if bs.Len() < off+4+l+4 {
return Decbuf{E: ErrInvalidSize}
}
// Load bytes holding the contents plus a CRC32 checksum.
b = bs.Range(off+4, off+4+l+4)
dec := Decbuf{B: b[:len(b)-4]}
if exp := binary.BigEndian.Uint32(b[len(b)-4:]); dec.Crc32(castagnoliTable) != exp {
return Decbuf{E: ErrInvalidChecksum}
}
return dec
}
|
go
|
func NewDecbufAt(bs ByteSlice, off int, castagnoliTable *crc32.Table) Decbuf {
if bs.Len() < off+4 {
return Decbuf{E: ErrInvalidSize}
}
b := bs.Range(off, off+4)
l := int(binary.BigEndian.Uint32(b))
if bs.Len() < off+4+l+4 {
return Decbuf{E: ErrInvalidSize}
}
// Load bytes holding the contents plus a CRC32 checksum.
b = bs.Range(off+4, off+4+l+4)
dec := Decbuf{B: b[:len(b)-4]}
if exp := binary.BigEndian.Uint32(b[len(b)-4:]); dec.Crc32(castagnoliTable) != exp {
return Decbuf{E: ErrInvalidChecksum}
}
return dec
}
|
[
"func",
"NewDecbufAt",
"(",
"bs",
"ByteSlice",
",",
"off",
"int",
",",
"castagnoliTable",
"*",
"crc32",
".",
"Table",
")",
"Decbuf",
"{",
"if",
"bs",
".",
"Len",
"(",
")",
"<",
"off",
"+",
"4",
"{",
"return",
"Decbuf",
"{",
"E",
":",
"ErrInvalidSize",
"}",
"\n",
"}",
"\n",
"b",
":=",
"bs",
".",
"Range",
"(",
"off",
",",
"off",
"+",
"4",
")",
"\n",
"l",
":=",
"int",
"(",
"binary",
".",
"BigEndian",
".",
"Uint32",
"(",
"b",
")",
")",
"\n\n",
"if",
"bs",
".",
"Len",
"(",
")",
"<",
"off",
"+",
"4",
"+",
"l",
"+",
"4",
"{",
"return",
"Decbuf",
"{",
"E",
":",
"ErrInvalidSize",
"}",
"\n",
"}",
"\n\n",
"// Load bytes holding the contents plus a CRC32 checksum.",
"b",
"=",
"bs",
".",
"Range",
"(",
"off",
"+",
"4",
",",
"off",
"+",
"4",
"+",
"l",
"+",
"4",
")",
"\n",
"dec",
":=",
"Decbuf",
"{",
"B",
":",
"b",
"[",
":",
"len",
"(",
"b",
")",
"-",
"4",
"]",
"}",
"\n\n",
"if",
"exp",
":=",
"binary",
".",
"BigEndian",
".",
"Uint32",
"(",
"b",
"[",
"len",
"(",
"b",
")",
"-",
"4",
":",
"]",
")",
";",
"dec",
".",
"Crc32",
"(",
"castagnoliTable",
")",
"!=",
"exp",
"{",
"return",
"Decbuf",
"{",
"E",
":",
"ErrInvalidChecksum",
"}",
"\n",
"}",
"\n",
"return",
"dec",
"\n",
"}"
] |
// NewDecbufAt returns a new decoding buffer. It expects the first 4 bytes
// after offset to hold the big endian encoded content length, followed by the contents and the expected
// checksum.
|
[
"NewDecbufAt",
"returns",
"a",
"new",
"decoding",
"buffer",
".",
"It",
"expects",
"the",
"first",
"4",
"bytes",
"after",
"offset",
"to",
"hold",
"the",
"big",
"endian",
"encoded",
"content",
"length",
"followed",
"by",
"the",
"contents",
"and",
"the",
"expected",
"checksum",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/encoding/encoding.go#L97-L116
|
train
|
prometheus/tsdb
|
encoding/encoding.go
|
NewDecbufUvarintAt
|
func NewDecbufUvarintAt(bs ByteSlice, off int, castagnoliTable *crc32.Table) Decbuf {
// We never have to access this method at the far end of the byte slice. Thus just checking
// against the MaxVarintLen32 is sufficient.
if bs.Len() < off+binary.MaxVarintLen32 {
return Decbuf{E: ErrInvalidSize}
}
b := bs.Range(off, off+binary.MaxVarintLen32)
l, n := binary.Uvarint(b)
if n <= 0 || n > binary.MaxVarintLen32 {
return Decbuf{E: errors.Errorf("invalid uvarint %d", n)}
}
if bs.Len() < off+n+int(l)+4 {
return Decbuf{E: ErrInvalidSize}
}
// Load bytes holding the contents plus a CRC32 checksum.
b = bs.Range(off+n, off+n+int(l)+4)
dec := Decbuf{B: b[:len(b)-4]}
if dec.Crc32(castagnoliTable) != binary.BigEndian.Uint32(b[len(b)-4:]) {
return Decbuf{E: ErrInvalidChecksum}
}
return dec
}
|
go
|
func NewDecbufUvarintAt(bs ByteSlice, off int, castagnoliTable *crc32.Table) Decbuf {
// We never have to access this method at the far end of the byte slice. Thus just checking
// against the MaxVarintLen32 is sufficient.
if bs.Len() < off+binary.MaxVarintLen32 {
return Decbuf{E: ErrInvalidSize}
}
b := bs.Range(off, off+binary.MaxVarintLen32)
l, n := binary.Uvarint(b)
if n <= 0 || n > binary.MaxVarintLen32 {
return Decbuf{E: errors.Errorf("invalid uvarint %d", n)}
}
if bs.Len() < off+n+int(l)+4 {
return Decbuf{E: ErrInvalidSize}
}
// Load bytes holding the contents plus a CRC32 checksum.
b = bs.Range(off+n, off+n+int(l)+4)
dec := Decbuf{B: b[:len(b)-4]}
if dec.Crc32(castagnoliTable) != binary.BigEndian.Uint32(b[len(b)-4:]) {
return Decbuf{E: ErrInvalidChecksum}
}
return dec
}
|
[
"func",
"NewDecbufUvarintAt",
"(",
"bs",
"ByteSlice",
",",
"off",
"int",
",",
"castagnoliTable",
"*",
"crc32",
".",
"Table",
")",
"Decbuf",
"{",
"// We never have to access this method at the far end of the byte slice. Thus just checking",
"// against the MaxVarintLen32 is sufficient.",
"if",
"bs",
".",
"Len",
"(",
")",
"<",
"off",
"+",
"binary",
".",
"MaxVarintLen32",
"{",
"return",
"Decbuf",
"{",
"E",
":",
"ErrInvalidSize",
"}",
"\n",
"}",
"\n",
"b",
":=",
"bs",
".",
"Range",
"(",
"off",
",",
"off",
"+",
"binary",
".",
"MaxVarintLen32",
")",
"\n\n",
"l",
",",
"n",
":=",
"binary",
".",
"Uvarint",
"(",
"b",
")",
"\n",
"if",
"n",
"<=",
"0",
"||",
"n",
">",
"binary",
".",
"MaxVarintLen32",
"{",
"return",
"Decbuf",
"{",
"E",
":",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"n",
")",
"}",
"\n",
"}",
"\n\n",
"if",
"bs",
".",
"Len",
"(",
")",
"<",
"off",
"+",
"n",
"+",
"int",
"(",
"l",
")",
"+",
"4",
"{",
"return",
"Decbuf",
"{",
"E",
":",
"ErrInvalidSize",
"}",
"\n",
"}",
"\n\n",
"// Load bytes holding the contents plus a CRC32 checksum.",
"b",
"=",
"bs",
".",
"Range",
"(",
"off",
"+",
"n",
",",
"off",
"+",
"n",
"+",
"int",
"(",
"l",
")",
"+",
"4",
")",
"\n",
"dec",
":=",
"Decbuf",
"{",
"B",
":",
"b",
"[",
":",
"len",
"(",
"b",
")",
"-",
"4",
"]",
"}",
"\n\n",
"if",
"dec",
".",
"Crc32",
"(",
"castagnoliTable",
")",
"!=",
"binary",
".",
"BigEndian",
".",
"Uint32",
"(",
"b",
"[",
"len",
"(",
"b",
")",
"-",
"4",
":",
"]",
")",
"{",
"return",
"Decbuf",
"{",
"E",
":",
"ErrInvalidChecksum",
"}",
"\n",
"}",
"\n",
"return",
"dec",
"\n",
"}"
] |
// NewDecbufUvarintAt returns a new decoding buffer. It expects the first bytes
// after offset to hold the uvarint-encoded buffers length, followed by the contents and the expected
// checksum.
|
[
"NewDecbufUvarintAt",
"returns",
"a",
"new",
"decoding",
"buffer",
".",
"It",
"expects",
"the",
"first",
"bytes",
"after",
"offset",
"to",
"hold",
"the",
"uvarint",
"-",
"encoded",
"buffers",
"length",
"followed",
"by",
"the",
"contents",
"and",
"the",
"expected",
"checksum",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/encoding/encoding.go#L121-L146
|
train
|
prometheus/tsdb
|
encoding/encoding.go
|
Crc32
|
func (d *Decbuf) Crc32(castagnoliTable *crc32.Table) uint32 {
return crc32.Checksum(d.B, castagnoliTable)
}
|
go
|
func (d *Decbuf) Crc32(castagnoliTable *crc32.Table) uint32 {
return crc32.Checksum(d.B, castagnoliTable)
}
|
[
"func",
"(",
"d",
"*",
"Decbuf",
")",
"Crc32",
"(",
"castagnoliTable",
"*",
"crc32",
".",
"Table",
")",
"uint32",
"{",
"return",
"crc32",
".",
"Checksum",
"(",
"d",
".",
"B",
",",
"castagnoliTable",
")",
"\n",
"}"
] |
// Crc32 returns a CRC32 checksum over the remaining bytes.
|
[
"Crc32",
"returns",
"a",
"CRC32",
"checksum",
"over",
"the",
"remaining",
"bytes",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/encoding/encoding.go#L153-L155
|
train
|
prometheus/tsdb
|
block.go
|
OpenBlock
|
func OpenBlock(logger log.Logger, dir string, pool chunkenc.Pool) (pb *Block, err error) {
if logger == nil {
logger = log.NewNopLogger()
}
var closers []io.Closer
defer func() {
if err != nil {
var merr tsdb_errors.MultiError
merr.Add(err)
merr.Add(closeAll(closers))
err = merr.Err()
}
}()
meta, err := readMetaFile(dir)
if err != nil {
return nil, err
}
cr, err := chunks.NewDirReader(chunkDir(dir), pool)
if err != nil {
return nil, err
}
closers = append(closers, cr)
ir, err := index.NewFileReader(filepath.Join(dir, indexFilename))
if err != nil {
return nil, err
}
closers = append(closers, ir)
tr, tsr, err := readTombstones(dir)
if err != nil {
return nil, err
}
closers = append(closers, tr)
// TODO refactor to set this at block creation time as
// that would be the logical place for a block size to be calculated.
bs := blockSize(cr, ir, tsr)
meta.Stats.NumBytes = bs
err = writeMetaFile(logger, dir, meta)
if err != nil {
level.Warn(logger).Log("msg", "couldn't write the meta file for the block size", "block", dir, "err", err)
}
pb = &Block{
dir: dir,
meta: *meta,
chunkr: cr,
indexr: ir,
tombstones: tr,
symbolTableSize: ir.SymbolTableSize(),
logger: logger,
}
return pb, nil
}
|
go
|
func OpenBlock(logger log.Logger, dir string, pool chunkenc.Pool) (pb *Block, err error) {
if logger == nil {
logger = log.NewNopLogger()
}
var closers []io.Closer
defer func() {
if err != nil {
var merr tsdb_errors.MultiError
merr.Add(err)
merr.Add(closeAll(closers))
err = merr.Err()
}
}()
meta, err := readMetaFile(dir)
if err != nil {
return nil, err
}
cr, err := chunks.NewDirReader(chunkDir(dir), pool)
if err != nil {
return nil, err
}
closers = append(closers, cr)
ir, err := index.NewFileReader(filepath.Join(dir, indexFilename))
if err != nil {
return nil, err
}
closers = append(closers, ir)
tr, tsr, err := readTombstones(dir)
if err != nil {
return nil, err
}
closers = append(closers, tr)
// TODO refactor to set this at block creation time as
// that would be the logical place for a block size to be calculated.
bs := blockSize(cr, ir, tsr)
meta.Stats.NumBytes = bs
err = writeMetaFile(logger, dir, meta)
if err != nil {
level.Warn(logger).Log("msg", "couldn't write the meta file for the block size", "block", dir, "err", err)
}
pb = &Block{
dir: dir,
meta: *meta,
chunkr: cr,
indexr: ir,
tombstones: tr,
symbolTableSize: ir.SymbolTableSize(),
logger: logger,
}
return pb, nil
}
|
[
"func",
"OpenBlock",
"(",
"logger",
"log",
".",
"Logger",
",",
"dir",
"string",
",",
"pool",
"chunkenc",
".",
"Pool",
")",
"(",
"pb",
"*",
"Block",
",",
"err",
"error",
")",
"{",
"if",
"logger",
"==",
"nil",
"{",
"logger",
"=",
"log",
".",
"NewNopLogger",
"(",
")",
"\n",
"}",
"\n",
"var",
"closers",
"[",
"]",
"io",
".",
"Closer",
"\n",
"defer",
"func",
"(",
")",
"{",
"if",
"err",
"!=",
"nil",
"{",
"var",
"merr",
"tsdb_errors",
".",
"MultiError",
"\n",
"merr",
".",
"Add",
"(",
"err",
")",
"\n",
"merr",
".",
"Add",
"(",
"closeAll",
"(",
"closers",
")",
")",
"\n",
"err",
"=",
"merr",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"meta",
",",
"err",
":=",
"readMetaFile",
"(",
"dir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"cr",
",",
"err",
":=",
"chunks",
".",
"NewDirReader",
"(",
"chunkDir",
"(",
"dir",
")",
",",
"pool",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"closers",
"=",
"append",
"(",
"closers",
",",
"cr",
")",
"\n\n",
"ir",
",",
"err",
":=",
"index",
".",
"NewFileReader",
"(",
"filepath",
".",
"Join",
"(",
"dir",
",",
"indexFilename",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"closers",
"=",
"append",
"(",
"closers",
",",
"ir",
")",
"\n\n",
"tr",
",",
"tsr",
",",
"err",
":=",
"readTombstones",
"(",
"dir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"closers",
"=",
"append",
"(",
"closers",
",",
"tr",
")",
"\n\n",
"// TODO refactor to set this at block creation time as",
"// that would be the logical place for a block size to be calculated.",
"bs",
":=",
"blockSize",
"(",
"cr",
",",
"ir",
",",
"tsr",
")",
"\n",
"meta",
".",
"Stats",
".",
"NumBytes",
"=",
"bs",
"\n",
"err",
"=",
"writeMetaFile",
"(",
"logger",
",",
"dir",
",",
"meta",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"level",
".",
"Warn",
"(",
"logger",
")",
".",
"Log",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"dir",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"pb",
"=",
"&",
"Block",
"{",
"dir",
":",
"dir",
",",
"meta",
":",
"*",
"meta",
",",
"chunkr",
":",
"cr",
",",
"indexr",
":",
"ir",
",",
"tombstones",
":",
"tr",
",",
"symbolTableSize",
":",
"ir",
".",
"SymbolTableSize",
"(",
")",
",",
"logger",
":",
"logger",
",",
"}",
"\n",
"return",
"pb",
",",
"nil",
"\n",
"}"
] |
// OpenBlock opens the block in the directory. It can be passed a chunk pool, which is used
// to instantiate chunk structs.
|
[
"OpenBlock",
"opens",
"the",
"block",
"in",
"the",
"directory",
".",
"It",
"can",
"be",
"passed",
"a",
"chunk",
"pool",
"which",
"is",
"used",
"to",
"instantiate",
"chunk",
"structs",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/block.go#L292-L347
|
train
|
prometheus/tsdb
|
block.go
|
Close
|
func (pb *Block) Close() error {
pb.mtx.Lock()
pb.closing = true
pb.mtx.Unlock()
pb.pendingReaders.Wait()
var merr tsdb_errors.MultiError
merr.Add(pb.chunkr.Close())
merr.Add(pb.indexr.Close())
merr.Add(pb.tombstones.Close())
return merr.Err()
}
|
go
|
func (pb *Block) Close() error {
pb.mtx.Lock()
pb.closing = true
pb.mtx.Unlock()
pb.pendingReaders.Wait()
var merr tsdb_errors.MultiError
merr.Add(pb.chunkr.Close())
merr.Add(pb.indexr.Close())
merr.Add(pb.tombstones.Close())
return merr.Err()
}
|
[
"func",
"(",
"pb",
"*",
"Block",
")",
"Close",
"(",
")",
"error",
"{",
"pb",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"pb",
".",
"closing",
"=",
"true",
"\n",
"pb",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"pb",
".",
"pendingReaders",
".",
"Wait",
"(",
")",
"\n\n",
"var",
"merr",
"tsdb_errors",
".",
"MultiError",
"\n\n",
"merr",
".",
"Add",
"(",
"pb",
".",
"chunkr",
".",
"Close",
"(",
")",
")",
"\n",
"merr",
".",
"Add",
"(",
"pb",
".",
"indexr",
".",
"Close",
"(",
")",
")",
"\n",
"merr",
".",
"Add",
"(",
"pb",
".",
"tombstones",
".",
"Close",
"(",
")",
")",
"\n\n",
"return",
"merr",
".",
"Err",
"(",
")",
"\n",
"}"
] |
// Close closes the on-disk block. It blocks as long as there are readers reading from the block.
|
[
"Close",
"closes",
"the",
"on",
"-",
"disk",
"block",
".",
"It",
"blocks",
"as",
"long",
"as",
"there",
"are",
"readers",
"reading",
"from",
"the",
"block",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/block.go#L360-L374
|
train
|
prometheus/tsdb
|
block.go
|
Index
|
func (pb *Block) Index() (IndexReader, error) {
if err := pb.startRead(); err != nil {
return nil, err
}
return blockIndexReader{ir: pb.indexr, b: pb}, nil
}
|
go
|
func (pb *Block) Index() (IndexReader, error) {
if err := pb.startRead(); err != nil {
return nil, err
}
return blockIndexReader{ir: pb.indexr, b: pb}, nil
}
|
[
"func",
"(",
"pb",
"*",
"Block",
")",
"Index",
"(",
")",
"(",
"IndexReader",
",",
"error",
")",
"{",
"if",
"err",
":=",
"pb",
".",
"startRead",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"blockIndexReader",
"{",
"ir",
":",
"pb",
".",
"indexr",
",",
"b",
":",
"pb",
"}",
",",
"nil",
"\n",
"}"
] |
// Index returns a new IndexReader against the block data.
|
[
"Index",
"returns",
"a",
"new",
"IndexReader",
"against",
"the",
"block",
"data",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/block.go#L410-L415
|
train
|
prometheus/tsdb
|
block.go
|
Chunks
|
func (pb *Block) Chunks() (ChunkReader, error) {
if err := pb.startRead(); err != nil {
return nil, err
}
return blockChunkReader{ChunkReader: pb.chunkr, b: pb}, nil
}
|
go
|
func (pb *Block) Chunks() (ChunkReader, error) {
if err := pb.startRead(); err != nil {
return nil, err
}
return blockChunkReader{ChunkReader: pb.chunkr, b: pb}, nil
}
|
[
"func",
"(",
"pb",
"*",
"Block",
")",
"Chunks",
"(",
")",
"(",
"ChunkReader",
",",
"error",
")",
"{",
"if",
"err",
":=",
"pb",
".",
"startRead",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"blockChunkReader",
"{",
"ChunkReader",
":",
"pb",
".",
"chunkr",
",",
"b",
":",
"pb",
"}",
",",
"nil",
"\n",
"}"
] |
// Chunks returns a new ChunkReader against the block data.
|
[
"Chunks",
"returns",
"a",
"new",
"ChunkReader",
"against",
"the",
"block",
"data",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/block.go#L418-L423
|
train
|
prometheus/tsdb
|
block.go
|
Tombstones
|
func (pb *Block) Tombstones() (TombstoneReader, error) {
if err := pb.startRead(); err != nil {
return nil, err
}
return blockTombstoneReader{TombstoneReader: pb.tombstones, b: pb}, nil
}
|
go
|
func (pb *Block) Tombstones() (TombstoneReader, error) {
if err := pb.startRead(); err != nil {
return nil, err
}
return blockTombstoneReader{TombstoneReader: pb.tombstones, b: pb}, nil
}
|
[
"func",
"(",
"pb",
"*",
"Block",
")",
"Tombstones",
"(",
")",
"(",
"TombstoneReader",
",",
"error",
")",
"{",
"if",
"err",
":=",
"pb",
".",
"startRead",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"blockTombstoneReader",
"{",
"TombstoneReader",
":",
"pb",
".",
"tombstones",
",",
"b",
":",
"pb",
"}",
",",
"nil",
"\n",
"}"
] |
// Tombstones returns a new TombstoneReader against the block data.
|
[
"Tombstones",
"returns",
"a",
"new",
"TombstoneReader",
"against",
"the",
"block",
"data",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/block.go#L426-L431
|
train
|
prometheus/tsdb
|
block.go
|
Delete
|
func (pb *Block) Delete(mint, maxt int64, ms ...labels.Matcher) error {
pb.mtx.Lock()
defer pb.mtx.Unlock()
if pb.closing {
return ErrClosing
}
p, err := PostingsForMatchers(pb.indexr, ms...)
if err != nil {
return errors.Wrap(err, "select series")
}
ir := pb.indexr
// Choose only valid postings which have chunks in the time-range.
stones := newMemTombstones()
var lset labels.Labels
var chks []chunks.Meta
Outer:
for p.Next() {
err := ir.Series(p.At(), &lset, &chks)
if err != nil {
return err
}
for _, chk := range chks {
if chk.OverlapsClosedInterval(mint, maxt) {
// Delete only until the current values and not beyond.
tmin, tmax := clampInterval(mint, maxt, chks[0].MinTime, chks[len(chks)-1].MaxTime)
stones.addInterval(p.At(), Interval{tmin, tmax})
continue Outer
}
}
}
if p.Err() != nil {
return p.Err()
}
err = pb.tombstones.Iter(func(id uint64, ivs Intervals) error {
for _, iv := range ivs {
stones.addInterval(id, iv)
}
return nil
})
if err != nil {
return err
}
pb.tombstones = stones
pb.meta.Stats.NumTombstones = pb.tombstones.Total()
if err := writeTombstoneFile(pb.logger, pb.dir, pb.tombstones); err != nil {
return err
}
return writeMetaFile(pb.logger, pb.dir, &pb.meta)
}
|
go
|
func (pb *Block) Delete(mint, maxt int64, ms ...labels.Matcher) error {
pb.mtx.Lock()
defer pb.mtx.Unlock()
if pb.closing {
return ErrClosing
}
p, err := PostingsForMatchers(pb.indexr, ms...)
if err != nil {
return errors.Wrap(err, "select series")
}
ir := pb.indexr
// Choose only valid postings which have chunks in the time-range.
stones := newMemTombstones()
var lset labels.Labels
var chks []chunks.Meta
Outer:
for p.Next() {
err := ir.Series(p.At(), &lset, &chks)
if err != nil {
return err
}
for _, chk := range chks {
if chk.OverlapsClosedInterval(mint, maxt) {
// Delete only until the current values and not beyond.
tmin, tmax := clampInterval(mint, maxt, chks[0].MinTime, chks[len(chks)-1].MaxTime)
stones.addInterval(p.At(), Interval{tmin, tmax})
continue Outer
}
}
}
if p.Err() != nil {
return p.Err()
}
err = pb.tombstones.Iter(func(id uint64, ivs Intervals) error {
for _, iv := range ivs {
stones.addInterval(id, iv)
}
return nil
})
if err != nil {
return err
}
pb.tombstones = stones
pb.meta.Stats.NumTombstones = pb.tombstones.Total()
if err := writeTombstoneFile(pb.logger, pb.dir, pb.tombstones); err != nil {
return err
}
return writeMetaFile(pb.logger, pb.dir, &pb.meta)
}
|
[
"func",
"(",
"pb",
"*",
"Block",
")",
"Delete",
"(",
"mint",
",",
"maxt",
"int64",
",",
"ms",
"...",
"labels",
".",
"Matcher",
")",
"error",
"{",
"pb",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"pb",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"pb",
".",
"closing",
"{",
"return",
"ErrClosing",
"\n",
"}",
"\n\n",
"p",
",",
"err",
":=",
"PostingsForMatchers",
"(",
"pb",
".",
"indexr",
",",
"ms",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"ir",
":=",
"pb",
".",
"indexr",
"\n\n",
"// Choose only valid postings which have chunks in the time-range.",
"stones",
":=",
"newMemTombstones",
"(",
")",
"\n\n",
"var",
"lset",
"labels",
".",
"Labels",
"\n",
"var",
"chks",
"[",
"]",
"chunks",
".",
"Meta",
"\n\n",
"Outer",
":",
"for",
"p",
".",
"Next",
"(",
")",
"{",
"err",
":=",
"ir",
".",
"Series",
"(",
"p",
".",
"At",
"(",
")",
",",
"&",
"lset",
",",
"&",
"chks",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"chk",
":=",
"range",
"chks",
"{",
"if",
"chk",
".",
"OverlapsClosedInterval",
"(",
"mint",
",",
"maxt",
")",
"{",
"// Delete only until the current values and not beyond.",
"tmin",
",",
"tmax",
":=",
"clampInterval",
"(",
"mint",
",",
"maxt",
",",
"chks",
"[",
"0",
"]",
".",
"MinTime",
",",
"chks",
"[",
"len",
"(",
"chks",
")",
"-",
"1",
"]",
".",
"MaxTime",
")",
"\n",
"stones",
".",
"addInterval",
"(",
"p",
".",
"At",
"(",
")",
",",
"Interval",
"{",
"tmin",
",",
"tmax",
"}",
")",
"\n",
"continue",
"Outer",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"p",
".",
"Err",
"(",
")",
"!=",
"nil",
"{",
"return",
"p",
".",
"Err",
"(",
")",
"\n",
"}",
"\n\n",
"err",
"=",
"pb",
".",
"tombstones",
".",
"Iter",
"(",
"func",
"(",
"id",
"uint64",
",",
"ivs",
"Intervals",
")",
"error",
"{",
"for",
"_",
",",
"iv",
":=",
"range",
"ivs",
"{",
"stones",
".",
"addInterval",
"(",
"id",
",",
"iv",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"pb",
".",
"tombstones",
"=",
"stones",
"\n",
"pb",
".",
"meta",
".",
"Stats",
".",
"NumTombstones",
"=",
"pb",
".",
"tombstones",
".",
"Total",
"(",
")",
"\n\n",
"if",
"err",
":=",
"writeTombstoneFile",
"(",
"pb",
".",
"logger",
",",
"pb",
".",
"dir",
",",
"pb",
".",
"tombstones",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"writeMetaFile",
"(",
"pb",
".",
"logger",
",",
"pb",
".",
"dir",
",",
"&",
"pb",
".",
"meta",
")",
"\n",
"}"
] |
// Delete matching series between mint and maxt in the block.
|
[
"Delete",
"matching",
"series",
"between",
"mint",
"and",
"maxt",
"in",
"the",
"block",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/block.go#L510-L568
|
train
|
prometheus/tsdb
|
block.go
|
Snapshot
|
func (pb *Block) Snapshot(dir string) error {
blockDir := filepath.Join(dir, pb.meta.ULID.String())
if err := os.MkdirAll(blockDir, 0777); err != nil {
return errors.Wrap(err, "create snapshot block dir")
}
chunksDir := chunkDir(blockDir)
if err := os.MkdirAll(chunksDir, 0777); err != nil {
return errors.Wrap(err, "create snapshot chunk dir")
}
// Hardlink meta, index and tombstones
for _, fname := range []string{
metaFilename,
indexFilename,
tombstoneFilename,
} {
if err := os.Link(filepath.Join(pb.dir, fname), filepath.Join(blockDir, fname)); err != nil {
return errors.Wrapf(err, "create snapshot %s", fname)
}
}
// Hardlink the chunks
curChunkDir := chunkDir(pb.dir)
files, err := ioutil.ReadDir(curChunkDir)
if err != nil {
return errors.Wrap(err, "ReadDir the current chunk dir")
}
for _, f := range files {
err := os.Link(filepath.Join(curChunkDir, f.Name()), filepath.Join(chunksDir, f.Name()))
if err != nil {
return errors.Wrap(err, "hardlink a chunk")
}
}
return nil
}
|
go
|
func (pb *Block) Snapshot(dir string) error {
blockDir := filepath.Join(dir, pb.meta.ULID.String())
if err := os.MkdirAll(blockDir, 0777); err != nil {
return errors.Wrap(err, "create snapshot block dir")
}
chunksDir := chunkDir(blockDir)
if err := os.MkdirAll(chunksDir, 0777); err != nil {
return errors.Wrap(err, "create snapshot chunk dir")
}
// Hardlink meta, index and tombstones
for _, fname := range []string{
metaFilename,
indexFilename,
tombstoneFilename,
} {
if err := os.Link(filepath.Join(pb.dir, fname), filepath.Join(blockDir, fname)); err != nil {
return errors.Wrapf(err, "create snapshot %s", fname)
}
}
// Hardlink the chunks
curChunkDir := chunkDir(pb.dir)
files, err := ioutil.ReadDir(curChunkDir)
if err != nil {
return errors.Wrap(err, "ReadDir the current chunk dir")
}
for _, f := range files {
err := os.Link(filepath.Join(curChunkDir, f.Name()), filepath.Join(chunksDir, f.Name()))
if err != nil {
return errors.Wrap(err, "hardlink a chunk")
}
}
return nil
}
|
[
"func",
"(",
"pb",
"*",
"Block",
")",
"Snapshot",
"(",
"dir",
"string",
")",
"error",
"{",
"blockDir",
":=",
"filepath",
".",
"Join",
"(",
"dir",
",",
"pb",
".",
"meta",
".",
"ULID",
".",
"String",
"(",
")",
")",
"\n",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"blockDir",
",",
"0777",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"chunksDir",
":=",
"chunkDir",
"(",
"blockDir",
")",
"\n",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"chunksDir",
",",
"0777",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Hardlink meta, index and tombstones",
"for",
"_",
",",
"fname",
":=",
"range",
"[",
"]",
"string",
"{",
"metaFilename",
",",
"indexFilename",
",",
"tombstoneFilename",
",",
"}",
"{",
"if",
"err",
":=",
"os",
".",
"Link",
"(",
"filepath",
".",
"Join",
"(",
"pb",
".",
"dir",
",",
"fname",
")",
",",
"filepath",
".",
"Join",
"(",
"blockDir",
",",
"fname",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"fname",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Hardlink the chunks",
"curChunkDir",
":=",
"chunkDir",
"(",
"pb",
".",
"dir",
")",
"\n",
"files",
",",
"err",
":=",
"ioutil",
".",
"ReadDir",
"(",
"curChunkDir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"f",
":=",
"range",
"files",
"{",
"err",
":=",
"os",
".",
"Link",
"(",
"filepath",
".",
"Join",
"(",
"curChunkDir",
",",
"f",
".",
"Name",
"(",
")",
")",
",",
"filepath",
".",
"Join",
"(",
"chunksDir",
",",
"f",
".",
"Name",
"(",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Snapshot creates snapshot of the block into dir.
|
[
"Snapshot",
"creates",
"snapshot",
"of",
"the",
"block",
"into",
"dir",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/block.go#L595-L632
|
train
|
prometheus/tsdb
|
wal.go
|
OpenSegmentWAL
|
func OpenSegmentWAL(dir string, logger log.Logger, flushInterval time.Duration, r prometheus.Registerer) (*SegmentWAL, error) {
if err := os.MkdirAll(dir, 0777); err != nil {
return nil, err
}
df, err := fileutil.OpenDir(dir)
if err != nil {
return nil, err
}
if logger == nil {
logger = log.NewNopLogger()
}
w := &SegmentWAL{
dirFile: df,
logger: logger,
flushInterval: flushInterval,
donec: make(chan struct{}),
stopc: make(chan struct{}),
actorc: make(chan func() error, 1),
segmentSize: walSegmentSizeBytes,
crc32: newCRC32(),
}
w.metrics = newWalMetrics(w, r)
fns, err := sequenceFiles(w.dirFile.Name())
if err != nil {
return nil, err
}
for i, fn := range fns {
f, err := w.openSegmentFile(fn)
if err == nil {
w.files = append(w.files, newSegmentFile(f))
continue
}
level.Warn(logger).Log("msg", "invalid segment file detected, truncating WAL", "err", err, "file", fn)
for _, fn := range fns[i:] {
if err := os.Remove(fn); err != nil {
return w, errors.Wrap(err, "removing segment failed")
}
}
break
}
go w.run(flushInterval)
return w, nil
}
|
go
|
func OpenSegmentWAL(dir string, logger log.Logger, flushInterval time.Duration, r prometheus.Registerer) (*SegmentWAL, error) {
if err := os.MkdirAll(dir, 0777); err != nil {
return nil, err
}
df, err := fileutil.OpenDir(dir)
if err != nil {
return nil, err
}
if logger == nil {
logger = log.NewNopLogger()
}
w := &SegmentWAL{
dirFile: df,
logger: logger,
flushInterval: flushInterval,
donec: make(chan struct{}),
stopc: make(chan struct{}),
actorc: make(chan func() error, 1),
segmentSize: walSegmentSizeBytes,
crc32: newCRC32(),
}
w.metrics = newWalMetrics(w, r)
fns, err := sequenceFiles(w.dirFile.Name())
if err != nil {
return nil, err
}
for i, fn := range fns {
f, err := w.openSegmentFile(fn)
if err == nil {
w.files = append(w.files, newSegmentFile(f))
continue
}
level.Warn(logger).Log("msg", "invalid segment file detected, truncating WAL", "err", err, "file", fn)
for _, fn := range fns[i:] {
if err := os.Remove(fn); err != nil {
return w, errors.Wrap(err, "removing segment failed")
}
}
break
}
go w.run(flushInterval)
return w, nil
}
|
[
"func",
"OpenSegmentWAL",
"(",
"dir",
"string",
",",
"logger",
"log",
".",
"Logger",
",",
"flushInterval",
"time",
".",
"Duration",
",",
"r",
"prometheus",
".",
"Registerer",
")",
"(",
"*",
"SegmentWAL",
",",
"error",
")",
"{",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"dir",
",",
"0777",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"df",
",",
"err",
":=",
"fileutil",
".",
"OpenDir",
"(",
"dir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"logger",
"==",
"nil",
"{",
"logger",
"=",
"log",
".",
"NewNopLogger",
"(",
")",
"\n",
"}",
"\n\n",
"w",
":=",
"&",
"SegmentWAL",
"{",
"dirFile",
":",
"df",
",",
"logger",
":",
"logger",
",",
"flushInterval",
":",
"flushInterval",
",",
"donec",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"stopc",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"actorc",
":",
"make",
"(",
"chan",
"func",
"(",
")",
"error",
",",
"1",
")",
",",
"segmentSize",
":",
"walSegmentSizeBytes",
",",
"crc32",
":",
"newCRC32",
"(",
")",
",",
"}",
"\n",
"w",
".",
"metrics",
"=",
"newWalMetrics",
"(",
"w",
",",
"r",
")",
"\n\n",
"fns",
",",
"err",
":=",
"sequenceFiles",
"(",
"w",
".",
"dirFile",
".",
"Name",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"for",
"i",
",",
"fn",
":=",
"range",
"fns",
"{",
"f",
",",
"err",
":=",
"w",
".",
"openSegmentFile",
"(",
"fn",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"w",
".",
"files",
"=",
"append",
"(",
"w",
".",
"files",
",",
"newSegmentFile",
"(",
"f",
")",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"level",
".",
"Warn",
"(",
"logger",
")",
".",
"Log",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
",",
"\"",
"\"",
",",
"fn",
")",
"\n\n",
"for",
"_",
",",
"fn",
":=",
"range",
"fns",
"[",
"i",
":",
"]",
"{",
"if",
"err",
":=",
"os",
".",
"Remove",
"(",
"fn",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"w",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"break",
"\n",
"}",
"\n\n",
"go",
"w",
".",
"run",
"(",
"flushInterval",
")",
"\n\n",
"return",
"w",
",",
"nil",
"\n",
"}"
] |
// OpenSegmentWAL opens or creates a write ahead log in the given directory.
// The WAL must be read completely before new data is written.
|
[
"OpenSegmentWAL",
"opens",
"or",
"creates",
"a",
"write",
"ahead",
"log",
"in",
"the",
"given",
"directory",
".",
"The",
"WAL",
"must",
"be",
"read",
"completely",
"before",
"new",
"data",
"is",
"written",
"."
] |
3ccab17f5dc60de1bea3e5cfc807cb63a287078f
|
https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/wal.go#L184-L232
|
train
|
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.