repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
sequence | docstring
stringlengths 6
2.61k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 85
252
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
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\n",
"centerX",
":=",
"bgMinX",
"+",
"bgW",
"/",
"2",
"\n",
"centerY",
":=",
"bgMinY",
"+",
"bgH",
"/",
"2",
"\n\n",
"x0",
":=",
"centerX",
"-",
"img",
".",
"Bounds",
"(",
")",
".",
"Dx",
"(",
")",
"/",
"2",
"\n",
"y0",
":=",
"centerY",
"-",
"img",
".",
"Bounds",
"(",
")",
".",
"Dy",
"(",
")",
"/",
"2",
"\n\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\n",
"centerX",
":=",
"bgMinX",
"+",
"bgW",
"/",
"2",
"\n",
"centerY",
":=",
"bgMinY",
"+",
"bgH",
"/",
"2",
"\n\n",
"x0",
":=",
"centerX",
"-",
"img",
".",
"Bounds",
"(",
")",
".",
"Dx",
"(",
")",
"/",
"2",
"\n",
"y0",
":=",
"centerY",
"-",
"img",
".",
"Bounds",
"(",
")",
".",
"Dy",
"(",
")",
"/",
"2",
"\n\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\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\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\n",
"if",
"dstW",
"<=",
"0",
"||",
"dstH",
"<=",
"0",
"{",
"return",
"dst",
"\n",
"}",
"\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\n",
"bgColorNRGBA",
":=",
"color",
".",
"NRGBAModel",
".",
"Convert",
"(",
"bgColor",
")",
".",
"(",
"color",
".",
"NRGBA",
")",
"\n",
"sin",
",",
"cos",
":=",
"math",
".",
"Sincos",
"(",
"math",
".",
"Pi",
"*",
"angle",
"/",
"180",
")",
"\n\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\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\n",
"procs",
":=",
"runtime",
".",
"GOMAXPROCS",
"(",
"0",
")",
"\n",
"if",
"procs",
">",
"count",
"{",
"procs",
"=",
"count",
"\n",
"}",
"\n\n",
"c",
":=",
"make",
"(",
"chan",
"int",
",",
"count",
")",
"\n",
"for",
"i",
":=",
"start",
";",
"i",
"<",
"stop",
";",
"i",
"++",
"{",
"c",
"<-",
"i",
"\n",
"}",
"\n",
"close",
"(",
"c",
")",
"\n\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\n",
"max",
":=",
"math",
".",
"Max",
"(",
"rr",
",",
"math",
".",
"Max",
"(",
"gg",
",",
"bb",
")",
")",
"\n",
"min",
":=",
"math",
".",
"Min",
"(",
"rr",
",",
"math",
".",
"Min",
"(",
"gg",
",",
"bb",
")",
")",
"\n\n",
"l",
":=",
"(",
"max",
"+",
"min",
")",
"/",
"2",
"\n\n",
"if",
"max",
"==",
"min",
"{",
"return",
"0",
",",
"0",
",",
"l",
"\n",
"}",
"\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\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\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\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\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\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\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\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\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\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\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\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\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\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\n",
"if",
"!",
"cfg",
".",
"autoOrientation",
"{",
"img",
",",
"_",
",",
"err",
":=",
"image",
".",
"Decode",
"(",
"r",
")",
"\n",
"return",
"img",
",",
"err",
"\n",
"}",
"\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\n",
"img",
",",
"_",
",",
"err",
":=",
"image",
".",
"Decode",
"(",
"r",
")",
"\n",
"pw",
".",
"Close",
"(",
")",
"\n",
"<-",
"done",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\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",
"(",
"\"",
"\"",
",",
"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\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\n",
"var",
"err",
"error",
"\n",
"var",
"conn",
"net",
".",
"Conn",
"\n",
"if",
"t",
".",
"remoteEncrypted",
"{",
"conf",
":=",
"&",
"tls",
".",
"Config",
"{",
"InsecureSkipVerify",
":",
"t",
".",
"skipVerify",
",",
"}",
"\n",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
")",
"\n",
"conn",
",",
"err",
"=",
"tls",
".",
"DialWithDialer",
"(",
"dialer",
",",
"\"",
"\"",
",",
"addr",
",",
"conf",
")",
"\n",
"}",
"else",
"{",
"conn",
",",
"err",
"=",
"dialer",
".",
"Dial",
"(",
"\"",
"\"",
",",
"addr",
")",
"\n",
"}",
"\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\n",
"b",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"s",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"h",
".",
"br",
"=",
"bytes",
".",
"NewReader",
"(",
"b",
")",
"\n\n",
"if",
"tx",
"{",
"h",
".",
"url",
"=",
"h",
".",
"url",
"+",
"\"",
"\"",
"\n",
"}",
"\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\n",
"start",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"resp",
",",
"err",
":=",
"h",
".",
"client",
".",
"Post",
"(",
"h",
".",
"url",
",",
"\"",
"\"",
",",
"h",
".",
"br",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"if",
"resp",
".",
"StatusCode",
"!=",
"http",
".",
"StatusOK",
"{",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"resp",
".",
"Status",
")",
"\n",
"}",
"\n",
"dur",
":=",
"time",
".",
"Since",
"(",
"start",
")",
"\n\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",
")",
"{",
"// Read the file",
"buf",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"filepath",
".",
"Join",
"(",
"raftDir",
",",
"jsonPeerPath",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"!",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"// Check for no peers",
"if",
"len",
"(",
"buf",
")",
"==",
"0",
"{",
"return",
"0",
",",
"nil",
"\n",
"}",
"\n\n",
"// Decode the peers",
"var",
"peerSet",
"[",
"]",
"string",
"\n",
"dec",
":=",
"json",
".",
"NewDecoder",
"(",
"bytes",
".",
"NewReader",
"(",
"buf",
")",
")",
"\n",
"if",
"err",
":=",
"dec",
".",
"Decode",
"(",
"&",
"peerSet",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\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",
",",
"\"",
"\"",
",",
"log",
".",
"LstdFlags",
")",
"\n",
"}",
"\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\n",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"s",
".",
"raftID",
")",
"\n\n",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"s",
".",
"raftDir",
")",
"\n",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"s",
".",
"raftDir",
",",
"0755",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Create underlying database.",
"if",
"err",
":=",
"s",
".",
"createDatabase",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Get utility connection to database.",
"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\n",
"// Is this a brand new node?",
"newNode",
":=",
"!",
"pathExists",
"(",
"filepath",
".",
"Join",
"(",
"s",
".",
"raftDir",
",",
"\"",
"\"",
")",
")",
"\n\n",
"// Create Raft-compatible network layer.",
"s",
".",
"raftTn",
"=",
"raft",
".",
"NewNetworkTransport",
"(",
"NewTransport",
"(",
"s",
".",
"ln",
")",
",",
"connectionPoolCount",
",",
"connectionTimeout",
",",
"nil",
")",
"\n\n",
"// Get the Raft configuration for this store.",
"config",
":=",
"s",
".",
"raftConfig",
"(",
")",
"\n",
"config",
".",
"LocalID",
"=",
"raft",
".",
"ServerID",
"(",
"s",
".",
"raftID",
")",
"\n",
"config",
".",
"Logger",
"=",
"log",
".",
"New",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\"",
",",
"log",
".",
"LstdFlags",
")",
"\n\n",
"// Create the snapshot store. This allows Raft to truncate the log.",
"snapshots",
",",
"err",
":=",
"raft",
".",
"NewFileSnapshotStore",
"(",
"s",
".",
"raftDir",
",",
"retainSnapshotCount",
",",
"os",
".",
"Stderr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Create the log store and stable store.",
"s",
".",
"boltStore",
",",
"err",
"=",
"raftboltdb",
".",
"NewBoltStore",
"(",
"filepath",
".",
"Join",
"(",
"s",
".",
"raftDir",
",",
"\"",
"\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"s",
".",
"raftStable",
"=",
"s",
".",
"boltStore",
"\n",
"s",
".",
"raftLog",
",",
"err",
"=",
"raft",
".",
"NewLogCache",
"(",
"raftLogCacheSize",
",",
"s",
".",
"boltStore",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Instantiate the Raft system.",
"ra",
",",
"err",
":=",
"raft",
".",
"NewRaft",
"(",
"config",
",",
"s",
",",
"s",
".",
"raftLog",
",",
"s",
".",
"raftStable",
",",
"snapshots",
",",
"s",
".",
"raftTn",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"enableSingle",
"&&",
"newNode",
"{",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
")",
"\n",
"configuration",
":=",
"raft",
".",
"Configuration",
"{",
"Servers",
":",
"[",
"]",
"raft",
".",
"Server",
"{",
"{",
"ID",
":",
"config",
".",
"LocalID",
",",
"Address",
":",
"s",
".",
"raftTn",
".",
"LocalAddr",
"(",
")",
",",
"}",
",",
"}",
",",
"}",
"\n",
"ra",
".",
"BootstrapCluster",
"(",
"configuration",
")",
"\n",
"}",
"else",
"{",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"s",
".",
"raft",
"=",
"ra",
"\n\n",
"// Start connection monitoring",
"s",
".",
"checkConnections",
"(",
")",
"\n\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",
")",
"{",
"// 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",
"(",
")",
"\n",
"defer",
"s",
".",
"connsMu",
".",
"Unlock",
"(",
")",
"\n",
"for",
"{",
"// Make sure we get an unused ID.",
"id",
":=",
"s",
".",
"randSrc",
".",
"Uint64",
"(",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"s",
".",
"conns",
"[",
"id",
"]",
";",
"!",
"ok",
"{",
"s",
".",
"conns",
"[",
"id",
"]",
"=",
"nil",
"\n",
"return",
"id",
"\n",
"}",
"\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\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\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\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\n",
"close",
"(",
"s",
".",
"done",
")",
"\n",
"s",
".",
"wg",
".",
"Wait",
"(",
")",
"\n\n",
"// XXX CLOSE OTHER CONNECTIONS",
"if",
"err",
":=",
"s",
".",
"dbConn",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"s",
".",
"dbConn",
"=",
"nil",
"\n",
"s",
".",
"db",
"=",
"nil",
"\n\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\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",
"(",
"\"",
"\"",
",",
"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",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\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\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\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\n",
"for",
"{",
"select",
"{",
"case",
"<-",
"tck",
".",
"C",
":",
"l",
":=",
"s",
".",
"LeaderAddr",
"(",
")",
"\n",
"if",
"l",
"!=",
"\"",
"\"",
"{",
"return",
"l",
",",
"nil",
"\n",
"}",
"\n",
"case",
"<-",
"tmr",
".",
"C",
":",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\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\n",
"for",
"{",
"select",
"{",
"case",
"<-",
"tck",
".",
"C",
":",
"if",
"s",
".",
"raft",
".",
"AppliedIndex",
"(",
")",
">=",
"idx",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"case",
"<-",
"tmr",
".",
"C",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\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\n",
"dbStatus",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"s",
".",
"dbConf",
".",
"DSN",
",",
"\"",
"\"",
":",
"enabledFromBool",
"(",
"fkEnabled",
")",
",",
"\"",
"\"",
":",
"sdb",
".",
"DBVersion",
",",
"}",
"\n",
"if",
"!",
"s",
".",
"dbConf",
".",
"Memory",
"{",
"dbStatus",
"[",
"\"",
"\"",
"]",
"=",
"s",
".",
"dbPath",
"\n",
"stat",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"s",
".",
"dbPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"dbStatus",
"[",
"\"",
"\"",
"]",
"=",
"stat",
".",
"Size",
"(",
")",
"\n",
"}",
"else",
"{",
"dbStatus",
"[",
"\"",
"\"",
"]",
"=",
"\"",
"\"",
"\n",
"}",
"\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\n",
"status",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"s",
".",
"raftID",
",",
"\"",
"\"",
":",
"s",
".",
"raft",
".",
"Stats",
"(",
")",
",",
"\"",
"\"",
":",
"s",
".",
"Addr",
"(",
")",
",",
"\"",
"\"",
":",
"map",
"[",
"string",
"]",
"string",
"{",
"\"",
"\"",
":",
"leaderID",
",",
"\"",
"\"",
":",
"s",
".",
"LeaderAddr",
"(",
")",
",",
"}",
",",
"\"",
"\"",
":",
"s",
".",
"ApplyTimeout",
".",
"String",
"(",
")",
",",
"\"",
"\"",
":",
"s",
".",
"HeartbeatTimeout",
".",
"String",
"(",
")",
",",
"\"",
"\"",
":",
"s",
".",
"SnapshotThreshold",
",",
"\"",
"\"",
":",
"s",
".",
"connPollPeriod",
".",
"String",
"(",
")",
",",
"\"",
"\"",
":",
"s",
".",
"meta",
",",
"\"",
"\"",
":",
"nodes",
",",
"\"",
"\"",
":",
"s",
".",
"raftDir",
",",
"\"",
"\"",
":",
"dbStatus",
",",
"\"",
"\"",
":",
"s",
".",
"dbConf",
",",
"}",
"\n\n",
"// Add connections status",
"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",
"[",
"\"",
"\"",
"]",
"=",
"conns",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\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\n",
"if",
"leader",
"&&",
"s",
".",
"raft",
".",
"State",
"(",
")",
"!=",
"raft",
".",
"Leader",
"{",
"return",
"ErrNotLeader",
"\n",
"}",
"\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",
"(",
"\"",
"\"",
",",
"addr",
")",
"\n",
"if",
"s",
".",
"raft",
".",
"State",
"(",
")",
"!=",
"raft",
".",
"Leader",
"{",
"return",
"ErrNotLeader",
"\n",
"}",
"\n\n",
"configFuture",
":=",
"s",
".",
"raft",
".",
"GetConfiguration",
"(",
")",
"\n",
"if",
"err",
":=",
"configFuture",
".",
"Error",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"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",
"(",
"\"",
"\"",
",",
"id",
",",
"addr",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"err",
":=",
"s",
".",
"remove",
"(",
"id",
")",
";",
"err",
"!=",
"nil",
"{",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\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\n",
"if",
"err",
":=",
"s",
".",
"setMetadata",
"(",
"id",
",",
"metadata",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"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",
"(",
"\"",
"\"",
",",
"id",
")",
"\n",
"if",
"err",
":=",
"s",
".",
"remove",
"(",
"id",
")",
";",
"err",
"!=",
"nil",
"{",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"id",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"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\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",
"{",
"// Check local data first.",
"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",
"}",
"(",
")",
"{",
"// Local data is same as data being pushed in,",
"// nothing to do.",
"return",
"nil",
"\n",
"}",
"\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\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\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\n",
"start",
":=",
"time",
".",
"Now",
"(",
")",
"\n\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\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\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",
"(",
"\"",
"\"",
")",
"\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\n",
"s",
".",
"restoreMu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"restoreMu",
".",
"RUnlock",
"(",
")",
"\n",
"start",
":=",
"time",
".",
"Now",
"(",
")",
"\n\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\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\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",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"qr",
".",
"Lvl",
"==",
"Weak",
"&&",
"s",
".",
"raft",
".",
"State",
"(",
")",
"!=",
"raft",
".",
"Leader",
"{",
"return",
"nil",
",",
"ErrNotLeader",
"\n",
"}",
"\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",
"{",
"// 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",
"\n",
"}",
"\n",
"db",
",",
"err",
"=",
"sdb",
".",
"New",
"(",
"s",
".",
"dbPath",
",",
"s",
".",
"dbConf",
".",
"DSN",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"s",
".",
"logger",
".",
"Println",
"(",
"\"",
"\"",
",",
"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",
"(",
"\"",
"\"",
")",
"\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\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\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\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",
":",
"// 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",
"\n",
"}",
"\n\n",
"var",
"conns",
"[",
"]",
"*",
"Connection",
"\n",
"s",
".",
"connsMu",
".",
"RLock",
"(",
")",
"\n",
"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",
"\n",
"}",
"\n",
"if",
"c",
".",
"IdleTimedOut",
"(",
")",
"||",
"c",
".",
"TxTimedOut",
"(",
")",
"{",
"conns",
"=",
"append",
"(",
"conns",
",",
"c",
")",
"\n",
"}",
"\n",
"}",
"\n",
"s",
".",
"connsMu",
".",
"RUnlock",
"(",
")",
"\n\n",
"for",
"_",
",",
"c",
":=",
"range",
"conns",
"{",
"if",
"err",
":=",
"c",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"ErrNotLeader",
"{",
"// Not an issue, the actual leader will close it.",
"continue",
"\n",
"}",
"\n",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"c",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"c",
")",
"\n",
"// Only increment stat here to make testing easier.",
"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\n",
"f",
",",
"err",
":=",
"ioutil",
".",
"TempFile",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\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\n",
"if",
"err",
":=",
"s",
".",
"dbConn",
".",
"Backup",
"(",
"conn",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"conn",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"of",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"f",
".",
"Name",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"of",
".",
"Close",
"(",
")",
"\n\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\n",
"// 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",
"(",
")",
"\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\n",
"// Copy the database.",
"fsm",
":=",
"&",
"fsmSnapshot",
"{",
"}",
"\n",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"var",
"err",
"error",
"\n",
"err",
"=",
"s",
".",
"database",
"(",
"false",
",",
"&",
"buf",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"fsm",
".",
"database",
"=",
"buf",
".",
"Bytes",
"(",
")",
"\n\n",
"// Copy the node metadata.",
"fsm",
".",
"meta",
",",
"err",
"=",
"json",
".",
"Marshal",
"(",
"s",
".",
"meta",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Copy the active connections.",
"fsm",
".",
"connections",
",",
"err",
"=",
"json",
".",
"Marshal",
"(",
"s",
".",
"conns",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"stats",
".",
"Add",
"(",
"numSnaphots",
",",
"1",
")",
"\n\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",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\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",
",",
"\"",
"\"",
",",
"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\n",
"if",
"_",
",",
"ok",
":=",
"s",
".",
"statuses",
"[",
"key",
"]",
";",
"ok",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"key",
")",
"\n",
"}",
"\n",
"s",
".",
"statuses",
"[",
"key",
"]",
"=",
"stat",
"\n\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\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\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\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",
"(",
"\"",
"\"",
",",
"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\n",
"remoteID",
",",
"ok",
":=",
"md",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"!",
"ok",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n",
"remoteAddr",
",",
"ok",
":=",
"md",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"!",
"ok",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n",
"var",
"m",
"map",
"[",
"string",
"]",
"string",
"\n",
"if",
"_",
",",
"ok",
":=",
"md",
"[",
"\"",
"\"",
"]",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"m",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"md",
"[",
"\"",
"\"",
"]",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"{",
"m",
"[",
"k",
"]",
"=",
"v",
".",
"(",
"string",
")",
"\n",
"}",
"\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\n",
"redirect",
":=",
"s",
".",
"FormRedirect",
"(",
"r",
",",
"leader",
")",
"\n",
"http",
".",
"Redirect",
"(",
"w",
",",
"r",
",",
"redirect",
",",
"http",
".",
"StatusMovedPermanently",
")",
"\n",
"return",
"\n",
"}",
"\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\n",
"if",
"len",
"(",
"m",
")",
"!=",
"1",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"remoteID",
",",
"ok",
":=",
"m",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"!",
"ok",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\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\n",
"redirect",
":=",
"s",
".",
"FormRedirect",
"(",
"r",
",",
"leader",
")",
"\n",
"http",
".",
"Redirect",
"(",
"w",
",",
"r",
",",
"redirect",
",",
"http",
".",
"StatusMovedPermanently",
")",
"\n",
"return",
"\n",
"}",
"\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\n",
"bf",
",",
"err",
":=",
"backupFormat",
"(",
"w",
",",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"err",
"=",
"s",
".",
"store",
".",
"Backup",
"(",
"!",
"noLeader",
",",
"bf",
",",
"w",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\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\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\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\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\n",
"rt",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"runtime",
".",
"GOARCH",
",",
"\"",
"\"",
":",
"runtime",
".",
"GOOS",
",",
"\"",
"\"",
":",
"runtime",
".",
"GOMAXPROCS",
"(",
"0",
")",
",",
"\"",
"\"",
":",
"runtime",
".",
"NumCPU",
"(",
")",
",",
"\"",
"\"",
":",
"runtime",
".",
"NumGoroutine",
"(",
")",
",",
"\"",
"\"",
":",
"runtime",
".",
"Version",
"(",
")",
",",
"}",
"\n\n",
"httpStatus",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"s",
".",
"Addr",
"(",
")",
".",
"String",
"(",
")",
",",
"\"",
"\"",
":",
"prettyEnabled",
"(",
"s",
".",
"credentialStore",
"!=",
"nil",
")",
",",
"\"",
"\"",
":",
"s",
".",
"leaderAPIAddr",
"(",
")",
",",
"\"",
"\"",
":",
"s",
".",
"ConnIdleTimeout",
".",
"String",
"(",
")",
",",
"\"",
"\"",
":",
"s",
".",
"ConnTxTimeout",
".",
"String",
"(",
")",
",",
"}",
"\n\n",
"nodeStatus",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"s",
".",
"start",
",",
"\"",
"\"",
":",
"time",
".",
"Since",
"(",
"s",
".",
"start",
")",
".",
"String",
"(",
")",
",",
"}",
"\n\n",
"// Build the status response.",
"status",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"rt",
",",
"\"",
"\"",
":",
"results",
",",
"\"",
"\"",
":",
"httpStatus",
",",
"\"",
"\"",
":",
"nodeStatus",
",",
"}",
"\n",
"if",
"!",
"s",
".",
"lastBackup",
".",
"IsZero",
"(",
")",
"{",
"status",
"[",
"\"",
"\"",
"]",
"=",
"s",
".",
"lastBackup",
"\n",
"}",
"\n",
"if",
"s",
".",
"BuildInfo",
"!=",
"nil",
"{",
"status",
"[",
"\"",
"\"",
"]",
"=",
"s",
".",
"BuildInfo",
"\n",
"}",
"\n\n",
"// Add any registered statusers.",
"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\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\n",
"timings",
",",
"err",
":=",
"timings",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\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\n",
"queries",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"b",
",",
"&",
"queries",
")",
";",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Get the right executer object.",
"var",
"execer",
"Execer",
"\n",
"if",
"connID",
"==",
"defaultConnID",
"{",
"execer",
"=",
"s",
".",
"store",
"\n",
"}",
"else",
"{",
"c",
",",
"ok",
":=",
"s",
".",
"store",
".",
"Connection",
"(",
"connID",
")",
"\n",
"if",
"!",
"ok",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusNotFound",
")",
"\n",
"return",
"\n",
"}",
"\n",
"execer",
"=",
"c",
"\n",
"}",
"\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\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\n",
"timings",
",",
"err",
":=",
"timings",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"lvl",
",",
"err",
":=",
"level",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Get the query statement(s), and do tx if necessary.",
"queries",
",",
"err",
":=",
"requestQueries",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Get the right queryer object.",
"var",
"queryer",
"Queryer",
"\n",
"if",
"connID",
"==",
"defaultConnID",
"{",
"queryer",
"=",
"s",
".",
"store",
"\n",
"}",
"else",
"{",
"c",
",",
"ok",
":=",
"s",
".",
"store",
".",
"Connection",
"(",
"connID",
")",
"\n",
"if",
"!",
"ok",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusNotFound",
")",
"\n",
"return",
"\n",
"}",
"\n",
"queryer",
"=",
"c",
"\n",
"}",
"\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\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",
"(",
"\"",
"\"",
",",
"rq",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"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",
".",
"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\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",
")",
"{",
"// Add version header to every response, if available.",
"version",
":=",
"\"",
"\"",
"\n",
"if",
"v",
",",
"ok",
":=",
"s",
".",
"BuildInfo",
"[",
"\"",
"\"",
"]",
".",
"(",
"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",
"(",
"\"",
"\"",
")",
")",
",",
"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",
")",
"{",
"// \"transaction\" is checked for backwards compatibility with",
"// client libraries.",
"for",
"_",
",",
"q",
":=",
"range",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
"{",
"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",
",",
"\"",
"\"",
")",
"\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 |
rqlite/rqlite | http/service.go | level | func level(req *http.Request) (store.ConsistencyLevel, error) {
q := req.URL.Query()
lvl := strings.TrimSpace(q.Get("level"))
switch strings.ToLower(lvl) {
case "none":
return store.None, nil
case "weak":
return store.Weak, nil
case "strong":
return store.Strong, nil
default:
return store.Weak, nil
}
} | go | func level(req *http.Request) (store.ConsistencyLevel, error) {
q := req.URL.Query()
lvl := strings.TrimSpace(q.Get("level"))
switch strings.ToLower(lvl) {
case "none":
return store.None, nil
case "weak":
return store.Weak, nil
case "strong":
return store.Strong, nil
default:
return store.Weak, nil
}
} | [
"func",
"level",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"(",
"store",
".",
"ConsistencyLevel",
",",
"error",
")",
"{",
"q",
":=",
"req",
".",
"URL",
".",
"Query",
"(",
")",
"\n",
"lvl",
":=",
"strings",
".",
"TrimSpace",
"(",
"q",
".",
"Get",
"(",
"\"",
"\"",
")",
")",
"\n\n",
"switch",
"strings",
".",
"ToLower",
"(",
"lvl",
")",
"{",
"case",
"\"",
"\"",
":",
"return",
"store",
".",
"None",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"store",
".",
"Weak",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"store",
".",
"Strong",
",",
"nil",
"\n",
"default",
":",
"return",
"store",
".",
"Weak",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // level returns the requested consistency level for a query | [
"level",
"returns",
"the",
"requested",
"consistency",
"level",
"for",
"a",
"query"
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L863-L877 | train |
rqlite/rqlite | http/service.go | backupFormat | func backupFormat(w http.ResponseWriter, r *http.Request) (store.BackupFormat, error) {
fmt, err := fmtParam(r)
if err != nil {
return store.BackupBinary, err
}
if fmt == "sql" {
w.Header().Set("Content-Type", "application/sql")
return store.BackupSQL, nil
}
w.Header().Set("Content-Type", "application/octet-stream")
return store.BackupBinary, nil
} | go | func backupFormat(w http.ResponseWriter, r *http.Request) (store.BackupFormat, error) {
fmt, err := fmtParam(r)
if err != nil {
return store.BackupBinary, err
}
if fmt == "sql" {
w.Header().Set("Content-Type", "application/sql")
return store.BackupSQL, nil
}
w.Header().Set("Content-Type", "application/octet-stream")
return store.BackupBinary, nil
} | [
"func",
"backupFormat",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"(",
"store",
".",
"BackupFormat",
",",
"error",
")",
"{",
"fmt",
",",
"err",
":=",
"fmtParam",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"store",
".",
"BackupBinary",
",",
"err",
"\n",
"}",
"\n",
"if",
"fmt",
"==",
"\"",
"\"",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"store",
".",
"BackupSQL",
",",
"nil",
"\n",
"}",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"store",
".",
"BackupBinary",
",",
"nil",
"\n",
"}"
] | // backuFormat returns the request backup format, setting the response header
// accordingly. | [
"backuFormat",
"returns",
"the",
"request",
"backup",
"format",
"setting",
"the",
"response",
"header",
"accordingly",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L881-L892 | train |
rqlite/rqlite | db/db.go | New | func New(path, dsnQuery string, memory bool) (*DB, error) {
q, err := url.ParseQuery(dsnQuery)
if err != nil {
return nil, err
}
if memory {
q.Set("mode", "memory")
q.Set("cache", "shared")
}
if !strings.HasPrefix(path, "file:") {
path = fmt.Sprintf("file:%s", path)
}
var fqdsn string
if len(q) > 0 {
fqdsn = fmt.Sprintf("%s?%s", path, q.Encode())
} else {
fqdsn = path
}
return &DB{
path: path,
dsnQuery: dsnQuery,
memory: memory,
fqdsn: fqdsn,
}, nil
} | go | func New(path, dsnQuery string, memory bool) (*DB, error) {
q, err := url.ParseQuery(dsnQuery)
if err != nil {
return nil, err
}
if memory {
q.Set("mode", "memory")
q.Set("cache", "shared")
}
if !strings.HasPrefix(path, "file:") {
path = fmt.Sprintf("file:%s", path)
}
var fqdsn string
if len(q) > 0 {
fqdsn = fmt.Sprintf("%s?%s", path, q.Encode())
} else {
fqdsn = path
}
return &DB{
path: path,
dsnQuery: dsnQuery,
memory: memory,
fqdsn: fqdsn,
}, nil
} | [
"func",
"New",
"(",
"path",
",",
"dsnQuery",
"string",
",",
"memory",
"bool",
")",
"(",
"*",
"DB",
",",
"error",
")",
"{",
"q",
",",
"err",
":=",
"url",
".",
"ParseQuery",
"(",
"dsnQuery",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"memory",
"{",
"q",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"q",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"path",
",",
"\"",
"\"",
")",
"{",
"path",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"path",
")",
"\n",
"}",
"\n\n",
"var",
"fqdsn",
"string",
"\n",
"if",
"len",
"(",
"q",
")",
">",
"0",
"{",
"fqdsn",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"path",
",",
"q",
".",
"Encode",
"(",
")",
")",
"\n",
"}",
"else",
"{",
"fqdsn",
"=",
"path",
"\n",
"}",
"\n\n",
"return",
"&",
"DB",
"{",
"path",
":",
"path",
",",
"dsnQuery",
":",
"dsnQuery",
",",
"memory",
":",
"memory",
",",
"fqdsn",
":",
"fqdsn",
",",
"}",
",",
"nil",
"\n",
"}"
] | // New returns an instance of the database at path. If the database
// has already been created and opened, this database will share
// the data of that database when connected. | [
"New",
"returns",
"an",
"instance",
"of",
"the",
"database",
"at",
"path",
".",
"If",
"the",
"database",
"has",
"already",
"been",
"created",
"and",
"opened",
"this",
"database",
"will",
"share",
"the",
"data",
"of",
"that",
"database",
"when",
"connected",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/db/db.go#L75-L102 | train |
rqlite/rqlite | db/db.go | Connect | func (d *DB) Connect() (*Conn, error) {
drv := sqlite3.SQLiteDriver{}
c, err := drv.Open(d.fqdsn)
if err != nil {
return nil, err
}
return &Conn{
sqlite: c.(*sqlite3.SQLiteConn),
}, nil
} | go | func (d *DB) Connect() (*Conn, error) {
drv := sqlite3.SQLiteDriver{}
c, err := drv.Open(d.fqdsn)
if err != nil {
return nil, err
}
return &Conn{
sqlite: c.(*sqlite3.SQLiteConn),
}, nil
} | [
"func",
"(",
"d",
"*",
"DB",
")",
"Connect",
"(",
")",
"(",
"*",
"Conn",
",",
"error",
")",
"{",
"drv",
":=",
"sqlite3",
".",
"SQLiteDriver",
"{",
"}",
"\n",
"c",
",",
"err",
":=",
"drv",
".",
"Open",
"(",
"d",
".",
"fqdsn",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"Conn",
"{",
"sqlite",
":",
"c",
".",
"(",
"*",
"sqlite3",
".",
"SQLiteConn",
")",
",",
"}",
",",
"nil",
"\n",
"}"
] | // Connect returns a connection to the database. | [
"Connect",
"returns",
"a",
"connection",
"to",
"the",
"database",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/db/db.go#L105-L115 | train |
rqlite/rqlite | db/db.go | Execute | func (c *Conn) Execute(queries []string, tx, xTime bool) ([]*Result, error) {
stats.Add(numExecutions, int64(len(queries)))
if tx {
stats.Add(numETx, 1)
}
type Execer interface {
Exec(query string, args []driver.Value) (driver.Result, error)
}
var allResults []*Result
err := func() error {
var execer Execer
var rollback bool
var t driver.Tx
var err error
// Check for the err, if set rollback.
defer func() {
if t != nil {
if rollback {
t.Rollback()
return
}
t.Commit()
}
}()
// handleError sets the error field on the given result. It returns
// whether the caller should continue processing or break.
handleError := func(result *Result, err error) bool {
stats.Add(numExecutionErrors, 1)
result.Error = err.Error()
allResults = append(allResults, result)
if tx {
rollback = true // Will trigger the rollback.
return false
}
return true
}
execer = c.sqlite
// Create the correct execution object, depending on whether a
// transaction was requested.
if tx {
t, err = c.sqlite.Begin()
if err != nil {
return err
}
}
// Execute each query.
for _, q := range queries {
if q == "" {
continue
}
result := &Result{}
start := time.Now()
r, err := execer.Exec(q, nil)
if err != nil {
if handleError(result, err) {
continue
}
break
}
if r == nil {
continue
}
lid, err := r.LastInsertId()
if err != nil {
if handleError(result, err) {
continue
}
break
}
result.LastInsertID = lid
ra, err := r.RowsAffected()
if err != nil {
if handleError(result, err) {
continue
}
break
}
result.RowsAffected = ra
if xTime {
result.Time = time.Now().Sub(start).Seconds()
}
allResults = append(allResults, result)
}
return nil
}()
return allResults, err
} | go | func (c *Conn) Execute(queries []string, tx, xTime bool) ([]*Result, error) {
stats.Add(numExecutions, int64(len(queries)))
if tx {
stats.Add(numETx, 1)
}
type Execer interface {
Exec(query string, args []driver.Value) (driver.Result, error)
}
var allResults []*Result
err := func() error {
var execer Execer
var rollback bool
var t driver.Tx
var err error
// Check for the err, if set rollback.
defer func() {
if t != nil {
if rollback {
t.Rollback()
return
}
t.Commit()
}
}()
// handleError sets the error field on the given result. It returns
// whether the caller should continue processing or break.
handleError := func(result *Result, err error) bool {
stats.Add(numExecutionErrors, 1)
result.Error = err.Error()
allResults = append(allResults, result)
if tx {
rollback = true // Will trigger the rollback.
return false
}
return true
}
execer = c.sqlite
// Create the correct execution object, depending on whether a
// transaction was requested.
if tx {
t, err = c.sqlite.Begin()
if err != nil {
return err
}
}
// Execute each query.
for _, q := range queries {
if q == "" {
continue
}
result := &Result{}
start := time.Now()
r, err := execer.Exec(q, nil)
if err != nil {
if handleError(result, err) {
continue
}
break
}
if r == nil {
continue
}
lid, err := r.LastInsertId()
if err != nil {
if handleError(result, err) {
continue
}
break
}
result.LastInsertID = lid
ra, err := r.RowsAffected()
if err != nil {
if handleError(result, err) {
continue
}
break
}
result.RowsAffected = ra
if xTime {
result.Time = time.Now().Sub(start).Seconds()
}
allResults = append(allResults, result)
}
return nil
}()
return allResults, err
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"Execute",
"(",
"queries",
"[",
"]",
"string",
",",
"tx",
",",
"xTime",
"bool",
")",
"(",
"[",
"]",
"*",
"Result",
",",
"error",
")",
"{",
"stats",
".",
"Add",
"(",
"numExecutions",
",",
"int64",
"(",
"len",
"(",
"queries",
")",
")",
")",
"\n",
"if",
"tx",
"{",
"stats",
".",
"Add",
"(",
"numETx",
",",
"1",
")",
"\n",
"}",
"\n\n",
"type",
"Execer",
"interface",
"{",
"Exec",
"(",
"query",
"string",
",",
"args",
"[",
"]",
"driver",
".",
"Value",
")",
"(",
"driver",
".",
"Result",
",",
"error",
")",
"\n",
"}",
"\n\n",
"var",
"allResults",
"[",
"]",
"*",
"Result",
"\n",
"err",
":=",
"func",
"(",
")",
"error",
"{",
"var",
"execer",
"Execer",
"\n",
"var",
"rollback",
"bool",
"\n",
"var",
"t",
"driver",
".",
"Tx",
"\n",
"var",
"err",
"error",
"\n\n",
"// Check for the err, if set rollback.",
"defer",
"func",
"(",
")",
"{",
"if",
"t",
"!=",
"nil",
"{",
"if",
"rollback",
"{",
"t",
".",
"Rollback",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"t",
".",
"Commit",
"(",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"// handleError sets the error field on the given result. It returns",
"// whether the caller should continue processing or break.",
"handleError",
":=",
"func",
"(",
"result",
"*",
"Result",
",",
"err",
"error",
")",
"bool",
"{",
"stats",
".",
"Add",
"(",
"numExecutionErrors",
",",
"1",
")",
"\n\n",
"result",
".",
"Error",
"=",
"err",
".",
"Error",
"(",
")",
"\n",
"allResults",
"=",
"append",
"(",
"allResults",
",",
"result",
")",
"\n",
"if",
"tx",
"{",
"rollback",
"=",
"true",
"// Will trigger the rollback.",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}",
"\n\n",
"execer",
"=",
"c",
".",
"sqlite",
"\n\n",
"// Create the correct execution object, depending on whether a",
"// transaction was requested.",
"if",
"tx",
"{",
"t",
",",
"err",
"=",
"c",
".",
"sqlite",
".",
"Begin",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Execute each query.",
"for",
"_",
",",
"q",
":=",
"range",
"queries",
"{",
"if",
"q",
"==",
"\"",
"\"",
"{",
"continue",
"\n",
"}",
"\n\n",
"result",
":=",
"&",
"Result",
"{",
"}",
"\n",
"start",
":=",
"time",
".",
"Now",
"(",
")",
"\n\n",
"r",
",",
"err",
":=",
"execer",
".",
"Exec",
"(",
"q",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"handleError",
"(",
"result",
",",
"err",
")",
"{",
"continue",
"\n",
"}",
"\n",
"break",
"\n",
"}",
"\n",
"if",
"r",
"==",
"nil",
"{",
"continue",
"\n",
"}",
"\n\n",
"lid",
",",
"err",
":=",
"r",
".",
"LastInsertId",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"handleError",
"(",
"result",
",",
"err",
")",
"{",
"continue",
"\n",
"}",
"\n",
"break",
"\n",
"}",
"\n",
"result",
".",
"LastInsertID",
"=",
"lid",
"\n\n",
"ra",
",",
"err",
":=",
"r",
".",
"RowsAffected",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"handleError",
"(",
"result",
",",
"err",
")",
"{",
"continue",
"\n",
"}",
"\n",
"break",
"\n",
"}",
"\n",
"result",
".",
"RowsAffected",
"=",
"ra",
"\n",
"if",
"xTime",
"{",
"result",
".",
"Time",
"=",
"time",
".",
"Now",
"(",
")",
".",
"Sub",
"(",
"start",
")",
".",
"Seconds",
"(",
")",
"\n",
"}",
"\n",
"allResults",
"=",
"append",
"(",
"allResults",
",",
"result",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}",
"(",
")",
"\n\n",
"return",
"allResults",
",",
"err",
"\n",
"}"
] | // Execute executes queries that modify the database. | [
"Execute",
"executes",
"queries",
"that",
"modify",
"the",
"database",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/db/db.go#L139-L239 | train |
rqlite/rqlite | db/db.go | Query | func (c *Conn) Query(queries []string, tx, xTime bool) ([]*Rows, error) {
stats.Add(numQueries, int64(len(queries)))
if tx {
stats.Add(numQTx, 1)
}
type Queryer interface {
Query(query string, args []driver.Value) (driver.Rows, error)
}
var allRows []*Rows
err := func() (err error) {
var queryer Queryer
var t driver.Tx
defer func() {
// XXX THIS DOESN'T ACTUALLY WORK! Might as WELL JUST COMMIT?
if t != nil {
if err != nil {
t.Rollback()
return
}
t.Commit()
}
}()
queryer = c.sqlite
// Create the correct query object, depending on whether a
// transaction was requested.
if tx {
t, err = c.sqlite.Begin()
if err != nil {
return err
}
}
for _, q := range queries {
if q == "" {
continue
}
rows := &Rows{}
start := time.Now()
rs, err := queryer.Query(q, nil)
if err != nil {
rows.Error = err.Error()
allRows = append(allRows, rows)
continue
}
defer rs.Close()
columns := rs.Columns()
rows.Columns = columns
rows.Types = rs.(*sqlite3.SQLiteRows).DeclTypes()
dest := make([]driver.Value, len(rows.Columns))
for {
err := rs.Next(dest)
if err != nil {
if err != io.EOF {
rows.Error = err.Error()
}
break
}
values := normalizeRowValues(dest, rows.Types)
rows.Values = append(rows.Values, values)
}
if xTime {
rows.Time = time.Now().Sub(start).Seconds()
}
allRows = append(allRows, rows)
}
return nil
}()
return allRows, err
} | go | func (c *Conn) Query(queries []string, tx, xTime bool) ([]*Rows, error) {
stats.Add(numQueries, int64(len(queries)))
if tx {
stats.Add(numQTx, 1)
}
type Queryer interface {
Query(query string, args []driver.Value) (driver.Rows, error)
}
var allRows []*Rows
err := func() (err error) {
var queryer Queryer
var t driver.Tx
defer func() {
// XXX THIS DOESN'T ACTUALLY WORK! Might as WELL JUST COMMIT?
if t != nil {
if err != nil {
t.Rollback()
return
}
t.Commit()
}
}()
queryer = c.sqlite
// Create the correct query object, depending on whether a
// transaction was requested.
if tx {
t, err = c.sqlite.Begin()
if err != nil {
return err
}
}
for _, q := range queries {
if q == "" {
continue
}
rows := &Rows{}
start := time.Now()
rs, err := queryer.Query(q, nil)
if err != nil {
rows.Error = err.Error()
allRows = append(allRows, rows)
continue
}
defer rs.Close()
columns := rs.Columns()
rows.Columns = columns
rows.Types = rs.(*sqlite3.SQLiteRows).DeclTypes()
dest := make([]driver.Value, len(rows.Columns))
for {
err := rs.Next(dest)
if err != nil {
if err != io.EOF {
rows.Error = err.Error()
}
break
}
values := normalizeRowValues(dest, rows.Types)
rows.Values = append(rows.Values, values)
}
if xTime {
rows.Time = time.Now().Sub(start).Seconds()
}
allRows = append(allRows, rows)
}
return nil
}()
return allRows, err
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"Query",
"(",
"queries",
"[",
"]",
"string",
",",
"tx",
",",
"xTime",
"bool",
")",
"(",
"[",
"]",
"*",
"Rows",
",",
"error",
")",
"{",
"stats",
".",
"Add",
"(",
"numQueries",
",",
"int64",
"(",
"len",
"(",
"queries",
")",
")",
")",
"\n",
"if",
"tx",
"{",
"stats",
".",
"Add",
"(",
"numQTx",
",",
"1",
")",
"\n",
"}",
"\n\n",
"type",
"Queryer",
"interface",
"{",
"Query",
"(",
"query",
"string",
",",
"args",
"[",
"]",
"driver",
".",
"Value",
")",
"(",
"driver",
".",
"Rows",
",",
"error",
")",
"\n",
"}",
"\n\n",
"var",
"allRows",
"[",
"]",
"*",
"Rows",
"\n",
"err",
":=",
"func",
"(",
")",
"(",
"err",
"error",
")",
"{",
"var",
"queryer",
"Queryer",
"\n",
"var",
"t",
"driver",
".",
"Tx",
"\n",
"defer",
"func",
"(",
")",
"{",
"// XXX THIS DOESN'T ACTUALLY WORK! Might as WELL JUST COMMIT?",
"if",
"t",
"!=",
"nil",
"{",
"if",
"err",
"!=",
"nil",
"{",
"t",
".",
"Rollback",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"t",
".",
"Commit",
"(",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"queryer",
"=",
"c",
".",
"sqlite",
"\n\n",
"// Create the correct query object, depending on whether a",
"// transaction was requested.",
"if",
"tx",
"{",
"t",
",",
"err",
"=",
"c",
".",
"sqlite",
".",
"Begin",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"q",
":=",
"range",
"queries",
"{",
"if",
"q",
"==",
"\"",
"\"",
"{",
"continue",
"\n",
"}",
"\n\n",
"rows",
":=",
"&",
"Rows",
"{",
"}",
"\n",
"start",
":=",
"time",
".",
"Now",
"(",
")",
"\n\n",
"rs",
",",
"err",
":=",
"queryer",
".",
"Query",
"(",
"q",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"rows",
".",
"Error",
"=",
"err",
".",
"Error",
"(",
")",
"\n",
"allRows",
"=",
"append",
"(",
"allRows",
",",
"rows",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"defer",
"rs",
".",
"Close",
"(",
")",
"\n",
"columns",
":=",
"rs",
".",
"Columns",
"(",
")",
"\n\n",
"rows",
".",
"Columns",
"=",
"columns",
"\n",
"rows",
".",
"Types",
"=",
"rs",
".",
"(",
"*",
"sqlite3",
".",
"SQLiteRows",
")",
".",
"DeclTypes",
"(",
")",
"\n",
"dest",
":=",
"make",
"(",
"[",
"]",
"driver",
".",
"Value",
",",
"len",
"(",
"rows",
".",
"Columns",
")",
")",
"\n",
"for",
"{",
"err",
":=",
"rs",
".",
"Next",
"(",
"dest",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
"!=",
"io",
".",
"EOF",
"{",
"rows",
".",
"Error",
"=",
"err",
".",
"Error",
"(",
")",
"\n",
"}",
"\n",
"break",
"\n",
"}",
"\n\n",
"values",
":=",
"normalizeRowValues",
"(",
"dest",
",",
"rows",
".",
"Types",
")",
"\n",
"rows",
".",
"Values",
"=",
"append",
"(",
"rows",
".",
"Values",
",",
"values",
")",
"\n",
"}",
"\n",
"if",
"xTime",
"{",
"rows",
".",
"Time",
"=",
"time",
".",
"Now",
"(",
")",
".",
"Sub",
"(",
"start",
")",
".",
"Seconds",
"(",
")",
"\n",
"}",
"\n",
"allRows",
"=",
"append",
"(",
"allRows",
",",
"rows",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}",
"(",
")",
"\n\n",
"return",
"allRows",
",",
"err",
"\n",
"}"
] | // Query executes queries that return rows, but don't modify the database. | [
"Query",
"executes",
"queries",
"that",
"return",
"rows",
"but",
"don",
"t",
"modify",
"the",
"database",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/db/db.go#L242-L320 | train |
rqlite/rqlite | db/db.go | EnableFKConstraints | func (c *Conn) EnableFKConstraints(e bool) error {
q := fkChecksEnabled
if !e {
q = fkChecksDisabled
}
_, err := c.sqlite.Exec(q, nil)
return err
} | go | func (c *Conn) EnableFKConstraints(e bool) error {
q := fkChecksEnabled
if !e {
q = fkChecksDisabled
}
_, err := c.sqlite.Exec(q, nil)
return err
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"EnableFKConstraints",
"(",
"e",
"bool",
")",
"error",
"{",
"q",
":=",
"fkChecksEnabled",
"\n",
"if",
"!",
"e",
"{",
"q",
"=",
"fkChecksDisabled",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"c",
".",
"sqlite",
".",
"Exec",
"(",
"q",
",",
"nil",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // EnableFKConstraints allows control of foreign key constraint checks. | [
"EnableFKConstraints",
"allows",
"control",
"of",
"foreign",
"key",
"constraint",
"checks",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/db/db.go#L323-L330 | train |
rqlite/rqlite | db/db.go | FKConstraints | func (c *Conn) FKConstraints() (bool, error) {
r, err := c.sqlite.Query(fkChecks, nil)
if err != nil {
return false, err
}
dest := make([]driver.Value, len(r.Columns()))
types := r.(*sqlite3.SQLiteRows).DeclTypes()
if err := r.Next(dest); err != nil {
return false, err
}
values := normalizeRowValues(dest, types)
if values[0] == int64(1) {
return true, nil
}
return false, nil
} | go | func (c *Conn) FKConstraints() (bool, error) {
r, err := c.sqlite.Query(fkChecks, nil)
if err != nil {
return false, err
}
dest := make([]driver.Value, len(r.Columns()))
types := r.(*sqlite3.SQLiteRows).DeclTypes()
if err := r.Next(dest); err != nil {
return false, err
}
values := normalizeRowValues(dest, types)
if values[0] == int64(1) {
return true, nil
}
return false, nil
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"FKConstraints",
"(",
")",
"(",
"bool",
",",
"error",
")",
"{",
"r",
",",
"err",
":=",
"c",
".",
"sqlite",
".",
"Query",
"(",
"fkChecks",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"dest",
":=",
"make",
"(",
"[",
"]",
"driver",
".",
"Value",
",",
"len",
"(",
"r",
".",
"Columns",
"(",
")",
")",
")",
"\n",
"types",
":=",
"r",
".",
"(",
"*",
"sqlite3",
".",
"SQLiteRows",
")",
".",
"DeclTypes",
"(",
")",
"\n",
"if",
"err",
":=",
"r",
".",
"Next",
"(",
"dest",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"values",
":=",
"normalizeRowValues",
"(",
"dest",
",",
"types",
")",
"\n",
"if",
"values",
"[",
"0",
"]",
"==",
"int64",
"(",
"1",
")",
"{",
"return",
"true",
",",
"nil",
"\n",
"}",
"\n",
"return",
"false",
",",
"nil",
"\n",
"}"
] | // FKConstraints returns whether FK constraints are set or not. | [
"FKConstraints",
"returns",
"whether",
"FK",
"constraints",
"are",
"set",
"or",
"not",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/db/db.go#L333-L350 | train |
rqlite/rqlite | db/db.go | Load | func (c *Conn) Load(src *Conn) error {
return copyDatabase(c.sqlite, src.sqlite)
} | go | func (c *Conn) Load(src *Conn) error {
return copyDatabase(c.sqlite, src.sqlite)
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"Load",
"(",
"src",
"*",
"Conn",
")",
"error",
"{",
"return",
"copyDatabase",
"(",
"c",
".",
"sqlite",
",",
"src",
".",
"sqlite",
")",
"\n",
"}"
] | // Load loads the connected database from the database connected to src.
// It overwrites the data contained in this database. It is the caller's
// responsibility to ensure that no other connections to this database
// are accessed while this operation is in progress. | [
"Load",
"loads",
"the",
"connected",
"database",
"from",
"the",
"database",
"connected",
"to",
"src",
".",
"It",
"overwrites",
"the",
"data",
"contained",
"in",
"this",
"database",
".",
"It",
"is",
"the",
"caller",
"s",
"responsibility",
"to",
"ensure",
"that",
"no",
"other",
"connections",
"to",
"this",
"database",
"are",
"accessed",
"while",
"this",
"operation",
"is",
"in",
"progress",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/db/db.go#L356-L358 | train |
rqlite/rqlite | db/db.go | Backup | func (c *Conn) Backup(dst *Conn) error {
return copyDatabase(dst.sqlite, c.sqlite)
} | go | func (c *Conn) Backup(dst *Conn) error {
return copyDatabase(dst.sqlite, c.sqlite)
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"Backup",
"(",
"dst",
"*",
"Conn",
")",
"error",
"{",
"return",
"copyDatabase",
"(",
"dst",
".",
"sqlite",
",",
"c",
".",
"sqlite",
")",
"\n",
"}"
] | // Backup writes a snapshot of the database over the given database
// connection, erasing all the contents of the destination database.
// The consistency of the snapshot is READ_COMMITTED relative to any
// other connections currently open to this database. The caller must
// ensure that all connections to the destination database are not
// accessed during this operation. | [
"Backup",
"writes",
"a",
"snapshot",
"of",
"the",
"database",
"over",
"the",
"given",
"database",
"connection",
"erasing",
"all",
"the",
"contents",
"of",
"the",
"destination",
"database",
".",
"The",
"consistency",
"of",
"the",
"snapshot",
"is",
"READ_COMMITTED",
"relative",
"to",
"any",
"other",
"connections",
"currently",
"open",
"to",
"this",
"database",
".",
"The",
"caller",
"must",
"ensure",
"that",
"all",
"connections",
"to",
"the",
"destination",
"database",
"are",
"not",
"accessed",
"during",
"this",
"operation",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/db/db.go#L366-L368 | train |
rqlite/rqlite | db/db.go | Dump | func (c *Conn) Dump(w io.Writer) error {
if _, err := w.Write([]byte("PRAGMA foreign_keys=OFF;\nBEGIN TRANSACTION;\n")); err != nil {
return err
}
// Get the schema.
query := `SELECT "name", "type", "sql" FROM "sqlite_master"
WHERE "sql" NOT NULL AND "type" == 'table' ORDER BY "name"`
rows, err := c.Query([]string{query}, false, false)
if err != nil {
return err
}
row := rows[0]
for _, v := range row.Values {
table := v[0].(string)
var stmt string
if table == "sqlite_sequence" {
stmt = `DELETE FROM "sqlite_sequence";`
} else if table == "sqlite_stat1" {
stmt = `ANALYZE "sqlite_master";`
} else if strings.HasPrefix(table, "sqlite_") {
continue
} else {
stmt = v[2].(string)
}
if _, err := w.Write([]byte(fmt.Sprintf("%s;\n", stmt))); err != nil {
return err
}
tableIndent := strings.Replace(table, `"`, `""`, -1)
query = fmt.Sprintf(`PRAGMA table_info("%s")`, tableIndent)
r, err := c.Query([]string{query}, false, false)
if err != nil {
return err
}
var columnNames []string
for _, w := range r[0].Values {
columnNames = append(columnNames, fmt.Sprintf(`'||quote("%s")||'`, w[1].(string)))
}
query = fmt.Sprintf(`SELECT 'INSERT INTO "%s" VALUES(%s)' FROM "%s";`,
tableIndent,
strings.Join(columnNames, ","),
tableIndent)
r, err = c.Query([]string{query}, false, false)
if err != nil {
return err
}
for _, x := range r[0].Values {
y := fmt.Sprintf("%s;\n", x[0].(string))
if _, err := w.Write([]byte(y)); err != nil {
return err
}
}
}
// Do indexes, triggers, and views.
query = `SELECT "name", "type", "sql" FROM "sqlite_master"
WHERE "sql" NOT NULL AND "type" IN ('index', 'trigger', 'view')`
rows, err = c.Query([]string{query}, false, false)
if err != nil {
return err
}
row = rows[0]
for _, v := range row.Values {
if _, err := w.Write([]byte(fmt.Sprintf("%s;\n", v[2]))); err != nil {
return err
}
}
if _, err := w.Write([]byte("COMMIT;\n")); err != nil {
return err
}
return nil
} | go | func (c *Conn) Dump(w io.Writer) error {
if _, err := w.Write([]byte("PRAGMA foreign_keys=OFF;\nBEGIN TRANSACTION;\n")); err != nil {
return err
}
// Get the schema.
query := `SELECT "name", "type", "sql" FROM "sqlite_master"
WHERE "sql" NOT NULL AND "type" == 'table' ORDER BY "name"`
rows, err := c.Query([]string{query}, false, false)
if err != nil {
return err
}
row := rows[0]
for _, v := range row.Values {
table := v[0].(string)
var stmt string
if table == "sqlite_sequence" {
stmt = `DELETE FROM "sqlite_sequence";`
} else if table == "sqlite_stat1" {
stmt = `ANALYZE "sqlite_master";`
} else if strings.HasPrefix(table, "sqlite_") {
continue
} else {
stmt = v[2].(string)
}
if _, err := w.Write([]byte(fmt.Sprintf("%s;\n", stmt))); err != nil {
return err
}
tableIndent := strings.Replace(table, `"`, `""`, -1)
query = fmt.Sprintf(`PRAGMA table_info("%s")`, tableIndent)
r, err := c.Query([]string{query}, false, false)
if err != nil {
return err
}
var columnNames []string
for _, w := range r[0].Values {
columnNames = append(columnNames, fmt.Sprintf(`'||quote("%s")||'`, w[1].(string)))
}
query = fmt.Sprintf(`SELECT 'INSERT INTO "%s" VALUES(%s)' FROM "%s";`,
tableIndent,
strings.Join(columnNames, ","),
tableIndent)
r, err = c.Query([]string{query}, false, false)
if err != nil {
return err
}
for _, x := range r[0].Values {
y := fmt.Sprintf("%s;\n", x[0].(string))
if _, err := w.Write([]byte(y)); err != nil {
return err
}
}
}
// Do indexes, triggers, and views.
query = `SELECT "name", "type", "sql" FROM "sqlite_master"
WHERE "sql" NOT NULL AND "type" IN ('index', 'trigger', 'view')`
rows, err = c.Query([]string{query}, false, false)
if err != nil {
return err
}
row = rows[0]
for _, v := range row.Values {
if _, err := w.Write([]byte(fmt.Sprintf("%s;\n", v[2]))); err != nil {
return err
}
}
if _, err := w.Write([]byte("COMMIT;\n")); err != nil {
return err
}
return nil
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"Dump",
"(",
"w",
"io",
".",
"Writer",
")",
"error",
"{",
"if",
"_",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\\n",
"\\n",
"\"",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Get the schema.",
"query",
":=",
"`SELECT \"name\", \"type\", \"sql\" FROM \"sqlite_master\"\n WHERE \"sql\" NOT NULL AND \"type\" == 'table' ORDER BY \"name\"`",
"\n",
"rows",
",",
"err",
":=",
"c",
".",
"Query",
"(",
"[",
"]",
"string",
"{",
"query",
"}",
",",
"false",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"row",
":=",
"rows",
"[",
"0",
"]",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"row",
".",
"Values",
"{",
"table",
":=",
"v",
"[",
"0",
"]",
".",
"(",
"string",
")",
"\n",
"var",
"stmt",
"string",
"\n\n",
"if",
"table",
"==",
"\"",
"\"",
"{",
"stmt",
"=",
"`DELETE FROM \"sqlite_sequence\";`",
"\n",
"}",
"else",
"if",
"table",
"==",
"\"",
"\"",
"{",
"stmt",
"=",
"`ANALYZE \"sqlite_master\";`",
"\n",
"}",
"else",
"if",
"strings",
".",
"HasPrefix",
"(",
"table",
",",
"\"",
"\"",
")",
"{",
"continue",
"\n",
"}",
"else",
"{",
"stmt",
"=",
"v",
"[",
"2",
"]",
".",
"(",
"string",
")",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\"",
",",
"stmt",
")",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"tableIndent",
":=",
"strings",
".",
"Replace",
"(",
"table",
",",
"`\"`",
",",
"`\"\"`",
",",
"-",
"1",
")",
"\n",
"query",
"=",
"fmt",
".",
"Sprintf",
"(",
"`PRAGMA table_info(\"%s\")`",
",",
"tableIndent",
")",
"\n",
"r",
",",
"err",
":=",
"c",
".",
"Query",
"(",
"[",
"]",
"string",
"{",
"query",
"}",
",",
"false",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"var",
"columnNames",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"w",
":=",
"range",
"r",
"[",
"0",
"]",
".",
"Values",
"{",
"columnNames",
"=",
"append",
"(",
"columnNames",
",",
"fmt",
".",
"Sprintf",
"(",
"`'||quote(\"%s\")||'`",
",",
"w",
"[",
"1",
"]",
".",
"(",
"string",
")",
")",
")",
"\n",
"}",
"\n\n",
"query",
"=",
"fmt",
".",
"Sprintf",
"(",
"`SELECT 'INSERT INTO \"%s\" VALUES(%s)' FROM \"%s\";`",
",",
"tableIndent",
",",
"strings",
".",
"Join",
"(",
"columnNames",
",",
"\"",
"\"",
")",
",",
"tableIndent",
")",
"\n",
"r",
",",
"err",
"=",
"c",
".",
"Query",
"(",
"[",
"]",
"string",
"{",
"query",
"}",
",",
"false",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"x",
":=",
"range",
"r",
"[",
"0",
"]",
".",
"Values",
"{",
"y",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\"",
",",
"x",
"[",
"0",
"]",
".",
"(",
"string",
")",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"y",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Do indexes, triggers, and views.",
"query",
"=",
"`SELECT \"name\", \"type\", \"sql\" FROM \"sqlite_master\"\n\t\t\t WHERE \"sql\" NOT NULL AND \"type\" IN ('index', 'trigger', 'view')`",
"\n",
"rows",
",",
"err",
"=",
"c",
".",
"Query",
"(",
"[",
"]",
"string",
"{",
"query",
"}",
",",
"false",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"row",
"=",
"rows",
"[",
"0",
"]",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"row",
".",
"Values",
"{",
"if",
"_",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\"",
",",
"v",
"[",
"2",
"]",
")",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\\n",
"\"",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Dump writes a snapshot of the database in SQL text format. The consistency
// of the snapshot is READ_COMMITTED relative to any other connections
// currently open to this database. | [
"Dump",
"writes",
"a",
"snapshot",
"of",
"the",
"database",
"in",
"SQL",
"text",
"format",
".",
"The",
"consistency",
"of",
"the",
"snapshot",
"is",
"READ_COMMITTED",
"relative",
"to",
"any",
"other",
"connections",
"currently",
"open",
"to",
"this",
"database",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/db/db.go#L373-L450 | train |
rqlite/rqlite | cmd/rqlite/main.go | cliJSON | func cliJSON(ctx *cli.Context, cmd, line, url string, argv *argT) error {
// Recursive JSON printer.
var pprint func(indent int, m map[string]interface{})
pprint = func(indent int, m map[string]interface{}) {
indentation := " "
for k, v := range m {
if v == nil {
continue
}
switch v.(type) {
case map[string]interface{}:
for i := 0; i < indent; i++ {
fmt.Print(indentation)
}
fmt.Printf("%s:\n", k)
pprint(indent+1, v.(map[string]interface{}))
default:
for i := 0; i < indent; i++ {
fmt.Print(indentation)
}
fmt.Printf("%s: %v\n", k, v)
}
}
}
client := http.Client{Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: argv.Insecure},
}}
resp, err := client.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusUnauthorized {
return fmt.Errorf("unauthorized")
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
ret := make(map[string]interface{})
if err := json.Unmarshal(body, &ret); err != nil {
return err
}
// Specific key requested?
parts := strings.Split(line, " ")
if len(parts) >= 2 {
ret = map[string]interface{}{parts[1]: ret[parts[1]]}
}
pprint(0, ret)
return nil
} | go | func cliJSON(ctx *cli.Context, cmd, line, url string, argv *argT) error {
// Recursive JSON printer.
var pprint func(indent int, m map[string]interface{})
pprint = func(indent int, m map[string]interface{}) {
indentation := " "
for k, v := range m {
if v == nil {
continue
}
switch v.(type) {
case map[string]interface{}:
for i := 0; i < indent; i++ {
fmt.Print(indentation)
}
fmt.Printf("%s:\n", k)
pprint(indent+1, v.(map[string]interface{}))
default:
for i := 0; i < indent; i++ {
fmt.Print(indentation)
}
fmt.Printf("%s: %v\n", k, v)
}
}
}
client := http.Client{Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: argv.Insecure},
}}
resp, err := client.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusUnauthorized {
return fmt.Errorf("unauthorized")
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
ret := make(map[string]interface{})
if err := json.Unmarshal(body, &ret); err != nil {
return err
}
// Specific key requested?
parts := strings.Split(line, " ")
if len(parts) >= 2 {
ret = map[string]interface{}{parts[1]: ret[parts[1]]}
}
pprint(0, ret)
return nil
} | [
"func",
"cliJSON",
"(",
"ctx",
"*",
"cli",
".",
"Context",
",",
"cmd",
",",
"line",
",",
"url",
"string",
",",
"argv",
"*",
"argT",
")",
"error",
"{",
"// Recursive JSON printer.",
"var",
"pprint",
"func",
"(",
"indent",
"int",
",",
"m",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"pprint",
"=",
"func",
"(",
"indent",
"int",
",",
"m",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"{",
"indentation",
":=",
"\"",
"\"",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"m",
"{",
"if",
"v",
"==",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"switch",
"v",
".",
"(",
"type",
")",
"{",
"case",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
":",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"indent",
";",
"i",
"++",
"{",
"fmt",
".",
"Print",
"(",
"indentation",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"k",
")",
"\n",
"pprint",
"(",
"indent",
"+",
"1",
",",
"v",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
")",
"\n",
"default",
":",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"indent",
";",
"i",
"++",
"{",
"fmt",
".",
"Print",
"(",
"indentation",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"k",
",",
"v",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"client",
":=",
"http",
".",
"Client",
"{",
"Transport",
":",
"&",
"http",
".",
"Transport",
"{",
"TLSClientConfig",
":",
"&",
"tls",
".",
"Config",
"{",
"InsecureSkipVerify",
":",
"argv",
".",
"Insecure",
"}",
",",
"}",
"}",
"\n",
"resp",
",",
"err",
":=",
"client",
".",
"Get",
"(",
"url",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"if",
"resp",
".",
"StatusCode",
"==",
"http",
".",
"StatusUnauthorized",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"body",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"resp",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"ret",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"body",
",",
"&",
"ret",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Specific key requested?",
"parts",
":=",
"strings",
".",
"Split",
"(",
"line",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"parts",
")",
">=",
"2",
"{",
"ret",
"=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"parts",
"[",
"1",
"]",
":",
"ret",
"[",
"parts",
"[",
"1",
"]",
"]",
"}",
"\n",
"}",
"\n",
"pprint",
"(",
"0",
",",
"ret",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // cliJSON fetches JSON from a URL, and displays it at the CLI. | [
"cliJSON",
"fetches",
"JSON",
"from",
"a",
"URL",
"and",
"displays",
"it",
"at",
"the",
"CLI",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/cmd/rqlite/main.go#L233-L289 | train |
rqlite/rqlite | disco/client.go | New | func New(url string) *Client {
return &Client{
url: url,
logger: log.New(os.Stderr, "[discovery] ", log.LstdFlags),
}
} | go | func New(url string) *Client {
return &Client{
url: url,
logger: log.New(os.Stderr, "[discovery] ", log.LstdFlags),
}
} | [
"func",
"New",
"(",
"url",
"string",
")",
"*",
"Client",
"{",
"return",
"&",
"Client",
"{",
"url",
":",
"url",
",",
"logger",
":",
"log",
".",
"New",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\"",
",",
"log",
".",
"LstdFlags",
")",
",",
"}",
"\n",
"}"
] | // New returns an initialized Discovery Service client. | [
"New",
"returns",
"an",
"initialized",
"Discovery",
"Service",
"client",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/disco/client.go#L29-L34 | train |
rqlite/rqlite | disco/client.go | Register | func (c *Client) Register(id, addr string) (*Response, error) {
m := map[string]string{
"addr": addr,
}
url := c.registrationURL(c.url, id)
client := &http.Client{}
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
for {
b, err := json.Marshal(m)
if err != nil {
return nil, err
}
c.logger.Printf("discovery client attempting registration of %s at %s", addr, url)
resp, err := client.Post(url, "application-type/json", bytes.NewReader(b))
if err != nil {
return nil, err
}
defer resp.Body.Close()
b, err = ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
switch resp.StatusCode {
case http.StatusOK:
r := &Response{}
if err := json.Unmarshal(b, r); err != nil {
return nil, err
}
c.logger.Printf("discovery client successfully registered %s at %s", addr, url)
return r, nil
case http.StatusMovedPermanently:
url = resp.Header.Get("location")
c.logger.Println("discovery client redirecting to", url)
continue
default:
return nil, errors.New(resp.Status)
}
}
} | go | func (c *Client) Register(id, addr string) (*Response, error) {
m := map[string]string{
"addr": addr,
}
url := c.registrationURL(c.url, id)
client := &http.Client{}
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
for {
b, err := json.Marshal(m)
if err != nil {
return nil, err
}
c.logger.Printf("discovery client attempting registration of %s at %s", addr, url)
resp, err := client.Post(url, "application-type/json", bytes.NewReader(b))
if err != nil {
return nil, err
}
defer resp.Body.Close()
b, err = ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
switch resp.StatusCode {
case http.StatusOK:
r := &Response{}
if err := json.Unmarshal(b, r); err != nil {
return nil, err
}
c.logger.Printf("discovery client successfully registered %s at %s", addr, url)
return r, nil
case http.StatusMovedPermanently:
url = resp.Header.Get("location")
c.logger.Println("discovery client redirecting to", url)
continue
default:
return nil, errors.New(resp.Status)
}
}
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Register",
"(",
"id",
",",
"addr",
"string",
")",
"(",
"*",
"Response",
",",
"error",
")",
"{",
"m",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"\"",
"\"",
":",
"addr",
",",
"}",
"\n\n",
"url",
":=",
"c",
".",
"registrationURL",
"(",
"c",
".",
"url",
",",
"id",
")",
"\n",
"client",
":=",
"&",
"http",
".",
"Client",
"{",
"}",
"\n",
"client",
".",
"CheckRedirect",
"=",
"func",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"via",
"[",
"]",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"return",
"http",
".",
"ErrUseLastResponse",
"\n",
"}",
"\n\n",
"for",
"{",
"b",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"m",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"c",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"addr",
",",
"url",
")",
"\n",
"resp",
",",
"err",
":=",
"client",
".",
"Post",
"(",
"url",
",",
"\"",
"\"",
",",
"bytes",
".",
"NewReader",
"(",
"b",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"b",
",",
"err",
"=",
"ioutil",
".",
"ReadAll",
"(",
"resp",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"switch",
"resp",
".",
"StatusCode",
"{",
"case",
"http",
".",
"StatusOK",
":",
"r",
":=",
"&",
"Response",
"{",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"b",
",",
"r",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"c",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"addr",
",",
"url",
")",
"\n",
"return",
"r",
",",
"nil",
"\n",
"case",
"http",
".",
"StatusMovedPermanently",
":",
"url",
"=",
"resp",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"c",
".",
"logger",
".",
"Println",
"(",
"\"",
"\"",
",",
"url",
")",
"\n",
"continue",
"\n",
"default",
":",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"resp",
".",
"Status",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Register attempts to register with the Discovery Service, using the given
// address. | [
"Register",
"attempts",
"to",
"register",
"with",
"the",
"Discovery",
"Service",
"using",
"the",
"given",
"address",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/disco/client.go#L43-L88 | train |
rqlite/rqlite | cmd/rqlited/main.go | startProfile | func startProfile(cpuprofile, memprofile string) {
if cpuprofile != "" {
f, err := os.Create(cpuprofile)
if err != nil {
log.Fatalf("failed to create CPU profile file at %s: %s", cpuprofile, err.Error())
}
log.Printf("writing CPU profile to: %s\n", cpuprofile)
prof.cpu = f
pprof.StartCPUProfile(prof.cpu)
}
if memprofile != "" {
f, err := os.Create(memprofile)
if err != nil {
log.Fatalf("failed to create memory profile file at %s: %s", cpuprofile, err.Error())
}
log.Printf("writing memory profile to: %s\n", memprofile)
prof.mem = f
runtime.MemProfileRate = 4096
}
} | go | func startProfile(cpuprofile, memprofile string) {
if cpuprofile != "" {
f, err := os.Create(cpuprofile)
if err != nil {
log.Fatalf("failed to create CPU profile file at %s: %s", cpuprofile, err.Error())
}
log.Printf("writing CPU profile to: %s\n", cpuprofile)
prof.cpu = f
pprof.StartCPUProfile(prof.cpu)
}
if memprofile != "" {
f, err := os.Create(memprofile)
if err != nil {
log.Fatalf("failed to create memory profile file at %s: %s", cpuprofile, err.Error())
}
log.Printf("writing memory profile to: %s\n", memprofile)
prof.mem = f
runtime.MemProfileRate = 4096
}
} | [
"func",
"startProfile",
"(",
"cpuprofile",
",",
"memprofile",
"string",
")",
"{",
"if",
"cpuprofile",
"!=",
"\"",
"\"",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"cpuprofile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"cpuprofile",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"log",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"cpuprofile",
")",
"\n",
"prof",
".",
"cpu",
"=",
"f",
"\n",
"pprof",
".",
"StartCPUProfile",
"(",
"prof",
".",
"cpu",
")",
"\n",
"}",
"\n\n",
"if",
"memprofile",
"!=",
"\"",
"\"",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"memprofile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"cpuprofile",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"log",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"memprofile",
")",
"\n",
"prof",
".",
"mem",
"=",
"f",
"\n",
"runtime",
".",
"MemProfileRate",
"=",
"4096",
"\n",
"}",
"\n",
"}"
] | // startProfile initializes the CPU and memory profile, if specified. | [
"startProfile",
"initializes",
"the",
"CPU",
"and",
"memory",
"profile",
"if",
"specified",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/cmd/rqlited/main.go#L374-L394 | train |
rqlite/rqlite | cmd/rqlited/main.go | stopProfile | func stopProfile() {
if prof.cpu != nil {
pprof.StopCPUProfile()
prof.cpu.Close()
log.Println("CPU profiling stopped")
}
if prof.mem != nil {
pprof.Lookup("heap").WriteTo(prof.mem, 0)
prof.mem.Close()
log.Println("memory profiling stopped")
}
} | go | func stopProfile() {
if prof.cpu != nil {
pprof.StopCPUProfile()
prof.cpu.Close()
log.Println("CPU profiling stopped")
}
if prof.mem != nil {
pprof.Lookup("heap").WriteTo(prof.mem, 0)
prof.mem.Close()
log.Println("memory profiling stopped")
}
} | [
"func",
"stopProfile",
"(",
")",
"{",
"if",
"prof",
".",
"cpu",
"!=",
"nil",
"{",
"pprof",
".",
"StopCPUProfile",
"(",
")",
"\n",
"prof",
".",
"cpu",
".",
"Close",
"(",
")",
"\n",
"log",
".",
"Println",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"prof",
".",
"mem",
"!=",
"nil",
"{",
"pprof",
".",
"Lookup",
"(",
"\"",
"\"",
")",
".",
"WriteTo",
"(",
"prof",
".",
"mem",
",",
"0",
")",
"\n",
"prof",
".",
"mem",
".",
"Close",
"(",
")",
"\n",
"log",
".",
"Println",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}"
] | // stopProfile closes the CPU and memory profiles if they are running. | [
"stopProfile",
"closes",
"the",
"CPU",
"and",
"memory",
"profiles",
"if",
"they",
"are",
"running",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/cmd/rqlited/main.go#L397-L408 | train |
rqlite/rqlite | cluster/join.go | Join | func Join(joinAddr []string, id, addr string, meta map[string]string, skip bool) (string, error) {
var err error
var j string
logger := log.New(os.Stderr, "[cluster-join] ", log.LstdFlags)
for i := 0; i < numAttempts; i++ {
for _, a := range joinAddr {
j, err = join(a, id, addr, meta, skip)
if err == nil {
// Success!
return j, nil
}
}
logger.Printf("failed to join cluster at %s, sleeping %s before retry", joinAddr, attemptInterval)
time.Sleep(attemptInterval)
}
logger.Printf("failed to join cluster at %s, after %d attempts", joinAddr, numAttempts)
return "", err
} | go | func Join(joinAddr []string, id, addr string, meta map[string]string, skip bool) (string, error) {
var err error
var j string
logger := log.New(os.Stderr, "[cluster-join] ", log.LstdFlags)
for i := 0; i < numAttempts; i++ {
for _, a := range joinAddr {
j, err = join(a, id, addr, meta, skip)
if err == nil {
// Success!
return j, nil
}
}
logger.Printf("failed to join cluster at %s, sleeping %s before retry", joinAddr, attemptInterval)
time.Sleep(attemptInterval)
}
logger.Printf("failed to join cluster at %s, after %d attempts", joinAddr, numAttempts)
return "", err
} | [
"func",
"Join",
"(",
"joinAddr",
"[",
"]",
"string",
",",
"id",
",",
"addr",
"string",
",",
"meta",
"map",
"[",
"string",
"]",
"string",
",",
"skip",
"bool",
")",
"(",
"string",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n",
"var",
"j",
"string",
"\n",
"logger",
":=",
"log",
".",
"New",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\"",
",",
"log",
".",
"LstdFlags",
")",
"\n\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"numAttempts",
";",
"i",
"++",
"{",
"for",
"_",
",",
"a",
":=",
"range",
"joinAddr",
"{",
"j",
",",
"err",
"=",
"join",
"(",
"a",
",",
"id",
",",
"addr",
",",
"meta",
",",
"skip",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"// Success!",
"return",
"j",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"joinAddr",
",",
"attemptInterval",
")",
"\n",
"time",
".",
"Sleep",
"(",
"attemptInterval",
")",
"\n",
"}",
"\n",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"joinAddr",
",",
"numAttempts",
")",
"\n",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}"
] | // Join attempts to join the cluster at one of the addresses given in joinAddr.
// It walks through joinAddr in order, and sets the node ID and Raft address of
// the joining node as id addr respectively. It returns the endpoint
// successfully used to join the cluster. | [
"Join",
"attempts",
"to",
"join",
"the",
"cluster",
"at",
"one",
"of",
"the",
"addresses",
"given",
"in",
"joinAddr",
".",
"It",
"walks",
"through",
"joinAddr",
"in",
"order",
"and",
"sets",
"the",
"node",
"ID",
"and",
"Raft",
"address",
"of",
"the",
"joining",
"node",
"as",
"id",
"addr",
"respectively",
".",
"It",
"returns",
"the",
"endpoint",
"successfully",
"used",
"to",
"join",
"the",
"cluster",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/cluster/join.go#L25-L43 | train |
rqlite/rqlite | cmd/rqlite/query.go | Get | func (r *Rows) Get(i, j int) string {
if i == 0 {
if j >= len(r.Columns) {
return ""
}
return r.Columns[j]
}
if r.Values == nil {
return "NULL"
}
if i-1 >= len(r.Values) {
return "NULL"
}
if j >= len(r.Values[i-1]) {
return "NULL"
}
return fmt.Sprintf("%v", r.Values[i-1][j])
} | go | func (r *Rows) Get(i, j int) string {
if i == 0 {
if j >= len(r.Columns) {
return ""
}
return r.Columns[j]
}
if r.Values == nil {
return "NULL"
}
if i-1 >= len(r.Values) {
return "NULL"
}
if j >= len(r.Values[i-1]) {
return "NULL"
}
return fmt.Sprintf("%v", r.Values[i-1][j])
} | [
"func",
"(",
"r",
"*",
"Rows",
")",
"Get",
"(",
"i",
",",
"j",
"int",
")",
"string",
"{",
"if",
"i",
"==",
"0",
"{",
"if",
"j",
">=",
"len",
"(",
"r",
".",
"Columns",
")",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"r",
".",
"Columns",
"[",
"j",
"]",
"\n",
"}",
"\n\n",
"if",
"r",
".",
"Values",
"==",
"nil",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"if",
"i",
"-",
"1",
">=",
"len",
"(",
"r",
".",
"Values",
")",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"j",
">=",
"len",
"(",
"r",
".",
"Values",
"[",
"i",
"-",
"1",
"]",
")",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"r",
".",
"Values",
"[",
"i",
"-",
"1",
"]",
"[",
"j",
"]",
")",
"\n",
"}"
] | // Get implements textutil.Table interface | [
"Get",
"implements",
"textutil",
".",
"Table",
"interface"
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/cmd/rqlite/query.go#L33-L52 | train |
rqlite/rqlite | auth/credential_store.go | NewCredentialsStore | func NewCredentialsStore() *CredentialsStore {
return &CredentialsStore{
store: make(map[string]string),
perms: make(map[string]map[string]bool),
}
} | go | func NewCredentialsStore() *CredentialsStore {
return &CredentialsStore{
store: make(map[string]string),
perms: make(map[string]map[string]bool),
}
} | [
"func",
"NewCredentialsStore",
"(",
")",
"*",
"CredentialsStore",
"{",
"return",
"&",
"CredentialsStore",
"{",
"store",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
",",
"perms",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"map",
"[",
"string",
"]",
"bool",
")",
",",
"}",
"\n",
"}"
] | // NewCredentialsStore returns a new instance of a CredentialStore. | [
"NewCredentialsStore",
"returns",
"a",
"new",
"instance",
"of",
"a",
"CredentialStore",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/auth/credential_store.go#L31-L36 | train |
rqlite/rqlite | auth/credential_store.go | Load | func (c *CredentialsStore) Load(r io.Reader) error {
dec := json.NewDecoder(r)
// Read open bracket
_, err := dec.Token()
if err != nil {
return err
}
var cred Credential
for dec.More() {
err := dec.Decode(&cred)
if err != nil {
return err
}
c.store[cred.Username] = cred.Password
c.perms[cred.Username] = make(map[string]bool, len(cred.Perms))
for _, p := range cred.Perms {
c.perms[cred.Username][p] = true
}
}
// Read closing bracket.
_, err = dec.Token()
if err != nil {
return err
}
return nil
} | go | func (c *CredentialsStore) Load(r io.Reader) error {
dec := json.NewDecoder(r)
// Read open bracket
_, err := dec.Token()
if err != nil {
return err
}
var cred Credential
for dec.More() {
err := dec.Decode(&cred)
if err != nil {
return err
}
c.store[cred.Username] = cred.Password
c.perms[cred.Username] = make(map[string]bool, len(cred.Perms))
for _, p := range cred.Perms {
c.perms[cred.Username][p] = true
}
}
// Read closing bracket.
_, err = dec.Token()
if err != nil {
return err
}
return nil
} | [
"func",
"(",
"c",
"*",
"CredentialsStore",
")",
"Load",
"(",
"r",
"io",
".",
"Reader",
")",
"error",
"{",
"dec",
":=",
"json",
".",
"NewDecoder",
"(",
"r",
")",
"\n",
"// Read open bracket",
"_",
",",
"err",
":=",
"dec",
".",
"Token",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"var",
"cred",
"Credential",
"\n",
"for",
"dec",
".",
"More",
"(",
")",
"{",
"err",
":=",
"dec",
".",
"Decode",
"(",
"&",
"cred",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"c",
".",
"store",
"[",
"cred",
".",
"Username",
"]",
"=",
"cred",
".",
"Password",
"\n",
"c",
".",
"perms",
"[",
"cred",
".",
"Username",
"]",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"bool",
",",
"len",
"(",
"cred",
".",
"Perms",
")",
")",
"\n",
"for",
"_",
",",
"p",
":=",
"range",
"cred",
".",
"Perms",
"{",
"c",
".",
"perms",
"[",
"cred",
".",
"Username",
"]",
"[",
"p",
"]",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Read closing bracket.",
"_",
",",
"err",
"=",
"dec",
".",
"Token",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Load loads credential information from a reader. | [
"Load",
"loads",
"credential",
"information",
"from",
"a",
"reader",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/auth/credential_store.go#L39-L67 | train |
rqlite/rqlite | auth/credential_store.go | Check | func (c *CredentialsStore) Check(username, password string) bool {
pw, ok := c.store[username]
if !ok {
return false
}
return password == pw ||
bcrypt.CompareHashAndPassword([]byte(pw), []byte(password)) == nil
} | go | func (c *CredentialsStore) Check(username, password string) bool {
pw, ok := c.store[username]
if !ok {
return false
}
return password == pw ||
bcrypt.CompareHashAndPassword([]byte(pw), []byte(password)) == nil
} | [
"func",
"(",
"c",
"*",
"CredentialsStore",
")",
"Check",
"(",
"username",
",",
"password",
"string",
")",
"bool",
"{",
"pw",
",",
"ok",
":=",
"c",
".",
"store",
"[",
"username",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"password",
"==",
"pw",
"||",
"bcrypt",
".",
"CompareHashAndPassword",
"(",
"[",
"]",
"byte",
"(",
"pw",
")",
",",
"[",
"]",
"byte",
"(",
"password",
")",
")",
"==",
"nil",
"\n",
"}"
] | // Check returns true if the password is correct for the given username. | [
"Check",
"returns",
"true",
"if",
"the",
"password",
"is",
"correct",
"for",
"the",
"given",
"username",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/auth/credential_store.go#L70-L77 | train |
rqlite/rqlite | auth/credential_store.go | CheckRequest | func (c *CredentialsStore) CheckRequest(b BasicAuther) bool {
username, password, ok := b.BasicAuth()
if !ok || !c.Check(username, password) {
return false
}
return true
} | go | func (c *CredentialsStore) CheckRequest(b BasicAuther) bool {
username, password, ok := b.BasicAuth()
if !ok || !c.Check(username, password) {
return false
}
return true
} | [
"func",
"(",
"c",
"*",
"CredentialsStore",
")",
"CheckRequest",
"(",
"b",
"BasicAuther",
")",
"bool",
"{",
"username",
",",
"password",
",",
"ok",
":=",
"b",
".",
"BasicAuth",
"(",
")",
"\n",
"if",
"!",
"ok",
"||",
"!",
"c",
".",
"Check",
"(",
"username",
",",
"password",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // CheckRequest returns true if b contains a valid username and password. | [
"CheckRequest",
"returns",
"true",
"if",
"b",
"contains",
"a",
"valid",
"username",
"and",
"password",
"."
] | 12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3 | https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/auth/credential_store.go#L80-L86 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.