repo stringlengths 5 67 | path stringlengths 4 218 | func_name stringlengths 0 151 | original_string stringlengths 52 373k | language stringclasses 6 values | code stringlengths 52 373k | code_tokens listlengths 10 512 | docstring stringlengths 3 47.2k | docstring_tokens listlengths 3 234 | sha stringlengths 40 40 | url stringlengths 85 339 | partition stringclasses 3 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
gopherjs/gopherjs | js/js.go | MakeWrapper | func MakeWrapper(i interface{}) *Object {
v := InternalObject(i)
o := Global.Get("Object").New()
o.Set("__internal_object__", v)
methods := v.Get("constructor").Get("methods")
for i := 0; i < methods.Length(); i++ {
m := methods.Index(i)
if m.Get("pkg").String() != "" { // not exported
continue
}
o.Set(m.Get("name").String(), func(args ...*Object) *Object {
return Global.Call("$externalizeFunction", v.Get(m.Get("prop").String()), m.Get("typ"), true).Call("apply", v, args)
})
}
return o
} | go | func MakeWrapper(i interface{}) *Object {
v := InternalObject(i)
o := Global.Get("Object").New()
o.Set("__internal_object__", v)
methods := v.Get("constructor").Get("methods")
for i := 0; i < methods.Length(); i++ {
m := methods.Index(i)
if m.Get("pkg").String() != "" { // not exported
continue
}
o.Set(m.Get("name").String(), func(args ...*Object) *Object {
return Global.Call("$externalizeFunction", v.Get(m.Get("prop").String()), m.Get("typ"), true).Call("apply", v, args)
})
}
return o
} | [
"func",
"MakeWrapper",
"(",
"i",
"interface",
"{",
"}",
")",
"*",
"Object",
"{",
"v",
":=",
"InternalObject",
"(",
"i",
")",
"\n",
"o",
":=",
"Global",
".",
"Get",
"(",
"\"Object\"",
")",
".",
"New",
"(",
")",
"\n",
"o",
".",
"Set",
"(",
"\"__internal_object__\"",
",",
"v",
")",
"\n",
"methods",
":=",
"v",
".",
"Get",
"(",
"\"constructor\"",
")",
".",
"Get",
"(",
"\"methods\"",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"methods",
".",
"Length",
"(",
")",
";",
"i",
"++",
"{",
"m",
":=",
"methods",
".",
"Index",
"(",
"i",
")",
"\n",
"if",
"m",
".",
"Get",
"(",
"\"pkg\"",
")",
".",
"String",
"(",
")",
"!=",
"\"\"",
"{",
"continue",
"\n",
"}",
"\n",
"o",
".",
"Set",
"(",
"m",
".",
"Get",
"(",
"\"name\"",
")",
".",
"String",
"(",
")",
",",
"func",
"(",
"args",
"...",
"*",
"Object",
")",
"*",
"Object",
"{",
"return",
"Global",
".",
"Call",
"(",
"\"$externalizeFunction\"",
",",
"v",
".",
"Get",
"(",
"m",
".",
"Get",
"(",
"\"prop\"",
")",
".",
"String",
"(",
")",
")",
",",
"m",
".",
"Get",
"(",
"\"typ\"",
")",
",",
"true",
")",
".",
"Call",
"(",
"\"apply\"",
",",
"v",
",",
"args",
")",
"\n",
"}",
")",
"\n",
"}",
"\n",
"return",
"o",
"\n",
"}"
] | // MakeWrapper creates a JavaScript object which has wrappers for the exported methods of i. Use explicit getter and setter methods to expose struct fields to JavaScript. | [
"MakeWrapper",
"creates",
"a",
"JavaScript",
"object",
"which",
"has",
"wrappers",
"for",
"the",
"exported",
"methods",
"of",
"i",
".",
"Use",
"explicit",
"getter",
"and",
"setter",
"methods",
"to",
"expose",
"struct",
"fields",
"to",
"JavaScript",
"."
] | 3e4dfb77656c424b6d1196a4d5fed0fcf63677cc | https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/js/js.go#L133-L148 | train |
gopherjs/gopherjs | js/js.go | NewArrayBuffer | func NewArrayBuffer(b []byte) *Object {
slice := InternalObject(b)
offset := slice.Get("$offset").Int()
length := slice.Get("$length").Int()
return slice.Get("$array").Get("buffer").Call("slice", offset, offset+length)
} | go | func NewArrayBuffer(b []byte) *Object {
slice := InternalObject(b)
offset := slice.Get("$offset").Int()
length := slice.Get("$length").Int()
return slice.Get("$array").Get("buffer").Call("slice", offset, offset+length)
} | [
"func",
"NewArrayBuffer",
"(",
"b",
"[",
"]",
"byte",
")",
"*",
"Object",
"{",
"slice",
":=",
"InternalObject",
"(",
"b",
")",
"\n",
"offset",
":=",
"slice",
".",
"Get",
"(",
"\"$offset\"",
")",
".",
"Int",
"(",
")",
"\n",
"length",
":=",
"slice",
".",
"Get",
"(",
"\"$length\"",
")",
".",
"Int",
"(",
")",
"\n",
"return",
"slice",
".",
"Get",
"(",
"\"$array\"",
")",
".",
"Get",
"(",
"\"buffer\"",
")",
".",
"Call",
"(",
"\"slice\"",
",",
"offset",
",",
"offset",
"+",
"length",
")",
"\n",
"}"
] | // NewArrayBuffer creates a JavaScript ArrayBuffer from a byte slice. | [
"NewArrayBuffer",
"creates",
"a",
"JavaScript",
"ArrayBuffer",
"from",
"a",
"byte",
"slice",
"."
] | 3e4dfb77656c424b6d1196a4d5fed0fcf63677cc | https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/js/js.go#L151-L156 | train |
gopherjs/gopherjs | compiler/natives/src/internal/poll/fd_poll.go | runtime_Semacquire | func runtime_Semacquire(s *uint32) {
if *s == 0 {
ch := make(chan bool)
semWaiters[s] = append(semWaiters[s], ch)
<-ch
}
*s--
} | go | func runtime_Semacquire(s *uint32) {
if *s == 0 {
ch := make(chan bool)
semWaiters[s] = append(semWaiters[s], ch)
<-ch
}
*s--
} | [
"func",
"runtime_Semacquire",
"(",
"s",
"*",
"uint32",
")",
"{",
"if",
"*",
"s",
"==",
"0",
"{",
"ch",
":=",
"make",
"(",
"chan",
"bool",
")",
"\n",
"semWaiters",
"[",
"s",
"]",
"=",
"append",
"(",
"semWaiters",
"[",
"s",
"]",
",",
"ch",
")",
"\n",
"<-",
"ch",
"\n",
"}",
"\n",
"*",
"s",
"--",
"\n",
"}"
] | // Copy of sync.runtime_Semacquire. | [
"Copy",
"of",
"sync",
".",
"runtime_Semacquire",
"."
] | 3e4dfb77656c424b6d1196a4d5fed0fcf63677cc | https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/compiler/natives/src/internal/poll/fd_poll.go#L60-L67 | train |
gopherjs/gopherjs | compiler/natives/src/internal/poll/fd_poll.go | runtime_Semrelease | func runtime_Semrelease(s *uint32) {
*s++
w := semWaiters[s]
if len(w) == 0 {
return
}
ch := w[0]
w = w[1:]
semWaiters[s] = w
if len(w) == 0 {
delete(semWaiters, s)
}
ch <- true
} | go | func runtime_Semrelease(s *uint32) {
*s++
w := semWaiters[s]
if len(w) == 0 {
return
}
ch := w[0]
w = w[1:]
semWaiters[s] = w
if len(w) == 0 {
delete(semWaiters, s)
}
ch <- true
} | [
"func",
"runtime_Semrelease",
"(",
"s",
"*",
"uint32",
")",
"{",
"*",
"s",
"++",
"\n",
"w",
":=",
"semWaiters",
"[",
"s",
"]",
"\n",
"if",
"len",
"(",
"w",
")",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n",
"ch",
":=",
"w",
"[",
"0",
"]",
"\n",
"w",
"=",
"w",
"[",
"1",
":",
"]",
"\n",
"semWaiters",
"[",
"s",
"]",
"=",
"w",
"\n",
"if",
"len",
"(",
"w",
")",
"==",
"0",
"{",
"delete",
"(",
"semWaiters",
",",
"s",
")",
"\n",
"}",
"\n",
"ch",
"<-",
"true",
"\n",
"}"
] | // Copy of sync.runtime_Semrelease. | [
"Copy",
"of",
"sync",
".",
"runtime_Semrelease",
"."
] | 3e4dfb77656c424b6d1196a4d5fed0fcf63677cc | https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/compiler/natives/src/internal/poll/fd_poll.go#L70-L86 | train |
gopherjs/gopherjs | build/build.go | excludeExecutable | func excludeExecutable(goFiles []string) []string {
var s []string
for _, f := range goFiles {
if strings.HasPrefix(f, "executable_") {
continue
}
s = append(s, f)
}
return s
} | go | func excludeExecutable(goFiles []string) []string {
var s []string
for _, f := range goFiles {
if strings.HasPrefix(f, "executable_") {
continue
}
s = append(s, f)
}
return s
} | [
"func",
"excludeExecutable",
"(",
"goFiles",
"[",
"]",
"string",
")",
"[",
"]",
"string",
"{",
"var",
"s",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"goFiles",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"f",
",",
"\"executable_\"",
")",
"{",
"continue",
"\n",
"}",
"\n",
"s",
"=",
"append",
"(",
"s",
",",
"f",
")",
"\n",
"}",
"\n",
"return",
"s",
"\n",
"}"
] | // excludeExecutable excludes all executable implementation .go files.
// They have "executable_" prefix. | [
"excludeExecutable",
"excludes",
"all",
"executable",
"implementation",
".",
"go",
"files",
".",
"They",
"have",
"executable_",
"prefix",
"."
] | 3e4dfb77656c424b6d1196a4d5fed0fcf63677cc | https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/build/build.go#L205-L214 | train |
gopherjs/gopherjs | build/build.go | exclude | func exclude(files []string, exclude ...string) []string {
var s []string
Outer:
for _, f := range files {
for _, e := range exclude {
if f == e {
continue Outer
}
}
s = append(s, f)
}
return s
} | go | func exclude(files []string, exclude ...string) []string {
var s []string
Outer:
for _, f := range files {
for _, e := range exclude {
if f == e {
continue Outer
}
}
s = append(s, f)
}
return s
} | [
"func",
"exclude",
"(",
"files",
"[",
"]",
"string",
",",
"exclude",
"...",
"string",
")",
"[",
"]",
"string",
"{",
"var",
"s",
"[",
"]",
"string",
"\n",
"Outer",
":",
"for",
"_",
",",
"f",
":=",
"range",
"files",
"{",
"for",
"_",
",",
"e",
":=",
"range",
"exclude",
"{",
"if",
"f",
"==",
"e",
"{",
"continue",
"Outer",
"\n",
"}",
"\n",
"}",
"\n",
"s",
"=",
"append",
"(",
"s",
",",
"f",
")",
"\n",
"}",
"\n",
"return",
"s",
"\n",
"}"
] | // exclude returns files, excluding specified files. | [
"exclude",
"returns",
"files",
"excluding",
"specified",
"files",
"."
] | 3e4dfb77656c424b6d1196a4d5fed0fcf63677cc | https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/build/build.go#L217-L229 | train |
gopherjs/gopherjs | build/build.go | ImportDir | func ImportDir(dir string, mode build.ImportMode, installSuffix string, buildTags []string) (*PackageData, error) {
bctx := NewBuildContext(installSuffix, buildTags)
pkg, err := bctx.ImportDir(dir, mode)
if err != nil {
return nil, err
}
jsFiles, err := jsFilesFromDir(bctx, pkg.Dir)
if err != nil {
return nil, err
}
return &PackageData{Package: pkg, JSFiles: jsFiles}, nil
} | go | func ImportDir(dir string, mode build.ImportMode, installSuffix string, buildTags []string) (*PackageData, error) {
bctx := NewBuildContext(installSuffix, buildTags)
pkg, err := bctx.ImportDir(dir, mode)
if err != nil {
return nil, err
}
jsFiles, err := jsFilesFromDir(bctx, pkg.Dir)
if err != nil {
return nil, err
}
return &PackageData{Package: pkg, JSFiles: jsFiles}, nil
} | [
"func",
"ImportDir",
"(",
"dir",
"string",
",",
"mode",
"build",
".",
"ImportMode",
",",
"installSuffix",
"string",
",",
"buildTags",
"[",
"]",
"string",
")",
"(",
"*",
"PackageData",
",",
"error",
")",
"{",
"bctx",
":=",
"NewBuildContext",
"(",
"installSuffix",
",",
"buildTags",
")",
"\n",
"pkg",
",",
"err",
":=",
"bctx",
".",
"ImportDir",
"(",
"dir",
",",
"mode",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"jsFiles",
",",
"err",
":=",
"jsFilesFromDir",
"(",
"bctx",
",",
"pkg",
".",
"Dir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"PackageData",
"{",
"Package",
":",
"pkg",
",",
"JSFiles",
":",
"jsFiles",
"}",
",",
"nil",
"\n",
"}"
] | // ImportDir is like Import but processes the Go package found in the named
// directory. | [
"ImportDir",
"is",
"like",
"Import",
"but",
"processes",
"the",
"Go",
"package",
"found",
"in",
"the",
"named",
"directory",
"."
] | 3e4dfb77656c424b6d1196a4d5fed0fcf63677cc | https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/build/build.go#L233-L246 | train |
gopherjs/gopherjs | build/build.go | hasGopathPrefix | func hasGopathPrefix(file, gopath string) (hasGopathPrefix bool, prefixLen int) {
gopathWorkspaces := filepath.SplitList(gopath)
for _, gopathWorkspace := range gopathWorkspaces {
gopathWorkspace = filepath.Clean(gopathWorkspace)
if strings.HasPrefix(file, gopathWorkspace) {
return true, len(gopathWorkspace)
}
}
return false, 0
} | go | func hasGopathPrefix(file, gopath string) (hasGopathPrefix bool, prefixLen int) {
gopathWorkspaces := filepath.SplitList(gopath)
for _, gopathWorkspace := range gopathWorkspaces {
gopathWorkspace = filepath.Clean(gopathWorkspace)
if strings.HasPrefix(file, gopathWorkspace) {
return true, len(gopathWorkspace)
}
}
return false, 0
} | [
"func",
"hasGopathPrefix",
"(",
"file",
",",
"gopath",
"string",
")",
"(",
"hasGopathPrefix",
"bool",
",",
"prefixLen",
"int",
")",
"{",
"gopathWorkspaces",
":=",
"filepath",
".",
"SplitList",
"(",
"gopath",
")",
"\n",
"for",
"_",
",",
"gopathWorkspace",
":=",
"range",
"gopathWorkspaces",
"{",
"gopathWorkspace",
"=",
"filepath",
".",
"Clean",
"(",
"gopathWorkspace",
")",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"file",
",",
"gopathWorkspace",
")",
"{",
"return",
"true",
",",
"len",
"(",
"gopathWorkspace",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
",",
"0",
"\n",
"}"
] | // hasGopathPrefix returns true and the length of the matched GOPATH workspace,
// iff file has a prefix that matches one of the GOPATH workspaces. | [
"hasGopathPrefix",
"returns",
"true",
"and",
"the",
"length",
"of",
"the",
"matched",
"GOPATH",
"workspace",
"iff",
"file",
"has",
"a",
"prefix",
"that",
"matches",
"one",
"of",
"the",
"GOPATH",
"workspaces",
"."
] | 3e4dfb77656c424b6d1196a4d5fed0fcf63677cc | https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/build/build.go#L843-L852 | train |
gopherjs/gopherjs | internal/sysutil/sysutil.go | RlimitStack | func RlimitStack() (cur uint64, err error) {
var r unix.Rlimit
err = unix.Getrlimit(unix.RLIMIT_STACK, &r)
return uint64(r.Cur), err // Type conversion because Cur is one of uint64, int64 depending on unix flavor.
} | go | func RlimitStack() (cur uint64, err error) {
var r unix.Rlimit
err = unix.Getrlimit(unix.RLIMIT_STACK, &r)
return uint64(r.Cur), err // Type conversion because Cur is one of uint64, int64 depending on unix flavor.
} | [
"func",
"RlimitStack",
"(",
")",
"(",
"cur",
"uint64",
",",
"err",
"error",
")",
"{",
"var",
"r",
"unix",
".",
"Rlimit",
"\n",
"err",
"=",
"unix",
".",
"Getrlimit",
"(",
"unix",
".",
"RLIMIT_STACK",
",",
"&",
"r",
")",
"\n",
"return",
"uint64",
"(",
"r",
".",
"Cur",
")",
",",
"err",
"\n",
"}"
] | // RlimitStack reports the current stack size limit in bytes. | [
"RlimitStack",
"reports",
"the",
"current",
"stack",
"size",
"limit",
"in",
"bytes",
"."
] | 3e4dfb77656c424b6d1196a4d5fed0fcf63677cc | https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/internal/sysutil/sysutil.go#L9-L13 | train |
gopherjs/gopherjs | compiler/natives/src/syscall/js/js.go | convertArgs | func convertArgs(args ...interface{}) []interface{} {
newArgs := []interface{}{}
for _, arg := range args {
v := ValueOf(arg)
newArgs = append(newArgs, v.internal())
}
return newArgs
} | go | func convertArgs(args ...interface{}) []interface{} {
newArgs := []interface{}{}
for _, arg := range args {
v := ValueOf(arg)
newArgs = append(newArgs, v.internal())
}
return newArgs
} | [
"func",
"convertArgs",
"(",
"args",
"...",
"interface",
"{",
"}",
")",
"[",
"]",
"interface",
"{",
"}",
"{",
"newArgs",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"}",
"\n",
"for",
"_",
",",
"arg",
":=",
"range",
"args",
"{",
"v",
":=",
"ValueOf",
"(",
"arg",
")",
"\n",
"newArgs",
"=",
"append",
"(",
"newArgs",
",",
"v",
".",
"internal",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"newArgs",
"\n",
"}"
] | // convertArgs converts arguments into values for GopherJS arguments. | [
"convertArgs",
"converts",
"arguments",
"into",
"values",
"for",
"GopherJS",
"arguments",
"."
] | 3e4dfb77656c424b6d1196a4d5fed0fcf63677cc | https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/compiler/natives/src/syscall/js/js.go#L171-L178 | train |
gopherjs/gopherjs | compiler/natives/src/net/net.go | bytesEqual | func bytesEqual(x, y []byte) bool {
if len(x) != len(y) {
return false
}
for i, b := range x {
if b != y[i] {
return false
}
}
return true
} | go | func bytesEqual(x, y []byte) bool {
if len(x) != len(y) {
return false
}
for i, b := range x {
if b != y[i] {
return false
}
}
return true
} | [
"func",
"bytesEqual",
"(",
"x",
",",
"y",
"[",
"]",
"byte",
")",
"bool",
"{",
"if",
"len",
"(",
"x",
")",
"!=",
"len",
"(",
"y",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"for",
"i",
",",
"b",
":=",
"range",
"x",
"{",
"if",
"b",
"!=",
"y",
"[",
"i",
"]",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // Copy of bytes.Equal. | [
"Copy",
"of",
"bytes",
".",
"Equal",
"."
] | 3e4dfb77656c424b6d1196a4d5fed0fcf63677cc | https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/compiler/natives/src/net/net.go#L45-L55 | train |
gopherjs/gopherjs | compiler/natives/src/net/net.go | bytesIndexByte | func bytesIndexByte(s []byte, c byte) int {
for i, b := range s {
if b == c {
return i
}
}
return -1
} | go | func bytesIndexByte(s []byte, c byte) int {
for i, b := range s {
if b == c {
return i
}
}
return -1
} | [
"func",
"bytesIndexByte",
"(",
"s",
"[",
"]",
"byte",
",",
"c",
"byte",
")",
"int",
"{",
"for",
"i",
",",
"b",
":=",
"range",
"s",
"{",
"if",
"b",
"==",
"c",
"{",
"return",
"i",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"-",
"1",
"\n",
"}"
] | // Copy of bytes.IndexByte. | [
"Copy",
"of",
"bytes",
".",
"IndexByte",
"."
] | 3e4dfb77656c424b6d1196a4d5fed0fcf63677cc | https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/compiler/natives/src/net/net.go#L58-L65 | train |
gopherjs/gopherjs | tool.go | handleError | func handleError(err error, options *gbuild.Options, browserErrors *bytes.Buffer) int {
switch err := err.(type) {
case nil:
return 0
case compiler.ErrorList:
for _, entry := range err {
printError(entry, options, browserErrors)
}
return 1
case *exec.ExitError:
return err.Sys().(syscall.WaitStatus).ExitStatus()
default:
printError(err, options, browserErrors)
return 1
}
} | go | func handleError(err error, options *gbuild.Options, browserErrors *bytes.Buffer) int {
switch err := err.(type) {
case nil:
return 0
case compiler.ErrorList:
for _, entry := range err {
printError(entry, options, browserErrors)
}
return 1
case *exec.ExitError:
return err.Sys().(syscall.WaitStatus).ExitStatus()
default:
printError(err, options, browserErrors)
return 1
}
} | [
"func",
"handleError",
"(",
"err",
"error",
",",
"options",
"*",
"gbuild",
".",
"Options",
",",
"browserErrors",
"*",
"bytes",
".",
"Buffer",
")",
"int",
"{",
"switch",
"err",
":=",
"err",
".",
"(",
"type",
")",
"{",
"case",
"nil",
":",
"return",
"0",
"\n",
"case",
"compiler",
".",
"ErrorList",
":",
"for",
"_",
",",
"entry",
":=",
"range",
"err",
"{",
"printError",
"(",
"entry",
",",
"options",
",",
"browserErrors",
")",
"\n",
"}",
"\n",
"return",
"1",
"\n",
"case",
"*",
"exec",
".",
"ExitError",
":",
"return",
"err",
".",
"Sys",
"(",
")",
".",
"(",
"syscall",
".",
"WaitStatus",
")",
".",
"ExitStatus",
"(",
")",
"\n",
"default",
":",
"printError",
"(",
"err",
",",
"options",
",",
"browserErrors",
")",
"\n",
"return",
"1",
"\n",
"}",
"\n",
"}"
] | // handleError handles err and returns an appropriate exit code.
// If browserErrors is non-nil, errors are written for presentation in browser. | [
"handleError",
"handles",
"err",
"and",
"returns",
"an",
"appropriate",
"exit",
"code",
".",
"If",
"browserErrors",
"is",
"non",
"-",
"nil",
"errors",
"are",
"written",
"for",
"presentation",
"in",
"browser",
"."
] | 3e4dfb77656c424b6d1196a4d5fed0fcf63677cc | https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/tool.go#L698-L713 | train |
gopherjs/gopherjs | tool.go | printError | func printError(err error, options *gbuild.Options, browserErrors *bytes.Buffer) {
e := sprintError(err)
options.PrintError("%s\n", e)
if browserErrors != nil {
fmt.Fprintln(browserErrors, `console.error("`+template.JSEscapeString(e)+`");`)
}
} | go | func printError(err error, options *gbuild.Options, browserErrors *bytes.Buffer) {
e := sprintError(err)
options.PrintError("%s\n", e)
if browserErrors != nil {
fmt.Fprintln(browserErrors, `console.error("`+template.JSEscapeString(e)+`");`)
}
} | [
"func",
"printError",
"(",
"err",
"error",
",",
"options",
"*",
"gbuild",
".",
"Options",
",",
"browserErrors",
"*",
"bytes",
".",
"Buffer",
")",
"{",
"e",
":=",
"sprintError",
"(",
"err",
")",
"\n",
"options",
".",
"PrintError",
"(",
"\"%s\\n\"",
",",
"\\n",
")",
"\n",
"e",
"\n",
"}"
] | // printError prints err to Stderr with options. If browserErrors is non-nil, errors are also written for presentation in browser. | [
"printError",
"prints",
"err",
"to",
"Stderr",
"with",
"options",
".",
"If",
"browserErrors",
"is",
"non",
"-",
"nil",
"errors",
"are",
"also",
"written",
"for",
"presentation",
"in",
"browser",
"."
] | 3e4dfb77656c424b6d1196a4d5fed0fcf63677cc | https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/tool.go#L716-L722 | train |
gopherjs/gopherjs | tool.go | sprintError | func sprintError(err error) string {
makeRel := func(name string) string {
if relname, err := filepath.Rel(currentDirectory, name); err == nil {
return relname
}
return name
}
switch e := err.(type) {
case *scanner.Error:
return fmt.Sprintf("%s:%d:%d: %s", makeRel(e.Pos.Filename), e.Pos.Line, e.Pos.Column, e.Msg)
case types.Error:
pos := e.Fset.Position(e.Pos)
return fmt.Sprintf("%s:%d:%d: %s", makeRel(pos.Filename), pos.Line, pos.Column, e.Msg)
default:
return fmt.Sprintf("%s", e)
}
} | go | func sprintError(err error) string {
makeRel := func(name string) string {
if relname, err := filepath.Rel(currentDirectory, name); err == nil {
return relname
}
return name
}
switch e := err.(type) {
case *scanner.Error:
return fmt.Sprintf("%s:%d:%d: %s", makeRel(e.Pos.Filename), e.Pos.Line, e.Pos.Column, e.Msg)
case types.Error:
pos := e.Fset.Position(e.Pos)
return fmt.Sprintf("%s:%d:%d: %s", makeRel(pos.Filename), pos.Line, pos.Column, e.Msg)
default:
return fmt.Sprintf("%s", e)
}
} | [
"func",
"sprintError",
"(",
"err",
"error",
")",
"string",
"{",
"makeRel",
":=",
"func",
"(",
"name",
"string",
")",
"string",
"{",
"if",
"relname",
",",
"err",
":=",
"filepath",
".",
"Rel",
"(",
"currentDirectory",
",",
"name",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"relname",
"\n",
"}",
"\n",
"return",
"name",
"\n",
"}",
"\n",
"switch",
"e",
":=",
"err",
".",
"(",
"type",
")",
"{",
"case",
"*",
"scanner",
".",
"Error",
":",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"%s:%d:%d: %s\"",
",",
"makeRel",
"(",
"e",
".",
"Pos",
".",
"Filename",
")",
",",
"e",
".",
"Pos",
".",
"Line",
",",
"e",
".",
"Pos",
".",
"Column",
",",
"e",
".",
"Msg",
")",
"\n",
"case",
"types",
".",
"Error",
":",
"pos",
":=",
"e",
".",
"Fset",
".",
"Position",
"(",
"e",
".",
"Pos",
")",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"%s:%d:%d: %s\"",
",",
"makeRel",
"(",
"pos",
".",
"Filename",
")",
",",
"pos",
".",
"Line",
",",
"pos",
".",
"Column",
",",
"e",
".",
"Msg",
")",
"\n",
"default",
":",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"%s\"",
",",
"e",
")",
"\n",
"}",
"\n",
"}"
] | // sprintError returns an annotated error string without trailing newline. | [
"sprintError",
"returns",
"an",
"annotated",
"error",
"string",
"without",
"trailing",
"newline",
"."
] | 3e4dfb77656c424b6d1196a4d5fed0fcf63677cc | https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/tool.go#L725-L742 | train |
gopherjs/gopherjs | tool.go | runNode | func runNode(script string, args []string, dir string, quiet bool) error {
var allArgs []string
if b, _ := strconv.ParseBool(os.Getenv("SOURCE_MAP_SUPPORT")); os.Getenv("SOURCE_MAP_SUPPORT") == "" || b {
allArgs = []string{"--require", "source-map-support/register"}
if err := exec.Command("node", "--require", "source-map-support/register", "--eval", "").Run(); err != nil {
if !quiet {
fmt.Fprintln(os.Stderr, "gopherjs: Source maps disabled. Install source-map-support module for nice stack traces. See https://github.com/gopherjs/gopherjs#gopherjs-run-gopherjs-test.")
}
allArgs = []string{}
}
}
if runtime.GOOS != "windows" {
// We've seen issues with stack space limits causing
// recursion-heavy standard library tests to fail (e.g., see
// https://github.com/gopherjs/gopherjs/pull/669#issuecomment-319319483).
//
// There are two separate limits in non-Windows environments:
//
// - OS process limit
// - Node.js (V8) limit
//
// GopherJS fetches the current OS process limit, and sets the
// Node.js limit to the same value. So both limits are kept in sync
// and can be controlled by setting OS process limit. E.g.:
//
// ulimit -s 10000 && gopherjs test
//
cur, err := sysutil.RlimitStack()
if err != nil {
return fmt.Errorf("failed to get stack size limit: %v", err)
}
allArgs = append(allArgs, fmt.Sprintf("--stack_size=%v", cur/1000)) // Convert from bytes to KB.
}
allArgs = append(allArgs, script)
allArgs = append(allArgs, args...)
node := exec.Command("node", allArgs...)
node.Dir = dir
node.Stdin = os.Stdin
node.Stdout = os.Stdout
node.Stderr = os.Stderr
err := node.Run()
if _, ok := err.(*exec.ExitError); err != nil && !ok {
err = fmt.Errorf("could not run Node.js: %s", err.Error())
}
return err
} | go | func runNode(script string, args []string, dir string, quiet bool) error {
var allArgs []string
if b, _ := strconv.ParseBool(os.Getenv("SOURCE_MAP_SUPPORT")); os.Getenv("SOURCE_MAP_SUPPORT") == "" || b {
allArgs = []string{"--require", "source-map-support/register"}
if err := exec.Command("node", "--require", "source-map-support/register", "--eval", "").Run(); err != nil {
if !quiet {
fmt.Fprintln(os.Stderr, "gopherjs: Source maps disabled. Install source-map-support module for nice stack traces. See https://github.com/gopherjs/gopherjs#gopherjs-run-gopherjs-test.")
}
allArgs = []string{}
}
}
if runtime.GOOS != "windows" {
// We've seen issues with stack space limits causing
// recursion-heavy standard library tests to fail (e.g., see
// https://github.com/gopherjs/gopherjs/pull/669#issuecomment-319319483).
//
// There are two separate limits in non-Windows environments:
//
// - OS process limit
// - Node.js (V8) limit
//
// GopherJS fetches the current OS process limit, and sets the
// Node.js limit to the same value. So both limits are kept in sync
// and can be controlled by setting OS process limit. E.g.:
//
// ulimit -s 10000 && gopherjs test
//
cur, err := sysutil.RlimitStack()
if err != nil {
return fmt.Errorf("failed to get stack size limit: %v", err)
}
allArgs = append(allArgs, fmt.Sprintf("--stack_size=%v", cur/1000)) // Convert from bytes to KB.
}
allArgs = append(allArgs, script)
allArgs = append(allArgs, args...)
node := exec.Command("node", allArgs...)
node.Dir = dir
node.Stdin = os.Stdin
node.Stdout = os.Stdout
node.Stderr = os.Stderr
err := node.Run()
if _, ok := err.(*exec.ExitError); err != nil && !ok {
err = fmt.Errorf("could not run Node.js: %s", err.Error())
}
return err
} | [
"func",
"runNode",
"(",
"script",
"string",
",",
"args",
"[",
"]",
"string",
",",
"dir",
"string",
",",
"quiet",
"bool",
")",
"error",
"{",
"var",
"allArgs",
"[",
"]",
"string",
"\n",
"if",
"b",
",",
"_",
":=",
"strconv",
".",
"ParseBool",
"(",
"os",
".",
"Getenv",
"(",
"\"SOURCE_MAP_SUPPORT\"",
")",
")",
";",
"os",
".",
"Getenv",
"(",
"\"SOURCE_MAP_SUPPORT\"",
")",
"==",
"\"\"",
"||",
"b",
"{",
"allArgs",
"=",
"[",
"]",
"string",
"{",
"\"--require\"",
",",
"\"source-map-support/register\"",
"}",
"\n",
"if",
"err",
":=",
"exec",
".",
"Command",
"(",
"\"node\"",
",",
"\"--require\"",
",",
"\"source-map-support/register\"",
",",
"\"--eval\"",
",",
"\"\"",
")",
".",
"Run",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"!",
"quiet",
"{",
"fmt",
".",
"Fprintln",
"(",
"os",
".",
"Stderr",
",",
"\"gopherjs: Source maps disabled. Install source-map-support module for nice stack traces. See https://github.com/gopherjs/gopherjs#gopherjs-run-gopherjs-test.\"",
")",
"\n",
"}",
"\n",
"allArgs",
"=",
"[",
"]",
"string",
"{",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"runtime",
".",
"GOOS",
"!=",
"\"windows\"",
"{",
"cur",
",",
"err",
":=",
"sysutil",
".",
"RlimitStack",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"failed to get stack size limit: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"allArgs",
"=",
"append",
"(",
"allArgs",
",",
"fmt",
".",
"Sprintf",
"(",
"\"--stack_size=%v\"",
",",
"cur",
"/",
"1000",
")",
")",
"\n",
"}",
"\n",
"allArgs",
"=",
"append",
"(",
"allArgs",
",",
"script",
")",
"\n",
"allArgs",
"=",
"append",
"(",
"allArgs",
",",
"args",
"...",
")",
"\n",
"node",
":=",
"exec",
".",
"Command",
"(",
"\"node\"",
",",
"allArgs",
"...",
")",
"\n",
"node",
".",
"Dir",
"=",
"dir",
"\n",
"node",
".",
"Stdin",
"=",
"os",
".",
"Stdin",
"\n",
"node",
".",
"Stdout",
"=",
"os",
".",
"Stdout",
"\n",
"node",
".",
"Stderr",
"=",
"os",
".",
"Stderr",
"\n",
"err",
":=",
"node",
".",
"Run",
"(",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"exec",
".",
"ExitError",
")",
";",
"err",
"!=",
"nil",
"&&",
"!",
"ok",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"could not run Node.js: %s\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // runNode runs script with args using Node.js in directory dir.
// If dir is empty string, current directory is used. | [
"runNode",
"runs",
"script",
"with",
"args",
"using",
"Node",
".",
"js",
"in",
"directory",
"dir",
".",
"If",
"dir",
"is",
"empty",
"string",
"current",
"directory",
"is",
"used",
"."
] | 3e4dfb77656c424b6d1196a4d5fed0fcf63677cc | https://github.com/gopherjs/gopherjs/blob/3e4dfb77656c424b6d1196a4d5fed0fcf63677cc/tool.go#L746-L794 | train |
disintegration/imaging | tools.go | New | func New(width, height int, fillColor color.Color) *image.NRGBA {
if width <= 0 || height <= 0 {
return &image.NRGBA{}
}
c := color.NRGBAModel.Convert(fillColor).(color.NRGBA)
if (c == color.NRGBA{0, 0, 0, 0}) {
return image.NewNRGBA(image.Rect(0, 0, width, height))
}
return &image.NRGBA{
Pix: bytes.Repeat([]byte{c.R, c.G, c.B, c.A}, width*height),
Stride: 4 * width,
Rect: image.Rect(0, 0, width, height),
}
} | go | func New(width, height int, fillColor color.Color) *image.NRGBA {
if width <= 0 || height <= 0 {
return &image.NRGBA{}
}
c := color.NRGBAModel.Convert(fillColor).(color.NRGBA)
if (c == color.NRGBA{0, 0, 0, 0}) {
return image.NewNRGBA(image.Rect(0, 0, width, height))
}
return &image.NRGBA{
Pix: bytes.Repeat([]byte{c.R, c.G, c.B, c.A}, width*height),
Stride: 4 * width,
Rect: image.Rect(0, 0, width, height),
}
} | [
"func",
"New",
"(",
"width",
",",
"height",
"int",
",",
"fillColor",
"color",
".",
"Color",
")",
"*",
"image",
".",
"NRGBA",
"{",
"if",
"width",
"<=",
"0",
"||",
"height",
"<=",
"0",
"{",
"return",
"&",
"image",
".",
"NRGBA",
"{",
"}",
"\n",
"}",
"\n",
"c",
":=",
"color",
".",
"NRGBAModel",
".",
"Convert",
"(",
"fillColor",
")",
".",
"(",
"color",
".",
"NRGBA",
")",
"\n",
"if",
"(",
"c",
"==",
"color",
".",
"NRGBA",
"{",
"0",
",",
"0",
",",
"0",
",",
"0",
"}",
")",
"{",
"return",
"image",
".",
"NewNRGBA",
"(",
"image",
".",
"Rect",
"(",
"0",
",",
"0",
",",
"width",
",",
"height",
")",
")",
"\n",
"}",
"\n",
"return",
"&",
"image",
".",
"NRGBA",
"{",
"Pix",
":",
"bytes",
".",
"Repeat",
"(",
"[",
"]",
"byte",
"{",
"c",
".",
"R",
",",
"c",
".",
"G",
",",
"c",
".",
"B",
",",
"c",
".",
"A",
"}",
",",
"width",
"*",
"height",
")",
",",
"Stride",
":",
"4",
"*",
"width",
",",
"Rect",
":",
"image",
".",
"Rect",
"(",
"0",
",",
"0",
",",
"width",
",",
"height",
")",
",",
"}",
"\n",
"}"
] | // New creates a new image with the specified width and height, and fills it with the specified color. | [
"New",
"creates",
"a",
"new",
"image",
"with",
"the",
"specified",
"width",
"and",
"height",
"and",
"fills",
"it",
"with",
"the",
"specified",
"color",
"."
] | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/tools.go#L11-L26 | train |
disintegration/imaging | tools.go | Clone | func Clone(img image.Image) *image.NRGBA {
src := newScanner(img)
dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
size := src.w * 4
parallel(0, src.h, func(ys <-chan int) {
for y := range ys {
i := y * dst.Stride
src.scan(0, y, src.w, y+1, dst.Pix[i:i+size])
}
})
return dst
} | go | func Clone(img image.Image) *image.NRGBA {
src := newScanner(img)
dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
size := src.w * 4
parallel(0, src.h, func(ys <-chan int) {
for y := range ys {
i := y * dst.Stride
src.scan(0, y, src.w, y+1, dst.Pix[i:i+size])
}
})
return dst
} | [
"func",
"Clone",
"(",
"img",
"image",
".",
"Image",
")",
"*",
"image",
".",
"NRGBA",
"{",
"src",
":=",
"newScanner",
"(",
"img",
")",
"\n",
"dst",
":=",
"image",
".",
"NewNRGBA",
"(",
"image",
".",
"Rect",
"(",
"0",
",",
"0",
",",
"src",
".",
"w",
",",
"src",
".",
"h",
")",
")",
"\n",
"size",
":=",
"src",
".",
"w",
"*",
"4",
"\n",
"parallel",
"(",
"0",
",",
"src",
".",
"h",
",",
"func",
"(",
"ys",
"<-",
"chan",
"int",
")",
"{",
"for",
"y",
":=",
"range",
"ys",
"{",
"i",
":=",
"y",
"*",
"dst",
".",
"Stride",
"\n",
"src",
".",
"scan",
"(",
"0",
",",
"y",
",",
"src",
".",
"w",
",",
"y",
"+",
"1",
",",
"dst",
".",
"Pix",
"[",
"i",
":",
"i",
"+",
"size",
"]",
")",
"\n",
"}",
"\n",
"}",
")",
"\n",
"return",
"dst",
"\n",
"}"
] | // Clone returns a copy of the given image. | [
"Clone",
"returns",
"a",
"copy",
"of",
"the",
"given",
"image",
"."
] | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/tools.go#L29-L40 | train |
disintegration/imaging | tools.go | Crop | func Crop(img image.Image, rect image.Rectangle) *image.NRGBA {
r := rect.Intersect(img.Bounds()).Sub(img.Bounds().Min)
if r.Empty() {
return &image.NRGBA{}
}
src := newScanner(img)
dst := image.NewNRGBA(image.Rect(0, 0, r.Dx(), r.Dy()))
rowSize := r.Dx() * 4
parallel(r.Min.Y, r.Max.Y, func(ys <-chan int) {
for y := range ys {
i := (y - r.Min.Y) * dst.Stride
src.scan(r.Min.X, y, r.Max.X, y+1, dst.Pix[i:i+rowSize])
}
})
return dst
} | go | func Crop(img image.Image, rect image.Rectangle) *image.NRGBA {
r := rect.Intersect(img.Bounds()).Sub(img.Bounds().Min)
if r.Empty() {
return &image.NRGBA{}
}
src := newScanner(img)
dst := image.NewNRGBA(image.Rect(0, 0, r.Dx(), r.Dy()))
rowSize := r.Dx() * 4
parallel(r.Min.Y, r.Max.Y, func(ys <-chan int) {
for y := range ys {
i := (y - r.Min.Y) * dst.Stride
src.scan(r.Min.X, y, r.Max.X, y+1, dst.Pix[i:i+rowSize])
}
})
return dst
} | [
"func",
"Crop",
"(",
"img",
"image",
".",
"Image",
",",
"rect",
"image",
".",
"Rectangle",
")",
"*",
"image",
".",
"NRGBA",
"{",
"r",
":=",
"rect",
".",
"Intersect",
"(",
"img",
".",
"Bounds",
"(",
")",
")",
".",
"Sub",
"(",
"img",
".",
"Bounds",
"(",
")",
".",
"Min",
")",
"\n",
"if",
"r",
".",
"Empty",
"(",
")",
"{",
"return",
"&",
"image",
".",
"NRGBA",
"{",
"}",
"\n",
"}",
"\n",
"src",
":=",
"newScanner",
"(",
"img",
")",
"\n",
"dst",
":=",
"image",
".",
"NewNRGBA",
"(",
"image",
".",
"Rect",
"(",
"0",
",",
"0",
",",
"r",
".",
"Dx",
"(",
")",
",",
"r",
".",
"Dy",
"(",
")",
")",
")",
"\n",
"rowSize",
":=",
"r",
".",
"Dx",
"(",
")",
"*",
"4",
"\n",
"parallel",
"(",
"r",
".",
"Min",
".",
"Y",
",",
"r",
".",
"Max",
".",
"Y",
",",
"func",
"(",
"ys",
"<-",
"chan",
"int",
")",
"{",
"for",
"y",
":=",
"range",
"ys",
"{",
"i",
":=",
"(",
"y",
"-",
"r",
".",
"Min",
".",
"Y",
")",
"*",
"dst",
".",
"Stride",
"\n",
"src",
".",
"scan",
"(",
"r",
".",
"Min",
".",
"X",
",",
"y",
",",
"r",
".",
"Max",
".",
"X",
",",
"y",
"+",
"1",
",",
"dst",
".",
"Pix",
"[",
"i",
":",
"i",
"+",
"rowSize",
"]",
")",
"\n",
"}",
"\n",
"}",
")",
"\n",
"return",
"dst",
"\n",
"}"
] | // Crop cuts out a rectangular region with the specified bounds
// from the image and returns the cropped image. | [
"Crop",
"cuts",
"out",
"a",
"rectangular",
"region",
"with",
"the",
"specified",
"bounds",
"from",
"the",
"image",
"and",
"returns",
"the",
"cropped",
"image",
"."
] | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/tools.go#L94-L109 | train |
disintegration/imaging | tools.go | CropAnchor | func CropAnchor(img image.Image, width, height int, anchor Anchor) *image.NRGBA {
srcBounds := img.Bounds()
pt := anchorPt(srcBounds, width, height, anchor)
r := image.Rect(0, 0, width, height).Add(pt)
b := srcBounds.Intersect(r)
return Crop(img, b)
} | go | func CropAnchor(img image.Image, width, height int, anchor Anchor) *image.NRGBA {
srcBounds := img.Bounds()
pt := anchorPt(srcBounds, width, height, anchor)
r := image.Rect(0, 0, width, height).Add(pt)
b := srcBounds.Intersect(r)
return Crop(img, b)
} | [
"func",
"CropAnchor",
"(",
"img",
"image",
".",
"Image",
",",
"width",
",",
"height",
"int",
",",
"anchor",
"Anchor",
")",
"*",
"image",
".",
"NRGBA",
"{",
"srcBounds",
":=",
"img",
".",
"Bounds",
"(",
")",
"\n",
"pt",
":=",
"anchorPt",
"(",
"srcBounds",
",",
"width",
",",
"height",
",",
"anchor",
")",
"\n",
"r",
":=",
"image",
".",
"Rect",
"(",
"0",
",",
"0",
",",
"width",
",",
"height",
")",
".",
"Add",
"(",
"pt",
")",
"\n",
"b",
":=",
"srcBounds",
".",
"Intersect",
"(",
"r",
")",
"\n",
"return",
"Crop",
"(",
"img",
",",
"b",
")",
"\n",
"}"
] | // CropAnchor cuts out a rectangular region with the specified size
// from the image using the specified anchor point and returns the cropped image. | [
"CropAnchor",
"cuts",
"out",
"a",
"rectangular",
"region",
"with",
"the",
"specified",
"size",
"from",
"the",
"image",
"using",
"the",
"specified",
"anchor",
"point",
"and",
"returns",
"the",
"cropped",
"image",
"."
] | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/tools.go#L113-L119 | train |
disintegration/imaging | tools.go | CropCenter | func CropCenter(img image.Image, width, height int) *image.NRGBA {
return CropAnchor(img, width, height, Center)
} | go | func CropCenter(img image.Image, width, height int) *image.NRGBA {
return CropAnchor(img, width, height, Center)
} | [
"func",
"CropCenter",
"(",
"img",
"image",
".",
"Image",
",",
"width",
",",
"height",
"int",
")",
"*",
"image",
".",
"NRGBA",
"{",
"return",
"CropAnchor",
"(",
"img",
",",
"width",
",",
"height",
",",
"Center",
")",
"\n",
"}"
] | // CropCenter cuts out a rectangular region with the specified size
// from the center of the image and returns the cropped image. | [
"CropCenter",
"cuts",
"out",
"a",
"rectangular",
"region",
"with",
"the",
"specified",
"size",
"from",
"the",
"center",
"of",
"the",
"image",
"and",
"returns",
"the",
"cropped",
"image",
"."
] | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/tools.go#L123-L125 | train |
disintegration/imaging | tools.go | Paste | func Paste(background, img image.Image, pos image.Point) *image.NRGBA {
dst := Clone(background)
pos = pos.Sub(background.Bounds().Min)
pasteRect := image.Rectangle{Min: pos, Max: pos.Add(img.Bounds().Size())}
interRect := pasteRect.Intersect(dst.Bounds())
if interRect.Empty() {
return dst
}
src := newScanner(img)
parallel(interRect.Min.Y, interRect.Max.Y, func(ys <-chan int) {
for y := range ys {
x1 := interRect.Min.X - pasteRect.Min.X
x2 := interRect.Max.X - pasteRect.Min.X
y1 := y - pasteRect.Min.Y
y2 := y1 + 1
i1 := y*dst.Stride + interRect.Min.X*4
i2 := i1 + interRect.Dx()*4
src.scan(x1, y1, x2, y2, dst.Pix[i1:i2])
}
})
return dst
} | go | func Paste(background, img image.Image, pos image.Point) *image.NRGBA {
dst := Clone(background)
pos = pos.Sub(background.Bounds().Min)
pasteRect := image.Rectangle{Min: pos, Max: pos.Add(img.Bounds().Size())}
interRect := pasteRect.Intersect(dst.Bounds())
if interRect.Empty() {
return dst
}
src := newScanner(img)
parallel(interRect.Min.Y, interRect.Max.Y, func(ys <-chan int) {
for y := range ys {
x1 := interRect.Min.X - pasteRect.Min.X
x2 := interRect.Max.X - pasteRect.Min.X
y1 := y - pasteRect.Min.Y
y2 := y1 + 1
i1 := y*dst.Stride + interRect.Min.X*4
i2 := i1 + interRect.Dx()*4
src.scan(x1, y1, x2, y2, dst.Pix[i1:i2])
}
})
return dst
} | [
"func",
"Paste",
"(",
"background",
",",
"img",
"image",
".",
"Image",
",",
"pos",
"image",
".",
"Point",
")",
"*",
"image",
".",
"NRGBA",
"{",
"dst",
":=",
"Clone",
"(",
"background",
")",
"\n",
"pos",
"=",
"pos",
".",
"Sub",
"(",
"background",
".",
"Bounds",
"(",
")",
".",
"Min",
")",
"\n",
"pasteRect",
":=",
"image",
".",
"Rectangle",
"{",
"Min",
":",
"pos",
",",
"Max",
":",
"pos",
".",
"Add",
"(",
"img",
".",
"Bounds",
"(",
")",
".",
"Size",
"(",
")",
")",
"}",
"\n",
"interRect",
":=",
"pasteRect",
".",
"Intersect",
"(",
"dst",
".",
"Bounds",
"(",
")",
")",
"\n",
"if",
"interRect",
".",
"Empty",
"(",
")",
"{",
"return",
"dst",
"\n",
"}",
"\n",
"src",
":=",
"newScanner",
"(",
"img",
")",
"\n",
"parallel",
"(",
"interRect",
".",
"Min",
".",
"Y",
",",
"interRect",
".",
"Max",
".",
"Y",
",",
"func",
"(",
"ys",
"<-",
"chan",
"int",
")",
"{",
"for",
"y",
":=",
"range",
"ys",
"{",
"x1",
":=",
"interRect",
".",
"Min",
".",
"X",
"-",
"pasteRect",
".",
"Min",
".",
"X",
"\n",
"x2",
":=",
"interRect",
".",
"Max",
".",
"X",
"-",
"pasteRect",
".",
"Min",
".",
"X",
"\n",
"y1",
":=",
"y",
"-",
"pasteRect",
".",
"Min",
".",
"Y",
"\n",
"y2",
":=",
"y1",
"+",
"1",
"\n",
"i1",
":=",
"y",
"*",
"dst",
".",
"Stride",
"+",
"interRect",
".",
"Min",
".",
"X",
"*",
"4",
"\n",
"i2",
":=",
"i1",
"+",
"interRect",
".",
"Dx",
"(",
")",
"*",
"4",
"\n",
"src",
".",
"scan",
"(",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"dst",
".",
"Pix",
"[",
"i1",
":",
"i2",
"]",
")",
"\n",
"}",
"\n",
"}",
")",
"\n",
"return",
"dst",
"\n",
"}"
] | // Paste pastes the img image to the background image at the specified position and returns the combined image. | [
"Paste",
"pastes",
"the",
"img",
"image",
"to",
"the",
"background",
"image",
"at",
"the",
"specified",
"position",
"and",
"returns",
"the",
"combined",
"image",
"."
] | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/tools.go#L128-L149 | train |
disintegration/imaging | tools.go | PasteCenter | func PasteCenter(background, img image.Image) *image.NRGBA {
bgBounds := background.Bounds()
bgW := bgBounds.Dx()
bgH := bgBounds.Dy()
bgMinX := bgBounds.Min.X
bgMinY := bgBounds.Min.Y
centerX := bgMinX + bgW/2
centerY := bgMinY + bgH/2
x0 := centerX - img.Bounds().Dx()/2
y0 := centerY - img.Bounds().Dy()/2
return Paste(background, img, image.Pt(x0, y0))
} | go | func PasteCenter(background, img image.Image) *image.NRGBA {
bgBounds := background.Bounds()
bgW := bgBounds.Dx()
bgH := bgBounds.Dy()
bgMinX := bgBounds.Min.X
bgMinY := bgBounds.Min.Y
centerX := bgMinX + bgW/2
centerY := bgMinY + bgH/2
x0 := centerX - img.Bounds().Dx()/2
y0 := centerY - img.Bounds().Dy()/2
return Paste(background, img, image.Pt(x0, y0))
} | [
"func",
"PasteCenter",
"(",
"background",
",",
"img",
"image",
".",
"Image",
")",
"*",
"image",
".",
"NRGBA",
"{",
"bgBounds",
":=",
"background",
".",
"Bounds",
"(",
")",
"\n",
"bgW",
":=",
"bgBounds",
".",
"Dx",
"(",
")",
"\n",
"bgH",
":=",
"bgBounds",
".",
"Dy",
"(",
")",
"\n",
"bgMinX",
":=",
"bgBounds",
".",
"Min",
".",
"X",
"\n",
"bgMinY",
":=",
"bgBounds",
".",
"Min",
".",
"Y",
"\n",
"centerX",
":=",
"bgMinX",
"+",
"bgW",
"/",
"2",
"\n",
"centerY",
":=",
"bgMinY",
"+",
"bgH",
"/",
"2",
"\n",
"x0",
":=",
"centerX",
"-",
"img",
".",
"Bounds",
"(",
")",
".",
"Dx",
"(",
")",
"/",
"2",
"\n",
"y0",
":=",
"centerY",
"-",
"img",
".",
"Bounds",
"(",
")",
".",
"Dy",
"(",
")",
"/",
"2",
"\n",
"return",
"Paste",
"(",
"background",
",",
"img",
",",
"image",
".",
"Pt",
"(",
"x0",
",",
"y0",
")",
")",
"\n",
"}"
] | // PasteCenter pastes the img image to the center of the background image and returns the combined image. | [
"PasteCenter",
"pastes",
"the",
"img",
"image",
"to",
"the",
"center",
"of",
"the",
"background",
"image",
"and",
"returns",
"the",
"combined",
"image",
"."
] | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/tools.go#L152-L166 | train |
disintegration/imaging | tools.go | OverlayCenter | func OverlayCenter(background, img image.Image, opacity float64) *image.NRGBA {
bgBounds := background.Bounds()
bgW := bgBounds.Dx()
bgH := bgBounds.Dy()
bgMinX := bgBounds.Min.X
bgMinY := bgBounds.Min.Y
centerX := bgMinX + bgW/2
centerY := bgMinY + bgH/2
x0 := centerX - img.Bounds().Dx()/2
y0 := centerY - img.Bounds().Dy()/2
return Overlay(background, img, image.Point{x0, y0}, opacity)
} | go | func OverlayCenter(background, img image.Image, opacity float64) *image.NRGBA {
bgBounds := background.Bounds()
bgW := bgBounds.Dx()
bgH := bgBounds.Dy()
bgMinX := bgBounds.Min.X
bgMinY := bgBounds.Min.Y
centerX := bgMinX + bgW/2
centerY := bgMinY + bgH/2
x0 := centerX - img.Bounds().Dx()/2
y0 := centerY - img.Bounds().Dy()/2
return Overlay(background, img, image.Point{x0, y0}, opacity)
} | [
"func",
"OverlayCenter",
"(",
"background",
",",
"img",
"image",
".",
"Image",
",",
"opacity",
"float64",
")",
"*",
"image",
".",
"NRGBA",
"{",
"bgBounds",
":=",
"background",
".",
"Bounds",
"(",
")",
"\n",
"bgW",
":=",
"bgBounds",
".",
"Dx",
"(",
")",
"\n",
"bgH",
":=",
"bgBounds",
".",
"Dy",
"(",
")",
"\n",
"bgMinX",
":=",
"bgBounds",
".",
"Min",
".",
"X",
"\n",
"bgMinY",
":=",
"bgBounds",
".",
"Min",
".",
"Y",
"\n",
"centerX",
":=",
"bgMinX",
"+",
"bgW",
"/",
"2",
"\n",
"centerY",
":=",
"bgMinY",
"+",
"bgH",
"/",
"2",
"\n",
"x0",
":=",
"centerX",
"-",
"img",
".",
"Bounds",
"(",
")",
".",
"Dx",
"(",
")",
"/",
"2",
"\n",
"y0",
":=",
"centerY",
"-",
"img",
".",
"Bounds",
"(",
")",
".",
"Dy",
"(",
")",
"/",
"2",
"\n",
"return",
"Overlay",
"(",
"background",
",",
"img",
",",
"image",
".",
"Point",
"{",
"x0",
",",
"y0",
"}",
",",
"opacity",
")",
"\n",
"}"
] | // OverlayCenter overlays the img image to the center of the background image and
// returns the combined image. Opacity parameter is the opacity of the img
// image layer, used to compose the images, it must be from 0.0 to 1.0. | [
"OverlayCenter",
"overlays",
"the",
"img",
"image",
"to",
"the",
"center",
"of",
"the",
"background",
"image",
"and",
"returns",
"the",
"combined",
"image",
".",
"Opacity",
"parameter",
"is",
"the",
"opacity",
"of",
"the",
"img",
"image",
"layer",
"used",
"to",
"compose",
"the",
"images",
"it",
"must",
"be",
"from",
"0",
".",
"0",
"to",
"1",
".",
"0",
"."
] | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/tools.go#L235-L249 | train |
disintegration/imaging | transform.go | Rotate | func Rotate(img image.Image, angle float64, bgColor color.Color) *image.NRGBA {
angle = angle - math.Floor(angle/360)*360
switch angle {
case 0:
return Clone(img)
case 90:
return Rotate90(img)
case 180:
return Rotate180(img)
case 270:
return Rotate270(img)
}
src := toNRGBA(img)
srcW := src.Bounds().Max.X
srcH := src.Bounds().Max.Y
dstW, dstH := rotatedSize(srcW, srcH, angle)
dst := image.NewNRGBA(image.Rect(0, 0, dstW, dstH))
if dstW <= 0 || dstH <= 0 {
return dst
}
srcXOff := float64(srcW)/2 - 0.5
srcYOff := float64(srcH)/2 - 0.5
dstXOff := float64(dstW)/2 - 0.5
dstYOff := float64(dstH)/2 - 0.5
bgColorNRGBA := color.NRGBAModel.Convert(bgColor).(color.NRGBA)
sin, cos := math.Sincos(math.Pi * angle / 180)
parallel(0, dstH, func(ys <-chan int) {
for dstY := range ys {
for dstX := 0; dstX < dstW; dstX++ {
xf, yf := rotatePoint(float64(dstX)-dstXOff, float64(dstY)-dstYOff, sin, cos)
xf, yf = xf+srcXOff, yf+srcYOff
interpolatePoint(dst, dstX, dstY, src, xf, yf, bgColorNRGBA)
}
}
})
return dst
} | go | func Rotate(img image.Image, angle float64, bgColor color.Color) *image.NRGBA {
angle = angle - math.Floor(angle/360)*360
switch angle {
case 0:
return Clone(img)
case 90:
return Rotate90(img)
case 180:
return Rotate180(img)
case 270:
return Rotate270(img)
}
src := toNRGBA(img)
srcW := src.Bounds().Max.X
srcH := src.Bounds().Max.Y
dstW, dstH := rotatedSize(srcW, srcH, angle)
dst := image.NewNRGBA(image.Rect(0, 0, dstW, dstH))
if dstW <= 0 || dstH <= 0 {
return dst
}
srcXOff := float64(srcW)/2 - 0.5
srcYOff := float64(srcH)/2 - 0.5
dstXOff := float64(dstW)/2 - 0.5
dstYOff := float64(dstH)/2 - 0.5
bgColorNRGBA := color.NRGBAModel.Convert(bgColor).(color.NRGBA)
sin, cos := math.Sincos(math.Pi * angle / 180)
parallel(0, dstH, func(ys <-chan int) {
for dstY := range ys {
for dstX := 0; dstX < dstW; dstX++ {
xf, yf := rotatePoint(float64(dstX)-dstXOff, float64(dstY)-dstYOff, sin, cos)
xf, yf = xf+srcXOff, yf+srcYOff
interpolatePoint(dst, dstX, dstY, src, xf, yf, bgColorNRGBA)
}
}
})
return dst
} | [
"func",
"Rotate",
"(",
"img",
"image",
".",
"Image",
",",
"angle",
"float64",
",",
"bgColor",
"color",
".",
"Color",
")",
"*",
"image",
".",
"NRGBA",
"{",
"angle",
"=",
"angle",
"-",
"math",
".",
"Floor",
"(",
"angle",
"/",
"360",
")",
"*",
"360",
"\n",
"switch",
"angle",
"{",
"case",
"0",
":",
"return",
"Clone",
"(",
"img",
")",
"\n",
"case",
"90",
":",
"return",
"Rotate90",
"(",
"img",
")",
"\n",
"case",
"180",
":",
"return",
"Rotate180",
"(",
"img",
")",
"\n",
"case",
"270",
":",
"return",
"Rotate270",
"(",
"img",
")",
"\n",
"}",
"\n",
"src",
":=",
"toNRGBA",
"(",
"img",
")",
"\n",
"srcW",
":=",
"src",
".",
"Bounds",
"(",
")",
".",
"Max",
".",
"X",
"\n",
"srcH",
":=",
"src",
".",
"Bounds",
"(",
")",
".",
"Max",
".",
"Y",
"\n",
"dstW",
",",
"dstH",
":=",
"rotatedSize",
"(",
"srcW",
",",
"srcH",
",",
"angle",
")",
"\n",
"dst",
":=",
"image",
".",
"NewNRGBA",
"(",
"image",
".",
"Rect",
"(",
"0",
",",
"0",
",",
"dstW",
",",
"dstH",
")",
")",
"\n",
"if",
"dstW",
"<=",
"0",
"||",
"dstH",
"<=",
"0",
"{",
"return",
"dst",
"\n",
"}",
"\n",
"srcXOff",
":=",
"float64",
"(",
"srcW",
")",
"/",
"2",
"-",
"0.5",
"\n",
"srcYOff",
":=",
"float64",
"(",
"srcH",
")",
"/",
"2",
"-",
"0.5",
"\n",
"dstXOff",
":=",
"float64",
"(",
"dstW",
")",
"/",
"2",
"-",
"0.5",
"\n",
"dstYOff",
":=",
"float64",
"(",
"dstH",
")",
"/",
"2",
"-",
"0.5",
"\n",
"bgColorNRGBA",
":=",
"color",
".",
"NRGBAModel",
".",
"Convert",
"(",
"bgColor",
")",
".",
"(",
"color",
".",
"NRGBA",
")",
"\n",
"sin",
",",
"cos",
":=",
"math",
".",
"Sincos",
"(",
"math",
".",
"Pi",
"*",
"angle",
"/",
"180",
")",
"\n",
"parallel",
"(",
"0",
",",
"dstH",
",",
"func",
"(",
"ys",
"<-",
"chan",
"int",
")",
"{",
"for",
"dstY",
":=",
"range",
"ys",
"{",
"for",
"dstX",
":=",
"0",
";",
"dstX",
"<",
"dstW",
";",
"dstX",
"++",
"{",
"xf",
",",
"yf",
":=",
"rotatePoint",
"(",
"float64",
"(",
"dstX",
")",
"-",
"dstXOff",
",",
"float64",
"(",
"dstY",
")",
"-",
"dstYOff",
",",
"sin",
",",
"cos",
")",
"\n",
"xf",
",",
"yf",
"=",
"xf",
"+",
"srcXOff",
",",
"yf",
"+",
"srcYOff",
"\n",
"interpolatePoint",
"(",
"dst",
",",
"dstX",
",",
"dstY",
",",
"src",
",",
"xf",
",",
"yf",
",",
"bgColorNRGBA",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
")",
"\n",
"return",
"dst",
"\n",
"}"
] | // Rotate rotates an image by the given angle counter-clockwise .
// The angle parameter is the rotation angle in degrees.
// The bgColor parameter specifies the color of the uncovered zone after the rotation. | [
"Rotate",
"rotates",
"an",
"image",
"by",
"the",
"given",
"angle",
"counter",
"-",
"clockwise",
".",
"The",
"angle",
"parameter",
"is",
"the",
"rotation",
"angle",
"in",
"degrees",
".",
"The",
"bgColor",
"parameter",
"specifies",
"the",
"color",
"of",
"the",
"uncovered",
"zone",
"after",
"the",
"rotation",
"."
] | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/transform.go#L135-L178 | train |
disintegration/imaging | utils.go | parallel | func parallel(start, stop int, fn func(<-chan int)) {
count := stop - start
if count < 1 {
return
}
procs := runtime.GOMAXPROCS(0)
if procs > count {
procs = count
}
c := make(chan int, count)
for i := start; i < stop; i++ {
c <- i
}
close(c)
var wg sync.WaitGroup
for i := 0; i < procs; i++ {
wg.Add(1)
go func() {
defer wg.Done()
fn(c)
}()
}
wg.Wait()
} | go | func parallel(start, stop int, fn func(<-chan int)) {
count := stop - start
if count < 1 {
return
}
procs := runtime.GOMAXPROCS(0)
if procs > count {
procs = count
}
c := make(chan int, count)
for i := start; i < stop; i++ {
c <- i
}
close(c)
var wg sync.WaitGroup
for i := 0; i < procs; i++ {
wg.Add(1)
go func() {
defer wg.Done()
fn(c)
}()
}
wg.Wait()
} | [
"func",
"parallel",
"(",
"start",
",",
"stop",
"int",
",",
"fn",
"func",
"(",
"<-",
"chan",
"int",
")",
")",
"{",
"count",
":=",
"stop",
"-",
"start",
"\n",
"if",
"count",
"<",
"1",
"{",
"return",
"\n",
"}",
"\n",
"procs",
":=",
"runtime",
".",
"GOMAXPROCS",
"(",
"0",
")",
"\n",
"if",
"procs",
">",
"count",
"{",
"procs",
"=",
"count",
"\n",
"}",
"\n",
"c",
":=",
"make",
"(",
"chan",
"int",
",",
"count",
")",
"\n",
"for",
"i",
":=",
"start",
";",
"i",
"<",
"stop",
";",
"i",
"++",
"{",
"c",
"<-",
"i",
"\n",
"}",
"\n",
"close",
"(",
"c",
")",
"\n",
"var",
"wg",
"sync",
".",
"WaitGroup",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"procs",
";",
"i",
"++",
"{",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"defer",
"wg",
".",
"Done",
"(",
")",
"\n",
"fn",
"(",
"c",
")",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n",
"wg",
".",
"Wait",
"(",
")",
"\n",
"}"
] | // parallel processes the data in separate goroutines. | [
"parallel",
"processes",
"the",
"data",
"in",
"separate",
"goroutines",
"."
] | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/utils.go#L11-L37 | train |
disintegration/imaging | utils.go | clamp | func clamp(x float64) uint8 {
v := int64(x + 0.5)
if v > 255 {
return 255
}
if v > 0 {
return uint8(v)
}
return 0
} | go | func clamp(x float64) uint8 {
v := int64(x + 0.5)
if v > 255 {
return 255
}
if v > 0 {
return uint8(v)
}
return 0
} | [
"func",
"clamp",
"(",
"x",
"float64",
")",
"uint8",
"{",
"v",
":=",
"int64",
"(",
"x",
"+",
"0.5",
")",
"\n",
"if",
"v",
">",
"255",
"{",
"return",
"255",
"\n",
"}",
"\n",
"if",
"v",
">",
"0",
"{",
"return",
"uint8",
"(",
"v",
")",
"\n",
"}",
"\n",
"return",
"0",
"\n",
"}"
] | // clamp rounds and clamps float64 value to fit into uint8. | [
"clamp",
"rounds",
"and",
"clamps",
"float64",
"value",
"to",
"fit",
"into",
"uint8",
"."
] | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/utils.go#L48-L57 | train |
disintegration/imaging | utils.go | rgbToHSL | func rgbToHSL(r, g, b uint8) (float64, float64, float64) {
rr := float64(r) / 255
gg := float64(g) / 255
bb := float64(b) / 255
max := math.Max(rr, math.Max(gg, bb))
min := math.Min(rr, math.Min(gg, bb))
l := (max + min) / 2
if max == min {
return 0, 0, l
}
var h, s float64
d := max - min
if l > 0.5 {
s = d / (2 - max - min)
} else {
s = d / (max + min)
}
switch max {
case rr:
h = (gg - bb) / d
if g < b {
h += 6
}
case gg:
h = (bb-rr)/d + 2
case bb:
h = (rr-gg)/d + 4
}
h /= 6
return h, s, l
} | go | func rgbToHSL(r, g, b uint8) (float64, float64, float64) {
rr := float64(r) / 255
gg := float64(g) / 255
bb := float64(b) / 255
max := math.Max(rr, math.Max(gg, bb))
min := math.Min(rr, math.Min(gg, bb))
l := (max + min) / 2
if max == min {
return 0, 0, l
}
var h, s float64
d := max - min
if l > 0.5 {
s = d / (2 - max - min)
} else {
s = d / (max + min)
}
switch max {
case rr:
h = (gg - bb) / d
if g < b {
h += 6
}
case gg:
h = (bb-rr)/d + 2
case bb:
h = (rr-gg)/d + 4
}
h /= 6
return h, s, l
} | [
"func",
"rgbToHSL",
"(",
"r",
",",
"g",
",",
"b",
"uint8",
")",
"(",
"float64",
",",
"float64",
",",
"float64",
")",
"{",
"rr",
":=",
"float64",
"(",
"r",
")",
"/",
"255",
"\n",
"gg",
":=",
"float64",
"(",
"g",
")",
"/",
"255",
"\n",
"bb",
":=",
"float64",
"(",
"b",
")",
"/",
"255",
"\n",
"max",
":=",
"math",
".",
"Max",
"(",
"rr",
",",
"math",
".",
"Max",
"(",
"gg",
",",
"bb",
")",
")",
"\n",
"min",
":=",
"math",
".",
"Min",
"(",
"rr",
",",
"math",
".",
"Min",
"(",
"gg",
",",
"bb",
")",
")",
"\n",
"l",
":=",
"(",
"max",
"+",
"min",
")",
"/",
"2",
"\n",
"if",
"max",
"==",
"min",
"{",
"return",
"0",
",",
"0",
",",
"l",
"\n",
"}",
"\n",
"var",
"h",
",",
"s",
"float64",
"\n",
"d",
":=",
"max",
"-",
"min",
"\n",
"if",
"l",
">",
"0.5",
"{",
"s",
"=",
"d",
"/",
"(",
"2",
"-",
"max",
"-",
"min",
")",
"\n",
"}",
"else",
"{",
"s",
"=",
"d",
"/",
"(",
"max",
"+",
"min",
")",
"\n",
"}",
"\n",
"switch",
"max",
"{",
"case",
"rr",
":",
"h",
"=",
"(",
"gg",
"-",
"bb",
")",
"/",
"d",
"\n",
"if",
"g",
"<",
"b",
"{",
"h",
"+=",
"6",
"\n",
"}",
"\n",
"case",
"gg",
":",
"h",
"=",
"(",
"bb",
"-",
"rr",
")",
"/",
"d",
"+",
"2",
"\n",
"case",
"bb",
":",
"h",
"=",
"(",
"rr",
"-",
"gg",
")",
"/",
"d",
"+",
"4",
"\n",
"}",
"\n",
"h",
"/=",
"6",
"\n",
"return",
"h",
",",
"s",
",",
"l",
"\n",
"}"
] | // rgbToHSL converts a color from RGB to HSL. | [
"rgbToHSL",
"converts",
"a",
"color",
"from",
"RGB",
"to",
"HSL",
"."
] | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/utils.go#L89-L125 | train |
disintegration/imaging | utils.go | hslToRGB | func hslToRGB(h, s, l float64) (uint8, uint8, uint8) {
var r, g, b float64
if s == 0 {
v := clamp(l * 255)
return v, v, v
}
var q float64
if l < 0.5 {
q = l * (1 + s)
} else {
q = l + s - l*s
}
p := 2*l - q
r = hueToRGB(p, q, h+1/3.0)
g = hueToRGB(p, q, h)
b = hueToRGB(p, q, h-1/3.0)
return clamp(r * 255), clamp(g * 255), clamp(b * 255)
} | go | func hslToRGB(h, s, l float64) (uint8, uint8, uint8) {
var r, g, b float64
if s == 0 {
v := clamp(l * 255)
return v, v, v
}
var q float64
if l < 0.5 {
q = l * (1 + s)
} else {
q = l + s - l*s
}
p := 2*l - q
r = hueToRGB(p, q, h+1/3.0)
g = hueToRGB(p, q, h)
b = hueToRGB(p, q, h-1/3.0)
return clamp(r * 255), clamp(g * 255), clamp(b * 255)
} | [
"func",
"hslToRGB",
"(",
"h",
",",
"s",
",",
"l",
"float64",
")",
"(",
"uint8",
",",
"uint8",
",",
"uint8",
")",
"{",
"var",
"r",
",",
"g",
",",
"b",
"float64",
"\n",
"if",
"s",
"==",
"0",
"{",
"v",
":=",
"clamp",
"(",
"l",
"*",
"255",
")",
"\n",
"return",
"v",
",",
"v",
",",
"v",
"\n",
"}",
"\n",
"var",
"q",
"float64",
"\n",
"if",
"l",
"<",
"0.5",
"{",
"q",
"=",
"l",
"*",
"(",
"1",
"+",
"s",
")",
"\n",
"}",
"else",
"{",
"q",
"=",
"l",
"+",
"s",
"-",
"l",
"*",
"s",
"\n",
"}",
"\n",
"p",
":=",
"2",
"*",
"l",
"-",
"q",
"\n",
"r",
"=",
"hueToRGB",
"(",
"p",
",",
"q",
",",
"h",
"+",
"1",
"/",
"3.0",
")",
"\n",
"g",
"=",
"hueToRGB",
"(",
"p",
",",
"q",
",",
"h",
")",
"\n",
"b",
"=",
"hueToRGB",
"(",
"p",
",",
"q",
",",
"h",
"-",
"1",
"/",
"3.0",
")",
"\n",
"return",
"clamp",
"(",
"r",
"*",
"255",
")",
",",
"clamp",
"(",
"g",
"*",
"255",
")",
",",
"clamp",
"(",
"b",
"*",
"255",
")",
"\n",
"}"
] | // hslToRGB converts a color from HSL to RGB. | [
"hslToRGB",
"converts",
"a",
"color",
"from",
"HSL",
"to",
"RGB",
"."
] | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/utils.go#L128-L148 | train |
disintegration/imaging | resize.go | resizeNearest | func resizeNearest(img image.Image, width, height int) *image.NRGBA {
dst := image.NewNRGBA(image.Rect(0, 0, width, height))
dx := float64(img.Bounds().Dx()) / float64(width)
dy := float64(img.Bounds().Dy()) / float64(height)
if dx > 1 && dy > 1 {
src := newScanner(img)
parallel(0, height, func(ys <-chan int) {
for y := range ys {
srcY := int((float64(y) + 0.5) * dy)
dstOff := y * dst.Stride
for x := 0; x < width; x++ {
srcX := int((float64(x) + 0.5) * dx)
src.scan(srcX, srcY, srcX+1, srcY+1, dst.Pix[dstOff:dstOff+4])
dstOff += 4
}
}
})
} else {
src := toNRGBA(img)
parallel(0, height, func(ys <-chan int) {
for y := range ys {
srcY := int((float64(y) + 0.5) * dy)
srcOff0 := srcY * src.Stride
dstOff := y * dst.Stride
for x := 0; x < width; x++ {
srcX := int((float64(x) + 0.5) * dx)
srcOff := srcOff0 + srcX*4
copy(dst.Pix[dstOff:dstOff+4], src.Pix[srcOff:srcOff+4])
dstOff += 4
}
}
})
}
return dst
} | go | func resizeNearest(img image.Image, width, height int) *image.NRGBA {
dst := image.NewNRGBA(image.Rect(0, 0, width, height))
dx := float64(img.Bounds().Dx()) / float64(width)
dy := float64(img.Bounds().Dy()) / float64(height)
if dx > 1 && dy > 1 {
src := newScanner(img)
parallel(0, height, func(ys <-chan int) {
for y := range ys {
srcY := int((float64(y) + 0.5) * dy)
dstOff := y * dst.Stride
for x := 0; x < width; x++ {
srcX := int((float64(x) + 0.5) * dx)
src.scan(srcX, srcY, srcX+1, srcY+1, dst.Pix[dstOff:dstOff+4])
dstOff += 4
}
}
})
} else {
src := toNRGBA(img)
parallel(0, height, func(ys <-chan int) {
for y := range ys {
srcY := int((float64(y) + 0.5) * dy)
srcOff0 := srcY * src.Stride
dstOff := y * dst.Stride
for x := 0; x < width; x++ {
srcX := int((float64(x) + 0.5) * dx)
srcOff := srcOff0 + srcX*4
copy(dst.Pix[dstOff:dstOff+4], src.Pix[srcOff:srcOff+4])
dstOff += 4
}
}
})
}
return dst
} | [
"func",
"resizeNearest",
"(",
"img",
"image",
".",
"Image",
",",
"width",
",",
"height",
"int",
")",
"*",
"image",
".",
"NRGBA",
"{",
"dst",
":=",
"image",
".",
"NewNRGBA",
"(",
"image",
".",
"Rect",
"(",
"0",
",",
"0",
",",
"width",
",",
"height",
")",
")",
"\n",
"dx",
":=",
"float64",
"(",
"img",
".",
"Bounds",
"(",
")",
".",
"Dx",
"(",
")",
")",
"/",
"float64",
"(",
"width",
")",
"\n",
"dy",
":=",
"float64",
"(",
"img",
".",
"Bounds",
"(",
")",
".",
"Dy",
"(",
")",
")",
"/",
"float64",
"(",
"height",
")",
"\n",
"if",
"dx",
">",
"1",
"&&",
"dy",
">",
"1",
"{",
"src",
":=",
"newScanner",
"(",
"img",
")",
"\n",
"parallel",
"(",
"0",
",",
"height",
",",
"func",
"(",
"ys",
"<-",
"chan",
"int",
")",
"{",
"for",
"y",
":=",
"range",
"ys",
"{",
"srcY",
":=",
"int",
"(",
"(",
"float64",
"(",
"y",
")",
"+",
"0.5",
")",
"*",
"dy",
")",
"\n",
"dstOff",
":=",
"y",
"*",
"dst",
".",
"Stride",
"\n",
"for",
"x",
":=",
"0",
";",
"x",
"<",
"width",
";",
"x",
"++",
"{",
"srcX",
":=",
"int",
"(",
"(",
"float64",
"(",
"x",
")",
"+",
"0.5",
")",
"*",
"dx",
")",
"\n",
"src",
".",
"scan",
"(",
"srcX",
",",
"srcY",
",",
"srcX",
"+",
"1",
",",
"srcY",
"+",
"1",
",",
"dst",
".",
"Pix",
"[",
"dstOff",
":",
"dstOff",
"+",
"4",
"]",
")",
"\n",
"dstOff",
"+=",
"4",
"\n",
"}",
"\n",
"}",
"\n",
"}",
")",
"\n",
"}",
"else",
"{",
"src",
":=",
"toNRGBA",
"(",
"img",
")",
"\n",
"parallel",
"(",
"0",
",",
"height",
",",
"func",
"(",
"ys",
"<-",
"chan",
"int",
")",
"{",
"for",
"y",
":=",
"range",
"ys",
"{",
"srcY",
":=",
"int",
"(",
"(",
"float64",
"(",
"y",
")",
"+",
"0.5",
")",
"*",
"dy",
")",
"\n",
"srcOff0",
":=",
"srcY",
"*",
"src",
".",
"Stride",
"\n",
"dstOff",
":=",
"y",
"*",
"dst",
".",
"Stride",
"\n",
"for",
"x",
":=",
"0",
";",
"x",
"<",
"width",
";",
"x",
"++",
"{",
"srcX",
":=",
"int",
"(",
"(",
"float64",
"(",
"x",
")",
"+",
"0.5",
")",
"*",
"dx",
")",
"\n",
"srcOff",
":=",
"srcOff0",
"+",
"srcX",
"*",
"4",
"\n",
"copy",
"(",
"dst",
".",
"Pix",
"[",
"dstOff",
":",
"dstOff",
"+",
"4",
"]",
",",
"src",
".",
"Pix",
"[",
"srcOff",
":",
"srcOff",
"+",
"4",
"]",
")",
"\n",
"dstOff",
"+=",
"4",
"\n",
"}",
"\n",
"}",
"\n",
"}",
")",
"\n",
"}",
"\n",
"return",
"dst",
"\n",
"}"
] | // resizeNearest is a fast nearest-neighbor resize, no filtering. | [
"resizeNearest",
"is",
"a",
"fast",
"nearest",
"-",
"neighbor",
"resize",
"no",
"filtering",
"."
] | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/resize.go#L177-L213 | train |
disintegration/imaging | resize.go | cropAndResize | func cropAndResize(img image.Image, width, height int, anchor Anchor, filter ResampleFilter) *image.NRGBA {
dstW, dstH := width, height
srcBounds := img.Bounds()
srcW := srcBounds.Dx()
srcH := srcBounds.Dy()
srcAspectRatio := float64(srcW) / float64(srcH)
dstAspectRatio := float64(dstW) / float64(dstH)
var tmp *image.NRGBA
if srcAspectRatio < dstAspectRatio {
cropH := float64(srcW) * float64(dstH) / float64(dstW)
tmp = CropAnchor(img, srcW, int(math.Max(1, cropH)+0.5), anchor)
} else {
cropW := float64(srcH) * float64(dstW) / float64(dstH)
tmp = CropAnchor(img, int(math.Max(1, cropW)+0.5), srcH, anchor)
}
return Resize(tmp, dstW, dstH, filter)
} | go | func cropAndResize(img image.Image, width, height int, anchor Anchor, filter ResampleFilter) *image.NRGBA {
dstW, dstH := width, height
srcBounds := img.Bounds()
srcW := srcBounds.Dx()
srcH := srcBounds.Dy()
srcAspectRatio := float64(srcW) / float64(srcH)
dstAspectRatio := float64(dstW) / float64(dstH)
var tmp *image.NRGBA
if srcAspectRatio < dstAspectRatio {
cropH := float64(srcW) * float64(dstH) / float64(dstW)
tmp = CropAnchor(img, srcW, int(math.Max(1, cropH)+0.5), anchor)
} else {
cropW := float64(srcH) * float64(dstW) / float64(dstH)
tmp = CropAnchor(img, int(math.Max(1, cropW)+0.5), srcH, anchor)
}
return Resize(tmp, dstW, dstH, filter)
} | [
"func",
"cropAndResize",
"(",
"img",
"image",
".",
"Image",
",",
"width",
",",
"height",
"int",
",",
"anchor",
"Anchor",
",",
"filter",
"ResampleFilter",
")",
"*",
"image",
".",
"NRGBA",
"{",
"dstW",
",",
"dstH",
":=",
"width",
",",
"height",
"\n",
"srcBounds",
":=",
"img",
".",
"Bounds",
"(",
")",
"\n",
"srcW",
":=",
"srcBounds",
".",
"Dx",
"(",
")",
"\n",
"srcH",
":=",
"srcBounds",
".",
"Dy",
"(",
")",
"\n",
"srcAspectRatio",
":=",
"float64",
"(",
"srcW",
")",
"/",
"float64",
"(",
"srcH",
")",
"\n",
"dstAspectRatio",
":=",
"float64",
"(",
"dstW",
")",
"/",
"float64",
"(",
"dstH",
")",
"\n",
"var",
"tmp",
"*",
"image",
".",
"NRGBA",
"\n",
"if",
"srcAspectRatio",
"<",
"dstAspectRatio",
"{",
"cropH",
":=",
"float64",
"(",
"srcW",
")",
"*",
"float64",
"(",
"dstH",
")",
"/",
"float64",
"(",
"dstW",
")",
"\n",
"tmp",
"=",
"CropAnchor",
"(",
"img",
",",
"srcW",
",",
"int",
"(",
"math",
".",
"Max",
"(",
"1",
",",
"cropH",
")",
"+",
"0.5",
")",
",",
"anchor",
")",
"\n",
"}",
"else",
"{",
"cropW",
":=",
"float64",
"(",
"srcH",
")",
"*",
"float64",
"(",
"dstW",
")",
"/",
"float64",
"(",
"dstH",
")",
"\n",
"tmp",
"=",
"CropAnchor",
"(",
"img",
",",
"int",
"(",
"math",
".",
"Max",
"(",
"1",
",",
"cropW",
")",
"+",
"0.5",
")",
",",
"srcH",
",",
"anchor",
")",
"\n",
"}",
"\n",
"return",
"Resize",
"(",
"tmp",
",",
"dstW",
",",
"dstH",
",",
"filter",
")",
"\n",
"}"
] | // cropAndResize crops the image to the smallest possible size that has the required aspect ratio using
// the given anchor point, then scales it to the specified dimensions and returns the transformed image.
//
// This is generally faster than resizing first, but may result in inaccuracies when used on small source images. | [
"cropAndResize",
"crops",
"the",
"image",
"to",
"the",
"smallest",
"possible",
"size",
"that",
"has",
"the",
"required",
"aspect",
"ratio",
"using",
"the",
"given",
"anchor",
"point",
"then",
"scales",
"it",
"to",
"the",
"specified",
"dimensions",
"and",
"returns",
"the",
"transformed",
"image",
".",
"This",
"is",
"generally",
"faster",
"than",
"resizing",
"first",
"but",
"may",
"result",
"in",
"inaccuracies",
"when",
"used",
"on",
"small",
"source",
"images",
"."
] | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/resize.go#L292-L311 | train |
disintegration/imaging | resize.go | resizeAndCrop | func resizeAndCrop(img image.Image, width, height int, anchor Anchor, filter ResampleFilter) *image.NRGBA {
dstW, dstH := width, height
srcBounds := img.Bounds()
srcW := srcBounds.Dx()
srcH := srcBounds.Dy()
srcAspectRatio := float64(srcW) / float64(srcH)
dstAspectRatio := float64(dstW) / float64(dstH)
var tmp *image.NRGBA
if srcAspectRatio < dstAspectRatio {
tmp = Resize(img, dstW, 0, filter)
} else {
tmp = Resize(img, 0, dstH, filter)
}
return CropAnchor(tmp, dstW, dstH, anchor)
} | go | func resizeAndCrop(img image.Image, width, height int, anchor Anchor, filter ResampleFilter) *image.NRGBA {
dstW, dstH := width, height
srcBounds := img.Bounds()
srcW := srcBounds.Dx()
srcH := srcBounds.Dy()
srcAspectRatio := float64(srcW) / float64(srcH)
dstAspectRatio := float64(dstW) / float64(dstH)
var tmp *image.NRGBA
if srcAspectRatio < dstAspectRatio {
tmp = Resize(img, dstW, 0, filter)
} else {
tmp = Resize(img, 0, dstH, filter)
}
return CropAnchor(tmp, dstW, dstH, anchor)
} | [
"func",
"resizeAndCrop",
"(",
"img",
"image",
".",
"Image",
",",
"width",
",",
"height",
"int",
",",
"anchor",
"Anchor",
",",
"filter",
"ResampleFilter",
")",
"*",
"image",
".",
"NRGBA",
"{",
"dstW",
",",
"dstH",
":=",
"width",
",",
"height",
"\n",
"srcBounds",
":=",
"img",
".",
"Bounds",
"(",
")",
"\n",
"srcW",
":=",
"srcBounds",
".",
"Dx",
"(",
")",
"\n",
"srcH",
":=",
"srcBounds",
".",
"Dy",
"(",
")",
"\n",
"srcAspectRatio",
":=",
"float64",
"(",
"srcW",
")",
"/",
"float64",
"(",
"srcH",
")",
"\n",
"dstAspectRatio",
":=",
"float64",
"(",
"dstW",
")",
"/",
"float64",
"(",
"dstH",
")",
"\n",
"var",
"tmp",
"*",
"image",
".",
"NRGBA",
"\n",
"if",
"srcAspectRatio",
"<",
"dstAspectRatio",
"{",
"tmp",
"=",
"Resize",
"(",
"img",
",",
"dstW",
",",
"0",
",",
"filter",
")",
"\n",
"}",
"else",
"{",
"tmp",
"=",
"Resize",
"(",
"img",
",",
"0",
",",
"dstH",
",",
"filter",
")",
"\n",
"}",
"\n",
"return",
"CropAnchor",
"(",
"tmp",
",",
"dstW",
",",
"dstH",
",",
"anchor",
")",
"\n",
"}"
] | // resizeAndCrop resizes the image to the smallest possible size that will cover the specified dimensions,
// crops the resized image to the specified dimensions using the given anchor point and returns
// the transformed image. | [
"resizeAndCrop",
"resizes",
"the",
"image",
"to",
"the",
"smallest",
"possible",
"size",
"that",
"will",
"cover",
"the",
"specified",
"dimensions",
"crops",
"the",
"resized",
"image",
"to",
"the",
"specified",
"dimensions",
"using",
"the",
"given",
"anchor",
"point",
"and",
"returns",
"the",
"transformed",
"image",
"."
] | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/resize.go#L316-L333 | train |
disintegration/imaging | adjust.go | Grayscale | func Grayscale(img image.Image) *image.NRGBA {
src := newScanner(img)
dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
parallel(0, src.h, func(ys <-chan int) {
for y := range ys {
i := y * dst.Stride
src.scan(0, y, src.w, y+1, dst.Pix[i:i+src.w*4])
for x := 0; x < src.w; x++ {
d := dst.Pix[i : i+3 : i+3]
r := d[0]
g := d[1]
b := d[2]
f := 0.299*float64(r) + 0.587*float64(g) + 0.114*float64(b)
y := uint8(f + 0.5)
d[0] = y
d[1] = y
d[2] = y
i += 4
}
}
})
return dst
} | go | func Grayscale(img image.Image) *image.NRGBA {
src := newScanner(img)
dst := image.NewNRGBA(image.Rect(0, 0, src.w, src.h))
parallel(0, src.h, func(ys <-chan int) {
for y := range ys {
i := y * dst.Stride
src.scan(0, y, src.w, y+1, dst.Pix[i:i+src.w*4])
for x := 0; x < src.w; x++ {
d := dst.Pix[i : i+3 : i+3]
r := d[0]
g := d[1]
b := d[2]
f := 0.299*float64(r) + 0.587*float64(g) + 0.114*float64(b)
y := uint8(f + 0.5)
d[0] = y
d[1] = y
d[2] = y
i += 4
}
}
})
return dst
} | [
"func",
"Grayscale",
"(",
"img",
"image",
".",
"Image",
")",
"*",
"image",
".",
"NRGBA",
"{",
"src",
":=",
"newScanner",
"(",
"img",
")",
"\n",
"dst",
":=",
"image",
".",
"NewNRGBA",
"(",
"image",
".",
"Rect",
"(",
"0",
",",
"0",
",",
"src",
".",
"w",
",",
"src",
".",
"h",
")",
")",
"\n",
"parallel",
"(",
"0",
",",
"src",
".",
"h",
",",
"func",
"(",
"ys",
"<-",
"chan",
"int",
")",
"{",
"for",
"y",
":=",
"range",
"ys",
"{",
"i",
":=",
"y",
"*",
"dst",
".",
"Stride",
"\n",
"src",
".",
"scan",
"(",
"0",
",",
"y",
",",
"src",
".",
"w",
",",
"y",
"+",
"1",
",",
"dst",
".",
"Pix",
"[",
"i",
":",
"i",
"+",
"src",
".",
"w",
"*",
"4",
"]",
")",
"\n",
"for",
"x",
":=",
"0",
";",
"x",
"<",
"src",
".",
"w",
";",
"x",
"++",
"{",
"d",
":=",
"dst",
".",
"Pix",
"[",
"i",
":",
"i",
"+",
"3",
":",
"i",
"+",
"3",
"]",
"\n",
"r",
":=",
"d",
"[",
"0",
"]",
"\n",
"g",
":=",
"d",
"[",
"1",
"]",
"\n",
"b",
":=",
"d",
"[",
"2",
"]",
"\n",
"f",
":=",
"0.299",
"*",
"float64",
"(",
"r",
")",
"+",
"0.587",
"*",
"float64",
"(",
"g",
")",
"+",
"0.114",
"*",
"float64",
"(",
"b",
")",
"\n",
"y",
":=",
"uint8",
"(",
"f",
"+",
"0.5",
")",
"\n",
"d",
"[",
"0",
"]",
"=",
"y",
"\n",
"d",
"[",
"1",
"]",
"=",
"y",
"\n",
"d",
"[",
"2",
"]",
"=",
"y",
"\n",
"i",
"+=",
"4",
"\n",
"}",
"\n",
"}",
"\n",
"}",
")",
"\n",
"return",
"dst",
"\n",
"}"
] | // Grayscale produces a grayscale version of the image. | [
"Grayscale",
"produces",
"a",
"grayscale",
"version",
"of",
"the",
"image",
"."
] | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/adjust.go#L10-L32 | train |
disintegration/imaging | io.go | Decode | func Decode(r io.Reader, opts ...DecodeOption) (image.Image, error) {
cfg := defaultDecodeConfig
for _, option := range opts {
option(&cfg)
}
if !cfg.autoOrientation {
img, _, err := image.Decode(r)
return img, err
}
var orient orientation
pr, pw := io.Pipe()
r = io.TeeReader(r, pw)
done := make(chan struct{})
go func() {
defer close(done)
orient = readOrientation(pr)
io.Copy(ioutil.Discard, pr)
}()
img, _, err := image.Decode(r)
pw.Close()
<-done
if err != nil {
return nil, err
}
return fixOrientation(img, orient), nil
} | go | func Decode(r io.Reader, opts ...DecodeOption) (image.Image, error) {
cfg := defaultDecodeConfig
for _, option := range opts {
option(&cfg)
}
if !cfg.autoOrientation {
img, _, err := image.Decode(r)
return img, err
}
var orient orientation
pr, pw := io.Pipe()
r = io.TeeReader(r, pw)
done := make(chan struct{})
go func() {
defer close(done)
orient = readOrientation(pr)
io.Copy(ioutil.Discard, pr)
}()
img, _, err := image.Decode(r)
pw.Close()
<-done
if err != nil {
return nil, err
}
return fixOrientation(img, orient), nil
} | [
"func",
"Decode",
"(",
"r",
"io",
".",
"Reader",
",",
"opts",
"...",
"DecodeOption",
")",
"(",
"image",
".",
"Image",
",",
"error",
")",
"{",
"cfg",
":=",
"defaultDecodeConfig",
"\n",
"for",
"_",
",",
"option",
":=",
"range",
"opts",
"{",
"option",
"(",
"&",
"cfg",
")",
"\n",
"}",
"\n",
"if",
"!",
"cfg",
".",
"autoOrientation",
"{",
"img",
",",
"_",
",",
"err",
":=",
"image",
".",
"Decode",
"(",
"r",
")",
"\n",
"return",
"img",
",",
"err",
"\n",
"}",
"\n",
"var",
"orient",
"orientation",
"\n",
"pr",
",",
"pw",
":=",
"io",
".",
"Pipe",
"(",
")",
"\n",
"r",
"=",
"io",
".",
"TeeReader",
"(",
"r",
",",
"pw",
")",
"\n",
"done",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"defer",
"close",
"(",
"done",
")",
"\n",
"orient",
"=",
"readOrientation",
"(",
"pr",
")",
"\n",
"io",
".",
"Copy",
"(",
"ioutil",
".",
"Discard",
",",
"pr",
")",
"\n",
"}",
"(",
")",
"\n",
"img",
",",
"_",
",",
"err",
":=",
"image",
".",
"Decode",
"(",
"r",
")",
"\n",
"pw",
".",
"Close",
"(",
")",
"\n",
"<-",
"done",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"fixOrientation",
"(",
"img",
",",
"orient",
")",
",",
"nil",
"\n",
"}"
] | // Decode reads an image from r. | [
"Decode",
"reads",
"an",
"image",
"from",
"r",
"."
] | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/io.go#L54-L83 | train |
disintegration/imaging | io.go | GIFQuantizer | func GIFQuantizer(quantizer draw.Quantizer) EncodeOption {
return func(c *encodeConfig) {
c.gifQuantizer = quantizer
}
} | go | func GIFQuantizer(quantizer draw.Quantizer) EncodeOption {
return func(c *encodeConfig) {
c.gifQuantizer = quantizer
}
} | [
"func",
"GIFQuantizer",
"(",
"quantizer",
"draw",
".",
"Quantizer",
")",
"EncodeOption",
"{",
"return",
"func",
"(",
"c",
"*",
"encodeConfig",
")",
"{",
"c",
".",
"gifQuantizer",
"=",
"quantizer",
"\n",
"}",
"\n",
"}"
] | // GIFQuantizer returns an EncodeOption that sets the quantizer that is used to produce
// a palette of the GIF-encoded image. | [
"GIFQuantizer",
"returns",
"an",
"EncodeOption",
"that",
"sets",
"the",
"quantizer",
"that",
"is",
"used",
"to",
"produce",
"a",
"palette",
"of",
"the",
"GIF",
"-",
"encoded",
"image",
"."
] | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/io.go#L194-L198 | train |
disintegration/imaging | io.go | GIFDrawer | func GIFDrawer(drawer draw.Drawer) EncodeOption {
return func(c *encodeConfig) {
c.gifDrawer = drawer
}
} | go | func GIFDrawer(drawer draw.Drawer) EncodeOption {
return func(c *encodeConfig) {
c.gifDrawer = drawer
}
} | [
"func",
"GIFDrawer",
"(",
"drawer",
"draw",
".",
"Drawer",
")",
"EncodeOption",
"{",
"return",
"func",
"(",
"c",
"*",
"encodeConfig",
")",
"{",
"c",
".",
"gifDrawer",
"=",
"drawer",
"\n",
"}",
"\n",
"}"
] | // GIFDrawer returns an EncodeOption that sets the drawer that is used to convert
// the source image to the desired palette of the GIF-encoded image. | [
"GIFDrawer",
"returns",
"an",
"EncodeOption",
"that",
"sets",
"the",
"drawer",
"that",
"is",
"used",
"to",
"convert",
"the",
"source",
"image",
"to",
"the",
"desired",
"palette",
"of",
"the",
"GIF",
"-",
"encoded",
"image",
"."
] | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/io.go#L202-L206 | train |
disintegration/imaging | io.go | PNGCompressionLevel | func PNGCompressionLevel(level png.CompressionLevel) EncodeOption {
return func(c *encodeConfig) {
c.pngCompressionLevel = level
}
} | go | func PNGCompressionLevel(level png.CompressionLevel) EncodeOption {
return func(c *encodeConfig) {
c.pngCompressionLevel = level
}
} | [
"func",
"PNGCompressionLevel",
"(",
"level",
"png",
".",
"CompressionLevel",
")",
"EncodeOption",
"{",
"return",
"func",
"(",
"c",
"*",
"encodeConfig",
")",
"{",
"c",
".",
"pngCompressionLevel",
"=",
"level",
"\n",
"}",
"\n",
"}"
] | // PNGCompressionLevel returns an EncodeOption that sets the compression level
// of the PNG-encoded image. Default is png.DefaultCompression. | [
"PNGCompressionLevel",
"returns",
"an",
"EncodeOption",
"that",
"sets",
"the",
"compression",
"level",
"of",
"the",
"PNG",
"-",
"encoded",
"image",
".",
"Default",
"is",
"png",
".",
"DefaultCompression",
"."
] | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/io.go#L210-L214 | train |
disintegration/imaging | io.go | fixOrientation | func fixOrientation(img image.Image, o orientation) image.Image {
switch o {
case orientationNormal:
case orientationFlipH:
img = FlipH(img)
case orientationFlipV:
img = FlipV(img)
case orientationRotate90:
img = Rotate90(img)
case orientationRotate180:
img = Rotate180(img)
case orientationRotate270:
img = Rotate270(img)
case orientationTranspose:
img = Transpose(img)
case orientationTransverse:
img = Transverse(img)
}
return img
} | go | func fixOrientation(img image.Image, o orientation) image.Image {
switch o {
case orientationNormal:
case orientationFlipH:
img = FlipH(img)
case orientationFlipV:
img = FlipV(img)
case orientationRotate90:
img = Rotate90(img)
case orientationRotate180:
img = Rotate180(img)
case orientationRotate270:
img = Rotate270(img)
case orientationTranspose:
img = Transpose(img)
case orientationTransverse:
img = Transverse(img)
}
return img
} | [
"func",
"fixOrientation",
"(",
"img",
"image",
".",
"Image",
",",
"o",
"orientation",
")",
"image",
".",
"Image",
"{",
"switch",
"o",
"{",
"case",
"orientationNormal",
":",
"case",
"orientationFlipH",
":",
"img",
"=",
"FlipH",
"(",
"img",
")",
"\n",
"case",
"orientationFlipV",
":",
"img",
"=",
"FlipV",
"(",
"img",
")",
"\n",
"case",
"orientationRotate90",
":",
"img",
"=",
"Rotate90",
"(",
"img",
")",
"\n",
"case",
"orientationRotate180",
":",
"img",
"=",
"Rotate180",
"(",
"img",
")",
"\n",
"case",
"orientationRotate270",
":",
"img",
"=",
"Rotate270",
"(",
"img",
")",
"\n",
"case",
"orientationTranspose",
":",
"img",
"=",
"Transpose",
"(",
"img",
")",
"\n",
"case",
"orientationTransverse",
":",
"img",
"=",
"Transverse",
"(",
"img",
")",
"\n",
"}",
"\n",
"return",
"img",
"\n",
"}"
] | // fixOrientation applies a transform to img corresponding to the given orientation flag. | [
"fixOrientation",
"applies",
"a",
"transform",
"to",
"img",
"corresponding",
"to",
"the",
"given",
"orientation",
"flag",
"."
] | 061e8a750a4db9667cdf9e2af7f4029ba506cb3b | https://github.com/disintegration/imaging/blob/061e8a750a4db9667cdf9e2af7f4029ba506cb3b/io.go#L425-L444 | train |
rqlite/rqlite | tcp/transport.go | NewTLSTransport | func NewTLSTransport(certFile, keyPath string, skipVerify bool) *Transport {
return &Transport{
certFile: certFile,
certKey: keyPath,
remoteEncrypted: true,
skipVerify: skipVerify,
}
} | go | func NewTLSTransport(certFile, keyPath string, skipVerify bool) *Transport {
return &Transport{
certFile: certFile,
certKey: keyPath,
remoteEncrypted: true,
skipVerify: skipVerify,
}
} | [
"func",
"NewTLSTransport",
"(",
"certFile",
",",
"keyPath",
"string",
",",
"skipVerify",
"bool",
")",
"*",
"Transport",
"{",
"return",
"&",
"Transport",
"{",
"certFile",
":",
"certFile",
",",
"certKey",
":",
"keyPath",
",",
"remoteEncrypted",
":",
"true",
",",
"skipVerify",
":",
"skipVerify",
",",
"}",
"\n",
"}"
] | // NewTLSTransport returns an initialized TLS-ecrypted Transport. | [
"NewTLSTransport",
"returns",
"an",
"initialized",
"TLS",
"-",
"ecrypted",
"Transport",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/tcp/transport.go#L26-L33 | train |
rqlite/rqlite | tcp/transport.go | Open | func (t *Transport) Open(addr string) error {
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
if t.certFile != "" {
config, err := createTLSConfig(t.certFile, t.certKey)
if err != nil {
return err
}
ln = tls.NewListener(ln, config)
}
t.ln = ln
return nil
} | go | func (t *Transport) Open(addr string) error {
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
if t.certFile != "" {
config, err := createTLSConfig(t.certFile, t.certKey)
if err != nil {
return err
}
ln = tls.NewListener(ln, config)
}
t.ln = ln
return nil
} | [
"func",
"(",
"t",
"*",
"Transport",
")",
"Open",
"(",
"addr",
"string",
")",
"error",
"{",
"ln",
",",
"err",
":=",
"net",
".",
"Listen",
"(",
"\"tcp\"",
",",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"t",
".",
"certFile",
"!=",
"\"\"",
"{",
"config",
",",
"err",
":=",
"createTLSConfig",
"(",
"t",
".",
"certFile",
",",
"t",
".",
"certKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"ln",
"=",
"tls",
".",
"NewListener",
"(",
"ln",
",",
"config",
")",
"\n",
"}",
"\n",
"t",
".",
"ln",
"=",
"ln",
"\n",
"return",
"nil",
"\n",
"}"
] | // Open opens the transport, binding to the supplied address. | [
"Open",
"opens",
"the",
"transport",
"binding",
"to",
"the",
"supplied",
"address",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/tcp/transport.go#L36-L51 | train |
rqlite/rqlite | tcp/transport.go | Dial | func (t *Transport) Dial(addr string, timeout time.Duration) (net.Conn, error) {
dialer := &net.Dialer{Timeout: timeout}
var err error
var conn net.Conn
if t.remoteEncrypted {
conf := &tls.Config{
InsecureSkipVerify: t.skipVerify,
}
fmt.Println("doing a TLS dial")
conn, err = tls.DialWithDialer(dialer, "tcp", addr, conf)
} else {
conn, err = dialer.Dial("tcp", addr)
}
return conn, err
} | go | func (t *Transport) Dial(addr string, timeout time.Duration) (net.Conn, error) {
dialer := &net.Dialer{Timeout: timeout}
var err error
var conn net.Conn
if t.remoteEncrypted {
conf := &tls.Config{
InsecureSkipVerify: t.skipVerify,
}
fmt.Println("doing a TLS dial")
conn, err = tls.DialWithDialer(dialer, "tcp", addr, conf)
} else {
conn, err = dialer.Dial("tcp", addr)
}
return conn, err
} | [
"func",
"(",
"t",
"*",
"Transport",
")",
"Dial",
"(",
"addr",
"string",
",",
"timeout",
"time",
".",
"Duration",
")",
"(",
"net",
".",
"Conn",
",",
"error",
")",
"{",
"dialer",
":=",
"&",
"net",
".",
"Dialer",
"{",
"Timeout",
":",
"timeout",
"}",
"\n",
"var",
"err",
"error",
"\n",
"var",
"conn",
"net",
".",
"Conn",
"\n",
"if",
"t",
".",
"remoteEncrypted",
"{",
"conf",
":=",
"&",
"tls",
".",
"Config",
"{",
"InsecureSkipVerify",
":",
"t",
".",
"skipVerify",
",",
"}",
"\n",
"fmt",
".",
"Println",
"(",
"\"doing a TLS dial\"",
")",
"\n",
"conn",
",",
"err",
"=",
"tls",
".",
"DialWithDialer",
"(",
"dialer",
",",
"\"tcp\"",
",",
"addr",
",",
"conf",
")",
"\n",
"}",
"else",
"{",
"conn",
",",
"err",
"=",
"dialer",
".",
"Dial",
"(",
"\"tcp\"",
",",
"addr",
")",
"\n",
"}",
"\n",
"return",
"conn",
",",
"err",
"\n",
"}"
] | // Dial opens a network connection. | [
"Dial",
"opens",
"a",
"network",
"connection",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/tcp/transport.go#L54-L70 | train |
rqlite/rqlite | cmd/rqbench/http.go | Prepare | func (h *HTTPTester) Prepare(stmt string, bSz int, tx bool) error {
s := make([]string, bSz)
for i := 0; i < len(s); i++ {
s[i] = stmt
}
b, err := json.Marshal(s)
if err != nil {
return err
}
h.br = bytes.NewReader(b)
if tx {
h.url = h.url + "?transaction"
}
return nil
} | go | func (h *HTTPTester) Prepare(stmt string, bSz int, tx bool) error {
s := make([]string, bSz)
for i := 0; i < len(s); i++ {
s[i] = stmt
}
b, err := json.Marshal(s)
if err != nil {
return err
}
h.br = bytes.NewReader(b)
if tx {
h.url = h.url + "?transaction"
}
return nil
} | [
"func",
"(",
"h",
"*",
"HTTPTester",
")",
"Prepare",
"(",
"stmt",
"string",
",",
"bSz",
"int",
",",
"tx",
"bool",
")",
"error",
"{",
"s",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"bSz",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"s",
")",
";",
"i",
"++",
"{",
"s",
"[",
"i",
"]",
"=",
"stmt",
"\n",
"}",
"\n",
"b",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"s",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"h",
".",
"br",
"=",
"bytes",
".",
"NewReader",
"(",
"b",
")",
"\n",
"if",
"tx",
"{",
"h",
".",
"url",
"=",
"h",
".",
"url",
"+",
"\"?transaction\"",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Prepare prepares the tester for execution. | [
"Prepare",
"prepares",
"the",
"tester",
"for",
"execution",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/cmd/rqbench/http.go#L28-L45 | train |
rqlite/rqlite | cmd/rqbench/http.go | Once | func (h *HTTPTester) Once() (time.Duration, error) {
h.br.Seek(0, io.SeekStart)
start := time.Now()
resp, err := h.client.Post(h.url, "application/json", h.br)
if err != nil {
return 0, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return 0, fmt.Errorf("received %s", resp.Status)
}
dur := time.Since(start)
return dur, nil
} | go | func (h *HTTPTester) Once() (time.Duration, error) {
h.br.Seek(0, io.SeekStart)
start := time.Now()
resp, err := h.client.Post(h.url, "application/json", h.br)
if err != nil {
return 0, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return 0, fmt.Errorf("received %s", resp.Status)
}
dur := time.Since(start)
return dur, nil
} | [
"func",
"(",
"h",
"*",
"HTTPTester",
")",
"Once",
"(",
")",
"(",
"time",
".",
"Duration",
",",
"error",
")",
"{",
"h",
".",
"br",
".",
"Seek",
"(",
"0",
",",
"io",
".",
"SeekStart",
")",
"\n",
"start",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"resp",
",",
"err",
":=",
"h",
".",
"client",
".",
"Post",
"(",
"h",
".",
"url",
",",
"\"application/json\"",
",",
"h",
".",
"br",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"if",
"resp",
".",
"StatusCode",
"!=",
"http",
".",
"StatusOK",
"{",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"received %s\"",
",",
"resp",
".",
"Status",
")",
"\n",
"}",
"\n",
"dur",
":=",
"time",
".",
"Since",
"(",
"start",
")",
"\n",
"return",
"dur",
",",
"nil",
"\n",
"}"
] | // Once executes a single test request. | [
"Once",
"executes",
"a",
"single",
"test",
"request",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/cmd/rqbench/http.go#L48-L64 | train |
rqlite/rqlite | store/peers.go | NumPeers | func NumPeers(raftDir string) (int, error) {
// Read the file
buf, err := ioutil.ReadFile(filepath.Join(raftDir, jsonPeerPath))
if err != nil && !os.IsNotExist(err) {
return 0, err
}
// Check for no peers
if len(buf) == 0 {
return 0, nil
}
// Decode the peers
var peerSet []string
dec := json.NewDecoder(bytes.NewReader(buf))
if err := dec.Decode(&peerSet); err != nil {
return 0, err
}
return len(peerSet), nil
} | go | func NumPeers(raftDir string) (int, error) {
// Read the file
buf, err := ioutil.ReadFile(filepath.Join(raftDir, jsonPeerPath))
if err != nil && !os.IsNotExist(err) {
return 0, err
}
// Check for no peers
if len(buf) == 0 {
return 0, nil
}
// Decode the peers
var peerSet []string
dec := json.NewDecoder(bytes.NewReader(buf))
if err := dec.Decode(&peerSet); err != nil {
return 0, err
}
return len(peerSet), nil
} | [
"func",
"NumPeers",
"(",
"raftDir",
"string",
")",
"(",
"int",
",",
"error",
")",
"{",
"buf",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"filepath",
".",
"Join",
"(",
"raftDir",
",",
"jsonPeerPath",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"!",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"buf",
")",
"==",
"0",
"{",
"return",
"0",
",",
"nil",
"\n",
"}",
"\n",
"var",
"peerSet",
"[",
"]",
"string",
"\n",
"dec",
":=",
"json",
".",
"NewDecoder",
"(",
"bytes",
".",
"NewReader",
"(",
"buf",
")",
")",
"\n",
"if",
"err",
":=",
"dec",
".",
"Decode",
"(",
"&",
"peerSet",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"return",
"len",
"(",
"peerSet",
")",
",",
"nil",
"\n",
"}"
] | // NumPeers returns the number of peers indicated by the config files
// within raftDir.
//
// This code makes assumptions about how the Raft module works. | [
"NumPeers",
"returns",
"the",
"number",
"of",
"peers",
"indicated",
"by",
"the",
"config",
"files",
"within",
"raftDir",
".",
"This",
"code",
"makes",
"assumptions",
"about",
"how",
"the",
"Raft",
"module",
"works",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/peers.go#L19-L39 | train |
rqlite/rqlite | store/peers.go | JoinAllowed | func JoinAllowed(raftDir string) (bool, error) {
n, err := NumPeers(raftDir)
if err != nil {
return false, err
}
return n <= 1, nil
} | go | func JoinAllowed(raftDir string) (bool, error) {
n, err := NumPeers(raftDir)
if err != nil {
return false, err
}
return n <= 1, nil
} | [
"func",
"JoinAllowed",
"(",
"raftDir",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"n",
",",
"err",
":=",
"NumPeers",
"(",
"raftDir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"return",
"n",
"<=",
"1",
",",
"nil",
"\n",
"}"
] | // JoinAllowed returns whether the config files within raftDir indicate
// that the node can join a cluster. | [
"JoinAllowed",
"returns",
"whether",
"the",
"config",
"files",
"within",
"raftDir",
"indicate",
"that",
"the",
"node",
"can",
"join",
"a",
"cluster",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/peers.go#L43-L49 | train |
rqlite/rqlite | store/store.go | New | func New(ln Listener, c *StoreConfig) *Store {
logger := c.Logger
if logger == nil {
logger = log.New(os.Stderr, "[store] ", log.LstdFlags)
}
return &Store{
ln: ln,
raftDir: c.Dir,
raftID: c.ID,
dbConf: c.DBConf,
dbPath: filepath.Join(c.Dir, sqliteFile),
randSrc: rand.New(rand.NewSource(time.Now().UnixNano())),
conns: make(map[uint64]*Connection),
done: make(chan struct{}, 1),
meta: make(map[string]map[string]string),
logger: logger,
ApplyTimeout: applyTimeout,
connPollPeriod: connectionPollPeriod,
}
} | go | func New(ln Listener, c *StoreConfig) *Store {
logger := c.Logger
if logger == nil {
logger = log.New(os.Stderr, "[store] ", log.LstdFlags)
}
return &Store{
ln: ln,
raftDir: c.Dir,
raftID: c.ID,
dbConf: c.DBConf,
dbPath: filepath.Join(c.Dir, sqliteFile),
randSrc: rand.New(rand.NewSource(time.Now().UnixNano())),
conns: make(map[uint64]*Connection),
done: make(chan struct{}, 1),
meta: make(map[string]map[string]string),
logger: logger,
ApplyTimeout: applyTimeout,
connPollPeriod: connectionPollPeriod,
}
} | [
"func",
"New",
"(",
"ln",
"Listener",
",",
"c",
"*",
"StoreConfig",
")",
"*",
"Store",
"{",
"logger",
":=",
"c",
".",
"Logger",
"\n",
"if",
"logger",
"==",
"nil",
"{",
"logger",
"=",
"log",
".",
"New",
"(",
"os",
".",
"Stderr",
",",
"\"[store] \"",
",",
"log",
".",
"LstdFlags",
")",
"\n",
"}",
"\n",
"return",
"&",
"Store",
"{",
"ln",
":",
"ln",
",",
"raftDir",
":",
"c",
".",
"Dir",
",",
"raftID",
":",
"c",
".",
"ID",
",",
"dbConf",
":",
"c",
".",
"DBConf",
",",
"dbPath",
":",
"filepath",
".",
"Join",
"(",
"c",
".",
"Dir",
",",
"sqliteFile",
")",
",",
"randSrc",
":",
"rand",
".",
"New",
"(",
"rand",
".",
"NewSource",
"(",
"time",
".",
"Now",
"(",
")",
".",
"UnixNano",
"(",
")",
")",
")",
",",
"conns",
":",
"make",
"(",
"map",
"[",
"uint64",
"]",
"*",
"Connection",
")",
",",
"done",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"1",
")",
",",
"meta",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"map",
"[",
"string",
"]",
"string",
")",
",",
"logger",
":",
"logger",
",",
"ApplyTimeout",
":",
"applyTimeout",
",",
"connPollPeriod",
":",
"connectionPollPeriod",
",",
"}",
"\n",
"}"
] | // New returns a new Store. | [
"New",
"returns",
"a",
"new",
"Store",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L220-L240 | train |
rqlite/rqlite | store/store.go | Open | func (s *Store) Open(enableSingle bool) error {
s.closedMu.Lock()
defer s.closedMu.Unlock()
if s.closed {
return ErrStoreInvalidState
}
s.logger.Printf("opening store with node ID %s", s.raftID)
s.logger.Printf("ensuring directory at %s exists", s.raftDir)
if err := os.MkdirAll(s.raftDir, 0755); err != nil {
return err
}
// Create underlying database.
if err := s.createDatabase(); err != nil {
return err
}
// Get utility connection to database.
conn, err := s.db.Connect()
if err != nil {
return err
}
s.dbConn = conn
s.conns[defaultConnID] = NewConnection(s.dbConn, s, defaultConnID, 0, 0)
// Is this a brand new node?
newNode := !pathExists(filepath.Join(s.raftDir, "raft.db"))
// Create Raft-compatible network layer.
s.raftTn = raft.NewNetworkTransport(NewTransport(s.ln),
connectionPoolCount, connectionTimeout, nil)
// Get the Raft configuration for this store.
config := s.raftConfig()
config.LocalID = raft.ServerID(s.raftID)
config.Logger = log.New(os.Stderr, "[raft] ", log.LstdFlags)
// Create the snapshot store. This allows Raft to truncate the log.
snapshots, err := raft.NewFileSnapshotStore(s.raftDir, retainSnapshotCount, os.Stderr)
if err != nil {
return fmt.Errorf("file snapshot store: %s", err)
}
// Create the log store and stable store.
s.boltStore, err = raftboltdb.NewBoltStore(filepath.Join(s.raftDir, "raft.db"))
if err != nil {
return fmt.Errorf("new bolt store: %s", err)
}
s.raftStable = s.boltStore
s.raftLog, err = raft.NewLogCache(raftLogCacheSize, s.boltStore)
if err != nil {
return fmt.Errorf("new cached store: %s", err)
}
// Instantiate the Raft system.
ra, err := raft.NewRaft(config, s, s.raftLog, s.raftStable, snapshots, s.raftTn)
if err != nil {
return fmt.Errorf("new raft: %s", err)
}
if enableSingle && newNode {
s.logger.Printf("bootstrap needed")
configuration := raft.Configuration{
Servers: []raft.Server{
{
ID: config.LocalID,
Address: s.raftTn.LocalAddr(),
},
},
}
ra.BootstrapCluster(configuration)
} else {
s.logger.Printf("no bootstrap needed")
}
s.raft = ra
// Start connection monitoring
s.checkConnections()
return nil
} | go | func (s *Store) Open(enableSingle bool) error {
s.closedMu.Lock()
defer s.closedMu.Unlock()
if s.closed {
return ErrStoreInvalidState
}
s.logger.Printf("opening store with node ID %s", s.raftID)
s.logger.Printf("ensuring directory at %s exists", s.raftDir)
if err := os.MkdirAll(s.raftDir, 0755); err != nil {
return err
}
// Create underlying database.
if err := s.createDatabase(); err != nil {
return err
}
// Get utility connection to database.
conn, err := s.db.Connect()
if err != nil {
return err
}
s.dbConn = conn
s.conns[defaultConnID] = NewConnection(s.dbConn, s, defaultConnID, 0, 0)
// Is this a brand new node?
newNode := !pathExists(filepath.Join(s.raftDir, "raft.db"))
// Create Raft-compatible network layer.
s.raftTn = raft.NewNetworkTransport(NewTransport(s.ln),
connectionPoolCount, connectionTimeout, nil)
// Get the Raft configuration for this store.
config := s.raftConfig()
config.LocalID = raft.ServerID(s.raftID)
config.Logger = log.New(os.Stderr, "[raft] ", log.LstdFlags)
// Create the snapshot store. This allows Raft to truncate the log.
snapshots, err := raft.NewFileSnapshotStore(s.raftDir, retainSnapshotCount, os.Stderr)
if err != nil {
return fmt.Errorf("file snapshot store: %s", err)
}
// Create the log store and stable store.
s.boltStore, err = raftboltdb.NewBoltStore(filepath.Join(s.raftDir, "raft.db"))
if err != nil {
return fmt.Errorf("new bolt store: %s", err)
}
s.raftStable = s.boltStore
s.raftLog, err = raft.NewLogCache(raftLogCacheSize, s.boltStore)
if err != nil {
return fmt.Errorf("new cached store: %s", err)
}
// Instantiate the Raft system.
ra, err := raft.NewRaft(config, s, s.raftLog, s.raftStable, snapshots, s.raftTn)
if err != nil {
return fmt.Errorf("new raft: %s", err)
}
if enableSingle && newNode {
s.logger.Printf("bootstrap needed")
configuration := raft.Configuration{
Servers: []raft.Server{
{
ID: config.LocalID,
Address: s.raftTn.LocalAddr(),
},
},
}
ra.BootstrapCluster(configuration)
} else {
s.logger.Printf("no bootstrap needed")
}
s.raft = ra
// Start connection monitoring
s.checkConnections()
return nil
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"Open",
"(",
"enableSingle",
"bool",
")",
"error",
"{",
"s",
".",
"closedMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"closedMu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"s",
".",
"closed",
"{",
"return",
"ErrStoreInvalidState",
"\n",
"}",
"\n",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"opening store with node ID %s\"",
",",
"s",
".",
"raftID",
")",
"\n",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"ensuring directory at %s exists\"",
",",
"s",
".",
"raftDir",
")",
"\n",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"s",
".",
"raftDir",
",",
"0755",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"s",
".",
"createDatabase",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"conn",
",",
"err",
":=",
"s",
".",
"db",
".",
"Connect",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"s",
".",
"dbConn",
"=",
"conn",
"\n",
"s",
".",
"conns",
"[",
"defaultConnID",
"]",
"=",
"NewConnection",
"(",
"s",
".",
"dbConn",
",",
"s",
",",
"defaultConnID",
",",
"0",
",",
"0",
")",
"\n",
"newNode",
":=",
"!",
"pathExists",
"(",
"filepath",
".",
"Join",
"(",
"s",
".",
"raftDir",
",",
"\"raft.db\"",
")",
")",
"\n",
"s",
".",
"raftTn",
"=",
"raft",
".",
"NewNetworkTransport",
"(",
"NewTransport",
"(",
"s",
".",
"ln",
")",
",",
"connectionPoolCount",
",",
"connectionTimeout",
",",
"nil",
")",
"\n",
"config",
":=",
"s",
".",
"raftConfig",
"(",
")",
"\n",
"config",
".",
"LocalID",
"=",
"raft",
".",
"ServerID",
"(",
"s",
".",
"raftID",
")",
"\n",
"config",
".",
"Logger",
"=",
"log",
".",
"New",
"(",
"os",
".",
"Stderr",
",",
"\"[raft] \"",
",",
"log",
".",
"LstdFlags",
")",
"\n",
"snapshots",
",",
"err",
":=",
"raft",
".",
"NewFileSnapshotStore",
"(",
"s",
".",
"raftDir",
",",
"retainSnapshotCount",
",",
"os",
".",
"Stderr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"file snapshot store: %s\"",
",",
"err",
")",
"\n",
"}",
"\n",
"s",
".",
"boltStore",
",",
"err",
"=",
"raftboltdb",
".",
"NewBoltStore",
"(",
"filepath",
".",
"Join",
"(",
"s",
".",
"raftDir",
",",
"\"raft.db\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"new bolt store: %s\"",
",",
"err",
")",
"\n",
"}",
"\n",
"s",
".",
"raftStable",
"=",
"s",
".",
"boltStore",
"\n",
"s",
".",
"raftLog",
",",
"err",
"=",
"raft",
".",
"NewLogCache",
"(",
"raftLogCacheSize",
",",
"s",
".",
"boltStore",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"new cached store: %s\"",
",",
"err",
")",
"\n",
"}",
"\n",
"ra",
",",
"err",
":=",
"raft",
".",
"NewRaft",
"(",
"config",
",",
"s",
",",
"s",
".",
"raftLog",
",",
"s",
".",
"raftStable",
",",
"snapshots",
",",
"s",
".",
"raftTn",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"new raft: %s\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"enableSingle",
"&&",
"newNode",
"{",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"bootstrap needed\"",
")",
"\n",
"configuration",
":=",
"raft",
".",
"Configuration",
"{",
"Servers",
":",
"[",
"]",
"raft",
".",
"Server",
"{",
"{",
"ID",
":",
"config",
".",
"LocalID",
",",
"Address",
":",
"s",
".",
"raftTn",
".",
"LocalAddr",
"(",
")",
",",
"}",
",",
"}",
",",
"}",
"\n",
"ra",
".",
"BootstrapCluster",
"(",
"configuration",
")",
"\n",
"}",
"else",
"{",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"no bootstrap needed\"",
")",
"\n",
"}",
"\n",
"s",
".",
"raft",
"=",
"ra",
"\n",
"s",
".",
"checkConnections",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Open opens the store. If enableSingle is set, and there are no existing peers,
// then this node becomes the first node, and therefore leader, of the cluster. | [
"Open",
"opens",
"the",
"store",
".",
"If",
"enableSingle",
"is",
"set",
"and",
"there",
"are",
"no",
"existing",
"peers",
"then",
"this",
"node",
"becomes",
"the",
"first",
"node",
"and",
"therefore",
"leader",
"of",
"the",
"cluster",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L244-L327 | train |
rqlite/rqlite | store/store.go | Connect | func (s *Store) Connect(opt *ConnectionOptions) (*Connection, error) {
// Randomly-selected connection ID must be part of command so
// that all nodes use the same value as connection ID.
connID := func() uint64 {
s.connsMu.Lock()
defer s.connsMu.Unlock()
for {
// Make sure we get an unused ID.
id := s.randSrc.Uint64()
if _, ok := s.conns[id]; !ok {
s.conns[id] = nil
return id
}
}
}()
var it time.Duration
var tt time.Duration
if opt != nil {
it = opt.IdleTimeout
tt = opt.TxTimeout
}
d := &connectionSub{connID, it, tt}
cmd, err := newCommand(connect, d)
if err != nil {
return nil, err
}
b, err := json.Marshal(cmd)
if err != nil {
return nil, err
}
f := s.raft.Apply(b, s.ApplyTimeout)
if e := f.(raft.Future); e.Error() != nil {
if e.Error() == raft.ErrNotLeader {
return nil, ErrNotLeader
}
return nil, e.Error()
}
s.connsMu.RLock()
defer s.connsMu.RUnlock()
stats.Add(numConnects, 1)
return s.conns[connID], nil
} | go | func (s *Store) Connect(opt *ConnectionOptions) (*Connection, error) {
// Randomly-selected connection ID must be part of command so
// that all nodes use the same value as connection ID.
connID := func() uint64 {
s.connsMu.Lock()
defer s.connsMu.Unlock()
for {
// Make sure we get an unused ID.
id := s.randSrc.Uint64()
if _, ok := s.conns[id]; !ok {
s.conns[id] = nil
return id
}
}
}()
var it time.Duration
var tt time.Duration
if opt != nil {
it = opt.IdleTimeout
tt = opt.TxTimeout
}
d := &connectionSub{connID, it, tt}
cmd, err := newCommand(connect, d)
if err != nil {
return nil, err
}
b, err := json.Marshal(cmd)
if err != nil {
return nil, err
}
f := s.raft.Apply(b, s.ApplyTimeout)
if e := f.(raft.Future); e.Error() != nil {
if e.Error() == raft.ErrNotLeader {
return nil, ErrNotLeader
}
return nil, e.Error()
}
s.connsMu.RLock()
defer s.connsMu.RUnlock()
stats.Add(numConnects, 1)
return s.conns[connID], nil
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"Connect",
"(",
"opt",
"*",
"ConnectionOptions",
")",
"(",
"*",
"Connection",
",",
"error",
")",
"{",
"connID",
":=",
"func",
"(",
")",
"uint64",
"{",
"s",
".",
"connsMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"connsMu",
".",
"Unlock",
"(",
")",
"\n",
"for",
"{",
"id",
":=",
"s",
".",
"randSrc",
".",
"Uint64",
"(",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"s",
".",
"conns",
"[",
"id",
"]",
";",
"!",
"ok",
"{",
"s",
".",
"conns",
"[",
"id",
"]",
"=",
"nil",
"\n",
"return",
"id",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"var",
"it",
"time",
".",
"Duration",
"\n",
"var",
"tt",
"time",
".",
"Duration",
"\n",
"if",
"opt",
"!=",
"nil",
"{",
"it",
"=",
"opt",
".",
"IdleTimeout",
"\n",
"tt",
"=",
"opt",
".",
"TxTimeout",
"\n",
"}",
"\n",
"d",
":=",
"&",
"connectionSub",
"{",
"connID",
",",
"it",
",",
"tt",
"}",
"\n",
"cmd",
",",
"err",
":=",
"newCommand",
"(",
"connect",
",",
"d",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"b",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"cmd",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"f",
":=",
"s",
".",
"raft",
".",
"Apply",
"(",
"b",
",",
"s",
".",
"ApplyTimeout",
")",
"\n",
"if",
"e",
":=",
"f",
".",
"(",
"raft",
".",
"Future",
")",
";",
"e",
".",
"Error",
"(",
")",
"!=",
"nil",
"{",
"if",
"e",
".",
"Error",
"(",
")",
"==",
"raft",
".",
"ErrNotLeader",
"{",
"return",
"nil",
",",
"ErrNotLeader",
"\n",
"}",
"\n",
"return",
"nil",
",",
"e",
".",
"Error",
"(",
")",
"\n",
"}",
"\n",
"s",
".",
"connsMu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"connsMu",
".",
"RUnlock",
"(",
")",
"\n",
"stats",
".",
"Add",
"(",
"numConnects",
",",
"1",
")",
"\n",
"return",
"s",
".",
"conns",
"[",
"connID",
"]",
",",
"nil",
"\n",
"}"
] | // Connect returns a new connection to the database. Changes made to the database
// through this connection are applied via the Raft consensus system. The Store
// must have been opened first. Must be called on the leader or an error will
// we returned.
//
// Any connection returned by this call are READ_COMMITTED isolated from all
// other connections, including the connection built-in to the Store itself. | [
"Connect",
"returns",
"a",
"new",
"connection",
"to",
"the",
"database",
".",
"Changes",
"made",
"to",
"the",
"database",
"through",
"this",
"connection",
"are",
"applied",
"via",
"the",
"Raft",
"consensus",
"system",
".",
"The",
"Store",
"must",
"have",
"been",
"opened",
"first",
".",
"Must",
"be",
"called",
"on",
"the",
"leader",
"or",
"an",
"error",
"will",
"we",
"returned",
".",
"Any",
"connection",
"returned",
"by",
"this",
"call",
"are",
"READ_COMMITTED",
"isolated",
"from",
"all",
"other",
"connections",
"including",
"the",
"connection",
"built",
"-",
"in",
"to",
"the",
"Store",
"itself",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L336-L381 | train |
rqlite/rqlite | store/store.go | Execute | func (s *Store) Execute(ex *ExecuteRequest) (*ExecuteResponse, error) {
return s.execute(nil, ex)
} | go | func (s *Store) Execute(ex *ExecuteRequest) (*ExecuteResponse, error) {
return s.execute(nil, ex)
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"Execute",
"(",
"ex",
"*",
"ExecuteRequest",
")",
"(",
"*",
"ExecuteResponse",
",",
"error",
")",
"{",
"return",
"s",
".",
"execute",
"(",
"nil",
",",
"ex",
")",
"\n",
"}"
] | // Execute executes queries that return no rows, but do modify the database.
// Changes made to the database through this call are applied via the Raft
// consensus system. The Store must have been opened first. Must be called
// on the leader or an error will we returned. The changes are made using
// the database connection built-in to the Store. | [
"Execute",
"executes",
"queries",
"that",
"return",
"no",
"rows",
"but",
"do",
"modify",
"the",
"database",
".",
"Changes",
"made",
"to",
"the",
"database",
"through",
"this",
"call",
"are",
"applied",
"via",
"the",
"Raft",
"consensus",
"system",
".",
"The",
"Store",
"must",
"have",
"been",
"opened",
"first",
".",
"Must",
"be",
"called",
"on",
"the",
"leader",
"or",
"an",
"error",
"will",
"we",
"returned",
".",
"The",
"changes",
"are",
"made",
"using",
"the",
"database",
"connection",
"built",
"-",
"in",
"to",
"the",
"Store",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L388-L390 | train |
rqlite/rqlite | store/store.go | ExecuteOrAbort | func (s *Store) ExecuteOrAbort(ex *ExecuteRequest) (resp *ExecuteResponse, retErr error) {
return s.executeOrAbort(nil, ex)
} | go | func (s *Store) ExecuteOrAbort(ex *ExecuteRequest) (resp *ExecuteResponse, retErr error) {
return s.executeOrAbort(nil, ex)
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"ExecuteOrAbort",
"(",
"ex",
"*",
"ExecuteRequest",
")",
"(",
"resp",
"*",
"ExecuteResponse",
",",
"retErr",
"error",
")",
"{",
"return",
"s",
".",
"executeOrAbort",
"(",
"nil",
",",
"ex",
")",
"\n",
"}"
] | // ExecuteOrAbort executes the requests, but aborts any active transaction
// on the underlying database in the case of any error. Any changes are made
// using the database connection built-in to the Store. | [
"ExecuteOrAbort",
"executes",
"the",
"requests",
"but",
"aborts",
"any",
"active",
"transaction",
"on",
"the",
"underlying",
"database",
"in",
"the",
"case",
"of",
"any",
"error",
".",
"Any",
"changes",
"are",
"made",
"using",
"the",
"database",
"connection",
"built",
"-",
"in",
"to",
"the",
"Store",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L395-L397 | train |
rqlite/rqlite | store/store.go | Query | func (s *Store) Query(qr *QueryRequest) (*QueryResponse, error) {
return s.query(nil, qr)
} | go | func (s *Store) Query(qr *QueryRequest) (*QueryResponse, error) {
return s.query(nil, qr)
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"Query",
"(",
"qr",
"*",
"QueryRequest",
")",
"(",
"*",
"QueryResponse",
",",
"error",
")",
"{",
"return",
"s",
".",
"query",
"(",
"nil",
",",
"qr",
")",
"\n",
"}"
] | // Query executes queries that return rows, and do not modify the database.
// The queries are made using the database connection built-in to the Store.
// Depending on the read consistency requested, it may or may not need to be
// called on the leader. | [
"Query",
"executes",
"queries",
"that",
"return",
"rows",
"and",
"do",
"not",
"modify",
"the",
"database",
".",
"The",
"queries",
"are",
"made",
"using",
"the",
"database",
"connection",
"built",
"-",
"in",
"to",
"the",
"Store",
".",
"Depending",
"on",
"the",
"read",
"consistency",
"requested",
"it",
"may",
"or",
"may",
"not",
"need",
"to",
"be",
"called",
"on",
"the",
"leader",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L403-L405 | train |
rqlite/rqlite | store/store.go | Close | func (s *Store) Close(wait bool) error {
s.closedMu.Lock()
defer s.closedMu.Unlock()
if s.closed {
return nil
}
defer func() {
s.closed = true
}()
close(s.done)
s.wg.Wait()
// XXX CLOSE OTHER CONNECTIONS
if err := s.dbConn.Close(); err != nil {
return err
}
s.dbConn = nil
s.db = nil
if s.raft != nil {
f := s.raft.Shutdown()
if wait {
if e := f.(raft.Future); e.Error() != nil {
return e.Error()
}
}
s.raft = nil
}
if s.boltStore != nil {
if err := s.boltStore.Close(); err != nil {
return err
}
s.boltStore = nil
}
s.raftLog = nil
s.raftStable = nil
return nil
} | go | func (s *Store) Close(wait bool) error {
s.closedMu.Lock()
defer s.closedMu.Unlock()
if s.closed {
return nil
}
defer func() {
s.closed = true
}()
close(s.done)
s.wg.Wait()
// XXX CLOSE OTHER CONNECTIONS
if err := s.dbConn.Close(); err != nil {
return err
}
s.dbConn = nil
s.db = nil
if s.raft != nil {
f := s.raft.Shutdown()
if wait {
if e := f.(raft.Future); e.Error() != nil {
return e.Error()
}
}
s.raft = nil
}
if s.boltStore != nil {
if err := s.boltStore.Close(); err != nil {
return err
}
s.boltStore = nil
}
s.raftLog = nil
s.raftStable = nil
return nil
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"Close",
"(",
"wait",
"bool",
")",
"error",
"{",
"s",
".",
"closedMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"closedMu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"s",
".",
"closed",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"defer",
"func",
"(",
")",
"{",
"s",
".",
"closed",
"=",
"true",
"\n",
"}",
"(",
")",
"\n",
"close",
"(",
"s",
".",
"done",
")",
"\n",
"s",
".",
"wg",
".",
"Wait",
"(",
")",
"\n",
"if",
"err",
":=",
"s",
".",
"dbConn",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"s",
".",
"dbConn",
"=",
"nil",
"\n",
"s",
".",
"db",
"=",
"nil",
"\n",
"if",
"s",
".",
"raft",
"!=",
"nil",
"{",
"f",
":=",
"s",
".",
"raft",
".",
"Shutdown",
"(",
")",
"\n",
"if",
"wait",
"{",
"if",
"e",
":=",
"f",
".",
"(",
"raft",
".",
"Future",
")",
";",
"e",
".",
"Error",
"(",
")",
"!=",
"nil",
"{",
"return",
"e",
".",
"Error",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"s",
".",
"raft",
"=",
"nil",
"\n",
"}",
"\n",
"if",
"s",
".",
"boltStore",
"!=",
"nil",
"{",
"if",
"err",
":=",
"s",
".",
"boltStore",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"s",
".",
"boltStore",
"=",
"nil",
"\n",
"}",
"\n",
"s",
".",
"raftLog",
"=",
"nil",
"\n",
"s",
".",
"raftStable",
"=",
"nil",
"\n",
"return",
"nil",
"\n",
"}"
] | // Close closes the store. If wait is true, waits for a graceful shutdown.
// Once closed, a Store may not be re-opened. | [
"Close",
"closes",
"the",
"store",
".",
"If",
"wait",
"is",
"true",
"waits",
"for",
"a",
"graceful",
"shutdown",
".",
"Once",
"closed",
"a",
"Store",
"may",
"not",
"be",
"re",
"-",
"opened",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L409-L448 | train |
rqlite/rqlite | store/store.go | WaitForApplied | func (s *Store) WaitForApplied(timeout time.Duration) error {
if timeout == 0 {
return nil
}
s.logger.Printf("waiting for up to %s for application of initial logs", timeout)
if err := s.WaitForAppliedIndex(s.raft.LastIndex(), timeout); err != nil {
return ErrOpenTimeout
}
return nil
} | go | func (s *Store) WaitForApplied(timeout time.Duration) error {
if timeout == 0 {
return nil
}
s.logger.Printf("waiting for up to %s for application of initial logs", timeout)
if err := s.WaitForAppliedIndex(s.raft.LastIndex(), timeout); err != nil {
return ErrOpenTimeout
}
return nil
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"WaitForApplied",
"(",
"timeout",
"time",
".",
"Duration",
")",
"error",
"{",
"if",
"timeout",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"waiting for up to %s for application of initial logs\"",
",",
"timeout",
")",
"\n",
"if",
"err",
":=",
"s",
".",
"WaitForAppliedIndex",
"(",
"s",
".",
"raft",
".",
"LastIndex",
"(",
")",
",",
"timeout",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"ErrOpenTimeout",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // WaitForApplied waits for all Raft log entries to to be applied to the
// underlying database. | [
"WaitForApplied",
"waits",
"for",
"all",
"Raft",
"log",
"entries",
"to",
"to",
"be",
"applied",
"to",
"the",
"underlying",
"database",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L452-L461 | train |
rqlite/rqlite | store/store.go | State | func (s *Store) State() ClusterState {
state := s.raft.State()
switch state {
case raft.Leader:
return Leader
case raft.Candidate:
return Candidate
case raft.Follower:
return Follower
case raft.Shutdown:
return Shutdown
default:
return Unknown
}
} | go | func (s *Store) State() ClusterState {
state := s.raft.State()
switch state {
case raft.Leader:
return Leader
case raft.Candidate:
return Candidate
case raft.Follower:
return Follower
case raft.Shutdown:
return Shutdown
default:
return Unknown
}
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"State",
"(",
")",
"ClusterState",
"{",
"state",
":=",
"s",
".",
"raft",
".",
"State",
"(",
")",
"\n",
"switch",
"state",
"{",
"case",
"raft",
".",
"Leader",
":",
"return",
"Leader",
"\n",
"case",
"raft",
".",
"Candidate",
":",
"return",
"Candidate",
"\n",
"case",
"raft",
".",
"Follower",
":",
"return",
"Follower",
"\n",
"case",
"raft",
".",
"Shutdown",
":",
"return",
"Shutdown",
"\n",
"default",
":",
"return",
"Unknown",
"\n",
"}",
"\n",
"}"
] | // State returns the current node's Raft state | [
"State",
"returns",
"the",
"current",
"node",
"s",
"Raft",
"state"
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L469-L483 | train |
rqlite/rqlite | store/store.go | Connection | func (s *Store) Connection(id uint64) (*Connection, bool) {
s.connsMu.RLock()
defer s.connsMu.RUnlock()
c, ok := s.conns[id]
return c, ok
} | go | func (s *Store) Connection(id uint64) (*Connection, bool) {
s.connsMu.RLock()
defer s.connsMu.RUnlock()
c, ok := s.conns[id]
return c, ok
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"Connection",
"(",
"id",
"uint64",
")",
"(",
"*",
"Connection",
",",
"bool",
")",
"{",
"s",
".",
"connsMu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"connsMu",
".",
"RUnlock",
"(",
")",
"\n",
"c",
",",
"ok",
":=",
"s",
".",
"conns",
"[",
"id",
"]",
"\n",
"return",
"c",
",",
"ok",
"\n",
"}"
] | // Connection returns the connection for the given ID. | [
"Connection",
"returns",
"the",
"connection",
"for",
"the",
"given",
"ID",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L501-L506 | train |
rqlite/rqlite | store/store.go | LeaderID | func (s *Store) LeaderID() (string, error) {
addr := s.LeaderAddr()
configFuture := s.raft.GetConfiguration()
if err := configFuture.Error(); err != nil {
s.logger.Printf("failed to get raft configuration: %v", err)
return "", err
}
for _, srv := range configFuture.Configuration().Servers {
if srv.Address == raft.ServerAddress(addr) {
return string(srv.ID), nil
}
}
return "", nil
} | go | func (s *Store) LeaderID() (string, error) {
addr := s.LeaderAddr()
configFuture := s.raft.GetConfiguration()
if err := configFuture.Error(); err != nil {
s.logger.Printf("failed to get raft configuration: %v", err)
return "", err
}
for _, srv := range configFuture.Configuration().Servers {
if srv.Address == raft.ServerAddress(addr) {
return string(srv.ID), nil
}
}
return "", nil
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"LeaderID",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"addr",
":=",
"s",
".",
"LeaderAddr",
"(",
")",
"\n",
"configFuture",
":=",
"s",
".",
"raft",
".",
"GetConfiguration",
"(",
")",
"\n",
"if",
"err",
":=",
"configFuture",
".",
"Error",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"failed to get raft configuration: %v\"",
",",
"err",
")",
"\n",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"srv",
":=",
"range",
"configFuture",
".",
"Configuration",
"(",
")",
".",
"Servers",
"{",
"if",
"srv",
".",
"Address",
"==",
"raft",
".",
"ServerAddress",
"(",
"addr",
")",
"{",
"return",
"string",
"(",
"srv",
".",
"ID",
")",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\"\"",
",",
"nil",
"\n",
"}"
] | // LeaderID returns the node ID of the Raft leader. Returns a
// blank string if there is no leader, or an error. | [
"LeaderID",
"returns",
"the",
"node",
"ID",
"of",
"the",
"Raft",
"leader",
".",
"Returns",
"a",
"blank",
"string",
"if",
"there",
"is",
"no",
"leader",
"or",
"an",
"error",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L516-L530 | train |
rqlite/rqlite | store/store.go | Nodes | func (s *Store) Nodes() ([]*Server, error) {
f := s.raft.GetConfiguration()
if f.Error() != nil {
return nil, f.Error()
}
rs := f.Configuration().Servers
servers := make([]*Server, len(rs))
for i := range rs {
servers[i] = &Server{
ID: string(rs[i].ID),
Addr: string(rs[i].Address),
}
}
sort.Sort(Servers(servers))
return servers, nil
} | go | func (s *Store) Nodes() ([]*Server, error) {
f := s.raft.GetConfiguration()
if f.Error() != nil {
return nil, f.Error()
}
rs := f.Configuration().Servers
servers := make([]*Server, len(rs))
for i := range rs {
servers[i] = &Server{
ID: string(rs[i].ID),
Addr: string(rs[i].Address),
}
}
sort.Sort(Servers(servers))
return servers, nil
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"Nodes",
"(",
")",
"(",
"[",
"]",
"*",
"Server",
",",
"error",
")",
"{",
"f",
":=",
"s",
".",
"raft",
".",
"GetConfiguration",
"(",
")",
"\n",
"if",
"f",
".",
"Error",
"(",
")",
"!=",
"nil",
"{",
"return",
"nil",
",",
"f",
".",
"Error",
"(",
")",
"\n",
"}",
"\n",
"rs",
":=",
"f",
".",
"Configuration",
"(",
")",
".",
"Servers",
"\n",
"servers",
":=",
"make",
"(",
"[",
"]",
"*",
"Server",
",",
"len",
"(",
"rs",
")",
")",
"\n",
"for",
"i",
":=",
"range",
"rs",
"{",
"servers",
"[",
"i",
"]",
"=",
"&",
"Server",
"{",
"ID",
":",
"string",
"(",
"rs",
"[",
"i",
"]",
".",
"ID",
")",
",",
"Addr",
":",
"string",
"(",
"rs",
"[",
"i",
"]",
".",
"Address",
")",
",",
"}",
"\n",
"}",
"\n",
"sort",
".",
"Sort",
"(",
"Servers",
"(",
"servers",
")",
")",
"\n",
"return",
"servers",
",",
"nil",
"\n",
"}"
] | // Nodes returns the slice of nodes in the cluster, sorted by ID ascending. | [
"Nodes",
"returns",
"the",
"slice",
"of",
"nodes",
"in",
"the",
"cluster",
"sorted",
"by",
"ID",
"ascending",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L533-L550 | train |
rqlite/rqlite | store/store.go | WaitForLeader | func (s *Store) WaitForLeader(timeout time.Duration) (string, error) {
tck := time.NewTicker(leaderWaitDelay)
defer tck.Stop()
tmr := time.NewTimer(timeout)
defer tmr.Stop()
for {
select {
case <-tck.C:
l := s.LeaderAddr()
if l != "" {
return l, nil
}
case <-tmr.C:
return "", fmt.Errorf("timeout expired")
}
}
} | go | func (s *Store) WaitForLeader(timeout time.Duration) (string, error) {
tck := time.NewTicker(leaderWaitDelay)
defer tck.Stop()
tmr := time.NewTimer(timeout)
defer tmr.Stop()
for {
select {
case <-tck.C:
l := s.LeaderAddr()
if l != "" {
return l, nil
}
case <-tmr.C:
return "", fmt.Errorf("timeout expired")
}
}
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"WaitForLeader",
"(",
"timeout",
"time",
".",
"Duration",
")",
"(",
"string",
",",
"error",
")",
"{",
"tck",
":=",
"time",
".",
"NewTicker",
"(",
"leaderWaitDelay",
")",
"\n",
"defer",
"tck",
".",
"Stop",
"(",
")",
"\n",
"tmr",
":=",
"time",
".",
"NewTimer",
"(",
"timeout",
")",
"\n",
"defer",
"tmr",
".",
"Stop",
"(",
")",
"\n",
"for",
"{",
"select",
"{",
"case",
"<-",
"tck",
".",
"C",
":",
"l",
":=",
"s",
".",
"LeaderAddr",
"(",
")",
"\n",
"if",
"l",
"!=",
"\"\"",
"{",
"return",
"l",
",",
"nil",
"\n",
"}",
"\n",
"case",
"<-",
"tmr",
".",
"C",
":",
"return",
"\"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"timeout expired\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // WaitForLeader blocks until a leader is detected, or the timeout expires. | [
"WaitForLeader",
"blocks",
"until",
"a",
"leader",
"is",
"detected",
"or",
"the",
"timeout",
"expires",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L553-L570 | train |
rqlite/rqlite | store/store.go | WaitForAppliedIndex | func (s *Store) WaitForAppliedIndex(idx uint64, timeout time.Duration) error {
tck := time.NewTicker(appliedWaitDelay)
defer tck.Stop()
tmr := time.NewTimer(timeout)
defer tmr.Stop()
for {
select {
case <-tck.C:
if s.raft.AppliedIndex() >= idx {
return nil
}
case <-tmr.C:
return fmt.Errorf("timeout expired")
}
}
} | go | func (s *Store) WaitForAppliedIndex(idx uint64, timeout time.Duration) error {
tck := time.NewTicker(appliedWaitDelay)
defer tck.Stop()
tmr := time.NewTimer(timeout)
defer tmr.Stop()
for {
select {
case <-tck.C:
if s.raft.AppliedIndex() >= idx {
return nil
}
case <-tmr.C:
return fmt.Errorf("timeout expired")
}
}
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"WaitForAppliedIndex",
"(",
"idx",
"uint64",
",",
"timeout",
"time",
".",
"Duration",
")",
"error",
"{",
"tck",
":=",
"time",
".",
"NewTicker",
"(",
"appliedWaitDelay",
")",
"\n",
"defer",
"tck",
".",
"Stop",
"(",
")",
"\n",
"tmr",
":=",
"time",
".",
"NewTimer",
"(",
"timeout",
")",
"\n",
"defer",
"tmr",
".",
"Stop",
"(",
")",
"\n",
"for",
"{",
"select",
"{",
"case",
"<-",
"tck",
".",
"C",
":",
"if",
"s",
".",
"raft",
".",
"AppliedIndex",
"(",
")",
">=",
"idx",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"case",
"<-",
"tmr",
".",
"C",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"timeout expired\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // WaitForAppliedIndex blocks until a given log index has been applied,
// or the timeout expires. | [
"WaitForAppliedIndex",
"blocks",
"until",
"a",
"given",
"log",
"index",
"has",
"been",
"applied",
"or",
"the",
"timeout",
"expires",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L574-L590 | train |
rqlite/rqlite | store/store.go | Stats | func (s *Store) Stats() (map[string]interface{}, error) {
fkEnabled, err := s.dbConn.FKConstraints()
if err != nil {
return nil, err
}
dbStatus := map[string]interface{}{
"dsn": s.dbConf.DSN,
"fk_constraints": enabledFromBool(fkEnabled),
"version": sdb.DBVersion,
}
if !s.dbConf.Memory {
dbStatus["path"] = s.dbPath
stat, err := os.Stat(s.dbPath)
if err != nil {
return nil, err
}
dbStatus["size"] = stat.Size()
} else {
dbStatus["path"] = ":memory:"
}
nodes, err := s.Nodes()
if err != nil {
return nil, err
}
leaderID, err := s.LeaderID()
if err != nil {
return nil, err
}
status := map[string]interface{}{
"node_id": s.raftID,
"raft": s.raft.Stats(),
"addr": s.Addr(),
"leader": map[string]string{
"node_id": leaderID,
"addr": s.LeaderAddr(),
},
"apply_timeout": s.ApplyTimeout.String(),
"heartbeat_timeout": s.HeartbeatTimeout.String(),
"snapshot_threshold": s.SnapshotThreshold,
"conn_poll_period": s.connPollPeriod.String(),
"metadata": s.meta,
"nodes": nodes,
"dir": s.raftDir,
"sqlite3": dbStatus,
"db_conf": s.dbConf,
}
// Add connections status
if err := func() error {
s.connsMu.RLock()
defer s.connsMu.RUnlock()
if len(s.conns) > 1 {
conns := make([]interface{}, len(s.conns)-1)
ci := 0
for id, c := range s.conns {
if id == defaultConnID {
continue
}
stats, err := c.Stats()
if err != nil {
return err
}
conns[ci] = stats
ci++
}
status["connections"] = conns
}
return nil
}(); err != nil {
return nil, err
}
return status, nil
} | go | func (s *Store) Stats() (map[string]interface{}, error) {
fkEnabled, err := s.dbConn.FKConstraints()
if err != nil {
return nil, err
}
dbStatus := map[string]interface{}{
"dsn": s.dbConf.DSN,
"fk_constraints": enabledFromBool(fkEnabled),
"version": sdb.DBVersion,
}
if !s.dbConf.Memory {
dbStatus["path"] = s.dbPath
stat, err := os.Stat(s.dbPath)
if err != nil {
return nil, err
}
dbStatus["size"] = stat.Size()
} else {
dbStatus["path"] = ":memory:"
}
nodes, err := s.Nodes()
if err != nil {
return nil, err
}
leaderID, err := s.LeaderID()
if err != nil {
return nil, err
}
status := map[string]interface{}{
"node_id": s.raftID,
"raft": s.raft.Stats(),
"addr": s.Addr(),
"leader": map[string]string{
"node_id": leaderID,
"addr": s.LeaderAddr(),
},
"apply_timeout": s.ApplyTimeout.String(),
"heartbeat_timeout": s.HeartbeatTimeout.String(),
"snapshot_threshold": s.SnapshotThreshold,
"conn_poll_period": s.connPollPeriod.String(),
"metadata": s.meta,
"nodes": nodes,
"dir": s.raftDir,
"sqlite3": dbStatus,
"db_conf": s.dbConf,
}
// Add connections status
if err := func() error {
s.connsMu.RLock()
defer s.connsMu.RUnlock()
if len(s.conns) > 1 {
conns := make([]interface{}, len(s.conns)-1)
ci := 0
for id, c := range s.conns {
if id == defaultConnID {
continue
}
stats, err := c.Stats()
if err != nil {
return err
}
conns[ci] = stats
ci++
}
status["connections"] = conns
}
return nil
}(); err != nil {
return nil, err
}
return status, nil
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"Stats",
"(",
")",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"fkEnabled",
",",
"err",
":=",
"s",
".",
"dbConn",
".",
"FKConstraints",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"dbStatus",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"dsn\"",
":",
"s",
".",
"dbConf",
".",
"DSN",
",",
"\"fk_constraints\"",
":",
"enabledFromBool",
"(",
"fkEnabled",
")",
",",
"\"version\"",
":",
"sdb",
".",
"DBVersion",
",",
"}",
"\n",
"if",
"!",
"s",
".",
"dbConf",
".",
"Memory",
"{",
"dbStatus",
"[",
"\"path\"",
"]",
"=",
"s",
".",
"dbPath",
"\n",
"stat",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"s",
".",
"dbPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"dbStatus",
"[",
"\"size\"",
"]",
"=",
"stat",
".",
"Size",
"(",
")",
"\n",
"}",
"else",
"{",
"dbStatus",
"[",
"\"path\"",
"]",
"=",
"\":memory:\"",
"\n",
"}",
"\n",
"nodes",
",",
"err",
":=",
"s",
".",
"Nodes",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"leaderID",
",",
"err",
":=",
"s",
".",
"LeaderID",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"status",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"node_id\"",
":",
"s",
".",
"raftID",
",",
"\"raft\"",
":",
"s",
".",
"raft",
".",
"Stats",
"(",
")",
",",
"\"addr\"",
":",
"s",
".",
"Addr",
"(",
")",
",",
"\"leader\"",
":",
"map",
"[",
"string",
"]",
"string",
"{",
"\"node_id\"",
":",
"leaderID",
",",
"\"addr\"",
":",
"s",
".",
"LeaderAddr",
"(",
")",
",",
"}",
",",
"\"apply_timeout\"",
":",
"s",
".",
"ApplyTimeout",
".",
"String",
"(",
")",
",",
"\"heartbeat_timeout\"",
":",
"s",
".",
"HeartbeatTimeout",
".",
"String",
"(",
")",
",",
"\"snapshot_threshold\"",
":",
"s",
".",
"SnapshotThreshold",
",",
"\"conn_poll_period\"",
":",
"s",
".",
"connPollPeriod",
".",
"String",
"(",
")",
",",
"\"metadata\"",
":",
"s",
".",
"meta",
",",
"\"nodes\"",
":",
"nodes",
",",
"\"dir\"",
":",
"s",
".",
"raftDir",
",",
"\"sqlite3\"",
":",
"dbStatus",
",",
"\"db_conf\"",
":",
"s",
".",
"dbConf",
",",
"}",
"\n",
"if",
"err",
":=",
"func",
"(",
")",
"error",
"{",
"s",
".",
"connsMu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"connsMu",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"len",
"(",
"s",
".",
"conns",
")",
">",
"1",
"{",
"conns",
":=",
"make",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"len",
"(",
"s",
".",
"conns",
")",
"-",
"1",
")",
"\n",
"ci",
":=",
"0",
"\n",
"for",
"id",
",",
"c",
":=",
"range",
"s",
".",
"conns",
"{",
"if",
"id",
"==",
"defaultConnID",
"{",
"continue",
"\n",
"}",
"\n",
"stats",
",",
"err",
":=",
"c",
".",
"Stats",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"conns",
"[",
"ci",
"]",
"=",
"stats",
"\n",
"ci",
"++",
"\n",
"}",
"\n",
"status",
"[",
"\"connections\"",
"]",
"=",
"conns",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"status",
",",
"nil",
"\n",
"}"
] | // Stats returns stats for the store. | [
"Stats",
"returns",
"stats",
"for",
"the",
"store",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L593-L669 | train |
rqlite/rqlite | store/store.go | Backup | func (s *Store) Backup(leader bool, fmt BackupFormat, dst io.Writer) error {
s.restoreMu.RLock()
defer s.restoreMu.RUnlock()
if leader && s.raft.State() != raft.Leader {
return ErrNotLeader
}
var err error
if fmt == BackupBinary {
err = s.database(leader, dst)
if err != nil {
return err
}
} else if fmt == BackupSQL {
if err := s.dbConn.Dump(dst); err != nil {
return err
}
} else {
return ErrInvalidBackupFormat
}
stats.Add(numBackups, 1)
return nil
} | go | func (s *Store) Backup(leader bool, fmt BackupFormat, dst io.Writer) error {
s.restoreMu.RLock()
defer s.restoreMu.RUnlock()
if leader && s.raft.State() != raft.Leader {
return ErrNotLeader
}
var err error
if fmt == BackupBinary {
err = s.database(leader, dst)
if err != nil {
return err
}
} else if fmt == BackupSQL {
if err := s.dbConn.Dump(dst); err != nil {
return err
}
} else {
return ErrInvalidBackupFormat
}
stats.Add(numBackups, 1)
return nil
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"Backup",
"(",
"leader",
"bool",
",",
"fmt",
"BackupFormat",
",",
"dst",
"io",
".",
"Writer",
")",
"error",
"{",
"s",
".",
"restoreMu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"restoreMu",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"leader",
"&&",
"s",
".",
"raft",
".",
"State",
"(",
")",
"!=",
"raft",
".",
"Leader",
"{",
"return",
"ErrNotLeader",
"\n",
"}",
"\n",
"var",
"err",
"error",
"\n",
"if",
"fmt",
"==",
"BackupBinary",
"{",
"err",
"=",
"s",
".",
"database",
"(",
"leader",
",",
"dst",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"else",
"if",
"fmt",
"==",
"BackupSQL",
"{",
"if",
"err",
":=",
"s",
".",
"dbConn",
".",
"Dump",
"(",
"dst",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"else",
"{",
"return",
"ErrInvalidBackupFormat",
"\n",
"}",
"\n",
"stats",
".",
"Add",
"(",
"numBackups",
",",
"1",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Backup writes a snapshot of the underlying database to dst
//
// If leader is true, this operation is performed with a read consistency
// level equivalent to "weak". Otherwise no guarantees are made about the
// read consistency level. | [
"Backup",
"writes",
"a",
"snapshot",
"of",
"the",
"underlying",
"database",
"to",
"dst",
"If",
"leader",
"is",
"true",
"this",
"operation",
"is",
"performed",
"with",
"a",
"read",
"consistency",
"level",
"equivalent",
"to",
"weak",
".",
"Otherwise",
"no",
"guarantees",
"are",
"made",
"about",
"the",
"read",
"consistency",
"level",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L676-L699 | train |
rqlite/rqlite | store/store.go | Join | func (s *Store) Join(id, addr string, metadata map[string]string) error {
s.logger.Printf("received request to join node at %s", addr)
if s.raft.State() != raft.Leader {
return ErrNotLeader
}
configFuture := s.raft.GetConfiguration()
if err := configFuture.Error(); err != nil {
s.logger.Printf("failed to get raft configuration: %v", err)
return err
}
for _, srv := range configFuture.Configuration().Servers {
// If a node already exists with either the joining node's ID or address,
// that node may need to be removed from the config first.
if srv.ID == raft.ServerID(id) || srv.Address == raft.ServerAddress(addr) {
// However if *both* the ID and the address are the same, the no
// join is actually needed.
if srv.Address == raft.ServerAddress(addr) && srv.ID == raft.ServerID(id) {
s.logger.Printf("node %s at %s already member of cluster, ignoring join request",
id, addr)
return nil
}
if err := s.remove(id); err != nil {
s.logger.Printf("failed to remove node: %v", err)
return err
}
}
}
f := s.raft.AddVoter(raft.ServerID(id), raft.ServerAddress(addr), 0, 0)
if e := f.(raft.Future); e.Error() != nil {
if e.Error() == raft.ErrNotLeader {
return ErrNotLeader
}
return e.Error()
}
if err := s.setMetadata(id, metadata); err != nil {
return err
}
s.logger.Printf("node at %s joined successfully", addr)
return nil
} | go | func (s *Store) Join(id, addr string, metadata map[string]string) error {
s.logger.Printf("received request to join node at %s", addr)
if s.raft.State() != raft.Leader {
return ErrNotLeader
}
configFuture := s.raft.GetConfiguration()
if err := configFuture.Error(); err != nil {
s.logger.Printf("failed to get raft configuration: %v", err)
return err
}
for _, srv := range configFuture.Configuration().Servers {
// If a node already exists with either the joining node's ID or address,
// that node may need to be removed from the config first.
if srv.ID == raft.ServerID(id) || srv.Address == raft.ServerAddress(addr) {
// However if *both* the ID and the address are the same, the no
// join is actually needed.
if srv.Address == raft.ServerAddress(addr) && srv.ID == raft.ServerID(id) {
s.logger.Printf("node %s at %s already member of cluster, ignoring join request",
id, addr)
return nil
}
if err := s.remove(id); err != nil {
s.logger.Printf("failed to remove node: %v", err)
return err
}
}
}
f := s.raft.AddVoter(raft.ServerID(id), raft.ServerAddress(addr), 0, 0)
if e := f.(raft.Future); e.Error() != nil {
if e.Error() == raft.ErrNotLeader {
return ErrNotLeader
}
return e.Error()
}
if err := s.setMetadata(id, metadata); err != nil {
return err
}
s.logger.Printf("node at %s joined successfully", addr)
return nil
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"Join",
"(",
"id",
",",
"addr",
"string",
",",
"metadata",
"map",
"[",
"string",
"]",
"string",
")",
"error",
"{",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"received request to join node at %s\"",
",",
"addr",
")",
"\n",
"if",
"s",
".",
"raft",
".",
"State",
"(",
")",
"!=",
"raft",
".",
"Leader",
"{",
"return",
"ErrNotLeader",
"\n",
"}",
"\n",
"configFuture",
":=",
"s",
".",
"raft",
".",
"GetConfiguration",
"(",
")",
"\n",
"if",
"err",
":=",
"configFuture",
".",
"Error",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"failed to get raft configuration: %v\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"srv",
":=",
"range",
"configFuture",
".",
"Configuration",
"(",
")",
".",
"Servers",
"{",
"if",
"srv",
".",
"ID",
"==",
"raft",
".",
"ServerID",
"(",
"id",
")",
"||",
"srv",
".",
"Address",
"==",
"raft",
".",
"ServerAddress",
"(",
"addr",
")",
"{",
"if",
"srv",
".",
"Address",
"==",
"raft",
".",
"ServerAddress",
"(",
"addr",
")",
"&&",
"srv",
".",
"ID",
"==",
"raft",
".",
"ServerID",
"(",
"id",
")",
"{",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"node %s at %s already member of cluster, ignoring join request\"",
",",
"id",
",",
"addr",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"err",
":=",
"s",
".",
"remove",
"(",
"id",
")",
";",
"err",
"!=",
"nil",
"{",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"failed to remove node: %v\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"f",
":=",
"s",
".",
"raft",
".",
"AddVoter",
"(",
"raft",
".",
"ServerID",
"(",
"id",
")",
",",
"raft",
".",
"ServerAddress",
"(",
"addr",
")",
",",
"0",
",",
"0",
")",
"\n",
"if",
"e",
":=",
"f",
".",
"(",
"raft",
".",
"Future",
")",
";",
"e",
".",
"Error",
"(",
")",
"!=",
"nil",
"{",
"if",
"e",
".",
"Error",
"(",
")",
"==",
"raft",
".",
"ErrNotLeader",
"{",
"return",
"ErrNotLeader",
"\n",
"}",
"\n",
"return",
"e",
".",
"Error",
"(",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"s",
".",
"setMetadata",
"(",
"id",
",",
"metadata",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"node at %s joined successfully\"",
",",
"addr",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Join joins a node, identified by id and located at addr, to this store.
// The node must be ready to respond to Raft communications at that address. | [
"Join",
"joins",
"a",
"node",
"identified",
"by",
"id",
"and",
"located",
"at",
"addr",
"to",
"this",
"store",
".",
"The",
"node",
"must",
"be",
"ready",
"to",
"respond",
"to",
"Raft",
"communications",
"at",
"that",
"address",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L703-L747 | train |
rqlite/rqlite | store/store.go | Remove | func (s *Store) Remove(id string) error {
s.logger.Printf("received request to remove node %s", id)
if err := s.remove(id); err != nil {
s.logger.Printf("failed to remove node %s: %s", id, err.Error())
return err
}
s.logger.Printf("node %s removed successfully", id)
return nil
} | go | func (s *Store) Remove(id string) error {
s.logger.Printf("received request to remove node %s", id)
if err := s.remove(id); err != nil {
s.logger.Printf("failed to remove node %s: %s", id, err.Error())
return err
}
s.logger.Printf("node %s removed successfully", id)
return nil
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"Remove",
"(",
"id",
"string",
")",
"error",
"{",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"received request to remove node %s\"",
",",
"id",
")",
"\n",
"if",
"err",
":=",
"s",
".",
"remove",
"(",
"id",
")",
";",
"err",
"!=",
"nil",
"{",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"failed to remove node %s: %s\"",
",",
"id",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"node %s removed successfully\"",
",",
"id",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Remove removes a node from the store, specified by ID. | [
"Remove",
"removes",
"a",
"node",
"from",
"the",
"store",
"specified",
"by",
"ID",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L750-L759 | train |
rqlite/rqlite | store/store.go | Metadata | func (s *Store) Metadata(id, key string) string {
s.metaMu.RLock()
defer s.metaMu.RUnlock()
if _, ok := s.meta[id]; !ok {
return ""
}
v, ok := s.meta[id][key]
if ok {
return v
}
return ""
} | go | func (s *Store) Metadata(id, key string) string {
s.metaMu.RLock()
defer s.metaMu.RUnlock()
if _, ok := s.meta[id]; !ok {
return ""
}
v, ok := s.meta[id][key]
if ok {
return v
}
return ""
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"Metadata",
"(",
"id",
",",
"key",
"string",
")",
"string",
"{",
"s",
".",
"metaMu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"metaMu",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"s",
".",
"meta",
"[",
"id",
"]",
";",
"!",
"ok",
"{",
"return",
"\"\"",
"\n",
"}",
"\n",
"v",
",",
"ok",
":=",
"s",
".",
"meta",
"[",
"id",
"]",
"[",
"key",
"]",
"\n",
"if",
"ok",
"{",
"return",
"v",
"\n",
"}",
"\n",
"return",
"\"\"",
"\n",
"}"
] | // Metadata returns the value for a given key, for a given node ID. | [
"Metadata",
"returns",
"the",
"value",
"for",
"a",
"given",
"key",
"for",
"a",
"given",
"node",
"ID",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L762-L774 | train |
rqlite/rqlite | store/store.go | SetMetadata | func (s *Store) SetMetadata(md map[string]string) error {
return s.setMetadata(s.raftID, md)
} | go | func (s *Store) SetMetadata(md map[string]string) error {
return s.setMetadata(s.raftID, md)
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"SetMetadata",
"(",
"md",
"map",
"[",
"string",
"]",
"string",
")",
"error",
"{",
"return",
"s",
".",
"setMetadata",
"(",
"s",
".",
"raftID",
",",
"md",
")",
"\n",
"}"
] | // SetMetadata adds the metadata md to any existing metadata for
// this node. | [
"SetMetadata",
"adds",
"the",
"metadata",
"md",
"to",
"any",
"existing",
"metadata",
"for",
"this",
"node",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L778-L780 | train |
rqlite/rqlite | store/store.go | setMetadata | func (s *Store) setMetadata(id string, md map[string]string) error {
// Check local data first.
if func() bool {
s.metaMu.RLock()
defer s.metaMu.RUnlock()
if _, ok := s.meta[id]; ok {
for k, v := range md {
if s.meta[id][k] != v {
return false
}
}
return true
}
return false
}() {
// Local data is same as data being pushed in,
// nothing to do.
return nil
}
c, err := newMetadataSetCommand(id, md)
if err != nil {
return err
}
b, err := json.Marshal(c)
if err != nil {
return err
}
f := s.raft.Apply(b, s.ApplyTimeout)
if e := f.(raft.Future); e.Error() != nil {
if e.Error() == raft.ErrNotLeader {
return ErrNotLeader
}
return e.Error()
}
return f.Response().(*fsmGenericResponse).error
} | go | func (s *Store) setMetadata(id string, md map[string]string) error {
// Check local data first.
if func() bool {
s.metaMu.RLock()
defer s.metaMu.RUnlock()
if _, ok := s.meta[id]; ok {
for k, v := range md {
if s.meta[id][k] != v {
return false
}
}
return true
}
return false
}() {
// Local data is same as data being pushed in,
// nothing to do.
return nil
}
c, err := newMetadataSetCommand(id, md)
if err != nil {
return err
}
b, err := json.Marshal(c)
if err != nil {
return err
}
f := s.raft.Apply(b, s.ApplyTimeout)
if e := f.(raft.Future); e.Error() != nil {
if e.Error() == raft.ErrNotLeader {
return ErrNotLeader
}
return e.Error()
}
return f.Response().(*fsmGenericResponse).error
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"setMetadata",
"(",
"id",
"string",
",",
"md",
"map",
"[",
"string",
"]",
"string",
")",
"error",
"{",
"if",
"func",
"(",
")",
"bool",
"{",
"s",
".",
"metaMu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"metaMu",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"s",
".",
"meta",
"[",
"id",
"]",
";",
"ok",
"{",
"for",
"k",
",",
"v",
":=",
"range",
"md",
"{",
"if",
"s",
".",
"meta",
"[",
"id",
"]",
"[",
"k",
"]",
"!=",
"v",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}",
"(",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"c",
",",
"err",
":=",
"newMetadataSetCommand",
"(",
"id",
",",
"md",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"b",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"c",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"f",
":=",
"s",
".",
"raft",
".",
"Apply",
"(",
"b",
",",
"s",
".",
"ApplyTimeout",
")",
"\n",
"if",
"e",
":=",
"f",
".",
"(",
"raft",
".",
"Future",
")",
";",
"e",
".",
"Error",
"(",
")",
"!=",
"nil",
"{",
"if",
"e",
".",
"Error",
"(",
")",
"==",
"raft",
".",
"ErrNotLeader",
"{",
"return",
"ErrNotLeader",
"\n",
"}",
"\n",
"return",
"e",
".",
"Error",
"(",
")",
"\n",
"}",
"\n",
"return",
"f",
".",
"Response",
"(",
")",
".",
"(",
"*",
"fsmGenericResponse",
")",
".",
"error",
"\n",
"}"
] | // setMetadata adds the metadata md to any existing metadata for
// the given node ID. | [
"setMetadata",
"adds",
"the",
"metadata",
"md",
"to",
"any",
"existing",
"metadata",
"for",
"the",
"given",
"node",
"ID",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L784-L821 | train |
rqlite/rqlite | store/store.go | disconnect | func (s *Store) disconnect(c *Connection) error {
d := &connectionSub{
ConnID: c.ID,
}
cmd, err := newCommand(disconnect, d)
if err != nil {
return err
}
b, err := json.Marshal(cmd)
if err != nil {
return err
}
f := s.raft.Apply(b, s.ApplyTimeout)
if e := f.(raft.Future); e.Error() != nil {
if e.Error() == raft.ErrNotLeader {
return ErrNotLeader
}
return e.Error()
}
stats.Add(numDisconnects, 1)
return f.Response().(*fsmGenericResponse).error
} | go | func (s *Store) disconnect(c *Connection) error {
d := &connectionSub{
ConnID: c.ID,
}
cmd, err := newCommand(disconnect, d)
if err != nil {
return err
}
b, err := json.Marshal(cmd)
if err != nil {
return err
}
f := s.raft.Apply(b, s.ApplyTimeout)
if e := f.(raft.Future); e.Error() != nil {
if e.Error() == raft.ErrNotLeader {
return ErrNotLeader
}
return e.Error()
}
stats.Add(numDisconnects, 1)
return f.Response().(*fsmGenericResponse).error
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"disconnect",
"(",
"c",
"*",
"Connection",
")",
"error",
"{",
"d",
":=",
"&",
"connectionSub",
"{",
"ConnID",
":",
"c",
".",
"ID",
",",
"}",
"\n",
"cmd",
",",
"err",
":=",
"newCommand",
"(",
"disconnect",
",",
"d",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"b",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"cmd",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"f",
":=",
"s",
".",
"raft",
".",
"Apply",
"(",
"b",
",",
"s",
".",
"ApplyTimeout",
")",
"\n",
"if",
"e",
":=",
"f",
".",
"(",
"raft",
".",
"Future",
")",
";",
"e",
".",
"Error",
"(",
")",
"!=",
"nil",
"{",
"if",
"e",
".",
"Error",
"(",
")",
"==",
"raft",
".",
"ErrNotLeader",
"{",
"return",
"ErrNotLeader",
"\n",
"}",
"\n",
"return",
"e",
".",
"Error",
"(",
")",
"\n",
"}",
"\n",
"stats",
".",
"Add",
"(",
"numDisconnects",
",",
"1",
")",
"\n",
"return",
"f",
".",
"Response",
"(",
")",
".",
"(",
"*",
"fsmGenericResponse",
")",
".",
"error",
"\n",
"}"
] | // disconnect removes a connection to the database, a connection
// which was previously established via Raft consensus. | [
"disconnect",
"removes",
"a",
"connection",
"to",
"the",
"database",
"a",
"connection",
"which",
"was",
"previously",
"established",
"via",
"Raft",
"consensus",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L825-L847 | train |
rqlite/rqlite | store/store.go | execute | func (s *Store) execute(c *Connection, ex *ExecuteRequest) (*ExecuteResponse, error) {
if c == nil {
s.connsMu.RLock()
c = s.conns[defaultConnID]
s.connsMu.RUnlock()
}
c.SetLastUsedNow()
start := time.Now()
d := &databaseSub{
ConnID: c.ID,
Atomic: ex.Atomic,
Queries: ex.Queries,
Timings: ex.Timings,
}
cmd, err := newCommand(execute, d)
if err != nil {
return nil, err
}
b, err := json.Marshal(cmd)
if err != nil {
return nil, err
}
f := s.raft.Apply(b, s.ApplyTimeout)
if e := f.(raft.Future); e.Error() != nil {
if e.Error() == raft.ErrNotLeader {
return nil, ErrNotLeader
}
return nil, e.Error()
}
switch r := f.Response().(type) {
case *fsmExecuteResponse:
return &ExecuteResponse{
Results: r.results,
Time: time.Since(start).Seconds(),
Raft: RaftResponse{f.Index(), s.raftID},
}, r.error
case *fsmGenericResponse:
return nil, r.error
default:
panic("unsupported type")
}
} | go | func (s *Store) execute(c *Connection, ex *ExecuteRequest) (*ExecuteResponse, error) {
if c == nil {
s.connsMu.RLock()
c = s.conns[defaultConnID]
s.connsMu.RUnlock()
}
c.SetLastUsedNow()
start := time.Now()
d := &databaseSub{
ConnID: c.ID,
Atomic: ex.Atomic,
Queries: ex.Queries,
Timings: ex.Timings,
}
cmd, err := newCommand(execute, d)
if err != nil {
return nil, err
}
b, err := json.Marshal(cmd)
if err != nil {
return nil, err
}
f := s.raft.Apply(b, s.ApplyTimeout)
if e := f.(raft.Future); e.Error() != nil {
if e.Error() == raft.ErrNotLeader {
return nil, ErrNotLeader
}
return nil, e.Error()
}
switch r := f.Response().(type) {
case *fsmExecuteResponse:
return &ExecuteResponse{
Results: r.results,
Time: time.Since(start).Seconds(),
Raft: RaftResponse{f.Index(), s.raftID},
}, r.error
case *fsmGenericResponse:
return nil, r.error
default:
panic("unsupported type")
}
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"execute",
"(",
"c",
"*",
"Connection",
",",
"ex",
"*",
"ExecuteRequest",
")",
"(",
"*",
"ExecuteResponse",
",",
"error",
")",
"{",
"if",
"c",
"==",
"nil",
"{",
"s",
".",
"connsMu",
".",
"RLock",
"(",
")",
"\n",
"c",
"=",
"s",
".",
"conns",
"[",
"defaultConnID",
"]",
"\n",
"s",
".",
"connsMu",
".",
"RUnlock",
"(",
")",
"\n",
"}",
"\n",
"c",
".",
"SetLastUsedNow",
"(",
")",
"\n",
"start",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"d",
":=",
"&",
"databaseSub",
"{",
"ConnID",
":",
"c",
".",
"ID",
",",
"Atomic",
":",
"ex",
".",
"Atomic",
",",
"Queries",
":",
"ex",
".",
"Queries",
",",
"Timings",
":",
"ex",
".",
"Timings",
",",
"}",
"\n",
"cmd",
",",
"err",
":=",
"newCommand",
"(",
"execute",
",",
"d",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"b",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"cmd",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"f",
":=",
"s",
".",
"raft",
".",
"Apply",
"(",
"b",
",",
"s",
".",
"ApplyTimeout",
")",
"\n",
"if",
"e",
":=",
"f",
".",
"(",
"raft",
".",
"Future",
")",
";",
"e",
".",
"Error",
"(",
")",
"!=",
"nil",
"{",
"if",
"e",
".",
"Error",
"(",
")",
"==",
"raft",
".",
"ErrNotLeader",
"{",
"return",
"nil",
",",
"ErrNotLeader",
"\n",
"}",
"\n",
"return",
"nil",
",",
"e",
".",
"Error",
"(",
")",
"\n",
"}",
"\n",
"switch",
"r",
":=",
"f",
".",
"Response",
"(",
")",
".",
"(",
"type",
")",
"{",
"case",
"*",
"fsmExecuteResponse",
":",
"return",
"&",
"ExecuteResponse",
"{",
"Results",
":",
"r",
".",
"results",
",",
"Time",
":",
"time",
".",
"Since",
"(",
"start",
")",
".",
"Seconds",
"(",
")",
",",
"Raft",
":",
"RaftResponse",
"{",
"f",
".",
"Index",
"(",
")",
",",
"s",
".",
"raftID",
"}",
",",
"}",
",",
"r",
".",
"error",
"\n",
"case",
"*",
"fsmGenericResponse",
":",
"return",
"nil",
",",
"r",
".",
"error",
"\n",
"default",
":",
"panic",
"(",
"\"unsupported type\"",
")",
"\n",
"}",
"\n",
"}"
] | // Execute executes queries that return no rows, but do modify the database. If connection
// is nil then the utility connection is used. | [
"Execute",
"executes",
"queries",
"that",
"return",
"no",
"rows",
"but",
"do",
"modify",
"the",
"database",
".",
"If",
"connection",
"is",
"nil",
"then",
"the",
"utility",
"connection",
"is",
"used",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L851-L896 | train |
rqlite/rqlite | store/store.go | query | func (s *Store) query(c *Connection, qr *QueryRequest) (*QueryResponse, error) {
if c == nil {
s.connsMu.RLock()
c = s.conns[defaultConnID]
s.connsMu.RUnlock()
}
c.SetLastUsedNow()
s.restoreMu.RLock()
defer s.restoreMu.RUnlock()
start := time.Now()
if qr.Lvl == Strong {
d := &databaseSub{
ConnID: c.ID,
Atomic: qr.Atomic,
Queries: qr.Queries,
Timings: qr.Timings,
}
cmd, err := newCommand(query, d)
if err != nil {
return nil, err
}
b, err := json.Marshal(cmd)
if err != nil {
return nil, err
}
f := s.raft.Apply(b, s.ApplyTimeout)
if e := f.(raft.Future); e.Error() != nil {
if e.Error() == raft.ErrNotLeader {
return nil, ErrNotLeader
}
return nil, e.Error()
}
switch r := f.Response().(type) {
case *fsmQueryResponse:
return &QueryResponse{
Rows: r.rows,
Time: time.Since(start).Seconds(),
Raft: &RaftResponse{f.Index(), s.raftID},
}, r.error
case *fsmGenericResponse:
return nil, r.error
default:
panic("unsupported type")
}
}
if qr.Lvl == Weak && s.raft.State() != raft.Leader {
return nil, ErrNotLeader
}
r, err := c.db.Query(qr.Queries, qr.Atomic, qr.Timings)
return &QueryResponse{
Rows: r,
Time: time.Since(start).Seconds(),
}, err
} | go | func (s *Store) query(c *Connection, qr *QueryRequest) (*QueryResponse, error) {
if c == nil {
s.connsMu.RLock()
c = s.conns[defaultConnID]
s.connsMu.RUnlock()
}
c.SetLastUsedNow()
s.restoreMu.RLock()
defer s.restoreMu.RUnlock()
start := time.Now()
if qr.Lvl == Strong {
d := &databaseSub{
ConnID: c.ID,
Atomic: qr.Atomic,
Queries: qr.Queries,
Timings: qr.Timings,
}
cmd, err := newCommand(query, d)
if err != nil {
return nil, err
}
b, err := json.Marshal(cmd)
if err != nil {
return nil, err
}
f := s.raft.Apply(b, s.ApplyTimeout)
if e := f.(raft.Future); e.Error() != nil {
if e.Error() == raft.ErrNotLeader {
return nil, ErrNotLeader
}
return nil, e.Error()
}
switch r := f.Response().(type) {
case *fsmQueryResponse:
return &QueryResponse{
Rows: r.rows,
Time: time.Since(start).Seconds(),
Raft: &RaftResponse{f.Index(), s.raftID},
}, r.error
case *fsmGenericResponse:
return nil, r.error
default:
panic("unsupported type")
}
}
if qr.Lvl == Weak && s.raft.State() != raft.Leader {
return nil, ErrNotLeader
}
r, err := c.db.Query(qr.Queries, qr.Atomic, qr.Timings)
return &QueryResponse{
Rows: r,
Time: time.Since(start).Seconds(),
}, err
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"query",
"(",
"c",
"*",
"Connection",
",",
"qr",
"*",
"QueryRequest",
")",
"(",
"*",
"QueryResponse",
",",
"error",
")",
"{",
"if",
"c",
"==",
"nil",
"{",
"s",
".",
"connsMu",
".",
"RLock",
"(",
")",
"\n",
"c",
"=",
"s",
".",
"conns",
"[",
"defaultConnID",
"]",
"\n",
"s",
".",
"connsMu",
".",
"RUnlock",
"(",
")",
"\n",
"}",
"\n",
"c",
".",
"SetLastUsedNow",
"(",
")",
"\n",
"s",
".",
"restoreMu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"restoreMu",
".",
"RUnlock",
"(",
")",
"\n",
"start",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"if",
"qr",
".",
"Lvl",
"==",
"Strong",
"{",
"d",
":=",
"&",
"databaseSub",
"{",
"ConnID",
":",
"c",
".",
"ID",
",",
"Atomic",
":",
"qr",
".",
"Atomic",
",",
"Queries",
":",
"qr",
".",
"Queries",
",",
"Timings",
":",
"qr",
".",
"Timings",
",",
"}",
"\n",
"cmd",
",",
"err",
":=",
"newCommand",
"(",
"query",
",",
"d",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"b",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"cmd",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"f",
":=",
"s",
".",
"raft",
".",
"Apply",
"(",
"b",
",",
"s",
".",
"ApplyTimeout",
")",
"\n",
"if",
"e",
":=",
"f",
".",
"(",
"raft",
".",
"Future",
")",
";",
"e",
".",
"Error",
"(",
")",
"!=",
"nil",
"{",
"if",
"e",
".",
"Error",
"(",
")",
"==",
"raft",
".",
"ErrNotLeader",
"{",
"return",
"nil",
",",
"ErrNotLeader",
"\n",
"}",
"\n",
"return",
"nil",
",",
"e",
".",
"Error",
"(",
")",
"\n",
"}",
"\n",
"switch",
"r",
":=",
"f",
".",
"Response",
"(",
")",
".",
"(",
"type",
")",
"{",
"case",
"*",
"fsmQueryResponse",
":",
"return",
"&",
"QueryResponse",
"{",
"Rows",
":",
"r",
".",
"rows",
",",
"Time",
":",
"time",
".",
"Since",
"(",
"start",
")",
".",
"Seconds",
"(",
")",
",",
"Raft",
":",
"&",
"RaftResponse",
"{",
"f",
".",
"Index",
"(",
")",
",",
"s",
".",
"raftID",
"}",
",",
"}",
",",
"r",
".",
"error",
"\n",
"case",
"*",
"fsmGenericResponse",
":",
"return",
"nil",
",",
"r",
".",
"error",
"\n",
"default",
":",
"panic",
"(",
"\"unsupported type\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"qr",
".",
"Lvl",
"==",
"Weak",
"&&",
"s",
".",
"raft",
".",
"State",
"(",
")",
"!=",
"raft",
".",
"Leader",
"{",
"return",
"nil",
",",
"ErrNotLeader",
"\n",
"}",
"\n",
"r",
",",
"err",
":=",
"c",
".",
"db",
".",
"Query",
"(",
"qr",
".",
"Queries",
",",
"qr",
".",
"Atomic",
",",
"qr",
".",
"Timings",
")",
"\n",
"return",
"&",
"QueryResponse",
"{",
"Rows",
":",
"r",
",",
"Time",
":",
"time",
".",
"Since",
"(",
"start",
")",
".",
"Seconds",
"(",
")",
",",
"}",
",",
"err",
"\n",
"}"
] | // Query executes queries that return rows, and do not modify the database. If
// connection is nil, then the utility connection is used. | [
"Query",
"executes",
"queries",
"that",
"return",
"rows",
"and",
"do",
"not",
"modify",
"the",
"database",
".",
"If",
"connection",
"is",
"nil",
"then",
"the",
"utility",
"connection",
"is",
"used",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L927-L986 | train |
rqlite/rqlite | store/store.go | createDatabase | func (s *Store) createDatabase() error {
var db *sdb.DB
var err error
if !s.dbConf.Memory {
// as it will be rebuilt from (possibly) a snapshot and committed log entries.
if err := os.Remove(s.dbPath); err != nil && !os.IsNotExist(err) {
return err
}
db, err = sdb.New(s.dbPath, s.dbConf.DSN, false)
if err != nil {
return err
}
s.logger.Println("SQLite database opened at", s.dbPath)
} else {
db, err = sdb.New(s.dbPath, s.dbConf.DSN, true)
if err != nil {
return err
}
s.logger.Println("SQLite in-memory database opened")
}
s.db = db
return nil
} | go | func (s *Store) createDatabase() error {
var db *sdb.DB
var err error
if !s.dbConf.Memory {
// as it will be rebuilt from (possibly) a snapshot and committed log entries.
if err := os.Remove(s.dbPath); err != nil && !os.IsNotExist(err) {
return err
}
db, err = sdb.New(s.dbPath, s.dbConf.DSN, false)
if err != nil {
return err
}
s.logger.Println("SQLite database opened at", s.dbPath)
} else {
db, err = sdb.New(s.dbPath, s.dbConf.DSN, true)
if err != nil {
return err
}
s.logger.Println("SQLite in-memory database opened")
}
s.db = db
return nil
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"createDatabase",
"(",
")",
"error",
"{",
"var",
"db",
"*",
"sdb",
".",
"DB",
"\n",
"var",
"err",
"error",
"\n",
"if",
"!",
"s",
".",
"dbConf",
".",
"Memory",
"{",
"if",
"err",
":=",
"os",
".",
"Remove",
"(",
"s",
".",
"dbPath",
")",
";",
"err",
"!=",
"nil",
"&&",
"!",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"err",
"\n",
"}",
"\n",
"db",
",",
"err",
"=",
"sdb",
".",
"New",
"(",
"s",
".",
"dbPath",
",",
"s",
".",
"dbConf",
".",
"DSN",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"s",
".",
"logger",
".",
"Println",
"(",
"\"SQLite database opened at\"",
",",
"s",
".",
"dbPath",
")",
"\n",
"}",
"else",
"{",
"db",
",",
"err",
"=",
"sdb",
".",
"New",
"(",
"s",
".",
"dbPath",
",",
"s",
".",
"dbConf",
".",
"DSN",
",",
"true",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"s",
".",
"logger",
".",
"Println",
"(",
"\"SQLite in-memory database opened\"",
")",
"\n",
"}",
"\n",
"s",
".",
"db",
"=",
"db",
"\n",
"return",
"nil",
"\n",
"}"
] | // createDatabase creates the the in-memory or file-based database. | [
"createDatabase",
"creates",
"the",
"the",
"in",
"-",
"memory",
"or",
"file",
"-",
"based",
"database",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L989-L1011 | train |
rqlite/rqlite | store/store.go | remove | func (s *Store) remove(id string) error {
if s.raft.State() != raft.Leader {
return ErrNotLeader
}
f := s.raft.RemoveServer(raft.ServerID(id), 0, 0)
if f.Error() != nil {
if f.Error() == raft.ErrNotLeader {
return ErrNotLeader
}
return f.Error()
}
c, err := newCommand(metadataDelete, id)
if err != nil {
return err
}
b, err := json.Marshal(c)
if err != nil {
return err
}
f = s.raft.Apply(b, s.ApplyTimeout)
if e := f.(raft.Future); e.Error() != nil {
if e.Error() == raft.ErrNotLeader {
return ErrNotLeader
}
e.Error()
}
return nil
} | go | func (s *Store) remove(id string) error {
if s.raft.State() != raft.Leader {
return ErrNotLeader
}
f := s.raft.RemoveServer(raft.ServerID(id), 0, 0)
if f.Error() != nil {
if f.Error() == raft.ErrNotLeader {
return ErrNotLeader
}
return f.Error()
}
c, err := newCommand(metadataDelete, id)
if err != nil {
return err
}
b, err := json.Marshal(c)
if err != nil {
return err
}
f = s.raft.Apply(b, s.ApplyTimeout)
if e := f.(raft.Future); e.Error() != nil {
if e.Error() == raft.ErrNotLeader {
return ErrNotLeader
}
e.Error()
}
return nil
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"remove",
"(",
"id",
"string",
")",
"error",
"{",
"if",
"s",
".",
"raft",
".",
"State",
"(",
")",
"!=",
"raft",
".",
"Leader",
"{",
"return",
"ErrNotLeader",
"\n",
"}",
"\n",
"f",
":=",
"s",
".",
"raft",
".",
"RemoveServer",
"(",
"raft",
".",
"ServerID",
"(",
"id",
")",
",",
"0",
",",
"0",
")",
"\n",
"if",
"f",
".",
"Error",
"(",
")",
"!=",
"nil",
"{",
"if",
"f",
".",
"Error",
"(",
")",
"==",
"raft",
".",
"ErrNotLeader",
"{",
"return",
"ErrNotLeader",
"\n",
"}",
"\n",
"return",
"f",
".",
"Error",
"(",
")",
"\n",
"}",
"\n",
"c",
",",
"err",
":=",
"newCommand",
"(",
"metadataDelete",
",",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"b",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"c",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"f",
"=",
"s",
".",
"raft",
".",
"Apply",
"(",
"b",
",",
"s",
".",
"ApplyTimeout",
")",
"\n",
"if",
"e",
":=",
"f",
".",
"(",
"raft",
".",
"Future",
")",
";",
"e",
".",
"Error",
"(",
")",
"!=",
"nil",
"{",
"if",
"e",
".",
"Error",
"(",
")",
"==",
"raft",
".",
"ErrNotLeader",
"{",
"return",
"ErrNotLeader",
"\n",
"}",
"\n",
"e",
".",
"Error",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // remove removes the node, with the given ID, from the cluster. | [
"remove",
"removes",
"the",
"node",
"with",
"the",
"given",
"ID",
"from",
"the",
"cluster",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L1014-L1044 | train |
rqlite/rqlite | store/store.go | raftConfig | func (s *Store) raftConfig() *raft.Config {
config := raft.DefaultConfig()
if s.SnapshotThreshold != 0 {
config.SnapshotThreshold = s.SnapshotThreshold
}
if s.SnapshotInterval != 0 {
config.SnapshotInterval = s.SnapshotInterval
}
if s.HeartbeatTimeout != 0 {
config.HeartbeatTimeout = s.HeartbeatTimeout
}
return config
} | go | func (s *Store) raftConfig() *raft.Config {
config := raft.DefaultConfig()
if s.SnapshotThreshold != 0 {
config.SnapshotThreshold = s.SnapshotThreshold
}
if s.SnapshotInterval != 0 {
config.SnapshotInterval = s.SnapshotInterval
}
if s.HeartbeatTimeout != 0 {
config.HeartbeatTimeout = s.HeartbeatTimeout
}
return config
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"raftConfig",
"(",
")",
"*",
"raft",
".",
"Config",
"{",
"config",
":=",
"raft",
".",
"DefaultConfig",
"(",
")",
"\n",
"if",
"s",
".",
"SnapshotThreshold",
"!=",
"0",
"{",
"config",
".",
"SnapshotThreshold",
"=",
"s",
".",
"SnapshotThreshold",
"\n",
"}",
"\n",
"if",
"s",
".",
"SnapshotInterval",
"!=",
"0",
"{",
"config",
".",
"SnapshotInterval",
"=",
"s",
".",
"SnapshotInterval",
"\n",
"}",
"\n",
"if",
"s",
".",
"HeartbeatTimeout",
"!=",
"0",
"{",
"config",
".",
"HeartbeatTimeout",
"=",
"s",
".",
"HeartbeatTimeout",
"\n",
"}",
"\n",
"return",
"config",
"\n",
"}"
] | // raftConfig returns a new Raft config for the store. | [
"raftConfig",
"returns",
"a",
"new",
"Raft",
"config",
"for",
"the",
"store",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L1047-L1059 | train |
rqlite/rqlite | store/store.go | checkConnections | func (s *Store) checkConnections() {
s.wg.Add(1)
ticker := time.NewTicker(s.connPollPeriod)
go func() {
defer s.wg.Done()
defer ticker.Stop()
for {
select {
case <-s.done:
return
case <-ticker.C:
// This is not a 100% correct check, but is right almost all
// the time, and saves the node from most unneeded network
// access. Read https://github.com/rqlite/rqlite/issues/5
if !s.IsLeader() {
continue
}
var conns []*Connection
s.connsMu.RLock()
for _, c := range s.conns {
// Sometimes IDs are in the slice without a connection, if a
// connection is in process of being formed via consensus.
if c == nil || c.ID == defaultConnID {
continue
}
if c.IdleTimedOut() || c.TxTimedOut() {
conns = append(conns, c)
}
}
s.connsMu.RUnlock()
for _, c := range conns {
if err := c.Close(); err != nil {
if err == ErrNotLeader {
// Not an issue, the actual leader will close it.
continue
}
s.logger.Printf("%s failed to close: %s", c, err.Error())
}
s.logger.Printf("%s closed due to timeout", c)
// Only increment stat here to make testing easier.
stats.Add(numConnTimeouts, 1)
}
}
}
}()
} | go | func (s *Store) checkConnections() {
s.wg.Add(1)
ticker := time.NewTicker(s.connPollPeriod)
go func() {
defer s.wg.Done()
defer ticker.Stop()
for {
select {
case <-s.done:
return
case <-ticker.C:
// This is not a 100% correct check, but is right almost all
// the time, and saves the node from most unneeded network
// access. Read https://github.com/rqlite/rqlite/issues/5
if !s.IsLeader() {
continue
}
var conns []*Connection
s.connsMu.RLock()
for _, c := range s.conns {
// Sometimes IDs are in the slice without a connection, if a
// connection is in process of being formed via consensus.
if c == nil || c.ID == defaultConnID {
continue
}
if c.IdleTimedOut() || c.TxTimedOut() {
conns = append(conns, c)
}
}
s.connsMu.RUnlock()
for _, c := range conns {
if err := c.Close(); err != nil {
if err == ErrNotLeader {
// Not an issue, the actual leader will close it.
continue
}
s.logger.Printf("%s failed to close: %s", c, err.Error())
}
s.logger.Printf("%s closed due to timeout", c)
// Only increment stat here to make testing easier.
stats.Add(numConnTimeouts, 1)
}
}
}
}()
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"checkConnections",
"(",
")",
"{",
"s",
".",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"ticker",
":=",
"time",
".",
"NewTicker",
"(",
"s",
".",
"connPollPeriod",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"defer",
"s",
".",
"wg",
".",
"Done",
"(",
")",
"\n",
"defer",
"ticker",
".",
"Stop",
"(",
")",
"\n",
"for",
"{",
"select",
"{",
"case",
"<-",
"s",
".",
"done",
":",
"return",
"\n",
"case",
"<-",
"ticker",
".",
"C",
":",
"if",
"!",
"s",
".",
"IsLeader",
"(",
")",
"{",
"continue",
"\n",
"}",
"\n",
"var",
"conns",
"[",
"]",
"*",
"Connection",
"\n",
"s",
".",
"connsMu",
".",
"RLock",
"(",
")",
"\n",
"for",
"_",
",",
"c",
":=",
"range",
"s",
".",
"conns",
"{",
"if",
"c",
"==",
"nil",
"||",
"c",
".",
"ID",
"==",
"defaultConnID",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"c",
".",
"IdleTimedOut",
"(",
")",
"||",
"c",
".",
"TxTimedOut",
"(",
")",
"{",
"conns",
"=",
"append",
"(",
"conns",
",",
"c",
")",
"\n",
"}",
"\n",
"}",
"\n",
"s",
".",
"connsMu",
".",
"RUnlock",
"(",
")",
"\n",
"for",
"_",
",",
"c",
":=",
"range",
"conns",
"{",
"if",
"err",
":=",
"c",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"ErrNotLeader",
"{",
"continue",
"\n",
"}",
"\n",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"%s failed to close: %s\"",
",",
"c",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"%s closed due to timeout\"",
",",
"c",
")",
"\n",
"stats",
".",
"Add",
"(",
"numConnTimeouts",
",",
"1",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"}"
] | // checkConnections periodically checks which connections should
// close due to timeouts. | [
"checkConnections",
"periodically",
"checks",
"which",
"connections",
"should",
"close",
"due",
"to",
"timeouts",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L1063-L1110 | train |
rqlite/rqlite | store/store.go | database | func (s *Store) database(leader bool, dst io.Writer) error {
if leader && s.raft.State() != raft.Leader {
return ErrNotLeader
}
f, err := ioutil.TempFile("", "rqlilte-snap-")
if err != nil {
return err
}
if err := f.Close(); err != nil {
return err
}
os.Remove(f.Name())
db, err := sdb.New(f.Name(), "", false)
if err != nil {
return err
}
conn, err := db.Connect()
if err != nil {
return err
}
if err := s.dbConn.Backup(conn); err != nil {
return err
}
if err := conn.Close(); err != nil {
return err
}
of, err := os.Open(f.Name())
if err != nil {
return err
}
defer of.Close()
_, err = io.Copy(dst, of)
return err
} | go | func (s *Store) database(leader bool, dst io.Writer) error {
if leader && s.raft.State() != raft.Leader {
return ErrNotLeader
}
f, err := ioutil.TempFile("", "rqlilte-snap-")
if err != nil {
return err
}
if err := f.Close(); err != nil {
return err
}
os.Remove(f.Name())
db, err := sdb.New(f.Name(), "", false)
if err != nil {
return err
}
conn, err := db.Connect()
if err != nil {
return err
}
if err := s.dbConn.Backup(conn); err != nil {
return err
}
if err := conn.Close(); err != nil {
return err
}
of, err := os.Open(f.Name())
if err != nil {
return err
}
defer of.Close()
_, err = io.Copy(dst, of)
return err
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"database",
"(",
"leader",
"bool",
",",
"dst",
"io",
".",
"Writer",
")",
"error",
"{",
"if",
"leader",
"&&",
"s",
".",
"raft",
".",
"State",
"(",
")",
"!=",
"raft",
".",
"Leader",
"{",
"return",
"ErrNotLeader",
"\n",
"}",
"\n",
"f",
",",
"err",
":=",
"ioutil",
".",
"TempFile",
"(",
"\"\"",
",",
"\"rqlilte-snap-\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"f",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"os",
".",
"Remove",
"(",
"f",
".",
"Name",
"(",
")",
")",
"\n",
"db",
",",
"err",
":=",
"sdb",
".",
"New",
"(",
"f",
".",
"Name",
"(",
")",
",",
"\"\"",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"conn",
",",
"err",
":=",
"db",
".",
"Connect",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"s",
".",
"dbConn",
".",
"Backup",
"(",
"conn",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"conn",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"of",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"f",
".",
"Name",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"of",
".",
"Close",
"(",
")",
"\n",
"_",
",",
"err",
"=",
"io",
".",
"Copy",
"(",
"dst",
",",
"of",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // Database copies contents of the underlying SQLite file to dst | [
"Database",
"copies",
"contents",
"of",
"the",
"underlying",
"SQLite",
"file",
"to",
"dst"
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L1222-L1259 | train |
rqlite/rqlite | store/store.go | Snapshot | func (s *Store) Snapshot() (raft.FSMSnapshot, error) {
s.restoreMu.RLock()
defer s.restoreMu.RUnlock()
// Snapshots are not permitted while any connection has a transaction
// in progress, because it's not possible (not without a lot of extra
// code anyway) to capture the state of a connection during a transaction
// on that connection. Since only during Apply() can a connection change
// its transaction state, and Apply() is never called concurrently with
// this call, it's safe to check transaction state here across all connections.
if err := func() error {
s.connsMu.Lock()
defer s.connsMu.Unlock()
for _, c := range s.conns {
if c.TransactionActive() {
stats.Add(numSnaphotsBlocked, 1)
return ErrTransactionActive
}
}
return nil
}(); err != nil {
return nil, err
}
// Copy the database.
fsm := &fsmSnapshot{}
var buf bytes.Buffer
var err error
err = s.database(false, &buf)
if err != nil {
s.logger.Printf("failed to read database for snapshot: %s", err.Error())
return nil, err
}
fsm.database = buf.Bytes()
// Copy the node metadata.
fsm.meta, err = json.Marshal(s.meta)
if err != nil {
s.logger.Printf("failed to encode meta for snapshot: %s", err.Error())
return nil, err
}
// Copy the active connections.
fsm.connections, err = json.Marshal(s.conns)
if err != nil {
s.logger.Printf("failed to encode connections for snapshot: %s", err.Error())
return nil, err
}
stats.Add(numSnaphots, 1)
return fsm, nil
} | go | func (s *Store) Snapshot() (raft.FSMSnapshot, error) {
s.restoreMu.RLock()
defer s.restoreMu.RUnlock()
// Snapshots are not permitted while any connection has a transaction
// in progress, because it's not possible (not without a lot of extra
// code anyway) to capture the state of a connection during a transaction
// on that connection. Since only during Apply() can a connection change
// its transaction state, and Apply() is never called concurrently with
// this call, it's safe to check transaction state here across all connections.
if err := func() error {
s.connsMu.Lock()
defer s.connsMu.Unlock()
for _, c := range s.conns {
if c.TransactionActive() {
stats.Add(numSnaphotsBlocked, 1)
return ErrTransactionActive
}
}
return nil
}(); err != nil {
return nil, err
}
// Copy the database.
fsm := &fsmSnapshot{}
var buf bytes.Buffer
var err error
err = s.database(false, &buf)
if err != nil {
s.logger.Printf("failed to read database for snapshot: %s", err.Error())
return nil, err
}
fsm.database = buf.Bytes()
// Copy the node metadata.
fsm.meta, err = json.Marshal(s.meta)
if err != nil {
s.logger.Printf("failed to encode meta for snapshot: %s", err.Error())
return nil, err
}
// Copy the active connections.
fsm.connections, err = json.Marshal(s.conns)
if err != nil {
s.logger.Printf("failed to encode connections for snapshot: %s", err.Error())
return nil, err
}
stats.Add(numSnaphots, 1)
return fsm, nil
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"Snapshot",
"(",
")",
"(",
"raft",
".",
"FSMSnapshot",
",",
"error",
")",
"{",
"s",
".",
"restoreMu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"restoreMu",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"err",
":=",
"func",
"(",
")",
"error",
"{",
"s",
".",
"connsMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"connsMu",
".",
"Unlock",
"(",
")",
"\n",
"for",
"_",
",",
"c",
":=",
"range",
"s",
".",
"conns",
"{",
"if",
"c",
".",
"TransactionActive",
"(",
")",
"{",
"stats",
".",
"Add",
"(",
"numSnaphotsBlocked",
",",
"1",
")",
"\n",
"return",
"ErrTransactionActive",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"fsm",
":=",
"&",
"fsmSnapshot",
"{",
"}",
"\n",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"var",
"err",
"error",
"\n",
"err",
"=",
"s",
".",
"database",
"(",
"false",
",",
"&",
"buf",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"failed to read database for snapshot: %s\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"fsm",
".",
"database",
"=",
"buf",
".",
"Bytes",
"(",
")",
"\n",
"fsm",
".",
"meta",
",",
"err",
"=",
"json",
".",
"Marshal",
"(",
"s",
".",
"meta",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"failed to encode meta for snapshot: %s\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"fsm",
".",
"connections",
",",
"err",
"=",
"json",
".",
"Marshal",
"(",
"s",
".",
"conns",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"failed to encode connections for snapshot: %s\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"stats",
".",
"Add",
"(",
"numSnaphots",
",",
"1",
")",
"\n",
"return",
"fsm",
",",
"nil",
"\n",
"}"
] | // Snapshot returns a snapshot of the store. The caller must ensure that
// no Raft transaction is taking place during this call. Hashicorp Raft
// guarantees that this function will not be called concurrently with Apply. | [
"Snapshot",
"returns",
"a",
"snapshot",
"of",
"the",
"store",
".",
"The",
"caller",
"must",
"ensure",
"that",
"no",
"Raft",
"transaction",
"is",
"taking",
"place",
"during",
"this",
"call",
".",
"Hashicorp",
"Raft",
"guarantees",
"that",
"this",
"function",
"will",
"not",
"be",
"called",
"concurrently",
"with",
"Apply",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L1264-L1315 | train |
rqlite/rqlite | store/store.go | RegisterObserver | func (s *Store) RegisterObserver(o *raft.Observer) {
s.raft.RegisterObserver(o)
} | go | func (s *Store) RegisterObserver(o *raft.Observer) {
s.raft.RegisterObserver(o)
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"RegisterObserver",
"(",
"o",
"*",
"raft",
".",
"Observer",
")",
"{",
"s",
".",
"raft",
".",
"RegisterObserver",
"(",
"o",
")",
"\n",
"}"
] | // RegisterObserver registers an observer of Raft events | [
"RegisterObserver",
"registers",
"an",
"observer",
"of",
"Raft",
"events"
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L1410-L1412 | train |
rqlite/rqlite | store/store.go | DeregisterObserver | func (s *Store) DeregisterObserver(o *raft.Observer) {
s.raft.DeregisterObserver(o)
} | go | func (s *Store) DeregisterObserver(o *raft.Observer) {
s.raft.DeregisterObserver(o)
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"DeregisterObserver",
"(",
"o",
"*",
"raft",
".",
"Observer",
")",
"{",
"s",
".",
"raft",
".",
"DeregisterObserver",
"(",
"o",
")",
"\n",
"}"
] | // DeregisterObserver deregisters an observer of Raft events | [
"DeregisterObserver",
"deregisters",
"an",
"observer",
"of",
"Raft",
"events"
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L1415-L1417 | train |
rqlite/rqlite | store/store.go | pathExists | func pathExists(p string) bool {
if _, err := os.Lstat(p); err != nil && os.IsNotExist(err) {
return false
}
return true
} | go | func pathExists(p string) bool {
if _, err := os.Lstat(p); err != nil && os.IsNotExist(err) {
return false
}
return true
} | [
"func",
"pathExists",
"(",
"p",
"string",
")",
"bool",
"{",
"if",
"_",
",",
"err",
":=",
"os",
".",
"Lstat",
"(",
"p",
")",
";",
"err",
"!=",
"nil",
"&&",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // pathExists returns true if the given path exists. | [
"pathExists",
"returns",
"true",
"if",
"the",
"given",
"path",
"exists",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L1473-L1478 | train |
rqlite/rqlite | store/store.go | tempfile | func tempfile() (*os.File, error) {
f, err := ioutil.TempFile("", "rqlilte-snap-")
if err != nil {
return nil, err
}
return f, nil
} | go | func tempfile() (*os.File, error) {
f, err := ioutil.TempFile("", "rqlilte-snap-")
if err != nil {
return nil, err
}
return f, nil
} | [
"func",
"tempfile",
"(",
")",
"(",
"*",
"os",
".",
"File",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"ioutil",
".",
"TempFile",
"(",
"\"\"",
",",
"\"rqlilte-snap-\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"f",
",",
"nil",
"\n",
"}"
] | // tempfile returns a temporary file for use | [
"tempfile",
"returns",
"a",
"temporary",
"file",
"for",
"use"
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/store.go#L1481-L1487 | train |
rqlite/rqlite | http/service.go | New | func New(addr string, store Store, credentials CredentialStore) *Service {
return &Service{
addr: addr,
store: store,
start: time.Now(),
statuses: make(map[string]Statuser),
credentialStore: credentials,
logger: log.New(os.Stderr, "[http] ", log.LstdFlags),
}
} | go | func New(addr string, store Store, credentials CredentialStore) *Service {
return &Service{
addr: addr,
store: store,
start: time.Now(),
statuses: make(map[string]Statuser),
credentialStore: credentials,
logger: log.New(os.Stderr, "[http] ", log.LstdFlags),
}
} | [
"func",
"New",
"(",
"addr",
"string",
",",
"store",
"Store",
",",
"credentials",
"CredentialStore",
")",
"*",
"Service",
"{",
"return",
"&",
"Service",
"{",
"addr",
":",
"addr",
",",
"store",
":",
"store",
",",
"start",
":",
"time",
".",
"Now",
"(",
")",
",",
"statuses",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"Statuser",
")",
",",
"credentialStore",
":",
"credentials",
",",
"logger",
":",
"log",
".",
"New",
"(",
"os",
".",
"Stderr",
",",
"\"[http] \"",
",",
"log",
".",
"LstdFlags",
")",
",",
"}",
"\n",
"}"
] | // New returns an uninitialized HTTP service. If credentials is nil, then
// the service performs no authentication and authorization checks. | [
"New",
"returns",
"an",
"uninitialized",
"HTTP",
"service",
".",
"If",
"credentials",
"is",
"nil",
"then",
"the",
"service",
"performs",
"no",
"authentication",
"and",
"authorization",
"checks",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L190-L199 | train |
rqlite/rqlite | http/service.go | ServeHTTP | func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.rootHandler.Handler(s).ServeHTTP(w, r)
} | go | func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.rootHandler.Handler(s).ServeHTTP(w, r)
} | [
"func",
"(",
"s",
"*",
"Service",
")",
"ServeHTTP",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"s",
".",
"rootHandler",
".",
"Handler",
"(",
"s",
")",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
")",
"\n",
"}"
] | // ServeHTTP allows Service to serve HTTP requests. | [
"ServeHTTP",
"allows",
"Service",
"to",
"serve",
"HTTP",
"requests",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L245-L247 | train |
rqlite/rqlite | http/service.go | RegisterStatus | func (s *Service) RegisterStatus(key string, stat Statuser) error {
s.statusMu.Lock()
defer s.statusMu.Unlock()
if _, ok := s.statuses[key]; ok {
return fmt.Errorf("status already registered with key %s", key)
}
s.statuses[key] = stat
return nil
} | go | func (s *Service) RegisterStatus(key string, stat Statuser) error {
s.statusMu.Lock()
defer s.statusMu.Unlock()
if _, ok := s.statuses[key]; ok {
return fmt.Errorf("status already registered with key %s", key)
}
s.statuses[key] = stat
return nil
} | [
"func",
"(",
"s",
"*",
"Service",
")",
"RegisterStatus",
"(",
"key",
"string",
",",
"stat",
"Statuser",
")",
"error",
"{",
"s",
".",
"statusMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"statusMu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"s",
".",
"statuses",
"[",
"key",
"]",
";",
"ok",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"status already registered with key %s\"",
",",
"key",
")",
"\n",
"}",
"\n",
"s",
".",
"statuses",
"[",
"key",
"]",
"=",
"stat",
"\n",
"return",
"nil",
"\n",
"}"
] | // RegisterStatus allows other modules to register status for serving over HTTP. | [
"RegisterStatus",
"allows",
"other",
"modules",
"to",
"register",
"status",
"for",
"serving",
"over",
"HTTP",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L250-L260 | train |
rqlite/rqlite | http/service.go | createConnection | func (s *Service) createConnection(w http.ResponseWriter, r *http.Request) {
opts := store.ConnectionOptions{
IdleTimeout: s.ConnIdleTimeout,
TxTimeout: s.ConnTxTimeout,
}
d, b, err := txTimeout(r)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
if b {
opts.TxTimeout = d
}
d, b, err = idleTimeout(r)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
if b {
opts.IdleTimeout = d
}
conn, err := s.store.Connect(&opts)
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
w.Header().Set("Location", s.FormConnectionURL(r, conn.ID))
w.WriteHeader(http.StatusCreated)
} | go | func (s *Service) createConnection(w http.ResponseWriter, r *http.Request) {
opts := store.ConnectionOptions{
IdleTimeout: s.ConnIdleTimeout,
TxTimeout: s.ConnTxTimeout,
}
d, b, err := txTimeout(r)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
if b {
opts.TxTimeout = d
}
d, b, err = idleTimeout(r)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
if b {
opts.IdleTimeout = d
}
conn, err := s.store.Connect(&opts)
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
w.Header().Set("Location", s.FormConnectionURL(r, conn.ID))
w.WriteHeader(http.StatusCreated)
} | [
"func",
"(",
"s",
"*",
"Service",
")",
"createConnection",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"opts",
":=",
"store",
".",
"ConnectionOptions",
"{",
"IdleTimeout",
":",
"s",
".",
"ConnIdleTimeout",
",",
"TxTimeout",
":",
"s",
".",
"ConnTxTimeout",
",",
"}",
"\n",
"d",
",",
"b",
",",
"err",
":=",
"txTimeout",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"b",
"{",
"opts",
".",
"TxTimeout",
"=",
"d",
"\n",
"}",
"\n",
"d",
",",
"b",
",",
"err",
"=",
"idleTimeout",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"b",
"{",
"opts",
".",
"IdleTimeout",
"=",
"d",
"\n",
"}",
"\n",
"conn",
",",
"err",
":=",
"s",
".",
"store",
".",
"Connect",
"(",
"&",
"opts",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusServiceUnavailable",
")",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"Location\"",
",",
"s",
".",
"FormConnectionURL",
"(",
"r",
",",
"conn",
".",
"ID",
")",
")",
"\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusCreated",
")",
"\n",
"}"
] | // createConnection creates a connection and returns its ID. | [
"createConnection",
"creates",
"a",
"connection",
"and",
"returns",
"its",
"ID",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L263-L294 | train |
rqlite/rqlite | http/service.go | deleteConnection | func (s *Service) deleteConnection(id uint64) error {
conn, ok := s.store.Connection(id)
if !ok {
return nil
}
return conn.Close()
} | go | func (s *Service) deleteConnection(id uint64) error {
conn, ok := s.store.Connection(id)
if !ok {
return nil
}
return conn.Close()
} | [
"func",
"(",
"s",
"*",
"Service",
")",
"deleteConnection",
"(",
"id",
"uint64",
")",
"error",
"{",
"conn",
",",
"ok",
":=",
"s",
".",
"store",
".",
"Connection",
"(",
"id",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"conn",
".",
"Close",
"(",
")",
"\n",
"}"
] | // deleteConnection closes a connection and makes it unavailable for
// future use. | [
"deleteConnection",
"closes",
"a",
"connection",
"and",
"makes",
"it",
"unavailable",
"for",
"future",
"use",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L298-L304 | train |
rqlite/rqlite | http/service.go | handleJoin | func (s *Service) handleJoin(w http.ResponseWriter, r *http.Request) {
b, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
md := map[string]interface{}{}
if err := json.Unmarshal(b, &md); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
remoteID, ok := md["id"]
if !ok {
w.WriteHeader(http.StatusBadRequest)
return
}
remoteAddr, ok := md["addr"]
if !ok {
w.WriteHeader(http.StatusBadRequest)
return
}
var m map[string]string
if _, ok := md["meta"].(map[string]interface{}); ok {
m = make(map[string]string)
for k, v := range md["meta"].(map[string]interface{}) {
m[k] = v.(string)
}
}
if err := s.store.Join(remoteID.(string), remoteAddr.(string), m); err != nil {
if err == store.ErrNotLeader {
leader := s.leaderAPIAddr()
if leader == "" {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
redirect := s.FormRedirect(r, leader)
http.Redirect(w, r, redirect, http.StatusMovedPermanently)
return
}
b := bytes.NewBufferString(err.Error())
w.WriteHeader(http.StatusInternalServerError)
w.Write(b.Bytes())
return
}
} | go | func (s *Service) handleJoin(w http.ResponseWriter, r *http.Request) {
b, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
md := map[string]interface{}{}
if err := json.Unmarshal(b, &md); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
remoteID, ok := md["id"]
if !ok {
w.WriteHeader(http.StatusBadRequest)
return
}
remoteAddr, ok := md["addr"]
if !ok {
w.WriteHeader(http.StatusBadRequest)
return
}
var m map[string]string
if _, ok := md["meta"].(map[string]interface{}); ok {
m = make(map[string]string)
for k, v := range md["meta"].(map[string]interface{}) {
m[k] = v.(string)
}
}
if err := s.store.Join(remoteID.(string), remoteAddr.(string), m); err != nil {
if err == store.ErrNotLeader {
leader := s.leaderAPIAddr()
if leader == "" {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
redirect := s.FormRedirect(r, leader)
http.Redirect(w, r, redirect, http.StatusMovedPermanently)
return
}
b := bytes.NewBufferString(err.Error())
w.WriteHeader(http.StatusInternalServerError)
w.Write(b.Bytes())
return
}
} | [
"func",
"(",
"s",
"*",
"Service",
")",
"handleJoin",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"b",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"r",
".",
"Body",
")",
"\n",
"defer",
"r",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n",
"md",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"b",
",",
"&",
"md",
")",
";",
"err",
"!=",
"nil",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n",
"remoteID",
",",
"ok",
":=",
"md",
"[",
"\"id\"",
"]",
"\n",
"if",
"!",
"ok",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n",
"remoteAddr",
",",
"ok",
":=",
"md",
"[",
"\"addr\"",
"]",
"\n",
"if",
"!",
"ok",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n",
"var",
"m",
"map",
"[",
"string",
"]",
"string",
"\n",
"if",
"_",
",",
"ok",
":=",
"md",
"[",
"\"meta\"",
"]",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"m",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"md",
"[",
"\"meta\"",
"]",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"{",
"m",
"[",
"k",
"]",
"=",
"v",
".",
"(",
"string",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"err",
":=",
"s",
".",
"store",
".",
"Join",
"(",
"remoteID",
".",
"(",
"string",
")",
",",
"remoteAddr",
".",
"(",
"string",
")",
",",
"m",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"store",
".",
"ErrNotLeader",
"{",
"leader",
":=",
"s",
".",
"leaderAPIAddr",
"(",
")",
"\n",
"if",
"leader",
"==",
"\"\"",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusServiceUnavailable",
")",
"\n",
"return",
"\n",
"}",
"\n",
"redirect",
":=",
"s",
".",
"FormRedirect",
"(",
"r",
",",
"leader",
")",
"\n",
"http",
".",
"Redirect",
"(",
"w",
",",
"r",
",",
"redirect",
",",
"http",
".",
"StatusMovedPermanently",
")",
"\n",
"return",
"\n",
"}",
"\n",
"b",
":=",
"bytes",
".",
"NewBufferString",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"w",
".",
"Write",
"(",
"b",
".",
"Bytes",
"(",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}"
] | // handleJoin handles cluster-join requests from other nodes. | [
"handleJoin",
"handles",
"cluster",
"-",
"join",
"requests",
"from",
"other",
"nodes",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L307-L356 | train |
rqlite/rqlite | http/service.go | handleRemove | func (s *Service) handleRemove(w http.ResponseWriter, r *http.Request) {
b, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
m := map[string]string{}
if err := json.Unmarshal(b, &m); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
if len(m) != 1 {
w.WriteHeader(http.StatusBadRequest)
return
}
remoteID, ok := m["id"]
if !ok {
w.WriteHeader(http.StatusBadRequest)
return
}
if err := s.store.Remove(remoteID); err != nil {
if err == store.ErrNotLeader {
leader := s.leaderAPIAddr()
if leader == "" {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
redirect := s.FormRedirect(r, leader)
http.Redirect(w, r, redirect, http.StatusMovedPermanently)
return
}
w.WriteHeader(http.StatusInternalServerError)
return
}
} | go | func (s *Service) handleRemove(w http.ResponseWriter, r *http.Request) {
b, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
m := map[string]string{}
if err := json.Unmarshal(b, &m); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
if len(m) != 1 {
w.WriteHeader(http.StatusBadRequest)
return
}
remoteID, ok := m["id"]
if !ok {
w.WriteHeader(http.StatusBadRequest)
return
}
if err := s.store.Remove(remoteID); err != nil {
if err == store.ErrNotLeader {
leader := s.leaderAPIAddr()
if leader == "" {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
redirect := s.FormRedirect(r, leader)
http.Redirect(w, r, redirect, http.StatusMovedPermanently)
return
}
w.WriteHeader(http.StatusInternalServerError)
return
}
} | [
"func",
"(",
"s",
"*",
"Service",
")",
"handleRemove",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"b",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"r",
".",
"Body",
")",
"\n",
"defer",
"r",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n",
"m",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"b",
",",
"&",
"m",
")",
";",
"err",
"!=",
"nil",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"len",
"(",
"m",
")",
"!=",
"1",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n",
"remoteID",
",",
"ok",
":=",
"m",
"[",
"\"id\"",
"]",
"\n",
"if",
"!",
"ok",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"err",
":=",
"s",
".",
"store",
".",
"Remove",
"(",
"remoteID",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"store",
".",
"ErrNotLeader",
"{",
"leader",
":=",
"s",
".",
"leaderAPIAddr",
"(",
")",
"\n",
"if",
"leader",
"==",
"\"\"",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusServiceUnavailable",
")",
"\n",
"return",
"\n",
"}",
"\n",
"redirect",
":=",
"s",
".",
"FormRedirect",
"(",
"r",
",",
"leader",
")",
"\n",
"http",
".",
"Redirect",
"(",
"w",
",",
"r",
",",
"redirect",
",",
"http",
".",
"StatusMovedPermanently",
")",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}"
] | // handleRemove handles cluster-remove requests. | [
"handleRemove",
"handles",
"cluster",
"-",
"remove",
"requests",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L359-L399 | train |
rqlite/rqlite | http/service.go | handleBackup | func (s *Service) handleBackup(w http.ResponseWriter, r *http.Request) {
noLeader, err := noLeader(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
bf, err := backupFormat(w, r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = s.store.Backup(!noLeader, bf, w)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
s.lastBackup = time.Now()
} | go | func (s *Service) handleBackup(w http.ResponseWriter, r *http.Request) {
noLeader, err := noLeader(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
bf, err := backupFormat(w, r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = s.store.Backup(!noLeader, bf, w)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
s.lastBackup = time.Now()
} | [
"func",
"(",
"s",
"*",
"Service",
")",
"handleBackup",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"noLeader",
",",
"err",
":=",
"noLeader",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"bf",
",",
"err",
":=",
"backupFormat",
"(",
"w",
",",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"err",
"=",
"s",
".",
"store",
".",
"Backup",
"(",
"!",
"noLeader",
",",
"bf",
",",
"w",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"s",
".",
"lastBackup",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"}"
] | // handleBackup returns the consistent database snapshot. | [
"handleBackup",
"returns",
"the",
"consistent",
"database",
"snapshot",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L402-L422 | train |
rqlite/rqlite | http/service.go | handleLoad | func (s *Service) handleLoad(w http.ResponseWriter, r *http.Request) {
timings, err := timings(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
b, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
var resp Response
queries := []string{string(b)}
results, err := s.store.ExecuteOrAbort(&store.ExecuteRequest{queries, timings, false})
if err != nil {
if err == store.ErrNotLeader {
leader := s.leaderAPIAddr()
if leader == "" {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
redirect := s.FormRedirect(r, leader)
http.Redirect(w, r, redirect, http.StatusMovedPermanently)
return
}
resp.Error = err.Error()
} else {
resp.Results = results.Results
if timings {
resp.Time = results.Time
}
resp.Raft = &results.Raft
}
writeResponse(w, r, &resp)
} | go | func (s *Service) handleLoad(w http.ResponseWriter, r *http.Request) {
timings, err := timings(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
b, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
var resp Response
queries := []string{string(b)}
results, err := s.store.ExecuteOrAbort(&store.ExecuteRequest{queries, timings, false})
if err != nil {
if err == store.ErrNotLeader {
leader := s.leaderAPIAddr()
if leader == "" {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
redirect := s.FormRedirect(r, leader)
http.Redirect(w, r, redirect, http.StatusMovedPermanently)
return
}
resp.Error = err.Error()
} else {
resp.Results = results.Results
if timings {
resp.Time = results.Time
}
resp.Raft = &results.Raft
}
writeResponse(w, r, &resp)
} | [
"func",
"(",
"s",
"*",
"Service",
")",
"handleLoad",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"timings",
",",
"err",
":=",
"timings",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"b",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"r",
".",
"Body",
")",
"\n",
"defer",
"r",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n",
"var",
"resp",
"Response",
"\n",
"queries",
":=",
"[",
"]",
"string",
"{",
"string",
"(",
"b",
")",
"}",
"\n",
"results",
",",
"err",
":=",
"s",
".",
"store",
".",
"ExecuteOrAbort",
"(",
"&",
"store",
".",
"ExecuteRequest",
"{",
"queries",
",",
"timings",
",",
"false",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"store",
".",
"ErrNotLeader",
"{",
"leader",
":=",
"s",
".",
"leaderAPIAddr",
"(",
")",
"\n",
"if",
"leader",
"==",
"\"\"",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusServiceUnavailable",
")",
"\n",
"return",
"\n",
"}",
"\n",
"redirect",
":=",
"s",
".",
"FormRedirect",
"(",
"r",
",",
"leader",
")",
"\n",
"http",
".",
"Redirect",
"(",
"w",
",",
"r",
",",
"redirect",
",",
"http",
".",
"StatusMovedPermanently",
")",
"\n",
"return",
"\n",
"}",
"\n",
"resp",
".",
"Error",
"=",
"err",
".",
"Error",
"(",
")",
"\n",
"}",
"else",
"{",
"resp",
".",
"Results",
"=",
"results",
".",
"Results",
"\n",
"if",
"timings",
"{",
"resp",
".",
"Time",
"=",
"results",
".",
"Time",
"\n",
"}",
"\n",
"resp",
".",
"Raft",
"=",
"&",
"results",
".",
"Raft",
"\n",
"}",
"\n",
"writeResponse",
"(",
"w",
",",
"r",
",",
"&",
"resp",
")",
"\n",
"}"
] | // handleLoad loads the state contained in a .dump output. | [
"handleLoad",
"loads",
"the",
"state",
"contained",
"in",
"a",
".",
"dump",
"output",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L425-L463 | train |
rqlite/rqlite | http/service.go | handleStatus | func (s *Service) handleStatus(w http.ResponseWriter, r *http.Request) {
results, err := s.store.Stats()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
rt := map[string]interface{}{
"GOARCH": runtime.GOARCH,
"GOOS": runtime.GOOS,
"GOMAXPROCS": runtime.GOMAXPROCS(0),
"num_cpu": runtime.NumCPU(),
"num_goroutine": runtime.NumGoroutine(),
"version": runtime.Version(),
}
httpStatus := map[string]interface{}{
"addr": s.Addr().String(),
"auth": prettyEnabled(s.credentialStore != nil),
"redirect": s.leaderAPIAddr(),
"conn_idle_timeout": s.ConnIdleTimeout.String(),
"conn_tx_timeout": s.ConnTxTimeout.String(),
}
nodeStatus := map[string]interface{}{
"start_time": s.start,
"uptime": time.Since(s.start).String(),
}
// Build the status response.
status := map[string]interface{}{
"runtime": rt,
"store": results,
"http": httpStatus,
"node": nodeStatus,
}
if !s.lastBackup.IsZero() {
status["last_backup_time"] = s.lastBackup
}
if s.BuildInfo != nil {
status["build"] = s.BuildInfo
}
// Add any registered statusers.
func() {
s.statusMu.RLock()
defer s.statusMu.RUnlock()
for k, v := range s.statuses {
stat, err := v.Stats()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
status[k] = stat
}
}()
pretty, _ := isPretty(r)
var b []byte
if pretty {
b, err = json.MarshalIndent(status, "", " ")
} else {
b, err = json.Marshal(status)
}
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
} else {
_, err = w.Write([]byte(b))
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
}
}
} | go | func (s *Service) handleStatus(w http.ResponseWriter, r *http.Request) {
results, err := s.store.Stats()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
rt := map[string]interface{}{
"GOARCH": runtime.GOARCH,
"GOOS": runtime.GOOS,
"GOMAXPROCS": runtime.GOMAXPROCS(0),
"num_cpu": runtime.NumCPU(),
"num_goroutine": runtime.NumGoroutine(),
"version": runtime.Version(),
}
httpStatus := map[string]interface{}{
"addr": s.Addr().String(),
"auth": prettyEnabled(s.credentialStore != nil),
"redirect": s.leaderAPIAddr(),
"conn_idle_timeout": s.ConnIdleTimeout.String(),
"conn_tx_timeout": s.ConnTxTimeout.String(),
}
nodeStatus := map[string]interface{}{
"start_time": s.start,
"uptime": time.Since(s.start).String(),
}
// Build the status response.
status := map[string]interface{}{
"runtime": rt,
"store": results,
"http": httpStatus,
"node": nodeStatus,
}
if !s.lastBackup.IsZero() {
status["last_backup_time"] = s.lastBackup
}
if s.BuildInfo != nil {
status["build"] = s.BuildInfo
}
// Add any registered statusers.
func() {
s.statusMu.RLock()
defer s.statusMu.RUnlock()
for k, v := range s.statuses {
stat, err := v.Stats()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
status[k] = stat
}
}()
pretty, _ := isPretty(r)
var b []byte
if pretty {
b, err = json.MarshalIndent(status, "", " ")
} else {
b, err = json.Marshal(status)
}
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
} else {
_, err = w.Write([]byte(b))
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
}
}
} | [
"func",
"(",
"s",
"*",
"Service",
")",
"handleStatus",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"results",
",",
"err",
":=",
"s",
".",
"store",
".",
"Stats",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"rt",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"GOARCH\"",
":",
"runtime",
".",
"GOARCH",
",",
"\"GOOS\"",
":",
"runtime",
".",
"GOOS",
",",
"\"GOMAXPROCS\"",
":",
"runtime",
".",
"GOMAXPROCS",
"(",
"0",
")",
",",
"\"num_cpu\"",
":",
"runtime",
".",
"NumCPU",
"(",
")",
",",
"\"num_goroutine\"",
":",
"runtime",
".",
"NumGoroutine",
"(",
")",
",",
"\"version\"",
":",
"runtime",
".",
"Version",
"(",
")",
",",
"}",
"\n",
"httpStatus",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"addr\"",
":",
"s",
".",
"Addr",
"(",
")",
".",
"String",
"(",
")",
",",
"\"auth\"",
":",
"prettyEnabled",
"(",
"s",
".",
"credentialStore",
"!=",
"nil",
")",
",",
"\"redirect\"",
":",
"s",
".",
"leaderAPIAddr",
"(",
")",
",",
"\"conn_idle_timeout\"",
":",
"s",
".",
"ConnIdleTimeout",
".",
"String",
"(",
")",
",",
"\"conn_tx_timeout\"",
":",
"s",
".",
"ConnTxTimeout",
".",
"String",
"(",
")",
",",
"}",
"\n",
"nodeStatus",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"start_time\"",
":",
"s",
".",
"start",
",",
"\"uptime\"",
":",
"time",
".",
"Since",
"(",
"s",
".",
"start",
")",
".",
"String",
"(",
")",
",",
"}",
"\n",
"status",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"runtime\"",
":",
"rt",
",",
"\"store\"",
":",
"results",
",",
"\"http\"",
":",
"httpStatus",
",",
"\"node\"",
":",
"nodeStatus",
",",
"}",
"\n",
"if",
"!",
"s",
".",
"lastBackup",
".",
"IsZero",
"(",
")",
"{",
"status",
"[",
"\"last_backup_time\"",
"]",
"=",
"s",
".",
"lastBackup",
"\n",
"}",
"\n",
"if",
"s",
".",
"BuildInfo",
"!=",
"nil",
"{",
"status",
"[",
"\"build\"",
"]",
"=",
"s",
".",
"BuildInfo",
"\n",
"}",
"\n",
"func",
"(",
")",
"{",
"s",
".",
"statusMu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"statusMu",
".",
"RUnlock",
"(",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"s",
".",
"statuses",
"{",
"stat",
",",
"err",
":=",
"v",
".",
"Stats",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"status",
"[",
"k",
"]",
"=",
"stat",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"pretty",
",",
"_",
":=",
"isPretty",
"(",
"r",
")",
"\n",
"var",
"b",
"[",
"]",
"byte",
"\n",
"if",
"pretty",
"{",
"b",
",",
"err",
"=",
"json",
".",
"MarshalIndent",
"(",
"status",
",",
"\"\"",
",",
"\" \"",
")",
"\n",
"}",
"else",
"{",
"b",
",",
"err",
"=",
"json",
".",
"Marshal",
"(",
"status",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"}",
"else",
"{",
"_",
",",
"err",
"=",
"w",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"b",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // handleStatus returns status on the system. | [
"handleStatus",
"returns",
"status",
"on",
"the",
"system",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L466-L538 | train |
rqlite/rqlite | http/service.go | handleExecute | func (s *Service) handleExecute(connID uint64, w http.ResponseWriter, r *http.Request) {
isAtomic, err := isAtomic(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
timings, err := timings(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
b, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
queries := []string{}
if err := json.Unmarshal(b, &queries); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Get the right executer object.
var execer Execer
if connID == defaultConnID {
execer = s.store
} else {
c, ok := s.store.Connection(connID)
if !ok {
http.Error(w, "connection not found", http.StatusNotFound)
return
}
execer = c
}
var resp Response
results, err := execer.Execute(&store.ExecuteRequest{queries, timings, isAtomic})
if err != nil {
if err == store.ErrNotLeader {
leader := s.leaderAPIAddr()
if leader == "" {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
redirect := s.FormRedirect(r, leader)
http.Redirect(w, r, redirect, http.StatusMovedPermanently)
return
}
resp.Error = err.Error()
} else {
resp.Results = results.Results
if timings {
resp.Time = results.Time
}
resp.Raft = &results.Raft
}
writeResponse(w, r, &resp)
} | go | func (s *Service) handleExecute(connID uint64, w http.ResponseWriter, r *http.Request) {
isAtomic, err := isAtomic(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
timings, err := timings(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
b, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
queries := []string{}
if err := json.Unmarshal(b, &queries); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Get the right executer object.
var execer Execer
if connID == defaultConnID {
execer = s.store
} else {
c, ok := s.store.Connection(connID)
if !ok {
http.Error(w, "connection not found", http.StatusNotFound)
return
}
execer = c
}
var resp Response
results, err := execer.Execute(&store.ExecuteRequest{queries, timings, isAtomic})
if err != nil {
if err == store.ErrNotLeader {
leader := s.leaderAPIAddr()
if leader == "" {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
redirect := s.FormRedirect(r, leader)
http.Redirect(w, r, redirect, http.StatusMovedPermanently)
return
}
resp.Error = err.Error()
} else {
resp.Results = results.Results
if timings {
resp.Time = results.Time
}
resp.Raft = &results.Raft
}
writeResponse(w, r, &resp)
} | [
"func",
"(",
"s",
"*",
"Service",
")",
"handleExecute",
"(",
"connID",
"uint64",
",",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"isAtomic",
",",
"err",
":=",
"isAtomic",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"timings",
",",
"err",
":=",
"timings",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"b",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"r",
".",
"Body",
")",
"\n",
"defer",
"r",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n",
"queries",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"b",
",",
"&",
"queries",
")",
";",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n",
"var",
"execer",
"Execer",
"\n",
"if",
"connID",
"==",
"defaultConnID",
"{",
"execer",
"=",
"s",
".",
"store",
"\n",
"}",
"else",
"{",
"c",
",",
"ok",
":=",
"s",
".",
"store",
".",
"Connection",
"(",
"connID",
")",
"\n",
"if",
"!",
"ok",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"connection not found\"",
",",
"http",
".",
"StatusNotFound",
")",
"\n",
"return",
"\n",
"}",
"\n",
"execer",
"=",
"c",
"\n",
"}",
"\n",
"var",
"resp",
"Response",
"\n",
"results",
",",
"err",
":=",
"execer",
".",
"Execute",
"(",
"&",
"store",
".",
"ExecuteRequest",
"{",
"queries",
",",
"timings",
",",
"isAtomic",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"store",
".",
"ErrNotLeader",
"{",
"leader",
":=",
"s",
".",
"leaderAPIAddr",
"(",
")",
"\n",
"if",
"leader",
"==",
"\"\"",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusServiceUnavailable",
")",
"\n",
"return",
"\n",
"}",
"\n",
"redirect",
":=",
"s",
".",
"FormRedirect",
"(",
"r",
",",
"leader",
")",
"\n",
"http",
".",
"Redirect",
"(",
"w",
",",
"r",
",",
"redirect",
",",
"http",
".",
"StatusMovedPermanently",
")",
"\n",
"return",
"\n",
"}",
"\n",
"resp",
".",
"Error",
"=",
"err",
".",
"Error",
"(",
")",
"\n",
"}",
"else",
"{",
"resp",
".",
"Results",
"=",
"results",
".",
"Results",
"\n",
"if",
"timings",
"{",
"resp",
".",
"Time",
"=",
"results",
".",
"Time",
"\n",
"}",
"\n",
"resp",
".",
"Raft",
"=",
"&",
"results",
".",
"Raft",
"\n",
"}",
"\n",
"writeResponse",
"(",
"w",
",",
"r",
",",
"&",
"resp",
")",
"\n",
"}"
] | // handleExecute handles queries that modify the database. | [
"handleExecute",
"handles",
"queries",
"that",
"modify",
"the",
"database",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L541-L603 | train |
rqlite/rqlite | http/service.go | handleQuery | func (s *Service) handleQuery(connID uint64, w http.ResponseWriter, r *http.Request) {
isAtomic, err := isAtomic(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
timings, err := timings(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
lvl, err := level(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Get the query statement(s), and do tx if necessary.
queries, err := requestQueries(r)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
// Get the right queryer object.
var queryer Queryer
if connID == defaultConnID {
queryer = s.store
} else {
c, ok := s.store.Connection(connID)
if !ok {
http.Error(w, "connection not found", http.StatusNotFound)
return
}
queryer = c
}
var resp Response
results, err := queryer.Query(&store.QueryRequest{queries, timings, isAtomic, lvl})
if err != nil {
if err == store.ErrNotLeader {
leader := s.leaderAPIAddr()
if leader == "" {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
redirect := s.FormRedirect(r, leader)
http.Redirect(w, r, redirect, http.StatusMovedPermanently)
return
}
resp.Error = err.Error()
} else {
resp.Results = results.Rows
if timings {
resp.Time = results.Time
}
resp.Raft = results.Raft
}
writeResponse(w, r, &resp)
} | go | func (s *Service) handleQuery(connID uint64, w http.ResponseWriter, r *http.Request) {
isAtomic, err := isAtomic(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
timings, err := timings(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
lvl, err := level(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Get the query statement(s), and do tx if necessary.
queries, err := requestQueries(r)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
// Get the right queryer object.
var queryer Queryer
if connID == defaultConnID {
queryer = s.store
} else {
c, ok := s.store.Connection(connID)
if !ok {
http.Error(w, "connection not found", http.StatusNotFound)
return
}
queryer = c
}
var resp Response
results, err := queryer.Query(&store.QueryRequest{queries, timings, isAtomic, lvl})
if err != nil {
if err == store.ErrNotLeader {
leader := s.leaderAPIAddr()
if leader == "" {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
redirect := s.FormRedirect(r, leader)
http.Redirect(w, r, redirect, http.StatusMovedPermanently)
return
}
resp.Error = err.Error()
} else {
resp.Results = results.Rows
if timings {
resp.Time = results.Time
}
resp.Raft = results.Raft
}
writeResponse(w, r, &resp)
} | [
"func",
"(",
"s",
"*",
"Service",
")",
"handleQuery",
"(",
"connID",
"uint64",
",",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"isAtomic",
",",
"err",
":=",
"isAtomic",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"timings",
",",
"err",
":=",
"timings",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"lvl",
",",
"err",
":=",
"level",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"queries",
",",
"err",
":=",
"requestQueries",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n",
"var",
"queryer",
"Queryer",
"\n",
"if",
"connID",
"==",
"defaultConnID",
"{",
"queryer",
"=",
"s",
".",
"store",
"\n",
"}",
"else",
"{",
"c",
",",
"ok",
":=",
"s",
".",
"store",
".",
"Connection",
"(",
"connID",
")",
"\n",
"if",
"!",
"ok",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"connection not found\"",
",",
"http",
".",
"StatusNotFound",
")",
"\n",
"return",
"\n",
"}",
"\n",
"queryer",
"=",
"c",
"\n",
"}",
"\n",
"var",
"resp",
"Response",
"\n",
"results",
",",
"err",
":=",
"queryer",
".",
"Query",
"(",
"&",
"store",
".",
"QueryRequest",
"{",
"queries",
",",
"timings",
",",
"isAtomic",
",",
"lvl",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"store",
".",
"ErrNotLeader",
"{",
"leader",
":=",
"s",
".",
"leaderAPIAddr",
"(",
")",
"\n",
"if",
"leader",
"==",
"\"\"",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusServiceUnavailable",
")",
"\n",
"return",
"\n",
"}",
"\n",
"redirect",
":=",
"s",
".",
"FormRedirect",
"(",
"r",
",",
"leader",
")",
"\n",
"http",
".",
"Redirect",
"(",
"w",
",",
"r",
",",
"redirect",
",",
"http",
".",
"StatusMovedPermanently",
")",
"\n",
"return",
"\n",
"}",
"\n",
"resp",
".",
"Error",
"=",
"err",
".",
"Error",
"(",
")",
"\n",
"}",
"else",
"{",
"resp",
".",
"Results",
"=",
"results",
".",
"Rows",
"\n",
"if",
"timings",
"{",
"resp",
".",
"Time",
"=",
"results",
".",
"Time",
"\n",
"}",
"\n",
"resp",
".",
"Raft",
"=",
"results",
".",
"Raft",
"\n",
"}",
"\n",
"writeResponse",
"(",
"w",
",",
"r",
",",
"&",
"resp",
")",
"\n",
"}"
] | // handleQuery handles queries that do not modify the database. | [
"handleQuery",
"handles",
"queries",
"that",
"do",
"not",
"modify",
"the",
"database",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L606-L668 | train |
rqlite/rqlite | http/service.go | FormRedirect | func (s *Service) FormRedirect(r *http.Request, host string) string {
rq := r.URL.RawQuery
if rq != "" {
rq = fmt.Sprintf("?%s", rq)
}
return fmt.Sprintf("%s://%s%s%s", s.protocol(), host, r.URL.Path, rq)
} | go | func (s *Service) FormRedirect(r *http.Request, host string) string {
rq := r.URL.RawQuery
if rq != "" {
rq = fmt.Sprintf("?%s", rq)
}
return fmt.Sprintf("%s://%s%s%s", s.protocol(), host, r.URL.Path, rq)
} | [
"func",
"(",
"s",
"*",
"Service",
")",
"FormRedirect",
"(",
"r",
"*",
"http",
".",
"Request",
",",
"host",
"string",
")",
"string",
"{",
"rq",
":=",
"r",
".",
"URL",
".",
"RawQuery",
"\n",
"if",
"rq",
"!=",
"\"\"",
"{",
"rq",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"?%s\"",
",",
"rq",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"%s://%s%s%s\"",
",",
"s",
".",
"protocol",
"(",
")",
",",
"host",
",",
"r",
".",
"URL",
".",
"Path",
",",
"rq",
")",
"\n",
"}"
] | // FormRedirect returns the value for the "Location" header for a 301 response. | [
"FormRedirect",
"returns",
"the",
"value",
"for",
"the",
"Location",
"header",
"for",
"a",
"301",
"response",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L676-L682 | train |
rqlite/rqlite | http/service.go | FormConnectionURL | func (s *Service) FormConnectionURL(r *http.Request, id uint64) string {
return fmt.Sprintf("%s://%s/db/connections/%d", s.protocol(), r.Host, id)
} | go | func (s *Service) FormConnectionURL(r *http.Request, id uint64) string {
return fmt.Sprintf("%s://%s/db/connections/%d", s.protocol(), r.Host, id)
} | [
"func",
"(",
"s",
"*",
"Service",
")",
"FormConnectionURL",
"(",
"r",
"*",
"http",
".",
"Request",
",",
"id",
"uint64",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"%s://%s/db/connections/%d\"",
",",
"s",
".",
"protocol",
"(",
")",
",",
"r",
".",
"Host",
",",
"id",
")",
"\n",
"}"
] | // FormConnectionURL returns the URL of the new connection. | [
"FormConnectionURL",
"returns",
"the",
"URL",
"of",
"the",
"new",
"connection",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L685-L687 | train |
rqlite/rqlite | http/service.go | CheckRequestPerm | func (s *Service) CheckRequestPerm(r *http.Request, perm string) bool {
if s.credentialStore == nil {
return true
}
username, _, ok := r.BasicAuth()
if !ok {
return false
}
return s.credentialStore.HasAnyPerm(username, perm, PermAll)
} | go | func (s *Service) CheckRequestPerm(r *http.Request, perm string) bool {
if s.credentialStore == nil {
return true
}
username, _, ok := r.BasicAuth()
if !ok {
return false
}
return s.credentialStore.HasAnyPerm(username, perm, PermAll)
} | [
"func",
"(",
"s",
"*",
"Service",
")",
"CheckRequestPerm",
"(",
"r",
"*",
"http",
".",
"Request",
",",
"perm",
"string",
")",
"bool",
"{",
"if",
"s",
".",
"credentialStore",
"==",
"nil",
"{",
"return",
"true",
"\n",
"}",
"\n",
"username",
",",
"_",
",",
"ok",
":=",
"r",
".",
"BasicAuth",
"(",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"s",
".",
"credentialStore",
".",
"HasAnyPerm",
"(",
"username",
",",
"perm",
",",
"PermAll",
")",
"\n",
"}"
] | // CheckRequestPerm returns true if authentication is enabled and the user contained
// in the BasicAuth request has either PermAll, or the given perm. | [
"CheckRequestPerm",
"returns",
"true",
"if",
"authentication",
"is",
"enabled",
"and",
"the",
"user",
"contained",
"in",
"the",
"BasicAuth",
"request",
"has",
"either",
"PermAll",
"or",
"the",
"given",
"perm",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L691-L701 | train |
rqlite/rqlite | http/service.go | addBuildVersion | func (s *Service) addBuildVersion(w http.ResponseWriter) {
// Add version header to every response, if available.
version := "unknown"
if v, ok := s.BuildInfo["version"].(string); ok {
version = v
}
w.Header().Add(VersionHTTPHeader, version)
} | go | func (s *Service) addBuildVersion(w http.ResponseWriter) {
// Add version header to every response, if available.
version := "unknown"
if v, ok := s.BuildInfo["version"].(string); ok {
version = v
}
w.Header().Add(VersionHTTPHeader, version)
} | [
"func",
"(",
"s",
"*",
"Service",
")",
"addBuildVersion",
"(",
"w",
"http",
".",
"ResponseWriter",
")",
"{",
"version",
":=",
"\"unknown\"",
"\n",
"if",
"v",
",",
"ok",
":=",
"s",
".",
"BuildInfo",
"[",
"\"version\"",
"]",
".",
"(",
"string",
")",
";",
"ok",
"{",
"version",
"=",
"v",
"\n",
"}",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Add",
"(",
"VersionHTTPHeader",
",",
"version",
")",
"\n",
"}"
] | // addBuildVersion adds the build version to the HTTP response. | [
"addBuildVersion",
"adds",
"the",
"build",
"version",
"to",
"the",
"HTTP",
"response",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L712-L719 | train |
rqlite/rqlite | http/service.go | queryParam | func queryParam(req *http.Request, param string) (bool, error) {
err := req.ParseForm()
if err != nil {
return false, err
}
if _, ok := req.Form[param]; ok {
return true, nil
}
return false, nil
} | go | func queryParam(req *http.Request, param string) (bool, error) {
err := req.ParseForm()
if err != nil {
return false, err
}
if _, ok := req.Form[param]; ok {
return true, nil
}
return false, nil
} | [
"func",
"queryParam",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"param",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"err",
":=",
"req",
".",
"ParseForm",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"req",
".",
"Form",
"[",
"param",
"]",
";",
"ok",
"{",
"return",
"true",
",",
"nil",
"\n",
"}",
"\n",
"return",
"false",
",",
"nil",
"\n",
"}"
] | // queryParam returns whether the given query param is set to true. | [
"queryParam",
"returns",
"whether",
"the",
"given",
"query",
"param",
"is",
"set",
"to",
"true",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L788-L797 | train |
rqlite/rqlite | http/service.go | durationParam | func durationParam(req *http.Request, param string) (time.Duration, bool, error) {
q := req.URL.Query()
t := strings.TrimSpace(q.Get(param))
if t == "" {
return 0, false, nil
}
dur, err := time.ParseDuration(t)
if err != nil {
return 0, false, err
}
return dur, true, nil
} | go | func durationParam(req *http.Request, param string) (time.Duration, bool, error) {
q := req.URL.Query()
t := strings.TrimSpace(q.Get(param))
if t == "" {
return 0, false, nil
}
dur, err := time.ParseDuration(t)
if err != nil {
return 0, false, err
}
return dur, true, nil
} | [
"func",
"durationParam",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"param",
"string",
")",
"(",
"time",
".",
"Duration",
",",
"bool",
",",
"error",
")",
"{",
"q",
":=",
"req",
".",
"URL",
".",
"Query",
"(",
")",
"\n",
"t",
":=",
"strings",
".",
"TrimSpace",
"(",
"q",
".",
"Get",
"(",
"param",
")",
")",
"\n",
"if",
"t",
"==",
"\"\"",
"{",
"return",
"0",
",",
"false",
",",
"nil",
"\n",
"}",
"\n",
"dur",
",",
"err",
":=",
"time",
".",
"ParseDuration",
"(",
"t",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"false",
",",
"err",
"\n",
"}",
"\n",
"return",
"dur",
",",
"true",
",",
"nil",
"\n",
"}"
] | // durationParam returns the duration of the given query param, if set. | [
"durationParam",
"returns",
"the",
"duration",
"of",
"the",
"given",
"query",
"param",
"if",
"set",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L800-L811 | train |
rqlite/rqlite | http/service.go | stmtParam | func stmtParam(req *http.Request) (string, error) {
q := req.URL.Query()
return strings.TrimSpace(q.Get("q")), nil
} | go | func stmtParam(req *http.Request) (string, error) {
q := req.URL.Query()
return strings.TrimSpace(q.Get("q")), nil
} | [
"func",
"stmtParam",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"(",
"string",
",",
"error",
")",
"{",
"q",
":=",
"req",
".",
"URL",
".",
"Query",
"(",
")",
"\n",
"return",
"strings",
".",
"TrimSpace",
"(",
"q",
".",
"Get",
"(",
"\"q\"",
")",
")",
",",
"nil",
"\n",
"}"
] | // stmtParam returns the value for URL param 'q', if present. | [
"stmtParam",
"returns",
"the",
"value",
"for",
"URL",
"param",
"q",
"if",
"present",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L814-L817 | train |
rqlite/rqlite | http/service.go | isAtomic | func isAtomic(req *http.Request) (bool, error) {
// "transaction" is checked for backwards compatibility with
// client libraries.
for _, q := range []string{"atomic", "transaction"} {
if a, err := queryParam(req, q); err != nil || a {
return a, err
}
}
return false, nil
} | go | func isAtomic(req *http.Request) (bool, error) {
// "transaction" is checked for backwards compatibility with
// client libraries.
for _, q := range []string{"atomic", "transaction"} {
if a, err := queryParam(req, q); err != nil || a {
return a, err
}
}
return false, nil
} | [
"func",
"isAtomic",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"(",
"bool",
",",
"error",
")",
"{",
"for",
"_",
",",
"q",
":=",
"range",
"[",
"]",
"string",
"{",
"\"atomic\"",
",",
"\"transaction\"",
"}",
"{",
"if",
"a",
",",
"err",
":=",
"queryParam",
"(",
"req",
",",
"q",
")",
";",
"err",
"!=",
"nil",
"||",
"a",
"{",
"return",
"a",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
",",
"nil",
"\n",
"}"
] | // isAtomic returns whether the HTTP request is an atomic request. | [
"isAtomic",
"returns",
"whether",
"the",
"HTTP",
"request",
"is",
"an",
"atomic",
"request",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L831-L840 | train |
rqlite/rqlite | http/service.go | txTimeout | func txTimeout(req *http.Request) (time.Duration, bool, error) {
return durationParam(req, "tx_timeout")
} | go | func txTimeout(req *http.Request) (time.Duration, bool, error) {
return durationParam(req, "tx_timeout")
} | [
"func",
"txTimeout",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"(",
"time",
".",
"Duration",
",",
"bool",
",",
"error",
")",
"{",
"return",
"durationParam",
"(",
"req",
",",
"\"tx_timeout\"",
")",
"\n",
"}"
] | // txTimeout returns the duration of any transaction timeout set. | [
"txTimeout",
"returns",
"the",
"duration",
"of",
"any",
"transaction",
"timeout",
"set",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L853-L855 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.