repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
list | docstring
stringlengths 6
2.61k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 85
252
| partition
stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
aarzilli/nucular
|
nucular.go
|
LayoutAvailableHeight
|
func (win *Window) LayoutAvailableHeight() int {
return win.layout.Clip.H - (win.layout.AtY - win.layout.Bounds.Y) - win.style().Spacing.Y - win.layout.Row.Height
}
|
go
|
func (win *Window) LayoutAvailableHeight() int {
return win.layout.Clip.H - (win.layout.AtY - win.layout.Bounds.Y) - win.style().Spacing.Y - win.layout.Row.Height
}
|
[
"func",
"(",
"win",
"*",
"Window",
")",
"LayoutAvailableHeight",
"(",
")",
"int",
"{",
"return",
"win",
".",
"layout",
".",
"Clip",
".",
"H",
"-",
"(",
"win",
".",
"layout",
".",
"AtY",
"-",
"win",
".",
"layout",
".",
"Bounds",
".",
"Y",
")",
"-",
"win",
".",
"style",
"(",
")",
".",
"Spacing",
".",
"Y",
"-",
"win",
".",
"layout",
".",
"Row",
".",
"Height",
"\n",
"}"
] |
// Returns remaining available height of win in scaled units.
|
[
"Returns",
"remaining",
"available",
"height",
"of",
"win",
"in",
"scaled",
"units",
"."
] |
64ec1eba91814ebb417978927206070dd1fc44e1
|
https://github.com/aarzilli/nucular/blob/64ec1eba91814ebb417978927206070dd1fc44e1/nucular.go#L1314-L1316
|
train
|
aarzilli/nucular
|
nucular.go
|
TreePushNamed
|
func (win *Window) TreePushNamed(type_ TreeType, name, title string, initial_open bool) bool {
labelBounds, _, ok := win.TreePushCustom(type_, name, initial_open)
style := win.style()
z := &win.ctx.Style
out := &win.cmds
var text textWidget
if type_ == TreeTab {
var background *nstyle.Item = &z.Tab.Background
if background.Type == nstyle.ItemImage {
text.Background = color.RGBA{0, 0, 0, 0}
} else {
text.Background = background.Data.Color
}
} else {
text.Background = style.Background
}
text.Text = z.Tab.Text
widgetText(out, labelBounds, title, &text, "LC", z.Font)
return ok
}
|
go
|
func (win *Window) TreePushNamed(type_ TreeType, name, title string, initial_open bool) bool {
labelBounds, _, ok := win.TreePushCustom(type_, name, initial_open)
style := win.style()
z := &win.ctx.Style
out := &win.cmds
var text textWidget
if type_ == TreeTab {
var background *nstyle.Item = &z.Tab.Background
if background.Type == nstyle.ItemImage {
text.Background = color.RGBA{0, 0, 0, 0}
} else {
text.Background = background.Data.Color
}
} else {
text.Background = style.Background
}
text.Text = z.Tab.Text
widgetText(out, labelBounds, title, &text, "LC", z.Font)
return ok
}
|
[
"func",
"(",
"win",
"*",
"Window",
")",
"TreePushNamed",
"(",
"type_",
"TreeType",
",",
"name",
",",
"title",
"string",
",",
"initial_open",
"bool",
")",
"bool",
"{",
"labelBounds",
",",
"_",
",",
"ok",
":=",
"win",
".",
"TreePushCustom",
"(",
"type_",
",",
"name",
",",
"initial_open",
")",
"\n\n",
"style",
":=",
"win",
".",
"style",
"(",
")",
"\n",
"z",
":=",
"&",
"win",
".",
"ctx",
".",
"Style",
"\n",
"out",
":=",
"&",
"win",
".",
"cmds",
"\n\n",
"var",
"text",
"textWidget",
"\n",
"if",
"type_",
"==",
"TreeTab",
"{",
"var",
"background",
"*",
"nstyle",
".",
"Item",
"=",
"&",
"z",
".",
"Tab",
".",
"Background",
"\n",
"if",
"background",
".",
"Type",
"==",
"nstyle",
".",
"ItemImage",
"{",
"text",
".",
"Background",
"=",
"color",
".",
"RGBA",
"{",
"0",
",",
"0",
",",
"0",
",",
"0",
"}",
"\n",
"}",
"else",
"{",
"text",
".",
"Background",
"=",
"background",
".",
"Data",
".",
"Color",
"\n",
"}",
"\n",
"}",
"else",
"{",
"text",
".",
"Background",
"=",
"style",
".",
"Background",
"\n",
"}",
"\n\n",
"text",
".",
"Text",
"=",
"z",
".",
"Tab",
".",
"Text",
"\n",
"widgetText",
"(",
"out",
",",
"labelBounds",
",",
"title",
",",
"&",
"text",
",",
"\"",
"\"",
",",
"z",
".",
"Font",
")",
"\n\n",
"return",
"ok",
"\n",
"}"
] |
// Creates a new collapsable section inside win. Returns true
// when the section is open. Widgets that are inside this collapsable
// section should be added to win only when this function returns true.
// Once you are done adding elements to the collapsable section
// call TreePop.
// Initial_open will determine whether this collapsable section
// will be initially open.
// Type_ will determine the style of this collapsable section.
|
[
"Creates",
"a",
"new",
"collapsable",
"section",
"inside",
"win",
".",
"Returns",
"true",
"when",
"the",
"section",
"is",
"open",
".",
"Widgets",
"that",
"are",
"inside",
"this",
"collapsable",
"section",
"should",
"be",
"added",
"to",
"win",
"only",
"when",
"this",
"function",
"returns",
"true",
".",
"Once",
"you",
"are",
"done",
"adding",
"elements",
"to",
"the",
"collapsable",
"section",
"call",
"TreePop",
".",
"Initial_open",
"will",
"determine",
"whether",
"this",
"collapsable",
"section",
"will",
"be",
"initially",
"open",
".",
"Type_",
"will",
"determine",
"the",
"style",
"of",
"this",
"collapsable",
"section",
"."
] |
64ec1eba91814ebb417978927206070dd1fc44e1
|
https://github.com/aarzilli/nucular/blob/64ec1eba91814ebb417978927206070dd1fc44e1/nucular.go#L1362-L1385
|
train
|
aarzilli/nucular
|
nucular.go
|
TreeIsOpen
|
func (win *Window) TreeIsOpen(name string) bool {
node := win.curNode.Children[name]
if node != nil {
return node.Open
}
return false
}
|
go
|
func (win *Window) TreeIsOpen(name string) bool {
node := win.curNode.Children[name]
if node != nil {
return node.Open
}
return false
}
|
[
"func",
"(",
"win",
"*",
"Window",
")",
"TreeIsOpen",
"(",
"name",
"string",
")",
"bool",
"{",
"node",
":=",
"win",
".",
"curNode",
".",
"Children",
"[",
"name",
"]",
"\n",
"if",
"node",
"!=",
"nil",
"{",
"return",
"node",
".",
"Open",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// Returns true if the specified node is open
|
[
"Returns",
"true",
"if",
"the",
"specified",
"node",
"is",
"open"
] |
64ec1eba91814ebb417978927206070dd1fc44e1
|
https://github.com/aarzilli/nucular/blob/64ec1eba91814ebb417978927206070dd1fc44e1/nucular.go#L1492-L1498
|
train
|
aarzilli/nucular
|
nucular.go
|
TreePop
|
func (win *Window) TreePop() {
layout := win.layout
panel_padding := win.style().Padding
layout.AtX -= panel_padding.X + win.ctx.Style.Tab.Indent
layout.Width += panel_padding.X + win.ctx.Style.Tab.Indent
if layout.Row.TreeDepth == 0 {
panic("TreePop called without opened tree nodes")
}
win.curNode = win.curNode.Parent
layout.Row.TreeDepth--
}
|
go
|
func (win *Window) TreePop() {
layout := win.layout
panel_padding := win.style().Padding
layout.AtX -= panel_padding.X + win.ctx.Style.Tab.Indent
layout.Width += panel_padding.X + win.ctx.Style.Tab.Indent
if layout.Row.TreeDepth == 0 {
panic("TreePop called without opened tree nodes")
}
win.curNode = win.curNode.Parent
layout.Row.TreeDepth--
}
|
[
"func",
"(",
"win",
"*",
"Window",
")",
"TreePop",
"(",
")",
"{",
"layout",
":=",
"win",
".",
"layout",
"\n",
"panel_padding",
":=",
"win",
".",
"style",
"(",
")",
".",
"Padding",
"\n",
"layout",
".",
"AtX",
"-=",
"panel_padding",
".",
"X",
"+",
"win",
".",
"ctx",
".",
"Style",
".",
"Tab",
".",
"Indent",
"\n",
"layout",
".",
"Width",
"+=",
"panel_padding",
".",
"X",
"+",
"win",
".",
"ctx",
".",
"Style",
".",
"Tab",
".",
"Indent",
"\n",
"if",
"layout",
".",
"Row",
".",
"TreeDepth",
"==",
"0",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"win",
".",
"curNode",
"=",
"win",
".",
"curNode",
".",
"Parent",
"\n",
"layout",
".",
"Row",
".",
"TreeDepth",
"--",
"\n",
"}"
] |
// TreePop signals that the program is done adding elements to the
// current collapsable section.
|
[
"TreePop",
"signals",
"that",
"the",
"program",
"is",
"done",
"adding",
"elements",
"to",
"the",
"current",
"collapsable",
"section",
"."
] |
64ec1eba91814ebb417978927206070dd1fc44e1
|
https://github.com/aarzilli/nucular/blob/64ec1eba91814ebb417978927206070dd1fc44e1/nucular.go#L1502-L1512
|
train
|
aarzilli/nucular
|
nucular.go
|
LabelWrapColored
|
func (win *Window) LabelWrapColored(str string, color color.RGBA) {
var bounds rect.Rect
var text textWidget
style := &win.ctx.Style
panelAllocSpace(&bounds, win)
item_padding := style.Text.Padding
text.Padding.X = item_padding.X
text.Padding.Y = item_padding.Y
text.Background = win.style().Background
text.Text = color
win.widgets.Add(nstyle.WidgetStateInactive, bounds)
widgetTextWrap(&win.cmds, bounds, []rune(str), &text, win.ctx.Style.Font)
}
|
go
|
func (win *Window) LabelWrapColored(str string, color color.RGBA) {
var bounds rect.Rect
var text textWidget
style := &win.ctx.Style
panelAllocSpace(&bounds, win)
item_padding := style.Text.Padding
text.Padding.X = item_padding.X
text.Padding.Y = item_padding.Y
text.Background = win.style().Background
text.Text = color
win.widgets.Add(nstyle.WidgetStateInactive, bounds)
widgetTextWrap(&win.cmds, bounds, []rune(str), &text, win.ctx.Style.Font)
}
|
[
"func",
"(",
"win",
"*",
"Window",
")",
"LabelWrapColored",
"(",
"str",
"string",
",",
"color",
"color",
".",
"RGBA",
")",
"{",
"var",
"bounds",
"rect",
".",
"Rect",
"\n",
"var",
"text",
"textWidget",
"\n\n",
"style",
":=",
"&",
"win",
".",
"ctx",
".",
"Style",
"\n",
"panelAllocSpace",
"(",
"&",
"bounds",
",",
"win",
")",
"\n",
"item_padding",
":=",
"style",
".",
"Text",
".",
"Padding",
"\n\n",
"text",
".",
"Padding",
".",
"X",
"=",
"item_padding",
".",
"X",
"\n",
"text",
".",
"Padding",
".",
"Y",
"=",
"item_padding",
".",
"Y",
"\n",
"text",
".",
"Background",
"=",
"win",
".",
"style",
"(",
")",
".",
"Background",
"\n",
"text",
".",
"Text",
"=",
"color",
"\n",
"win",
".",
"widgets",
".",
"Add",
"(",
"nstyle",
".",
"WidgetStateInactive",
",",
"bounds",
")",
"\n",
"widgetTextWrap",
"(",
"&",
"win",
".",
"cmds",
",",
"bounds",
",",
"[",
"]",
"rune",
"(",
"str",
")",
",",
"&",
"text",
",",
"win",
".",
"ctx",
".",
"Style",
".",
"Font",
")",
"\n",
"}"
] |
// LabelWrapColored draws a text label with the specified background
// color autowrappping the text.
|
[
"LabelWrapColored",
"draws",
"a",
"text",
"label",
"with",
"the",
"specified",
"background",
"color",
"autowrappping",
"the",
"text",
"."
] |
64ec1eba91814ebb417978927206070dd1fc44e1
|
https://github.com/aarzilli/nucular/blob/64ec1eba91814ebb417978927206070dd1fc44e1/nucular.go#L1541-L1555
|
train
|
aarzilli/nucular
|
nucular.go
|
Label
|
func (win *Window) Label(str string, alignment label.Align) {
win.LabelColored(str, alignment, win.ctx.Style.Text.Color)
}
|
go
|
func (win *Window) Label(str string, alignment label.Align) {
win.LabelColored(str, alignment, win.ctx.Style.Text.Color)
}
|
[
"func",
"(",
"win",
"*",
"Window",
")",
"Label",
"(",
"str",
"string",
",",
"alignment",
"label",
".",
"Align",
")",
"{",
"win",
".",
"LabelColored",
"(",
"str",
",",
"alignment",
",",
"win",
".",
"ctx",
".",
"Style",
".",
"Text",
".",
"Color",
")",
"\n",
"}"
] |
// Label draws a text label.
|
[
"Label",
"draws",
"a",
"text",
"label",
"."
] |
64ec1eba91814ebb417978927206070dd1fc44e1
|
https://github.com/aarzilli/nucular/blob/64ec1eba91814ebb417978927206070dd1fc44e1/nucular.go#L1558-L1560
|
train
|
aarzilli/nucular
|
nucular.go
|
LabelWrap
|
func (win *Window) LabelWrap(str string) {
win.LabelWrapColored(str, win.ctx.Style.Text.Color)
}
|
go
|
func (win *Window) LabelWrap(str string) {
win.LabelWrapColored(str, win.ctx.Style.Text.Color)
}
|
[
"func",
"(",
"win",
"*",
"Window",
")",
"LabelWrap",
"(",
"str",
"string",
")",
"{",
"win",
".",
"LabelWrapColored",
"(",
"str",
",",
"win",
".",
"ctx",
".",
"Style",
".",
"Text",
".",
"Color",
")",
"\n",
"}"
] |
// LabelWrap draws a text label, autowrapping its contents.
|
[
"LabelWrap",
"draws",
"a",
"text",
"label",
"autowrapping",
"its",
"contents",
"."
] |
64ec1eba91814ebb417978927206070dd1fc44e1
|
https://github.com/aarzilli/nucular/blob/64ec1eba91814ebb417978927206070dd1fc44e1/nucular.go#L1563-L1565
|
train
|
aarzilli/nucular
|
nucular.go
|
Image
|
func (win *Window) Image(img *image.RGBA) {
s, bounds, fitting := win.widget()
if fitting != nil {
fitting(img.Bounds().Dx())
}
if !s {
return
}
win.widgets.Add(nstyle.WidgetStateInactive, bounds)
win.cmds.DrawImage(bounds, img)
}
|
go
|
func (win *Window) Image(img *image.RGBA) {
s, bounds, fitting := win.widget()
if fitting != nil {
fitting(img.Bounds().Dx())
}
if !s {
return
}
win.widgets.Add(nstyle.WidgetStateInactive, bounds)
win.cmds.DrawImage(bounds, img)
}
|
[
"func",
"(",
"win",
"*",
"Window",
")",
"Image",
"(",
"img",
"*",
"image",
".",
"RGBA",
")",
"{",
"s",
",",
"bounds",
",",
"fitting",
":=",
"win",
".",
"widget",
"(",
")",
"\n",
"if",
"fitting",
"!=",
"nil",
"{",
"fitting",
"(",
"img",
".",
"Bounds",
"(",
")",
".",
"Dx",
"(",
")",
")",
"\n",
"}",
"\n",
"if",
"!",
"s",
"{",
"return",
"\n",
"}",
"\n",
"win",
".",
"widgets",
".",
"Add",
"(",
"nstyle",
".",
"WidgetStateInactive",
",",
"bounds",
")",
"\n",
"win",
".",
"cmds",
".",
"DrawImage",
"(",
"bounds",
",",
"img",
")",
"\n",
"}"
] |
// Image draws an image.
|
[
"Image",
"draws",
"an",
"image",
"."
] |
64ec1eba91814ebb417978927206070dd1fc44e1
|
https://github.com/aarzilli/nucular/blob/64ec1eba91814ebb417978927206070dd1fc44e1/nucular.go#L1568-L1578
|
train
|
aarzilli/nucular
|
nucular.go
|
Spacing
|
func (win *Window) Spacing(cols int) {
for i := 0; i < cols; i++ {
win.widget()
}
}
|
go
|
func (win *Window) Spacing(cols int) {
for i := 0; i < cols; i++ {
win.widget()
}
}
|
[
"func",
"(",
"win",
"*",
"Window",
")",
"Spacing",
"(",
"cols",
"int",
")",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"cols",
";",
"i",
"++",
"{",
"win",
".",
"widget",
"(",
")",
"\n",
"}",
"\n",
"}"
] |
// Spacing adds empty space
|
[
"Spacing",
"adds",
"empty",
"space"
] |
64ec1eba91814ebb417978927206070dd1fc44e1
|
https://github.com/aarzilli/nucular/blob/64ec1eba91814ebb417978927206070dd1fc44e1/nucular.go#L1581-L1585
|
train
|
aarzilli/nucular
|
nucular.go
|
CustomState
|
func (win *Window) CustomState() nstyle.WidgetStates {
bounds := win.WidgetBounds()
s := true
if !win.layout.Clip.Intersect(&bounds) {
s = false
}
ws := win.widgets.PrevState(bounds)
basicWidgetStateControl(&ws, win.inputMaybe(s), bounds)
return ws
}
|
go
|
func (win *Window) CustomState() nstyle.WidgetStates {
bounds := win.WidgetBounds()
s := true
if !win.layout.Clip.Intersect(&bounds) {
s = false
}
ws := win.widgets.PrevState(bounds)
basicWidgetStateControl(&ws, win.inputMaybe(s), bounds)
return ws
}
|
[
"func",
"(",
"win",
"*",
"Window",
")",
"CustomState",
"(",
")",
"nstyle",
".",
"WidgetStates",
"{",
"bounds",
":=",
"win",
".",
"WidgetBounds",
"(",
")",
"\n",
"s",
":=",
"true",
"\n",
"if",
"!",
"win",
".",
"layout",
".",
"Clip",
".",
"Intersect",
"(",
"&",
"bounds",
")",
"{",
"s",
"=",
"false",
"\n",
"}",
"\n\n",
"ws",
":=",
"win",
".",
"widgets",
".",
"PrevState",
"(",
"bounds",
")",
"\n",
"basicWidgetStateControl",
"(",
"&",
"ws",
",",
"win",
".",
"inputMaybe",
"(",
"s",
")",
",",
"bounds",
")",
"\n",
"return",
"ws",
"\n",
"}"
] |
// CustomState returns the widget state of a custom widget.
|
[
"CustomState",
"returns",
"the",
"widget",
"state",
"of",
"a",
"custom",
"widget",
"."
] |
64ec1eba91814ebb417978927206070dd1fc44e1
|
https://github.com/aarzilli/nucular/blob/64ec1eba91814ebb417978927206070dd1fc44e1/nucular.go#L1588-L1598
|
train
|
aarzilli/nucular
|
nucular.go
|
Custom
|
func (win *Window) Custom(state nstyle.WidgetStates) (bounds rect.Rect, out *command.Buffer) {
var s bool
if s, bounds, _ = win.widget(); !s {
return
}
prevstate := win.widgets.PrevState(bounds)
exitstate := basicWidgetStateControl(&prevstate, win.inputMaybe(s), bounds)
if state != nstyle.WidgetStateActive {
state = exitstate
}
win.widgets.Add(state, bounds)
return bounds, &win.cmds
}
|
go
|
func (win *Window) Custom(state nstyle.WidgetStates) (bounds rect.Rect, out *command.Buffer) {
var s bool
if s, bounds, _ = win.widget(); !s {
return
}
prevstate := win.widgets.PrevState(bounds)
exitstate := basicWidgetStateControl(&prevstate, win.inputMaybe(s), bounds)
if state != nstyle.WidgetStateActive {
state = exitstate
}
win.widgets.Add(state, bounds)
return bounds, &win.cmds
}
|
[
"func",
"(",
"win",
"*",
"Window",
")",
"Custom",
"(",
"state",
"nstyle",
".",
"WidgetStates",
")",
"(",
"bounds",
"rect",
".",
"Rect",
",",
"out",
"*",
"command",
".",
"Buffer",
")",
"{",
"var",
"s",
"bool",
"\n\n",
"if",
"s",
",",
"bounds",
",",
"_",
"=",
"win",
".",
"widget",
"(",
")",
";",
"!",
"s",
"{",
"return",
"\n",
"}",
"\n",
"prevstate",
":=",
"win",
".",
"widgets",
".",
"PrevState",
"(",
"bounds",
")",
"\n",
"exitstate",
":=",
"basicWidgetStateControl",
"(",
"&",
"prevstate",
",",
"win",
".",
"inputMaybe",
"(",
"s",
")",
",",
"bounds",
")",
"\n",
"if",
"state",
"!=",
"nstyle",
".",
"WidgetStateActive",
"{",
"state",
"=",
"exitstate",
"\n",
"}",
"\n",
"win",
".",
"widgets",
".",
"Add",
"(",
"state",
",",
"bounds",
")",
"\n",
"return",
"bounds",
",",
"&",
"win",
".",
"cmds",
"\n",
"}"
] |
// Custom adds a custom widget.
|
[
"Custom",
"adds",
"a",
"custom",
"widget",
"."
] |
64ec1eba91814ebb417978927206070dd1fc44e1
|
https://github.com/aarzilli/nucular/blob/64ec1eba91814ebb417978927206070dd1fc44e1/nucular.go#L1601-L1614
|
train
|
aarzilli/nucular
|
nucular.go
|
Button
|
func (win *Window) Button(lbl label.Label, repeat bool) bool {
style := &win.ctx.Style
state, bounds, fitting := win.widget()
if fitting != nil {
buttonWidth(lbl, &style.Button, style.Font)
}
if !state {
return false
}
in := win.inputMaybe(state)
return doButton(win, lbl, bounds, &style.Button, in, repeat)
}
|
go
|
func (win *Window) Button(lbl label.Label, repeat bool) bool {
style := &win.ctx.Style
state, bounds, fitting := win.widget()
if fitting != nil {
buttonWidth(lbl, &style.Button, style.Font)
}
if !state {
return false
}
in := win.inputMaybe(state)
return doButton(win, lbl, bounds, &style.Button, in, repeat)
}
|
[
"func",
"(",
"win",
"*",
"Window",
")",
"Button",
"(",
"lbl",
"label",
".",
"Label",
",",
"repeat",
"bool",
")",
"bool",
"{",
"style",
":=",
"&",
"win",
".",
"ctx",
".",
"Style",
"\n",
"state",
",",
"bounds",
",",
"fitting",
":=",
"win",
".",
"widget",
"(",
")",
"\n",
"if",
"fitting",
"!=",
"nil",
"{",
"buttonWidth",
"(",
"lbl",
",",
"&",
"style",
".",
"Button",
",",
"style",
".",
"Font",
")",
"\n",
"}",
"\n",
"if",
"!",
"state",
"{",
"return",
"false",
"\n",
"}",
"\n",
"in",
":=",
"win",
".",
"inputMaybe",
"(",
"state",
")",
"\n",
"return",
"doButton",
"(",
"win",
",",
"lbl",
",",
"bounds",
",",
"&",
"style",
".",
"Button",
",",
"in",
",",
"repeat",
")",
"\n",
"}"
] |
// Button adds a button
|
[
"Button",
"adds",
"a",
"button"
] |
64ec1eba91814ebb417978927206070dd1fc44e1
|
https://github.com/aarzilli/nucular/blob/64ec1eba91814ebb417978927206070dd1fc44e1/nucular.go#L1774-L1785
|
train
|
aarzilli/nucular
|
nucular.go
|
SelectableLabel
|
func (win *Window) SelectableLabel(str string, align label.Align, value *bool) bool {
style := &win.ctx.Style
state, bounds, fitting := win.widget()
if fitting != nil {
fitting(selectableWidth(str, &style.Selectable, style.Font))
}
if !state {
return false
}
in := win.inputMaybe(state)
return doSelectable(win, bounds, str, align, value, &style.Selectable, in)
}
|
go
|
func (win *Window) SelectableLabel(str string, align label.Align, value *bool) bool {
style := &win.ctx.Style
state, bounds, fitting := win.widget()
if fitting != nil {
fitting(selectableWidth(str, &style.Selectable, style.Font))
}
if !state {
return false
}
in := win.inputMaybe(state)
return doSelectable(win, bounds, str, align, value, &style.Selectable, in)
}
|
[
"func",
"(",
"win",
"*",
"Window",
")",
"SelectableLabel",
"(",
"str",
"string",
",",
"align",
"label",
".",
"Align",
",",
"value",
"*",
"bool",
")",
"bool",
"{",
"style",
":=",
"&",
"win",
".",
"ctx",
".",
"Style",
"\n",
"state",
",",
"bounds",
",",
"fitting",
":=",
"win",
".",
"widget",
"(",
")",
"\n",
"if",
"fitting",
"!=",
"nil",
"{",
"fitting",
"(",
"selectableWidth",
"(",
"str",
",",
"&",
"style",
".",
"Selectable",
",",
"style",
".",
"Font",
")",
")",
"\n",
"}",
"\n",
"if",
"!",
"state",
"{",
"return",
"false",
"\n",
"}",
"\n",
"in",
":=",
"win",
".",
"inputMaybe",
"(",
"state",
")",
"\n",
"return",
"doSelectable",
"(",
"win",
",",
"bounds",
",",
"str",
",",
"align",
",",
"value",
",",
"&",
"style",
".",
"Selectable",
",",
"in",
")",
"\n",
"}"
] |
// SelectableLabel adds a selectable label. Value is a pointer
// to a flag that will be changed to reflect the selected state of
// this label.
// Returns true when the label is clicked.
|
[
"SelectableLabel",
"adds",
"a",
"selectable",
"label",
".",
"Value",
"is",
"a",
"pointer",
"to",
"a",
"flag",
"that",
"will",
"be",
"changed",
"to",
"reflect",
"the",
"selected",
"state",
"of",
"this",
"label",
".",
"Returns",
"true",
"when",
"the",
"label",
"is",
"clicked",
"."
] |
64ec1eba91814ebb417978927206070dd1fc44e1
|
https://github.com/aarzilli/nucular/blob/64ec1eba91814ebb417978927206070dd1fc44e1/nucular.go#L1827-L1838
|
train
|
aarzilli/nucular
|
nucular.go
|
OptionText
|
func (win *Window) OptionText(text string, is_active bool) bool {
style := &win.ctx.Style
state, bounds, fitting := win.widget()
if fitting != nil {
fitting(toggleWidth(text, toggleOption, &style.Option, style.Font))
}
if !state {
return false
}
in := win.inputMaybe(state)
is_active = doToggle(win, bounds, is_active, text, toggleOption, &style.Option, in, style.Font)
return is_active
}
|
go
|
func (win *Window) OptionText(text string, is_active bool) bool {
style := &win.ctx.Style
state, bounds, fitting := win.widget()
if fitting != nil {
fitting(toggleWidth(text, toggleOption, &style.Option, style.Font))
}
if !state {
return false
}
in := win.inputMaybe(state)
is_active = doToggle(win, bounds, is_active, text, toggleOption, &style.Option, in, style.Font)
return is_active
}
|
[
"func",
"(",
"win",
"*",
"Window",
")",
"OptionText",
"(",
"text",
"string",
",",
"is_active",
"bool",
")",
"bool",
"{",
"style",
":=",
"&",
"win",
".",
"ctx",
".",
"Style",
"\n",
"state",
",",
"bounds",
",",
"fitting",
":=",
"win",
".",
"widget",
"(",
")",
"\n",
"if",
"fitting",
"!=",
"nil",
"{",
"fitting",
"(",
"toggleWidth",
"(",
"text",
",",
"toggleOption",
",",
"&",
"style",
".",
"Option",
",",
"style",
".",
"Font",
")",
")",
"\n",
"}",
"\n",
"if",
"!",
"state",
"{",
"return",
"false",
"\n",
"}",
"\n",
"in",
":=",
"win",
".",
"inputMaybe",
"(",
"state",
")",
"\n",
"is_active",
"=",
"doToggle",
"(",
"win",
",",
"bounds",
",",
"is_active",
",",
"text",
",",
"toggleOption",
",",
"&",
"style",
".",
"Option",
",",
"in",
",",
"style",
".",
"Font",
")",
"\n",
"return",
"is_active",
"\n",
"}"
] |
// OptionText adds a radio button to win. If is_active is true the
// radio button will be drawn selected. Returns true when the button
// is clicked once.
// You are responsible for ensuring that only one radio button is selected at once.
|
[
"OptionText",
"adds",
"a",
"radio",
"button",
"to",
"win",
".",
"If",
"is_active",
"is",
"true",
"the",
"radio",
"button",
"will",
"be",
"drawn",
"selected",
".",
"Returns",
"true",
"when",
"the",
"button",
"is",
"clicked",
"once",
".",
"You",
"are",
"responsible",
"for",
"ensuring",
"that",
"only",
"one",
"radio",
"button",
"is",
"selected",
"at",
"once",
"."
] |
64ec1eba91814ebb417978927206070dd1fc44e1
|
https://github.com/aarzilli/nucular/blob/64ec1eba91814ebb417978927206070dd1fc44e1/nucular.go#L2178-L2190
|
train
|
aarzilli/nucular
|
nucular.go
|
CheckboxText
|
func (win *Window) CheckboxText(text string, active *bool) bool {
state, bounds, fitting := win.widget()
if fitting != nil {
fitting(toggleWidth(text, toggleCheck, &win.ctx.Style.Checkbox, win.ctx.Style.Font))
}
if !state {
return false
}
in := win.inputMaybe(state)
old_active := *active
*active = doToggle(win, bounds, *active, text, toggleCheck, &win.ctx.Style.Checkbox, in, win.ctx.Style.Font)
return *active != old_active
}
|
go
|
func (win *Window) CheckboxText(text string, active *bool) bool {
state, bounds, fitting := win.widget()
if fitting != nil {
fitting(toggleWidth(text, toggleCheck, &win.ctx.Style.Checkbox, win.ctx.Style.Font))
}
if !state {
return false
}
in := win.inputMaybe(state)
old_active := *active
*active = doToggle(win, bounds, *active, text, toggleCheck, &win.ctx.Style.Checkbox, in, win.ctx.Style.Font)
return *active != old_active
}
|
[
"func",
"(",
"win",
"*",
"Window",
")",
"CheckboxText",
"(",
"text",
"string",
",",
"active",
"*",
"bool",
")",
"bool",
"{",
"state",
",",
"bounds",
",",
"fitting",
":=",
"win",
".",
"widget",
"(",
")",
"\n",
"if",
"fitting",
"!=",
"nil",
"{",
"fitting",
"(",
"toggleWidth",
"(",
"text",
",",
"toggleCheck",
",",
"&",
"win",
".",
"ctx",
".",
"Style",
".",
"Checkbox",
",",
"win",
".",
"ctx",
".",
"Style",
".",
"Font",
")",
")",
"\n",
"}",
"\n",
"if",
"!",
"state",
"{",
"return",
"false",
"\n",
"}",
"\n",
"in",
":=",
"win",
".",
"inputMaybe",
"(",
"state",
")",
"\n",
"old_active",
":=",
"*",
"active",
"\n",
"*",
"active",
"=",
"doToggle",
"(",
"win",
",",
"bounds",
",",
"*",
"active",
",",
"text",
",",
"toggleCheck",
",",
"&",
"win",
".",
"ctx",
".",
"Style",
".",
"Checkbox",
",",
"in",
",",
"win",
".",
"ctx",
".",
"Style",
".",
"Font",
")",
"\n",
"return",
"*",
"active",
"!=",
"old_active",
"\n",
"}"
] |
// CheckboxText adds a checkbox button to win. Active will contain
// the checkbox value.
// Returns true when value changes.
|
[
"CheckboxText",
"adds",
"a",
"checkbox",
"button",
"to",
"win",
".",
"Active",
"will",
"contain",
"the",
"checkbox",
"value",
".",
"Returns",
"true",
"when",
"value",
"changes",
"."
] |
64ec1eba91814ebb417978927206070dd1fc44e1
|
https://github.com/aarzilli/nucular/blob/64ec1eba91814ebb417978927206070dd1fc44e1/nucular.go#L2195-L2207
|
train
|
aarzilli/nucular
|
nucular.go
|
SliderFloat
|
func (win *Window) SliderFloat(min_value float64, value *float64, max_value float64, value_step float64) bool {
style := &win.ctx.Style
state, bounds, _ := win.widget()
if !state {
return false
}
in := win.inputMaybe(state)
old_value := *value
*value = doSlider(win, bounds, min_value, old_value, max_value, value_step, &style.Slider, in)
return old_value > *value || old_value < *value
}
|
go
|
func (win *Window) SliderFloat(min_value float64, value *float64, max_value float64, value_step float64) bool {
style := &win.ctx.Style
state, bounds, _ := win.widget()
if !state {
return false
}
in := win.inputMaybe(state)
old_value := *value
*value = doSlider(win, bounds, min_value, old_value, max_value, value_step, &style.Slider, in)
return old_value > *value || old_value < *value
}
|
[
"func",
"(",
"win",
"*",
"Window",
")",
"SliderFloat",
"(",
"min_value",
"float64",
",",
"value",
"*",
"float64",
",",
"max_value",
"float64",
",",
"value_step",
"float64",
")",
"bool",
"{",
"style",
":=",
"&",
"win",
".",
"ctx",
".",
"Style",
"\n",
"state",
",",
"bounds",
",",
"_",
":=",
"win",
".",
"widget",
"(",
")",
"\n",
"if",
"!",
"state",
"{",
"return",
"false",
"\n",
"}",
"\n",
"in",
":=",
"win",
".",
"inputMaybe",
"(",
"state",
")",
"\n\n",
"old_value",
":=",
"*",
"value",
"\n",
"*",
"value",
"=",
"doSlider",
"(",
"win",
",",
"bounds",
",",
"min_value",
",",
"old_value",
",",
"max_value",
",",
"value_step",
",",
"&",
"style",
".",
"Slider",
",",
"in",
")",
"\n",
"return",
"old_value",
">",
"*",
"value",
"||",
"old_value",
"<",
"*",
"value",
"\n",
"}"
] |
// Adds a slider with a floating point value to win.
// Returns true when the slider's value is changed.
|
[
"Adds",
"a",
"slider",
"with",
"a",
"floating",
"point",
"value",
"to",
"win",
".",
"Returns",
"true",
"when",
"the",
"slider",
"s",
"value",
"is",
"changed",
"."
] |
64ec1eba91814ebb417978927206070dd1fc44e1
|
https://github.com/aarzilli/nucular/blob/64ec1eba91814ebb417978927206070dd1fc44e1/nucular.go#L2301-L2312
|
train
|
aarzilli/nucular
|
nucular.go
|
SliderInt
|
func (win *Window) SliderInt(min int, val *int, max int, step int) bool {
value := float64(*val)
ret := win.SliderFloat(float64(min), &value, float64(max), float64(step))
*val = int(value)
return ret
}
|
go
|
func (win *Window) SliderInt(min int, val *int, max int, step int) bool {
value := float64(*val)
ret := win.SliderFloat(float64(min), &value, float64(max), float64(step))
*val = int(value)
return ret
}
|
[
"func",
"(",
"win",
"*",
"Window",
")",
"SliderInt",
"(",
"min",
"int",
",",
"val",
"*",
"int",
",",
"max",
"int",
",",
"step",
"int",
")",
"bool",
"{",
"value",
":=",
"float64",
"(",
"*",
"val",
")",
"\n",
"ret",
":=",
"win",
".",
"SliderFloat",
"(",
"float64",
"(",
"min",
")",
",",
"&",
"value",
",",
"float64",
"(",
"max",
")",
",",
"float64",
"(",
"step",
")",
")",
"\n",
"*",
"val",
"=",
"int",
"(",
"value",
")",
"\n",
"return",
"ret",
"\n",
"}"
] |
// Adds a slider with an integer value to win.
// Returns true when the slider's value changes.
|
[
"Adds",
"a",
"slider",
"with",
"an",
"integer",
"value",
"to",
"win",
".",
"Returns",
"true",
"when",
"the",
"slider",
"s",
"value",
"changes",
"."
] |
64ec1eba91814ebb417978927206070dd1fc44e1
|
https://github.com/aarzilli/nucular/blob/64ec1eba91814ebb417978927206070dd1fc44e1/nucular.go#L2316-L2321
|
train
|
aarzilli/nucular
|
nucular.go
|
Progress
|
func (win *Window) Progress(cur *int, maxval int, is_modifiable bool) bool {
style := &win.ctx.Style
state, bounds, _ := win.widget()
if !state {
return false
}
in := win.inputMaybe(state)
old_value := *cur
*cur = doProgress(win, bounds, *cur, maxval, is_modifiable, &style.Progress, in)
return *cur != old_value
}
|
go
|
func (win *Window) Progress(cur *int, maxval int, is_modifiable bool) bool {
style := &win.ctx.Style
state, bounds, _ := win.widget()
if !state {
return false
}
in := win.inputMaybe(state)
old_value := *cur
*cur = doProgress(win, bounds, *cur, maxval, is_modifiable, &style.Progress, in)
return *cur != old_value
}
|
[
"func",
"(",
"win",
"*",
"Window",
")",
"Progress",
"(",
"cur",
"*",
"int",
",",
"maxval",
"int",
",",
"is_modifiable",
"bool",
")",
"bool",
"{",
"style",
":=",
"&",
"win",
".",
"ctx",
".",
"Style",
"\n",
"state",
",",
"bounds",
",",
"_",
":=",
"win",
".",
"widget",
"(",
")",
"\n",
"if",
"!",
"state",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"in",
":=",
"win",
".",
"inputMaybe",
"(",
"state",
")",
"\n",
"old_value",
":=",
"*",
"cur",
"\n",
"*",
"cur",
"=",
"doProgress",
"(",
"win",
",",
"bounds",
",",
"*",
"cur",
",",
"maxval",
",",
"is_modifiable",
",",
"&",
"style",
".",
"Progress",
",",
"in",
")",
"\n",
"return",
"*",
"cur",
"!=",
"old_value",
"\n",
"}"
] |
// Adds a progress bar to win. if is_modifiable is true the progress
// bar will be user modifiable through click-and-drag.
// Returns true when the progress bar values is modified.
|
[
"Adds",
"a",
"progress",
"bar",
"to",
"win",
".",
"if",
"is_modifiable",
"is",
"true",
"the",
"progress",
"bar",
"will",
"be",
"user",
"modifiable",
"through",
"click",
"-",
"and",
"-",
"drag",
".",
"Returns",
"true",
"when",
"the",
"progress",
"bar",
"values",
"is",
"modified",
"."
] |
64ec1eba91814ebb417978927206070dd1fc44e1
|
https://github.com/aarzilli/nucular/blob/64ec1eba91814ebb417978927206070dd1fc44e1/nucular.go#L2378-L2389
|
train
|
aarzilli/nucular
|
nucular.go
|
PropertyInt
|
func (win *Window) PropertyInt(name string, min int, val *int, max, step, inc_per_pixel int) (changed bool) {
s, bounds, fitting := win.widget()
if fitting != nil {
fitting(propertyWidth(max, &win.ctx.Style.Property, win.ctx.Style.Font))
}
if !s {
return
}
in := win.inputMaybe(s)
text := strconv.Itoa(*val)
ret, delta, ed := win.doProperty(bounds, name, text, FilterDecimal, in)
switch ret {
case doPropertyDec:
*val -= step
case doPropertyInc:
*val += step
case doPropertyDrag:
*val += delta * inc_per_pixel
case doPropertySet:
*val, _ = strconv.Atoi(string(ed.Buffer))
}
changed = ret != doPropertyStay
if changed {
*val = clampInt(min, *val, max)
}
return
}
|
go
|
func (win *Window) PropertyInt(name string, min int, val *int, max, step, inc_per_pixel int) (changed bool) {
s, bounds, fitting := win.widget()
if fitting != nil {
fitting(propertyWidth(max, &win.ctx.Style.Property, win.ctx.Style.Font))
}
if !s {
return
}
in := win.inputMaybe(s)
text := strconv.Itoa(*val)
ret, delta, ed := win.doProperty(bounds, name, text, FilterDecimal, in)
switch ret {
case doPropertyDec:
*val -= step
case doPropertyInc:
*val += step
case doPropertyDrag:
*val += delta * inc_per_pixel
case doPropertySet:
*val, _ = strconv.Atoi(string(ed.Buffer))
}
changed = ret != doPropertyStay
if changed {
*val = clampInt(min, *val, max)
}
return
}
|
[
"func",
"(",
"win",
"*",
"Window",
")",
"PropertyInt",
"(",
"name",
"string",
",",
"min",
"int",
",",
"val",
"*",
"int",
",",
"max",
",",
"step",
",",
"inc_per_pixel",
"int",
")",
"(",
"changed",
"bool",
")",
"{",
"s",
",",
"bounds",
",",
"fitting",
":=",
"win",
".",
"widget",
"(",
")",
"\n",
"if",
"fitting",
"!=",
"nil",
"{",
"fitting",
"(",
"propertyWidth",
"(",
"max",
",",
"&",
"win",
".",
"ctx",
".",
"Style",
".",
"Property",
",",
"win",
".",
"ctx",
".",
"Style",
".",
"Font",
")",
")",
"\n",
"}",
"\n",
"if",
"!",
"s",
"{",
"return",
"\n",
"}",
"\n",
"in",
":=",
"win",
".",
"inputMaybe",
"(",
"s",
")",
"\n",
"text",
":=",
"strconv",
".",
"Itoa",
"(",
"*",
"val",
")",
"\n",
"ret",
",",
"delta",
",",
"ed",
":=",
"win",
".",
"doProperty",
"(",
"bounds",
",",
"name",
",",
"text",
",",
"FilterDecimal",
",",
"in",
")",
"\n",
"switch",
"ret",
"{",
"case",
"doPropertyDec",
":",
"*",
"val",
"-=",
"step",
"\n",
"case",
"doPropertyInc",
":",
"*",
"val",
"+=",
"step",
"\n",
"case",
"doPropertyDrag",
":",
"*",
"val",
"+=",
"delta",
"*",
"inc_per_pixel",
"\n",
"case",
"doPropertySet",
":",
"*",
"val",
",",
"_",
"=",
"strconv",
".",
"Atoi",
"(",
"string",
"(",
"ed",
".",
"Buffer",
")",
")",
"\n",
"}",
"\n",
"changed",
"=",
"ret",
"!=",
"doPropertyStay",
"\n",
"if",
"changed",
"{",
"*",
"val",
"=",
"clampInt",
"(",
"min",
",",
"*",
"val",
",",
"max",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Same as PropertyFloat but with integer values.
|
[
"Same",
"as",
"PropertyFloat",
"but",
"with",
"integer",
"values",
"."
] |
64ec1eba91814ebb417978927206070dd1fc44e1
|
https://github.com/aarzilli/nucular/blob/64ec1eba91814ebb417978927206070dd1fc44e1/nucular.go#L2599-L2625
|
train
|
aarzilli/nucular
|
nucular.go
|
MenuItem
|
func (win *Window) MenuItem(lbl label.Label) bool {
style := &win.ctx.Style
state, bounds := win.widgetFitting(style.ContextualButton.Padding)
if !state {
return false
}
if win.flags&windowHDynamic != 0 {
w := FontWidth(style.Font, lbl.Text) + 2*style.ContextualButton.Padding.X
if w > win.menuItemWidth {
win.menuItemWidth = w
}
}
in := win.inputMaybe(state)
if doButton(win, lbl, bounds, &style.ContextualButton, in, false) {
win.Close()
return true
}
return false
}
|
go
|
func (win *Window) MenuItem(lbl label.Label) bool {
style := &win.ctx.Style
state, bounds := win.widgetFitting(style.ContextualButton.Padding)
if !state {
return false
}
if win.flags&windowHDynamic != 0 {
w := FontWidth(style.Font, lbl.Text) + 2*style.ContextualButton.Padding.X
if w > win.menuItemWidth {
win.menuItemWidth = w
}
}
in := win.inputMaybe(state)
if doButton(win, lbl, bounds, &style.ContextualButton, in, false) {
win.Close()
return true
}
return false
}
|
[
"func",
"(",
"win",
"*",
"Window",
")",
"MenuItem",
"(",
"lbl",
"label",
".",
"Label",
")",
"bool",
"{",
"style",
":=",
"&",
"win",
".",
"ctx",
".",
"Style",
"\n",
"state",
",",
"bounds",
":=",
"win",
".",
"widgetFitting",
"(",
"style",
".",
"ContextualButton",
".",
"Padding",
")",
"\n",
"if",
"!",
"state",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"if",
"win",
".",
"flags",
"&",
"windowHDynamic",
"!=",
"0",
"{",
"w",
":=",
"FontWidth",
"(",
"style",
".",
"Font",
",",
"lbl",
".",
"Text",
")",
"+",
"2",
"*",
"style",
".",
"ContextualButton",
".",
"Padding",
".",
"X",
"\n",
"if",
"w",
">",
"win",
".",
"menuItemWidth",
"{",
"win",
".",
"menuItemWidth",
"=",
"w",
"\n",
"}",
"\n",
"}",
"\n\n",
"in",
":=",
"win",
".",
"inputMaybe",
"(",
"state",
")",
"\n",
"if",
"doButton",
"(",
"win",
",",
"lbl",
",",
"bounds",
",",
"&",
"style",
".",
"ContextualButton",
",",
"in",
",",
"false",
")",
"{",
"win",
".",
"Close",
"(",
")",
"\n",
"return",
"true",
"\n",
"}",
"\n\n",
"return",
"false",
"\n",
"}"
] |
// MenuItem adds a menu item
|
[
"MenuItem",
"adds",
"a",
"menu",
"item"
] |
64ec1eba91814ebb417978927206070dd1fc44e1
|
https://github.com/aarzilli/nucular/blob/64ec1eba91814ebb417978927206070dd1fc44e1/nucular.go#L2745-L2766
|
train
|
aarzilli/nucular
|
nucular.go
|
TooltipOpen
|
func (win *Window) TooltipOpen(width int, scale bool, updateFn UpdateFn) {
in := &win.ctx.Input
if scale {
width = win.ctx.scale(width)
}
var bounds rect.Rect
bounds.W = width
bounds.H = nk_null_rect.H
bounds.X = (in.Mouse.Pos.X + 1)
bounds.Y = (in.Mouse.Pos.Y + 1)
win.ctx.popupOpen(tooltipWindowTitle, WindowDynamic|WindowNoScrollbar|windowTooltip, bounds, false, updateFn)
}
|
go
|
func (win *Window) TooltipOpen(width int, scale bool, updateFn UpdateFn) {
in := &win.ctx.Input
if scale {
width = win.ctx.scale(width)
}
var bounds rect.Rect
bounds.W = width
bounds.H = nk_null_rect.H
bounds.X = (in.Mouse.Pos.X + 1)
bounds.Y = (in.Mouse.Pos.Y + 1)
win.ctx.popupOpen(tooltipWindowTitle, WindowDynamic|WindowNoScrollbar|windowTooltip, bounds, false, updateFn)
}
|
[
"func",
"(",
"win",
"*",
"Window",
")",
"TooltipOpen",
"(",
"width",
"int",
",",
"scale",
"bool",
",",
"updateFn",
"UpdateFn",
")",
"{",
"in",
":=",
"&",
"win",
".",
"ctx",
".",
"Input",
"\n\n",
"if",
"scale",
"{",
"width",
"=",
"win",
".",
"ctx",
".",
"scale",
"(",
"width",
")",
"\n",
"}",
"\n\n",
"var",
"bounds",
"rect",
".",
"Rect",
"\n",
"bounds",
".",
"W",
"=",
"width",
"\n",
"bounds",
".",
"H",
"=",
"nk_null_rect",
".",
"H",
"\n",
"bounds",
".",
"X",
"=",
"(",
"in",
".",
"Mouse",
".",
"Pos",
".",
"X",
"+",
"1",
")",
"\n",
"bounds",
".",
"Y",
"=",
"(",
"in",
".",
"Mouse",
".",
"Pos",
".",
"Y",
"+",
"1",
")",
"\n\n",
"win",
".",
"ctx",
".",
"popupOpen",
"(",
"tooltipWindowTitle",
",",
"WindowDynamic",
"|",
"WindowNoScrollbar",
"|",
"windowTooltip",
",",
"bounds",
",",
"false",
",",
"updateFn",
")",
"\n",
"}"
] |
// Displays a tooltip window.
|
[
"Displays",
"a",
"tooltip",
"window",
"."
] |
64ec1eba91814ebb417978927206070dd1fc44e1
|
https://github.com/aarzilli/nucular/blob/64ec1eba91814ebb417978927206070dd1fc44e1/nucular.go#L2775-L2789
|
train
|
aarzilli/nucular
|
nucular.go
|
Tooltip
|
func (win *Window) Tooltip(text string) {
if text == "" {
return
}
/* fetch configuration data */
padding := win.ctx.Style.TooltipWindow.Padding
item_spacing := win.ctx.Style.TooltipWindow.Spacing
/* calculate size of the text and tooltip */
text_width := FontWidth(win.ctx.Style.Font, text) + win.ctx.scale(4*padding.X) + win.ctx.scale(2*item_spacing.X)
text_height := FontHeight(win.ctx.Style.Font)
win.TooltipOpen(text_width, false, func(tw *Window) {
tw.RowScaled(text_height).Dynamic(1)
tw.Label(text, "LC")
})
}
|
go
|
func (win *Window) Tooltip(text string) {
if text == "" {
return
}
/* fetch configuration data */
padding := win.ctx.Style.TooltipWindow.Padding
item_spacing := win.ctx.Style.TooltipWindow.Spacing
/* calculate size of the text and tooltip */
text_width := FontWidth(win.ctx.Style.Font, text) + win.ctx.scale(4*padding.X) + win.ctx.scale(2*item_spacing.X)
text_height := FontHeight(win.ctx.Style.Font)
win.TooltipOpen(text_width, false, func(tw *Window) {
tw.RowScaled(text_height).Dynamic(1)
tw.Label(text, "LC")
})
}
|
[
"func",
"(",
"win",
"*",
"Window",
")",
"Tooltip",
"(",
"text",
"string",
")",
"{",
"if",
"text",
"==",
"\"",
"\"",
"{",
"return",
"\n",
"}",
"\n\n",
"/* fetch configuration data */",
"padding",
":=",
"win",
".",
"ctx",
".",
"Style",
".",
"TooltipWindow",
".",
"Padding",
"\n",
"item_spacing",
":=",
"win",
".",
"ctx",
".",
"Style",
".",
"TooltipWindow",
".",
"Spacing",
"\n\n",
"/* calculate size of the text and tooltip */",
"text_width",
":=",
"FontWidth",
"(",
"win",
".",
"ctx",
".",
"Style",
".",
"Font",
",",
"text",
")",
"+",
"win",
".",
"ctx",
".",
"scale",
"(",
"4",
"*",
"padding",
".",
"X",
")",
"+",
"win",
".",
"ctx",
".",
"scale",
"(",
"2",
"*",
"item_spacing",
".",
"X",
")",
"\n",
"text_height",
":=",
"FontHeight",
"(",
"win",
".",
"ctx",
".",
"Style",
".",
"Font",
")",
"\n\n",
"win",
".",
"TooltipOpen",
"(",
"text_width",
",",
"false",
",",
"func",
"(",
"tw",
"*",
"Window",
")",
"{",
"tw",
".",
"RowScaled",
"(",
"text_height",
")",
".",
"Dynamic",
"(",
"1",
")",
"\n",
"tw",
".",
"Label",
"(",
"text",
",",
"\"",
"\"",
")",
"\n",
"}",
")",
"\n",
"}"
] |
// Shows a tooltip window containing the specified text.
|
[
"Shows",
"a",
"tooltip",
"window",
"containing",
"the",
"specified",
"text",
"."
] |
64ec1eba91814ebb417978927206070dd1fc44e1
|
https://github.com/aarzilli/nucular/blob/64ec1eba91814ebb417978927206070dd1fc44e1/nucular.go#L2792-L2809
|
train
|
aarzilli/nucular
|
nucular.go
|
ComboSimple
|
func (win *Window) ComboSimple(items []string, selected int, item_height int) int {
if len(items) == 0 {
return selected
}
item_height = win.ctx.scale(item_height)
item_padding := win.ctx.Style.Combo.ButtonPadding.Y
window_padding := win.style().Padding.Y
max_height := (len(items)+1)*item_height + item_padding*3 + window_padding*2
if w := win.Combo(label.T(items[selected]), max_height, nil); w != nil {
w.RowScaled(item_height).Dynamic(1)
for i := range items {
if w.MenuItem(label.TA(items[i], "LC")) {
selected = i
}
}
}
return selected
}
|
go
|
func (win *Window) ComboSimple(items []string, selected int, item_height int) int {
if len(items) == 0 {
return selected
}
item_height = win.ctx.scale(item_height)
item_padding := win.ctx.Style.Combo.ButtonPadding.Y
window_padding := win.style().Padding.Y
max_height := (len(items)+1)*item_height + item_padding*3 + window_padding*2
if w := win.Combo(label.T(items[selected]), max_height, nil); w != nil {
w.RowScaled(item_height).Dynamic(1)
for i := range items {
if w.MenuItem(label.TA(items[i], "LC")) {
selected = i
}
}
}
return selected
}
|
[
"func",
"(",
"win",
"*",
"Window",
")",
"ComboSimple",
"(",
"items",
"[",
"]",
"string",
",",
"selected",
"int",
",",
"item_height",
"int",
")",
"int",
"{",
"if",
"len",
"(",
"items",
")",
"==",
"0",
"{",
"return",
"selected",
"\n",
"}",
"\n\n",
"item_height",
"=",
"win",
".",
"ctx",
".",
"scale",
"(",
"item_height",
")",
"\n",
"item_padding",
":=",
"win",
".",
"ctx",
".",
"Style",
".",
"Combo",
".",
"ButtonPadding",
".",
"Y",
"\n",
"window_padding",
":=",
"win",
".",
"style",
"(",
")",
".",
"Padding",
".",
"Y",
"\n",
"max_height",
":=",
"(",
"len",
"(",
"items",
")",
"+",
"1",
")",
"*",
"item_height",
"+",
"item_padding",
"*",
"3",
"+",
"window_padding",
"*",
"2",
"\n",
"if",
"w",
":=",
"win",
".",
"Combo",
"(",
"label",
".",
"T",
"(",
"items",
"[",
"selected",
"]",
")",
",",
"max_height",
",",
"nil",
")",
";",
"w",
"!=",
"nil",
"{",
"w",
".",
"RowScaled",
"(",
"item_height",
")",
".",
"Dynamic",
"(",
"1",
")",
"\n",
"for",
"i",
":=",
"range",
"items",
"{",
"if",
"w",
".",
"MenuItem",
"(",
"label",
".",
"TA",
"(",
"items",
"[",
"i",
"]",
",",
"\"",
"\"",
")",
")",
"{",
"selected",
"=",
"i",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"selected",
"\n",
"}"
] |
// Adds a drop-down list to win. The contents are specified by items,
// with selected being the index of the selected item.
|
[
"Adds",
"a",
"drop",
"-",
"down",
"list",
"to",
"win",
".",
"The",
"contents",
"are",
"specified",
"by",
"items",
"with",
"selected",
"being",
"the",
"index",
"of",
"the",
"selected",
"item",
"."
] |
64ec1eba91814ebb417978927206070dd1fc44e1
|
https://github.com/aarzilli/nucular/blob/64ec1eba91814ebb417978927206070dd1fc44e1/nucular.go#L2869-L2887
|
train
|
aarzilli/nucular
|
nucular.go
|
GroupEnd
|
func (win *Window) GroupEnd() {
panelEnd(win.ctx, win)
win.parent.usingSub = false
// immediate drawing
win.parent.cmds.Commands = append(win.parent.cmds.Commands, win.cmds.Commands...)
}
|
go
|
func (win *Window) GroupEnd() {
panelEnd(win.ctx, win)
win.parent.usingSub = false
// immediate drawing
win.parent.cmds.Commands = append(win.parent.cmds.Commands, win.cmds.Commands...)
}
|
[
"func",
"(",
"win",
"*",
"Window",
")",
"GroupEnd",
"(",
")",
"{",
"panelEnd",
"(",
"win",
".",
"ctx",
",",
"win",
")",
"\n",
"win",
".",
"parent",
".",
"usingSub",
"=",
"false",
"\n\n",
"// immediate drawing",
"win",
".",
"parent",
".",
"cmds",
".",
"Commands",
"=",
"append",
"(",
"win",
".",
"parent",
".",
"cmds",
".",
"Commands",
",",
"win",
".",
"cmds",
".",
"Commands",
"...",
")",
"\n",
"}"
] |
// Signals that you are done adding widgets to a group.
|
[
"Signals",
"that",
"you",
"are",
"done",
"adding",
"widgets",
"to",
"a",
"group",
"."
] |
64ec1eba91814ebb417978927206070dd1fc44e1
|
https://github.com/aarzilli/nucular/blob/64ec1eba91814ebb417978927206070dd1fc44e1/nucular.go#L2989-L2995
|
train
|
goadapp/goad
|
lambda/lambda.go
|
newLambda
|
func newLambda(s LambdaSettings) *goadLambda {
setLambdaExecTimeout(&s)
setDefaultConcurrencyCount(&s)
l := &goadLambda{}
l.Settings = s
l.Metrics = NewRequestMetric(s.LambdaRegion, s.RunnerID)
remainingRequestCount := s.MaxRequestCount - s.CompletedRequestCount
if remainingRequestCount < 0 {
remainingRequestCount = 0
}
l.setupHTTPClientForSelfsignedTLS()
awsSqsConfig := l.setupAwsConfig()
l.setupAwsSqsAdapter(awsSqsConfig)
l.setupJobQueue(remainingRequestCount)
l.results = make(chan requestResult)
return l
}
|
go
|
func newLambda(s LambdaSettings) *goadLambda {
setLambdaExecTimeout(&s)
setDefaultConcurrencyCount(&s)
l := &goadLambda{}
l.Settings = s
l.Metrics = NewRequestMetric(s.LambdaRegion, s.RunnerID)
remainingRequestCount := s.MaxRequestCount - s.CompletedRequestCount
if remainingRequestCount < 0 {
remainingRequestCount = 0
}
l.setupHTTPClientForSelfsignedTLS()
awsSqsConfig := l.setupAwsConfig()
l.setupAwsSqsAdapter(awsSqsConfig)
l.setupJobQueue(remainingRequestCount)
l.results = make(chan requestResult)
return l
}
|
[
"func",
"newLambda",
"(",
"s",
"LambdaSettings",
")",
"*",
"goadLambda",
"{",
"setLambdaExecTimeout",
"(",
"&",
"s",
")",
"\n",
"setDefaultConcurrencyCount",
"(",
"&",
"s",
")",
"\n\n",
"l",
":=",
"&",
"goadLambda",
"{",
"}",
"\n",
"l",
".",
"Settings",
"=",
"s",
"\n\n",
"l",
".",
"Metrics",
"=",
"NewRequestMetric",
"(",
"s",
".",
"LambdaRegion",
",",
"s",
".",
"RunnerID",
")",
"\n",
"remainingRequestCount",
":=",
"s",
".",
"MaxRequestCount",
"-",
"s",
".",
"CompletedRequestCount",
"\n",
"if",
"remainingRequestCount",
"<",
"0",
"{",
"remainingRequestCount",
"=",
"0",
"\n",
"}",
"\n",
"l",
".",
"setupHTTPClientForSelfsignedTLS",
"(",
")",
"\n",
"awsSqsConfig",
":=",
"l",
".",
"setupAwsConfig",
"(",
")",
"\n",
"l",
".",
"setupAwsSqsAdapter",
"(",
"awsSqsConfig",
")",
"\n",
"l",
".",
"setupJobQueue",
"(",
"remainingRequestCount",
")",
"\n",
"l",
".",
"results",
"=",
"make",
"(",
"chan",
"requestResult",
")",
"\n",
"return",
"l",
"\n",
"}"
] |
// newLambda creates a new Lambda to execute a load test from a given
// LambdaSettings
|
[
"newLambda",
"creates",
"a",
"new",
"Lambda",
"to",
"execute",
"a",
"load",
"test",
"from",
"a",
"given",
"LambdaSettings"
] |
612187f4fd0d04b18f7181e8434717a175341ada
|
https://github.com/goadapp/goad/blob/612187f4fd0d04b18f7181e8434717a175341ada/lambda/lambda.go#L200-L218
|
train
|
goadapp/goad
|
result/result.go
|
Regions
|
func (r *LambdaResults) Regions() []string {
regions := make([]string, 0)
for _, lambda := range r.Lambdas {
if lambda.Region != "" {
regions = append(regions, lambda.Region)
}
}
regions = util.RemoveDuplicates(regions)
sort.Strings(regions)
return regions
}
|
go
|
func (r *LambdaResults) Regions() []string {
regions := make([]string, 0)
for _, lambda := range r.Lambdas {
if lambda.Region != "" {
regions = append(regions, lambda.Region)
}
}
regions = util.RemoveDuplicates(regions)
sort.Strings(regions)
return regions
}
|
[
"func",
"(",
"r",
"*",
"LambdaResults",
")",
"Regions",
"(",
")",
"[",
"]",
"string",
"{",
"regions",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
")",
"\n",
"for",
"_",
",",
"lambda",
":=",
"range",
"r",
".",
"Lambdas",
"{",
"if",
"lambda",
".",
"Region",
"!=",
"\"",
"\"",
"{",
"regions",
"=",
"append",
"(",
"regions",
",",
"lambda",
".",
"Region",
")",
"\n",
"}",
"\n",
"}",
"\n",
"regions",
"=",
"util",
".",
"RemoveDuplicates",
"(",
"regions",
")",
"\n",
"sort",
".",
"Strings",
"(",
"regions",
")",
"\n",
"return",
"regions",
"\n",
"}"
] |
// Regions the LambdaResults were collected from
|
[
"Regions",
"the",
"LambdaResults",
"were",
"collected",
"from"
] |
612187f4fd0d04b18f7181e8434717a175341ada
|
https://github.com/goadapp/goad/blob/612187f4fd0d04b18f7181e8434717a175341ada/result/result.go#L37-L47
|
train
|
goadapp/goad
|
result/result.go
|
RegionsData
|
func (r *LambdaResults) RegionsData() map[string]AggData {
regionsMap := make(map[string]AggData)
for _, region := range r.Regions() {
regionsMap[region] = sumAggData(r.ResultsForRegion(region))
}
return regionsMap
}
|
go
|
func (r *LambdaResults) RegionsData() map[string]AggData {
regionsMap := make(map[string]AggData)
for _, region := range r.Regions() {
regionsMap[region] = sumAggData(r.ResultsForRegion(region))
}
return regionsMap
}
|
[
"func",
"(",
"r",
"*",
"LambdaResults",
")",
"RegionsData",
"(",
")",
"map",
"[",
"string",
"]",
"AggData",
"{",
"regionsMap",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"AggData",
")",
"\n",
"for",
"_",
",",
"region",
":=",
"range",
"r",
".",
"Regions",
"(",
")",
"{",
"regionsMap",
"[",
"region",
"]",
"=",
"sumAggData",
"(",
"r",
".",
"ResultsForRegion",
"(",
"region",
")",
")",
"\n",
"}",
"\n",
"return",
"regionsMap",
"\n",
"}"
] |
// RegionsData aggregates the individual lambda functions results per region
|
[
"RegionsData",
"aggregates",
"the",
"individual",
"lambda",
"functions",
"results",
"per",
"region"
] |
612187f4fd0d04b18f7181e8434717a175341ada
|
https://github.com/goadapp/goad/blob/612187f4fd0d04b18f7181e8434717a175341ada/result/result.go#L50-L56
|
train
|
goadapp/goad
|
result/result.go
|
ResultsForRegion
|
func (r *LambdaResults) ResultsForRegion(region string) []AggData {
lambdasOfRegion := make([]AggData, 0)
for _, lambda := range r.Lambdas {
if lambda.Region == region {
lambdasOfRegion = append(lambdasOfRegion, lambda)
}
}
return lambdasOfRegion
}
|
go
|
func (r *LambdaResults) ResultsForRegion(region string) []AggData {
lambdasOfRegion := make([]AggData, 0)
for _, lambda := range r.Lambdas {
if lambda.Region == region {
lambdasOfRegion = append(lambdasOfRegion, lambda)
}
}
return lambdasOfRegion
}
|
[
"func",
"(",
"r",
"*",
"LambdaResults",
")",
"ResultsForRegion",
"(",
"region",
"string",
")",
"[",
"]",
"AggData",
"{",
"lambdasOfRegion",
":=",
"make",
"(",
"[",
"]",
"AggData",
",",
"0",
")",
"\n",
"for",
"_",
",",
"lambda",
":=",
"range",
"r",
".",
"Lambdas",
"{",
"if",
"lambda",
".",
"Region",
"==",
"region",
"{",
"lambdasOfRegion",
"=",
"append",
"(",
"lambdasOfRegion",
",",
"lambda",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"lambdasOfRegion",
"\n",
"}"
] |
//ResultsForRegion return the sum of results for a given regions
|
[
"ResultsForRegion",
"return",
"the",
"sum",
"of",
"results",
"for",
"a",
"given",
"regions"
] |
612187f4fd0d04b18f7181e8434717a175341ada
|
https://github.com/goadapp/goad/blob/612187f4fd0d04b18f7181e8434717a175341ada/result/result.go#L64-L72
|
train
|
goadapp/goad
|
cli/cli.go
|
Run
|
func Run() {
app.HelpFlag.Short('h')
app.Version(version.String())
app.VersionFlag.Short('V')
config := aggregateConfiguration()
err := config.Check()
goad.HandleErr(err)
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM) // but interrupts from kbd are blocked by termbox
result := start(config, sigChan)
defer printSummary(result)
if config.Output != "" {
defer saveJSONSummary(*outputFile, result)
}
}
|
go
|
func Run() {
app.HelpFlag.Short('h')
app.Version(version.String())
app.VersionFlag.Short('V')
config := aggregateConfiguration()
err := config.Check()
goad.HandleErr(err)
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM) // but interrupts from kbd are blocked by termbox
result := start(config, sigChan)
defer printSummary(result)
if config.Output != "" {
defer saveJSONSummary(*outputFile, result)
}
}
|
[
"func",
"Run",
"(",
")",
"{",
"app",
".",
"HelpFlag",
".",
"Short",
"(",
"'h'",
")",
"\n",
"app",
".",
"Version",
"(",
"version",
".",
"String",
"(",
")",
")",
"\n",
"app",
".",
"VersionFlag",
".",
"Short",
"(",
"'V'",
")",
"\n\n",
"config",
":=",
"aggregateConfiguration",
"(",
")",
"\n",
"err",
":=",
"config",
".",
"Check",
"(",
")",
"\n",
"goad",
".",
"HandleErr",
"(",
"err",
")",
"\n\n",
"sigChan",
":=",
"make",
"(",
"chan",
"os",
".",
"Signal",
",",
"1",
")",
"\n",
"signal",
".",
"Notify",
"(",
"sigChan",
",",
"syscall",
".",
"SIGINT",
",",
"syscall",
".",
"SIGTERM",
")",
"// but interrupts from kbd are blocked by termbox",
"\n\n",
"result",
":=",
"start",
"(",
"config",
",",
"sigChan",
")",
"\n",
"defer",
"printSummary",
"(",
"result",
")",
"\n",
"if",
"config",
".",
"Output",
"!=",
"\"",
"\"",
"{",
"defer",
"saveJSONSummary",
"(",
"*",
"outputFile",
",",
"result",
")",
"\n",
"}",
"\n",
"}"
] |
// Run the goad cli
|
[
"Run",
"the",
"goad",
"cli"
] |
612187f4fd0d04b18f7181e8434717a175341ada
|
https://github.com/goadapp/goad/blob/612187f4fd0d04b18f7181e8434717a175341ada/cli/cli.go#L77-L94
|
train
|
goadapp/goad
|
cli/cli.go
|
clearLogo
|
func clearLogo() {
w, h := termbox.Size()
clearStr := strings.Repeat(" ", w)
for i := 0; i < h-1; i++ {
renderString(0, i, clearStr, coldef, coldef)
}
}
|
go
|
func clearLogo() {
w, h := termbox.Size()
clearStr := strings.Repeat(" ", w)
for i := 0; i < h-1; i++ {
renderString(0, i, clearStr, coldef, coldef)
}
}
|
[
"func",
"clearLogo",
"(",
")",
"{",
"w",
",",
"h",
":=",
"termbox",
".",
"Size",
"(",
")",
"\n",
"clearStr",
":=",
"strings",
".",
"Repeat",
"(",
"\"",
"\"",
",",
"w",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"h",
"-",
"1",
";",
"i",
"++",
"{",
"renderString",
"(",
"0",
",",
"i",
",",
"clearStr",
",",
"coldef",
",",
"coldef",
")",
"\n",
"}",
"\n",
"}"
] |
// Also clears loading message
|
[
"Also",
"clears",
"loading",
"message"
] |
612187f4fd0d04b18f7181e8434717a175341ada
|
https://github.com/goadapp/goad/blob/612187f4fd0d04b18f7181e8434717a175341ada/cli/cli.go#L381-L387
|
train
|
goadapp/goad
|
cli/cli.go
|
renderRegion
|
func renderRegion(data result.AggData, y int) int {
x := 0
renderString(x, y, "Region: ", termbox.ColorWhite, termbox.ColorBlue)
x += 8
regionStr := fmt.Sprintf("%s", data.Region)
renderString(x, y, regionStr, termbox.ColorWhite|termbox.AttrBold, termbox.ColorBlue)
x = 0
y++
headingStr := " TotReqs TotBytes AvgTime AvgReq/s (post)unzip"
renderString(x, y, headingStr, coldef|termbox.AttrBold, coldef)
y++
resultStr := fmt.Sprintf("%10d %10s %7.3fs %10.2f %10s/s", data.TotalReqs, humanize.Bytes(uint64(data.TotBytesRead)), float64(data.AveTimeForReq)/nano, data.AveReqPerSec, humanize.Bytes(uint64(data.AveKBytesPerSec)))
renderString(x, y, resultStr, coldef, coldef)
y++
headingStr = " Slowest Fastest Timeouts TotErrors"
renderString(x, y, headingStr, coldef|termbox.AttrBold, coldef)
y++
resultStr = fmt.Sprintf(" %7.3fs %7.3fs %10d %10d", float64(data.Slowest)/nano, float64(data.Fastest)/nano, data.TotalTimedOut, totErrors(data))
renderString(x, y, resultStr, coldef, coldef)
y++
return y
}
|
go
|
func renderRegion(data result.AggData, y int) int {
x := 0
renderString(x, y, "Region: ", termbox.ColorWhite, termbox.ColorBlue)
x += 8
regionStr := fmt.Sprintf("%s", data.Region)
renderString(x, y, regionStr, termbox.ColorWhite|termbox.AttrBold, termbox.ColorBlue)
x = 0
y++
headingStr := " TotReqs TotBytes AvgTime AvgReq/s (post)unzip"
renderString(x, y, headingStr, coldef|termbox.AttrBold, coldef)
y++
resultStr := fmt.Sprintf("%10d %10s %7.3fs %10.2f %10s/s", data.TotalReqs, humanize.Bytes(uint64(data.TotBytesRead)), float64(data.AveTimeForReq)/nano, data.AveReqPerSec, humanize.Bytes(uint64(data.AveKBytesPerSec)))
renderString(x, y, resultStr, coldef, coldef)
y++
headingStr = " Slowest Fastest Timeouts TotErrors"
renderString(x, y, headingStr, coldef|termbox.AttrBold, coldef)
y++
resultStr = fmt.Sprintf(" %7.3fs %7.3fs %10d %10d", float64(data.Slowest)/nano, float64(data.Fastest)/nano, data.TotalTimedOut, totErrors(data))
renderString(x, y, resultStr, coldef, coldef)
y++
return y
}
|
[
"func",
"renderRegion",
"(",
"data",
"result",
".",
"AggData",
",",
"y",
"int",
")",
"int",
"{",
"x",
":=",
"0",
"\n",
"renderString",
"(",
"x",
",",
"y",
",",
"\"",
"\"",
",",
"termbox",
".",
"ColorWhite",
",",
"termbox",
".",
"ColorBlue",
")",
"\n",
"x",
"+=",
"8",
"\n",
"regionStr",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"data",
".",
"Region",
")",
"\n",
"renderString",
"(",
"x",
",",
"y",
",",
"regionStr",
",",
"termbox",
".",
"ColorWhite",
"|",
"termbox",
".",
"AttrBold",
",",
"termbox",
".",
"ColorBlue",
")",
"\n",
"x",
"=",
"0",
"\n",
"y",
"++",
"\n",
"headingStr",
":=",
"\"",
"\"",
"\n",
"renderString",
"(",
"x",
",",
"y",
",",
"headingStr",
",",
"coldef",
"|",
"termbox",
".",
"AttrBold",
",",
"coldef",
")",
"\n",
"y",
"++",
"\n",
"resultStr",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"data",
".",
"TotalReqs",
",",
"humanize",
".",
"Bytes",
"(",
"uint64",
"(",
"data",
".",
"TotBytesRead",
")",
")",
",",
"float64",
"(",
"data",
".",
"AveTimeForReq",
")",
"/",
"nano",
",",
"data",
".",
"AveReqPerSec",
",",
"humanize",
".",
"Bytes",
"(",
"uint64",
"(",
"data",
".",
"AveKBytesPerSec",
")",
")",
")",
"\n",
"renderString",
"(",
"x",
",",
"y",
",",
"resultStr",
",",
"coldef",
",",
"coldef",
")",
"\n",
"y",
"++",
"\n",
"headingStr",
"=",
"\"",
"\"",
"\n",
"renderString",
"(",
"x",
",",
"y",
",",
"headingStr",
",",
"coldef",
"|",
"termbox",
".",
"AttrBold",
",",
"coldef",
")",
"\n",
"y",
"++",
"\n",
"resultStr",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"float64",
"(",
"data",
".",
"Slowest",
")",
"/",
"nano",
",",
"float64",
"(",
"data",
".",
"Fastest",
")",
"/",
"nano",
",",
"data",
".",
"TotalTimedOut",
",",
"totErrors",
"(",
"data",
")",
")",
"\n",
"renderString",
"(",
"x",
",",
"y",
",",
"resultStr",
",",
"coldef",
",",
"coldef",
")",
"\n",
"y",
"++",
"\n\n",
"return",
"y",
"\n",
"}"
] |
// renderRegion returns the y for the next empty line
|
[
"renderRegion",
"returns",
"the",
"y",
"for",
"the",
"next",
"empty",
"line"
] |
612187f4fd0d04b18f7181e8434717a175341ada
|
https://github.com/goadapp/goad/blob/612187f4fd0d04b18f7181e8434717a175341ada/cli/cli.go#L390-L412
|
train
|
goadapp/goad
|
goad/goad.go
|
Start
|
func Start(t *types.TestConfig) (<-chan *result.LambdaResults, func()) {
var infra infrastructure.Infrastructure
if t.RunDocker {
infra = dockerinfra.New(t)
} else {
infra = awsinfra.New(t)
}
teardown, err := infra.Setup()
HandleErr(err)
t.Lambdas = numberOfLambdas(t.Concurrency, len(t.Regions))
infrastructure.InvokeLambdas(infra)
results := make(chan *result.LambdaResults)
go func() {
for result := range infrastructure.Aggregate(infra) {
results <- result
}
close(results)
}()
return results, teardown
}
|
go
|
func Start(t *types.TestConfig) (<-chan *result.LambdaResults, func()) {
var infra infrastructure.Infrastructure
if t.RunDocker {
infra = dockerinfra.New(t)
} else {
infra = awsinfra.New(t)
}
teardown, err := infra.Setup()
HandleErr(err)
t.Lambdas = numberOfLambdas(t.Concurrency, len(t.Regions))
infrastructure.InvokeLambdas(infra)
results := make(chan *result.LambdaResults)
go func() {
for result := range infrastructure.Aggregate(infra) {
results <- result
}
close(results)
}()
return results, teardown
}
|
[
"func",
"Start",
"(",
"t",
"*",
"types",
".",
"TestConfig",
")",
"(",
"<-",
"chan",
"*",
"result",
".",
"LambdaResults",
",",
"func",
"(",
")",
")",
"{",
"var",
"infra",
"infrastructure",
".",
"Infrastructure",
"\n",
"if",
"t",
".",
"RunDocker",
"{",
"infra",
"=",
"dockerinfra",
".",
"New",
"(",
"t",
")",
"\n",
"}",
"else",
"{",
"infra",
"=",
"awsinfra",
".",
"New",
"(",
"t",
")",
"\n",
"}",
"\n",
"teardown",
",",
"err",
":=",
"infra",
".",
"Setup",
"(",
")",
"\n",
"HandleErr",
"(",
"err",
")",
"\n",
"t",
".",
"Lambdas",
"=",
"numberOfLambdas",
"(",
"t",
".",
"Concurrency",
",",
"len",
"(",
"t",
".",
"Regions",
")",
")",
"\n",
"infrastructure",
".",
"InvokeLambdas",
"(",
"infra",
")",
"\n\n",
"results",
":=",
"make",
"(",
"chan",
"*",
"result",
".",
"LambdaResults",
")",
"\n\n",
"go",
"func",
"(",
")",
"{",
"for",
"result",
":=",
"range",
"infrastructure",
".",
"Aggregate",
"(",
"infra",
")",
"{",
"results",
"<-",
"result",
"\n",
"}",
"\n",
"close",
"(",
"results",
")",
"\n",
"}",
"(",
")",
"\n\n",
"return",
"results",
",",
"teardown",
"\n",
"}"
] |
// Start a test
|
[
"Start",
"a",
"test"
] |
612187f4fd0d04b18f7181e8434717a175341ada
|
https://github.com/goadapp/goad/blob/612187f4fd0d04b18f7181e8434717a175341ada/goad/goad.go#L12-L35
|
train
|
goadapp/goad
|
infrastructure/aws/sqsadapter/sqsadapter.go
|
New
|
func New(awsConfig *aws.Config, queueURL string) *Adapter {
return &Adapter{getClient(awsConfig), queueURL}
}
|
go
|
func New(awsConfig *aws.Config, queueURL string) *Adapter {
return &Adapter{getClient(awsConfig), queueURL}
}
|
[
"func",
"New",
"(",
"awsConfig",
"*",
"aws",
".",
"Config",
",",
"queueURL",
"string",
")",
"*",
"Adapter",
"{",
"return",
"&",
"Adapter",
"{",
"getClient",
"(",
"awsConfig",
")",
",",
"queueURL",
"}",
"\n",
"}"
] |
// NewSQSAdapter returns a new sqs adator object
|
[
"NewSQSAdapter",
"returns",
"a",
"new",
"sqs",
"adator",
"object"
] |
612187f4fd0d04b18f7181e8434717a175341ada
|
https://github.com/goadapp/goad/blob/612187f4fd0d04b18f7181e8434717a175341ada/infrastructure/aws/sqsadapter/sqsadapter.go#L26-L28
|
train
|
goadapp/goad
|
infrastructure/aws/sqsadapter/sqsadapter.go
|
Receive
|
func (adaptor Adapter) Receive() []*api.RunnerResult {
params := &sqs.ReceiveMessageInput{
QueueUrl: aws.String(adaptor.QueueURL),
MaxNumberOfMessages: aws.Int64(10),
VisibilityTimeout: aws.Int64(1),
WaitTimeSeconds: aws.Int64(1),
}
resp, err := adaptor.Client.ReceiveMessage(params)
if err != nil {
fmt.Println(err.Error())
return nil
}
if len(resp.Messages) == 0 {
return nil
}
items := resp.Messages
results := make([]*api.RunnerResult, 0)
deleteEntries := make([]*sqs.DeleteMessageBatchRequestEntry, 0)
for _, item := range items {
result, jsonerr := resultFromJSON(*item.Body)
if jsonerr != nil {
fmt.Println(err.Error())
return nil
}
deleteEntries = append(deleteEntries, &sqs.DeleteMessageBatchRequestEntry{
Id: aws.String(*item.MessageId),
ReceiptHandle: aws.String(*item.ReceiptHandle),
})
results = append(results, result)
}
deleteParams := &sqs.DeleteMessageBatchInput{
Entries: deleteEntries,
QueueUrl: aws.String(adaptor.QueueURL),
}
_, delerr := adaptor.Client.DeleteMessageBatch(deleteParams)
if delerr != nil {
fmt.Println(delerr.Error())
return nil
}
return results
}
|
go
|
func (adaptor Adapter) Receive() []*api.RunnerResult {
params := &sqs.ReceiveMessageInput{
QueueUrl: aws.String(adaptor.QueueURL),
MaxNumberOfMessages: aws.Int64(10),
VisibilityTimeout: aws.Int64(1),
WaitTimeSeconds: aws.Int64(1),
}
resp, err := adaptor.Client.ReceiveMessage(params)
if err != nil {
fmt.Println(err.Error())
return nil
}
if len(resp.Messages) == 0 {
return nil
}
items := resp.Messages
results := make([]*api.RunnerResult, 0)
deleteEntries := make([]*sqs.DeleteMessageBatchRequestEntry, 0)
for _, item := range items {
result, jsonerr := resultFromJSON(*item.Body)
if jsonerr != nil {
fmt.Println(err.Error())
return nil
}
deleteEntries = append(deleteEntries, &sqs.DeleteMessageBatchRequestEntry{
Id: aws.String(*item.MessageId),
ReceiptHandle: aws.String(*item.ReceiptHandle),
})
results = append(results, result)
}
deleteParams := &sqs.DeleteMessageBatchInput{
Entries: deleteEntries,
QueueUrl: aws.String(adaptor.QueueURL),
}
_, delerr := adaptor.Client.DeleteMessageBatch(deleteParams)
if delerr != nil {
fmt.Println(delerr.Error())
return nil
}
return results
}
|
[
"func",
"(",
"adaptor",
"Adapter",
")",
"Receive",
"(",
")",
"[",
"]",
"*",
"api",
".",
"RunnerResult",
"{",
"params",
":=",
"&",
"sqs",
".",
"ReceiveMessageInput",
"{",
"QueueUrl",
":",
"aws",
".",
"String",
"(",
"adaptor",
".",
"QueueURL",
")",
",",
"MaxNumberOfMessages",
":",
"aws",
".",
"Int64",
"(",
"10",
")",
",",
"VisibilityTimeout",
":",
"aws",
".",
"Int64",
"(",
"1",
")",
",",
"WaitTimeSeconds",
":",
"aws",
".",
"Int64",
"(",
"1",
")",
",",
"}",
"\n",
"resp",
",",
"err",
":=",
"adaptor",
".",
"Client",
".",
"ReceiveMessage",
"(",
"params",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Println",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"resp",
".",
"Messages",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"items",
":=",
"resp",
".",
"Messages",
"\n",
"results",
":=",
"make",
"(",
"[",
"]",
"*",
"api",
".",
"RunnerResult",
",",
"0",
")",
"\n",
"deleteEntries",
":=",
"make",
"(",
"[",
"]",
"*",
"sqs",
".",
"DeleteMessageBatchRequestEntry",
",",
"0",
")",
"\n",
"for",
"_",
",",
"item",
":=",
"range",
"items",
"{",
"result",
",",
"jsonerr",
":=",
"resultFromJSON",
"(",
"*",
"item",
".",
"Body",
")",
"\n",
"if",
"jsonerr",
"!=",
"nil",
"{",
"fmt",
".",
"Println",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"deleteEntries",
"=",
"append",
"(",
"deleteEntries",
",",
"&",
"sqs",
".",
"DeleteMessageBatchRequestEntry",
"{",
"Id",
":",
"aws",
".",
"String",
"(",
"*",
"item",
".",
"MessageId",
")",
",",
"ReceiptHandle",
":",
"aws",
".",
"String",
"(",
"*",
"item",
".",
"ReceiptHandle",
")",
",",
"}",
")",
"\n",
"results",
"=",
"append",
"(",
"results",
",",
"result",
")",
"\n",
"}",
"\n\n",
"deleteParams",
":=",
"&",
"sqs",
".",
"DeleteMessageBatchInput",
"{",
"Entries",
":",
"deleteEntries",
",",
"QueueUrl",
":",
"aws",
".",
"String",
"(",
"adaptor",
".",
"QueueURL",
")",
",",
"}",
"\n",
"_",
",",
"delerr",
":=",
"adaptor",
".",
"Client",
".",
"DeleteMessageBatch",
"(",
"deleteParams",
")",
"\n\n",
"if",
"delerr",
"!=",
"nil",
"{",
"fmt",
".",
"Println",
"(",
"delerr",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"results",
"\n",
"}"
] |
// Receive a result, or timeout in 1 second
|
[
"Receive",
"a",
"result",
"or",
"timeout",
"in",
"1",
"second"
] |
612187f4fd0d04b18f7181e8434717a175341ada
|
https://github.com/goadapp/goad/blob/612187f4fd0d04b18f7181e8434717a175341ada/infrastructure/aws/sqsadapter/sqsadapter.go#L41-L87
|
train
|
goadapp/goad
|
infrastructure/aws/sqsadapter/sqsadapter.go
|
SendResult
|
func (adaptor Adapter) SendResult(result api.RunnerResult) error {
str, jsonerr := jsonFromResult(result)
if jsonerr != nil {
fmt.Println(jsonerr)
panic(jsonerr)
}
params := &sqs.SendMessageInput{
MessageBody: aws.String(str),
MessageGroupId: aws.String("goad-lambda"),
MessageDeduplicationId: aws.String(uuid.NewV4().String()),
QueueUrl: aws.String(adaptor.QueueURL),
}
_, err := adaptor.Client.SendMessage(params)
return err
}
|
go
|
func (adaptor Adapter) SendResult(result api.RunnerResult) error {
str, jsonerr := jsonFromResult(result)
if jsonerr != nil {
fmt.Println(jsonerr)
panic(jsonerr)
}
params := &sqs.SendMessageInput{
MessageBody: aws.String(str),
MessageGroupId: aws.String("goad-lambda"),
MessageDeduplicationId: aws.String(uuid.NewV4().String()),
QueueUrl: aws.String(adaptor.QueueURL),
}
_, err := adaptor.Client.SendMessage(params)
return err
}
|
[
"func",
"(",
"adaptor",
"Adapter",
")",
"SendResult",
"(",
"result",
"api",
".",
"RunnerResult",
")",
"error",
"{",
"str",
",",
"jsonerr",
":=",
"jsonFromResult",
"(",
"result",
")",
"\n",
"if",
"jsonerr",
"!=",
"nil",
"{",
"fmt",
".",
"Println",
"(",
"jsonerr",
")",
"\n",
"panic",
"(",
"jsonerr",
")",
"\n",
"}",
"\n",
"params",
":=",
"&",
"sqs",
".",
"SendMessageInput",
"{",
"MessageBody",
":",
"aws",
".",
"String",
"(",
"str",
")",
",",
"MessageGroupId",
":",
"aws",
".",
"String",
"(",
"\"",
"\"",
")",
",",
"MessageDeduplicationId",
":",
"aws",
".",
"String",
"(",
"uuid",
".",
"NewV4",
"(",
")",
".",
"String",
"(",
")",
")",
",",
"QueueUrl",
":",
"aws",
".",
"String",
"(",
"adaptor",
".",
"QueueURL",
")",
",",
"}",
"\n",
"_",
",",
"err",
":=",
"adaptor",
".",
"Client",
".",
"SendMessage",
"(",
"params",
")",
"\n\n",
"return",
"err",
"\n",
"}"
] |
// SendResult adds a result to the queue
|
[
"SendResult",
"adds",
"a",
"result",
"to",
"the",
"queue"
] |
612187f4fd0d04b18f7181e8434717a175341ada
|
https://github.com/goadapp/goad/blob/612187f4fd0d04b18f7181e8434717a175341ada/infrastructure/aws/sqsadapter/sqsadapter.go#L109-L124
|
train
|
goadapp/goad
|
infrastructure/aws/sqsadapter/sqsadapter.go
|
SendResult
|
func (adaptor DummyAdapter) SendResult(result api.RunnerResult) {
str, jsonerr := jsonFromResult(result)
if jsonerr != nil {
fmt.Println(jsonerr)
return
}
fmt.Println("\n" + str)
}
|
go
|
func (adaptor DummyAdapter) SendResult(result api.RunnerResult) {
str, jsonerr := jsonFromResult(result)
if jsonerr != nil {
fmt.Println(jsonerr)
return
}
fmt.Println("\n" + str)
}
|
[
"func",
"(",
"adaptor",
"DummyAdapter",
")",
"SendResult",
"(",
"result",
"api",
".",
"RunnerResult",
")",
"{",
"str",
",",
"jsonerr",
":=",
"jsonFromResult",
"(",
"result",
")",
"\n",
"if",
"jsonerr",
"!=",
"nil",
"{",
"fmt",
".",
"Println",
"(",
"jsonerr",
")",
"\n",
"return",
"\n",
"}",
"\n",
"fmt",
".",
"Println",
"(",
"\"",
"\\n",
"\"",
"+",
"str",
")",
"\n",
"}"
] |
// SendResult prints the result
|
[
"SendResult",
"prints",
"the",
"result"
] |
612187f4fd0d04b18f7181e8434717a175341ada
|
https://github.com/goadapp/goad/blob/612187f4fd0d04b18f7181e8434717a175341ada/infrastructure/aws/sqsadapter/sqsadapter.go#L127-L134
|
train
|
goadapp/goad
|
webapi/webapi.go
|
Serve
|
func Serve() {
http.HandleFunc("/goad", serveResults)
http.HandleFunc("/_health", health)
err := http.ListenAndServe(*addr, nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
|
go
|
func Serve() {
http.HandleFunc("/goad", serveResults)
http.HandleFunc("/_health", health)
err := http.ListenAndServe(*addr, nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
|
[
"func",
"Serve",
"(",
")",
"{",
"http",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"serveResults",
")",
"\n",
"http",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"health",
")",
"\n",
"err",
":=",
"http",
".",
"ListenAndServe",
"(",
"*",
"addr",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatal",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}"
] |
// Serve waits for connections and serves the results
|
[
"Serve",
"waits",
"for",
"connections",
"and",
"serves",
"the",
"results"
] |
612187f4fd0d04b18f7181e8434717a175341ada
|
https://github.com/goadapp/goad/blob/612187f4fd0d04b18f7181e8434717a175341ada/webapi/webapi.go#L141-L148
|
train
|
goadapp/goad
|
infrastructure/aws/aws.go
|
New
|
func New(config *types.TestConfig) infrastructure.Infrastructure {
awsConfig := aws.NewConfig().WithRegion(config.Regions[0])
infra := &AwsInfrastructure{config: config, awsConfig: awsConfig}
return infra
}
|
go
|
func New(config *types.TestConfig) infrastructure.Infrastructure {
awsConfig := aws.NewConfig().WithRegion(config.Regions[0])
infra := &AwsInfrastructure{config: config, awsConfig: awsConfig}
return infra
}
|
[
"func",
"New",
"(",
"config",
"*",
"types",
".",
"TestConfig",
")",
"infrastructure",
".",
"Infrastructure",
"{",
"awsConfig",
":=",
"aws",
".",
"NewConfig",
"(",
")",
".",
"WithRegion",
"(",
"config",
".",
"Regions",
"[",
"0",
"]",
")",
"\n",
"infra",
":=",
"&",
"AwsInfrastructure",
"{",
"config",
":",
"config",
",",
"awsConfig",
":",
"awsConfig",
"}",
"\n",
"return",
"infra",
"\n",
"}"
] |
// New creates the required infrastructure to run the load tests in Lambda
// functions.
|
[
"New",
"creates",
"the",
"required",
"infrastructure",
"to",
"run",
"the",
"load",
"tests",
"in",
"Lambda",
"functions",
"."
] |
612187f4fd0d04b18f7181e8434717a175341ada
|
https://github.com/goadapp/goad/blob/612187f4fd0d04b18f7181e8434717a175341ada/infrastructure/aws/aws.go#L43-L47
|
train
|
opencontainers/image-spec
|
schema/validator.go
|
Validate
|
func (v Validator) Validate(src io.Reader) error {
buf, err := ioutil.ReadAll(src)
if err != nil {
return errors.Wrap(err, "unable to read the document file")
}
if f, ok := mapValidate[v]; ok {
if f == nil {
return fmt.Errorf("internal error: mapValidate[%q] is nil", v)
}
err = f(bytes.NewReader(buf))
if err != nil {
return err
}
}
sl := newFSLoaderFactory(schemaNamespaces, fs).New(specs[v])
ml := gojsonschema.NewStringLoader(string(buf))
result, err := gojsonschema.Validate(sl, ml)
if err != nil {
return errors.Wrapf(
WrapSyntaxError(bytes.NewReader(buf), err),
"schema %s: unable to validate", v)
}
if result.Valid() {
return nil
}
errs := make([]error, 0, len(result.Errors()))
for _, desc := range result.Errors() {
errs = append(errs, fmt.Errorf("%s", desc))
}
return ValidationError{
Errs: errs,
}
}
|
go
|
func (v Validator) Validate(src io.Reader) error {
buf, err := ioutil.ReadAll(src)
if err != nil {
return errors.Wrap(err, "unable to read the document file")
}
if f, ok := mapValidate[v]; ok {
if f == nil {
return fmt.Errorf("internal error: mapValidate[%q] is nil", v)
}
err = f(bytes.NewReader(buf))
if err != nil {
return err
}
}
sl := newFSLoaderFactory(schemaNamespaces, fs).New(specs[v])
ml := gojsonschema.NewStringLoader(string(buf))
result, err := gojsonschema.Validate(sl, ml)
if err != nil {
return errors.Wrapf(
WrapSyntaxError(bytes.NewReader(buf), err),
"schema %s: unable to validate", v)
}
if result.Valid() {
return nil
}
errs := make([]error, 0, len(result.Errors()))
for _, desc := range result.Errors() {
errs = append(errs, fmt.Errorf("%s", desc))
}
return ValidationError{
Errs: errs,
}
}
|
[
"func",
"(",
"v",
"Validator",
")",
"Validate",
"(",
"src",
"io",
".",
"Reader",
")",
"error",
"{",
"buf",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"src",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"f",
",",
"ok",
":=",
"mapValidate",
"[",
"v",
"]",
";",
"ok",
"{",
"if",
"f",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"v",
")",
"\n",
"}",
"\n",
"err",
"=",
"f",
"(",
"bytes",
".",
"NewReader",
"(",
"buf",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"sl",
":=",
"newFSLoaderFactory",
"(",
"schemaNamespaces",
",",
"fs",
")",
".",
"New",
"(",
"specs",
"[",
"v",
"]",
")",
"\n",
"ml",
":=",
"gojsonschema",
".",
"NewStringLoader",
"(",
"string",
"(",
"buf",
")",
")",
"\n\n",
"result",
",",
"err",
":=",
"gojsonschema",
".",
"Validate",
"(",
"sl",
",",
"ml",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"WrapSyntaxError",
"(",
"bytes",
".",
"NewReader",
"(",
"buf",
")",
",",
"err",
")",
",",
"\"",
"\"",
",",
"v",
")",
"\n",
"}",
"\n\n",
"if",
"result",
".",
"Valid",
"(",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"errs",
":=",
"make",
"(",
"[",
"]",
"error",
",",
"0",
",",
"len",
"(",
"result",
".",
"Errors",
"(",
")",
")",
")",
"\n",
"for",
"_",
",",
"desc",
":=",
"range",
"result",
".",
"Errors",
"(",
")",
"{",
"errs",
"=",
"append",
"(",
"errs",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"desc",
")",
")",
"\n",
"}",
"\n\n",
"return",
"ValidationError",
"{",
"Errs",
":",
"errs",
",",
"}",
"\n",
"}"
] |
// Validate validates the given reader against the schema of the wrapped media type.
|
[
"Validate",
"validates",
"the",
"given",
"reader",
"against",
"the",
"schema",
"of",
"the",
"wrapped",
"media",
"type",
"."
] |
da296dcb1e473a9b4e2d148941d7faa9ac8fea3f
|
https://github.com/opencontainers/image-spec/blob/da296dcb1e473a9b4e2d148941d7faa9ac8fea3f/schema/validator.go#L54-L92
|
train
|
opencontainers/image-spec
|
identity/chainid.go
|
ChainID
|
func ChainID(dgsts []digest.Digest) digest.Digest {
chainIDs := make([]digest.Digest, len(dgsts))
copy(chainIDs, dgsts)
ChainIDs(chainIDs)
if len(chainIDs) == 0 {
return ""
}
return chainIDs[len(chainIDs)-1]
}
|
go
|
func ChainID(dgsts []digest.Digest) digest.Digest {
chainIDs := make([]digest.Digest, len(dgsts))
copy(chainIDs, dgsts)
ChainIDs(chainIDs)
if len(chainIDs) == 0 {
return ""
}
return chainIDs[len(chainIDs)-1]
}
|
[
"func",
"ChainID",
"(",
"dgsts",
"[",
"]",
"digest",
".",
"Digest",
")",
"digest",
".",
"Digest",
"{",
"chainIDs",
":=",
"make",
"(",
"[",
"]",
"digest",
".",
"Digest",
",",
"len",
"(",
"dgsts",
")",
")",
"\n",
"copy",
"(",
"chainIDs",
",",
"dgsts",
")",
"\n",
"ChainIDs",
"(",
"chainIDs",
")",
"\n\n",
"if",
"len",
"(",
"chainIDs",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"chainIDs",
"[",
"len",
"(",
"chainIDs",
")",
"-",
"1",
"]",
"\n",
"}"
] |
// ChainID takes a slice of digests and returns the ChainID corresponding to
// the last entry. Typically, these are a list of layer DiffIDs, with the
// result providing the ChainID identifying the result of sequential
// application of the preceding layers.
|
[
"ChainID",
"takes",
"a",
"slice",
"of",
"digests",
"and",
"returns",
"the",
"ChainID",
"corresponding",
"to",
"the",
"last",
"entry",
".",
"Typically",
"these",
"are",
"a",
"list",
"of",
"layer",
"DiffIDs",
"with",
"the",
"result",
"providing",
"the",
"ChainID",
"identifying",
"the",
"result",
"of",
"sequential",
"application",
"of",
"the",
"preceding",
"layers",
"."
] |
da296dcb1e473a9b4e2d148941d7faa9ac8fea3f
|
https://github.com/opencontainers/image-spec/blob/da296dcb1e473a9b4e2d148941d7faa9ac8fea3f/identity/chainid.go#L30-L39
|
train
|
opencontainers/image-spec
|
identity/helpers.go
|
FromReader
|
func FromReader(rd io.Reader) (digest.Digest, error) {
return digest.Canonical.FromReader(rd)
}
|
go
|
func FromReader(rd io.Reader) (digest.Digest, error) {
return digest.Canonical.FromReader(rd)
}
|
[
"func",
"FromReader",
"(",
"rd",
"io",
".",
"Reader",
")",
"(",
"digest",
".",
"Digest",
",",
"error",
")",
"{",
"return",
"digest",
".",
"Canonical",
".",
"FromReader",
"(",
"rd",
")",
"\n",
"}"
] |
// FromReader consumes the content of rd until io.EOF, returning canonical
// digest.
|
[
"FromReader",
"consumes",
"the",
"content",
"of",
"rd",
"until",
"io",
".",
"EOF",
"returning",
"canonical",
"digest",
"."
] |
da296dcb1e473a9b4e2d148941d7faa9ac8fea3f
|
https://github.com/opencontainers/image-spec/blob/da296dcb1e473a9b4e2d148941d7faa9ac8fea3f/identity/helpers.go#L28-L30
|
train
|
opencontainers/image-spec
|
schema/loader.go
|
newFSLoaderFactory
|
func newFSLoaderFactory(namespaces []string, fs http.FileSystem) *fsLoaderFactory {
return &fsLoaderFactory{
namespaces: namespaces,
fs: fs,
}
}
|
go
|
func newFSLoaderFactory(namespaces []string, fs http.FileSystem) *fsLoaderFactory {
return &fsLoaderFactory{
namespaces: namespaces,
fs: fs,
}
}
|
[
"func",
"newFSLoaderFactory",
"(",
"namespaces",
"[",
"]",
"string",
",",
"fs",
"http",
".",
"FileSystem",
")",
"*",
"fsLoaderFactory",
"{",
"return",
"&",
"fsLoaderFactory",
"{",
"namespaces",
":",
"namespaces",
",",
"fs",
":",
"fs",
",",
"}",
"\n",
"}"
] |
// newFSLoaderFactory returns a fsLoaderFactory reading files under the specified namespaces from the root of fs.
|
[
"newFSLoaderFactory",
"returns",
"a",
"fsLoaderFactory",
"reading",
"files",
"under",
"the",
"specified",
"namespaces",
"from",
"the",
"root",
"of",
"fs",
"."
] |
da296dcb1e473a9b4e2d148941d7faa9ac8fea3f
|
https://github.com/opencontainers/image-spec/blob/da296dcb1e473a9b4e2d148941d7faa9ac8fea3f/schema/loader.go#L37-L42
|
train
|
opencontainers/image-spec
|
schema/loader.go
|
refContents
|
func (factory *fsLoaderFactory) refContents(ref gojsonreference.JsonReference) ([]byte, error) {
refStr := ref.String()
path := ""
for _, ns := range factory.namespaces {
if strings.HasPrefix(refStr, ns) {
path = "/" + strings.TrimPrefix(refStr, ns)
break
}
}
if path == "" {
return nil, fmt.Errorf("Schema reference %#v unexpectedly not available in fsLoaderFactory with namespaces %#v", path, factory.namespaces)
}
f, err := factory.fs.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
return ioutil.ReadAll(f)
}
|
go
|
func (factory *fsLoaderFactory) refContents(ref gojsonreference.JsonReference) ([]byte, error) {
refStr := ref.String()
path := ""
for _, ns := range factory.namespaces {
if strings.HasPrefix(refStr, ns) {
path = "/" + strings.TrimPrefix(refStr, ns)
break
}
}
if path == "" {
return nil, fmt.Errorf("Schema reference %#v unexpectedly not available in fsLoaderFactory with namespaces %#v", path, factory.namespaces)
}
f, err := factory.fs.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
return ioutil.ReadAll(f)
}
|
[
"func",
"(",
"factory",
"*",
"fsLoaderFactory",
")",
"refContents",
"(",
"ref",
"gojsonreference",
".",
"JsonReference",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"refStr",
":=",
"ref",
".",
"String",
"(",
")",
"\n",
"path",
":=",
"\"",
"\"",
"\n",
"for",
"_",
",",
"ns",
":=",
"range",
"factory",
".",
"namespaces",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"refStr",
",",
"ns",
")",
"{",
"path",
"=",
"\"",
"\"",
"+",
"strings",
".",
"TrimPrefix",
"(",
"refStr",
",",
"ns",
")",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"path",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"path",
",",
"factory",
".",
"namespaces",
")",
"\n",
"}",
"\n\n",
"f",
",",
"err",
":=",
"factory",
".",
"fs",
".",
"Open",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n\n",
"return",
"ioutil",
".",
"ReadAll",
"(",
"f",
")",
"\n",
"}"
] |
// refContents returns the contents of ref, if available in fsLoaderFactory.
|
[
"refContents",
"returns",
"the",
"contents",
"of",
"ref",
"if",
"available",
"in",
"fsLoaderFactory",
"."
] |
da296dcb1e473a9b4e2d148941d7faa9ac8fea3f
|
https://github.com/opencontainers/image-spec/blob/da296dcb1e473a9b4e2d148941d7faa9ac8fea3f/schema/loader.go#L52-L72
|
train
|
opencontainers/image-spec
|
schema/loader.go
|
decodeJSONUsingNumber
|
func decodeJSONUsingNumber(r io.Reader) (interface{}, error) {
// Copied from gojsonschema.
var document interface{}
decoder := json.NewDecoder(r)
decoder.UseNumber()
err := decoder.Decode(&document)
if err != nil {
return nil, err
}
return document, nil
}
|
go
|
func decodeJSONUsingNumber(r io.Reader) (interface{}, error) {
// Copied from gojsonschema.
var document interface{}
decoder := json.NewDecoder(r)
decoder.UseNumber()
err := decoder.Decode(&document)
if err != nil {
return nil, err
}
return document, nil
}
|
[
"func",
"decodeJSONUsingNumber",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"// Copied from gojsonschema.",
"var",
"document",
"interface",
"{",
"}",
"\n\n",
"decoder",
":=",
"json",
".",
"NewDecoder",
"(",
"r",
")",
"\n",
"decoder",
".",
"UseNumber",
"(",
")",
"\n\n",
"err",
":=",
"decoder",
".",
"Decode",
"(",
"&",
"document",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"document",
",",
"nil",
"\n",
"}"
] |
// decodeJSONUsingNumber returns JSON parsed from an io.Reader
|
[
"decodeJSONUsingNumber",
"returns",
"JSON",
"parsed",
"from",
"an",
"io",
".",
"Reader"
] |
da296dcb1e473a9b4e2d148941d7faa9ac8fea3f
|
https://github.com/opencontainers/image-spec/blob/da296dcb1e473a9b4e2d148941d7faa9ac8fea3f/schema/loader.go#L104-L117
|
train
|
opencontainers/image-spec
|
schema/loader.go
|
JsonReference
|
func (l *fsLoader) JsonReference() (gojsonreference.JsonReference, error) { // nolint: golint
return gojsonreference.NewJsonReference(l.JsonSource().(string))
}
|
go
|
func (l *fsLoader) JsonReference() (gojsonreference.JsonReference, error) { // nolint: golint
return gojsonreference.NewJsonReference(l.JsonSource().(string))
}
|
[
"func",
"(",
"l",
"*",
"fsLoader",
")",
"JsonReference",
"(",
")",
"(",
"gojsonreference",
".",
"JsonReference",
",",
"error",
")",
"{",
"// nolint: golint",
"return",
"gojsonreference",
".",
"NewJsonReference",
"(",
"l",
".",
"JsonSource",
"(",
")",
".",
"(",
"string",
")",
")",
"\n",
"}"
] |
// JsonReference implements gojsonschema.JSONLoader.JsonReference. The "Json" capitalization needs to be maintained to conform to the interface.
|
[
"JsonReference",
"implements",
"gojsonschema",
".",
"JSONLoader",
".",
"JsonReference",
".",
"The",
"Json",
"capitalization",
"needs",
"to",
"be",
"maintained",
"to",
"conform",
"to",
"the",
"interface",
"."
] |
da296dcb1e473a9b4e2d148941d7faa9ac8fea3f
|
https://github.com/opencontainers/image-spec/blob/da296dcb1e473a9b4e2d148941d7faa9ac8fea3f/schema/loader.go#L120-L122
|
train
|
gocraft/work
|
enqueue.go
|
NewEnqueuer
|
func NewEnqueuer(namespace string, pool *redis.Pool) *Enqueuer {
if pool == nil {
panic("NewEnqueuer needs a non-nil *redis.Pool")
}
return &Enqueuer{
Namespace: namespace,
Pool: pool,
queuePrefix: redisKeyJobsPrefix(namespace),
knownJobs: make(map[string]int64),
enqueueUniqueScript: redis.NewScript(2, redisLuaEnqueueUnique),
enqueueUniqueInScript: redis.NewScript(2, redisLuaEnqueueUniqueIn),
}
}
|
go
|
func NewEnqueuer(namespace string, pool *redis.Pool) *Enqueuer {
if pool == nil {
panic("NewEnqueuer needs a non-nil *redis.Pool")
}
return &Enqueuer{
Namespace: namespace,
Pool: pool,
queuePrefix: redisKeyJobsPrefix(namespace),
knownJobs: make(map[string]int64),
enqueueUniqueScript: redis.NewScript(2, redisLuaEnqueueUnique),
enqueueUniqueInScript: redis.NewScript(2, redisLuaEnqueueUniqueIn),
}
}
|
[
"func",
"NewEnqueuer",
"(",
"namespace",
"string",
",",
"pool",
"*",
"redis",
".",
"Pool",
")",
"*",
"Enqueuer",
"{",
"if",
"pool",
"==",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"Enqueuer",
"{",
"Namespace",
":",
"namespace",
",",
"Pool",
":",
"pool",
",",
"queuePrefix",
":",
"redisKeyJobsPrefix",
"(",
"namespace",
")",
",",
"knownJobs",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"int64",
")",
",",
"enqueueUniqueScript",
":",
"redis",
".",
"NewScript",
"(",
"2",
",",
"redisLuaEnqueueUnique",
")",
",",
"enqueueUniqueInScript",
":",
"redis",
".",
"NewScript",
"(",
"2",
",",
"redisLuaEnqueueUniqueIn",
")",
",",
"}",
"\n",
"}"
] |
// NewEnqueuer creates a new enqueuer with the specified Redis namespace and Redis pool.
|
[
"NewEnqueuer",
"creates",
"a",
"new",
"enqueuer",
"with",
"the",
"specified",
"Redis",
"namespace",
"and",
"Redis",
"pool",
"."
] |
c85b71e20062f3ab71d4749604faf956d364614f
|
https://github.com/gocraft/work/blob/c85b71e20062f3ab71d4749604faf956d364614f/enqueue.go#L23-L36
|
train
|
gocraft/work
|
enqueue.go
|
EnqueueIn
|
func (e *Enqueuer) EnqueueIn(jobName string, secondsFromNow int64, args map[string]interface{}) (*ScheduledJob, error) {
job := &Job{
Name: jobName,
ID: makeIdentifier(),
EnqueuedAt: nowEpochSeconds(),
Args: args,
}
rawJSON, err := job.serialize()
if err != nil {
return nil, err
}
conn := e.Pool.Get()
defer conn.Close()
scheduledJob := &ScheduledJob{
RunAt: nowEpochSeconds() + secondsFromNow,
Job: job,
}
_, err = conn.Do("ZADD", redisKeyScheduled(e.Namespace), scheduledJob.RunAt, rawJSON)
if err != nil {
return nil, err
}
if err := e.addToKnownJobs(conn, jobName); err != nil {
return scheduledJob, err
}
return scheduledJob, nil
}
|
go
|
func (e *Enqueuer) EnqueueIn(jobName string, secondsFromNow int64, args map[string]interface{}) (*ScheduledJob, error) {
job := &Job{
Name: jobName,
ID: makeIdentifier(),
EnqueuedAt: nowEpochSeconds(),
Args: args,
}
rawJSON, err := job.serialize()
if err != nil {
return nil, err
}
conn := e.Pool.Get()
defer conn.Close()
scheduledJob := &ScheduledJob{
RunAt: nowEpochSeconds() + secondsFromNow,
Job: job,
}
_, err = conn.Do("ZADD", redisKeyScheduled(e.Namespace), scheduledJob.RunAt, rawJSON)
if err != nil {
return nil, err
}
if err := e.addToKnownJobs(conn, jobName); err != nil {
return scheduledJob, err
}
return scheduledJob, nil
}
|
[
"func",
"(",
"e",
"*",
"Enqueuer",
")",
"EnqueueIn",
"(",
"jobName",
"string",
",",
"secondsFromNow",
"int64",
",",
"args",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"(",
"*",
"ScheduledJob",
",",
"error",
")",
"{",
"job",
":=",
"&",
"Job",
"{",
"Name",
":",
"jobName",
",",
"ID",
":",
"makeIdentifier",
"(",
")",
",",
"EnqueuedAt",
":",
"nowEpochSeconds",
"(",
")",
",",
"Args",
":",
"args",
",",
"}",
"\n\n",
"rawJSON",
",",
"err",
":=",
"job",
".",
"serialize",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"conn",
":=",
"e",
".",
"Pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n\n",
"scheduledJob",
":=",
"&",
"ScheduledJob",
"{",
"RunAt",
":",
"nowEpochSeconds",
"(",
")",
"+",
"secondsFromNow",
",",
"Job",
":",
"job",
",",
"}",
"\n\n",
"_",
",",
"err",
"=",
"conn",
".",
"Do",
"(",
"\"",
"\"",
",",
"redisKeyScheduled",
"(",
"e",
".",
"Namespace",
")",
",",
"scheduledJob",
".",
"RunAt",
",",
"rawJSON",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"e",
".",
"addToKnownJobs",
"(",
"conn",
",",
"jobName",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"scheduledJob",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"scheduledJob",
",",
"nil",
"\n",
"}"
] |
// EnqueueIn enqueues a job in the scheduled job queue for execution in secondsFromNow seconds.
|
[
"EnqueueIn",
"enqueues",
"a",
"job",
"in",
"the",
"scheduled",
"job",
"queue",
"for",
"execution",
"in",
"secondsFromNow",
"seconds",
"."
] |
c85b71e20062f3ab71d4749604faf956d364614f
|
https://github.com/gocraft/work/blob/c85b71e20062f3ab71d4749604faf956d364614f/enqueue.go#L68-L99
|
train
|
gocraft/work
|
enqueue.go
|
EnqueueUniqueIn
|
func (e *Enqueuer) EnqueueUniqueIn(jobName string, secondsFromNow int64, args map[string]interface{}) (*ScheduledJob, error) {
return e.EnqueueUniqueInByKey(jobName, secondsFromNow, args, nil)
}
|
go
|
func (e *Enqueuer) EnqueueUniqueIn(jobName string, secondsFromNow int64, args map[string]interface{}) (*ScheduledJob, error) {
return e.EnqueueUniqueInByKey(jobName, secondsFromNow, args, nil)
}
|
[
"func",
"(",
"e",
"*",
"Enqueuer",
")",
"EnqueueUniqueIn",
"(",
"jobName",
"string",
",",
"secondsFromNow",
"int64",
",",
"args",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"(",
"*",
"ScheduledJob",
",",
"error",
")",
"{",
"return",
"e",
".",
"EnqueueUniqueInByKey",
"(",
"jobName",
",",
"secondsFromNow",
",",
"args",
",",
"nil",
")",
"\n",
"}"
] |
// EnqueueUniqueIn enqueues a unique job in the scheduled job queue for execution in secondsFromNow seconds. See EnqueueUnique for the semantics of unique jobs.
|
[
"EnqueueUniqueIn",
"enqueues",
"a",
"unique",
"job",
"in",
"the",
"scheduled",
"job",
"queue",
"for",
"execution",
"in",
"secondsFromNow",
"seconds",
".",
"See",
"EnqueueUnique",
"for",
"the",
"semantics",
"of",
"unique",
"jobs",
"."
] |
c85b71e20062f3ab71d4749604faf956d364614f
|
https://github.com/gocraft/work/blob/c85b71e20062f3ab71d4749604faf956d364614f/enqueue.go#L112-L114
|
train
|
gocraft/work
|
enqueue.go
|
EnqueueUniqueInByKey
|
func (e *Enqueuer) EnqueueUniqueInByKey(jobName string, secondsFromNow int64, args map[string]interface{}, keyMap map[string]interface{}) (*ScheduledJob, error) {
enqueue, job, err := e.uniqueJobHelper(jobName, args, keyMap)
if err != nil {
return nil, err
}
scheduledJob := &ScheduledJob{
RunAt: nowEpochSeconds() + secondsFromNow,
Job: job,
}
res, err := enqueue(&scheduledJob.RunAt)
if res == "ok" && err == nil {
return scheduledJob, nil
}
return nil, err
}
|
go
|
func (e *Enqueuer) EnqueueUniqueInByKey(jobName string, secondsFromNow int64, args map[string]interface{}, keyMap map[string]interface{}) (*ScheduledJob, error) {
enqueue, job, err := e.uniqueJobHelper(jobName, args, keyMap)
if err != nil {
return nil, err
}
scheduledJob := &ScheduledJob{
RunAt: nowEpochSeconds() + secondsFromNow,
Job: job,
}
res, err := enqueue(&scheduledJob.RunAt)
if res == "ok" && err == nil {
return scheduledJob, nil
}
return nil, err
}
|
[
"func",
"(",
"e",
"*",
"Enqueuer",
")",
"EnqueueUniqueInByKey",
"(",
"jobName",
"string",
",",
"secondsFromNow",
"int64",
",",
"args",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"keyMap",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"(",
"*",
"ScheduledJob",
",",
"error",
")",
"{",
"enqueue",
",",
"job",
",",
"err",
":=",
"e",
".",
"uniqueJobHelper",
"(",
"jobName",
",",
"args",
",",
"keyMap",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"scheduledJob",
":=",
"&",
"ScheduledJob",
"{",
"RunAt",
":",
"nowEpochSeconds",
"(",
")",
"+",
"secondsFromNow",
",",
"Job",
":",
"job",
",",
"}",
"\n\n",
"res",
",",
"err",
":=",
"enqueue",
"(",
"&",
"scheduledJob",
".",
"RunAt",
")",
"\n",
"if",
"res",
"==",
"\"",
"\"",
"&&",
"err",
"==",
"nil",
"{",
"return",
"scheduledJob",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}"
] |
// EnqueueUniqueInByKey enqueues a job in the scheduled job queue that is unique on specified key for execution in secondsFromNow seconds. See EnqueueUnique for the semantics of unique jobs.
// Subsequent calls with same key will update arguments
|
[
"EnqueueUniqueInByKey",
"enqueues",
"a",
"job",
"in",
"the",
"scheduled",
"job",
"queue",
"that",
"is",
"unique",
"on",
"specified",
"key",
"for",
"execution",
"in",
"secondsFromNow",
"seconds",
".",
"See",
"EnqueueUnique",
"for",
"the",
"semantics",
"of",
"unique",
"jobs",
".",
"Subsequent",
"calls",
"with",
"same",
"key",
"will",
"update",
"arguments"
] |
c85b71e20062f3ab71d4749604faf956d364614f
|
https://github.com/gocraft/work/blob/c85b71e20062f3ab71d4749604faf956d364614f/enqueue.go#L138-L154
|
train
|
gocraft/work
|
client.go
|
NewClient
|
func NewClient(namespace string, pool *redis.Pool) *Client {
return &Client{
namespace: namespace,
pool: pool,
}
}
|
go
|
func NewClient(namespace string, pool *redis.Pool) *Client {
return &Client{
namespace: namespace,
pool: pool,
}
}
|
[
"func",
"NewClient",
"(",
"namespace",
"string",
",",
"pool",
"*",
"redis",
".",
"Pool",
")",
"*",
"Client",
"{",
"return",
"&",
"Client",
"{",
"namespace",
":",
"namespace",
",",
"pool",
":",
"pool",
",",
"}",
"\n",
"}"
] |
// NewClient creates a new Client with the specified redis namespace and connection pool.
|
[
"NewClient",
"creates",
"a",
"new",
"Client",
"with",
"the",
"specified",
"redis",
"namespace",
"and",
"connection",
"pool",
"."
] |
c85b71e20062f3ab71d4749604faf956d364614f
|
https://github.com/gocraft/work/blob/c85b71e20062f3ab71d4749604faf956d364614f/client.go#L27-L32
|
train
|
gocraft/work
|
client.go
|
WorkerObservations
|
func (c *Client) WorkerObservations() ([]*WorkerObservation, error) {
conn := c.pool.Get()
defer conn.Close()
hbs, err := c.WorkerPoolHeartbeats()
if err != nil {
logError("worker_observations.worker_pool_heartbeats", err)
return nil, err
}
var workerIDs []string
for _, hb := range hbs {
workerIDs = append(workerIDs, hb.WorkerIDs...)
}
for _, wid := range workerIDs {
key := redisKeyWorkerObservation(c.namespace, wid)
conn.Send("HGETALL", key)
}
if err := conn.Flush(); err != nil {
logError("worker_observations.flush", err)
return nil, err
}
observations := make([]*WorkerObservation, 0, len(workerIDs))
for _, wid := range workerIDs {
vals, err := redis.Strings(conn.Receive())
if err != nil {
logError("worker_observations.receive", err)
return nil, err
}
ob := &WorkerObservation{
WorkerID: wid,
}
for i := 0; i < len(vals)-1; i += 2 {
key := vals[i]
value := vals[i+1]
ob.IsBusy = true
var err error
if key == "job_name" {
ob.JobName = value
} else if key == "job_id" {
ob.JobID = value
} else if key == "started_at" {
ob.StartedAt, err = strconv.ParseInt(value, 10, 64)
} else if key == "args" {
ob.ArgsJSON = value
} else if key == "checkin" {
ob.Checkin = value
} else if key == "checkin_at" {
ob.CheckinAt, err = strconv.ParseInt(value, 10, 64)
}
if err != nil {
logError("worker_observations.parse", err)
return nil, err
}
}
observations = append(observations, ob)
}
return observations, nil
}
|
go
|
func (c *Client) WorkerObservations() ([]*WorkerObservation, error) {
conn := c.pool.Get()
defer conn.Close()
hbs, err := c.WorkerPoolHeartbeats()
if err != nil {
logError("worker_observations.worker_pool_heartbeats", err)
return nil, err
}
var workerIDs []string
for _, hb := range hbs {
workerIDs = append(workerIDs, hb.WorkerIDs...)
}
for _, wid := range workerIDs {
key := redisKeyWorkerObservation(c.namespace, wid)
conn.Send("HGETALL", key)
}
if err := conn.Flush(); err != nil {
logError("worker_observations.flush", err)
return nil, err
}
observations := make([]*WorkerObservation, 0, len(workerIDs))
for _, wid := range workerIDs {
vals, err := redis.Strings(conn.Receive())
if err != nil {
logError("worker_observations.receive", err)
return nil, err
}
ob := &WorkerObservation{
WorkerID: wid,
}
for i := 0; i < len(vals)-1; i += 2 {
key := vals[i]
value := vals[i+1]
ob.IsBusy = true
var err error
if key == "job_name" {
ob.JobName = value
} else if key == "job_id" {
ob.JobID = value
} else if key == "started_at" {
ob.StartedAt, err = strconv.ParseInt(value, 10, 64)
} else if key == "args" {
ob.ArgsJSON = value
} else if key == "checkin" {
ob.Checkin = value
} else if key == "checkin_at" {
ob.CheckinAt, err = strconv.ParseInt(value, 10, 64)
}
if err != nil {
logError("worker_observations.parse", err)
return nil, err
}
}
observations = append(observations, ob)
}
return observations, nil
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"WorkerObservations",
"(",
")",
"(",
"[",
"]",
"*",
"WorkerObservation",
",",
"error",
")",
"{",
"conn",
":=",
"c",
".",
"pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n\n",
"hbs",
",",
"err",
":=",
"c",
".",
"WorkerPoolHeartbeats",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logError",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"workerIDs",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"hb",
":=",
"range",
"hbs",
"{",
"workerIDs",
"=",
"append",
"(",
"workerIDs",
",",
"hb",
".",
"WorkerIDs",
"...",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"wid",
":=",
"range",
"workerIDs",
"{",
"key",
":=",
"redisKeyWorkerObservation",
"(",
"c",
".",
"namespace",
",",
"wid",
")",
"\n",
"conn",
".",
"Send",
"(",
"\"",
"\"",
",",
"key",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"conn",
".",
"Flush",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"logError",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"observations",
":=",
"make",
"(",
"[",
"]",
"*",
"WorkerObservation",
",",
"0",
",",
"len",
"(",
"workerIDs",
")",
")",
"\n\n",
"for",
"_",
",",
"wid",
":=",
"range",
"workerIDs",
"{",
"vals",
",",
"err",
":=",
"redis",
".",
"Strings",
"(",
"conn",
".",
"Receive",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logError",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"ob",
":=",
"&",
"WorkerObservation",
"{",
"WorkerID",
":",
"wid",
",",
"}",
"\n\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"vals",
")",
"-",
"1",
";",
"i",
"+=",
"2",
"{",
"key",
":=",
"vals",
"[",
"i",
"]",
"\n",
"value",
":=",
"vals",
"[",
"i",
"+",
"1",
"]",
"\n\n",
"ob",
".",
"IsBusy",
"=",
"true",
"\n\n",
"var",
"err",
"error",
"\n",
"if",
"key",
"==",
"\"",
"\"",
"{",
"ob",
".",
"JobName",
"=",
"value",
"\n",
"}",
"else",
"if",
"key",
"==",
"\"",
"\"",
"{",
"ob",
".",
"JobID",
"=",
"value",
"\n",
"}",
"else",
"if",
"key",
"==",
"\"",
"\"",
"{",
"ob",
".",
"StartedAt",
",",
"err",
"=",
"strconv",
".",
"ParseInt",
"(",
"value",
",",
"10",
",",
"64",
")",
"\n",
"}",
"else",
"if",
"key",
"==",
"\"",
"\"",
"{",
"ob",
".",
"ArgsJSON",
"=",
"value",
"\n",
"}",
"else",
"if",
"key",
"==",
"\"",
"\"",
"{",
"ob",
".",
"Checkin",
"=",
"value",
"\n",
"}",
"else",
"if",
"key",
"==",
"\"",
"\"",
"{",
"ob",
".",
"CheckinAt",
",",
"err",
"=",
"strconv",
".",
"ParseInt",
"(",
"value",
",",
"10",
",",
"64",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logError",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"observations",
"=",
"append",
"(",
"observations",
",",
"ob",
")",
"\n",
"}",
"\n\n",
"return",
"observations",
",",
"nil",
"\n",
"}"
] |
// WorkerObservations returns all of the WorkerObservation's it finds for all worker pools' workers.
|
[
"WorkerObservations",
"returns",
"all",
"of",
"the",
"WorkerObservation",
"s",
"it",
"finds",
"for",
"all",
"worker",
"pools",
"workers",
"."
] |
c85b71e20062f3ab71d4749604faf956d364614f
|
https://github.com/gocraft/work/blob/c85b71e20062f3ab71d4749604faf956d364614f/client.go#L135-L203
|
train
|
gocraft/work
|
client.go
|
Queues
|
func (c *Client) Queues() ([]*Queue, error) {
conn := c.pool.Get()
defer conn.Close()
key := redisKeyKnownJobs(c.namespace)
jobNames, err := redis.Strings(conn.Do("SMEMBERS", key))
if err != nil {
return nil, err
}
sort.Strings(jobNames)
for _, jobName := range jobNames {
conn.Send("LLEN", redisKeyJobs(c.namespace, jobName))
}
if err := conn.Flush(); err != nil {
logError("client.queues.flush", err)
return nil, err
}
queues := make([]*Queue, 0, len(jobNames))
for _, jobName := range jobNames {
count, err := redis.Int64(conn.Receive())
if err != nil {
logError("client.queues.receive", err)
return nil, err
}
queue := &Queue{
JobName: jobName,
Count: count,
}
queues = append(queues, queue)
}
for _, s := range queues {
if s.Count > 0 {
conn.Send("LINDEX", redisKeyJobs(c.namespace, s.JobName), -1)
}
}
if err := conn.Flush(); err != nil {
logError("client.queues.flush2", err)
return nil, err
}
now := nowEpochSeconds()
for _, s := range queues {
if s.Count > 0 {
b, err := redis.Bytes(conn.Receive())
if err != nil {
logError("client.queues.receive2", err)
return nil, err
}
job, err := newJob(b, nil, nil)
if err != nil {
logError("client.queues.new_job", err)
}
s.Latency = now - job.EnqueuedAt
}
}
return queues, nil
}
|
go
|
func (c *Client) Queues() ([]*Queue, error) {
conn := c.pool.Get()
defer conn.Close()
key := redisKeyKnownJobs(c.namespace)
jobNames, err := redis.Strings(conn.Do("SMEMBERS", key))
if err != nil {
return nil, err
}
sort.Strings(jobNames)
for _, jobName := range jobNames {
conn.Send("LLEN", redisKeyJobs(c.namespace, jobName))
}
if err := conn.Flush(); err != nil {
logError("client.queues.flush", err)
return nil, err
}
queues := make([]*Queue, 0, len(jobNames))
for _, jobName := range jobNames {
count, err := redis.Int64(conn.Receive())
if err != nil {
logError("client.queues.receive", err)
return nil, err
}
queue := &Queue{
JobName: jobName,
Count: count,
}
queues = append(queues, queue)
}
for _, s := range queues {
if s.Count > 0 {
conn.Send("LINDEX", redisKeyJobs(c.namespace, s.JobName), -1)
}
}
if err := conn.Flush(); err != nil {
logError("client.queues.flush2", err)
return nil, err
}
now := nowEpochSeconds()
for _, s := range queues {
if s.Count > 0 {
b, err := redis.Bytes(conn.Receive())
if err != nil {
logError("client.queues.receive2", err)
return nil, err
}
job, err := newJob(b, nil, nil)
if err != nil {
logError("client.queues.new_job", err)
}
s.Latency = now - job.EnqueuedAt
}
}
return queues, nil
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"Queues",
"(",
")",
"(",
"[",
"]",
"*",
"Queue",
",",
"error",
")",
"{",
"conn",
":=",
"c",
".",
"pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n\n",
"key",
":=",
"redisKeyKnownJobs",
"(",
"c",
".",
"namespace",
")",
"\n",
"jobNames",
",",
"err",
":=",
"redis",
".",
"Strings",
"(",
"conn",
".",
"Do",
"(",
"\"",
"\"",
",",
"key",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"jobNames",
")",
"\n\n",
"for",
"_",
",",
"jobName",
":=",
"range",
"jobNames",
"{",
"conn",
".",
"Send",
"(",
"\"",
"\"",
",",
"redisKeyJobs",
"(",
"c",
".",
"namespace",
",",
"jobName",
")",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"conn",
".",
"Flush",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"logError",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"queues",
":=",
"make",
"(",
"[",
"]",
"*",
"Queue",
",",
"0",
",",
"len",
"(",
"jobNames",
")",
")",
"\n\n",
"for",
"_",
",",
"jobName",
":=",
"range",
"jobNames",
"{",
"count",
",",
"err",
":=",
"redis",
".",
"Int64",
"(",
"conn",
".",
"Receive",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logError",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"queue",
":=",
"&",
"Queue",
"{",
"JobName",
":",
"jobName",
",",
"Count",
":",
"count",
",",
"}",
"\n\n",
"queues",
"=",
"append",
"(",
"queues",
",",
"queue",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"s",
":=",
"range",
"queues",
"{",
"if",
"s",
".",
"Count",
">",
"0",
"{",
"conn",
".",
"Send",
"(",
"\"",
"\"",
",",
"redisKeyJobs",
"(",
"c",
".",
"namespace",
",",
"s",
".",
"JobName",
")",
",",
"-",
"1",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"conn",
".",
"Flush",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"logError",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"now",
":=",
"nowEpochSeconds",
"(",
")",
"\n\n",
"for",
"_",
",",
"s",
":=",
"range",
"queues",
"{",
"if",
"s",
".",
"Count",
">",
"0",
"{",
"b",
",",
"err",
":=",
"redis",
".",
"Bytes",
"(",
"conn",
".",
"Receive",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logError",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"job",
",",
"err",
":=",
"newJob",
"(",
"b",
",",
"nil",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logError",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"s",
".",
"Latency",
"=",
"now",
"-",
"job",
".",
"EnqueuedAt",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"queues",
",",
"nil",
"\n",
"}"
] |
// Queues returns the Queue's it finds.
|
[
"Queues",
"returns",
"the",
"Queue",
"s",
"it",
"finds",
"."
] |
c85b71e20062f3ab71d4749604faf956d364614f
|
https://github.com/gocraft/work/blob/c85b71e20062f3ab71d4749604faf956d364614f/client.go#L213-L280
|
train
|
gocraft/work
|
client.go
|
DeleteDeadJob
|
func (c *Client) DeleteDeadJob(diedAt int64, jobID string) error {
ok, _, err := c.deleteZsetJob(redisKeyDead(c.namespace), diedAt, jobID)
if err != nil {
return err
}
if !ok {
return ErrNotDeleted
}
return nil
}
|
go
|
func (c *Client) DeleteDeadJob(diedAt int64, jobID string) error {
ok, _, err := c.deleteZsetJob(redisKeyDead(c.namespace), diedAt, jobID)
if err != nil {
return err
}
if !ok {
return ErrNotDeleted
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"DeleteDeadJob",
"(",
"diedAt",
"int64",
",",
"jobID",
"string",
")",
"error",
"{",
"ok",
",",
"_",
",",
"err",
":=",
"c",
".",
"deleteZsetJob",
"(",
"redisKeyDead",
"(",
"c",
".",
"namespace",
")",
",",
"diedAt",
",",
"jobID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"!",
"ok",
"{",
"return",
"ErrNotDeleted",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// DeleteDeadJob deletes a dead job from Redis.
|
[
"DeleteDeadJob",
"deletes",
"a",
"dead",
"job",
"from",
"Redis",
"."
] |
c85b71e20062f3ab71d4749604faf956d364614f
|
https://github.com/gocraft/work/blob/c85b71e20062f3ab71d4749604faf956d364614f/client.go#L355-L364
|
train
|
gocraft/work
|
client.go
|
RetryDeadJob
|
func (c *Client) RetryDeadJob(diedAt int64, jobID string) error {
// Get queues for job names
queues, err := c.Queues()
if err != nil {
logError("client.retry_all_dead_jobs.queues", err)
return err
}
// Extract job names
var jobNames []string
for _, q := range queues {
jobNames = append(jobNames, q.JobName)
}
script := redis.NewScript(len(jobNames)+1, redisLuaRequeueSingleDeadCmd)
args := make([]interface{}, 0, len(jobNames)+1+3)
args = append(args, redisKeyDead(c.namespace)) // KEY[1]
for _, jobName := range jobNames {
args = append(args, redisKeyJobs(c.namespace, jobName)) // KEY[2, 3, ...]
}
args = append(args, redisKeyJobsPrefix(c.namespace)) // ARGV[1]
args = append(args, nowEpochSeconds())
args = append(args, diedAt)
args = append(args, jobID)
conn := c.pool.Get()
defer conn.Close()
cnt, err := redis.Int64(script.Do(conn, args...))
if err != nil {
logError("client.retry_dead_job.do", err)
return err
}
if cnt == 0 {
return ErrNotRetried
}
return nil
}
|
go
|
func (c *Client) RetryDeadJob(diedAt int64, jobID string) error {
// Get queues for job names
queues, err := c.Queues()
if err != nil {
logError("client.retry_all_dead_jobs.queues", err)
return err
}
// Extract job names
var jobNames []string
for _, q := range queues {
jobNames = append(jobNames, q.JobName)
}
script := redis.NewScript(len(jobNames)+1, redisLuaRequeueSingleDeadCmd)
args := make([]interface{}, 0, len(jobNames)+1+3)
args = append(args, redisKeyDead(c.namespace)) // KEY[1]
for _, jobName := range jobNames {
args = append(args, redisKeyJobs(c.namespace, jobName)) // KEY[2, 3, ...]
}
args = append(args, redisKeyJobsPrefix(c.namespace)) // ARGV[1]
args = append(args, nowEpochSeconds())
args = append(args, diedAt)
args = append(args, jobID)
conn := c.pool.Get()
defer conn.Close()
cnt, err := redis.Int64(script.Do(conn, args...))
if err != nil {
logError("client.retry_dead_job.do", err)
return err
}
if cnt == 0 {
return ErrNotRetried
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"RetryDeadJob",
"(",
"diedAt",
"int64",
",",
"jobID",
"string",
")",
"error",
"{",
"// Get queues for job names",
"queues",
",",
"err",
":=",
"c",
".",
"Queues",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logError",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"// Extract job names",
"var",
"jobNames",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"q",
":=",
"range",
"queues",
"{",
"jobNames",
"=",
"append",
"(",
"jobNames",
",",
"q",
".",
"JobName",
")",
"\n",
"}",
"\n\n",
"script",
":=",
"redis",
".",
"NewScript",
"(",
"len",
"(",
"jobNames",
")",
"+",
"1",
",",
"redisLuaRequeueSingleDeadCmd",
")",
"\n\n",
"args",
":=",
"make",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"0",
",",
"len",
"(",
"jobNames",
")",
"+",
"1",
"+",
"3",
")",
"\n",
"args",
"=",
"append",
"(",
"args",
",",
"redisKeyDead",
"(",
"c",
".",
"namespace",
")",
")",
"// KEY[1]",
"\n",
"for",
"_",
",",
"jobName",
":=",
"range",
"jobNames",
"{",
"args",
"=",
"append",
"(",
"args",
",",
"redisKeyJobs",
"(",
"c",
".",
"namespace",
",",
"jobName",
")",
")",
"// KEY[2, 3, ...]",
"\n",
"}",
"\n",
"args",
"=",
"append",
"(",
"args",
",",
"redisKeyJobsPrefix",
"(",
"c",
".",
"namespace",
")",
")",
"// ARGV[1]",
"\n",
"args",
"=",
"append",
"(",
"args",
",",
"nowEpochSeconds",
"(",
")",
")",
"\n",
"args",
"=",
"append",
"(",
"args",
",",
"diedAt",
")",
"\n",
"args",
"=",
"append",
"(",
"args",
",",
"jobID",
")",
"\n\n",
"conn",
":=",
"c",
".",
"pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n\n",
"cnt",
",",
"err",
":=",
"redis",
".",
"Int64",
"(",
"script",
".",
"Do",
"(",
"conn",
",",
"args",
"...",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logError",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"cnt",
"==",
"0",
"{",
"return",
"ErrNotRetried",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// RetryDeadJob retries a dead job. The job will be re-queued on the normal work queue for eventual processing by a worker.
|
[
"RetryDeadJob",
"retries",
"a",
"dead",
"job",
".",
"The",
"job",
"will",
"be",
"re",
"-",
"queued",
"on",
"the",
"normal",
"work",
"queue",
"for",
"eventual",
"processing",
"by",
"a",
"worker",
"."
] |
c85b71e20062f3ab71d4749604faf956d364614f
|
https://github.com/gocraft/work/blob/c85b71e20062f3ab71d4749604faf956d364614f/client.go#L367-L407
|
train
|
gocraft/work
|
client.go
|
RetryAllDeadJobs
|
func (c *Client) RetryAllDeadJobs() error {
// Get queues for job names
queues, err := c.Queues()
if err != nil {
logError("client.retry_all_dead_jobs.queues", err)
return err
}
// Extract job names
var jobNames []string
for _, q := range queues {
jobNames = append(jobNames, q.JobName)
}
script := redis.NewScript(len(jobNames)+1, redisLuaRequeueAllDeadCmd)
args := make([]interface{}, 0, len(jobNames)+1+3)
args = append(args, redisKeyDead(c.namespace)) // KEY[1]
for _, jobName := range jobNames {
args = append(args, redisKeyJobs(c.namespace, jobName)) // KEY[2, 3, ...]
}
args = append(args, redisKeyJobsPrefix(c.namespace)) // ARGV[1]
args = append(args, nowEpochSeconds())
args = append(args, 1000)
conn := c.pool.Get()
defer conn.Close()
// Cap iterations for safety (which could reprocess 1k*1k jobs).
// This is conceptually an infinite loop but let's be careful.
for i := 0; i < 1000; i++ {
res, err := redis.Int64(script.Do(conn, args...))
if err != nil {
logError("client.retry_all_dead_jobs.do", err)
return err
}
if res == 0 {
break
}
}
return nil
}
|
go
|
func (c *Client) RetryAllDeadJobs() error {
// Get queues for job names
queues, err := c.Queues()
if err != nil {
logError("client.retry_all_dead_jobs.queues", err)
return err
}
// Extract job names
var jobNames []string
for _, q := range queues {
jobNames = append(jobNames, q.JobName)
}
script := redis.NewScript(len(jobNames)+1, redisLuaRequeueAllDeadCmd)
args := make([]interface{}, 0, len(jobNames)+1+3)
args = append(args, redisKeyDead(c.namespace)) // KEY[1]
for _, jobName := range jobNames {
args = append(args, redisKeyJobs(c.namespace, jobName)) // KEY[2, 3, ...]
}
args = append(args, redisKeyJobsPrefix(c.namespace)) // ARGV[1]
args = append(args, nowEpochSeconds())
args = append(args, 1000)
conn := c.pool.Get()
defer conn.Close()
// Cap iterations for safety (which could reprocess 1k*1k jobs).
// This is conceptually an infinite loop but let's be careful.
for i := 0; i < 1000; i++ {
res, err := redis.Int64(script.Do(conn, args...))
if err != nil {
logError("client.retry_all_dead_jobs.do", err)
return err
}
if res == 0 {
break
}
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"RetryAllDeadJobs",
"(",
")",
"error",
"{",
"// Get queues for job names",
"queues",
",",
"err",
":=",
"c",
".",
"Queues",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logError",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"// Extract job names",
"var",
"jobNames",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"q",
":=",
"range",
"queues",
"{",
"jobNames",
"=",
"append",
"(",
"jobNames",
",",
"q",
".",
"JobName",
")",
"\n",
"}",
"\n\n",
"script",
":=",
"redis",
".",
"NewScript",
"(",
"len",
"(",
"jobNames",
")",
"+",
"1",
",",
"redisLuaRequeueAllDeadCmd",
")",
"\n\n",
"args",
":=",
"make",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"0",
",",
"len",
"(",
"jobNames",
")",
"+",
"1",
"+",
"3",
")",
"\n",
"args",
"=",
"append",
"(",
"args",
",",
"redisKeyDead",
"(",
"c",
".",
"namespace",
")",
")",
"// KEY[1]",
"\n",
"for",
"_",
",",
"jobName",
":=",
"range",
"jobNames",
"{",
"args",
"=",
"append",
"(",
"args",
",",
"redisKeyJobs",
"(",
"c",
".",
"namespace",
",",
"jobName",
")",
")",
"// KEY[2, 3, ...]",
"\n",
"}",
"\n",
"args",
"=",
"append",
"(",
"args",
",",
"redisKeyJobsPrefix",
"(",
"c",
".",
"namespace",
")",
")",
"// ARGV[1]",
"\n",
"args",
"=",
"append",
"(",
"args",
",",
"nowEpochSeconds",
"(",
")",
")",
"\n",
"args",
"=",
"append",
"(",
"args",
",",
"1000",
")",
"\n\n",
"conn",
":=",
"c",
".",
"pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n\n",
"// Cap iterations for safety (which could reprocess 1k*1k jobs).",
"// This is conceptually an infinite loop but let's be careful.",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"1000",
";",
"i",
"++",
"{",
"res",
",",
"err",
":=",
"redis",
".",
"Int64",
"(",
"script",
".",
"Do",
"(",
"conn",
",",
"args",
"...",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logError",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"res",
"==",
"0",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// RetryAllDeadJobs requeues all dead jobs. In other words, it puts them all back on the normal work queue for workers to pull from and process.
|
[
"RetryAllDeadJobs",
"requeues",
"all",
"dead",
"jobs",
".",
"In",
"other",
"words",
"it",
"puts",
"them",
"all",
"back",
"on",
"the",
"normal",
"work",
"queue",
"for",
"workers",
"to",
"pull",
"from",
"and",
"process",
"."
] |
c85b71e20062f3ab71d4749604faf956d364614f
|
https://github.com/gocraft/work/blob/c85b71e20062f3ab71d4749604faf956d364614f/client.go#L410-L453
|
train
|
gocraft/work
|
client.go
|
DeleteAllDeadJobs
|
func (c *Client) DeleteAllDeadJobs() error {
conn := c.pool.Get()
defer conn.Close()
_, err := conn.Do("DEL", redisKeyDead(c.namespace))
if err != nil {
logError("client.delete_all_dead_jobs", err)
return err
}
return nil
}
|
go
|
func (c *Client) DeleteAllDeadJobs() error {
conn := c.pool.Get()
defer conn.Close()
_, err := conn.Do("DEL", redisKeyDead(c.namespace))
if err != nil {
logError("client.delete_all_dead_jobs", err)
return err
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"DeleteAllDeadJobs",
"(",
")",
"error",
"{",
"conn",
":=",
"c",
".",
"pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n",
"_",
",",
"err",
":=",
"conn",
".",
"Do",
"(",
"\"",
"\"",
",",
"redisKeyDead",
"(",
"c",
".",
"namespace",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logError",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// DeleteAllDeadJobs deletes all dead jobs.
|
[
"DeleteAllDeadJobs",
"deletes",
"all",
"dead",
"jobs",
"."
] |
c85b71e20062f3ab71d4749604faf956d364614f
|
https://github.com/gocraft/work/blob/c85b71e20062f3ab71d4749604faf956d364614f/client.go#L456-L466
|
train
|
gocraft/work
|
client.go
|
DeleteScheduledJob
|
func (c *Client) DeleteScheduledJob(scheduledFor int64, jobID string) error {
ok, jobBytes, err := c.deleteZsetJob(redisKeyScheduled(c.namespace), scheduledFor, jobID)
if err != nil {
return err
}
// If we get a job back, parse it and see if it's a unique job. If it is, we need to delete the unique key.
if len(jobBytes) > 0 {
job, err := newJob(jobBytes, nil, nil)
if err != nil {
logError("client.delete_scheduled_job.new_job", err)
return err
}
if job.Unique {
uniqueKey, err := redisKeyUniqueJob(c.namespace, job.Name, job.Args)
if err != nil {
logError("client.delete_scheduled_job.redis_key_unique_job", err)
return err
}
conn := c.pool.Get()
defer conn.Close()
_, err = conn.Do("DEL", uniqueKey)
if err != nil {
logError("worker.delete_unique_job.del", err)
return err
}
}
}
if !ok {
return ErrNotDeleted
}
return nil
}
|
go
|
func (c *Client) DeleteScheduledJob(scheduledFor int64, jobID string) error {
ok, jobBytes, err := c.deleteZsetJob(redisKeyScheduled(c.namespace), scheduledFor, jobID)
if err != nil {
return err
}
// If we get a job back, parse it and see if it's a unique job. If it is, we need to delete the unique key.
if len(jobBytes) > 0 {
job, err := newJob(jobBytes, nil, nil)
if err != nil {
logError("client.delete_scheduled_job.new_job", err)
return err
}
if job.Unique {
uniqueKey, err := redisKeyUniqueJob(c.namespace, job.Name, job.Args)
if err != nil {
logError("client.delete_scheduled_job.redis_key_unique_job", err)
return err
}
conn := c.pool.Get()
defer conn.Close()
_, err = conn.Do("DEL", uniqueKey)
if err != nil {
logError("worker.delete_unique_job.del", err)
return err
}
}
}
if !ok {
return ErrNotDeleted
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"DeleteScheduledJob",
"(",
"scheduledFor",
"int64",
",",
"jobID",
"string",
")",
"error",
"{",
"ok",
",",
"jobBytes",
",",
"err",
":=",
"c",
".",
"deleteZsetJob",
"(",
"redisKeyScheduled",
"(",
"c",
".",
"namespace",
")",
",",
"scheduledFor",
",",
"jobID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// If we get a job back, parse it and see if it's a unique job. If it is, we need to delete the unique key.",
"if",
"len",
"(",
"jobBytes",
")",
">",
"0",
"{",
"job",
",",
"err",
":=",
"newJob",
"(",
"jobBytes",
",",
"nil",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logError",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"job",
".",
"Unique",
"{",
"uniqueKey",
",",
"err",
":=",
"redisKeyUniqueJob",
"(",
"c",
".",
"namespace",
",",
"job",
".",
"Name",
",",
"job",
".",
"Args",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logError",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"conn",
":=",
"c",
".",
"pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n\n",
"_",
",",
"err",
"=",
"conn",
".",
"Do",
"(",
"\"",
"\"",
",",
"uniqueKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logError",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"!",
"ok",
"{",
"return",
"ErrNotDeleted",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// DeleteScheduledJob deletes a job in the scheduled queue.
|
[
"DeleteScheduledJob",
"deletes",
"a",
"job",
"in",
"the",
"scheduled",
"queue",
"."
] |
c85b71e20062f3ab71d4749604faf956d364614f
|
https://github.com/gocraft/work/blob/c85b71e20062f3ab71d4749604faf956d364614f/client.go#L469-L504
|
train
|
gocraft/work
|
client.go
|
DeleteRetryJob
|
func (c *Client) DeleteRetryJob(retryAt int64, jobID string) error {
ok, _, err := c.deleteZsetJob(redisKeyRetry(c.namespace), retryAt, jobID)
if err != nil {
return err
}
if !ok {
return ErrNotDeleted
}
return nil
}
|
go
|
func (c *Client) DeleteRetryJob(retryAt int64, jobID string) error {
ok, _, err := c.deleteZsetJob(redisKeyRetry(c.namespace), retryAt, jobID)
if err != nil {
return err
}
if !ok {
return ErrNotDeleted
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"DeleteRetryJob",
"(",
"retryAt",
"int64",
",",
"jobID",
"string",
")",
"error",
"{",
"ok",
",",
"_",
",",
"err",
":=",
"c",
".",
"deleteZsetJob",
"(",
"redisKeyRetry",
"(",
"c",
".",
"namespace",
")",
",",
"retryAt",
",",
"jobID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"!",
"ok",
"{",
"return",
"ErrNotDeleted",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// DeleteRetryJob deletes a job in the retry queue.
|
[
"DeleteRetryJob",
"deletes",
"a",
"job",
"in",
"the",
"retry",
"queue",
"."
] |
c85b71e20062f3ab71d4749604faf956d364614f
|
https://github.com/gocraft/work/blob/c85b71e20062f3ab71d4749604faf956d364614f/client.go#L507-L516
|
train
|
gocraft/work
|
job.go
|
setArg
|
func (j *Job) setArg(key string, val interface{}) {
if j.Args == nil {
j.Args = make(map[string]interface{})
}
j.Args[key] = val
}
|
go
|
func (j *Job) setArg(key string, val interface{}) {
if j.Args == nil {
j.Args = make(map[string]interface{})
}
j.Args[key] = val
}
|
[
"func",
"(",
"j",
"*",
"Job",
")",
"setArg",
"(",
"key",
"string",
",",
"val",
"interface",
"{",
"}",
")",
"{",
"if",
"j",
".",
"Args",
"==",
"nil",
"{",
"j",
".",
"Args",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"}",
"\n",
"j",
".",
"Args",
"[",
"key",
"]",
"=",
"val",
"\n",
"}"
] |
// setArg sets a single named argument on the job.
|
[
"setArg",
"sets",
"a",
"single",
"named",
"argument",
"on",
"the",
"job",
"."
] |
c85b71e20062f3ab71d4749604faf956d364614f
|
https://github.com/gocraft/work/blob/c85b71e20062f3ab71d4749604faf956d364614f/job.go#L53-L58
|
train
|
gocraft/work
|
job.go
|
Checkin
|
func (j *Job) Checkin(msg string) {
if j.observer != nil {
j.observer.observeCheckin(j.Name, j.ID, msg)
}
}
|
go
|
func (j *Job) Checkin(msg string) {
if j.observer != nil {
j.observer.observeCheckin(j.Name, j.ID, msg)
}
}
|
[
"func",
"(",
"j",
"*",
"Job",
")",
"Checkin",
"(",
"msg",
"string",
")",
"{",
"if",
"j",
".",
"observer",
"!=",
"nil",
"{",
"j",
".",
"observer",
".",
"observeCheckin",
"(",
"j",
".",
"Name",
",",
"j",
".",
"ID",
",",
"msg",
")",
"\n",
"}",
"\n",
"}"
] |
// Checkin will update the status of the executing job to the specified messages. This message is visible within the web UI. This is useful for indicating some sort of progress on very long running jobs. For instance, on a job that has to process a million records over the course of an hour, the job could call Checkin with the current job number every 10k jobs.
|
[
"Checkin",
"will",
"update",
"the",
"status",
"of",
"the",
"executing",
"job",
"to",
"the",
"specified",
"messages",
".",
"This",
"message",
"is",
"visible",
"within",
"the",
"web",
"UI",
".",
"This",
"is",
"useful",
"for",
"indicating",
"some",
"sort",
"of",
"progress",
"on",
"very",
"long",
"running",
"jobs",
".",
"For",
"instance",
"on",
"a",
"job",
"that",
"has",
"to",
"process",
"a",
"million",
"records",
"over",
"the",
"course",
"of",
"an",
"hour",
"the",
"job",
"could",
"call",
"Checkin",
"with",
"the",
"current",
"job",
"number",
"every",
"10k",
"jobs",
"."
] |
c85b71e20062f3ab71d4749604faf956d364614f
|
https://github.com/gocraft/work/blob/c85b71e20062f3ab71d4749604faf956d364614f/job.go#L67-L71
|
train
|
gocraft/work
|
worker.go
|
defaultBackoffCalculator
|
func defaultBackoffCalculator(job *Job) int64 {
fails := job.Fails
return (fails * fails * fails * fails) + 15 + (rand.Int63n(30) * (fails + 1))
}
|
go
|
func defaultBackoffCalculator(job *Job) int64 {
fails := job.Fails
return (fails * fails * fails * fails) + 15 + (rand.Int63n(30) * (fails + 1))
}
|
[
"func",
"defaultBackoffCalculator",
"(",
"job",
"*",
"Job",
")",
"int64",
"{",
"fails",
":=",
"job",
".",
"Fails",
"\n",
"return",
"(",
"fails",
"*",
"fails",
"*",
"fails",
"*",
"fails",
")",
"+",
"15",
"+",
"(",
"rand",
".",
"Int63n",
"(",
"30",
")",
"*",
"(",
"fails",
"+",
"1",
")",
")",
"\n",
"}"
] |
// Default algorithm returns an fastly increasing backoff counter which grows in an unbounded fashion
|
[
"Default",
"algorithm",
"returns",
"an",
"fastly",
"increasing",
"backoff",
"counter",
"which",
"grows",
"in",
"an",
"unbounded",
"fashion"
] |
c85b71e20062f3ab71d4749604faf956d364614f
|
https://github.com/gocraft/work/blob/c85b71e20062f3ab71d4749604faf956d364614f/worker.go#L324-L327
|
train
|
gocraft/work
|
webui/webui.go
|
NewServer
|
func NewServer(namespace string, pool *redis.Pool, hostPort string) *Server {
router := web.New(context{})
server := &Server{
namespace: namespace,
pool: pool,
client: work.NewClient(namespace, pool),
hostPort: hostPort,
server: manners.NewWithServer(&http.Server{Addr: hostPort, Handler: router}),
router: router,
}
router.Middleware(func(c *context, rw web.ResponseWriter, r *web.Request, next web.NextMiddlewareFunc) {
c.Server = server
next(rw, r)
})
router.Middleware(func(rw web.ResponseWriter, r *web.Request, next web.NextMiddlewareFunc) {
rw.Header().Set("Content-Type", "application/json; charset=utf-8")
next(rw, r)
})
router.Get("/queues", (*context).queues)
router.Get("/worker_pools", (*context).workerPools)
router.Get("/busy_workers", (*context).busyWorkers)
router.Get("/retry_jobs", (*context).retryJobs)
router.Get("/scheduled_jobs", (*context).scheduledJobs)
router.Get("/dead_jobs", (*context).deadJobs)
router.Post("/delete_dead_job/:died_at:\\d.*/:job_id", (*context).deleteDeadJob)
router.Post("/retry_dead_job/:died_at:\\d.*/:job_id", (*context).retryDeadJob)
router.Post("/delete_all_dead_jobs", (*context).deleteAllDeadJobs)
router.Post("/retry_all_dead_jobs", (*context).retryAllDeadJobs)
//
// Build the HTML page:
//
assetRouter := router.Subrouter(context{}, "")
assetRouter.Get("/", func(c *context, rw web.ResponseWriter, req *web.Request) {
rw.Header().Set("Content-Type", "text/html; charset=utf-8")
rw.Write(assets.MustAsset("index.html"))
})
assetRouter.Get("/work.js", func(c *context, rw web.ResponseWriter, req *web.Request) {
rw.Header().Set("Content-Type", "application/javascript; charset=utf-8")
rw.Write(assets.MustAsset("work.js"))
})
return server
}
|
go
|
func NewServer(namespace string, pool *redis.Pool, hostPort string) *Server {
router := web.New(context{})
server := &Server{
namespace: namespace,
pool: pool,
client: work.NewClient(namespace, pool),
hostPort: hostPort,
server: manners.NewWithServer(&http.Server{Addr: hostPort, Handler: router}),
router: router,
}
router.Middleware(func(c *context, rw web.ResponseWriter, r *web.Request, next web.NextMiddlewareFunc) {
c.Server = server
next(rw, r)
})
router.Middleware(func(rw web.ResponseWriter, r *web.Request, next web.NextMiddlewareFunc) {
rw.Header().Set("Content-Type", "application/json; charset=utf-8")
next(rw, r)
})
router.Get("/queues", (*context).queues)
router.Get("/worker_pools", (*context).workerPools)
router.Get("/busy_workers", (*context).busyWorkers)
router.Get("/retry_jobs", (*context).retryJobs)
router.Get("/scheduled_jobs", (*context).scheduledJobs)
router.Get("/dead_jobs", (*context).deadJobs)
router.Post("/delete_dead_job/:died_at:\\d.*/:job_id", (*context).deleteDeadJob)
router.Post("/retry_dead_job/:died_at:\\d.*/:job_id", (*context).retryDeadJob)
router.Post("/delete_all_dead_jobs", (*context).deleteAllDeadJobs)
router.Post("/retry_all_dead_jobs", (*context).retryAllDeadJobs)
//
// Build the HTML page:
//
assetRouter := router.Subrouter(context{}, "")
assetRouter.Get("/", func(c *context, rw web.ResponseWriter, req *web.Request) {
rw.Header().Set("Content-Type", "text/html; charset=utf-8")
rw.Write(assets.MustAsset("index.html"))
})
assetRouter.Get("/work.js", func(c *context, rw web.ResponseWriter, req *web.Request) {
rw.Header().Set("Content-Type", "application/javascript; charset=utf-8")
rw.Write(assets.MustAsset("work.js"))
})
return server
}
|
[
"func",
"NewServer",
"(",
"namespace",
"string",
",",
"pool",
"*",
"redis",
".",
"Pool",
",",
"hostPort",
"string",
")",
"*",
"Server",
"{",
"router",
":=",
"web",
".",
"New",
"(",
"context",
"{",
"}",
")",
"\n",
"server",
":=",
"&",
"Server",
"{",
"namespace",
":",
"namespace",
",",
"pool",
":",
"pool",
",",
"client",
":",
"work",
".",
"NewClient",
"(",
"namespace",
",",
"pool",
")",
",",
"hostPort",
":",
"hostPort",
",",
"server",
":",
"manners",
".",
"NewWithServer",
"(",
"&",
"http",
".",
"Server",
"{",
"Addr",
":",
"hostPort",
",",
"Handler",
":",
"router",
"}",
")",
",",
"router",
":",
"router",
",",
"}",
"\n\n",
"router",
".",
"Middleware",
"(",
"func",
"(",
"c",
"*",
"context",
",",
"rw",
"web",
".",
"ResponseWriter",
",",
"r",
"*",
"web",
".",
"Request",
",",
"next",
"web",
".",
"NextMiddlewareFunc",
")",
"{",
"c",
".",
"Server",
"=",
"server",
"\n",
"next",
"(",
"rw",
",",
"r",
")",
"\n",
"}",
")",
"\n",
"router",
".",
"Middleware",
"(",
"func",
"(",
"rw",
"web",
".",
"ResponseWriter",
",",
"r",
"*",
"web",
".",
"Request",
",",
"next",
"web",
".",
"NextMiddlewareFunc",
")",
"{",
"rw",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"next",
"(",
"rw",
",",
"r",
")",
"\n",
"}",
")",
"\n",
"router",
".",
"Get",
"(",
"\"",
"\"",
",",
"(",
"*",
"context",
")",
".",
"queues",
")",
"\n",
"router",
".",
"Get",
"(",
"\"",
"\"",
",",
"(",
"*",
"context",
")",
".",
"workerPools",
")",
"\n",
"router",
".",
"Get",
"(",
"\"",
"\"",
",",
"(",
"*",
"context",
")",
".",
"busyWorkers",
")",
"\n",
"router",
".",
"Get",
"(",
"\"",
"\"",
",",
"(",
"*",
"context",
")",
".",
"retryJobs",
")",
"\n",
"router",
".",
"Get",
"(",
"\"",
"\"",
",",
"(",
"*",
"context",
")",
".",
"scheduledJobs",
")",
"\n",
"router",
".",
"Get",
"(",
"\"",
"\"",
",",
"(",
"*",
"context",
")",
".",
"deadJobs",
")",
"\n",
"router",
".",
"Post",
"(",
"\"",
"\\\\",
"\"",
",",
"(",
"*",
"context",
")",
".",
"deleteDeadJob",
")",
"\n",
"router",
".",
"Post",
"(",
"\"",
"\\\\",
"\"",
",",
"(",
"*",
"context",
")",
".",
"retryDeadJob",
")",
"\n",
"router",
".",
"Post",
"(",
"\"",
"\"",
",",
"(",
"*",
"context",
")",
".",
"deleteAllDeadJobs",
")",
"\n",
"router",
".",
"Post",
"(",
"\"",
"\"",
",",
"(",
"*",
"context",
")",
".",
"retryAllDeadJobs",
")",
"\n\n",
"//",
"// Build the HTML page:",
"//",
"assetRouter",
":=",
"router",
".",
"Subrouter",
"(",
"context",
"{",
"}",
",",
"\"",
"\"",
")",
"\n",
"assetRouter",
".",
"Get",
"(",
"\"",
"\"",
",",
"func",
"(",
"c",
"*",
"context",
",",
"rw",
"web",
".",
"ResponseWriter",
",",
"req",
"*",
"web",
".",
"Request",
")",
"{",
"rw",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"rw",
".",
"Write",
"(",
"assets",
".",
"MustAsset",
"(",
"\"",
"\"",
")",
")",
"\n",
"}",
")",
"\n",
"assetRouter",
".",
"Get",
"(",
"\"",
"\"",
",",
"func",
"(",
"c",
"*",
"context",
",",
"rw",
"web",
".",
"ResponseWriter",
",",
"req",
"*",
"web",
".",
"Request",
")",
"{",
"rw",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"rw",
".",
"Write",
"(",
"assets",
".",
"MustAsset",
"(",
"\"",
"\"",
")",
")",
"\n",
"}",
")",
"\n\n",
"return",
"server",
"\n",
"}"
] |
// NewServer creates and returns a new server. The 'namespace' param is the redis namespace to use. The hostPort param is the address to bind on to expose the API.
|
[
"NewServer",
"creates",
"and",
"returns",
"a",
"new",
"server",
".",
"The",
"namespace",
"param",
"is",
"the",
"redis",
"namespace",
"to",
"use",
".",
"The",
"hostPort",
"param",
"is",
"the",
"address",
"to",
"bind",
"on",
"to",
"expose",
"the",
"API",
"."
] |
c85b71e20062f3ab71d4749604faf956d364614f
|
https://github.com/gocraft/work/blob/c85b71e20062f3ab71d4749604faf956d364614f/webui/webui.go#L33-L77
|
train
|
gocraft/work
|
webui/webui.go
|
Start
|
func (w *Server) Start() {
w.wg.Add(1)
go func(w *Server) {
w.server.ListenAndServe()
w.wg.Done()
}(w)
}
|
go
|
func (w *Server) Start() {
w.wg.Add(1)
go func(w *Server) {
w.server.ListenAndServe()
w.wg.Done()
}(w)
}
|
[
"func",
"(",
"w",
"*",
"Server",
")",
"Start",
"(",
")",
"{",
"w",
".",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
"w",
"*",
"Server",
")",
"{",
"w",
".",
"server",
".",
"ListenAndServe",
"(",
")",
"\n",
"w",
".",
"wg",
".",
"Done",
"(",
")",
"\n",
"}",
"(",
"w",
")",
"\n",
"}"
] |
// Start starts the server listening for requests on the hostPort specified in NewServer.
|
[
"Start",
"starts",
"the",
"server",
"listening",
"for",
"requests",
"on",
"the",
"hostPort",
"specified",
"in",
"NewServer",
"."
] |
c85b71e20062f3ab71d4749604faf956d364614f
|
https://github.com/gocraft/work/blob/c85b71e20062f3ab71d4749604faf956d364614f/webui/webui.go#L80-L86
|
train
|
gocraft/work
|
run.go
|
runJob
|
func runJob(job *Job, ctxType reflect.Type, middleware []*middlewareHandler, jt *jobType) (returnCtx reflect.Value, returnError error) {
returnCtx = reflect.New(ctxType)
currentMiddleware := 0
maxMiddleware := len(middleware)
var next NextMiddlewareFunc
next = func() error {
if currentMiddleware < maxMiddleware {
mw := middleware[currentMiddleware]
currentMiddleware++
if mw.IsGeneric {
return mw.GenericMiddlewareHandler(job, next)
}
res := mw.DynamicMiddleware.Call([]reflect.Value{returnCtx, reflect.ValueOf(job), reflect.ValueOf(next)})
x := res[0].Interface()
if x == nil {
return nil
}
return x.(error)
}
if jt.IsGeneric {
return jt.GenericHandler(job)
}
res := jt.DynamicHandler.Call([]reflect.Value{returnCtx, reflect.ValueOf(job)})
x := res[0].Interface()
if x == nil {
return nil
}
return x.(error)
}
defer func() {
if panicErr := recover(); panicErr != nil {
// err turns out to be interface{}, of actual type "runtime.errorCString"
// Luckily, the err sprints nicely via fmt.
errorishError := fmt.Errorf("%v", panicErr)
logError("runJob.panic", errorishError)
returnError = errorishError
}
}()
returnError = next()
return
}
|
go
|
func runJob(job *Job, ctxType reflect.Type, middleware []*middlewareHandler, jt *jobType) (returnCtx reflect.Value, returnError error) {
returnCtx = reflect.New(ctxType)
currentMiddleware := 0
maxMiddleware := len(middleware)
var next NextMiddlewareFunc
next = func() error {
if currentMiddleware < maxMiddleware {
mw := middleware[currentMiddleware]
currentMiddleware++
if mw.IsGeneric {
return mw.GenericMiddlewareHandler(job, next)
}
res := mw.DynamicMiddleware.Call([]reflect.Value{returnCtx, reflect.ValueOf(job), reflect.ValueOf(next)})
x := res[0].Interface()
if x == nil {
return nil
}
return x.(error)
}
if jt.IsGeneric {
return jt.GenericHandler(job)
}
res := jt.DynamicHandler.Call([]reflect.Value{returnCtx, reflect.ValueOf(job)})
x := res[0].Interface()
if x == nil {
return nil
}
return x.(error)
}
defer func() {
if panicErr := recover(); panicErr != nil {
// err turns out to be interface{}, of actual type "runtime.errorCString"
// Luckily, the err sprints nicely via fmt.
errorishError := fmt.Errorf("%v", panicErr)
logError("runJob.panic", errorishError)
returnError = errorishError
}
}()
returnError = next()
return
}
|
[
"func",
"runJob",
"(",
"job",
"*",
"Job",
",",
"ctxType",
"reflect",
".",
"Type",
",",
"middleware",
"[",
"]",
"*",
"middlewareHandler",
",",
"jt",
"*",
"jobType",
")",
"(",
"returnCtx",
"reflect",
".",
"Value",
",",
"returnError",
"error",
")",
"{",
"returnCtx",
"=",
"reflect",
".",
"New",
"(",
"ctxType",
")",
"\n",
"currentMiddleware",
":=",
"0",
"\n",
"maxMiddleware",
":=",
"len",
"(",
"middleware",
")",
"\n\n",
"var",
"next",
"NextMiddlewareFunc",
"\n",
"next",
"=",
"func",
"(",
")",
"error",
"{",
"if",
"currentMiddleware",
"<",
"maxMiddleware",
"{",
"mw",
":=",
"middleware",
"[",
"currentMiddleware",
"]",
"\n",
"currentMiddleware",
"++",
"\n",
"if",
"mw",
".",
"IsGeneric",
"{",
"return",
"mw",
".",
"GenericMiddlewareHandler",
"(",
"job",
",",
"next",
")",
"\n",
"}",
"\n",
"res",
":=",
"mw",
".",
"DynamicMiddleware",
".",
"Call",
"(",
"[",
"]",
"reflect",
".",
"Value",
"{",
"returnCtx",
",",
"reflect",
".",
"ValueOf",
"(",
"job",
")",
",",
"reflect",
".",
"ValueOf",
"(",
"next",
")",
"}",
")",
"\n",
"x",
":=",
"res",
"[",
"0",
"]",
".",
"Interface",
"(",
")",
"\n",
"if",
"x",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"x",
".",
"(",
"error",
")",
"\n",
"}",
"\n",
"if",
"jt",
".",
"IsGeneric",
"{",
"return",
"jt",
".",
"GenericHandler",
"(",
"job",
")",
"\n",
"}",
"\n",
"res",
":=",
"jt",
".",
"DynamicHandler",
".",
"Call",
"(",
"[",
"]",
"reflect",
".",
"Value",
"{",
"returnCtx",
",",
"reflect",
".",
"ValueOf",
"(",
"job",
")",
"}",
")",
"\n",
"x",
":=",
"res",
"[",
"0",
"]",
".",
"Interface",
"(",
")",
"\n",
"if",
"x",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"x",
".",
"(",
"error",
")",
"\n",
"}",
"\n\n",
"defer",
"func",
"(",
")",
"{",
"if",
"panicErr",
":=",
"recover",
"(",
")",
";",
"panicErr",
"!=",
"nil",
"{",
"// err turns out to be interface{}, of actual type \"runtime.errorCString\"",
"// Luckily, the err sprints nicely via fmt.",
"errorishError",
":=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"panicErr",
")",
"\n",
"logError",
"(",
"\"",
"\"",
",",
"errorishError",
")",
"\n",
"returnError",
"=",
"errorishError",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"returnError",
"=",
"next",
"(",
")",
"\n\n",
"return",
"\n",
"}"
] |
// returns an error if the job fails, or there's a panic, or we couldn't reflect correctly.
// if we return an error, it signals we want the job to be retried.
|
[
"returns",
"an",
"error",
"if",
"the",
"job",
"fails",
"or",
"there",
"s",
"a",
"panic",
"or",
"we",
"couldn",
"t",
"reflect",
"correctly",
".",
"if",
"we",
"return",
"an",
"error",
"it",
"signals",
"we",
"want",
"the",
"job",
"to",
"be",
"retried",
"."
] |
c85b71e20062f3ab71d4749604faf956d364614f
|
https://github.com/gocraft/work/blob/c85b71e20062f3ab71d4749604faf956d364614f/run.go#L10-L54
|
train
|
gocraft/work
|
worker_pool.go
|
NewWorkerPool
|
func NewWorkerPool(ctx interface{}, concurrency uint, namespace string, pool *redis.Pool) *WorkerPool {
return NewWorkerPoolWithOptions(ctx, concurrency, namespace, pool, WorkerPoolOptions{})
}
|
go
|
func NewWorkerPool(ctx interface{}, concurrency uint, namespace string, pool *redis.Pool) *WorkerPool {
return NewWorkerPoolWithOptions(ctx, concurrency, namespace, pool, WorkerPoolOptions{})
}
|
[
"func",
"NewWorkerPool",
"(",
"ctx",
"interface",
"{",
"}",
",",
"concurrency",
"uint",
",",
"namespace",
"string",
",",
"pool",
"*",
"redis",
".",
"Pool",
")",
"*",
"WorkerPool",
"{",
"return",
"NewWorkerPoolWithOptions",
"(",
"ctx",
",",
"concurrency",
",",
"namespace",
",",
"pool",
",",
"WorkerPoolOptions",
"{",
"}",
")",
"\n",
"}"
] |
// NewWorkerPool creates a new worker pool. ctx should be a struct literal whose type will be used for middleware and handlers.
// concurrency specifies how many workers to spin up - each worker can process jobs concurrently.
|
[
"NewWorkerPool",
"creates",
"a",
"new",
"worker",
"pool",
".",
"ctx",
"should",
"be",
"a",
"struct",
"literal",
"whose",
"type",
"will",
"be",
"used",
"for",
"middleware",
"and",
"handlers",
".",
"concurrency",
"specifies",
"how",
"many",
"workers",
"to",
"spin",
"up",
"-",
"each",
"worker",
"can",
"process",
"jobs",
"concurrently",
"."
] |
c85b71e20062f3ab71d4749604faf956d364614f
|
https://github.com/gocraft/work/blob/c85b71e20062f3ab71d4749604faf956d364614f/worker_pool.go#L88-L90
|
train
|
gocraft/work
|
worker_pool.go
|
NewWorkerPoolWithOptions
|
func NewWorkerPoolWithOptions(ctx interface{}, concurrency uint, namespace string, pool *redis.Pool, workerPoolOpts WorkerPoolOptions) *WorkerPool {
if pool == nil {
panic("NewWorkerPool needs a non-nil *redis.Pool")
}
ctxType := reflect.TypeOf(ctx)
validateContextType(ctxType)
wp := &WorkerPool{
workerPoolID: makeIdentifier(),
concurrency: concurrency,
namespace: namespace,
pool: pool,
sleepBackoffs: workerPoolOpts.SleepBackoffs,
contextType: ctxType,
jobTypes: make(map[string]*jobType),
}
for i := uint(0); i < wp.concurrency; i++ {
w := newWorker(wp.namespace, wp.workerPoolID, wp.pool, wp.contextType, nil, wp.jobTypes, wp.sleepBackoffs)
wp.workers = append(wp.workers, w)
}
return wp
}
|
go
|
func NewWorkerPoolWithOptions(ctx interface{}, concurrency uint, namespace string, pool *redis.Pool, workerPoolOpts WorkerPoolOptions) *WorkerPool {
if pool == nil {
panic("NewWorkerPool needs a non-nil *redis.Pool")
}
ctxType := reflect.TypeOf(ctx)
validateContextType(ctxType)
wp := &WorkerPool{
workerPoolID: makeIdentifier(),
concurrency: concurrency,
namespace: namespace,
pool: pool,
sleepBackoffs: workerPoolOpts.SleepBackoffs,
contextType: ctxType,
jobTypes: make(map[string]*jobType),
}
for i := uint(0); i < wp.concurrency; i++ {
w := newWorker(wp.namespace, wp.workerPoolID, wp.pool, wp.contextType, nil, wp.jobTypes, wp.sleepBackoffs)
wp.workers = append(wp.workers, w)
}
return wp
}
|
[
"func",
"NewWorkerPoolWithOptions",
"(",
"ctx",
"interface",
"{",
"}",
",",
"concurrency",
"uint",
",",
"namespace",
"string",
",",
"pool",
"*",
"redis",
".",
"Pool",
",",
"workerPoolOpts",
"WorkerPoolOptions",
")",
"*",
"WorkerPool",
"{",
"if",
"pool",
"==",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"ctxType",
":=",
"reflect",
".",
"TypeOf",
"(",
"ctx",
")",
"\n",
"validateContextType",
"(",
"ctxType",
")",
"\n",
"wp",
":=",
"&",
"WorkerPool",
"{",
"workerPoolID",
":",
"makeIdentifier",
"(",
")",
",",
"concurrency",
":",
"concurrency",
",",
"namespace",
":",
"namespace",
",",
"pool",
":",
"pool",
",",
"sleepBackoffs",
":",
"workerPoolOpts",
".",
"SleepBackoffs",
",",
"contextType",
":",
"ctxType",
",",
"jobTypes",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"jobType",
")",
",",
"}",
"\n\n",
"for",
"i",
":=",
"uint",
"(",
"0",
")",
";",
"i",
"<",
"wp",
".",
"concurrency",
";",
"i",
"++",
"{",
"w",
":=",
"newWorker",
"(",
"wp",
".",
"namespace",
",",
"wp",
".",
"workerPoolID",
",",
"wp",
".",
"pool",
",",
"wp",
".",
"contextType",
",",
"nil",
",",
"wp",
".",
"jobTypes",
",",
"wp",
".",
"sleepBackoffs",
")",
"\n",
"wp",
".",
"workers",
"=",
"append",
"(",
"wp",
".",
"workers",
",",
"w",
")",
"\n",
"}",
"\n\n",
"return",
"wp",
"\n",
"}"
] |
// NewWorkerPoolWithOptions creates a new worker pool as per the NewWorkerPool function, but permits you to specify
// additional options such as sleep backoffs.
|
[
"NewWorkerPoolWithOptions",
"creates",
"a",
"new",
"worker",
"pool",
"as",
"per",
"the",
"NewWorkerPool",
"function",
"but",
"permits",
"you",
"to",
"specify",
"additional",
"options",
"such",
"as",
"sleep",
"backoffs",
"."
] |
c85b71e20062f3ab71d4749604faf956d364614f
|
https://github.com/gocraft/work/blob/c85b71e20062f3ab71d4749604faf956d364614f/worker_pool.go#L94-L117
|
train
|
gocraft/work
|
worker_pool.go
|
JobWithOptions
|
func (wp *WorkerPool) JobWithOptions(name string, jobOpts JobOptions, fn interface{}) *WorkerPool {
jobOpts = applyDefaultsAndValidate(jobOpts)
vfn := reflect.ValueOf(fn)
validateHandlerType(wp.contextType, vfn)
jt := &jobType{
Name: name,
DynamicHandler: vfn,
JobOptions: jobOpts,
}
if gh, ok := fn.(func(*Job) error); ok {
jt.IsGeneric = true
jt.GenericHandler = gh
}
wp.jobTypes[name] = jt
for _, w := range wp.workers {
w.updateMiddlewareAndJobTypes(wp.middleware, wp.jobTypes)
}
return wp
}
|
go
|
func (wp *WorkerPool) JobWithOptions(name string, jobOpts JobOptions, fn interface{}) *WorkerPool {
jobOpts = applyDefaultsAndValidate(jobOpts)
vfn := reflect.ValueOf(fn)
validateHandlerType(wp.contextType, vfn)
jt := &jobType{
Name: name,
DynamicHandler: vfn,
JobOptions: jobOpts,
}
if gh, ok := fn.(func(*Job) error); ok {
jt.IsGeneric = true
jt.GenericHandler = gh
}
wp.jobTypes[name] = jt
for _, w := range wp.workers {
w.updateMiddlewareAndJobTypes(wp.middleware, wp.jobTypes)
}
return wp
}
|
[
"func",
"(",
"wp",
"*",
"WorkerPool",
")",
"JobWithOptions",
"(",
"name",
"string",
",",
"jobOpts",
"JobOptions",
",",
"fn",
"interface",
"{",
"}",
")",
"*",
"WorkerPool",
"{",
"jobOpts",
"=",
"applyDefaultsAndValidate",
"(",
"jobOpts",
")",
"\n\n",
"vfn",
":=",
"reflect",
".",
"ValueOf",
"(",
"fn",
")",
"\n",
"validateHandlerType",
"(",
"wp",
".",
"contextType",
",",
"vfn",
")",
"\n",
"jt",
":=",
"&",
"jobType",
"{",
"Name",
":",
"name",
",",
"DynamicHandler",
":",
"vfn",
",",
"JobOptions",
":",
"jobOpts",
",",
"}",
"\n",
"if",
"gh",
",",
"ok",
":=",
"fn",
".",
"(",
"func",
"(",
"*",
"Job",
")",
"error",
")",
";",
"ok",
"{",
"jt",
".",
"IsGeneric",
"=",
"true",
"\n",
"jt",
".",
"GenericHandler",
"=",
"gh",
"\n",
"}",
"\n\n",
"wp",
".",
"jobTypes",
"[",
"name",
"]",
"=",
"jt",
"\n\n",
"for",
"_",
",",
"w",
":=",
"range",
"wp",
".",
"workers",
"{",
"w",
".",
"updateMiddlewareAndJobTypes",
"(",
"wp",
".",
"middleware",
",",
"wp",
".",
"jobTypes",
")",
"\n",
"}",
"\n\n",
"return",
"wp",
"\n",
"}"
] |
// JobWithOptions adds a handler for 'name' jobs as per the Job function, but permits you specify additional options
// such as a job's priority, retry count, and whether to send dead jobs to the dead job queue or trash them.
|
[
"JobWithOptions",
"adds",
"a",
"handler",
"for",
"name",
"jobs",
"as",
"per",
"the",
"Job",
"function",
"but",
"permits",
"you",
"specify",
"additional",
"options",
"such",
"as",
"a",
"job",
"s",
"priority",
"retry",
"count",
"and",
"whether",
"to",
"send",
"dead",
"jobs",
"to",
"the",
"dead",
"job",
"queue",
"or",
"trash",
"them",
"."
] |
c85b71e20062f3ab71d4749604faf956d364614f
|
https://github.com/gocraft/work/blob/c85b71e20062f3ab71d4749604faf956d364614f/worker_pool.go#L154-L176
|
train
|
gocraft/work
|
worker_pool.go
|
Start
|
func (wp *WorkerPool) Start() {
if wp.started {
return
}
wp.started = true
// TODO: we should cleanup stale keys on startup from previously registered jobs
wp.writeConcurrencyControlsToRedis()
go wp.writeKnownJobsToRedis()
for _, w := range wp.workers {
go w.start()
}
wp.heartbeater = newWorkerPoolHeartbeater(wp.namespace, wp.pool, wp.workerPoolID, wp.jobTypes, wp.concurrency, wp.workerIDs())
wp.heartbeater.start()
wp.startRequeuers()
wp.periodicEnqueuer = newPeriodicEnqueuer(wp.namespace, wp.pool, wp.periodicJobs)
wp.periodicEnqueuer.start()
}
|
go
|
func (wp *WorkerPool) Start() {
if wp.started {
return
}
wp.started = true
// TODO: we should cleanup stale keys on startup from previously registered jobs
wp.writeConcurrencyControlsToRedis()
go wp.writeKnownJobsToRedis()
for _, w := range wp.workers {
go w.start()
}
wp.heartbeater = newWorkerPoolHeartbeater(wp.namespace, wp.pool, wp.workerPoolID, wp.jobTypes, wp.concurrency, wp.workerIDs())
wp.heartbeater.start()
wp.startRequeuers()
wp.periodicEnqueuer = newPeriodicEnqueuer(wp.namespace, wp.pool, wp.periodicJobs)
wp.periodicEnqueuer.start()
}
|
[
"func",
"(",
"wp",
"*",
"WorkerPool",
")",
"Start",
"(",
")",
"{",
"if",
"wp",
".",
"started",
"{",
"return",
"\n",
"}",
"\n",
"wp",
".",
"started",
"=",
"true",
"\n\n",
"// TODO: we should cleanup stale keys on startup from previously registered jobs",
"wp",
".",
"writeConcurrencyControlsToRedis",
"(",
")",
"\n",
"go",
"wp",
".",
"writeKnownJobsToRedis",
"(",
")",
"\n\n",
"for",
"_",
",",
"w",
":=",
"range",
"wp",
".",
"workers",
"{",
"go",
"w",
".",
"start",
"(",
")",
"\n",
"}",
"\n\n",
"wp",
".",
"heartbeater",
"=",
"newWorkerPoolHeartbeater",
"(",
"wp",
".",
"namespace",
",",
"wp",
".",
"pool",
",",
"wp",
".",
"workerPoolID",
",",
"wp",
".",
"jobTypes",
",",
"wp",
".",
"concurrency",
",",
"wp",
".",
"workerIDs",
"(",
")",
")",
"\n",
"wp",
".",
"heartbeater",
".",
"start",
"(",
")",
"\n",
"wp",
".",
"startRequeuers",
"(",
")",
"\n",
"wp",
".",
"periodicEnqueuer",
"=",
"newPeriodicEnqueuer",
"(",
"wp",
".",
"namespace",
",",
"wp",
".",
"pool",
",",
"wp",
".",
"periodicJobs",
")",
"\n",
"wp",
".",
"periodicEnqueuer",
".",
"start",
"(",
")",
"\n",
"}"
] |
// Start starts the workers and associated processes.
|
[
"Start",
"starts",
"the",
"workers",
"and",
"associated",
"processes",
"."
] |
c85b71e20062f3ab71d4749604faf956d364614f
|
https://github.com/gocraft/work/blob/c85b71e20062f3ab71d4749604faf956d364614f/worker_pool.go#L194-L213
|
train
|
gocraft/work
|
worker_pool.go
|
Stop
|
func (wp *WorkerPool) Stop() {
if !wp.started {
return
}
wp.started = false
wg := sync.WaitGroup{}
for _, w := range wp.workers {
wg.Add(1)
go func(w *worker) {
w.stop()
wg.Done()
}(w)
}
wg.Wait()
wp.heartbeater.stop()
wp.retrier.stop()
wp.scheduler.stop()
wp.deadPoolReaper.stop()
wp.periodicEnqueuer.stop()
}
|
go
|
func (wp *WorkerPool) Stop() {
if !wp.started {
return
}
wp.started = false
wg := sync.WaitGroup{}
for _, w := range wp.workers {
wg.Add(1)
go func(w *worker) {
w.stop()
wg.Done()
}(w)
}
wg.Wait()
wp.heartbeater.stop()
wp.retrier.stop()
wp.scheduler.stop()
wp.deadPoolReaper.stop()
wp.periodicEnqueuer.stop()
}
|
[
"func",
"(",
"wp",
"*",
"WorkerPool",
")",
"Stop",
"(",
")",
"{",
"if",
"!",
"wp",
".",
"started",
"{",
"return",
"\n",
"}",
"\n",
"wp",
".",
"started",
"=",
"false",
"\n\n",
"wg",
":=",
"sync",
".",
"WaitGroup",
"{",
"}",
"\n",
"for",
"_",
",",
"w",
":=",
"range",
"wp",
".",
"workers",
"{",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
"w",
"*",
"worker",
")",
"{",
"w",
".",
"stop",
"(",
")",
"\n",
"wg",
".",
"Done",
"(",
")",
"\n",
"}",
"(",
"w",
")",
"\n",
"}",
"\n",
"wg",
".",
"Wait",
"(",
")",
"\n",
"wp",
".",
"heartbeater",
".",
"stop",
"(",
")",
"\n",
"wp",
".",
"retrier",
".",
"stop",
"(",
")",
"\n",
"wp",
".",
"scheduler",
".",
"stop",
"(",
")",
"\n",
"wp",
".",
"deadPoolReaper",
".",
"stop",
"(",
")",
"\n",
"wp",
".",
"periodicEnqueuer",
".",
"stop",
"(",
")",
"\n",
"}"
] |
// Stop stops the workers and associated processes.
|
[
"Stop",
"stops",
"the",
"workers",
"and",
"associated",
"processes",
"."
] |
c85b71e20062f3ab71d4749604faf956d364614f
|
https://github.com/gocraft/work/blob/c85b71e20062f3ab71d4749604faf956d364614f/worker_pool.go#L216-L236
|
train
|
gocraft/work
|
worker_pool.go
|
Drain
|
func (wp *WorkerPool) Drain() {
wg := sync.WaitGroup{}
for _, w := range wp.workers {
wg.Add(1)
go func(w *worker) {
w.drain()
wg.Done()
}(w)
}
wg.Wait()
}
|
go
|
func (wp *WorkerPool) Drain() {
wg := sync.WaitGroup{}
for _, w := range wp.workers {
wg.Add(1)
go func(w *worker) {
w.drain()
wg.Done()
}(w)
}
wg.Wait()
}
|
[
"func",
"(",
"wp",
"*",
"WorkerPool",
")",
"Drain",
"(",
")",
"{",
"wg",
":=",
"sync",
".",
"WaitGroup",
"{",
"}",
"\n",
"for",
"_",
",",
"w",
":=",
"range",
"wp",
".",
"workers",
"{",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
"w",
"*",
"worker",
")",
"{",
"w",
".",
"drain",
"(",
")",
"\n",
"wg",
".",
"Done",
"(",
")",
"\n",
"}",
"(",
"w",
")",
"\n",
"}",
"\n",
"wg",
".",
"Wait",
"(",
")",
"\n",
"}"
] |
// Drain drains all jobs in the queue before returning. Note that if jobs are added faster than we can process them, this function wouldn't return.
|
[
"Drain",
"drains",
"all",
"jobs",
"in",
"the",
"queue",
"before",
"returning",
".",
"Note",
"that",
"if",
"jobs",
"are",
"added",
"faster",
"than",
"we",
"can",
"process",
"them",
"this",
"function",
"wouldn",
"t",
"return",
"."
] |
c85b71e20062f3ab71d4749604faf956d364614f
|
https://github.com/gocraft/work/blob/c85b71e20062f3ab71d4749604faf956d364614f/worker_pool.go#L239-L249
|
train
|
pilosa/pilosa
|
api.go
|
NewAPI
|
func NewAPI(opts ...apiOption) (*API, error) {
api := &API{}
for _, opt := range opts {
err := opt(api)
if err != nil {
return nil, errors.Wrap(err, "applying option")
}
}
return api, nil
}
|
go
|
func NewAPI(opts ...apiOption) (*API, error) {
api := &API{}
for _, opt := range opts {
err := opt(api)
if err != nil {
return nil, errors.Wrap(err, "applying option")
}
}
return api, nil
}
|
[
"func",
"NewAPI",
"(",
"opts",
"...",
"apiOption",
")",
"(",
"*",
"API",
",",
"error",
")",
"{",
"api",
":=",
"&",
"API",
"{",
"}",
"\n\n",
"for",
"_",
",",
"opt",
":=",
"range",
"opts",
"{",
"err",
":=",
"opt",
"(",
"api",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"api",
",",
"nil",
"\n",
"}"
] |
// NewAPI returns a new API instance.
|
[
"NewAPI",
"returns",
"a",
"new",
"API",
"instance",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/api.go#L62-L72
|
train
|
pilosa/pilosa
|
api.go
|
Query
|
func (api *API) Query(ctx context.Context, req *QueryRequest) (QueryResponse, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "API.Query")
defer span.Finish()
if err := api.validate(apiQuery); err != nil {
return QueryResponse{}, errors.Wrap(err, "validating api method")
}
q, err := pql.NewParser(strings.NewReader(req.Query)).Parse()
if err != nil {
return QueryResponse{}, errors.Wrap(err, "parsing")
}
execOpts := &execOptions{
Remote: req.Remote,
ExcludeRowAttrs: req.ExcludeRowAttrs, // NOTE: Kept for Pilosa 1.x compat.
ExcludeColumns: req.ExcludeColumns, // NOTE: Kept for Pilosa 1.x compat.
ColumnAttrs: req.ColumnAttrs, // NOTE: Kept for Pilosa 1.x compat.
}
resp, err := api.server.executor.Execute(ctx, req.Index, q, req.Shards, execOpts)
if err != nil {
return QueryResponse{}, errors.Wrap(err, "executing")
}
return resp, nil
}
|
go
|
func (api *API) Query(ctx context.Context, req *QueryRequest) (QueryResponse, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "API.Query")
defer span.Finish()
if err := api.validate(apiQuery); err != nil {
return QueryResponse{}, errors.Wrap(err, "validating api method")
}
q, err := pql.NewParser(strings.NewReader(req.Query)).Parse()
if err != nil {
return QueryResponse{}, errors.Wrap(err, "parsing")
}
execOpts := &execOptions{
Remote: req.Remote,
ExcludeRowAttrs: req.ExcludeRowAttrs, // NOTE: Kept for Pilosa 1.x compat.
ExcludeColumns: req.ExcludeColumns, // NOTE: Kept for Pilosa 1.x compat.
ColumnAttrs: req.ColumnAttrs, // NOTE: Kept for Pilosa 1.x compat.
}
resp, err := api.server.executor.Execute(ctx, req.Index, q, req.Shards, execOpts)
if err != nil {
return QueryResponse{}, errors.Wrap(err, "executing")
}
return resp, nil
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"Query",
"(",
"ctx",
"context",
".",
"Context",
",",
"req",
"*",
"QueryRequest",
")",
"(",
"QueryResponse",
",",
"error",
")",
"{",
"span",
",",
"ctx",
":=",
"tracing",
".",
"StartSpanFromContext",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n\n",
"if",
"err",
":=",
"api",
".",
"validate",
"(",
"apiQuery",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"QueryResponse",
"{",
"}",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"q",
",",
"err",
":=",
"pql",
".",
"NewParser",
"(",
"strings",
".",
"NewReader",
"(",
"req",
".",
"Query",
")",
")",
".",
"Parse",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"QueryResponse",
"{",
"}",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"execOpts",
":=",
"&",
"execOptions",
"{",
"Remote",
":",
"req",
".",
"Remote",
",",
"ExcludeRowAttrs",
":",
"req",
".",
"ExcludeRowAttrs",
",",
"// NOTE: Kept for Pilosa 1.x compat.",
"ExcludeColumns",
":",
"req",
".",
"ExcludeColumns",
",",
"// NOTE: Kept for Pilosa 1.x compat.",
"ColumnAttrs",
":",
"req",
".",
"ColumnAttrs",
",",
"// NOTE: Kept for Pilosa 1.x compat.",
"}",
"\n",
"resp",
",",
"err",
":=",
"api",
".",
"server",
".",
"executor",
".",
"Execute",
"(",
"ctx",
",",
"req",
".",
"Index",
",",
"q",
",",
"req",
".",
"Shards",
",",
"execOpts",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"QueryResponse",
"{",
"}",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"resp",
",",
"nil",
"\n",
"}"
] |
// Query parses a PQL query out of the request and executes it.
|
[
"Query",
"parses",
"a",
"PQL",
"query",
"out",
"of",
"the",
"request",
"and",
"executes",
"it",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/api.go#L103-L127
|
train
|
pilosa/pilosa
|
api.go
|
CreateIndex
|
func (api *API) CreateIndex(ctx context.Context, indexName string, options IndexOptions) (*Index, error) {
span, _ := tracing.StartSpanFromContext(ctx, "API.CreateIndex")
defer span.Finish()
if err := api.validate(apiCreateIndex); err != nil {
return nil, errors.Wrap(err, "validating api method")
}
// Create index.
index, err := api.holder.CreateIndex(indexName, options)
if err != nil {
return nil, errors.Wrap(err, "creating index")
}
// Send the create index message to all nodes.
err = api.server.SendSync(
&CreateIndexMessage{
Index: indexName,
Meta: &options,
})
if err != nil {
return nil, errors.Wrap(err, "sending CreateIndex message")
}
api.holder.Stats.Count("createIndex", 1, 1.0)
return index, nil
}
|
go
|
func (api *API) CreateIndex(ctx context.Context, indexName string, options IndexOptions) (*Index, error) {
span, _ := tracing.StartSpanFromContext(ctx, "API.CreateIndex")
defer span.Finish()
if err := api.validate(apiCreateIndex); err != nil {
return nil, errors.Wrap(err, "validating api method")
}
// Create index.
index, err := api.holder.CreateIndex(indexName, options)
if err != nil {
return nil, errors.Wrap(err, "creating index")
}
// Send the create index message to all nodes.
err = api.server.SendSync(
&CreateIndexMessage{
Index: indexName,
Meta: &options,
})
if err != nil {
return nil, errors.Wrap(err, "sending CreateIndex message")
}
api.holder.Stats.Count("createIndex", 1, 1.0)
return index, nil
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"CreateIndex",
"(",
"ctx",
"context",
".",
"Context",
",",
"indexName",
"string",
",",
"options",
"IndexOptions",
")",
"(",
"*",
"Index",
",",
"error",
")",
"{",
"span",
",",
"_",
":=",
"tracing",
".",
"StartSpanFromContext",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n\n",
"if",
"err",
":=",
"api",
".",
"validate",
"(",
"apiCreateIndex",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Create index.",
"index",
",",
"err",
":=",
"api",
".",
"holder",
".",
"CreateIndex",
"(",
"indexName",
",",
"options",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// Send the create index message to all nodes.",
"err",
"=",
"api",
".",
"server",
".",
"SendSync",
"(",
"&",
"CreateIndexMessage",
"{",
"Index",
":",
"indexName",
",",
"Meta",
":",
"&",
"options",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"api",
".",
"holder",
".",
"Stats",
".",
"Count",
"(",
"\"",
"\"",
",",
"1",
",",
"1.0",
")",
"\n",
"return",
"index",
",",
"nil",
"\n",
"}"
] |
// CreateIndex makes a new Pilosa index.
|
[
"CreateIndex",
"makes",
"a",
"new",
"Pilosa",
"index",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/api.go#L130-L154
|
train
|
pilosa/pilosa
|
api.go
|
Index
|
func (api *API) Index(ctx context.Context, indexName string) (*Index, error) {
span, _ := tracing.StartSpanFromContext(ctx, "API.Index")
defer span.Finish()
if err := api.validate(apiIndex); err != nil {
return nil, errors.Wrap(err, "validating api method")
}
index := api.holder.Index(indexName)
if index == nil {
return nil, newNotFoundError(ErrIndexNotFound)
}
return index, nil
}
|
go
|
func (api *API) Index(ctx context.Context, indexName string) (*Index, error) {
span, _ := tracing.StartSpanFromContext(ctx, "API.Index")
defer span.Finish()
if err := api.validate(apiIndex); err != nil {
return nil, errors.Wrap(err, "validating api method")
}
index := api.holder.Index(indexName)
if index == nil {
return nil, newNotFoundError(ErrIndexNotFound)
}
return index, nil
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"Index",
"(",
"ctx",
"context",
".",
"Context",
",",
"indexName",
"string",
")",
"(",
"*",
"Index",
",",
"error",
")",
"{",
"span",
",",
"_",
":=",
"tracing",
".",
"StartSpanFromContext",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n\n",
"if",
"err",
":=",
"api",
".",
"validate",
"(",
"apiIndex",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"index",
":=",
"api",
".",
"holder",
".",
"Index",
"(",
"indexName",
")",
"\n",
"if",
"index",
"==",
"nil",
"{",
"return",
"nil",
",",
"newNotFoundError",
"(",
"ErrIndexNotFound",
")",
"\n",
"}",
"\n",
"return",
"index",
",",
"nil",
"\n",
"}"
] |
// Index retrieves the named index.
|
[
"Index",
"retrieves",
"the",
"named",
"index",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/api.go#L157-L170
|
train
|
pilosa/pilosa
|
api.go
|
DeleteIndex
|
func (api *API) DeleteIndex(ctx context.Context, indexName string) error {
span, _ := tracing.StartSpanFromContext(ctx, "API.DeleteIndex")
defer span.Finish()
if err := api.validate(apiDeleteIndex); err != nil {
return errors.Wrap(err, "validating api method")
}
// Delete index from the holder.
err := api.holder.DeleteIndex(indexName)
if err != nil {
return errors.Wrap(err, "deleting index")
}
// Send the delete index message to all nodes.
err = api.server.SendSync(
&DeleteIndexMessage{
Index: indexName,
})
if err != nil {
api.server.logger.Printf("problem sending DeleteIndex message: %s", err)
return errors.Wrap(err, "sending DeleteIndex message")
}
api.holder.Stats.Count("deleteIndex", 1, 1.0)
return nil
}
|
go
|
func (api *API) DeleteIndex(ctx context.Context, indexName string) error {
span, _ := tracing.StartSpanFromContext(ctx, "API.DeleteIndex")
defer span.Finish()
if err := api.validate(apiDeleteIndex); err != nil {
return errors.Wrap(err, "validating api method")
}
// Delete index from the holder.
err := api.holder.DeleteIndex(indexName)
if err != nil {
return errors.Wrap(err, "deleting index")
}
// Send the delete index message to all nodes.
err = api.server.SendSync(
&DeleteIndexMessage{
Index: indexName,
})
if err != nil {
api.server.logger.Printf("problem sending DeleteIndex message: %s", err)
return errors.Wrap(err, "sending DeleteIndex message")
}
api.holder.Stats.Count("deleteIndex", 1, 1.0)
return nil
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"DeleteIndex",
"(",
"ctx",
"context",
".",
"Context",
",",
"indexName",
"string",
")",
"error",
"{",
"span",
",",
"_",
":=",
"tracing",
".",
"StartSpanFromContext",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n\n",
"if",
"err",
":=",
"api",
".",
"validate",
"(",
"apiDeleteIndex",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Delete index from the holder.",
"err",
":=",
"api",
".",
"holder",
".",
"DeleteIndex",
"(",
"indexName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// Send the delete index message to all nodes.",
"err",
"=",
"api",
".",
"server",
".",
"SendSync",
"(",
"&",
"DeleteIndexMessage",
"{",
"Index",
":",
"indexName",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"api",
".",
"server",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"api",
".",
"holder",
".",
"Stats",
".",
"Count",
"(",
"\"",
"\"",
",",
"1",
",",
"1.0",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// DeleteIndex removes the named index. If the index is not found it does
// nothing and returns no error.
|
[
"DeleteIndex",
"removes",
"the",
"named",
"index",
".",
"If",
"the",
"index",
"is",
"not",
"found",
"it",
"does",
"nothing",
"and",
"returns",
"no",
"error",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/api.go#L174-L198
|
train
|
pilosa/pilosa
|
api.go
|
CreateField
|
func (api *API) CreateField(ctx context.Context, indexName string, fieldName string, opts ...FieldOption) (*Field, error) {
span, _ := tracing.StartSpanFromContext(ctx, "API.CreateField")
defer span.Finish()
if err := api.validate(apiCreateField); err != nil {
return nil, errors.Wrap(err, "validating api method")
}
// Apply functional options.
fo := FieldOptions{}
for _, opt := range opts {
err := opt(&fo)
if err != nil {
return nil, errors.Wrap(err, "applying option")
}
}
// Find index.
index := api.holder.Index(indexName)
if index == nil {
return nil, newNotFoundError(ErrIndexNotFound)
}
// Create field.
field, err := index.CreateField(fieldName, opts...)
if err != nil {
return nil, errors.Wrap(err, "creating field")
}
// Send the create field message to all nodes.
err = api.server.SendSync(
&CreateFieldMessage{
Index: indexName,
Field: fieldName,
Meta: &fo,
})
if err != nil {
api.server.logger.Printf("problem sending CreateField message: %s", err)
return nil, errors.Wrap(err, "sending CreateField message")
}
api.holder.Stats.CountWithCustomTags("createField", 1, 1.0, []string{fmt.Sprintf("index:%s", indexName)})
return field, nil
}
|
go
|
func (api *API) CreateField(ctx context.Context, indexName string, fieldName string, opts ...FieldOption) (*Field, error) {
span, _ := tracing.StartSpanFromContext(ctx, "API.CreateField")
defer span.Finish()
if err := api.validate(apiCreateField); err != nil {
return nil, errors.Wrap(err, "validating api method")
}
// Apply functional options.
fo := FieldOptions{}
for _, opt := range opts {
err := opt(&fo)
if err != nil {
return nil, errors.Wrap(err, "applying option")
}
}
// Find index.
index := api.holder.Index(indexName)
if index == nil {
return nil, newNotFoundError(ErrIndexNotFound)
}
// Create field.
field, err := index.CreateField(fieldName, opts...)
if err != nil {
return nil, errors.Wrap(err, "creating field")
}
// Send the create field message to all nodes.
err = api.server.SendSync(
&CreateFieldMessage{
Index: indexName,
Field: fieldName,
Meta: &fo,
})
if err != nil {
api.server.logger.Printf("problem sending CreateField message: %s", err)
return nil, errors.Wrap(err, "sending CreateField message")
}
api.holder.Stats.CountWithCustomTags("createField", 1, 1.0, []string{fmt.Sprintf("index:%s", indexName)})
return field, nil
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"CreateField",
"(",
"ctx",
"context",
".",
"Context",
",",
"indexName",
"string",
",",
"fieldName",
"string",
",",
"opts",
"...",
"FieldOption",
")",
"(",
"*",
"Field",
",",
"error",
")",
"{",
"span",
",",
"_",
":=",
"tracing",
".",
"StartSpanFromContext",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n\n",
"if",
"err",
":=",
"api",
".",
"validate",
"(",
"apiCreateField",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Apply functional options.",
"fo",
":=",
"FieldOptions",
"{",
"}",
"\n",
"for",
"_",
",",
"opt",
":=",
"range",
"opts",
"{",
"err",
":=",
"opt",
"(",
"&",
"fo",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Find index.",
"index",
":=",
"api",
".",
"holder",
".",
"Index",
"(",
"indexName",
")",
"\n",
"if",
"index",
"==",
"nil",
"{",
"return",
"nil",
",",
"newNotFoundError",
"(",
"ErrIndexNotFound",
")",
"\n",
"}",
"\n\n",
"// Create field.",
"field",
",",
"err",
":=",
"index",
".",
"CreateField",
"(",
"fieldName",
",",
"opts",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Send the create field message to all nodes.",
"err",
"=",
"api",
".",
"server",
".",
"SendSync",
"(",
"&",
"CreateFieldMessage",
"{",
"Index",
":",
"indexName",
",",
"Field",
":",
"fieldName",
",",
"Meta",
":",
"&",
"fo",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"api",
".",
"server",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"api",
".",
"holder",
".",
"Stats",
".",
"CountWithCustomTags",
"(",
"\"",
"\"",
",",
"1",
",",
"1.0",
",",
"[",
"]",
"string",
"{",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"indexName",
")",
"}",
")",
"\n",
"return",
"field",
",",
"nil",
"\n",
"}"
] |
// CreateField makes the named field in the named index with the given options.
// This method currently only takes a single functional option, but that may be
// changed in the future to support multiple options.
|
[
"CreateField",
"makes",
"the",
"named",
"field",
"in",
"the",
"named",
"index",
"with",
"the",
"given",
"options",
".",
"This",
"method",
"currently",
"only",
"takes",
"a",
"single",
"functional",
"option",
"but",
"that",
"may",
"be",
"changed",
"in",
"the",
"future",
"to",
"support",
"multiple",
"options",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/api.go#L203-L245
|
train
|
pilosa/pilosa
|
api.go
|
Field
|
func (api *API) Field(ctx context.Context, indexName, fieldName string) (*Field, error) {
span, _ := tracing.StartSpanFromContext(ctx, "API.Field")
defer span.Finish()
if err := api.validate(apiField); err != nil {
return nil, errors.Wrap(err, "validating api method")
}
field := api.holder.Field(indexName, fieldName)
if field == nil {
return nil, newNotFoundError(ErrFieldNotFound)
}
return field, nil
}
|
go
|
func (api *API) Field(ctx context.Context, indexName, fieldName string) (*Field, error) {
span, _ := tracing.StartSpanFromContext(ctx, "API.Field")
defer span.Finish()
if err := api.validate(apiField); err != nil {
return nil, errors.Wrap(err, "validating api method")
}
field := api.holder.Field(indexName, fieldName)
if field == nil {
return nil, newNotFoundError(ErrFieldNotFound)
}
return field, nil
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"Field",
"(",
"ctx",
"context",
".",
"Context",
",",
"indexName",
",",
"fieldName",
"string",
")",
"(",
"*",
"Field",
",",
"error",
")",
"{",
"span",
",",
"_",
":=",
"tracing",
".",
"StartSpanFromContext",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n\n",
"if",
"err",
":=",
"api",
".",
"validate",
"(",
"apiField",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"field",
":=",
"api",
".",
"holder",
".",
"Field",
"(",
"indexName",
",",
"fieldName",
")",
"\n",
"if",
"field",
"==",
"nil",
"{",
"return",
"nil",
",",
"newNotFoundError",
"(",
"ErrFieldNotFound",
")",
"\n",
"}",
"\n",
"return",
"field",
",",
"nil",
"\n",
"}"
] |
// Field retrieves the named field.
|
[
"Field",
"retrieves",
"the",
"named",
"field",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/api.go#L248-L261
|
train
|
pilosa/pilosa
|
api.go
|
DeleteField
|
func (api *API) DeleteField(ctx context.Context, indexName string, fieldName string) error {
span, _ := tracing.StartSpanFromContext(ctx, "API.DeleteField")
defer span.Finish()
if err := api.validate(apiDeleteField); err != nil {
return errors.Wrap(err, "validating api method")
}
// Find index.
index := api.holder.Index(indexName)
if index == nil {
return newNotFoundError(ErrIndexNotFound)
}
// Delete field from the index.
if err := index.DeleteField(fieldName); err != nil {
return errors.Wrap(err, "deleting field")
}
// Send the delete field message to all nodes.
err := api.server.SendSync(
&DeleteFieldMessage{
Index: indexName,
Field: fieldName,
})
if err != nil {
api.server.logger.Printf("problem sending DeleteField message: %s", err)
return errors.Wrap(err, "sending DeleteField message")
}
api.holder.Stats.CountWithCustomTags("deleteField", 1, 1.0, []string{fmt.Sprintf("index:%s", indexName)})
return nil
}
|
go
|
func (api *API) DeleteField(ctx context.Context, indexName string, fieldName string) error {
span, _ := tracing.StartSpanFromContext(ctx, "API.DeleteField")
defer span.Finish()
if err := api.validate(apiDeleteField); err != nil {
return errors.Wrap(err, "validating api method")
}
// Find index.
index := api.holder.Index(indexName)
if index == nil {
return newNotFoundError(ErrIndexNotFound)
}
// Delete field from the index.
if err := index.DeleteField(fieldName); err != nil {
return errors.Wrap(err, "deleting field")
}
// Send the delete field message to all nodes.
err := api.server.SendSync(
&DeleteFieldMessage{
Index: indexName,
Field: fieldName,
})
if err != nil {
api.server.logger.Printf("problem sending DeleteField message: %s", err)
return errors.Wrap(err, "sending DeleteField message")
}
api.holder.Stats.CountWithCustomTags("deleteField", 1, 1.0, []string{fmt.Sprintf("index:%s", indexName)})
return nil
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"DeleteField",
"(",
"ctx",
"context",
".",
"Context",
",",
"indexName",
"string",
",",
"fieldName",
"string",
")",
"error",
"{",
"span",
",",
"_",
":=",
"tracing",
".",
"StartSpanFromContext",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n\n",
"if",
"err",
":=",
"api",
".",
"validate",
"(",
"apiDeleteField",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Find index.",
"index",
":=",
"api",
".",
"holder",
".",
"Index",
"(",
"indexName",
")",
"\n",
"if",
"index",
"==",
"nil",
"{",
"return",
"newNotFoundError",
"(",
"ErrIndexNotFound",
")",
"\n",
"}",
"\n\n",
"// Delete field from the index.",
"if",
"err",
":=",
"index",
".",
"DeleteField",
"(",
"fieldName",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Send the delete field message to all nodes.",
"err",
":=",
"api",
".",
"server",
".",
"SendSync",
"(",
"&",
"DeleteFieldMessage",
"{",
"Index",
":",
"indexName",
",",
"Field",
":",
"fieldName",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"api",
".",
"server",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"api",
".",
"holder",
".",
"Stats",
".",
"CountWithCustomTags",
"(",
"\"",
"\"",
",",
"1",
",",
"1.0",
",",
"[",
"]",
"string",
"{",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"indexName",
")",
"}",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// DeleteField removes the named field from the named index. If the index is not
// found, an error is returned. If the field is not found, it is ignored and no
// action is taken.
|
[
"DeleteField",
"removes",
"the",
"named",
"field",
"from",
"the",
"named",
"index",
".",
"If",
"the",
"index",
"is",
"not",
"found",
"an",
"error",
"is",
"returned",
".",
"If",
"the",
"field",
"is",
"not",
"found",
"it",
"is",
"ignored",
"and",
"no",
"action",
"is",
"taken",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/api.go#L360-L391
|
train
|
pilosa/pilosa
|
api.go
|
DeleteAvailableShard
|
func (api *API) DeleteAvailableShard(_ context.Context, indexName, fieldName string, shardID uint64) error {
if err := api.validate(apiDeleteAvailableShard); err != nil {
return errors.Wrap(err, "validating api method")
}
// Find field.
field := api.holder.Field(indexName, fieldName)
if field == nil {
return newNotFoundError(ErrFieldNotFound)
}
// Delete shard from the cache.
if err := field.RemoveAvailableShard(shardID); err != nil {
return errors.Wrap(err, "deleting available shard")
}
// Send the delete shard message to all nodes.
err := api.server.SendSync(
&DeleteAvailableShardMessage{
Index: indexName,
Field: fieldName,
ShardID: shardID,
})
if err != nil {
api.server.logger.Printf("problem sending DeleteAvailableShard message: %s", err)
return errors.Wrap(err, "sending DeleteAvailableShard message")
}
api.holder.Stats.CountWithCustomTags("deleteAvailableShard", 1, 1.0, []string{fmt.Sprintf("index:%s", indexName), fmt.Sprintf("field:%s", fieldName)})
return nil
}
|
go
|
func (api *API) DeleteAvailableShard(_ context.Context, indexName, fieldName string, shardID uint64) error {
if err := api.validate(apiDeleteAvailableShard); err != nil {
return errors.Wrap(err, "validating api method")
}
// Find field.
field := api.holder.Field(indexName, fieldName)
if field == nil {
return newNotFoundError(ErrFieldNotFound)
}
// Delete shard from the cache.
if err := field.RemoveAvailableShard(shardID); err != nil {
return errors.Wrap(err, "deleting available shard")
}
// Send the delete shard message to all nodes.
err := api.server.SendSync(
&DeleteAvailableShardMessage{
Index: indexName,
Field: fieldName,
ShardID: shardID,
})
if err != nil {
api.server.logger.Printf("problem sending DeleteAvailableShard message: %s", err)
return errors.Wrap(err, "sending DeleteAvailableShard message")
}
api.holder.Stats.CountWithCustomTags("deleteAvailableShard", 1, 1.0, []string{fmt.Sprintf("index:%s", indexName), fmt.Sprintf("field:%s", fieldName)})
return nil
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"DeleteAvailableShard",
"(",
"_",
"context",
".",
"Context",
",",
"indexName",
",",
"fieldName",
"string",
",",
"shardID",
"uint64",
")",
"error",
"{",
"if",
"err",
":=",
"api",
".",
"validate",
"(",
"apiDeleteAvailableShard",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Find field.",
"field",
":=",
"api",
".",
"holder",
".",
"Field",
"(",
"indexName",
",",
"fieldName",
")",
"\n",
"if",
"field",
"==",
"nil",
"{",
"return",
"newNotFoundError",
"(",
"ErrFieldNotFound",
")",
"\n",
"}",
"\n\n",
"// Delete shard from the cache.",
"if",
"err",
":=",
"field",
".",
"RemoveAvailableShard",
"(",
"shardID",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Send the delete shard message to all nodes.",
"err",
":=",
"api",
".",
"server",
".",
"SendSync",
"(",
"&",
"DeleteAvailableShardMessage",
"{",
"Index",
":",
"indexName",
",",
"Field",
":",
"fieldName",
",",
"ShardID",
":",
"shardID",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"api",
".",
"server",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"api",
".",
"holder",
".",
"Stats",
".",
"CountWithCustomTags",
"(",
"\"",
"\"",
",",
"1",
",",
"1.0",
",",
"[",
"]",
"string",
"{",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"indexName",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"fieldName",
")",
"}",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// DeleteAvailableShard a shard ID from the available shard set cache.
|
[
"DeleteAvailableShard",
"a",
"shard",
"ID",
"from",
"the",
"available",
"shard",
"set",
"cache",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/api.go#L394-L423
|
train
|
pilosa/pilosa
|
api.go
|
ShardNodes
|
func (api *API) ShardNodes(ctx context.Context, indexName string, shard uint64) ([]*Node, error) {
span, _ := tracing.StartSpanFromContext(ctx, "API.ShardNodes")
defer span.Finish()
if err := api.validate(apiShardNodes); err != nil {
return nil, errors.Wrap(err, "validating api method")
}
return api.cluster.shardNodes(indexName, shard), nil
}
|
go
|
func (api *API) ShardNodes(ctx context.Context, indexName string, shard uint64) ([]*Node, error) {
span, _ := tracing.StartSpanFromContext(ctx, "API.ShardNodes")
defer span.Finish()
if err := api.validate(apiShardNodes); err != nil {
return nil, errors.Wrap(err, "validating api method")
}
return api.cluster.shardNodes(indexName, shard), nil
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"ShardNodes",
"(",
"ctx",
"context",
".",
"Context",
",",
"indexName",
"string",
",",
"shard",
"uint64",
")",
"(",
"[",
"]",
"*",
"Node",
",",
"error",
")",
"{",
"span",
",",
"_",
":=",
"tracing",
".",
"StartSpanFromContext",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n\n",
"if",
"err",
":=",
"api",
".",
"validate",
"(",
"apiShardNodes",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"api",
".",
"cluster",
".",
"shardNodes",
"(",
"indexName",
",",
"shard",
")",
",",
"nil",
"\n",
"}"
] |
// ShardNodes returns the node and all replicas which should contain a shard's data.
|
[
"ShardNodes",
"returns",
"the",
"node",
"and",
"all",
"replicas",
"which",
"should",
"contain",
"a",
"shard",
"s",
"data",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/api.go#L504-L513
|
train
|
pilosa/pilosa
|
api.go
|
FragmentBlockData
|
func (api *API) FragmentBlockData(ctx context.Context, body io.Reader) ([]byte, error) {
span, _ := tracing.StartSpanFromContext(ctx, "API.FragmentBlockData")
defer span.Finish()
if err := api.validate(apiFragmentBlockData); err != nil {
return nil, errors.Wrap(err, "validating api method")
}
reqBytes, err := ioutil.ReadAll(body)
if err != nil {
return nil, NewBadRequestError(errors.Wrap(err, "read body error"))
}
var req BlockDataRequest
if err := api.Serializer.Unmarshal(reqBytes, &req); err != nil {
return nil, NewBadRequestError(errors.Wrap(err, "unmarshal body error"))
}
// Retrieve fragment from holder.
f := api.holder.fragment(req.Index, req.Field, req.View, req.Shard)
if f == nil {
return nil, ErrFragmentNotFound
}
var resp = BlockDataResponse{}
resp.RowIDs, resp.ColumnIDs = f.blockData(int(req.Block))
// Encode response.
buf, err := api.Serializer.Marshal(&resp)
if err != nil {
return nil, errors.Wrap(err, "merge block response encoding error")
}
return buf, nil
}
|
go
|
func (api *API) FragmentBlockData(ctx context.Context, body io.Reader) ([]byte, error) {
span, _ := tracing.StartSpanFromContext(ctx, "API.FragmentBlockData")
defer span.Finish()
if err := api.validate(apiFragmentBlockData); err != nil {
return nil, errors.Wrap(err, "validating api method")
}
reqBytes, err := ioutil.ReadAll(body)
if err != nil {
return nil, NewBadRequestError(errors.Wrap(err, "read body error"))
}
var req BlockDataRequest
if err := api.Serializer.Unmarshal(reqBytes, &req); err != nil {
return nil, NewBadRequestError(errors.Wrap(err, "unmarshal body error"))
}
// Retrieve fragment from holder.
f := api.holder.fragment(req.Index, req.Field, req.View, req.Shard)
if f == nil {
return nil, ErrFragmentNotFound
}
var resp = BlockDataResponse{}
resp.RowIDs, resp.ColumnIDs = f.blockData(int(req.Block))
// Encode response.
buf, err := api.Serializer.Marshal(&resp)
if err != nil {
return nil, errors.Wrap(err, "merge block response encoding error")
}
return buf, nil
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"FragmentBlockData",
"(",
"ctx",
"context",
".",
"Context",
",",
"body",
"io",
".",
"Reader",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"span",
",",
"_",
":=",
"tracing",
".",
"StartSpanFromContext",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n\n",
"if",
"err",
":=",
"api",
".",
"validate",
"(",
"apiFragmentBlockData",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"reqBytes",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"NewBadRequestError",
"(",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"var",
"req",
"BlockDataRequest",
"\n",
"if",
"err",
":=",
"api",
".",
"Serializer",
".",
"Unmarshal",
"(",
"reqBytes",
",",
"&",
"req",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"NewBadRequestError",
"(",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n\n",
"// Retrieve fragment from holder.",
"f",
":=",
"api",
".",
"holder",
".",
"fragment",
"(",
"req",
".",
"Index",
",",
"req",
".",
"Field",
",",
"req",
".",
"View",
",",
"req",
".",
"Shard",
")",
"\n",
"if",
"f",
"==",
"nil",
"{",
"return",
"nil",
",",
"ErrFragmentNotFound",
"\n",
"}",
"\n\n",
"var",
"resp",
"=",
"BlockDataResponse",
"{",
"}",
"\n",
"resp",
".",
"RowIDs",
",",
"resp",
".",
"ColumnIDs",
"=",
"f",
".",
"blockData",
"(",
"int",
"(",
"req",
".",
"Block",
")",
")",
"\n\n",
"// Encode response.",
"buf",
",",
"err",
":=",
"api",
".",
"Serializer",
".",
"Marshal",
"(",
"&",
"resp",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"buf",
",",
"nil",
"\n",
"}"
] |
// FragmentBlockData is an endpoint for internal usage. It is not guaranteed to
// return anything useful. Currently it returns protobuf encoded row and column
// ids from a "block" which is a subdivision of a fragment.
|
[
"FragmentBlockData",
"is",
"an",
"endpoint",
"for",
"internal",
"usage",
".",
"It",
"is",
"not",
"guaranteed",
"to",
"return",
"anything",
"useful",
".",
"Currently",
"it",
"returns",
"protobuf",
"encoded",
"row",
"and",
"column",
"ids",
"from",
"a",
"block",
"which",
"is",
"a",
"subdivision",
"of",
"a",
"fragment",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/api.go#L518-L551
|
train
|
pilosa/pilosa
|
api.go
|
FragmentBlocks
|
func (api *API) FragmentBlocks(ctx context.Context, indexName, fieldName, viewName string, shard uint64) ([]FragmentBlock, error) {
span, _ := tracing.StartSpanFromContext(ctx, "API.FragmentBlocks")
defer span.Finish()
if err := api.validate(apiFragmentBlocks); err != nil {
return nil, errors.Wrap(err, "validating api method")
}
// Retrieve fragment from holder.
f := api.holder.fragment(indexName, fieldName, viewName, shard)
if f == nil {
return nil, ErrFragmentNotFound
}
// Retrieve blocks.
blocks := f.Blocks()
return blocks, nil
}
|
go
|
func (api *API) FragmentBlocks(ctx context.Context, indexName, fieldName, viewName string, shard uint64) ([]FragmentBlock, error) {
span, _ := tracing.StartSpanFromContext(ctx, "API.FragmentBlocks")
defer span.Finish()
if err := api.validate(apiFragmentBlocks); err != nil {
return nil, errors.Wrap(err, "validating api method")
}
// Retrieve fragment from holder.
f := api.holder.fragment(indexName, fieldName, viewName, shard)
if f == nil {
return nil, ErrFragmentNotFound
}
// Retrieve blocks.
blocks := f.Blocks()
return blocks, nil
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"FragmentBlocks",
"(",
"ctx",
"context",
".",
"Context",
",",
"indexName",
",",
"fieldName",
",",
"viewName",
"string",
",",
"shard",
"uint64",
")",
"(",
"[",
"]",
"FragmentBlock",
",",
"error",
")",
"{",
"span",
",",
"_",
":=",
"tracing",
".",
"StartSpanFromContext",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n\n",
"if",
"err",
":=",
"api",
".",
"validate",
"(",
"apiFragmentBlocks",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Retrieve fragment from holder.",
"f",
":=",
"api",
".",
"holder",
".",
"fragment",
"(",
"indexName",
",",
"fieldName",
",",
"viewName",
",",
"shard",
")",
"\n",
"if",
"f",
"==",
"nil",
"{",
"return",
"nil",
",",
"ErrFragmentNotFound",
"\n",
"}",
"\n\n",
"// Retrieve blocks.",
"blocks",
":=",
"f",
".",
"Blocks",
"(",
")",
"\n",
"return",
"blocks",
",",
"nil",
"\n",
"}"
] |
// FragmentBlocks returns the checksums and block ids for all blocks in the specified fragment.
|
[
"FragmentBlocks",
"returns",
"the",
"checksums",
"and",
"block",
"ids",
"for",
"all",
"blocks",
"in",
"the",
"specified",
"fragment",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/api.go#L554-L571
|
train
|
pilosa/pilosa
|
api.go
|
FragmentData
|
func (api *API) FragmentData(ctx context.Context, indexName, fieldName, viewName string, shard uint64) (io.WriterTo, error) {
span, _ := tracing.StartSpanFromContext(ctx, "API.FragmentData")
defer span.Finish()
if err := api.validate(apiFragmentData); err != nil {
return nil, errors.Wrap(err, "validating api method")
}
// Retrieve fragment from holder.
f := api.holder.fragment(indexName, fieldName, viewName, shard)
if f == nil {
return nil, ErrFragmentNotFound
}
return f, nil
}
|
go
|
func (api *API) FragmentData(ctx context.Context, indexName, fieldName, viewName string, shard uint64) (io.WriterTo, error) {
span, _ := tracing.StartSpanFromContext(ctx, "API.FragmentData")
defer span.Finish()
if err := api.validate(apiFragmentData); err != nil {
return nil, errors.Wrap(err, "validating api method")
}
// Retrieve fragment from holder.
f := api.holder.fragment(indexName, fieldName, viewName, shard)
if f == nil {
return nil, ErrFragmentNotFound
}
return f, nil
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"FragmentData",
"(",
"ctx",
"context",
".",
"Context",
",",
"indexName",
",",
"fieldName",
",",
"viewName",
"string",
",",
"shard",
"uint64",
")",
"(",
"io",
".",
"WriterTo",
",",
"error",
")",
"{",
"span",
",",
"_",
":=",
"tracing",
".",
"StartSpanFromContext",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n\n",
"if",
"err",
":=",
"api",
".",
"validate",
"(",
"apiFragmentData",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Retrieve fragment from holder.",
"f",
":=",
"api",
".",
"holder",
".",
"fragment",
"(",
"indexName",
",",
"fieldName",
",",
"viewName",
",",
"shard",
")",
"\n",
"if",
"f",
"==",
"nil",
"{",
"return",
"nil",
",",
"ErrFragmentNotFound",
"\n",
"}",
"\n",
"return",
"f",
",",
"nil",
"\n",
"}"
] |
// FragmentData returns all data in the specified fragment.
|
[
"FragmentData",
"returns",
"all",
"data",
"in",
"the",
"specified",
"fragment",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/api.go#L574-L588
|
train
|
pilosa/pilosa
|
api.go
|
Hosts
|
func (api *API) Hosts(ctx context.Context) []*Node {
span, _ := tracing.StartSpanFromContext(ctx, "API.Hosts")
defer span.Finish()
return api.cluster.Nodes()
}
|
go
|
func (api *API) Hosts(ctx context.Context) []*Node {
span, _ := tracing.StartSpanFromContext(ctx, "API.Hosts")
defer span.Finish()
return api.cluster.Nodes()
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"Hosts",
"(",
"ctx",
"context",
".",
"Context",
")",
"[",
"]",
"*",
"Node",
"{",
"span",
",",
"_",
":=",
"tracing",
".",
"StartSpanFromContext",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n",
"return",
"api",
".",
"cluster",
".",
"Nodes",
"(",
")",
"\n",
"}"
] |
// Hosts returns a list of the hosts in the cluster including their ID,
// URL, and which is the coordinator.
|
[
"Hosts",
"returns",
"a",
"list",
"of",
"the",
"hosts",
"in",
"the",
"cluster",
"including",
"their",
"ID",
"URL",
"and",
"which",
"is",
"the",
"coordinator",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/api.go#L592-L596
|
train
|
pilosa/pilosa
|
api.go
|
RecalculateCaches
|
func (api *API) RecalculateCaches(ctx context.Context) error {
span, _ := tracing.StartSpanFromContext(ctx, "API.RecalculateCaches")
defer span.Finish()
if err := api.validate(apiRecalculateCaches); err != nil {
return errors.Wrap(err, "validating api method")
}
err := api.server.SendSync(&RecalculateCaches{})
if err != nil {
return errors.Wrap(err, "broacasting message")
}
api.holder.recalculateCaches()
return nil
}
|
go
|
func (api *API) RecalculateCaches(ctx context.Context) error {
span, _ := tracing.StartSpanFromContext(ctx, "API.RecalculateCaches")
defer span.Finish()
if err := api.validate(apiRecalculateCaches); err != nil {
return errors.Wrap(err, "validating api method")
}
err := api.server.SendSync(&RecalculateCaches{})
if err != nil {
return errors.Wrap(err, "broacasting message")
}
api.holder.recalculateCaches()
return nil
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"RecalculateCaches",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"span",
",",
"_",
":=",
"tracing",
".",
"StartSpanFromContext",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n\n",
"if",
"err",
":=",
"api",
".",
"validate",
"(",
"apiRecalculateCaches",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"err",
":=",
"api",
".",
"server",
".",
"SendSync",
"(",
"&",
"RecalculateCaches",
"{",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"api",
".",
"holder",
".",
"recalculateCaches",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// RecalculateCaches forces all TopN caches to be updated. Used mainly for integration tests.
|
[
"RecalculateCaches",
"forces",
"all",
"TopN",
"caches",
"to",
"be",
"updated",
".",
"Used",
"mainly",
"for",
"integration",
"tests",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/api.go#L605-L619
|
train
|
pilosa/pilosa
|
api.go
|
ClusterMessage
|
func (api *API) ClusterMessage(ctx context.Context, reqBody io.Reader) error {
span, _ := tracing.StartSpanFromContext(ctx, "API.ClusterMessage")
defer span.Finish()
if err := api.validate(apiClusterMessage); err != nil {
return errors.Wrap(err, "validating api method")
}
// Read entire body.
body, err := ioutil.ReadAll(reqBody)
if err != nil {
return errors.Wrap(err, "reading body")
}
typ := body[0]
msg := getMessage(typ)
err = api.server.serializer.Unmarshal(body[1:], msg)
if err != nil {
return errors.Wrap(err, "deserializing cluster message")
}
// Forward the error message.
if err := api.server.receiveMessage(msg); err != nil {
return errors.Wrap(err, "receiving message")
}
return nil
}
|
go
|
func (api *API) ClusterMessage(ctx context.Context, reqBody io.Reader) error {
span, _ := tracing.StartSpanFromContext(ctx, "API.ClusterMessage")
defer span.Finish()
if err := api.validate(apiClusterMessage); err != nil {
return errors.Wrap(err, "validating api method")
}
// Read entire body.
body, err := ioutil.ReadAll(reqBody)
if err != nil {
return errors.Wrap(err, "reading body")
}
typ := body[0]
msg := getMessage(typ)
err = api.server.serializer.Unmarshal(body[1:], msg)
if err != nil {
return errors.Wrap(err, "deserializing cluster message")
}
// Forward the error message.
if err := api.server.receiveMessage(msg); err != nil {
return errors.Wrap(err, "receiving message")
}
return nil
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"ClusterMessage",
"(",
"ctx",
"context",
".",
"Context",
",",
"reqBody",
"io",
".",
"Reader",
")",
"error",
"{",
"span",
",",
"_",
":=",
"tracing",
".",
"StartSpanFromContext",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n\n",
"if",
"err",
":=",
"api",
".",
"validate",
"(",
"apiClusterMessage",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Read entire body.",
"body",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"reqBody",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"typ",
":=",
"body",
"[",
"0",
"]",
"\n",
"msg",
":=",
"getMessage",
"(",
"typ",
")",
"\n",
"err",
"=",
"api",
".",
"server",
".",
"serializer",
".",
"Unmarshal",
"(",
"body",
"[",
"1",
":",
"]",
",",
"msg",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Forward the error message.",
"if",
"err",
":=",
"api",
".",
"server",
".",
"receiveMessage",
"(",
"msg",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// ClusterMessage is for internal use. It decodes a protobuf message out of
// the body and forwards it to the BroadcastHandler.
|
[
"ClusterMessage",
"is",
"for",
"internal",
"use",
".",
"It",
"decodes",
"a",
"protobuf",
"message",
"out",
"of",
"the",
"body",
"and",
"forwards",
"it",
"to",
"the",
"BroadcastHandler",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/api.go#L623-L649
|
train
|
pilosa/pilosa
|
api.go
|
Schema
|
func (api *API) Schema(ctx context.Context) []*IndexInfo {
span, _ := tracing.StartSpanFromContext(ctx, "API.Schema")
defer span.Finish()
return api.holder.limitedSchema()
}
|
go
|
func (api *API) Schema(ctx context.Context) []*IndexInfo {
span, _ := tracing.StartSpanFromContext(ctx, "API.Schema")
defer span.Finish()
return api.holder.limitedSchema()
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"Schema",
"(",
"ctx",
"context",
".",
"Context",
")",
"[",
"]",
"*",
"IndexInfo",
"{",
"span",
",",
"_",
":=",
"tracing",
".",
"StartSpanFromContext",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n",
"return",
"api",
".",
"holder",
".",
"limitedSchema",
"(",
")",
"\n",
"}"
] |
// Schema returns information about each index in Pilosa including which fields
// they contain.
|
[
"Schema",
"returns",
"information",
"about",
"each",
"index",
"in",
"Pilosa",
"including",
"which",
"fields",
"they",
"contain",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/api.go#L653-L657
|
train
|
pilosa/pilosa
|
api.go
|
Views
|
func (api *API) Views(ctx context.Context, indexName string, fieldName string) ([]*view, error) {
span, _ := tracing.StartSpanFromContext(ctx, "API.Views")
defer span.Finish()
if err := api.validate(apiViews); err != nil {
return nil, errors.Wrap(err, "validating api method")
}
// Retrieve views.
f := api.holder.Field(indexName, fieldName)
if f == nil {
return nil, ErrFieldNotFound
}
// Fetch views.
views := f.views()
return views, nil
}
|
go
|
func (api *API) Views(ctx context.Context, indexName string, fieldName string) ([]*view, error) {
span, _ := tracing.StartSpanFromContext(ctx, "API.Views")
defer span.Finish()
if err := api.validate(apiViews); err != nil {
return nil, errors.Wrap(err, "validating api method")
}
// Retrieve views.
f := api.holder.Field(indexName, fieldName)
if f == nil {
return nil, ErrFieldNotFound
}
// Fetch views.
views := f.views()
return views, nil
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"Views",
"(",
"ctx",
"context",
".",
"Context",
",",
"indexName",
"string",
",",
"fieldName",
"string",
")",
"(",
"[",
"]",
"*",
"view",
",",
"error",
")",
"{",
"span",
",",
"_",
":=",
"tracing",
".",
"StartSpanFromContext",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n\n",
"if",
"err",
":=",
"api",
".",
"validate",
"(",
"apiViews",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Retrieve views.",
"f",
":=",
"api",
".",
"holder",
".",
"Field",
"(",
"indexName",
",",
"fieldName",
")",
"\n",
"if",
"f",
"==",
"nil",
"{",
"return",
"nil",
",",
"ErrFieldNotFound",
"\n",
"}",
"\n\n",
"// Fetch views.",
"views",
":=",
"f",
".",
"views",
"(",
")",
"\n",
"return",
"views",
",",
"nil",
"\n",
"}"
] |
// Views returns the views in the given field.
|
[
"Views",
"returns",
"the",
"views",
"in",
"the",
"given",
"field",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/api.go#L687-L704
|
train
|
pilosa/pilosa
|
api.go
|
DeleteView
|
func (api *API) DeleteView(ctx context.Context, indexName string, fieldName string, viewName string) error {
span, _ := tracing.StartSpanFromContext(ctx, "API.DeleteView")
defer span.Finish()
if err := api.validate(apiDeleteView); err != nil {
return errors.Wrap(err, "validating api method")
}
// Retrieve field.
f := api.holder.Field(indexName, fieldName)
if f == nil {
return ErrFieldNotFound
}
// Delete the view.
if err := f.deleteView(viewName); err != nil {
// Ignore this error because views do not exist on all nodes due to shard distribution.
if err != ErrInvalidView {
return errors.Wrap(err, "deleting view")
}
}
// Send the delete view message to all nodes.
err := api.server.SendSync(
&DeleteViewMessage{
Index: indexName,
Field: fieldName,
View: viewName,
})
if err != nil {
api.server.logger.Printf("problem sending DeleteView message: %s", err)
}
return errors.Wrap(err, "sending DeleteView message")
}
|
go
|
func (api *API) DeleteView(ctx context.Context, indexName string, fieldName string, viewName string) error {
span, _ := tracing.StartSpanFromContext(ctx, "API.DeleteView")
defer span.Finish()
if err := api.validate(apiDeleteView); err != nil {
return errors.Wrap(err, "validating api method")
}
// Retrieve field.
f := api.holder.Field(indexName, fieldName)
if f == nil {
return ErrFieldNotFound
}
// Delete the view.
if err := f.deleteView(viewName); err != nil {
// Ignore this error because views do not exist on all nodes due to shard distribution.
if err != ErrInvalidView {
return errors.Wrap(err, "deleting view")
}
}
// Send the delete view message to all nodes.
err := api.server.SendSync(
&DeleteViewMessage{
Index: indexName,
Field: fieldName,
View: viewName,
})
if err != nil {
api.server.logger.Printf("problem sending DeleteView message: %s", err)
}
return errors.Wrap(err, "sending DeleteView message")
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"DeleteView",
"(",
"ctx",
"context",
".",
"Context",
",",
"indexName",
"string",
",",
"fieldName",
"string",
",",
"viewName",
"string",
")",
"error",
"{",
"span",
",",
"_",
":=",
"tracing",
".",
"StartSpanFromContext",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n\n",
"if",
"err",
":=",
"api",
".",
"validate",
"(",
"apiDeleteView",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Retrieve field.",
"f",
":=",
"api",
".",
"holder",
".",
"Field",
"(",
"indexName",
",",
"fieldName",
")",
"\n",
"if",
"f",
"==",
"nil",
"{",
"return",
"ErrFieldNotFound",
"\n",
"}",
"\n\n",
"// Delete the view.",
"if",
"err",
":=",
"f",
".",
"deleteView",
"(",
"viewName",
")",
";",
"err",
"!=",
"nil",
"{",
"// Ignore this error because views do not exist on all nodes due to shard distribution.",
"if",
"err",
"!=",
"ErrInvalidView",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Send the delete view message to all nodes.",
"err",
":=",
"api",
".",
"server",
".",
"SendSync",
"(",
"&",
"DeleteViewMessage",
"{",
"Index",
":",
"indexName",
",",
"Field",
":",
"fieldName",
",",
"View",
":",
"viewName",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"api",
".",
"server",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}"
] |
// DeleteView removes the given view.
|
[
"DeleteView",
"removes",
"the",
"given",
"view",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/api.go#L707-L741
|
train
|
pilosa/pilosa
|
api.go
|
IndexAttrDiff
|
func (api *API) IndexAttrDiff(ctx context.Context, indexName string, blocks []AttrBlock) (map[uint64]map[string]interface{}, error) {
span, _ := tracing.StartSpanFromContext(ctx, "API.IndexAttrDiff")
defer span.Finish()
if err := api.validate(apiIndexAttrDiff); err != nil {
return nil, errors.Wrap(err, "validating api method")
}
// Retrieve index from holder.
index := api.holder.Index(indexName)
if index == nil {
return nil, newNotFoundError(ErrIndexNotFound)
}
// Retrieve local blocks.
localBlocks, err := index.ColumnAttrStore().Blocks()
if err != nil {
return nil, errors.Wrap(err, "getting blocks")
}
// Read all attributes from all mismatched blocks.
attrs := make(map[uint64]map[string]interface{})
for _, blockID := range attrBlocks(localBlocks).Diff(blocks) {
// Retrieve block data.
m, err := index.ColumnAttrStore().BlockData(blockID)
if err != nil {
return nil, errors.Wrap(err, "getting block")
}
// Copy to index-wide struct.
for k, v := range m {
attrs[k] = v
}
}
return attrs, nil
}
|
go
|
func (api *API) IndexAttrDiff(ctx context.Context, indexName string, blocks []AttrBlock) (map[uint64]map[string]interface{}, error) {
span, _ := tracing.StartSpanFromContext(ctx, "API.IndexAttrDiff")
defer span.Finish()
if err := api.validate(apiIndexAttrDiff); err != nil {
return nil, errors.Wrap(err, "validating api method")
}
// Retrieve index from holder.
index := api.holder.Index(indexName)
if index == nil {
return nil, newNotFoundError(ErrIndexNotFound)
}
// Retrieve local blocks.
localBlocks, err := index.ColumnAttrStore().Blocks()
if err != nil {
return nil, errors.Wrap(err, "getting blocks")
}
// Read all attributes from all mismatched blocks.
attrs := make(map[uint64]map[string]interface{})
for _, blockID := range attrBlocks(localBlocks).Diff(blocks) {
// Retrieve block data.
m, err := index.ColumnAttrStore().BlockData(blockID)
if err != nil {
return nil, errors.Wrap(err, "getting block")
}
// Copy to index-wide struct.
for k, v := range m {
attrs[k] = v
}
}
return attrs, nil
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"IndexAttrDiff",
"(",
"ctx",
"context",
".",
"Context",
",",
"indexName",
"string",
",",
"blocks",
"[",
"]",
"AttrBlock",
")",
"(",
"map",
"[",
"uint64",
"]",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"span",
",",
"_",
":=",
"tracing",
".",
"StartSpanFromContext",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n\n",
"if",
"err",
":=",
"api",
".",
"validate",
"(",
"apiIndexAttrDiff",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Retrieve index from holder.",
"index",
":=",
"api",
".",
"holder",
".",
"Index",
"(",
"indexName",
")",
"\n",
"if",
"index",
"==",
"nil",
"{",
"return",
"nil",
",",
"newNotFoundError",
"(",
"ErrIndexNotFound",
")",
"\n",
"}",
"\n\n",
"// Retrieve local blocks.",
"localBlocks",
",",
"err",
":=",
"index",
".",
"ColumnAttrStore",
"(",
")",
".",
"Blocks",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Read all attributes from all mismatched blocks.",
"attrs",
":=",
"make",
"(",
"map",
"[",
"uint64",
"]",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"for",
"_",
",",
"blockID",
":=",
"range",
"attrBlocks",
"(",
"localBlocks",
")",
".",
"Diff",
"(",
"blocks",
")",
"{",
"// Retrieve block data.",
"m",
",",
"err",
":=",
"index",
".",
"ColumnAttrStore",
"(",
")",
".",
"BlockData",
"(",
"blockID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Copy to index-wide struct.",
"for",
"k",
",",
"v",
":=",
"range",
"m",
"{",
"attrs",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"attrs",
",",
"nil",
"\n",
"}"
] |
// IndexAttrDiff determines the local column attribute data blocks which differ from those provided.
|
[
"IndexAttrDiff",
"determines",
"the",
"local",
"column",
"attribute",
"data",
"blocks",
"which",
"differ",
"from",
"those",
"provided",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/api.go#L744-L779
|
train
|
pilosa/pilosa
|
api.go
|
FieldAttrDiff
|
func (api *API) FieldAttrDiff(ctx context.Context, indexName string, fieldName string, blocks []AttrBlock) (map[uint64]map[string]interface{}, error) {
span, _ := tracing.StartSpanFromContext(ctx, "API.FieldAttrDiff")
defer span.Finish()
if err := api.validate(apiFieldAttrDiff); err != nil {
return nil, errors.Wrap(err, "validating api method")
}
// Retrieve index from holder.
f := api.holder.Field(indexName, fieldName)
if f == nil {
return nil, ErrFieldNotFound
}
// Retrieve local blocks.
localBlocks, err := f.RowAttrStore().Blocks()
if err != nil {
return nil, errors.Wrap(err, "getting blocks")
}
// Read all attributes from all mismatched blocks.
attrs := make(map[uint64]map[string]interface{})
for _, blockID := range attrBlocks(localBlocks).Diff(blocks) {
// Retrieve block data.
m, err := f.RowAttrStore().BlockData(blockID)
if err != nil {
return nil, errors.Wrap(err, "getting block")
}
// Copy to index-wide struct.
for k, v := range m {
attrs[k] = v
}
}
return attrs, nil
}
|
go
|
func (api *API) FieldAttrDiff(ctx context.Context, indexName string, fieldName string, blocks []AttrBlock) (map[uint64]map[string]interface{}, error) {
span, _ := tracing.StartSpanFromContext(ctx, "API.FieldAttrDiff")
defer span.Finish()
if err := api.validate(apiFieldAttrDiff); err != nil {
return nil, errors.Wrap(err, "validating api method")
}
// Retrieve index from holder.
f := api.holder.Field(indexName, fieldName)
if f == nil {
return nil, ErrFieldNotFound
}
// Retrieve local blocks.
localBlocks, err := f.RowAttrStore().Blocks()
if err != nil {
return nil, errors.Wrap(err, "getting blocks")
}
// Read all attributes from all mismatched blocks.
attrs := make(map[uint64]map[string]interface{})
for _, blockID := range attrBlocks(localBlocks).Diff(blocks) {
// Retrieve block data.
m, err := f.RowAttrStore().BlockData(blockID)
if err != nil {
return nil, errors.Wrap(err, "getting block")
}
// Copy to index-wide struct.
for k, v := range m {
attrs[k] = v
}
}
return attrs, nil
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"FieldAttrDiff",
"(",
"ctx",
"context",
".",
"Context",
",",
"indexName",
"string",
",",
"fieldName",
"string",
",",
"blocks",
"[",
"]",
"AttrBlock",
")",
"(",
"map",
"[",
"uint64",
"]",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"span",
",",
"_",
":=",
"tracing",
".",
"StartSpanFromContext",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n\n",
"if",
"err",
":=",
"api",
".",
"validate",
"(",
"apiFieldAttrDiff",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Retrieve index from holder.",
"f",
":=",
"api",
".",
"holder",
".",
"Field",
"(",
"indexName",
",",
"fieldName",
")",
"\n",
"if",
"f",
"==",
"nil",
"{",
"return",
"nil",
",",
"ErrFieldNotFound",
"\n",
"}",
"\n\n",
"// Retrieve local blocks.",
"localBlocks",
",",
"err",
":=",
"f",
".",
"RowAttrStore",
"(",
")",
".",
"Blocks",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Read all attributes from all mismatched blocks.",
"attrs",
":=",
"make",
"(",
"map",
"[",
"uint64",
"]",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"for",
"_",
",",
"blockID",
":=",
"range",
"attrBlocks",
"(",
"localBlocks",
")",
".",
"Diff",
"(",
"blocks",
")",
"{",
"// Retrieve block data.",
"m",
",",
"err",
":=",
"f",
".",
"RowAttrStore",
"(",
")",
".",
"BlockData",
"(",
"blockID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Copy to index-wide struct.",
"for",
"k",
",",
"v",
":=",
"range",
"m",
"{",
"attrs",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"attrs",
",",
"nil",
"\n",
"}"
] |
// FieldAttrDiff determines the local row attribute data blocks which differ from those provided.
|
[
"FieldAttrDiff",
"determines",
"the",
"local",
"row",
"attribute",
"data",
"blocks",
"which",
"differ",
"from",
"those",
"provided",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/api.go#L782-L817
|
train
|
pilosa/pilosa
|
api.go
|
OptImportOptionsClear
|
func OptImportOptionsClear(c bool) ImportOption {
return func(o *ImportOptions) error {
o.Clear = c
return nil
}
}
|
go
|
func OptImportOptionsClear(c bool) ImportOption {
return func(o *ImportOptions) error {
o.Clear = c
return nil
}
}
|
[
"func",
"OptImportOptionsClear",
"(",
"c",
"bool",
")",
"ImportOption",
"{",
"return",
"func",
"(",
"o",
"*",
"ImportOptions",
")",
"error",
"{",
"o",
".",
"Clear",
"=",
"c",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] |
// OptImportOptionsClear is a functional option on ImportOption
// used to specify whether the import is a set or clear operation.
|
[
"OptImportOptionsClear",
"is",
"a",
"functional",
"option",
"on",
"ImportOption",
"used",
"to",
"specify",
"whether",
"the",
"import",
"is",
"a",
"set",
"or",
"clear",
"operation",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/api.go#L830-L835
|
train
|
pilosa/pilosa
|
api.go
|
OptImportOptionsIgnoreKeyCheck
|
func OptImportOptionsIgnoreKeyCheck(b bool) ImportOption {
return func(o *ImportOptions) error {
o.IgnoreKeyCheck = b
return nil
}
}
|
go
|
func OptImportOptionsIgnoreKeyCheck(b bool) ImportOption {
return func(o *ImportOptions) error {
o.IgnoreKeyCheck = b
return nil
}
}
|
[
"func",
"OptImportOptionsIgnoreKeyCheck",
"(",
"b",
"bool",
")",
"ImportOption",
"{",
"return",
"func",
"(",
"o",
"*",
"ImportOptions",
")",
"error",
"{",
"o",
".",
"IgnoreKeyCheck",
"=",
"b",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] |
// OptImportOptionsIgnoreKeyCheck is a functional option on ImportOption
// used to specify whether key check should be ignored.
|
[
"OptImportOptionsIgnoreKeyCheck",
"is",
"a",
"functional",
"option",
"on",
"ImportOption",
"used",
"to",
"specify",
"whether",
"key",
"check",
"should",
"be",
"ignored",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/api.go#L839-L844
|
train
|
pilosa/pilosa
|
api.go
|
AvailableShardsByIndex
|
func (api *API) AvailableShardsByIndex(ctx context.Context) map[string]*roaring.Bitmap {
span, _ := tracing.StartSpanFromContext(ctx, "API.AvailableShardsByIndex")
defer span.Finish()
return api.holder.availableShardsByIndex()
}
|
go
|
func (api *API) AvailableShardsByIndex(ctx context.Context) map[string]*roaring.Bitmap {
span, _ := tracing.StartSpanFromContext(ctx, "API.AvailableShardsByIndex")
defer span.Finish()
return api.holder.availableShardsByIndex()
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"AvailableShardsByIndex",
"(",
"ctx",
"context",
".",
"Context",
")",
"map",
"[",
"string",
"]",
"*",
"roaring",
".",
"Bitmap",
"{",
"span",
",",
"_",
":=",
"tracing",
".",
"StartSpanFromContext",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n",
"return",
"api",
".",
"holder",
".",
"availableShardsByIndex",
"(",
")",
"\n",
"}"
] |
// AvailableShardsByIndex returns bitmaps of shards with available by index name.
|
[
"AvailableShardsByIndex",
"returns",
"bitmaps",
"of",
"shards",
"with",
"available",
"by",
"index",
"name",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/api.go#L1064-L1068
|
train
|
pilosa/pilosa
|
api.go
|
StatsWithTags
|
func (api *API) StatsWithTags(tags []string) stats.StatsClient {
if api.holder == nil || api.cluster == nil {
return nil
}
return api.holder.Stats.WithTags(tags...)
}
|
go
|
func (api *API) StatsWithTags(tags []string) stats.StatsClient {
if api.holder == nil || api.cluster == nil {
return nil
}
return api.holder.Stats.WithTags(tags...)
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"StatsWithTags",
"(",
"tags",
"[",
"]",
"string",
")",
"stats",
".",
"StatsClient",
"{",
"if",
"api",
".",
"holder",
"==",
"nil",
"||",
"api",
".",
"cluster",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"api",
".",
"holder",
".",
"Stats",
".",
"WithTags",
"(",
"tags",
"...",
")",
"\n",
"}"
] |
// StatsWithTags returns an instance of whatever implementation of StatsClient
// pilosa is using with the given tags.
|
[
"StatsWithTags",
"returns",
"an",
"instance",
"of",
"whatever",
"implementation",
"of",
"StatsClient",
"pilosa",
"is",
"using",
"with",
"the",
"given",
"tags",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/api.go#L1072-L1077
|
train
|
pilosa/pilosa
|
api.go
|
SetCoordinator
|
func (api *API) SetCoordinator(ctx context.Context, id string) (oldNode, newNode *Node, err error) {
span, _ := tracing.StartSpanFromContext(ctx, "API.SetCoordinator")
defer span.Finish()
if err := api.validate(apiSetCoordinator); err != nil {
return nil, nil, errors.Wrap(err, "validating api method")
}
oldNode = api.cluster.nodeByID(api.cluster.Coordinator)
newNode = api.cluster.nodeByID(id)
if newNode == nil {
return nil, nil, errors.Wrap(ErrNodeIDNotExists, "getting new node")
}
// If the new coordinator is this node, do the SetCoordinator directly.
if newNode.ID == api.Node().ID {
return oldNode, newNode, api.cluster.setCoordinator(newNode)
}
// Send the set-coordinator message to new node.
err = api.server.SendTo(
newNode,
&SetCoordinatorMessage{
New: newNode,
})
if err != nil {
return nil, nil, fmt.Errorf("problem sending SetCoordinator message: %s", err)
}
return oldNode, newNode, nil
}
|
go
|
func (api *API) SetCoordinator(ctx context.Context, id string) (oldNode, newNode *Node, err error) {
span, _ := tracing.StartSpanFromContext(ctx, "API.SetCoordinator")
defer span.Finish()
if err := api.validate(apiSetCoordinator); err != nil {
return nil, nil, errors.Wrap(err, "validating api method")
}
oldNode = api.cluster.nodeByID(api.cluster.Coordinator)
newNode = api.cluster.nodeByID(id)
if newNode == nil {
return nil, nil, errors.Wrap(ErrNodeIDNotExists, "getting new node")
}
// If the new coordinator is this node, do the SetCoordinator directly.
if newNode.ID == api.Node().ID {
return oldNode, newNode, api.cluster.setCoordinator(newNode)
}
// Send the set-coordinator message to new node.
err = api.server.SendTo(
newNode,
&SetCoordinatorMessage{
New: newNode,
})
if err != nil {
return nil, nil, fmt.Errorf("problem sending SetCoordinator message: %s", err)
}
return oldNode, newNode, nil
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"SetCoordinator",
"(",
"ctx",
"context",
".",
"Context",
",",
"id",
"string",
")",
"(",
"oldNode",
",",
"newNode",
"*",
"Node",
",",
"err",
"error",
")",
"{",
"span",
",",
"_",
":=",
"tracing",
".",
"StartSpanFromContext",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n\n",
"if",
"err",
":=",
"api",
".",
"validate",
"(",
"apiSetCoordinator",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"oldNode",
"=",
"api",
".",
"cluster",
".",
"nodeByID",
"(",
"api",
".",
"cluster",
".",
"Coordinator",
")",
"\n",
"newNode",
"=",
"api",
".",
"cluster",
".",
"nodeByID",
"(",
"id",
")",
"\n",
"if",
"newNode",
"==",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"ErrNodeIDNotExists",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// If the new coordinator is this node, do the SetCoordinator directly.",
"if",
"newNode",
".",
"ID",
"==",
"api",
".",
"Node",
"(",
")",
".",
"ID",
"{",
"return",
"oldNode",
",",
"newNode",
",",
"api",
".",
"cluster",
".",
"setCoordinator",
"(",
"newNode",
")",
"\n",
"}",
"\n\n",
"// Send the set-coordinator message to new node.",
"err",
"=",
"api",
".",
"server",
".",
"SendTo",
"(",
"newNode",
",",
"&",
"SetCoordinatorMessage",
"{",
"New",
":",
"newNode",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"oldNode",
",",
"newNode",
",",
"nil",
"\n",
"}"
] |
// SetCoordinator makes a new Node the cluster coordinator.
|
[
"SetCoordinator",
"makes",
"a",
"new",
"Node",
"the",
"cluster",
"coordinator",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/api.go#L1117-L1146
|
train
|
pilosa/pilosa
|
api.go
|
RemoveNode
|
func (api *API) RemoveNode(id string) (*Node, error) {
if err := api.validate(apiRemoveNode); err != nil {
return nil, errors.Wrap(err, "validating api method")
}
removeNode := api.cluster.nodeByID(id)
if removeNode == nil {
if !api.cluster.topologyContainsNode(id) {
return nil, errors.Wrap(ErrNodeIDNotExists, "finding node to remove")
}
removeNode = &Node{
ID: id,
}
}
// Start the resize process (similar to NodeJoin)
err := api.cluster.nodeLeave(id)
if err != nil {
return removeNode, errors.Wrap(err, "calling node leave")
}
return removeNode, nil
}
|
go
|
func (api *API) RemoveNode(id string) (*Node, error) {
if err := api.validate(apiRemoveNode); err != nil {
return nil, errors.Wrap(err, "validating api method")
}
removeNode := api.cluster.nodeByID(id)
if removeNode == nil {
if !api.cluster.topologyContainsNode(id) {
return nil, errors.Wrap(ErrNodeIDNotExists, "finding node to remove")
}
removeNode = &Node{
ID: id,
}
}
// Start the resize process (similar to NodeJoin)
err := api.cluster.nodeLeave(id)
if err != nil {
return removeNode, errors.Wrap(err, "calling node leave")
}
return removeNode, nil
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"RemoveNode",
"(",
"id",
"string",
")",
"(",
"*",
"Node",
",",
"error",
")",
"{",
"if",
"err",
":=",
"api",
".",
"validate",
"(",
"apiRemoveNode",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"removeNode",
":=",
"api",
".",
"cluster",
".",
"nodeByID",
"(",
"id",
")",
"\n",
"if",
"removeNode",
"==",
"nil",
"{",
"if",
"!",
"api",
".",
"cluster",
".",
"topologyContainsNode",
"(",
"id",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"ErrNodeIDNotExists",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"removeNode",
"=",
"&",
"Node",
"{",
"ID",
":",
"id",
",",
"}",
"\n",
"}",
"\n\n",
"// Start the resize process (similar to NodeJoin)",
"err",
":=",
"api",
".",
"cluster",
".",
"nodeLeave",
"(",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"removeNode",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"removeNode",
",",
"nil",
"\n",
"}"
] |
// RemoveNode puts the cluster into the "RESIZING" state and begins the job of
// removing the given node.
|
[
"RemoveNode",
"puts",
"the",
"cluster",
"into",
"the",
"RESIZING",
"state",
"and",
"begins",
"the",
"job",
"of",
"removing",
"the",
"given",
"node",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/api.go#L1150-L1171
|
train
|
pilosa/pilosa
|
api.go
|
ResizeAbort
|
func (api *API) ResizeAbort() error {
if err := api.validate(apiResizeAbort); err != nil {
return errors.Wrap(err, "validating api method")
}
err := api.cluster.completeCurrentJob(resizeJobStateAborted)
return errors.Wrap(err, "complete current job")
}
|
go
|
func (api *API) ResizeAbort() error {
if err := api.validate(apiResizeAbort); err != nil {
return errors.Wrap(err, "validating api method")
}
err := api.cluster.completeCurrentJob(resizeJobStateAborted)
return errors.Wrap(err, "complete current job")
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"ResizeAbort",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"api",
".",
"validate",
"(",
"apiResizeAbort",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"err",
":=",
"api",
".",
"cluster",
".",
"completeCurrentJob",
"(",
"resizeJobStateAborted",
")",
"\n",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}"
] |
// ResizeAbort stops the current resize job.
|
[
"ResizeAbort",
"stops",
"the",
"current",
"resize",
"job",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/api.go#L1174-L1181
|
train
|
pilosa/pilosa
|
api.go
|
GetTranslateData
|
func (api *API) GetTranslateData(ctx context.Context, offset int64) (io.ReadCloser, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "API.GetTranslateData")
defer span.Finish()
rc, err := api.holder.translateFile.Reader(ctx, offset)
if err != nil {
return nil, errors.Wrap(err, "read from translate store")
}
// Ensure reader is closed when the client disconnects.
go func() { <-ctx.Done(); rc.Close() }()
return rc, nil
}
|
go
|
func (api *API) GetTranslateData(ctx context.Context, offset int64) (io.ReadCloser, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "API.GetTranslateData")
defer span.Finish()
rc, err := api.holder.translateFile.Reader(ctx, offset)
if err != nil {
return nil, errors.Wrap(err, "read from translate store")
}
// Ensure reader is closed when the client disconnects.
go func() { <-ctx.Done(); rc.Close() }()
return rc, nil
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"GetTranslateData",
"(",
"ctx",
"context",
".",
"Context",
",",
"offset",
"int64",
")",
"(",
"io",
".",
"ReadCloser",
",",
"error",
")",
"{",
"span",
",",
"ctx",
":=",
"tracing",
".",
"StartSpanFromContext",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n\n",
"rc",
",",
"err",
":=",
"api",
".",
"holder",
".",
"translateFile",
".",
"Reader",
"(",
"ctx",
",",
"offset",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Ensure reader is closed when the client disconnects.",
"go",
"func",
"(",
")",
"{",
"<-",
"ctx",
".",
"Done",
"(",
")",
";",
"rc",
".",
"Close",
"(",
")",
"}",
"(",
")",
"\n\n",
"return",
"rc",
",",
"nil",
"\n",
"}"
] |
// GetTranslateData provides a reader for key translation logs starting at offset.
|
[
"GetTranslateData",
"provides",
"a",
"reader",
"for",
"key",
"translation",
"logs",
"starting",
"at",
"offset",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/api.go#L1184-L1197
|
train
|
pilosa/pilosa
|
api.go
|
Info
|
func (api *API) Info() serverInfo {
si := api.server.systemInfo
// we don't report errors on failures to get this information
physicalCores, logicalCores, _ := si.CPUCores()
mhz, _ := si.CPUMHz()
mem, _ := si.MemTotal()
return serverInfo{
ShardWidth: ShardWidth,
CPUPhysicalCores: physicalCores,
CPULogicalCores: logicalCores,
CPUMHz: mhz,
CPUType: si.CPUModel(),
Memory: mem,
}
}
|
go
|
func (api *API) Info() serverInfo {
si := api.server.systemInfo
// we don't report errors on failures to get this information
physicalCores, logicalCores, _ := si.CPUCores()
mhz, _ := si.CPUMHz()
mem, _ := si.MemTotal()
return serverInfo{
ShardWidth: ShardWidth,
CPUPhysicalCores: physicalCores,
CPULogicalCores: logicalCores,
CPUMHz: mhz,
CPUType: si.CPUModel(),
Memory: mem,
}
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"Info",
"(",
")",
"serverInfo",
"{",
"si",
":=",
"api",
".",
"server",
".",
"systemInfo",
"\n",
"// we don't report errors on failures to get this information",
"physicalCores",
",",
"logicalCores",
",",
"_",
":=",
"si",
".",
"CPUCores",
"(",
")",
"\n",
"mhz",
",",
"_",
":=",
"si",
".",
"CPUMHz",
"(",
")",
"\n",
"mem",
",",
"_",
":=",
"si",
".",
"MemTotal",
"(",
")",
"\n",
"return",
"serverInfo",
"{",
"ShardWidth",
":",
"ShardWidth",
",",
"CPUPhysicalCores",
":",
"physicalCores",
",",
"CPULogicalCores",
":",
"logicalCores",
",",
"CPUMHz",
":",
"mhz",
",",
"CPUType",
":",
"si",
".",
"CPUModel",
"(",
")",
",",
"Memory",
":",
"mem",
",",
"}",
"\n",
"}"
] |
// Info returns information about this server instance.
|
[
"Info",
"returns",
"information",
"about",
"this",
"server",
"instance",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/api.go#L1212-L1226
|
train
|
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.