repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
sequence | docstring
stringlengths 6
2.61k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 85
252
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
flynn/flynn | pkg/syslog/rfc6587/rfc6587.go | Bytes | func Bytes(m *rfc5424.Message) []byte {
msg := m.Bytes()
return bytes.Join([][]byte{[]byte(strconv.Itoa(len(msg))), msg}, []byte{' '})
} | go | func Bytes(m *rfc5424.Message) []byte {
msg := m.Bytes()
return bytes.Join([][]byte{[]byte(strconv.Itoa(len(msg))), msg}, []byte{' '})
} | [
"func",
"Bytes",
"(",
"m",
"*",
"rfc5424",
".",
"Message",
")",
"[",
"]",
"byte",
"{",
"msg",
":=",
"m",
".",
"Bytes",
"(",
")",
"\n",
"return",
"bytes",
".",
"Join",
"(",
"[",
"]",
"[",
"]",
"byte",
"{",
"[",
"]",
"byte",
"(",
"strconv",
".",
"Itoa",
"(",
"len",
"(",
"msg",
")",
")",
")",
",",
"msg",
"}",
",",
"[",
"]",
"byte",
"{",
"' '",
"}",
")",
"\n",
"}"
] | // Bytes returns the RFC6587-framed bytes of an RFC5424 syslog Message,
// including length prefix. | [
"Bytes",
"returns",
"the",
"RFC6587",
"-",
"framed",
"bytes",
"of",
"an",
"RFC5424",
"syslog",
"Message",
"including",
"length",
"prefix",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/syslog/rfc6587/rfc6587.go#L14-L17 | train |
flynn/flynn | pkg/syslog/rfc6587/rfc6587.go | Split | func Split(data []byte, atEOF bool) (advance int, token []byte, err error) {
return split(false, data, atEOF)
} | go | func Split(data []byte, atEOF bool) (advance int, token []byte, err error) {
return split(false, data, atEOF)
} | [
"func",
"Split",
"(",
"data",
"[",
"]",
"byte",
",",
"atEOF",
"bool",
")",
"(",
"advance",
"int",
",",
"token",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"return",
"split",
"(",
"false",
",",
"data",
",",
"atEOF",
")",
"\n",
"}"
] | // Split is a bufio.SplitFunc that splits on RFC6587-framed syslog messages. | [
"Split",
"is",
"a",
"bufio",
".",
"SplitFunc",
"that",
"splits",
"on",
"RFC6587",
"-",
"framed",
"syslog",
"messages",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/syslog/rfc6587/rfc6587.go#L24-L26 | train |
flynn/flynn | pkg/syslog/rfc6587/rfc6587.go | SplitWithNewlines | func SplitWithNewlines(data []byte, atEOF bool) (advance int, token []byte, err error) {
return split(true, data, atEOF)
} | go | func SplitWithNewlines(data []byte, atEOF bool) (advance int, token []byte, err error) {
return split(true, data, atEOF)
} | [
"func",
"SplitWithNewlines",
"(",
"data",
"[",
"]",
"byte",
",",
"atEOF",
"bool",
")",
"(",
"advance",
"int",
",",
"token",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"return",
"split",
"(",
"true",
",",
"data",
",",
"atEOF",
")",
"\n",
"}"
] | // SplitWithNewlines is a bufio.SplitFunc that splits on RFC6587-framed syslog
// messages that are each followed by a newline. | [
"SplitWithNewlines",
"is",
"a",
"bufio",
".",
"SplitFunc",
"that",
"splits",
"on",
"RFC6587",
"-",
"framed",
"syslog",
"messages",
"that",
"are",
"each",
"followed",
"by",
"a",
"newline",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/syslog/rfc6587/rfc6587.go#L30-L32 | train |
flynn/flynn | pkg/connutil/close_notify.go | CloseNotifyConn | func CloseNotifyConn(conn net.Conn) net.Conn {
pr, pw := io.Pipe()
c := &closeNotifyConn{
Conn: conn,
r: pr,
cnc: make(chan bool),
}
go func() {
_, err := io.Copy(pw, conn)
if err == nil {
err = io.EOF
}
pw.CloseWithError(err)
close(c.cnc)
}()
return c
} | go | func CloseNotifyConn(conn net.Conn) net.Conn {
pr, pw := io.Pipe()
c := &closeNotifyConn{
Conn: conn,
r: pr,
cnc: make(chan bool),
}
go func() {
_, err := io.Copy(pw, conn)
if err == nil {
err = io.EOF
}
pw.CloseWithError(err)
close(c.cnc)
}()
return c
} | [
"func",
"CloseNotifyConn",
"(",
"conn",
"net",
".",
"Conn",
")",
"net",
".",
"Conn",
"{",
"pr",
",",
"pw",
":=",
"io",
".",
"Pipe",
"(",
")",
"\n\n",
"c",
":=",
"&",
"closeNotifyConn",
"{",
"Conn",
":",
"conn",
",",
"r",
":",
"pr",
",",
"cnc",
":",
"make",
"(",
"chan",
"bool",
")",
",",
"}",
"\n\n",
"go",
"func",
"(",
")",
"{",
"_",
",",
"err",
":=",
"io",
".",
"Copy",
"(",
"pw",
",",
"conn",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"err",
"=",
"io",
".",
"EOF",
"\n",
"}",
"\n",
"pw",
".",
"CloseWithError",
"(",
"err",
")",
"\n",
"close",
"(",
"c",
".",
"cnc",
")",
"\n",
"}",
"(",
")",
"\n\n",
"return",
"c",
"\n",
"}"
] | // CloseNotifyConn returns a net.Conn that implements http.CloseNotifier.
// Used to detect connections closed early on the client side. | [
"CloseNotifyConn",
"returns",
"a",
"net",
".",
"Conn",
"that",
"implements",
"http",
".",
"CloseNotifier",
".",
"Used",
"to",
"detect",
"connections",
"closed",
"early",
"on",
"the",
"client",
"side",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/connutil/close_notify.go#L21-L40 | train |
flynn/flynn | pkg/sse/sse.go | Decode | func (dec *Decoder) Decode(v interface{}) error {
data, err := dec.Reader.Read()
if err != nil {
return err
}
return json.Unmarshal(data, v)
} | go | func (dec *Decoder) Decode(v interface{}) error {
data, err := dec.Reader.Read()
if err != nil {
return err
}
return json.Unmarshal(data, v)
} | [
"func",
"(",
"dec",
"*",
"Decoder",
")",
"Decode",
"(",
"v",
"interface",
"{",
"}",
")",
"error",
"{",
"data",
",",
"err",
":=",
"dec",
".",
"Reader",
".",
"Read",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"json",
".",
"Unmarshal",
"(",
"data",
",",
"v",
")",
"\n",
"}"
] | // Decode finds the next "data" field and decodes it into v | [
"Decode",
"finds",
"the",
"next",
"data",
"field",
"and",
"decodes",
"it",
"into",
"v"
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/sse/sse.go#L103-L109 | train |
flynn/flynn | flannel/discoverd/registry.go | WatchSubnets | func (r *registry) WatchSubnets(since uint64, stop chan bool) (*subnet.Response, error) {
for {
select {
case event, ok := <-r.events:
if !ok {
return nil, errors.New("unexpected close of discoverd event stream")
}
if event.Kind != discoverd.EventKindServiceMeta {
continue
}
net := &Network{}
if err := json.Unmarshal(event.ServiceMeta.Data, net); err != nil {
return nil, err
}
subnets := make(map[string][]byte)
for subnet, data := range net.Subnets {
if known, ok := knownSubnets[subnet]; ok && reflect.DeepEqual(known, data) {
continue
}
subnets[subnet] = []byte(*data)
}
knownSubnets = net.Subnets
if event.ServiceMeta.Index >= since {
return &subnet.Response{Subnets: subnets, Index: event.ServiceMeta.Index}, nil
}
case <-stop:
return nil, nil
}
}
} | go | func (r *registry) WatchSubnets(since uint64, stop chan bool) (*subnet.Response, error) {
for {
select {
case event, ok := <-r.events:
if !ok {
return nil, errors.New("unexpected close of discoverd event stream")
}
if event.Kind != discoverd.EventKindServiceMeta {
continue
}
net := &Network{}
if err := json.Unmarshal(event.ServiceMeta.Data, net); err != nil {
return nil, err
}
subnets := make(map[string][]byte)
for subnet, data := range net.Subnets {
if known, ok := knownSubnets[subnet]; ok && reflect.DeepEqual(known, data) {
continue
}
subnets[subnet] = []byte(*data)
}
knownSubnets = net.Subnets
if event.ServiceMeta.Index >= since {
return &subnet.Response{Subnets: subnets, Index: event.ServiceMeta.Index}, nil
}
case <-stop:
return nil, nil
}
}
} | [
"func",
"(",
"r",
"*",
"registry",
")",
"WatchSubnets",
"(",
"since",
"uint64",
",",
"stop",
"chan",
"bool",
")",
"(",
"*",
"subnet",
".",
"Response",
",",
"error",
")",
"{",
"for",
"{",
"select",
"{",
"case",
"event",
",",
"ok",
":=",
"<-",
"r",
".",
"events",
":",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"event",
".",
"Kind",
"!=",
"discoverd",
".",
"EventKindServiceMeta",
"{",
"continue",
"\n",
"}",
"\n",
"net",
":=",
"&",
"Network",
"{",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"event",
".",
"ServiceMeta",
".",
"Data",
",",
"net",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"subnets",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"byte",
")",
"\n",
"for",
"subnet",
",",
"data",
":=",
"range",
"net",
".",
"Subnets",
"{",
"if",
"known",
",",
"ok",
":=",
"knownSubnets",
"[",
"subnet",
"]",
";",
"ok",
"&&",
"reflect",
".",
"DeepEqual",
"(",
"known",
",",
"data",
")",
"{",
"continue",
"\n",
"}",
"\n",
"subnets",
"[",
"subnet",
"]",
"=",
"[",
"]",
"byte",
"(",
"*",
"data",
")",
"\n",
"}",
"\n",
"knownSubnets",
"=",
"net",
".",
"Subnets",
"\n",
"if",
"event",
".",
"ServiceMeta",
".",
"Index",
">=",
"since",
"{",
"return",
"&",
"subnet",
".",
"Response",
"{",
"Subnets",
":",
"subnets",
",",
"Index",
":",
"event",
".",
"ServiceMeta",
".",
"Index",
"}",
",",
"nil",
"\n",
"}",
"\n",
"case",
"<-",
"stop",
":",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // WatchSubnets waits for a service metadata event with an index greater than
// a given value, and then returns a response. | [
"WatchSubnets",
"waits",
"for",
"a",
"service",
"metadata",
"event",
"with",
"an",
"index",
"greater",
"than",
"a",
"given",
"value",
"and",
"then",
"returns",
"a",
"response",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/flannel/discoverd/registry.go#L99-L128 | train |
flynn/flynn | builder/build.go | newLogger | func newLogger(tty bool, file string, verbose bool) log15.Logger {
stdoutFormat := log15.LogfmtFormat()
if tty {
stdoutFormat = log15.TerminalFormat()
}
stdoutHandler := log15.StreamHandler(os.Stdout, stdoutFormat)
if !verbose {
stdoutHandler = log15.LvlFilterHandler(log15.LvlInfo, stdoutHandler)
}
log := log15.New()
log.SetHandler(log15.MultiHandler(
log15.Must.FileHandler(file, log15.LogfmtFormat()),
stdoutHandler,
))
return log
} | go | func newLogger(tty bool, file string, verbose bool) log15.Logger {
stdoutFormat := log15.LogfmtFormat()
if tty {
stdoutFormat = log15.TerminalFormat()
}
stdoutHandler := log15.StreamHandler(os.Stdout, stdoutFormat)
if !verbose {
stdoutHandler = log15.LvlFilterHandler(log15.LvlInfo, stdoutHandler)
}
log := log15.New()
log.SetHandler(log15.MultiHandler(
log15.Must.FileHandler(file, log15.LogfmtFormat()),
stdoutHandler,
))
return log
} | [
"func",
"newLogger",
"(",
"tty",
"bool",
",",
"file",
"string",
",",
"verbose",
"bool",
")",
"log15",
".",
"Logger",
"{",
"stdoutFormat",
":=",
"log15",
".",
"LogfmtFormat",
"(",
")",
"\n",
"if",
"tty",
"{",
"stdoutFormat",
"=",
"log15",
".",
"TerminalFormat",
"(",
")",
"\n",
"}",
"\n",
"stdoutHandler",
":=",
"log15",
".",
"StreamHandler",
"(",
"os",
".",
"Stdout",
",",
"stdoutFormat",
")",
"\n",
"if",
"!",
"verbose",
"{",
"stdoutHandler",
"=",
"log15",
".",
"LvlFilterHandler",
"(",
"log15",
".",
"LvlInfo",
",",
"stdoutHandler",
")",
"\n",
"}",
"\n",
"log",
":=",
"log15",
".",
"New",
"(",
")",
"\n",
"log",
".",
"SetHandler",
"(",
"log15",
".",
"MultiHandler",
"(",
"log15",
".",
"Must",
".",
"FileHandler",
"(",
"file",
",",
"log15",
".",
"LogfmtFormat",
"(",
")",
")",
",",
"stdoutHandler",
",",
")",
")",
"\n",
"return",
"log",
"\n",
"}"
] | // newLogger returns a log15.Logger which writes to stdout and a log file | [
"newLogger",
"returns",
"a",
"log15",
".",
"Logger",
"which",
"writes",
"to",
"stdout",
"and",
"a",
"log",
"file"
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/builder/build.go#L296-L311 | train |
flynn/flynn | builder/build.go | NewProgressBar | func NewProgressBar(count int, tty bool) (*pb.ProgressBar, error) {
bar := pb.New(count)
if !tty {
bar.Output = os.Stderr
return bar, nil
}
// replace os.Stdout / os.Stderr with a pipe and copy output to a
// channel so that the progress bar can be wiped before printing output
type stdOutput struct {
Out io.Writer
Text string
}
output := make(chan *stdOutput)
wrap := func(out io.Writer) (*os.File, error) {
r, w, err := os.Pipe()
if err != nil {
return nil, err
}
go func() {
s := bufio.NewScanner(r)
for s.Scan() {
output <- &stdOutput{out, s.Text()}
}
}()
return w, nil
}
stdout := os.Stdout
var err error
os.Stdout, err = wrap(stdout)
if err != nil {
return nil, err
}
stderr := os.Stderr
os.Stderr, err = wrap(stderr)
if err != nil {
return nil, err
}
progress := make(chan string)
bar.Callback = func(out string) { progress <- out }
go func() {
var barText string
for {
select {
case out := <-output:
// if we have printed the bar, replace it with
// spaces then write the output on the same line
if len(barText) > 0 {
spaces := make([]byte, len(barText))
for i := 0; i < len(barText); i++ {
spaces[i] = ' '
}
fmt.Fprint(stderr, "\r", string(spaces), "\r")
}
fmt.Fprintln(out.Out, out.Text)
// re-print the bar on the next line
if len(barText) > 0 {
fmt.Fprint(stderr, "\r"+barText)
}
case out := <-progress:
// print the bar over the previous bar
barText = out
fmt.Fprint(stderr, "\r"+out)
}
}
}()
return bar, nil
} | go | func NewProgressBar(count int, tty bool) (*pb.ProgressBar, error) {
bar := pb.New(count)
if !tty {
bar.Output = os.Stderr
return bar, nil
}
// replace os.Stdout / os.Stderr with a pipe and copy output to a
// channel so that the progress bar can be wiped before printing output
type stdOutput struct {
Out io.Writer
Text string
}
output := make(chan *stdOutput)
wrap := func(out io.Writer) (*os.File, error) {
r, w, err := os.Pipe()
if err != nil {
return nil, err
}
go func() {
s := bufio.NewScanner(r)
for s.Scan() {
output <- &stdOutput{out, s.Text()}
}
}()
return w, nil
}
stdout := os.Stdout
var err error
os.Stdout, err = wrap(stdout)
if err != nil {
return nil, err
}
stderr := os.Stderr
os.Stderr, err = wrap(stderr)
if err != nil {
return nil, err
}
progress := make(chan string)
bar.Callback = func(out string) { progress <- out }
go func() {
var barText string
for {
select {
case out := <-output:
// if we have printed the bar, replace it with
// spaces then write the output on the same line
if len(barText) > 0 {
spaces := make([]byte, len(barText))
for i := 0; i < len(barText); i++ {
spaces[i] = ' '
}
fmt.Fprint(stderr, "\r", string(spaces), "\r")
}
fmt.Fprintln(out.Out, out.Text)
// re-print the bar on the next line
if len(barText) > 0 {
fmt.Fprint(stderr, "\r"+barText)
}
case out := <-progress:
// print the bar over the previous bar
barText = out
fmt.Fprint(stderr, "\r"+out)
}
}
}()
return bar, nil
} | [
"func",
"NewProgressBar",
"(",
"count",
"int",
",",
"tty",
"bool",
")",
"(",
"*",
"pb",
".",
"ProgressBar",
",",
"error",
")",
"{",
"bar",
":=",
"pb",
".",
"New",
"(",
"count",
")",
"\n\n",
"if",
"!",
"tty",
"{",
"bar",
".",
"Output",
"=",
"os",
".",
"Stderr",
"\n",
"return",
"bar",
",",
"nil",
"\n",
"}",
"\n\n",
"// replace os.Stdout / os.Stderr with a pipe and copy output to a",
"// channel so that the progress bar can be wiped before printing output",
"type",
"stdOutput",
"struct",
"{",
"Out",
"io",
".",
"Writer",
"\n",
"Text",
"string",
"\n",
"}",
"\n",
"output",
":=",
"make",
"(",
"chan",
"*",
"stdOutput",
")",
"\n",
"wrap",
":=",
"func",
"(",
"out",
"io",
".",
"Writer",
")",
"(",
"*",
"os",
".",
"File",
",",
"error",
")",
"{",
"r",
",",
"w",
",",
"err",
":=",
"os",
".",
"Pipe",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"go",
"func",
"(",
")",
"{",
"s",
":=",
"bufio",
".",
"NewScanner",
"(",
"r",
")",
"\n",
"for",
"s",
".",
"Scan",
"(",
")",
"{",
"output",
"<-",
"&",
"stdOutput",
"{",
"out",
",",
"s",
".",
"Text",
"(",
")",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"return",
"w",
",",
"nil",
"\n",
"}",
"\n",
"stdout",
":=",
"os",
".",
"Stdout",
"\n",
"var",
"err",
"error",
"\n",
"os",
".",
"Stdout",
",",
"err",
"=",
"wrap",
"(",
"stdout",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"stderr",
":=",
"os",
".",
"Stderr",
"\n",
"os",
".",
"Stderr",
",",
"err",
"=",
"wrap",
"(",
"stderr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"progress",
":=",
"make",
"(",
"chan",
"string",
")",
"\n",
"bar",
".",
"Callback",
"=",
"func",
"(",
"out",
"string",
")",
"{",
"progress",
"<-",
"out",
"}",
"\n",
"go",
"func",
"(",
")",
"{",
"var",
"barText",
"string",
"\n",
"for",
"{",
"select",
"{",
"case",
"out",
":=",
"<-",
"output",
":",
"// if we have printed the bar, replace it with",
"// spaces then write the output on the same line",
"if",
"len",
"(",
"barText",
")",
">",
"0",
"{",
"spaces",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"barText",
")",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"barText",
")",
";",
"i",
"++",
"{",
"spaces",
"[",
"i",
"]",
"=",
"' '",
"\n",
"}",
"\n",
"fmt",
".",
"Fprint",
"(",
"stderr",
",",
"\"",
"\\r",
"\"",
",",
"string",
"(",
"spaces",
")",
",",
"\"",
"\\r",
"\"",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Fprintln",
"(",
"out",
".",
"Out",
",",
"out",
".",
"Text",
")",
"\n\n",
"// re-print the bar on the next line",
"if",
"len",
"(",
"barText",
")",
">",
"0",
"{",
"fmt",
".",
"Fprint",
"(",
"stderr",
",",
"\"",
"\\r",
"\"",
"+",
"barText",
")",
"\n",
"}",
"\n",
"case",
"out",
":=",
"<-",
"progress",
":",
"// print the bar over the previous bar",
"barText",
"=",
"out",
"\n",
"fmt",
".",
"Fprint",
"(",
"stderr",
",",
"\"",
"\\r",
"\"",
"+",
"out",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"return",
"bar",
",",
"nil",
"\n",
"}"
] | // NewProgressBar creates a progress bar which is pinned to the bottom of the
// terminal screen | [
"NewProgressBar",
"creates",
"a",
"progress",
"bar",
"which",
"is",
"pinned",
"to",
"the",
"bottom",
"of",
"the",
"terminal",
"screen"
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/builder/build.go#L1021-L1092 | train |
flynn/flynn | pkg/tufutil/tufutil.go | GetVersion | func GetVersion(client *tuf.Client, name string) (string, error) {
targets, err := client.Targets()
if err != nil {
return "", err
}
target, ok := targets[name]
if !ok {
return "", fmt.Errorf("missing %q in tuf targets", name)
}
if target.Custom == nil || len(*target.Custom) == 0 {
return "", errors.New("missing custom metadata in tuf target")
}
var data struct {
Version string
}
json.Unmarshal(*target.Custom, &data)
if data.Version == "" {
return "", errors.New("missing version in tuf target")
}
return data.Version, nil
} | go | func GetVersion(client *tuf.Client, name string) (string, error) {
targets, err := client.Targets()
if err != nil {
return "", err
}
target, ok := targets[name]
if !ok {
return "", fmt.Errorf("missing %q in tuf targets", name)
}
if target.Custom == nil || len(*target.Custom) == 0 {
return "", errors.New("missing custom metadata in tuf target")
}
var data struct {
Version string
}
json.Unmarshal(*target.Custom, &data)
if data.Version == "" {
return "", errors.New("missing version in tuf target")
}
return data.Version, nil
} | [
"func",
"GetVersion",
"(",
"client",
"*",
"tuf",
".",
"Client",
",",
"name",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"targets",
",",
"err",
":=",
"client",
".",
"Targets",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"target",
",",
"ok",
":=",
"targets",
"[",
"name",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n",
"if",
"target",
".",
"Custom",
"==",
"nil",
"||",
"len",
"(",
"*",
"target",
".",
"Custom",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"var",
"data",
"struct",
"{",
"Version",
"string",
"\n",
"}",
"\n",
"json",
".",
"Unmarshal",
"(",
"*",
"target",
".",
"Custom",
",",
"&",
"data",
")",
"\n",
"if",
"data",
".",
"Version",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"data",
".",
"Version",
",",
"nil",
"\n",
"}"
] | // GetVersion returns the given target's version from custom metadata | [
"GetVersion",
"returns",
"the",
"given",
"target",
"s",
"version",
"from",
"custom",
"metadata"
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/tufutil/tufutil.go#L69-L89 | train |
flynn/flynn | pkg/httphelper/httphelper.go | IsRetryableError | func IsRetryableError(err error) bool {
e, ok := err.(JSONError)
return ok && e.Retry
} | go | func IsRetryableError(err error) bool {
e, ok := err.(JSONError)
return ok && e.Retry
} | [
"func",
"IsRetryableError",
"(",
"err",
"error",
")",
"bool",
"{",
"e",
",",
"ok",
":=",
"err",
".",
"(",
"JSONError",
")",
"\n",
"return",
"ok",
"&&",
"e",
".",
"Retry",
"\n",
"}"
] | // IsRetryableError indicates whether a HTTP request can be safely retried. | [
"IsRetryableError",
"indicates",
"whether",
"a",
"HTTP",
"request",
"can",
"be",
"safely",
"retried",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/httphelper/httphelper.go#L89-L92 | train |
flynn/flynn | pkg/sirenia/state/state.go | evalLater | func (p *Peer) evalLater(delay time.Duration) {
if p.retryCh != nil {
p.retryCh <- struct{}{}
return
}
time.AfterFunc(delay, p.triggerEval)
} | go | func (p *Peer) evalLater(delay time.Duration) {
if p.retryCh != nil {
p.retryCh <- struct{}{}
return
}
time.AfterFunc(delay, p.triggerEval)
} | [
"func",
"(",
"p",
"*",
"Peer",
")",
"evalLater",
"(",
"delay",
"time",
".",
"Duration",
")",
"{",
"if",
"p",
".",
"retryCh",
"!=",
"nil",
"{",
"p",
".",
"retryCh",
"<-",
"struct",
"{",
"}",
"{",
"}",
"\n",
"return",
"\n",
"}",
"\n",
"time",
".",
"AfterFunc",
"(",
"delay",
",",
"p",
".",
"triggerEval",
")",
"\n",
"}"
] | // evalLater triggers a cluster state evaluation after delay has elapsed | [
"evalLater",
"triggers",
"a",
"cluster",
"state",
"evaluation",
"after",
"delay",
"has",
"elapsed"
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/sirenia/state/state.go#L440-L446 | train |
flynn/flynn | pkg/sirenia/state/state.go | startTransitionToNormalMode | func (p *Peer) startTransitionToNormalMode() {
log := p.log.New("fn", "startTransitionToNormalMode")
if p.Info().State.Primary.Meta[p.idKey] != p.id || p.Info().Role != RolePrimary {
panic("startTransitionToNormalMode called when not primary")
}
// In the normal takeover case, we'd pick an async. In this case, we take
// any other peer because we know none of them has anything replicated.
var newSync *discoverd.Instance
for _, peer := range p.Info().Peers {
if peer.Meta[p.idKey] != p.id {
newSync = peer
}
}
if newSync == nil {
log.Warn("would takeover but no peers present")
return
}
newAsync := make([]*discoverd.Instance, 0, len(p.Info().Peers))
for _, a := range p.Info().Peers {
if a.Meta[p.idKey] != p.id && a.Meta[p.idKey] != newSync.Meta[p.idKey] {
newAsync = append(newAsync, a)
}
}
log.Debug("transitioning to normal mode")
p.startTakeoverWithPeer("transitioning to normal mode", p.db.XLog().Zero(), &State{
Sync: newSync,
Async: newAsync,
})
} | go | func (p *Peer) startTransitionToNormalMode() {
log := p.log.New("fn", "startTransitionToNormalMode")
if p.Info().State.Primary.Meta[p.idKey] != p.id || p.Info().Role != RolePrimary {
panic("startTransitionToNormalMode called when not primary")
}
// In the normal takeover case, we'd pick an async. In this case, we take
// any other peer because we know none of them has anything replicated.
var newSync *discoverd.Instance
for _, peer := range p.Info().Peers {
if peer.Meta[p.idKey] != p.id {
newSync = peer
}
}
if newSync == nil {
log.Warn("would takeover but no peers present")
return
}
newAsync := make([]*discoverd.Instance, 0, len(p.Info().Peers))
for _, a := range p.Info().Peers {
if a.Meta[p.idKey] != p.id && a.Meta[p.idKey] != newSync.Meta[p.idKey] {
newAsync = append(newAsync, a)
}
}
log.Debug("transitioning to normal mode")
p.startTakeoverWithPeer("transitioning to normal mode", p.db.XLog().Zero(), &State{
Sync: newSync,
Async: newAsync,
})
} | [
"func",
"(",
"p",
"*",
"Peer",
")",
"startTransitionToNormalMode",
"(",
")",
"{",
"log",
":=",
"p",
".",
"log",
".",
"New",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"p",
".",
"Info",
"(",
")",
".",
"State",
".",
"Primary",
".",
"Meta",
"[",
"p",
".",
"idKey",
"]",
"!=",
"p",
".",
"id",
"||",
"p",
".",
"Info",
"(",
")",
".",
"Role",
"!=",
"RolePrimary",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// In the normal takeover case, we'd pick an async. In this case, we take",
"// any other peer because we know none of them has anything replicated.",
"var",
"newSync",
"*",
"discoverd",
".",
"Instance",
"\n",
"for",
"_",
",",
"peer",
":=",
"range",
"p",
".",
"Info",
"(",
")",
".",
"Peers",
"{",
"if",
"peer",
".",
"Meta",
"[",
"p",
".",
"idKey",
"]",
"!=",
"p",
".",
"id",
"{",
"newSync",
"=",
"peer",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"newSync",
"==",
"nil",
"{",
"log",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"newAsync",
":=",
"make",
"(",
"[",
"]",
"*",
"discoverd",
".",
"Instance",
",",
"0",
",",
"len",
"(",
"p",
".",
"Info",
"(",
")",
".",
"Peers",
")",
")",
"\n",
"for",
"_",
",",
"a",
":=",
"range",
"p",
".",
"Info",
"(",
")",
".",
"Peers",
"{",
"if",
"a",
".",
"Meta",
"[",
"p",
".",
"idKey",
"]",
"!=",
"p",
".",
"id",
"&&",
"a",
".",
"Meta",
"[",
"p",
".",
"idKey",
"]",
"!=",
"newSync",
".",
"Meta",
"[",
"p",
".",
"idKey",
"]",
"{",
"newAsync",
"=",
"append",
"(",
"newAsync",
",",
"a",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"p",
".",
"startTakeoverWithPeer",
"(",
"\"",
"\"",
",",
"p",
".",
"db",
".",
"XLog",
"(",
")",
".",
"Zero",
"(",
")",
",",
"&",
"State",
"{",
"Sync",
":",
"newSync",
",",
"Async",
":",
"newAsync",
",",
"}",
")",
"\n",
"}"
] | // As the primary, converts the current cluster to normal mode from singleton
// mode. | [
"As",
"the",
"primary",
"converts",
"the",
"current",
"cluster",
"to",
"normal",
"mode",
"from",
"singleton",
"mode",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/sirenia/state/state.go#L946-L976 | train |
flynn/flynn | pkg/sirenia/state/state.go | applyConfig | func (p *Peer) applyConfig() (err error) {
p.moving()
log := p.log.New("fn", "applyConfig")
if p.online == nil {
panic("applyConfig with database in unknown state")
}
config := p.Config()
if p.applied != nil && p.applied.Equal(config) && p.applied.State.Equal(config.State) {
log.Info("skipping config apply, no changes")
return nil
}
defer func() {
if err == nil {
return
}
// This is a very unexpected error, and it's very unclear how to deal
// with it. If we're the primary or sync, we might be tempted to
// abdicate our position. But without understanding the failure mode,
// there's no reason to believe any other peer is in a better position
// to deal with this, and we don't want to flap unnecessarily. So just
// log an error and try again shortly.
log.Error("error applying database config", "err", err)
t := TimeNow()
p.setRetryPending(&t)
p.applyConfigLater(1 * time.Second)
}()
log.Info("reconfiguring database")
if err := p.db.Reconfigure(config); err != nil {
return err
}
if config.Role != RoleNone {
if *p.online {
log.Debug("skipping start, already online")
} else {
log.Debug("starting database")
if err := p.db.Start(); err != nil {
return err
}
}
} else {
if *p.online {
log.Debug("stopping database")
if err := p.db.Stop(); err != nil {
return err
}
} else {
log.Debug("skipping stop, already offline")
}
}
log.Info("applied database config")
p.setRetryPending(nil)
p.applied = config
online := config.Role != RoleNone
p.online = &online
// Try applying the configuration again in case anything's
// changed. If not, this will be a no-op.
p.triggerApplyConfig()
return nil
} | go | func (p *Peer) applyConfig() (err error) {
p.moving()
log := p.log.New("fn", "applyConfig")
if p.online == nil {
panic("applyConfig with database in unknown state")
}
config := p.Config()
if p.applied != nil && p.applied.Equal(config) && p.applied.State.Equal(config.State) {
log.Info("skipping config apply, no changes")
return nil
}
defer func() {
if err == nil {
return
}
// This is a very unexpected error, and it's very unclear how to deal
// with it. If we're the primary or sync, we might be tempted to
// abdicate our position. But without understanding the failure mode,
// there's no reason to believe any other peer is in a better position
// to deal with this, and we don't want to flap unnecessarily. So just
// log an error and try again shortly.
log.Error("error applying database config", "err", err)
t := TimeNow()
p.setRetryPending(&t)
p.applyConfigLater(1 * time.Second)
}()
log.Info("reconfiguring database")
if err := p.db.Reconfigure(config); err != nil {
return err
}
if config.Role != RoleNone {
if *p.online {
log.Debug("skipping start, already online")
} else {
log.Debug("starting database")
if err := p.db.Start(); err != nil {
return err
}
}
} else {
if *p.online {
log.Debug("stopping database")
if err := p.db.Stop(); err != nil {
return err
}
} else {
log.Debug("skipping stop, already offline")
}
}
log.Info("applied database config")
p.setRetryPending(nil)
p.applied = config
online := config.Role != RoleNone
p.online = &online
// Try applying the configuration again in case anything's
// changed. If not, this will be a no-op.
p.triggerApplyConfig()
return nil
} | [
"func",
"(",
"p",
"*",
"Peer",
")",
"applyConfig",
"(",
")",
"(",
"err",
"error",
")",
"{",
"p",
".",
"moving",
"(",
")",
"\n",
"log",
":=",
"p",
".",
"log",
".",
"New",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"if",
"p",
".",
"online",
"==",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"config",
":=",
"p",
".",
"Config",
"(",
")",
"\n",
"if",
"p",
".",
"applied",
"!=",
"nil",
"&&",
"p",
".",
"applied",
".",
"Equal",
"(",
"config",
")",
"&&",
"p",
".",
"applied",
".",
"State",
".",
"Equal",
"(",
"config",
".",
"State",
")",
"{",
"log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"defer",
"func",
"(",
")",
"{",
"if",
"err",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"// This is a very unexpected error, and it's very unclear how to deal",
"// with it. If we're the primary or sync, we might be tempted to",
"// abdicate our position. But without understanding the failure mode,",
"// there's no reason to believe any other peer is in a better position",
"// to deal with this, and we don't want to flap unnecessarily. So just",
"// log an error and try again shortly.",
"log",
".",
"Error",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"t",
":=",
"TimeNow",
"(",
")",
"\n",
"p",
".",
"setRetryPending",
"(",
"&",
"t",
")",
"\n",
"p",
".",
"applyConfigLater",
"(",
"1",
"*",
"time",
".",
"Second",
")",
"\n",
"}",
"(",
")",
"\n\n",
"log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
":=",
"p",
".",
"db",
".",
"Reconfigure",
"(",
"config",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"config",
".",
"Role",
"!=",
"RoleNone",
"{",
"if",
"*",
"p",
".",
"online",
"{",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
":=",
"p",
".",
"db",
".",
"Start",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"else",
"{",
"if",
"*",
"p",
".",
"online",
"{",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
":=",
"p",
".",
"db",
".",
"Stop",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"else",
"{",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"p",
".",
"setRetryPending",
"(",
"nil",
")",
"\n",
"p",
".",
"applied",
"=",
"config",
"\n",
"online",
":=",
"config",
".",
"Role",
"!=",
"RoleNone",
"\n",
"p",
".",
"online",
"=",
"&",
"online",
"\n\n",
"// Try applying the configuration again in case anything's",
"// changed. If not, this will be a no-op.",
"p",
".",
"triggerApplyConfig",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Reconfigure database based on the current configuration. During
// reconfiguration, new requests to reconfigure will be ignored, and incoming
// cluster state changes will be recorded but otherwise ignored. When
// reconfiguration completes, if the desired configuration has changed, we'll
// take another lap to apply the updated configuration. | [
"Reconfigure",
"database",
"based",
"on",
"the",
"current",
"configuration",
".",
"During",
"reconfiguration",
"new",
"requests",
"to",
"reconfigure",
"will",
"be",
"ignored",
"and",
"incoming",
"cluster",
"state",
"changes",
"will",
"be",
"recorded",
"but",
"otherwise",
"ignored",
".",
"When",
"reconfiguration",
"completes",
"if",
"the",
"desired",
"configuration",
"has",
"changed",
"we",
"ll",
"take",
"another",
"lap",
"to",
"apply",
"the",
"updated",
"configuration",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/sirenia/state/state.go#L1009-L1075 | train |
flynn/flynn | pkg/sirenia/state/state.go | whichAsync | func (p *Peer) whichAsync() int {
for i, a := range p.Info().State.Async {
if p.id == a.Meta[p.idKey] {
return i
}
}
return -1
} | go | func (p *Peer) whichAsync() int {
for i, a := range p.Info().State.Async {
if p.id == a.Meta[p.idKey] {
return i
}
}
return -1
} | [
"func",
"(",
"p",
"*",
"Peer",
")",
"whichAsync",
"(",
")",
"int",
"{",
"for",
"i",
",",
"a",
":=",
"range",
"p",
".",
"Info",
"(",
")",
".",
"State",
".",
"Async",
"{",
"if",
"p",
".",
"id",
"==",
"a",
".",
"Meta",
"[",
"p",
".",
"idKey",
"]",
"{",
"return",
"i",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"-",
"1",
"\n",
"}"
] | // Determine our index in the async peer list. -1 means not present. | [
"Determine",
"our",
"index",
"in",
"the",
"async",
"peer",
"list",
".",
"-",
"1",
"means",
"not",
"present",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/sirenia/state/state.go#L1090-L1097 | train |
flynn/flynn | pkg/sirenia/state/state.go | lookupUpstream | func (p *Peer) lookupUpstream(whichAsync int) *discoverd.Instance {
if whichAsync == 0 {
return p.Info().State.Sync
}
return p.Info().State.Async[whichAsync-1]
} | go | func (p *Peer) lookupUpstream(whichAsync int) *discoverd.Instance {
if whichAsync == 0 {
return p.Info().State.Sync
}
return p.Info().State.Async[whichAsync-1]
} | [
"func",
"(",
"p",
"*",
"Peer",
")",
"lookupUpstream",
"(",
"whichAsync",
"int",
")",
"*",
"discoverd",
".",
"Instance",
"{",
"if",
"whichAsync",
"==",
"0",
"{",
"return",
"p",
".",
"Info",
"(",
")",
".",
"State",
".",
"Sync",
"\n",
"}",
"\n",
"return",
"p",
".",
"Info",
"(",
")",
".",
"State",
".",
"Async",
"[",
"whichAsync",
"-",
"1",
"]",
"\n",
"}"
] | // Return the upstream peer for a given one of the async peers | [
"Return",
"the",
"upstream",
"peer",
"for",
"a",
"given",
"one",
"of",
"the",
"async",
"peers"
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/sirenia/state/state.go#L1100-L1105 | train |
flynn/flynn | pkg/sirenia/state/state.go | lookupDownstream | func (p *Peer) lookupDownstream(whichAsync int) *discoverd.Instance {
async := p.Info().State.Async
if whichAsync == len(async)-1 {
return nil
}
return async[whichAsync+1]
} | go | func (p *Peer) lookupDownstream(whichAsync int) *discoverd.Instance {
async := p.Info().State.Async
if whichAsync == len(async)-1 {
return nil
}
return async[whichAsync+1]
} | [
"func",
"(",
"p",
"*",
"Peer",
")",
"lookupDownstream",
"(",
"whichAsync",
"int",
")",
"*",
"discoverd",
".",
"Instance",
"{",
"async",
":=",
"p",
".",
"Info",
"(",
")",
".",
"State",
".",
"Async",
"\n",
"if",
"whichAsync",
"==",
"len",
"(",
"async",
")",
"-",
"1",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"async",
"[",
"whichAsync",
"+",
"1",
"]",
"\n",
"}"
] | // Return the downstream peer for a given one of the async peers | [
"Return",
"the",
"downstream",
"peer",
"for",
"a",
"given",
"one",
"of",
"the",
"async",
"peers"
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/sirenia/state/state.go#L1108-L1114 | train |
flynn/flynn | pkg/sirenia/state/state.go | peerIsPresent | func (p *Peer) peerIsPresent(other *discoverd.Instance) bool {
// We should never even be asking whether we're present. If we need to do
// this at some point in the future, we need to consider we should always
// consider ourselves present or whether we should check the list.
if other.Meta[p.idKey] == p.id {
panic("peerIsPresent with self")
}
for _, peer := range p.Info().Peers {
if peer.Meta[p.idKey] == other.Meta[p.idKey] {
return true
}
}
return false
} | go | func (p *Peer) peerIsPresent(other *discoverd.Instance) bool {
// We should never even be asking whether we're present. If we need to do
// this at some point in the future, we need to consider we should always
// consider ourselves present or whether we should check the list.
if other.Meta[p.idKey] == p.id {
panic("peerIsPresent with self")
}
for _, peer := range p.Info().Peers {
if peer.Meta[p.idKey] == other.Meta[p.idKey] {
return true
}
}
return false
} | [
"func",
"(",
"p",
"*",
"Peer",
")",
"peerIsPresent",
"(",
"other",
"*",
"discoverd",
".",
"Instance",
")",
"bool",
"{",
"// We should never even be asking whether we're present. If we need to do",
"// this at some point in the future, we need to consider we should always",
"// consider ourselves present or whether we should check the list.",
"if",
"other",
".",
"Meta",
"[",
"p",
".",
"idKey",
"]",
"==",
"p",
".",
"id",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"peer",
":=",
"range",
"p",
".",
"Info",
"(",
")",
".",
"Peers",
"{",
"if",
"peer",
".",
"Meta",
"[",
"p",
".",
"idKey",
"]",
"==",
"other",
".",
"Meta",
"[",
"p",
".",
"idKey",
"]",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"false",
"\n",
"}"
] | // Returns true if the given other peer appears to be present in the most
// recently received list of present peers. | [
"Returns",
"true",
"if",
"the",
"given",
"other",
"peer",
"appears",
"to",
"be",
"present",
"in",
"the",
"most",
"recently",
"received",
"list",
"of",
"present",
"peers",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/sirenia/state/state.go#L1118-L1132 | train |
flynn/flynn | router/proxy/reverseproxy.go | NewReverseProxy | func NewReverseProxy(bf BackendListFunc, stickyKey *[32]byte, sticky bool, rt RequestTracker, l log15.Logger) *ReverseProxy {
return &ReverseProxy{
transport: &transport{
getBackends: bf,
stickyCookieKey: stickyKey,
useStickySessions: sticky,
},
FlushInterval: 10 * time.Millisecond,
RequestTracker: rt,
Logger: l,
}
} | go | func NewReverseProxy(bf BackendListFunc, stickyKey *[32]byte, sticky bool, rt RequestTracker, l log15.Logger) *ReverseProxy {
return &ReverseProxy{
transport: &transport{
getBackends: bf,
stickyCookieKey: stickyKey,
useStickySessions: sticky,
},
FlushInterval: 10 * time.Millisecond,
RequestTracker: rt,
Logger: l,
}
} | [
"func",
"NewReverseProxy",
"(",
"bf",
"BackendListFunc",
",",
"stickyKey",
"*",
"[",
"32",
"]",
"byte",
",",
"sticky",
"bool",
",",
"rt",
"RequestTracker",
",",
"l",
"log15",
".",
"Logger",
")",
"*",
"ReverseProxy",
"{",
"return",
"&",
"ReverseProxy",
"{",
"transport",
":",
"&",
"transport",
"{",
"getBackends",
":",
"bf",
",",
"stickyCookieKey",
":",
"stickyKey",
",",
"useStickySessions",
":",
"sticky",
",",
"}",
",",
"FlushInterval",
":",
"10",
"*",
"time",
".",
"Millisecond",
",",
"RequestTracker",
":",
"rt",
",",
"Logger",
":",
"l",
",",
"}",
"\n",
"}"
] | // NewReverseProxy initializes a new ReverseProxy with a callback to get
// backends, a stickyKey for encrypting sticky session cookies, and a flag
// sticky to enable sticky sessions. | [
"NewReverseProxy",
"initializes",
"a",
"new",
"ReverseProxy",
"with",
"a",
"callback",
"to",
"get",
"backends",
"a",
"stickyKey",
"for",
"encrypting",
"sticky",
"session",
"cookies",
"and",
"a",
"flag",
"sticky",
"to",
"enable",
"sticky",
"sessions",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/router/proxy/reverseproxy.go#L71-L82 | train |
flynn/flynn | router/proxy/reverseproxy.go | ServeConn | func (p *ReverseProxy) ServeConn(ctx context.Context, dconn net.Conn) {
transport := p.transport
if transport == nil {
panic("router: nil transport for proxy")
}
defer dconn.Close()
clientGone := dconn.(http.CloseNotifier).CloseNotify()
ctx, cancel := context.WithCancel(ctx)
defer cancel() // finish cancellation goroutine
go func() {
select {
case <-clientGone:
cancel() // client went away, cancel request
case <-ctx.Done():
}
}()
l := p.Logger.New("client_addr", dconn.RemoteAddr(), "host_addr", dconn.LocalAddr(), "proxy", "tcp")
uconn, err := transport.Connect(ctx, l)
if err != nil {
return
}
defer uconn.Close()
joinConns(uconn, dconn)
} | go | func (p *ReverseProxy) ServeConn(ctx context.Context, dconn net.Conn) {
transport := p.transport
if transport == nil {
panic("router: nil transport for proxy")
}
defer dconn.Close()
clientGone := dconn.(http.CloseNotifier).CloseNotify()
ctx, cancel := context.WithCancel(ctx)
defer cancel() // finish cancellation goroutine
go func() {
select {
case <-clientGone:
cancel() // client went away, cancel request
case <-ctx.Done():
}
}()
l := p.Logger.New("client_addr", dconn.RemoteAddr(), "host_addr", dconn.LocalAddr(), "proxy", "tcp")
uconn, err := transport.Connect(ctx, l)
if err != nil {
return
}
defer uconn.Close()
joinConns(uconn, dconn)
} | [
"func",
"(",
"p",
"*",
"ReverseProxy",
")",
"ServeConn",
"(",
"ctx",
"context",
".",
"Context",
",",
"dconn",
"net",
".",
"Conn",
")",
"{",
"transport",
":=",
"p",
".",
"transport",
"\n",
"if",
"transport",
"==",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"defer",
"dconn",
".",
"Close",
"(",
")",
"\n\n",
"clientGone",
":=",
"dconn",
".",
"(",
"http",
".",
"CloseNotifier",
")",
".",
"CloseNotify",
"(",
")",
"\n",
"ctx",
",",
"cancel",
":=",
"context",
".",
"WithCancel",
"(",
"ctx",
")",
"\n",
"defer",
"cancel",
"(",
")",
"// finish cancellation goroutine",
"\n\n",
"go",
"func",
"(",
")",
"{",
"select",
"{",
"case",
"<-",
"clientGone",
":",
"cancel",
"(",
")",
"// client went away, cancel request",
"\n",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"l",
":=",
"p",
".",
"Logger",
".",
"New",
"(",
"\"",
"\"",
",",
"dconn",
".",
"RemoteAddr",
"(",
")",
",",
"\"",
"\"",
",",
"dconn",
".",
"LocalAddr",
"(",
")",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"uconn",
",",
"err",
":=",
"transport",
".",
"Connect",
"(",
"ctx",
",",
"l",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"defer",
"uconn",
".",
"Close",
"(",
")",
"\n\n",
"joinConns",
"(",
"uconn",
",",
"dconn",
")",
"\n",
"}"
] | // ServeConn takes an inbound conn and proxies it to a backend. | [
"ServeConn",
"takes",
"an",
"inbound",
"conn",
"and",
"proxies",
"it",
"to",
"a",
"backend",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/router/proxy/reverseproxy.go#L162-L190 | train |
flynn/flynn | discoverd/deployment/deployment.go | update | func (d *Deployment) update() error {
select {
case event, ok := <-d.events:
if !ok {
return fmt.Errorf("service stream closed unexpectedly: %s", d.stream.Err())
}
if event.Kind == discoverd.EventKindServiceMeta {
d.meta = event.ServiceMeta
}
default:
}
return nil
} | go | func (d *Deployment) update() error {
select {
case event, ok := <-d.events:
if !ok {
return fmt.Errorf("service stream closed unexpectedly: %s", d.stream.Err())
}
if event.Kind == discoverd.EventKindServiceMeta {
d.meta = event.ServiceMeta
}
default:
}
return nil
} | [
"func",
"(",
"d",
"*",
"Deployment",
")",
"update",
"(",
")",
"error",
"{",
"select",
"{",
"case",
"event",
",",
"ok",
":=",
"<-",
"d",
".",
"events",
":",
"if",
"!",
"ok",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"d",
".",
"stream",
".",
"Err",
"(",
")",
")",
"\n",
"}",
"\n",
"if",
"event",
".",
"Kind",
"==",
"discoverd",
".",
"EventKindServiceMeta",
"{",
"d",
".",
"meta",
"=",
"event",
".",
"ServiceMeta",
"\n",
"}",
"\n",
"default",
":",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // update drains any pending events, updating the service metadata, it doesn't block. | [
"update",
"drains",
"any",
"pending",
"events",
"updating",
"the",
"service",
"metadata",
"it",
"doesn",
"t",
"block",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/discoverd/deployment/deployment.go#L71-L83 | train |
flynn/flynn | discoverd/deployment/deployment.go | MarkDone | func (d *Deployment) MarkDone(addr string) error {
return attempts.Run(func() error {
if err := d.update(); err != nil {
return err
}
deploymentMeta, err := d.decode(d.meta)
if err != nil {
return err
}
deploymentMeta.States[addr] = DeploymentStateDone
return d.set(d.meta, deploymentMeta)
})
} | go | func (d *Deployment) MarkDone(addr string) error {
return attempts.Run(func() error {
if err := d.update(); err != nil {
return err
}
deploymentMeta, err := d.decode(d.meta)
if err != nil {
return err
}
deploymentMeta.States[addr] = DeploymentStateDone
return d.set(d.meta, deploymentMeta)
})
} | [
"func",
"(",
"d",
"*",
"Deployment",
")",
"MarkDone",
"(",
"addr",
"string",
")",
"error",
"{",
"return",
"attempts",
".",
"Run",
"(",
"func",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"d",
".",
"update",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"deploymentMeta",
",",
"err",
":=",
"d",
".",
"decode",
"(",
"d",
".",
"meta",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"deploymentMeta",
".",
"States",
"[",
"addr",
"]",
"=",
"DeploymentStateDone",
"\n\n",
"return",
"d",
".",
"set",
"(",
"d",
".",
"meta",
",",
"deploymentMeta",
")",
"\n",
"}",
")",
"\n",
"}"
] | // MarkDone marks the addr as done in the service metadata | [
"MarkDone",
"marks",
"the",
"addr",
"as",
"done",
"in",
"the",
"service",
"metadata"
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/discoverd/deployment/deployment.go#L169-L184 | train |
flynn/flynn | discoverd/deployment/deployment.go | Wait | func (d *Deployment) Wait(id string, timeout time.Duration, log log15.Logger) error {
timeoutCh := time.After(timeout)
for {
actual := 0
select {
case event, ok := <-d.events:
if !ok {
return fmt.Errorf("service stream closed unexpectedly: %s", d.stream.Err())
}
if event.Kind == discoverd.EventKindServiceMeta {
deploymentMeta, err := d.decode(event.ServiceMeta)
if err != nil {
return err
}
log.Info("got service meta event", "state", deploymentMeta)
if deploymentMeta.ID == id {
actual = 0
for _, state := range deploymentMeta.States {
if state == DeploymentStateDone {
actual++
}
}
if actual == d.jobCount {
return nil
}
} else {
log.Warn("ignoring service meta even with wrong ID", "expected", id, "got", deploymentMeta.ID)
}
}
case <-timeoutCh:
return fmt.Errorf("timed out waiting for discoverd deployment (expected=%d actual=%d)", d.jobCount, actual)
}
}
} | go | func (d *Deployment) Wait(id string, timeout time.Duration, log log15.Logger) error {
timeoutCh := time.After(timeout)
for {
actual := 0
select {
case event, ok := <-d.events:
if !ok {
return fmt.Errorf("service stream closed unexpectedly: %s", d.stream.Err())
}
if event.Kind == discoverd.EventKindServiceMeta {
deploymentMeta, err := d.decode(event.ServiceMeta)
if err != nil {
return err
}
log.Info("got service meta event", "state", deploymentMeta)
if deploymentMeta.ID == id {
actual = 0
for _, state := range deploymentMeta.States {
if state == DeploymentStateDone {
actual++
}
}
if actual == d.jobCount {
return nil
}
} else {
log.Warn("ignoring service meta even with wrong ID", "expected", id, "got", deploymentMeta.ID)
}
}
case <-timeoutCh:
return fmt.Errorf("timed out waiting for discoverd deployment (expected=%d actual=%d)", d.jobCount, actual)
}
}
} | [
"func",
"(",
"d",
"*",
"Deployment",
")",
"Wait",
"(",
"id",
"string",
",",
"timeout",
"time",
".",
"Duration",
",",
"log",
"log15",
".",
"Logger",
")",
"error",
"{",
"timeoutCh",
":=",
"time",
".",
"After",
"(",
"timeout",
")",
"\n",
"for",
"{",
"actual",
":=",
"0",
"\n",
"select",
"{",
"case",
"event",
",",
"ok",
":=",
"<-",
"d",
".",
"events",
":",
"if",
"!",
"ok",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"d",
".",
"stream",
".",
"Err",
"(",
")",
")",
"\n",
"}",
"\n",
"if",
"event",
".",
"Kind",
"==",
"discoverd",
".",
"EventKindServiceMeta",
"{",
"deploymentMeta",
",",
"err",
":=",
"d",
".",
"decode",
"(",
"event",
".",
"ServiceMeta",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"log",
".",
"Info",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"deploymentMeta",
")",
"\n",
"if",
"deploymentMeta",
".",
"ID",
"==",
"id",
"{",
"actual",
"=",
"0",
"\n",
"for",
"_",
",",
"state",
":=",
"range",
"deploymentMeta",
".",
"States",
"{",
"if",
"state",
"==",
"DeploymentStateDone",
"{",
"actual",
"++",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"actual",
"==",
"d",
".",
"jobCount",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"else",
"{",
"log",
".",
"Warn",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"id",
",",
"\"",
"\"",
",",
"deploymentMeta",
".",
"ID",
")",
"\n",
"}",
"\n\n",
"}",
"\n",
"case",
"<-",
"timeoutCh",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"d",
".",
"jobCount",
",",
"actual",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Wait waits for an expected number of "done" addresses in the service metadata | [
"Wait",
"waits",
"for",
"an",
"expected",
"number",
"of",
"done",
"addresses",
"in",
"the",
"service",
"metadata"
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/discoverd/deployment/deployment.go#L187-L221 | train |
flynn/flynn | discoverd/deployment/deployment.go | Create | func (d *Deployment) Create(id string) error {
return attempts.Run(func() error {
if err := d.set(&discoverd.ServiceMeta{}, NewDeploymentMeta(id)); err == nil {
return nil
}
if err := d.update(); err != nil {
return err
}
return d.set(d.meta, NewDeploymentMeta(id))
})
} | go | func (d *Deployment) Create(id string) error {
return attempts.Run(func() error {
if err := d.set(&discoverd.ServiceMeta{}, NewDeploymentMeta(id)); err == nil {
return nil
}
if err := d.update(); err != nil {
return err
}
return d.set(d.meta, NewDeploymentMeta(id))
})
} | [
"func",
"(",
"d",
"*",
"Deployment",
")",
"Create",
"(",
"id",
"string",
")",
"error",
"{",
"return",
"attempts",
".",
"Run",
"(",
"func",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"d",
".",
"set",
"(",
"&",
"discoverd",
".",
"ServiceMeta",
"{",
"}",
",",
"NewDeploymentMeta",
"(",
"id",
")",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"err",
":=",
"d",
".",
"update",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"d",
".",
"set",
"(",
"d",
".",
"meta",
",",
"NewDeploymentMeta",
"(",
"id",
")",
")",
"\n",
"}",
")",
"\n",
"}"
] | // Create starts a new deployment with a given ID | [
"Create",
"starts",
"a",
"new",
"deployment",
"with",
"a",
"given",
"ID"
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/discoverd/deployment/deployment.go#L224-L234 | train |
flynn/flynn | pkg/cluster/attach.go | Attach | func (c *Host) Attach(req *host.AttachReq, wait bool) (AttachClient, error) {
rwc, err := c.c.Hijack("POST", "/attach", http.Header{"Upgrade": {"flynn-attach/0"}}, req)
if err != nil {
return nil, err
}
attachState := make([]byte, 1)
if _, err := rwc.Read(attachState); err != nil {
rwc.Close()
return nil, err
}
handleState := func() error {
switch attachState[0] {
case host.AttachSuccess:
return nil
case host.AttachError:
errBytes, err := ioutil.ReadAll(rwc)
rwc.Close()
if err != nil {
return err
}
if len(errBytes) >= 4 {
errBytes = errBytes[4:]
}
errMsg := string(errBytes)
switch errMsg {
case host.ErrJobNotRunning.Error():
return host.ErrJobNotRunning
case host.ErrAttached.Error():
return host.ErrAttached
}
return errors.New(errMsg)
default:
rwc.Close()
return fmt.Errorf("cluster: unknown attach state: %d", attachState)
}
}
if attachState[0] == host.AttachWaiting {
if !wait {
rwc.Close()
return nil, ErrWouldWait
}
wait := func() error {
if _, err := rwc.Read(attachState); err != nil {
rwc.Close()
return err
}
return handleState()
}
c := &attachClient{
conn: rwc,
wait: wait,
w: bufio.NewWriter(rwc),
}
c.mtx.Lock()
return c, nil
}
return NewAttachClient(rwc), handleState()
} | go | func (c *Host) Attach(req *host.AttachReq, wait bool) (AttachClient, error) {
rwc, err := c.c.Hijack("POST", "/attach", http.Header{"Upgrade": {"flynn-attach/0"}}, req)
if err != nil {
return nil, err
}
attachState := make([]byte, 1)
if _, err := rwc.Read(attachState); err != nil {
rwc.Close()
return nil, err
}
handleState := func() error {
switch attachState[0] {
case host.AttachSuccess:
return nil
case host.AttachError:
errBytes, err := ioutil.ReadAll(rwc)
rwc.Close()
if err != nil {
return err
}
if len(errBytes) >= 4 {
errBytes = errBytes[4:]
}
errMsg := string(errBytes)
switch errMsg {
case host.ErrJobNotRunning.Error():
return host.ErrJobNotRunning
case host.ErrAttached.Error():
return host.ErrAttached
}
return errors.New(errMsg)
default:
rwc.Close()
return fmt.Errorf("cluster: unknown attach state: %d", attachState)
}
}
if attachState[0] == host.AttachWaiting {
if !wait {
rwc.Close()
return nil, ErrWouldWait
}
wait := func() error {
if _, err := rwc.Read(attachState); err != nil {
rwc.Close()
return err
}
return handleState()
}
c := &attachClient{
conn: rwc,
wait: wait,
w: bufio.NewWriter(rwc),
}
c.mtx.Lock()
return c, nil
}
return NewAttachClient(rwc), handleState()
} | [
"func",
"(",
"c",
"*",
"Host",
")",
"Attach",
"(",
"req",
"*",
"host",
".",
"AttachReq",
",",
"wait",
"bool",
")",
"(",
"AttachClient",
",",
"error",
")",
"{",
"rwc",
",",
"err",
":=",
"c",
".",
"c",
".",
"Hijack",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"http",
".",
"Header",
"{",
"\"",
"\"",
":",
"{",
"\"",
"\"",
"}",
"}",
",",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"attachState",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"1",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"rwc",
".",
"Read",
"(",
"attachState",
")",
";",
"err",
"!=",
"nil",
"{",
"rwc",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"handleState",
":=",
"func",
"(",
")",
"error",
"{",
"switch",
"attachState",
"[",
"0",
"]",
"{",
"case",
"host",
".",
"AttachSuccess",
":",
"return",
"nil",
"\n",
"case",
"host",
".",
"AttachError",
":",
"errBytes",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"rwc",
")",
"\n",
"rwc",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"errBytes",
")",
">=",
"4",
"{",
"errBytes",
"=",
"errBytes",
"[",
"4",
":",
"]",
"\n",
"}",
"\n",
"errMsg",
":=",
"string",
"(",
"errBytes",
")",
"\n",
"switch",
"errMsg",
"{",
"case",
"host",
".",
"ErrJobNotRunning",
".",
"Error",
"(",
")",
":",
"return",
"host",
".",
"ErrJobNotRunning",
"\n",
"case",
"host",
".",
"ErrAttached",
".",
"Error",
"(",
")",
":",
"return",
"host",
".",
"ErrAttached",
"\n",
"}",
"\n",
"return",
"errors",
".",
"New",
"(",
"errMsg",
")",
"\n",
"default",
":",
"rwc",
".",
"Close",
"(",
")",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"attachState",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"attachState",
"[",
"0",
"]",
"==",
"host",
".",
"AttachWaiting",
"{",
"if",
"!",
"wait",
"{",
"rwc",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
",",
"ErrWouldWait",
"\n",
"}",
"\n",
"wait",
":=",
"func",
"(",
")",
"error",
"{",
"if",
"_",
",",
"err",
":=",
"rwc",
".",
"Read",
"(",
"attachState",
")",
";",
"err",
"!=",
"nil",
"{",
"rwc",
".",
"Close",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"return",
"handleState",
"(",
")",
"\n",
"}",
"\n",
"c",
":=",
"&",
"attachClient",
"{",
"conn",
":",
"rwc",
",",
"wait",
":",
"wait",
",",
"w",
":",
"bufio",
".",
"NewWriter",
"(",
"rwc",
")",
",",
"}",
"\n",
"c",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"return",
"c",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"NewAttachClient",
"(",
"rwc",
")",
",",
"handleState",
"(",
")",
"\n",
"}"
] | // Attach attaches to the job specified in req and returns an attach client. If
// wait is true, the client will wait for the job to start before returning the
// first bytes. If wait is false and the job is not running, ErrWouldWait is
// returned. | [
"Attach",
"attaches",
"to",
"the",
"job",
"specified",
"in",
"req",
"and",
"returns",
"an",
"attach",
"client",
".",
"If",
"wait",
"is",
"true",
"the",
"client",
"will",
"wait",
"for",
"the",
"job",
"to",
"start",
"before",
"returning",
"the",
"first",
"bytes",
".",
"If",
"wait",
"is",
"false",
"and",
"the",
"job",
"is",
"not",
"running",
"ErrWouldWait",
"is",
"returned",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/cluster/attach.go#L24-L85 | train |
flynn/flynn | pkg/cluster/attach.go | NewAttachClient | func NewAttachClient(conn io.ReadWriteCloser) AttachClient {
return &attachClient{conn: conn, w: bufio.NewWriter(conn)}
} | go | func NewAttachClient(conn io.ReadWriteCloser) AttachClient {
return &attachClient{conn: conn, w: bufio.NewWriter(conn)}
} | [
"func",
"NewAttachClient",
"(",
"conn",
"io",
".",
"ReadWriteCloser",
")",
"AttachClient",
"{",
"return",
"&",
"attachClient",
"{",
"conn",
":",
"conn",
",",
"w",
":",
"bufio",
".",
"NewWriter",
"(",
"conn",
")",
"}",
"\n",
"}"
] | // NewAttachClient wraps conn in an implementation of AttachClient. | [
"NewAttachClient",
"wraps",
"conn",
"in",
"an",
"implementation",
"of",
"AttachClient",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/cluster/attach.go#L88-L90 | train |
flynn/flynn | pkg/pinned/pinned.go | Dial | func (c *Config) Dial(network, addr string) (net.Conn, error) {
var conf tls.Config
if c.Config != nil {
conf = *c.Config
}
conf.InsecureSkipVerify = true
cn, err := dialer.Retry.Dial(network, addr)
if err != nil {
return nil, err
}
conn := Conn{
Conn: tls.Client(cn, &conf),
Wire: cn,
}
if conf.ServerName == "" {
conf.ServerName, _, _ = net.SplitHostPort(addr)
}
if err = conn.Handshake(); err != nil {
conn.Close()
return nil, err
}
state := conn.ConnectionState()
hashFunc := c.Hash
if hashFunc == nil {
hashFunc = sha256.New
}
h := hashFunc()
h.Write(state.PeerCertificates[0].Raw)
if !bytes.Equal(h.Sum(nil), c.Pin) {
conn.Close()
return nil, ErrPinFailure
}
return conn, nil
} | go | func (c *Config) Dial(network, addr string) (net.Conn, error) {
var conf tls.Config
if c.Config != nil {
conf = *c.Config
}
conf.InsecureSkipVerify = true
cn, err := dialer.Retry.Dial(network, addr)
if err != nil {
return nil, err
}
conn := Conn{
Conn: tls.Client(cn, &conf),
Wire: cn,
}
if conf.ServerName == "" {
conf.ServerName, _, _ = net.SplitHostPort(addr)
}
if err = conn.Handshake(); err != nil {
conn.Close()
return nil, err
}
state := conn.ConnectionState()
hashFunc := c.Hash
if hashFunc == nil {
hashFunc = sha256.New
}
h := hashFunc()
h.Write(state.PeerCertificates[0].Raw)
if !bytes.Equal(h.Sum(nil), c.Pin) {
conn.Close()
return nil, ErrPinFailure
}
return conn, nil
} | [
"func",
"(",
"c",
"*",
"Config",
")",
"Dial",
"(",
"network",
",",
"addr",
"string",
")",
"(",
"net",
".",
"Conn",
",",
"error",
")",
"{",
"var",
"conf",
"tls",
".",
"Config",
"\n",
"if",
"c",
".",
"Config",
"!=",
"nil",
"{",
"conf",
"=",
"*",
"c",
".",
"Config",
"\n",
"}",
"\n",
"conf",
".",
"InsecureSkipVerify",
"=",
"true",
"\n\n",
"cn",
",",
"err",
":=",
"dialer",
".",
"Retry",
".",
"Dial",
"(",
"network",
",",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"conn",
":=",
"Conn",
"{",
"Conn",
":",
"tls",
".",
"Client",
"(",
"cn",
",",
"&",
"conf",
")",
",",
"Wire",
":",
"cn",
",",
"}",
"\n\n",
"if",
"conf",
".",
"ServerName",
"==",
"\"",
"\"",
"{",
"conf",
".",
"ServerName",
",",
"_",
",",
"_",
"=",
"net",
".",
"SplitHostPort",
"(",
"addr",
")",
"\n",
"}",
"\n\n",
"if",
"err",
"=",
"conn",
".",
"Handshake",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"conn",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"state",
":=",
"conn",
".",
"ConnectionState",
"(",
")",
"\n",
"hashFunc",
":=",
"c",
".",
"Hash",
"\n",
"if",
"hashFunc",
"==",
"nil",
"{",
"hashFunc",
"=",
"sha256",
".",
"New",
"\n",
"}",
"\n",
"h",
":=",
"hashFunc",
"(",
")",
"\n",
"h",
".",
"Write",
"(",
"state",
".",
"PeerCertificates",
"[",
"0",
"]",
".",
"Raw",
")",
"\n",
"if",
"!",
"bytes",
".",
"Equal",
"(",
"h",
".",
"Sum",
"(",
"nil",
")",
",",
"c",
".",
"Pin",
")",
"{",
"conn",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
",",
"ErrPinFailure",
"\n",
"}",
"\n",
"return",
"conn",
",",
"nil",
"\n",
"}"
] | // Dial establishes a TLS connection to addr and checks the peer leaf
// certificate against the configured pin. The underlying type of the returned
// net.Conn is a Conn. | [
"Dial",
"establishes",
"a",
"TLS",
"connection",
"to",
"addr",
"and",
"checks",
"the",
"peer",
"leaf",
"certificate",
"against",
"the",
"configured",
"pin",
".",
"The",
"underlying",
"type",
"of",
"the",
"returned",
"net",
".",
"Conn",
"is",
"a",
"Conn",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/pinned/pinned.go#L36-L74 | train |
flynn/flynn | pkg/pinned/pinned.go | CloseWrite | func (c Conn) CloseWrite() error {
if cw, ok := c.Wire.(interface {
CloseWrite() error
}); ok {
return cw.CloseWrite()
}
return errors.New("pinned: underlying connection does not support CloseWrite")
} | go | func (c Conn) CloseWrite() error {
if cw, ok := c.Wire.(interface {
CloseWrite() error
}); ok {
return cw.CloseWrite()
}
return errors.New("pinned: underlying connection does not support CloseWrite")
} | [
"func",
"(",
"c",
"Conn",
")",
"CloseWrite",
"(",
")",
"error",
"{",
"if",
"cw",
",",
"ok",
":=",
"c",
".",
"Wire",
".",
"(",
"interface",
"{",
"CloseWrite",
"(",
")",
"error",
"\n",
"}",
")",
";",
"ok",
"{",
"return",
"cw",
".",
"CloseWrite",
"(",
")",
"\n",
"}",
"\n",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // CloseWrite shuts down the writing side of the connection. | [
"CloseWrite",
"shuts",
"down",
"the",
"writing",
"side",
"of",
"the",
"connection",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/pinned/pinned.go#L86-L93 | train |
flynn/flynn | discoverd/client/client.go | currentPin | func (c *Client) currentPin() (string, string) {
c.mu.RLock()
defer c.mu.RUnlock()
return c.leader, c.pinned
} | go | func (c *Client) currentPin() (string, string) {
c.mu.RLock()
defer c.mu.RUnlock()
return c.leader, c.pinned
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"currentPin",
"(",
")",
"(",
"string",
",",
"string",
")",
"{",
"c",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"c",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"c",
".",
"leader",
",",
"c",
".",
"pinned",
"\n",
"}"
] | // Retrieves current pin value | [
"Retrieves",
"current",
"pin",
"value"
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/discoverd/client/client.go#L132-L136 | train |
flynn/flynn | discoverd/client/client.go | updatePin | func (c *Client) updatePin(new string) {
c.mu.Lock()
defer c.mu.Unlock()
c.pinned = new
} | go | func (c *Client) updatePin(new string) {
c.mu.Lock()
defer c.mu.Unlock()
c.pinned = new
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"updatePin",
"(",
"new",
"string",
")",
"{",
"c",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"c",
".",
"pinned",
"=",
"new",
"\n",
"}"
] | // Update the currently pinned server | [
"Update",
"the",
"currently",
"pinned",
"server"
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/discoverd/client/client.go#L139-L143 | train |
flynn/flynn | discoverd/client/client.go | updateServers | func (c *Client) updateServers(servers []string, idx uint64) {
c.mu.Lock()
defer c.mu.Unlock()
// If the new index isn't greater than the current index then ignore
// changes to the peer list. Prevents out of order request handling
// nuking a more recent version of the peer list.
if idx < c.idx {
return
}
c.idx = idx
servers = formatURLs(servers)
// First add any new servers
for _, s := range servers {
if _, ok := c.servers[s]; !ok {
c.servers[s] = c.httpClient(s)
}
}
// Then remove any that are no longer current
for addr := range c.servers {
present := false
for _, s := range servers {
if _, ok := c.servers[s]; ok {
present = true
break
}
}
if !present {
delete(c.servers, addr)
}
}
} | go | func (c *Client) updateServers(servers []string, idx uint64) {
c.mu.Lock()
defer c.mu.Unlock()
// If the new index isn't greater than the current index then ignore
// changes to the peer list. Prevents out of order request handling
// nuking a more recent version of the peer list.
if idx < c.idx {
return
}
c.idx = idx
servers = formatURLs(servers)
// First add any new servers
for _, s := range servers {
if _, ok := c.servers[s]; !ok {
c.servers[s] = c.httpClient(s)
}
}
// Then remove any that are no longer current
for addr := range c.servers {
present := false
for _, s := range servers {
if _, ok := c.servers[s]; ok {
present = true
break
}
}
if !present {
delete(c.servers, addr)
}
}
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"updateServers",
"(",
"servers",
"[",
"]",
"string",
",",
"idx",
"uint64",
")",
"{",
"c",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"// If the new index isn't greater than the current index then ignore",
"// changes to the peer list. Prevents out of order request handling",
"// nuking a more recent version of the peer list.",
"if",
"idx",
"<",
"c",
".",
"idx",
"{",
"return",
"\n",
"}",
"\n",
"c",
".",
"idx",
"=",
"idx",
"\n",
"servers",
"=",
"formatURLs",
"(",
"servers",
")",
"\n\n",
"// First add any new servers",
"for",
"_",
",",
"s",
":=",
"range",
"servers",
"{",
"if",
"_",
",",
"ok",
":=",
"c",
".",
"servers",
"[",
"s",
"]",
";",
"!",
"ok",
"{",
"c",
".",
"servers",
"[",
"s",
"]",
"=",
"c",
".",
"httpClient",
"(",
"s",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Then remove any that are no longer current",
"for",
"addr",
":=",
"range",
"c",
".",
"servers",
"{",
"present",
":=",
"false",
"\n",
"for",
"_",
",",
"s",
":=",
"range",
"servers",
"{",
"if",
"_",
",",
"ok",
":=",
"c",
".",
"servers",
"[",
"s",
"]",
";",
"ok",
"{",
"present",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"present",
"{",
"delete",
"(",
"c",
".",
"servers",
",",
"addr",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Updates the list of peers | [
"Updates",
"the",
"list",
"of",
"peers"
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/discoverd/client/client.go#L146-L179 | train |
flynn/flynn | pkg/keepalive/reuseport.go | ReusableListen | func ReusableListen(proto, addr string) (net.Listener, error) {
backlogOnce.Do(func() {
backlog = maxListenerBacklog()
})
saddr, typ, err := sockaddr(proto, addr)
if err != nil {
return nil, err
}
fd, err := syscall.Socket(typ, syscall.SOCK_STREAM, syscall.IPPROTO_TCP)
if err != nil {
return nil, err
}
if err := setSockopt(fd); err != nil {
return nil, err
}
if err := syscall.Bind(fd, saddr); err != nil {
return nil, err
}
if err := syscall.Listen(fd, backlog); err != nil {
return nil, err
}
f := os.NewFile(uintptr(fd), proto+":"+addr)
l, err := net.FileListener(f)
if err != nil {
return nil, err
}
if err := f.Close(); err != nil {
l.Close()
return nil, err
}
return l, nil
} | go | func ReusableListen(proto, addr string) (net.Listener, error) {
backlogOnce.Do(func() {
backlog = maxListenerBacklog()
})
saddr, typ, err := sockaddr(proto, addr)
if err != nil {
return nil, err
}
fd, err := syscall.Socket(typ, syscall.SOCK_STREAM, syscall.IPPROTO_TCP)
if err != nil {
return nil, err
}
if err := setSockopt(fd); err != nil {
return nil, err
}
if err := syscall.Bind(fd, saddr); err != nil {
return nil, err
}
if err := syscall.Listen(fd, backlog); err != nil {
return nil, err
}
f := os.NewFile(uintptr(fd), proto+":"+addr)
l, err := net.FileListener(f)
if err != nil {
return nil, err
}
if err := f.Close(); err != nil {
l.Close()
return nil, err
}
return l, nil
} | [
"func",
"ReusableListen",
"(",
"proto",
",",
"addr",
"string",
")",
"(",
"net",
".",
"Listener",
",",
"error",
")",
"{",
"backlogOnce",
".",
"Do",
"(",
"func",
"(",
")",
"{",
"backlog",
"=",
"maxListenerBacklog",
"(",
")",
"\n",
"}",
")",
"\n\n",
"saddr",
",",
"typ",
",",
"err",
":=",
"sockaddr",
"(",
"proto",
",",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"fd",
",",
"err",
":=",
"syscall",
".",
"Socket",
"(",
"typ",
",",
"syscall",
".",
"SOCK_STREAM",
",",
"syscall",
".",
"IPPROTO_TCP",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"setSockopt",
"(",
"fd",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"syscall",
".",
"Bind",
"(",
"fd",
",",
"saddr",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"syscall",
".",
"Listen",
"(",
"fd",
",",
"backlog",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"f",
":=",
"os",
".",
"NewFile",
"(",
"uintptr",
"(",
"fd",
")",
",",
"proto",
"+",
"\"",
"\"",
"+",
"addr",
")",
"\n",
"l",
",",
"err",
":=",
"net",
".",
"FileListener",
"(",
"f",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"f",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"l",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"l",
",",
"nil",
"\n",
"}"
] | // ReusableListen returns a TCP listener with SO_REUSEPORT and keepalives
// enabled. | [
"ReusableListen",
"returns",
"a",
"TCP",
"listener",
"with",
"SO_REUSEPORT",
"and",
"keepalives",
"enabled",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/keepalive/reuseport.go#L19-L58 | train |
flynn/flynn | router/client/client.go | NewWithAddr | func NewWithAddr(addr string) Client {
c := newRouterClient()
c.URL = fmt.Sprintf("http://%s", addr)
return c
} | go | func NewWithAddr(addr string) Client {
c := newRouterClient()
c.URL = fmt.Sprintf("http://%s", addr)
return c
} | [
"func",
"NewWithAddr",
"(",
"addr",
"string",
")",
"Client",
"{",
"c",
":=",
"newRouterClient",
"(",
")",
"\n",
"c",
".",
"URL",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"addr",
")",
"\n",
"return",
"c",
"\n",
"}"
] | // NewWithAddr uses addr as the specified API url and returns a client. | [
"NewWithAddr",
"uses",
"addr",
"as",
"the",
"specified",
"API",
"url",
"and",
"returns",
"a",
"client",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/router/client/client.go#L46-L50 | train |
flynn/flynn | appliance/redis/process.go | NewProcess | func NewProcess() *Process {
p := &Process{
Port: DefaultPort,
BinDir: DefaultBinDir,
DataDir: DefaultDataDir,
Password: DefaultPassword,
OpTimeout: DefaultOpTimeout,
ReplTimeout: DefaultReplTimeout,
Logger: log15.New("app", "redis"),
}
p.stopping.Store(false)
return p
} | go | func NewProcess() *Process {
p := &Process{
Port: DefaultPort,
BinDir: DefaultBinDir,
DataDir: DefaultDataDir,
Password: DefaultPassword,
OpTimeout: DefaultOpTimeout,
ReplTimeout: DefaultReplTimeout,
Logger: log15.New("app", "redis"),
}
p.stopping.Store(false)
return p
} | [
"func",
"NewProcess",
"(",
")",
"*",
"Process",
"{",
"p",
":=",
"&",
"Process",
"{",
"Port",
":",
"DefaultPort",
",",
"BinDir",
":",
"DefaultBinDir",
",",
"DataDir",
":",
"DefaultDataDir",
",",
"Password",
":",
"DefaultPassword",
",",
"OpTimeout",
":",
"DefaultOpTimeout",
",",
"ReplTimeout",
":",
"DefaultReplTimeout",
",",
"Logger",
":",
"log15",
".",
"New",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"}",
"\n",
"p",
".",
"stopping",
".",
"Store",
"(",
"false",
")",
"\n",
"return",
"p",
"\n",
"}"
] | // NewProcess returns a new instance of Process with defaults. | [
"NewProcess",
"returns",
"a",
"new",
"instance",
"of",
"Process",
"with",
"defaults",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/appliance/redis/process.go#L70-L82 | train |
flynn/flynn | appliance/redis/process.go | Start | func (p *Process) Start() error {
p.mtx.Lock()
defer p.mtx.Unlock()
// Valdiate that process is not already running and that we have a config.
if p.running {
return ErrRunning
}
return p.start()
} | go | func (p *Process) Start() error {
p.mtx.Lock()
defer p.mtx.Unlock()
// Valdiate that process is not already running and that we have a config.
if p.running {
return ErrRunning
}
return p.start()
} | [
"func",
"(",
"p",
"*",
"Process",
")",
"Start",
"(",
")",
"error",
"{",
"p",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"p",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"// Valdiate that process is not already running and that we have a config.",
"if",
"p",
".",
"running",
"{",
"return",
"ErrRunning",
"\n",
"}",
"\n",
"return",
"p",
".",
"start",
"(",
")",
"\n",
"}"
] | // Start begins the process.
// Returns an error if the process is already running. | [
"Start",
"begins",
"the",
"process",
".",
"Returns",
"an",
"error",
"if",
"the",
"process",
"is",
"already",
"running",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/appliance/redis/process.go#L89-L98 | train |
flynn/flynn | appliance/redis/process.go | Stop | func (p *Process) Stop() error {
p.mtx.Lock()
defer p.mtx.Unlock()
if !p.running {
return ErrStopped
}
return p.stop()
} | go | func (p *Process) Stop() error {
p.mtx.Lock()
defer p.mtx.Unlock()
if !p.running {
return ErrStopped
}
return p.stop()
} | [
"func",
"(",
"p",
"*",
"Process",
")",
"Stop",
"(",
")",
"error",
"{",
"p",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"p",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"!",
"p",
".",
"running",
"{",
"return",
"ErrStopped",
"\n",
"}",
"\n",
"return",
"p",
".",
"stop",
"(",
")",
"\n",
"}"
] | // Stop attempts to gracefully stop the process. If the process cannot be
// stopped gracefully then it is forcefully stopped. Returns an error if the
// process is already stopped. | [
"Stop",
"attempts",
"to",
"gracefully",
"stop",
"the",
"process",
".",
"If",
"the",
"process",
"cannot",
"be",
"stopped",
"gracefully",
"then",
"it",
"is",
"forcefully",
"stopped",
".",
"Returns",
"an",
"error",
"if",
"the",
"process",
"is",
"already",
"stopped",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/appliance/redis/process.go#L142-L150 | train |
flynn/flynn | appliance/redis/process.go | monitorCmd | func (p *Process) monitorCmd(cmd *exec.Cmd, stopped chan struct{}) {
err := cmd.Wait()
if !p.stopping.Load().(bool) {
p.Logger.Error("unexpectedly exit", "err", err)
shutdown.ExitWithCode(1)
}
close(stopped)
} | go | func (p *Process) monitorCmd(cmd *exec.Cmd, stopped chan struct{}) {
err := cmd.Wait()
if !p.stopping.Load().(bool) {
p.Logger.Error("unexpectedly exit", "err", err)
shutdown.ExitWithCode(1)
}
close(stopped)
} | [
"func",
"(",
"p",
"*",
"Process",
")",
"monitorCmd",
"(",
"cmd",
"*",
"exec",
".",
"Cmd",
",",
"stopped",
"chan",
"struct",
"{",
"}",
")",
"{",
"err",
":=",
"cmd",
".",
"Wait",
"(",
")",
"\n",
"if",
"!",
"p",
".",
"stopping",
".",
"Load",
"(",
")",
".",
"(",
"bool",
")",
"{",
"p",
".",
"Logger",
".",
"Error",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"shutdown",
".",
"ExitWithCode",
"(",
"1",
")",
"\n",
"}",
"\n",
"close",
"(",
"stopped",
")",
"\n",
"}"
] | // monitorCmd waits for cmd to finish and reports an error if it was unexpected.
// Also closes the stopped channel to notify other listeners that it has finished. | [
"monitorCmd",
"waits",
"for",
"cmd",
"to",
"finish",
"and",
"reports",
"an",
"error",
"if",
"it",
"was",
"unexpected",
".",
"Also",
"closes",
"the",
"stopped",
"channel",
"to",
"notify",
"other",
"listeners",
"that",
"it",
"has",
"finished",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/appliance/redis/process.go#L179-L186 | train |
flynn/flynn | appliance/redis/process.go | writeConfig | func (p *Process) writeConfig() error {
logger := p.Logger.New("fn", "writeConfig")
logger.Info("writing")
// Create parent directory if it doesn't exist.
if err := os.MkdirAll(filepath.Dir(p.ConfigPath()), 0777); err != nil {
logger.Error("cannot create config parent directory", "err", err)
return err
}
f, err := os.Create(p.ConfigPath())
if err != nil {
logger.Error("cannot create config file", "err", err)
return err
}
defer f.Close()
return configTemplate.Execute(f, struct {
ID string
Port string
DataDir string
Password string
}{p.ID, p.Port, p.DataDir, p.Password})
} | go | func (p *Process) writeConfig() error {
logger := p.Logger.New("fn", "writeConfig")
logger.Info("writing")
// Create parent directory if it doesn't exist.
if err := os.MkdirAll(filepath.Dir(p.ConfigPath()), 0777); err != nil {
logger.Error("cannot create config parent directory", "err", err)
return err
}
f, err := os.Create(p.ConfigPath())
if err != nil {
logger.Error("cannot create config file", "err", err)
return err
}
defer f.Close()
return configTemplate.Execute(f, struct {
ID string
Port string
DataDir string
Password string
}{p.ID, p.Port, p.DataDir, p.Password})
} | [
"func",
"(",
"p",
"*",
"Process",
")",
"writeConfig",
"(",
")",
"error",
"{",
"logger",
":=",
"p",
".",
"Logger",
".",
"New",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"logger",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"// Create parent directory if it doesn't exist.",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"filepath",
".",
"Dir",
"(",
"p",
".",
"ConfigPath",
"(",
")",
")",
",",
"0777",
")",
";",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Error",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"f",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"p",
".",
"ConfigPath",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Error",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n\n",
"return",
"configTemplate",
".",
"Execute",
"(",
"f",
",",
"struct",
"{",
"ID",
"string",
"\n",
"Port",
"string",
"\n",
"DataDir",
"string",
"\n",
"Password",
"string",
"\n",
"}",
"{",
"p",
".",
"ID",
",",
"p",
".",
"Port",
",",
"p",
".",
"DataDir",
",",
"p",
".",
"Password",
"}",
")",
"\n",
"}"
] | // writeConfig generates a new redis.conf at the config path. | [
"writeConfig",
"generates",
"a",
"new",
"redis",
".",
"conf",
"at",
"the",
"config",
"path",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/appliance/redis/process.go#L189-L212 | train |
flynn/flynn | appliance/redis/process.go | Info | func (p *Process) Info() (*ProcessInfo, error) {
p.mtx.Lock()
defer p.mtx.Unlock()
return &ProcessInfo{Running: p.running}, nil
} | go | func (p *Process) Info() (*ProcessInfo, error) {
p.mtx.Lock()
defer p.mtx.Unlock()
return &ProcessInfo{Running: p.running}, nil
} | [
"func",
"(",
"p",
"*",
"Process",
")",
"Info",
"(",
")",
"(",
"*",
"ProcessInfo",
",",
"error",
")",
"{",
"p",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"p",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n",
"return",
"&",
"ProcessInfo",
"{",
"Running",
":",
"p",
".",
"running",
"}",
",",
"nil",
"\n",
"}"
] | // Info returns information about the process. | [
"Info",
"returns",
"information",
"about",
"the",
"process",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/appliance/redis/process.go#L215-L219 | train |
flynn/flynn | appliance/redis/process.go | ping | func (p *Process) ping(addr string, timeout time.Duration) error {
// Default to local process if addr not specified.
if addr == "" {
addr = fmt.Sprintf("localhost:%s", p.Port)
}
logger := p.Logger.New("fn", "ping", "addr", addr, "timeout", timeout)
logger.Info("sending")
timer := time.NewTimer(timeout)
defer timer.Stop()
ticker := time.NewTicker(checkInterval)
defer ticker.Stop()
for {
// Attempt to ping the server.
if ok := func() bool {
logger.Info("sending PING")
conn, err := redis.Dial("tcp", addr,
redis.DialPassword(p.Password),
redis.DialConnectTimeout(timeout),
redis.DialReadTimeout(timeout),
redis.DialWriteTimeout(timeout),
)
if err != nil {
logger.Error("conn error", "err", err)
return false
}
defer conn.Close()
if _, err := conn.Do("PING"); err != nil {
logger.Error("error getting upstream status", "err", err)
return false
}
logger.Info("PONG received")
return true
}(); ok {
return nil
}
select {
case <-timer.C:
logger.Info("timeout")
return ErrTimeout
case <-ticker.C:
}
}
} | go | func (p *Process) ping(addr string, timeout time.Duration) error {
// Default to local process if addr not specified.
if addr == "" {
addr = fmt.Sprintf("localhost:%s", p.Port)
}
logger := p.Logger.New("fn", "ping", "addr", addr, "timeout", timeout)
logger.Info("sending")
timer := time.NewTimer(timeout)
defer timer.Stop()
ticker := time.NewTicker(checkInterval)
defer ticker.Stop()
for {
// Attempt to ping the server.
if ok := func() bool {
logger.Info("sending PING")
conn, err := redis.Dial("tcp", addr,
redis.DialPassword(p.Password),
redis.DialConnectTimeout(timeout),
redis.DialReadTimeout(timeout),
redis.DialWriteTimeout(timeout),
)
if err != nil {
logger.Error("conn error", "err", err)
return false
}
defer conn.Close()
if _, err := conn.Do("PING"); err != nil {
logger.Error("error getting upstream status", "err", err)
return false
}
logger.Info("PONG received")
return true
}(); ok {
return nil
}
select {
case <-timer.C:
logger.Info("timeout")
return ErrTimeout
case <-ticker.C:
}
}
} | [
"func",
"(",
"p",
"*",
"Process",
")",
"ping",
"(",
"addr",
"string",
",",
"timeout",
"time",
".",
"Duration",
")",
"error",
"{",
"// Default to local process if addr not specified.",
"if",
"addr",
"==",
"\"",
"\"",
"{",
"addr",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"p",
".",
"Port",
")",
"\n",
"}",
"\n\n",
"logger",
":=",
"p",
".",
"Logger",
".",
"New",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"addr",
",",
"\"",
"\"",
",",
"timeout",
")",
"\n",
"logger",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"timer",
":=",
"time",
".",
"NewTimer",
"(",
"timeout",
")",
"\n",
"defer",
"timer",
".",
"Stop",
"(",
")",
"\n\n",
"ticker",
":=",
"time",
".",
"NewTicker",
"(",
"checkInterval",
")",
"\n",
"defer",
"ticker",
".",
"Stop",
"(",
")",
"\n\n",
"for",
"{",
"// Attempt to ping the server.",
"if",
"ok",
":=",
"func",
"(",
")",
"bool",
"{",
"logger",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"conn",
",",
"err",
":=",
"redis",
".",
"Dial",
"(",
"\"",
"\"",
",",
"addr",
",",
"redis",
".",
"DialPassword",
"(",
"p",
".",
"Password",
")",
",",
"redis",
".",
"DialConnectTimeout",
"(",
"timeout",
")",
",",
"redis",
".",
"DialReadTimeout",
"(",
"timeout",
")",
",",
"redis",
".",
"DialWriteTimeout",
"(",
"timeout",
")",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Error",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n\n",
"if",
"_",
",",
"err",
":=",
"conn",
".",
"Do",
"(",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Error",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n\n",
"logger",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"return",
"true",
"\n",
"}",
"(",
")",
";",
"ok",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"select",
"{",
"case",
"<-",
"timer",
".",
"C",
":",
"logger",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"return",
"ErrTimeout",
"\n",
"case",
"<-",
"ticker",
".",
"C",
":",
"}",
"\n",
"}",
"\n",
"}"
] | // ping executes a PING command against addr until timeout occurs. | [
"ping",
"executes",
"a",
"PING",
"command",
"against",
"addr",
"until",
"timeout",
"occurs",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/appliance/redis/process.go#L227-L277 | train |
flynn/flynn | appliance/redis/process.go | pingWait | func (p *Process) pingWait(addr string, timeout time.Duration) error {
// Default to local process if addr not specified.
if addr == "" {
addr = fmt.Sprintf("localhost:%s", p.Port)
}
logger := p.Logger.New("fn", "pingWait", "addr", addr, "timeout", timeout)
ticker := time.NewTicker(checkInterval)
defer ticker.Stop()
timer := time.NewTimer(timeout)
defer timer.Stop()
for {
select {
case <-timer.C:
return ErrTimeout
case <-ticker.C:
}
if err := p.ping(addr, timeout); err != nil {
logger.Error("ping error", "err", err)
continue
}
return nil
}
} | go | func (p *Process) pingWait(addr string, timeout time.Duration) error {
// Default to local process if addr not specified.
if addr == "" {
addr = fmt.Sprintf("localhost:%s", p.Port)
}
logger := p.Logger.New("fn", "pingWait", "addr", addr, "timeout", timeout)
ticker := time.NewTicker(checkInterval)
defer ticker.Stop()
timer := time.NewTimer(timeout)
defer timer.Stop()
for {
select {
case <-timer.C:
return ErrTimeout
case <-ticker.C:
}
if err := p.ping(addr, timeout); err != nil {
logger.Error("ping error", "err", err)
continue
}
return nil
}
} | [
"func",
"(",
"p",
"*",
"Process",
")",
"pingWait",
"(",
"addr",
"string",
",",
"timeout",
"time",
".",
"Duration",
")",
"error",
"{",
"// Default to local process if addr not specified.",
"if",
"addr",
"==",
"\"",
"\"",
"{",
"addr",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"p",
".",
"Port",
")",
"\n",
"}",
"\n\n",
"logger",
":=",
"p",
".",
"Logger",
".",
"New",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"addr",
",",
"\"",
"\"",
",",
"timeout",
")",
"\n\n",
"ticker",
":=",
"time",
".",
"NewTicker",
"(",
"checkInterval",
")",
"\n",
"defer",
"ticker",
".",
"Stop",
"(",
")",
"\n\n",
"timer",
":=",
"time",
".",
"NewTimer",
"(",
"timeout",
")",
"\n",
"defer",
"timer",
".",
"Stop",
"(",
")",
"\n\n",
"for",
"{",
"select",
"{",
"case",
"<-",
"timer",
".",
"C",
":",
"return",
"ErrTimeout",
"\n",
"case",
"<-",
"ticker",
".",
"C",
":",
"}",
"\n\n",
"if",
"err",
":=",
"p",
".",
"ping",
"(",
"addr",
",",
"timeout",
")",
";",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Error",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // pingWait continually pings a server until successful response or timeout. | [
"pingWait",
"continually",
"pings",
"a",
"server",
"until",
"successful",
"response",
"or",
"timeout",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/appliance/redis/process.go#L280-L308 | train |
flynn/flynn | appliance/redis/process.go | Restore | func (p *Process) Restore(r io.Reader) error {
p.mtx.Lock()
defer p.mtx.Unlock()
logger := p.Logger.New("fn", "Restore")
logger.Info("begin restore")
// Stop if running.
if p.running {
logger.Info("stopping process")
if err := p.stop(); err != nil {
logger.Error("error stopping process", "err", err)
return err
}
}
// Create dump file in data directory.
logger.Info("copying dump.rdb")
if err := func() error {
f, err := os.Create(filepath.Join(p.DataDir, "dump.rdb"))
if err != nil {
logger.Error("error creating dump file", "err", err)
return err
}
defer f.Close()
// Copy from reader to dump file.
n, err := io.Copy(f, r)
if err != nil {
logger.Error("error creating dump file", "err", err)
return err
}
logger.Info("copy completed", "n", n)
return nil
}(); err != nil {
return err
}
// Restart process.
if err := p.start(); err != nil {
logger.Error("error restarting process", "err", err)
return err
}
return nil
} | go | func (p *Process) Restore(r io.Reader) error {
p.mtx.Lock()
defer p.mtx.Unlock()
logger := p.Logger.New("fn", "Restore")
logger.Info("begin restore")
// Stop if running.
if p.running {
logger.Info("stopping process")
if err := p.stop(); err != nil {
logger.Error("error stopping process", "err", err)
return err
}
}
// Create dump file in data directory.
logger.Info("copying dump.rdb")
if err := func() error {
f, err := os.Create(filepath.Join(p.DataDir, "dump.rdb"))
if err != nil {
logger.Error("error creating dump file", "err", err)
return err
}
defer f.Close()
// Copy from reader to dump file.
n, err := io.Copy(f, r)
if err != nil {
logger.Error("error creating dump file", "err", err)
return err
}
logger.Info("copy completed", "n", n)
return nil
}(); err != nil {
return err
}
// Restart process.
if err := p.start(); err != nil {
logger.Error("error restarting process", "err", err)
return err
}
return nil
} | [
"func",
"(",
"p",
"*",
"Process",
")",
"Restore",
"(",
"r",
"io",
".",
"Reader",
")",
"error",
"{",
"p",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"p",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"logger",
":=",
"p",
".",
"Logger",
".",
"New",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"logger",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"// Stop if running.",
"if",
"p",
".",
"running",
"{",
"logger",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
":=",
"p",
".",
"stop",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Error",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Create dump file in data directory.",
"logger",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
":=",
"func",
"(",
")",
"error",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"filepath",
".",
"Join",
"(",
"p",
".",
"DataDir",
",",
"\"",
"\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Error",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n\n",
"// Copy from reader to dump file.",
"n",
",",
"err",
":=",
"io",
".",
"Copy",
"(",
"f",
",",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Error",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"logger",
".",
"Info",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"n",
")",
"\n\n",
"return",
"nil",
"\n",
"}",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Restart process.",
"if",
"err",
":=",
"p",
".",
"start",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Error",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Restore stops the process, copies an RDB from r, and restarts the process.
// Redis automatically handles recovery when there's a dump.rdb file present. | [
"Restore",
"stops",
"the",
"process",
"copies",
"an",
"RDB",
"from",
"r",
"and",
"restarts",
"the",
"process",
".",
"Redis",
"automatically",
"handles",
"recovery",
"when",
"there",
"s",
"a",
"dump",
".",
"rdb",
"file",
"present",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/appliance/redis/process.go#L312-L358 | train |
flynn/flynn | appliance/redis/process.go | RedisInfo | func (p *Process) RedisInfo(addr string, timeout time.Duration) (*RedisInfo, error) {
// Default to local process if addr not specified.
if addr == "" {
addr = fmt.Sprintf("localhost:%s", p.Port)
}
logger := p.Logger.New("fn", "replInfo", "addr", addr)
logger.Info("sending INFO")
// Connect to the redis server.
conn, err := redis.Dial("tcp", addr,
redis.DialPassword(p.Password),
redis.DialConnectTimeout(timeout),
redis.DialReadTimeout(timeout),
redis.DialWriteTimeout(timeout),
)
if err != nil {
logger.Info("dial error", "err", err)
return nil, err
}
defer conn.Close()
// Execute INFO command.
reply, err := conn.Do("INFO")
if err != nil {
logger.Error("info error", "err", err)
return nil, err
}
buf, ok := reply.([]byte)
if !ok {
logger.Error("info reply type error", "type", fmt.Sprintf("%T", buf))
return nil, fmt.Errorf("unexpected INFO reply format: %T", buf)
}
// Parse the bulk string reply info a typed object.
info, err := ParseRedisInfo(string(buf))
if err != nil {
logger.Error("parse info error", "err", err)
return nil, fmt.Errorf("parse info: %s", err)
}
logger.Info("INFO received")
return info, nil
} | go | func (p *Process) RedisInfo(addr string, timeout time.Duration) (*RedisInfo, error) {
// Default to local process if addr not specified.
if addr == "" {
addr = fmt.Sprintf("localhost:%s", p.Port)
}
logger := p.Logger.New("fn", "replInfo", "addr", addr)
logger.Info("sending INFO")
// Connect to the redis server.
conn, err := redis.Dial("tcp", addr,
redis.DialPassword(p.Password),
redis.DialConnectTimeout(timeout),
redis.DialReadTimeout(timeout),
redis.DialWriteTimeout(timeout),
)
if err != nil {
logger.Info("dial error", "err", err)
return nil, err
}
defer conn.Close()
// Execute INFO command.
reply, err := conn.Do("INFO")
if err != nil {
logger.Error("info error", "err", err)
return nil, err
}
buf, ok := reply.([]byte)
if !ok {
logger.Error("info reply type error", "type", fmt.Sprintf("%T", buf))
return nil, fmt.Errorf("unexpected INFO reply format: %T", buf)
}
// Parse the bulk string reply info a typed object.
info, err := ParseRedisInfo(string(buf))
if err != nil {
logger.Error("parse info error", "err", err)
return nil, fmt.Errorf("parse info: %s", err)
}
logger.Info("INFO received")
return info, nil
} | [
"func",
"(",
"p",
"*",
"Process",
")",
"RedisInfo",
"(",
"addr",
"string",
",",
"timeout",
"time",
".",
"Duration",
")",
"(",
"*",
"RedisInfo",
",",
"error",
")",
"{",
"// Default to local process if addr not specified.",
"if",
"addr",
"==",
"\"",
"\"",
"{",
"addr",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"p",
".",
"Port",
")",
"\n",
"}",
"\n\n",
"logger",
":=",
"p",
".",
"Logger",
".",
"New",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"addr",
")",
"\n",
"logger",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"// Connect to the redis server.",
"conn",
",",
"err",
":=",
"redis",
".",
"Dial",
"(",
"\"",
"\"",
",",
"addr",
",",
"redis",
".",
"DialPassword",
"(",
"p",
".",
"Password",
")",
",",
"redis",
".",
"DialConnectTimeout",
"(",
"timeout",
")",
",",
"redis",
".",
"DialReadTimeout",
"(",
"timeout",
")",
",",
"redis",
".",
"DialWriteTimeout",
"(",
"timeout",
")",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Info",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n\n",
"// Execute INFO command.",
"reply",
",",
"err",
":=",
"conn",
".",
"Do",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Error",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"buf",
",",
"ok",
":=",
"reply",
".",
"(",
"[",
"]",
"byte",
")",
"\n",
"if",
"!",
"ok",
"{",
"logger",
".",
"Error",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"buf",
")",
")",
"\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"buf",
")",
"\n",
"}",
"\n\n",
"// Parse the bulk string reply info a typed object.",
"info",
",",
"err",
":=",
"ParseRedisInfo",
"(",
"string",
"(",
"buf",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Error",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"logger",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"return",
"info",
",",
"nil",
"\n",
"}"
] | // RedisInfo executes an INFO command against a Redis server and returns the results. | [
"RedisInfo",
"executes",
"an",
"INFO",
"command",
"against",
"a",
"Redis",
"server",
"and",
"returns",
"the",
"results",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/appliance/redis/process.go#L361-L405 | train |
flynn/flynn | appliance/redis/process.go | ParseRedisInfo | func ParseRedisInfo(s string) (*RedisInfo, error) {
var info RedisInfo
scanner := bufio.NewScanner(strings.NewReader(s))
for scanner.Scan() {
line := scanner.Text()
// Skip blank lines & comment lines
if strings.HasPrefix(line, "#") || line == "" {
continue
}
// Split into key/value.
a := strings.SplitN(line, ":", 2)
if len(a) < 2 {
continue
}
key, value := strings.TrimSpace(a[0]), strings.TrimSpace(a[1])
// Parse into appropriate field.
switch key {
case "role":
info.Role = value
case "master_host":
info.MasterHost = value
case "master_port":
info.MasterPort = atoi(value)
case "master_link_status":
info.MasterLinkStatus = value
case "master_last_io_seconds_ago":
info.MasterLastIO = time.Duration(atoi(value)) * time.Second
case "master_sync_in_progress":
info.MasterSyncInProgress = value == "1"
case "master_sync_left_bytes":
info.MasterSyncLeftBytes, _ = strconv.ParseInt(value, 10, 64)
case "master_sync_last_io_seconds_ago":
info.MasterSyncLastIO = time.Duration(atoi(value)) * time.Second
case "master_link_down_since_seconds":
info.MasterLinkDownSince = time.Duration(atoi(value)) * time.Second
case "connected_slaves":
info.ConnectedSlaves = atoi(value)
}
}
if err := scanner.Err(); err != nil {
return nil, err
}
return &info, nil
} | go | func ParseRedisInfo(s string) (*RedisInfo, error) {
var info RedisInfo
scanner := bufio.NewScanner(strings.NewReader(s))
for scanner.Scan() {
line := scanner.Text()
// Skip blank lines & comment lines
if strings.HasPrefix(line, "#") || line == "" {
continue
}
// Split into key/value.
a := strings.SplitN(line, ":", 2)
if len(a) < 2 {
continue
}
key, value := strings.TrimSpace(a[0]), strings.TrimSpace(a[1])
// Parse into appropriate field.
switch key {
case "role":
info.Role = value
case "master_host":
info.MasterHost = value
case "master_port":
info.MasterPort = atoi(value)
case "master_link_status":
info.MasterLinkStatus = value
case "master_last_io_seconds_ago":
info.MasterLastIO = time.Duration(atoi(value)) * time.Second
case "master_sync_in_progress":
info.MasterSyncInProgress = value == "1"
case "master_sync_left_bytes":
info.MasterSyncLeftBytes, _ = strconv.ParseInt(value, 10, 64)
case "master_sync_last_io_seconds_ago":
info.MasterSyncLastIO = time.Duration(atoi(value)) * time.Second
case "master_link_down_since_seconds":
info.MasterLinkDownSince = time.Duration(atoi(value)) * time.Second
case "connected_slaves":
info.ConnectedSlaves = atoi(value)
}
}
if err := scanner.Err(); err != nil {
return nil, err
}
return &info, nil
} | [
"func",
"ParseRedisInfo",
"(",
"s",
"string",
")",
"(",
"*",
"RedisInfo",
",",
"error",
")",
"{",
"var",
"info",
"RedisInfo",
"\n\n",
"scanner",
":=",
"bufio",
".",
"NewScanner",
"(",
"strings",
".",
"NewReader",
"(",
"s",
")",
")",
"\n",
"for",
"scanner",
".",
"Scan",
"(",
")",
"{",
"line",
":=",
"scanner",
".",
"Text",
"(",
")",
"\n\n",
"// Skip blank lines & comment lines",
"if",
"strings",
".",
"HasPrefix",
"(",
"line",
",",
"\"",
"\"",
")",
"||",
"line",
"==",
"\"",
"\"",
"{",
"continue",
"\n",
"}",
"\n\n",
"// Split into key/value.",
"a",
":=",
"strings",
".",
"SplitN",
"(",
"line",
",",
"\"",
"\"",
",",
"2",
")",
"\n",
"if",
"len",
"(",
"a",
")",
"<",
"2",
"{",
"continue",
"\n",
"}",
"\n",
"key",
",",
"value",
":=",
"strings",
".",
"TrimSpace",
"(",
"a",
"[",
"0",
"]",
")",
",",
"strings",
".",
"TrimSpace",
"(",
"a",
"[",
"1",
"]",
")",
"\n\n",
"// Parse into appropriate field.",
"switch",
"key",
"{",
"case",
"\"",
"\"",
":",
"info",
".",
"Role",
"=",
"value",
"\n",
"case",
"\"",
"\"",
":",
"info",
".",
"MasterHost",
"=",
"value",
"\n",
"case",
"\"",
"\"",
":",
"info",
".",
"MasterPort",
"=",
"atoi",
"(",
"value",
")",
"\n",
"case",
"\"",
"\"",
":",
"info",
".",
"MasterLinkStatus",
"=",
"value",
"\n",
"case",
"\"",
"\"",
":",
"info",
".",
"MasterLastIO",
"=",
"time",
".",
"Duration",
"(",
"atoi",
"(",
"value",
")",
")",
"*",
"time",
".",
"Second",
"\n",
"case",
"\"",
"\"",
":",
"info",
".",
"MasterSyncInProgress",
"=",
"value",
"==",
"\"",
"\"",
"\n",
"case",
"\"",
"\"",
":",
"info",
".",
"MasterSyncLeftBytes",
",",
"_",
"=",
"strconv",
".",
"ParseInt",
"(",
"value",
",",
"10",
",",
"64",
")",
"\n",
"case",
"\"",
"\"",
":",
"info",
".",
"MasterSyncLastIO",
"=",
"time",
".",
"Duration",
"(",
"atoi",
"(",
"value",
")",
")",
"*",
"time",
".",
"Second",
"\n",
"case",
"\"",
"\"",
":",
"info",
".",
"MasterLinkDownSince",
"=",
"time",
".",
"Duration",
"(",
"atoi",
"(",
"value",
")",
")",
"*",
"time",
".",
"Second",
"\n",
"case",
"\"",
"\"",
":",
"info",
".",
"ConnectedSlaves",
"=",
"atoi",
"(",
"value",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"scanner",
".",
"Err",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"info",
",",
"nil",
"\n",
"}"
] | // ParseRedisInfo parses the response from an INFO command. | [
"ParseRedisInfo",
"parses",
"the",
"response",
"from",
"an",
"INFO",
"command",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/appliance/redis/process.go#L426-L474 | train |
flynn/flynn | appliance/redis/process.go | atoi | func atoi(s string) int {
i, _ := strconv.Atoi(s)
return i
} | go | func atoi(s string) int {
i, _ := strconv.Atoi(s)
return i
} | [
"func",
"atoi",
"(",
"s",
"string",
")",
"int",
"{",
"i",
",",
"_",
":=",
"strconv",
".",
"Atoi",
"(",
"s",
")",
"\n",
"return",
"i",
"\n",
"}"
] | // atoi returns the parsed integer value of s. Returns zero if a parse error occurs. | [
"atoi",
"returns",
"the",
"parsed",
"integer",
"value",
"of",
"s",
".",
"Returns",
"zero",
"if",
"a",
"parse",
"error",
"occurs",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/appliance/redis/process.go#L490-L493 | train |
flynn/flynn | gitreceive/receiver/flynn-receive.go | needsDefaultScale | func needsDefaultScale(appID, prevReleaseID string, procs map[string]ct.ProcessType, client controller.Client) bool {
if _, ok := procs["web"]; !ok {
return false
}
if prevReleaseID == "" {
return true
}
_, err := client.GetFormation(appID, prevReleaseID)
return err == controller.ErrNotFound
} | go | func needsDefaultScale(appID, prevReleaseID string, procs map[string]ct.ProcessType, client controller.Client) bool {
if _, ok := procs["web"]; !ok {
return false
}
if prevReleaseID == "" {
return true
}
_, err := client.GetFormation(appID, prevReleaseID)
return err == controller.ErrNotFound
} | [
"func",
"needsDefaultScale",
"(",
"appID",
",",
"prevReleaseID",
"string",
",",
"procs",
"map",
"[",
"string",
"]",
"ct",
".",
"ProcessType",
",",
"client",
"controller",
".",
"Client",
")",
"bool",
"{",
"if",
"_",
",",
"ok",
":=",
"procs",
"[",
"\"",
"\"",
"]",
";",
"!",
"ok",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"prevReleaseID",
"==",
"\"",
"\"",
"{",
"return",
"true",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"client",
".",
"GetFormation",
"(",
"appID",
",",
"prevReleaseID",
")",
"\n",
"return",
"err",
"==",
"controller",
".",
"ErrNotFound",
"\n",
"}"
] | // needsDefaultScale indicates whether a release needs a default scale based on
// whether it has a web process type and either has no previous release or no
// previous scale. | [
"needsDefaultScale",
"indicates",
"whether",
"a",
"release",
"needs",
"a",
"default",
"scale",
"based",
"on",
"whether",
"it",
"has",
"a",
"web",
"process",
"type",
"and",
"either",
"has",
"no",
"previous",
"release",
"or",
"no",
"previous",
"scale",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/gitreceive/receiver/flynn-receive.go#L269-L278 | train |
flynn/flynn | host/update.go | setEnv | func setEnv(cmd *exec.Cmd, envs map[string]string) {
env := os.Environ()
cmd.Env = make([]string, 0, len(env)+len(envs))
outer:
for _, e := range env {
for k := range envs {
if strings.HasPrefix(e, k+"=") {
continue outer
}
}
cmd.Env = append(cmd.Env, e)
}
for k, v := range envs {
cmd.Env = append(cmd.Env, k+"="+v)
}
} | go | func setEnv(cmd *exec.Cmd, envs map[string]string) {
env := os.Environ()
cmd.Env = make([]string, 0, len(env)+len(envs))
outer:
for _, e := range env {
for k := range envs {
if strings.HasPrefix(e, k+"=") {
continue outer
}
}
cmd.Env = append(cmd.Env, e)
}
for k, v := range envs {
cmd.Env = append(cmd.Env, k+"="+v)
}
} | [
"func",
"setEnv",
"(",
"cmd",
"*",
"exec",
".",
"Cmd",
",",
"envs",
"map",
"[",
"string",
"]",
"string",
")",
"{",
"env",
":=",
"os",
".",
"Environ",
"(",
")",
"\n",
"cmd",
".",
"Env",
"=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"env",
")",
"+",
"len",
"(",
"envs",
")",
")",
"\n",
"outer",
":",
"for",
"_",
",",
"e",
":=",
"range",
"env",
"{",
"for",
"k",
":=",
"range",
"envs",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"e",
",",
"k",
"+",
"\"",
"\"",
")",
"{",
"continue",
"outer",
"\n",
"}",
"\n",
"}",
"\n",
"cmd",
".",
"Env",
"=",
"append",
"(",
"cmd",
".",
"Env",
",",
"e",
")",
"\n",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"envs",
"{",
"cmd",
".",
"Env",
"=",
"append",
"(",
"cmd",
".",
"Env",
",",
"k",
"+",
"\"",
"\"",
"+",
"v",
")",
"\n",
"}",
"\n",
"}"
] | // setEnv sets the given environment variables for the command, ensuring they
// are only set once. | [
"setEnv",
"sets",
"the",
"given",
"environment",
"variables",
"for",
"the",
"command",
"ensuring",
"they",
"are",
"only",
"set",
"once",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/host/update.go#L183-L198 | train |
flynn/flynn | host/update.go | Resume | func (c *Child) Resume(buffers host.LogBuffers) error {
if buffers == nil {
buffers = host.LogBuffers{}
}
data, err := json.Marshal(buffers)
if err != nil {
return err
}
if _, err := syscall.Write(c.sock, append(ControlMsgResume, data...)); err != nil {
return err
}
msg := make([]byte, len(ControlMsgOK))
if _, err := syscall.Read(c.sock, msg); err != nil {
return err
}
if !bytes.Equal(msg, ControlMsgOK) {
return fmt.Errorf("unexpected resume message from child: %s", msg)
}
return nil
} | go | func (c *Child) Resume(buffers host.LogBuffers) error {
if buffers == nil {
buffers = host.LogBuffers{}
}
data, err := json.Marshal(buffers)
if err != nil {
return err
}
if _, err := syscall.Write(c.sock, append(ControlMsgResume, data...)); err != nil {
return err
}
msg := make([]byte, len(ControlMsgOK))
if _, err := syscall.Read(c.sock, msg); err != nil {
return err
}
if !bytes.Equal(msg, ControlMsgOK) {
return fmt.Errorf("unexpected resume message from child: %s", msg)
}
return nil
} | [
"func",
"(",
"c",
"*",
"Child",
")",
"Resume",
"(",
"buffers",
"host",
".",
"LogBuffers",
")",
"error",
"{",
"if",
"buffers",
"==",
"nil",
"{",
"buffers",
"=",
"host",
".",
"LogBuffers",
"{",
"}",
"\n",
"}",
"\n",
"data",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"buffers",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"syscall",
".",
"Write",
"(",
"c",
".",
"sock",
",",
"append",
"(",
"ControlMsgResume",
",",
"data",
"...",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"msg",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"ControlMsgOK",
")",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"syscall",
".",
"Read",
"(",
"c",
".",
"sock",
",",
"msg",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"!",
"bytes",
".",
"Equal",
"(",
"msg",
",",
"ControlMsgOK",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"msg",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Resume writes ControlMsgResume to the control socket and waits for a
// ControlMsgOK response | [
"Resume",
"writes",
"ControlMsgResume",
"to",
"the",
"control",
"socket",
"and",
"waits",
"for",
"a",
"ControlMsgOK",
"response"
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/host/update.go#L216-L235 | train |
flynn/flynn | pkg/cluster/client.go | Host | func (c *Client) Host(id string) (*Host, error) {
hosts, err := c.Hosts()
if err != nil {
return nil, err
}
for _, h := range hosts {
if h.ID() == id {
return h, nil
}
}
return nil, fmt.Errorf("cluster: unknown host %q", id)
} | go | func (c *Client) Host(id string) (*Host, error) {
hosts, err := c.Hosts()
if err != nil {
return nil, err
}
for _, h := range hosts {
if h.ID() == id {
return h, nil
}
}
return nil, fmt.Errorf("cluster: unknown host %q", id)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Host",
"(",
"id",
"string",
")",
"(",
"*",
"Host",
",",
"error",
")",
"{",
"hosts",
",",
"err",
":=",
"c",
".",
"Hosts",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"h",
":=",
"range",
"hosts",
"{",
"if",
"h",
".",
"ID",
"(",
")",
"==",
"id",
"{",
"return",
"h",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"id",
")",
"\n",
"}"
] | // Host returns the host identified by id. | [
"Host",
"returns",
"the",
"host",
"identified",
"by",
"id",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/cluster/client.go#L54-L65 | train |
flynn/flynn | pkg/cluster/client.go | Hosts | func (c *Client) Hosts() ([]*Host, error) {
insts, err := c.s.Instances()
if err != nil {
return nil, err
}
hosts := make([]*Host, len(insts))
for i, inst := range insts {
hosts[i] = NewHost(
inst.Meta["id"],
inst.Addr,
c.h,
HostTagsFromMeta(inst.Meta),
)
}
return hosts, nil
} | go | func (c *Client) Hosts() ([]*Host, error) {
insts, err := c.s.Instances()
if err != nil {
return nil, err
}
hosts := make([]*Host, len(insts))
for i, inst := range insts {
hosts[i] = NewHost(
inst.Meta["id"],
inst.Addr,
c.h,
HostTagsFromMeta(inst.Meta),
)
}
return hosts, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Hosts",
"(",
")",
"(",
"[",
"]",
"*",
"Host",
",",
"error",
")",
"{",
"insts",
",",
"err",
":=",
"c",
".",
"s",
".",
"Instances",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"hosts",
":=",
"make",
"(",
"[",
"]",
"*",
"Host",
",",
"len",
"(",
"insts",
")",
")",
"\n",
"for",
"i",
",",
"inst",
":=",
"range",
"insts",
"{",
"hosts",
"[",
"i",
"]",
"=",
"NewHost",
"(",
"inst",
".",
"Meta",
"[",
"\"",
"\"",
"]",
",",
"inst",
".",
"Addr",
",",
"c",
".",
"h",
",",
"HostTagsFromMeta",
"(",
"inst",
".",
"Meta",
")",
",",
")",
"\n",
"}",
"\n",
"return",
"hosts",
",",
"nil",
"\n",
"}"
] | // Hosts returns a list of hosts in the cluster. | [
"Hosts",
"returns",
"a",
"list",
"of",
"hosts",
"in",
"the",
"cluster",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/cluster/client.go#L68-L83 | train |
flynn/flynn | host/types/types.go | Merge | func (x ContainerConfig) Merge(y ContainerConfig) ContainerConfig {
x.TTY = x.TTY || y.TTY
x.Stdin = x.Stdin || y.Stdin
x.Data = x.Data || y.Data
if y.Args != nil {
x.Args = y.Args
}
env := make(map[string]string, len(x.Env)+len(y.Env))
for k, v := range x.Env {
env[k] = v
}
for k, v := range y.Env {
env[k] = v
}
x.Env = env
mounts := make([]Mount, 0, len(x.Mounts)+len(y.Mounts))
mounts = append(mounts, x.Mounts...)
mounts = append(mounts, y.Mounts...)
x.Mounts = mounts
volumes := make([]VolumeBinding, 0, len(x.Volumes)+len(y.Volumes))
volumes = append(volumes, x.Volumes...)
volumes = append(volumes, y.Volumes...)
x.Volumes = volumes
ports := make([]Port, 0, len(x.Ports)+len(y.Ports))
ports = append(ports, x.Ports...)
ports = append(ports, y.Ports...)
x.Ports = ports
if y.WorkingDir != "" {
x.WorkingDir = y.WorkingDir
}
if y.Uid != nil {
x.Uid = y.Uid
}
if y.Gid != nil {
x.Gid = y.Gid
}
x.HostNetwork = x.HostNetwork || y.HostNetwork
x.HostPIDNamespace = x.HostPIDNamespace || y.HostPIDNamespace
return x
} | go | func (x ContainerConfig) Merge(y ContainerConfig) ContainerConfig {
x.TTY = x.TTY || y.TTY
x.Stdin = x.Stdin || y.Stdin
x.Data = x.Data || y.Data
if y.Args != nil {
x.Args = y.Args
}
env := make(map[string]string, len(x.Env)+len(y.Env))
for k, v := range x.Env {
env[k] = v
}
for k, v := range y.Env {
env[k] = v
}
x.Env = env
mounts := make([]Mount, 0, len(x.Mounts)+len(y.Mounts))
mounts = append(mounts, x.Mounts...)
mounts = append(mounts, y.Mounts...)
x.Mounts = mounts
volumes := make([]VolumeBinding, 0, len(x.Volumes)+len(y.Volumes))
volumes = append(volumes, x.Volumes...)
volumes = append(volumes, y.Volumes...)
x.Volumes = volumes
ports := make([]Port, 0, len(x.Ports)+len(y.Ports))
ports = append(ports, x.Ports...)
ports = append(ports, y.Ports...)
x.Ports = ports
if y.WorkingDir != "" {
x.WorkingDir = y.WorkingDir
}
if y.Uid != nil {
x.Uid = y.Uid
}
if y.Gid != nil {
x.Gid = y.Gid
}
x.HostNetwork = x.HostNetwork || y.HostNetwork
x.HostPIDNamespace = x.HostPIDNamespace || y.HostPIDNamespace
return x
} | [
"func",
"(",
"x",
"ContainerConfig",
")",
"Merge",
"(",
"y",
"ContainerConfig",
")",
"ContainerConfig",
"{",
"x",
".",
"TTY",
"=",
"x",
".",
"TTY",
"||",
"y",
".",
"TTY",
"\n",
"x",
".",
"Stdin",
"=",
"x",
".",
"Stdin",
"||",
"y",
".",
"Stdin",
"\n",
"x",
".",
"Data",
"=",
"x",
".",
"Data",
"||",
"y",
".",
"Data",
"\n",
"if",
"y",
".",
"Args",
"!=",
"nil",
"{",
"x",
".",
"Args",
"=",
"y",
".",
"Args",
"\n",
"}",
"\n",
"env",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"len",
"(",
"x",
".",
"Env",
")",
"+",
"len",
"(",
"y",
".",
"Env",
")",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"x",
".",
"Env",
"{",
"env",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"y",
".",
"Env",
"{",
"env",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"x",
".",
"Env",
"=",
"env",
"\n",
"mounts",
":=",
"make",
"(",
"[",
"]",
"Mount",
",",
"0",
",",
"len",
"(",
"x",
".",
"Mounts",
")",
"+",
"len",
"(",
"y",
".",
"Mounts",
")",
")",
"\n",
"mounts",
"=",
"append",
"(",
"mounts",
",",
"x",
".",
"Mounts",
"...",
")",
"\n",
"mounts",
"=",
"append",
"(",
"mounts",
",",
"y",
".",
"Mounts",
"...",
")",
"\n",
"x",
".",
"Mounts",
"=",
"mounts",
"\n",
"volumes",
":=",
"make",
"(",
"[",
"]",
"VolumeBinding",
",",
"0",
",",
"len",
"(",
"x",
".",
"Volumes",
")",
"+",
"len",
"(",
"y",
".",
"Volumes",
")",
")",
"\n",
"volumes",
"=",
"append",
"(",
"volumes",
",",
"x",
".",
"Volumes",
"...",
")",
"\n",
"volumes",
"=",
"append",
"(",
"volumes",
",",
"y",
".",
"Volumes",
"...",
")",
"\n",
"x",
".",
"Volumes",
"=",
"volumes",
"\n",
"ports",
":=",
"make",
"(",
"[",
"]",
"Port",
",",
"0",
",",
"len",
"(",
"x",
".",
"Ports",
")",
"+",
"len",
"(",
"y",
".",
"Ports",
")",
")",
"\n",
"ports",
"=",
"append",
"(",
"ports",
",",
"x",
".",
"Ports",
"...",
")",
"\n",
"ports",
"=",
"append",
"(",
"ports",
",",
"y",
".",
"Ports",
"...",
")",
"\n",
"x",
".",
"Ports",
"=",
"ports",
"\n",
"if",
"y",
".",
"WorkingDir",
"!=",
"\"",
"\"",
"{",
"x",
".",
"WorkingDir",
"=",
"y",
".",
"WorkingDir",
"\n",
"}",
"\n",
"if",
"y",
".",
"Uid",
"!=",
"nil",
"{",
"x",
".",
"Uid",
"=",
"y",
".",
"Uid",
"\n",
"}",
"\n",
"if",
"y",
".",
"Gid",
"!=",
"nil",
"{",
"x",
".",
"Gid",
"=",
"y",
".",
"Gid",
"\n",
"}",
"\n",
"x",
".",
"HostNetwork",
"=",
"x",
".",
"HostNetwork",
"||",
"y",
".",
"HostNetwork",
"\n",
"x",
".",
"HostPIDNamespace",
"=",
"x",
".",
"HostPIDNamespace",
"||",
"y",
".",
"HostPIDNamespace",
"\n",
"return",
"x",
"\n",
"}"
] | // Apply 'y' to 'x', returning a new structure. 'y' trumps. | [
"Apply",
"y",
"to",
"x",
"returning",
"a",
"new",
"structure",
".",
"y",
"trumps",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/host/types/types.go#L122-L161 | train |
flynn/flynn | pkg/cliutil/json.go | DecodeJSONArg | func DecodeJSONArg(name string, v interface{}) error {
var src io.Reader = os.Stdin
if name != "-" && name != "" {
f, err := os.Open(name)
if err != nil {
return err
}
defer f.Close()
src = f
}
return json.NewDecoder(src).Decode(v)
} | go | func DecodeJSONArg(name string, v interface{}) error {
var src io.Reader = os.Stdin
if name != "-" && name != "" {
f, err := os.Open(name)
if err != nil {
return err
}
defer f.Close()
src = f
}
return json.NewDecoder(src).Decode(v)
} | [
"func",
"DecodeJSONArg",
"(",
"name",
"string",
",",
"v",
"interface",
"{",
"}",
")",
"error",
"{",
"var",
"src",
"io",
".",
"Reader",
"=",
"os",
".",
"Stdin",
"\n",
"if",
"name",
"!=",
"\"",
"\"",
"&&",
"name",
"!=",
"\"",
"\"",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n",
"src",
"=",
"f",
"\n",
"}",
"\n",
"return",
"json",
".",
"NewDecoder",
"(",
"src",
")",
".",
"Decode",
"(",
"v",
")",
"\n",
"}"
] | // DecodeJSONArg decodes JSON into v from a file named name, if name is empty or
// "-", stdin is used. | [
"DecodeJSONArg",
"decodes",
"JSON",
"into",
"v",
"from",
"a",
"file",
"named",
"name",
"if",
"name",
"is",
"empty",
"or",
"-",
"stdin",
"is",
"used",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/cliutil/json.go#L11-L22 | train |
flynn/flynn | host/volume/manager/manager.go | LockDB | func (m *Manager) LockDB() error {
m.dbMtx.RLock()
if m.db == nil {
m.dbMtx.RUnlock()
return ErrDBClosed
}
return nil
} | go | func (m *Manager) LockDB() error {
m.dbMtx.RLock()
if m.db == nil {
m.dbMtx.RUnlock()
return ErrDBClosed
}
return nil
} | [
"func",
"(",
"m",
"*",
"Manager",
")",
"LockDB",
"(",
")",
"error",
"{",
"m",
".",
"dbMtx",
".",
"RLock",
"(",
")",
"\n",
"if",
"m",
".",
"db",
"==",
"nil",
"{",
"m",
".",
"dbMtx",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"ErrDBClosed",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // LockDB acquires a read lock on the DB mutex so that it cannot be closed
// until the caller has finished performing actions which will lead to changes
// being persisted to the DB.
//
// For example, creating a volume first delegates to the provider to create the
// volume and then persists to the DB, but if the DB is closed in that time
// then the volume state will be lost.
//
// ErrDBClosed is returned if the DB is already closed so API requests will
// fail before any actions are performed. | [
"LockDB",
"acquires",
"a",
"read",
"lock",
"on",
"the",
"DB",
"mutex",
"so",
"that",
"it",
"cannot",
"be",
"closed",
"until",
"the",
"caller",
"has",
"finished",
"performing",
"actions",
"which",
"will",
"lead",
"to",
"changes",
"being",
"persisted",
"to",
"the",
"DB",
".",
"For",
"example",
"creating",
"a",
"volume",
"first",
"delegates",
"to",
"the",
"provider",
"to",
"create",
"the",
"volume",
"and",
"then",
"persists",
"to",
"the",
"DB",
"but",
"if",
"the",
"DB",
"is",
"closed",
"in",
"that",
"time",
"then",
"the",
"volume",
"state",
"will",
"be",
"lost",
".",
"ErrDBClosed",
"is",
"returned",
"if",
"the",
"DB",
"is",
"already",
"closed",
"so",
"API",
"requests",
"will",
"fail",
"before",
"any",
"actions",
"are",
"performed",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/host/volume/manager/manager.go#L126-L133 | train |
flynn/flynn | host/volume/manager/manager.go | persistVolume | func (m *Manager) persistVolume(tx *bolt.Tx, vol volume.Volume) error {
// Save the general volume info
volumesBucket := tx.Bucket([]byte("volumes"))
id := vol.Info().ID
k := []byte(id)
_, volExists := m.volumes[id]
if !volExists {
volumesBucket.Delete(k)
} else {
b, err := json.Marshal(vol.Info())
if err != nil {
return fmt.Errorf("failed to serialize volume info: %s", err)
}
err = volumesBucket.Put(k, b)
if err != nil {
return fmt.Errorf("could not persist volume info to boltdb: %s", err)
}
}
// Save any provider-specific metadata associated with the volume.
// These are saved per-provider since the deserialization is also only defined per-provider implementation.
providerBucket, err := m.getProviderBucket(tx, m.providerIDs[vol.Provider()])
if err != nil {
return fmt.Errorf("could not persist provider volume info to boltdb: %s", err)
}
providerVolumesBucket := providerBucket.Bucket([]byte("volumes"))
if !volExists {
providerVolumesBucket.Delete(k)
} else {
b, err := vol.Provider().MarshalVolumeState(id)
if err != nil {
return fmt.Errorf("failed to serialize provider volume info: %s", err)
}
err = providerVolumesBucket.Put(k, b)
if err != nil {
return fmt.Errorf("could not persist provider volume info to boltdb: %s", err)
}
}
return nil
} | go | func (m *Manager) persistVolume(tx *bolt.Tx, vol volume.Volume) error {
// Save the general volume info
volumesBucket := tx.Bucket([]byte("volumes"))
id := vol.Info().ID
k := []byte(id)
_, volExists := m.volumes[id]
if !volExists {
volumesBucket.Delete(k)
} else {
b, err := json.Marshal(vol.Info())
if err != nil {
return fmt.Errorf("failed to serialize volume info: %s", err)
}
err = volumesBucket.Put(k, b)
if err != nil {
return fmt.Errorf("could not persist volume info to boltdb: %s", err)
}
}
// Save any provider-specific metadata associated with the volume.
// These are saved per-provider since the deserialization is also only defined per-provider implementation.
providerBucket, err := m.getProviderBucket(tx, m.providerIDs[vol.Provider()])
if err != nil {
return fmt.Errorf("could not persist provider volume info to boltdb: %s", err)
}
providerVolumesBucket := providerBucket.Bucket([]byte("volumes"))
if !volExists {
providerVolumesBucket.Delete(k)
} else {
b, err := vol.Provider().MarshalVolumeState(id)
if err != nil {
return fmt.Errorf("failed to serialize provider volume info: %s", err)
}
err = providerVolumesBucket.Put(k, b)
if err != nil {
return fmt.Errorf("could not persist provider volume info to boltdb: %s", err)
}
}
return nil
} | [
"func",
"(",
"m",
"*",
"Manager",
")",
"persistVolume",
"(",
"tx",
"*",
"bolt",
".",
"Tx",
",",
"vol",
"volume",
".",
"Volume",
")",
"error",
"{",
"// Save the general volume info",
"volumesBucket",
":=",
"tx",
".",
"Bucket",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
")",
"\n",
"id",
":=",
"vol",
".",
"Info",
"(",
")",
".",
"ID",
"\n",
"k",
":=",
"[",
"]",
"byte",
"(",
"id",
")",
"\n",
"_",
",",
"volExists",
":=",
"m",
".",
"volumes",
"[",
"id",
"]",
"\n",
"if",
"!",
"volExists",
"{",
"volumesBucket",
".",
"Delete",
"(",
"k",
")",
"\n",
"}",
"else",
"{",
"b",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"vol",
".",
"Info",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"err",
"=",
"volumesBucket",
".",
"Put",
"(",
"k",
",",
"b",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"// Save any provider-specific metadata associated with the volume.",
"// These are saved per-provider since the deserialization is also only defined per-provider implementation.",
"providerBucket",
",",
"err",
":=",
"m",
".",
"getProviderBucket",
"(",
"tx",
",",
"m",
".",
"providerIDs",
"[",
"vol",
".",
"Provider",
"(",
")",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"providerVolumesBucket",
":=",
"providerBucket",
".",
"Bucket",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
")",
"\n",
"if",
"!",
"volExists",
"{",
"providerVolumesBucket",
".",
"Delete",
"(",
"k",
")",
"\n",
"}",
"else",
"{",
"b",
",",
"err",
":=",
"vol",
".",
"Provider",
"(",
")",
".",
"MarshalVolumeState",
"(",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"err",
"=",
"providerVolumesBucket",
".",
"Put",
"(",
"k",
",",
"b",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Called to sync changes to disk when a volume is updated | [
"Called",
"to",
"sync",
"changes",
"to",
"disk",
"when",
"a",
"volume",
"is",
"updated"
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/host/volume/manager/manager.go#L488-L526 | train |
flynn/flynn | flannel/backend/vxlan/device.go | setAddr4 | func setAddr4(link *netlink.Vxlan, ipn *net.IPNet) error {
addrs, err := netlink.AddrList(link, syscall.AF_INET)
if err != nil {
return err
}
addr := netlink.Addr{IPNet: ipn}
existing := false
for _, old := range addrs {
if old.IPNet.String() == addr.IPNet.String() {
existing = true
continue
}
if err = netlink.AddrDel(link, &old); err != nil {
return fmt.Errorf("failed to delete IPv4 addr %s from %s", old.String(), link.Attrs().Name)
}
}
if !existing {
if err = netlink.AddrAdd(link, &addr); err != nil {
return fmt.Errorf("failed to add IP address %s to %s: %s", ipn.String(), link.Attrs().Name, err)
}
}
return nil
} | go | func setAddr4(link *netlink.Vxlan, ipn *net.IPNet) error {
addrs, err := netlink.AddrList(link, syscall.AF_INET)
if err != nil {
return err
}
addr := netlink.Addr{IPNet: ipn}
existing := false
for _, old := range addrs {
if old.IPNet.String() == addr.IPNet.String() {
existing = true
continue
}
if err = netlink.AddrDel(link, &old); err != nil {
return fmt.Errorf("failed to delete IPv4 addr %s from %s", old.String(), link.Attrs().Name)
}
}
if !existing {
if err = netlink.AddrAdd(link, &addr); err != nil {
return fmt.Errorf("failed to add IP address %s to %s: %s", ipn.String(), link.Attrs().Name, err)
}
}
return nil
} | [
"func",
"setAddr4",
"(",
"link",
"*",
"netlink",
".",
"Vxlan",
",",
"ipn",
"*",
"net",
".",
"IPNet",
")",
"error",
"{",
"addrs",
",",
"err",
":=",
"netlink",
".",
"AddrList",
"(",
"link",
",",
"syscall",
".",
"AF_INET",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"addr",
":=",
"netlink",
".",
"Addr",
"{",
"IPNet",
":",
"ipn",
"}",
"\n",
"existing",
":=",
"false",
"\n",
"for",
"_",
",",
"old",
":=",
"range",
"addrs",
"{",
"if",
"old",
".",
"IPNet",
".",
"String",
"(",
")",
"==",
"addr",
".",
"IPNet",
".",
"String",
"(",
")",
"{",
"existing",
"=",
"true",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"err",
"=",
"netlink",
".",
"AddrDel",
"(",
"link",
",",
"&",
"old",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"old",
".",
"String",
"(",
")",
",",
"link",
".",
"Attrs",
"(",
")",
".",
"Name",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"!",
"existing",
"{",
"if",
"err",
"=",
"netlink",
".",
"AddrAdd",
"(",
"link",
",",
"&",
"addr",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"ipn",
".",
"String",
"(",
")",
",",
"link",
".",
"Attrs",
"(",
")",
".",
"Name",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // sets IP4 addr on link removing any existing ones first | [
"sets",
"IP4",
"addr",
"on",
"link",
"removing",
"any",
"existing",
"ones",
"first"
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/flannel/backend/vxlan/device.go#L231-L256 | train |
flynn/flynn | pkg/syslog/rfc5424/parser.go | Parse | func Parse(buf []byte) (*Message, error) {
msg := &Message{}
return msg, parse(buf, msg)
} | go | func Parse(buf []byte) (*Message, error) {
msg := &Message{}
return msg, parse(buf, msg)
} | [
"func",
"Parse",
"(",
"buf",
"[",
"]",
"byte",
")",
"(",
"*",
"Message",
",",
"error",
")",
"{",
"msg",
":=",
"&",
"Message",
"{",
"}",
"\n",
"return",
"msg",
",",
"parse",
"(",
"buf",
",",
"msg",
")",
"\n",
"}"
] | // Parse parses RFC5424 syslog messages into a Message. | [
"Parse",
"parses",
"RFC5424",
"syslog",
"messages",
"into",
"a",
"Message",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/syslog/rfc5424/parser.go#L10-L13 | train |
flynn/flynn | logaggregator/buffer/buffer.go | Add | func (b *Buffer) Add(m *rfc5424.Message) error {
b.mu.Lock()
defer b.mu.Unlock()
if b.length == -1 {
return errors.New("buffer closed")
}
if b.head == nil {
b.head = &message{Message: *m}
b.tail = b.head
} else {
// iterate from newest to oldest through messages to find position
// to insert new message
for other := b.tail; other != nil; other = other.prev {
if m.Timestamp.Equal(other.Timestamp) && bytes.Equal(m.StructuredData, other.StructuredData) {
// duplicate log line
return nil
}
if m.Timestamp.Before(other.Timestamp) {
if other.prev == nil {
// insert before other at head
other.prev = &message{Message: *m, next: other}
b.head = other.prev
break
} else {
continue
}
}
msg := &message{Message: *m, prev: other}
if other.next != nil {
// insert between other and other.next
other.next.prev = msg
msg.next = other.next
} else {
// insert at tail
b.tail = msg
}
other.next = msg
break
}
}
if b.length < b.capacity {
// buffer not yet full
b.length++
} else {
// at capacity, remove head
b.head = b.head.next
b.head.prev = nil
}
for msgc := range b.subs {
select {
case msgc <- m:
default: // chan is full, drop this message to it
}
}
return nil
} | go | func (b *Buffer) Add(m *rfc5424.Message) error {
b.mu.Lock()
defer b.mu.Unlock()
if b.length == -1 {
return errors.New("buffer closed")
}
if b.head == nil {
b.head = &message{Message: *m}
b.tail = b.head
} else {
// iterate from newest to oldest through messages to find position
// to insert new message
for other := b.tail; other != nil; other = other.prev {
if m.Timestamp.Equal(other.Timestamp) && bytes.Equal(m.StructuredData, other.StructuredData) {
// duplicate log line
return nil
}
if m.Timestamp.Before(other.Timestamp) {
if other.prev == nil {
// insert before other at head
other.prev = &message{Message: *m, next: other}
b.head = other.prev
break
} else {
continue
}
}
msg := &message{Message: *m, prev: other}
if other.next != nil {
// insert between other and other.next
other.next.prev = msg
msg.next = other.next
} else {
// insert at tail
b.tail = msg
}
other.next = msg
break
}
}
if b.length < b.capacity {
// buffer not yet full
b.length++
} else {
// at capacity, remove head
b.head = b.head.next
b.head.prev = nil
}
for msgc := range b.subs {
select {
case msgc <- m:
default: // chan is full, drop this message to it
}
}
return nil
} | [
"func",
"(",
"b",
"*",
"Buffer",
")",
"Add",
"(",
"m",
"*",
"rfc5424",
".",
"Message",
")",
"error",
"{",
"b",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"b",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"b",
".",
"length",
"==",
"-",
"1",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"b",
".",
"head",
"==",
"nil",
"{",
"b",
".",
"head",
"=",
"&",
"message",
"{",
"Message",
":",
"*",
"m",
"}",
"\n",
"b",
".",
"tail",
"=",
"b",
".",
"head",
"\n",
"}",
"else",
"{",
"// iterate from newest to oldest through messages to find position",
"// to insert new message",
"for",
"other",
":=",
"b",
".",
"tail",
";",
"other",
"!=",
"nil",
";",
"other",
"=",
"other",
".",
"prev",
"{",
"if",
"m",
".",
"Timestamp",
".",
"Equal",
"(",
"other",
".",
"Timestamp",
")",
"&&",
"bytes",
".",
"Equal",
"(",
"m",
".",
"StructuredData",
",",
"other",
".",
"StructuredData",
")",
"{",
"// duplicate log line",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"m",
".",
"Timestamp",
".",
"Before",
"(",
"other",
".",
"Timestamp",
")",
"{",
"if",
"other",
".",
"prev",
"==",
"nil",
"{",
"// insert before other at head",
"other",
".",
"prev",
"=",
"&",
"message",
"{",
"Message",
":",
"*",
"m",
",",
"next",
":",
"other",
"}",
"\n",
"b",
".",
"head",
"=",
"other",
".",
"prev",
"\n",
"break",
"\n",
"}",
"else",
"{",
"continue",
"\n",
"}",
"\n",
"}",
"\n",
"msg",
":=",
"&",
"message",
"{",
"Message",
":",
"*",
"m",
",",
"prev",
":",
"other",
"}",
"\n",
"if",
"other",
".",
"next",
"!=",
"nil",
"{",
"// insert between other and other.next",
"other",
".",
"next",
".",
"prev",
"=",
"msg",
"\n",
"msg",
".",
"next",
"=",
"other",
".",
"next",
"\n",
"}",
"else",
"{",
"// insert at tail",
"b",
".",
"tail",
"=",
"msg",
"\n",
"}",
"\n",
"other",
".",
"next",
"=",
"msg",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"b",
".",
"length",
"<",
"b",
".",
"capacity",
"{",
"// buffer not yet full",
"b",
".",
"length",
"++",
"\n",
"}",
"else",
"{",
"// at capacity, remove head",
"b",
".",
"head",
"=",
"b",
".",
"head",
".",
"next",
"\n",
"b",
".",
"head",
".",
"prev",
"=",
"nil",
"\n",
"}",
"\n\n",
"for",
"msgc",
":=",
"range",
"b",
".",
"subs",
"{",
"select",
"{",
"case",
"msgc",
"<-",
"m",
":",
"default",
":",
"// chan is full, drop this message to it",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Add adds an element to the Buffer. If the Buffer is already full, it removes
// an existing message. | [
"Add",
"adds",
"an",
"element",
"to",
"the",
"Buffer",
".",
"If",
"the",
"Buffer",
"is",
"already",
"full",
"it",
"removes",
"an",
"existing",
"message",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/logaggregator/buffer/buffer.go#L50-L108 | train |
flynn/flynn | logaggregator/buffer/buffer.go | Read | func (b *Buffer) Read() []*rfc5424.Message {
b.mu.RLock()
defer b.mu.RUnlock()
return b.read()
} | go | func (b *Buffer) Read() []*rfc5424.Message {
b.mu.RLock()
defer b.mu.RUnlock()
return b.read()
} | [
"func",
"(",
"b",
"*",
"Buffer",
")",
"Read",
"(",
")",
"[",
"]",
"*",
"rfc5424",
".",
"Message",
"{",
"b",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"b",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"b",
".",
"read",
"(",
")",
"\n",
"}"
] | // Read returns a copied slice with the contents of the Buffer. It does not
// modify the underlying buffer in any way. You are free to modify the
// returned slice without affecting Buffer, though modifying the individual
// elements in the result will also modify those elements in the Buffer. | [
"Read",
"returns",
"a",
"copied",
"slice",
"with",
"the",
"contents",
"of",
"the",
"Buffer",
".",
"It",
"does",
"not",
"modify",
"the",
"underlying",
"buffer",
"in",
"any",
"way",
".",
"You",
"are",
"free",
"to",
"modify",
"the",
"returned",
"slice",
"without",
"affecting",
"Buffer",
"though",
"modifying",
"the",
"individual",
"elements",
"in",
"the",
"result",
"will",
"also",
"modify",
"those",
"elements",
"in",
"the",
"Buffer",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/logaggregator/buffer/buffer.go#L124-L128 | train |
flynn/flynn | logaggregator/buffer/buffer.go | ReadAndSubscribe | func (b *Buffer) ReadAndSubscribe(msgc chan<- *rfc5424.Message, donec <-chan struct{}) []*rfc5424.Message {
b.mu.RLock()
defer b.mu.RUnlock()
b.subscribe(msgc, donec)
return b.read()
} | go | func (b *Buffer) ReadAndSubscribe(msgc chan<- *rfc5424.Message, donec <-chan struct{}) []*rfc5424.Message {
b.mu.RLock()
defer b.mu.RUnlock()
b.subscribe(msgc, donec)
return b.read()
} | [
"func",
"(",
"b",
"*",
"Buffer",
")",
"ReadAndSubscribe",
"(",
"msgc",
"chan",
"<-",
"*",
"rfc5424",
".",
"Message",
",",
"donec",
"<-",
"chan",
"struct",
"{",
"}",
")",
"[",
"]",
"*",
"rfc5424",
".",
"Message",
"{",
"b",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"b",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n\n",
"b",
".",
"subscribe",
"(",
"msgc",
",",
"donec",
")",
"\n",
"return",
"b",
".",
"read",
"(",
")",
"\n",
"}"
] | // ReadAndSubscribe returns all buffered messages just like Read, and also
// returns a channel that will stream new messages as they arrive. | [
"ReadAndSubscribe",
"returns",
"all",
"buffered",
"messages",
"just",
"like",
"Read",
"and",
"also",
"returns",
"a",
"channel",
"that",
"will",
"stream",
"new",
"messages",
"as",
"they",
"arrive",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/logaggregator/buffer/buffer.go#L132-L138 | train |
flynn/flynn | logaggregator/buffer/buffer.go | Subscribe | func (b *Buffer) Subscribe(msgc chan<- *rfc5424.Message, donec <-chan struct{}) {
b.mu.RLock()
defer b.mu.RUnlock()
b.subscribe(msgc, donec)
} | go | func (b *Buffer) Subscribe(msgc chan<- *rfc5424.Message, donec <-chan struct{}) {
b.mu.RLock()
defer b.mu.RUnlock()
b.subscribe(msgc, donec)
} | [
"func",
"(",
"b",
"*",
"Buffer",
")",
"Subscribe",
"(",
"msgc",
"chan",
"<-",
"*",
"rfc5424",
".",
"Message",
",",
"donec",
"<-",
"chan",
"struct",
"{",
"}",
")",
"{",
"b",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"b",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n\n",
"b",
".",
"subscribe",
"(",
"msgc",
",",
"donec",
")",
"\n",
"}"
] | // Subscribe returns a channel that sends all future messages added to the
// Buffer. The returned channel is buffered, and any attempts to send new
// messages to the channel will drop messages if the channel is full.
//
// The caller closes the donec channel to stop receiving messages. | [
"Subscribe",
"returns",
"a",
"channel",
"that",
"sends",
"all",
"future",
"messages",
"added",
"to",
"the",
"Buffer",
".",
"The",
"returned",
"channel",
"is",
"buffered",
"and",
"any",
"attempts",
"to",
"send",
"new",
"messages",
"to",
"the",
"channel",
"will",
"drop",
"messages",
"if",
"the",
"channel",
"is",
"full",
".",
"The",
"caller",
"closes",
"the",
"donec",
"channel",
"to",
"stop",
"receiving",
"messages",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/logaggregator/buffer/buffer.go#L145-L150 | train |
flynn/flynn | logaggregator/buffer/buffer.go | read | func (b *Buffer) read() []*rfc5424.Message {
if b.length == -1 {
return nil
}
buf := make([]*rfc5424.Message, 0, b.length)
msg := b.head
for msg != nil {
buf = append(buf, &msg.Message)
msg = msg.next
}
return buf
} | go | func (b *Buffer) read() []*rfc5424.Message {
if b.length == -1 {
return nil
}
buf := make([]*rfc5424.Message, 0, b.length)
msg := b.head
for msg != nil {
buf = append(buf, &msg.Message)
msg = msg.next
}
return buf
} | [
"func",
"(",
"b",
"*",
"Buffer",
")",
"read",
"(",
")",
"[",
"]",
"*",
"rfc5424",
".",
"Message",
"{",
"if",
"b",
".",
"length",
"==",
"-",
"1",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"buf",
":=",
"make",
"(",
"[",
"]",
"*",
"rfc5424",
".",
"Message",
",",
"0",
",",
"b",
".",
"length",
")",
"\n",
"msg",
":=",
"b",
".",
"head",
"\n",
"for",
"msg",
"!=",
"nil",
"{",
"buf",
"=",
"append",
"(",
"buf",
",",
"&",
"msg",
".",
"Message",
")",
"\n",
"msg",
"=",
"msg",
".",
"next",
"\n",
"}",
"\n",
"return",
"buf",
"\n",
"}"
] | // _read expects b.mu to already be locked | [
"_read",
"expects",
"b",
".",
"mu",
"to",
"already",
"be",
"locked"
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/logaggregator/buffer/buffer.go#L153-L165 | train |
flynn/flynn | logaggregator/buffer/buffer.go | subscribe | func (b *Buffer) subscribe(msgc chan<- *rfc5424.Message, donec <-chan struct{}) {
b.subs[msgc] = struct{}{}
go func() {
select {
case <-donec:
case <-b.donec:
}
b.mu.Lock()
defer b.mu.Unlock()
delete(b.subs, msgc)
close(msgc)
}()
} | go | func (b *Buffer) subscribe(msgc chan<- *rfc5424.Message, donec <-chan struct{}) {
b.subs[msgc] = struct{}{}
go func() {
select {
case <-donec:
case <-b.donec:
}
b.mu.Lock()
defer b.mu.Unlock()
delete(b.subs, msgc)
close(msgc)
}()
} | [
"func",
"(",
"b",
"*",
"Buffer",
")",
"subscribe",
"(",
"msgc",
"chan",
"<-",
"*",
"rfc5424",
".",
"Message",
",",
"donec",
"<-",
"chan",
"struct",
"{",
"}",
")",
"{",
"b",
".",
"subs",
"[",
"msgc",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n\n",
"go",
"func",
"(",
")",
"{",
"select",
"{",
"case",
"<-",
"donec",
":",
"case",
"<-",
"b",
".",
"donec",
":",
"}",
"\n\n",
"b",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"b",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"delete",
"(",
"b",
".",
"subs",
",",
"msgc",
")",
"\n",
"close",
"(",
"msgc",
")",
"\n",
"}",
"(",
")",
"\n",
"}"
] | // _subscribe assumes b.mu is already locked | [
"_subscribe",
"assumes",
"b",
".",
"mu",
"is",
"already",
"locked"
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/logaggregator/buffer/buffer.go#L168-L183 | train |
flynn/flynn | controller/client/client.go | NewClient | func NewClient(uri, key string) (Client, error) {
return NewClientWithHTTP(uri, key, httphelper.RetryClient)
} | go | func NewClient(uri, key string) (Client, error) {
return NewClientWithHTTP(uri, key, httphelper.RetryClient)
} | [
"func",
"NewClient",
"(",
"uri",
",",
"key",
"string",
")",
"(",
"Client",
",",
"error",
")",
"{",
"return",
"NewClientWithHTTP",
"(",
"uri",
",",
"key",
",",
"httphelper",
".",
"RetryClient",
")",
"\n",
"}"
] | // NewClient creates a new Client pointing at uri and using key for
// authentication. | [
"NewClient",
"creates",
"a",
"new",
"Client",
"pointing",
"at",
"uri",
"and",
"using",
"key",
"for",
"authentication",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/controller/client/client.go#L130-L132 | train |
flynn/flynn | controller/client/client.go | NewClientWithConfig | func NewClientWithConfig(uri, key string, config Config) (Client, error) {
if config.Pin == nil {
return NewClient(uri, key)
}
d := &pinned.Config{Pin: config.Pin}
if config.Domain != "" {
d.Config = &tls.Config{ServerName: config.Domain}
}
httpClient := &http.Client{Transport: &http.Transport{DialTLS: d.Dial}}
c := newClient(key, uri, httpClient)
c.Host = config.Domain
c.HijackDial = d.Dial
return c, nil
} | go | func NewClientWithConfig(uri, key string, config Config) (Client, error) {
if config.Pin == nil {
return NewClient(uri, key)
}
d := &pinned.Config{Pin: config.Pin}
if config.Domain != "" {
d.Config = &tls.Config{ServerName: config.Domain}
}
httpClient := &http.Client{Transport: &http.Transport{DialTLS: d.Dial}}
c := newClient(key, uri, httpClient)
c.Host = config.Domain
c.HijackDial = d.Dial
return c, nil
} | [
"func",
"NewClientWithConfig",
"(",
"uri",
",",
"key",
"string",
",",
"config",
"Config",
")",
"(",
"Client",
",",
"error",
")",
"{",
"if",
"config",
".",
"Pin",
"==",
"nil",
"{",
"return",
"NewClient",
"(",
"uri",
",",
"key",
")",
"\n",
"}",
"\n",
"d",
":=",
"&",
"pinned",
".",
"Config",
"{",
"Pin",
":",
"config",
".",
"Pin",
"}",
"\n",
"if",
"config",
".",
"Domain",
"!=",
"\"",
"\"",
"{",
"d",
".",
"Config",
"=",
"&",
"tls",
".",
"Config",
"{",
"ServerName",
":",
"config",
".",
"Domain",
"}",
"\n",
"}",
"\n",
"httpClient",
":=",
"&",
"http",
".",
"Client",
"{",
"Transport",
":",
"&",
"http",
".",
"Transport",
"{",
"DialTLS",
":",
"d",
".",
"Dial",
"}",
"}",
"\n",
"c",
":=",
"newClient",
"(",
"key",
",",
"uri",
",",
"httpClient",
")",
"\n",
"c",
".",
"Host",
"=",
"config",
".",
"Domain",
"\n",
"c",
".",
"HijackDial",
"=",
"d",
".",
"Dial",
"\n",
"return",
"c",
",",
"nil",
"\n",
"}"
] | // NewClientWithConfig acts like NewClient, but supports custom configuration. | [
"NewClientWithConfig",
"acts",
"like",
"NewClient",
"but",
"supports",
"custom",
"configuration",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/controller/client/client.go#L146-L159 | train |
flynn/flynn | pkg/rpcplus/jsonrpc/server.go | NewServerCodec | func NewServerCodec(conn io.ReadWriteCloser) rpc.ServerCodec {
return &serverCodec{
dec: json.NewDecoder(conn),
enc: json.NewEncoder(conn),
c: conn,
pending: make(map[uint64]*json.RawMessage),
}
} | go | func NewServerCodec(conn io.ReadWriteCloser) rpc.ServerCodec {
return &serverCodec{
dec: json.NewDecoder(conn),
enc: json.NewEncoder(conn),
c: conn,
pending: make(map[uint64]*json.RawMessage),
}
} | [
"func",
"NewServerCodec",
"(",
"conn",
"io",
".",
"ReadWriteCloser",
")",
"rpc",
".",
"ServerCodec",
"{",
"return",
"&",
"serverCodec",
"{",
"dec",
":",
"json",
".",
"NewDecoder",
"(",
"conn",
")",
",",
"enc",
":",
"json",
".",
"NewEncoder",
"(",
"conn",
")",
",",
"c",
":",
"conn",
",",
"pending",
":",
"make",
"(",
"map",
"[",
"uint64",
"]",
"*",
"json",
".",
"RawMessage",
")",
",",
"}",
"\n",
"}"
] | // NewServerCodec returns a new rpc.ServerCodec using JSON-RPC on conn. | [
"NewServerCodec",
"returns",
"a",
"new",
"rpc",
".",
"ServerCodec",
"using",
"JSON",
"-",
"RPC",
"on",
"conn",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/rpcplus/jsonrpc/server.go#L36-L43 | train |
flynn/flynn | pkg/rpcplus/jsonrpc/server.go | ServeConnWithContext | func ServeConnWithContext(conn io.ReadWriteCloser, context interface{}) {
rpc.ServeCodecWithContext(NewServerCodec(conn), context)
} | go | func ServeConnWithContext(conn io.ReadWriteCloser, context interface{}) {
rpc.ServeCodecWithContext(NewServerCodec(conn), context)
} | [
"func",
"ServeConnWithContext",
"(",
"conn",
"io",
".",
"ReadWriteCloser",
",",
"context",
"interface",
"{",
"}",
")",
"{",
"rpc",
".",
"ServeCodecWithContext",
"(",
"NewServerCodec",
"(",
"conn",
")",
",",
"context",
")",
"\n",
"}"
] | // ServeConnWithContext is like ServeConn but it allows to pass a
// connection context to the RPC methods. | [
"ServeConnWithContext",
"is",
"like",
"ServeConn",
"but",
"it",
"allows",
"to",
"pass",
"a",
"connection",
"context",
"to",
"the",
"RPC",
"methods",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/rpcplus/jsonrpc/server.go#L142-L144 | train |
flynn/flynn | host/state.go | CloseDB | func (s *State) CloseDB() error {
s.dbCond.L.Lock()
defer s.dbCond.L.Unlock()
if s.stateDB == nil {
return nil
}
for s.dbUsers > 0 {
s.dbCond.Wait()
}
if err := s.stateDB.Close(); err != nil {
return err
}
s.stateDB = nil
return nil
} | go | func (s *State) CloseDB() error {
s.dbCond.L.Lock()
defer s.dbCond.L.Unlock()
if s.stateDB == nil {
return nil
}
for s.dbUsers > 0 {
s.dbCond.Wait()
}
if err := s.stateDB.Close(); err != nil {
return err
}
s.stateDB = nil
return nil
} | [
"func",
"(",
"s",
"*",
"State",
")",
"CloseDB",
"(",
")",
"error",
"{",
"s",
".",
"dbCond",
".",
"L",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"dbCond",
".",
"L",
".",
"Unlock",
"(",
")",
"\n",
"if",
"s",
".",
"stateDB",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"for",
"s",
".",
"dbUsers",
">",
"0",
"{",
"s",
".",
"dbCond",
".",
"Wait",
"(",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"s",
".",
"stateDB",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"s",
".",
"stateDB",
"=",
"nil",
"\n",
"return",
"nil",
"\n",
"}"
] | // CloseDB closes the persistence DB, waiting for the state to be fully
// released first. | [
"CloseDB",
"closes",
"the",
"persistence",
"DB",
"waiting",
"for",
"the",
"state",
"to",
"be",
"fully",
"released",
"first",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/host/state.go#L199-L213 | train |
flynn/flynn | host/state.go | Acquire | func (s *State) Acquire() error {
s.dbCond.L.Lock()
defer s.dbCond.L.Unlock()
if s.stateDB == nil {
return ErrDBClosed
}
s.dbUsers++
return nil
} | go | func (s *State) Acquire() error {
s.dbCond.L.Lock()
defer s.dbCond.L.Unlock()
if s.stateDB == nil {
return ErrDBClosed
}
s.dbUsers++
return nil
} | [
"func",
"(",
"s",
"*",
"State",
")",
"Acquire",
"(",
")",
"error",
"{",
"s",
".",
"dbCond",
".",
"L",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"dbCond",
".",
"L",
".",
"Unlock",
"(",
")",
"\n",
"if",
"s",
".",
"stateDB",
"==",
"nil",
"{",
"return",
"ErrDBClosed",
"\n",
"}",
"\n",
"s",
".",
"dbUsers",
"++",
"\n",
"return",
"nil",
"\n",
"}"
] | // Acquire acquires the state for use by incrementing s.dbUsers, which prevents
// the state DB being closed until the caller has finished performing actions
// which will lead to changes being persisted to the DB.
//
// For example, running a job starts the job and then persists the change of
// state, but if the DB is closed in that time then the state of the running
// job will be lost.
//
// ErrDBClosed is returned if the DB is already closed so API requests will
// fail before any actions are performed. | [
"Acquire",
"acquires",
"the",
"state",
"for",
"use",
"by",
"incrementing",
"s",
".",
"dbUsers",
"which",
"prevents",
"the",
"state",
"DB",
"being",
"closed",
"until",
"the",
"caller",
"has",
"finished",
"performing",
"actions",
"which",
"will",
"lead",
"to",
"changes",
"being",
"persisted",
"to",
"the",
"DB",
".",
"For",
"example",
"running",
"a",
"job",
"starts",
"the",
"job",
"and",
"then",
"persists",
"the",
"change",
"of",
"state",
"but",
"if",
"the",
"DB",
"is",
"closed",
"in",
"that",
"time",
"then",
"the",
"state",
"of",
"the",
"running",
"job",
"will",
"be",
"lost",
".",
"ErrDBClosed",
"is",
"returned",
"if",
"the",
"DB",
"is",
"already",
"closed",
"so",
"API",
"requests",
"will",
"fail",
"before",
"any",
"actions",
"are",
"performed",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/host/state.go#L227-L235 | train |
flynn/flynn | host/state.go | Release | func (s *State) Release() {
s.dbCond.L.Lock()
defer s.dbCond.L.Unlock()
s.dbUsers--
if s.dbUsers == 0 {
s.dbCond.Broadcast()
}
} | go | func (s *State) Release() {
s.dbCond.L.Lock()
defer s.dbCond.L.Unlock()
s.dbUsers--
if s.dbUsers == 0 {
s.dbCond.Broadcast()
}
} | [
"func",
"(",
"s",
"*",
"State",
")",
"Release",
"(",
")",
"{",
"s",
".",
"dbCond",
".",
"L",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"dbCond",
".",
"L",
".",
"Unlock",
"(",
")",
"\n",
"s",
".",
"dbUsers",
"--",
"\n",
"if",
"s",
".",
"dbUsers",
"==",
"0",
"{",
"s",
".",
"dbCond",
".",
"Broadcast",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // Release releases the state by decrementing s.dbUsers, broadcasting the
// condition variable if no users are left to wake CloseDB. | [
"Release",
"releases",
"the",
"state",
"by",
"decrementing",
"s",
".",
"dbUsers",
"broadcasting",
"the",
"condition",
"variable",
"if",
"no",
"users",
"are",
"left",
"to",
"wake",
"CloseDB",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/host/state.go#L239-L246 | train |
flynn/flynn | controller/utils/utils.go | GetEntrypoint | func GetEntrypoint(artifacts []*ct.Artifact, typ string) *ct.ImageEntrypoint {
for i := len(artifacts) - 1; i >= 0; i-- {
artifact := artifacts[i]
if artifact.Type != ct.ArtifactTypeFlynn {
continue
}
if e, ok := artifact.Manifest().Entrypoints[typ]; ok {
return e
}
}
for i := len(artifacts) - 1; i >= 0; i-- {
artifact := artifacts[i]
if artifact.Type != ct.ArtifactTypeFlynn {
continue
}
if e := artifact.Manifest().DefaultEntrypoint(); e != nil {
return e
}
}
return nil
} | go | func GetEntrypoint(artifacts []*ct.Artifact, typ string) *ct.ImageEntrypoint {
for i := len(artifacts) - 1; i >= 0; i-- {
artifact := artifacts[i]
if artifact.Type != ct.ArtifactTypeFlynn {
continue
}
if e, ok := artifact.Manifest().Entrypoints[typ]; ok {
return e
}
}
for i := len(artifacts) - 1; i >= 0; i-- {
artifact := artifacts[i]
if artifact.Type != ct.ArtifactTypeFlynn {
continue
}
if e := artifact.Manifest().DefaultEntrypoint(); e != nil {
return e
}
}
return nil
} | [
"func",
"GetEntrypoint",
"(",
"artifacts",
"[",
"]",
"*",
"ct",
".",
"Artifact",
",",
"typ",
"string",
")",
"*",
"ct",
".",
"ImageEntrypoint",
"{",
"for",
"i",
":=",
"len",
"(",
"artifacts",
")",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
"{",
"artifact",
":=",
"artifacts",
"[",
"i",
"]",
"\n",
"if",
"artifact",
".",
"Type",
"!=",
"ct",
".",
"ArtifactTypeFlynn",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"e",
",",
"ok",
":=",
"artifact",
".",
"Manifest",
"(",
")",
".",
"Entrypoints",
"[",
"typ",
"]",
";",
"ok",
"{",
"return",
"e",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"i",
":=",
"len",
"(",
"artifacts",
")",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
"{",
"artifact",
":=",
"artifacts",
"[",
"i",
"]",
"\n",
"if",
"artifact",
".",
"Type",
"!=",
"ct",
".",
"ArtifactTypeFlynn",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"e",
":=",
"artifact",
".",
"Manifest",
"(",
")",
".",
"DefaultEntrypoint",
"(",
")",
";",
"e",
"!=",
"nil",
"{",
"return",
"e",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // GetEntrypoint returns an image entrypoint for a process type from a list of
// artifacts, first iterating through them and returning any entrypoint having
// the exact type, then iterating through them and returning the artifact's
// default entrypoint if it has one.
//
// The artifacts are traversed in reverse order so that entrypoints in the
// image being overlayed at the top are considered first. | [
"GetEntrypoint",
"returns",
"an",
"image",
"entrypoint",
"for",
"a",
"process",
"type",
"from",
"a",
"list",
"of",
"artifacts",
"first",
"iterating",
"through",
"them",
"and",
"returning",
"any",
"entrypoint",
"having",
"the",
"exact",
"type",
"then",
"iterating",
"through",
"them",
"and",
"returning",
"the",
"artifact",
"s",
"default",
"entrypoint",
"if",
"it",
"has",
"one",
".",
"The",
"artifacts",
"are",
"traversed",
"in",
"reverse",
"order",
"so",
"that",
"entrypoints",
"in",
"the",
"image",
"being",
"overlayed",
"at",
"the",
"top",
"are",
"considered",
"first",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/controller/utils/utils.go#L106-L126 | train |
flynn/flynn | controller/utils/utils.go | SetupMountspecs | func SetupMountspecs(job *host.Job, artifacts []*ct.Artifact) {
for _, artifact := range artifacts {
if artifact.Type != ct.ArtifactTypeFlynn {
continue
}
if len(artifact.Manifest().Rootfs) != 1 {
continue
}
rootfs := artifact.Manifest().Rootfs[0]
for _, layer := range rootfs.Layers {
if layer.Type != ct.ImageLayerTypeSquashfs {
continue
}
job.Mountspecs = append(job.Mountspecs, &host.Mountspec{
Type: host.MountspecTypeSquashfs,
ID: layer.ID,
URL: artifact.LayerURL(layer),
Size: layer.Length,
Hashes: layer.Hashes,
Meta: artifact.Meta,
})
}
}
} | go | func SetupMountspecs(job *host.Job, artifacts []*ct.Artifact) {
for _, artifact := range artifacts {
if artifact.Type != ct.ArtifactTypeFlynn {
continue
}
if len(artifact.Manifest().Rootfs) != 1 {
continue
}
rootfs := artifact.Manifest().Rootfs[0]
for _, layer := range rootfs.Layers {
if layer.Type != ct.ImageLayerTypeSquashfs {
continue
}
job.Mountspecs = append(job.Mountspecs, &host.Mountspec{
Type: host.MountspecTypeSquashfs,
ID: layer.ID,
URL: artifact.LayerURL(layer),
Size: layer.Length,
Hashes: layer.Hashes,
Meta: artifact.Meta,
})
}
}
} | [
"func",
"SetupMountspecs",
"(",
"job",
"*",
"host",
".",
"Job",
",",
"artifacts",
"[",
"]",
"*",
"ct",
".",
"Artifact",
")",
"{",
"for",
"_",
",",
"artifact",
":=",
"range",
"artifacts",
"{",
"if",
"artifact",
".",
"Type",
"!=",
"ct",
".",
"ArtifactTypeFlynn",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"len",
"(",
"artifact",
".",
"Manifest",
"(",
")",
".",
"Rootfs",
")",
"!=",
"1",
"{",
"continue",
"\n",
"}",
"\n",
"rootfs",
":=",
"artifact",
".",
"Manifest",
"(",
")",
".",
"Rootfs",
"[",
"0",
"]",
"\n",
"for",
"_",
",",
"layer",
":=",
"range",
"rootfs",
".",
"Layers",
"{",
"if",
"layer",
".",
"Type",
"!=",
"ct",
".",
"ImageLayerTypeSquashfs",
"{",
"continue",
"\n",
"}",
"\n",
"job",
".",
"Mountspecs",
"=",
"append",
"(",
"job",
".",
"Mountspecs",
",",
"&",
"host",
".",
"Mountspec",
"{",
"Type",
":",
"host",
".",
"MountspecTypeSquashfs",
",",
"ID",
":",
"layer",
".",
"ID",
",",
"URL",
":",
"artifact",
".",
"LayerURL",
"(",
"layer",
")",
",",
"Size",
":",
"layer",
".",
"Length",
",",
"Hashes",
":",
"layer",
".",
"Hashes",
",",
"Meta",
":",
"artifact",
".",
"Meta",
",",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // SetupMountspecs populates job.Mountspecs using the layers from a list of
// Flynn image artifacts, expecting each artifact to have a single rootfs entry
// containing squashfs layers | [
"SetupMountspecs",
"populates",
"job",
".",
"Mountspecs",
"using",
"the",
"layers",
"from",
"a",
"list",
"of",
"Flynn",
"image",
"artifacts",
"expecting",
"each",
"artifact",
"to",
"have",
"a",
"single",
"rootfs",
"entry",
"containing",
"squashfs",
"layers"
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/controller/utils/utils.go#L131-L154 | train |
flynn/flynn | controller/scheduler/formation.go | IsScaleDownOf | func (p Processes) IsScaleDownOf(proc Processes) bool {
for typ, count := range p {
if count <= -proc[typ] {
return true
}
}
return false
} | go | func (p Processes) IsScaleDownOf(proc Processes) bool {
for typ, count := range p {
if count <= -proc[typ] {
return true
}
}
return false
} | [
"func",
"(",
"p",
"Processes",
")",
"IsScaleDownOf",
"(",
"proc",
"Processes",
")",
"bool",
"{",
"for",
"typ",
",",
"count",
":=",
"range",
"p",
"{",
"if",
"count",
"<=",
"-",
"proc",
"[",
"typ",
"]",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // IsScaleDownOf returns whether a diff is the complete scale down of any
// process types in the given processes | [
"IsScaleDownOf",
"returns",
"whether",
"a",
"diff",
"is",
"the",
"complete",
"scale",
"down",
"of",
"any",
"process",
"types",
"in",
"the",
"given",
"processes"
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/controller/scheduler/formation.go#L59-L66 | train |
flynn/flynn | controller/scheduler/formation.go | RectifyOmni | func (f *Formation) RectifyOmni(hostCount int) bool {
changed := false
for typ, proc := range f.Release.Processes {
if proc.Omni && f.Processes != nil && f.Processes[typ] > 0 {
count := f.OriginalProcesses[typ] * hostCount
if f.Processes[typ] != count {
f.Processes[typ] = count
changed = true
}
}
}
return changed
} | go | func (f *Formation) RectifyOmni(hostCount int) bool {
changed := false
for typ, proc := range f.Release.Processes {
if proc.Omni && f.Processes != nil && f.Processes[typ] > 0 {
count := f.OriginalProcesses[typ] * hostCount
if f.Processes[typ] != count {
f.Processes[typ] = count
changed = true
}
}
}
return changed
} | [
"func",
"(",
"f",
"*",
"Formation",
")",
"RectifyOmni",
"(",
"hostCount",
"int",
")",
"bool",
"{",
"changed",
":=",
"false",
"\n",
"for",
"typ",
",",
"proc",
":=",
"range",
"f",
".",
"Release",
".",
"Processes",
"{",
"if",
"proc",
".",
"Omni",
"&&",
"f",
".",
"Processes",
"!=",
"nil",
"&&",
"f",
".",
"Processes",
"[",
"typ",
"]",
">",
"0",
"{",
"count",
":=",
"f",
".",
"OriginalProcesses",
"[",
"typ",
"]",
"*",
"hostCount",
"\n",
"if",
"f",
".",
"Processes",
"[",
"typ",
"]",
"!=",
"count",
"{",
"f",
".",
"Processes",
"[",
"typ",
"]",
"=",
"count",
"\n",
"changed",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"changed",
"\n",
"}"
] | // RectifyOmni updates the process counts for omni jobs by multiplying them by
// the host count, returning whether or not any counts have changed | [
"RectifyOmni",
"updates",
"the",
"process",
"counts",
"for",
"omni",
"jobs",
"by",
"multiplying",
"them",
"by",
"the",
"host",
"count",
"returning",
"whether",
"or",
"not",
"any",
"counts",
"have",
"changed"
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/controller/scheduler/formation.go#L90-L102 | train |
flynn/flynn | controller/scheduler/formation.go | Diff | func (f *Formation) Diff(running Processes) Processes {
return Processes(f.Processes).Diff(running)
} | go | func (f *Formation) Diff(running Processes) Processes {
return Processes(f.Processes).Diff(running)
} | [
"func",
"(",
"f",
"*",
"Formation",
")",
"Diff",
"(",
"running",
"Processes",
")",
"Processes",
"{",
"return",
"Processes",
"(",
"f",
".",
"Processes",
")",
".",
"Diff",
"(",
"running",
")",
"\n",
"}"
] | // Diff returns the diff between the given running processes and what is
// expected to be running for the formation | [
"Diff",
"returns",
"the",
"diff",
"between",
"the",
"given",
"running",
"processes",
"and",
"what",
"is",
"expected",
"to",
"be",
"running",
"for",
"the",
"formation"
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/controller/scheduler/formation.go#L124-L126 | train |
flynn/flynn | host/cli/download.go | updateTUFClient | func updateTUFClient(client *tuf.Client) error {
_, err := client.Update()
if err == nil || tuf.IsLatestSnapshot(err) {
return nil
}
if err == tuf.ErrNoRootKeys {
if err := client.Init(tufconfig.RootKeys, len(tufconfig.RootKeys)); err != nil {
return err
}
return updateTUFClient(client)
}
return err
} | go | func updateTUFClient(client *tuf.Client) error {
_, err := client.Update()
if err == nil || tuf.IsLatestSnapshot(err) {
return nil
}
if err == tuf.ErrNoRootKeys {
if err := client.Init(tufconfig.RootKeys, len(tufconfig.RootKeys)); err != nil {
return err
}
return updateTUFClient(client)
}
return err
} | [
"func",
"updateTUFClient",
"(",
"client",
"*",
"tuf",
".",
"Client",
")",
"error",
"{",
"_",
",",
"err",
":=",
"client",
".",
"Update",
"(",
")",
"\n",
"if",
"err",
"==",
"nil",
"||",
"tuf",
".",
"IsLatestSnapshot",
"(",
"err",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"err",
"==",
"tuf",
".",
"ErrNoRootKeys",
"{",
"if",
"err",
":=",
"client",
".",
"Init",
"(",
"tufconfig",
".",
"RootKeys",
",",
"len",
"(",
"tufconfig",
".",
"RootKeys",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"updateTUFClient",
"(",
"client",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // updateTUFClient updates the given client, initializing and re-running the
// update if ErrNoRootKeys is returned. | [
"updateTUFClient",
"updates",
"the",
"given",
"client",
"initializing",
"and",
"re",
"-",
"running",
"the",
"update",
"if",
"ErrNoRootKeys",
"is",
"returned",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/host/cli/download.go#L146-L158 | train |
flynn/flynn | controller/scheduler/job.go | Tags | func (j *Job) Tags() map[string]string {
if j.Formation == nil {
return nil
}
return j.Formation.Tags[j.Type]
} | go | func (j *Job) Tags() map[string]string {
if j.Formation == nil {
return nil
}
return j.Formation.Tags[j.Type]
} | [
"func",
"(",
"j",
"*",
"Job",
")",
"Tags",
"(",
")",
"map",
"[",
"string",
"]",
"string",
"{",
"if",
"j",
".",
"Formation",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"j",
".",
"Formation",
".",
"Tags",
"[",
"j",
".",
"Type",
"]",
"\n",
"}"
] | // Tags returns the tags for the job's process type from the formation | [
"Tags",
"returns",
"the",
"tags",
"for",
"the",
"job",
"s",
"process",
"type",
"from",
"the",
"formation"
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/controller/scheduler/job.go#L115-L120 | train |
flynn/flynn | controller/scheduler/job.go | TagsMatchHost | func (j *Job) TagsMatchHost(host *Host) bool {
for k, v := range j.Tags() {
if w, ok := host.Tags[k]; !ok || v != w {
return false
}
}
return true
} | go | func (j *Job) TagsMatchHost(host *Host) bool {
for k, v := range j.Tags() {
if w, ok := host.Tags[k]; !ok || v != w {
return false
}
}
return true
} | [
"func",
"(",
"j",
"*",
"Job",
")",
"TagsMatchHost",
"(",
"host",
"*",
"Host",
")",
"bool",
"{",
"for",
"k",
",",
"v",
":=",
"range",
"j",
".",
"Tags",
"(",
")",
"{",
"if",
"w",
",",
"ok",
":=",
"host",
".",
"Tags",
"[",
"k",
"]",
";",
"!",
"ok",
"||",
"v",
"!=",
"w",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // TagsMatchHost checks whether all of the job's tags match the corresponding
// host's tags | [
"TagsMatchHost",
"checks",
"whether",
"all",
"of",
"the",
"job",
"s",
"tags",
"match",
"the",
"corresponding",
"host",
"s",
"tags"
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/controller/scheduler/job.go#L124-L131 | train |
flynn/flynn | controller/scheduler/job.go | WithFormationAndType | func (j Jobs) WithFormationAndType(f *Formation, typ string) sortJobs {
jobs := make(sortJobs, 0, len(j))
for _, job := range j {
if job.Formation == f && job.Type == typ {
jobs = append(jobs, job)
}
}
jobs.Sort()
return jobs
} | go | func (j Jobs) WithFormationAndType(f *Formation, typ string) sortJobs {
jobs := make(sortJobs, 0, len(j))
for _, job := range j {
if job.Formation == f && job.Type == typ {
jobs = append(jobs, job)
}
}
jobs.Sort()
return jobs
} | [
"func",
"(",
"j",
"Jobs",
")",
"WithFormationAndType",
"(",
"f",
"*",
"Formation",
",",
"typ",
"string",
")",
"sortJobs",
"{",
"jobs",
":=",
"make",
"(",
"sortJobs",
",",
"0",
",",
"len",
"(",
"j",
")",
")",
"\n",
"for",
"_",
",",
"job",
":=",
"range",
"j",
"{",
"if",
"job",
".",
"Formation",
"==",
"f",
"&&",
"job",
".",
"Type",
"==",
"typ",
"{",
"jobs",
"=",
"append",
"(",
"jobs",
",",
"job",
")",
"\n",
"}",
"\n",
"}",
"\n",
"jobs",
".",
"Sort",
"(",
")",
"\n",
"return",
"jobs",
"\n",
"}"
] | // WithFormationAndType returns a list of jobs which belong to the given
// formation and have the given type, ordered with the most recently started
// job first | [
"WithFormationAndType",
"returns",
"a",
"list",
"of",
"jobs",
"which",
"belong",
"to",
"the",
"given",
"formation",
"and",
"have",
"the",
"given",
"type",
"ordered",
"with",
"the",
"most",
"recently",
"started",
"job",
"first"
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/controller/scheduler/job.go#L211-L220 | train |
flynn/flynn | host/logmux/logmux.go | Follow | func (m *Mux) Follow(r io.ReadCloser, buffer string, msgID logagg.MsgID, config *Config) *LogStream {
hdr := &rfc5424.Header{
Hostname: []byte(config.HostID),
AppName: []byte(config.AppID),
MsgID: []byte(msgID),
}
if config.JobType != "" {
hdr.ProcID = []byte(config.JobType + "." + config.JobID)
} else {
hdr.ProcID = []byte(config.JobID)
}
s := &LogStream{
m: m,
log: r,
done: make(chan struct{}),
}
s.closed.Store(false)
m.jobsMtx.Lock()
defer m.jobsMtx.Unlock()
// set up the WaitGroup so that subscribers can track when the job fds have closed
wg, ok := m.jobWaits[config.JobID]
if !ok {
wg = &sync.WaitGroup{}
m.jobWaits[config.JobID] = wg
}
wg.Add(1)
if !ok {
// we created the wg, so create a goroutine to clean up
go func() {
wg.Wait()
m.jobsMtx.Lock()
defer m.jobsMtx.Unlock()
delete(m.jobWaits, config.JobID)
}()
}
// if there is a jobStart channel, a subscriber is waiting for the WaitGroup
// to be created, signal it.
if ch, ok := m.jobStarts[config.JobID]; ok {
close(ch)
delete(m.jobStarts, config.JobID)
}
go s.follow(r, buffer, config.AppID, hdr, wg)
return s
} | go | func (m *Mux) Follow(r io.ReadCloser, buffer string, msgID logagg.MsgID, config *Config) *LogStream {
hdr := &rfc5424.Header{
Hostname: []byte(config.HostID),
AppName: []byte(config.AppID),
MsgID: []byte(msgID),
}
if config.JobType != "" {
hdr.ProcID = []byte(config.JobType + "." + config.JobID)
} else {
hdr.ProcID = []byte(config.JobID)
}
s := &LogStream{
m: m,
log: r,
done: make(chan struct{}),
}
s.closed.Store(false)
m.jobsMtx.Lock()
defer m.jobsMtx.Unlock()
// set up the WaitGroup so that subscribers can track when the job fds have closed
wg, ok := m.jobWaits[config.JobID]
if !ok {
wg = &sync.WaitGroup{}
m.jobWaits[config.JobID] = wg
}
wg.Add(1)
if !ok {
// we created the wg, so create a goroutine to clean up
go func() {
wg.Wait()
m.jobsMtx.Lock()
defer m.jobsMtx.Unlock()
delete(m.jobWaits, config.JobID)
}()
}
// if there is a jobStart channel, a subscriber is waiting for the WaitGroup
// to be created, signal it.
if ch, ok := m.jobStarts[config.JobID]; ok {
close(ch)
delete(m.jobStarts, config.JobID)
}
go s.follow(r, buffer, config.AppID, hdr, wg)
return s
} | [
"func",
"(",
"m",
"*",
"Mux",
")",
"Follow",
"(",
"r",
"io",
".",
"ReadCloser",
",",
"buffer",
"string",
",",
"msgID",
"logagg",
".",
"MsgID",
",",
"config",
"*",
"Config",
")",
"*",
"LogStream",
"{",
"hdr",
":=",
"&",
"rfc5424",
".",
"Header",
"{",
"Hostname",
":",
"[",
"]",
"byte",
"(",
"config",
".",
"HostID",
")",
",",
"AppName",
":",
"[",
"]",
"byte",
"(",
"config",
".",
"AppID",
")",
",",
"MsgID",
":",
"[",
"]",
"byte",
"(",
"msgID",
")",
",",
"}",
"\n",
"if",
"config",
".",
"JobType",
"!=",
"\"",
"\"",
"{",
"hdr",
".",
"ProcID",
"=",
"[",
"]",
"byte",
"(",
"config",
".",
"JobType",
"+",
"\"",
"\"",
"+",
"config",
".",
"JobID",
")",
"\n",
"}",
"else",
"{",
"hdr",
".",
"ProcID",
"=",
"[",
"]",
"byte",
"(",
"config",
".",
"JobID",
")",
"\n",
"}",
"\n\n",
"s",
":=",
"&",
"LogStream",
"{",
"m",
":",
"m",
",",
"log",
":",
"r",
",",
"done",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"}",
"\n",
"s",
".",
"closed",
".",
"Store",
"(",
"false",
")",
"\n\n",
"m",
".",
"jobsMtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"m",
".",
"jobsMtx",
".",
"Unlock",
"(",
")",
"\n",
"// set up the WaitGroup so that subscribers can track when the job fds have closed",
"wg",
",",
"ok",
":=",
"m",
".",
"jobWaits",
"[",
"config",
".",
"JobID",
"]",
"\n",
"if",
"!",
"ok",
"{",
"wg",
"=",
"&",
"sync",
".",
"WaitGroup",
"{",
"}",
"\n",
"m",
".",
"jobWaits",
"[",
"config",
".",
"JobID",
"]",
"=",
"wg",
"\n",
"}",
"\n",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"if",
"!",
"ok",
"{",
"// we created the wg, so create a goroutine to clean up",
"go",
"func",
"(",
")",
"{",
"wg",
".",
"Wait",
"(",
")",
"\n",
"m",
".",
"jobsMtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"m",
".",
"jobsMtx",
".",
"Unlock",
"(",
")",
"\n",
"delete",
"(",
"m",
".",
"jobWaits",
",",
"config",
".",
"JobID",
")",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n\n",
"// if there is a jobStart channel, a subscriber is waiting for the WaitGroup",
"// to be created, signal it.",
"if",
"ch",
",",
"ok",
":=",
"m",
".",
"jobStarts",
"[",
"config",
".",
"JobID",
"]",
";",
"ok",
"{",
"close",
"(",
"ch",
")",
"\n",
"delete",
"(",
"m",
".",
"jobStarts",
",",
"config",
".",
"JobID",
")",
"\n",
"}",
"\n\n",
"go",
"s",
".",
"follow",
"(",
"r",
",",
"buffer",
",",
"config",
".",
"AppID",
",",
"hdr",
",",
"wg",
")",
"\n",
"return",
"s",
"\n",
"}"
] | // Follow starts a goroutine that reads log lines from the reader into the mux.
// It runs until the reader is closed or an error occurs. If an error occurs,
// the reader may still be open. | [
"Follow",
"starts",
"a",
"goroutine",
"that",
"reads",
"log",
"lines",
"from",
"the",
"reader",
"into",
"the",
"mux",
".",
"It",
"runs",
"until",
"the",
"reader",
"is",
"closed",
"or",
"an",
"error",
"occurs",
".",
"If",
"an",
"error",
"occurs",
"the",
"reader",
"may",
"still",
"be",
"open",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/host/logmux/logmux.go#L286-L333 | train |
flynn/flynn | host/logmux/logmux.go | jobDoneCh | func (m *Mux) jobDoneCh(jobID string, stop <-chan struct{}) <-chan struct{} {
ch := make(chan struct{})
go func() {
defer close(ch)
var started chan struct{}
m.jobsMtx.Lock()
// check if there is already a WaitGroup
wg, ok := m.jobWaits[jobID]
if !ok {
// if not, check if there is a channel to be notified when one is
// created
started, ok = m.jobStarts[jobID]
if !ok {
// if not, make and save the channel
started = make(chan struct{})
m.jobStarts[jobID] = started
}
}
m.jobsMtx.Unlock()
if started != nil {
// if the wg doesn't exist, wait for it
select {
case <-started:
case <-stop:
return
}
m.jobsMtx.Lock()
wg, ok = m.jobWaits[jobID]
m.jobsMtx.Unlock()
if !ok {
// if there is no wg, it was created and deleted before we could
// read it, we're done
return
}
}
// wait for the job to finish
wg.Wait()
}()
return ch
} | go | func (m *Mux) jobDoneCh(jobID string, stop <-chan struct{}) <-chan struct{} {
ch := make(chan struct{})
go func() {
defer close(ch)
var started chan struct{}
m.jobsMtx.Lock()
// check if there is already a WaitGroup
wg, ok := m.jobWaits[jobID]
if !ok {
// if not, check if there is a channel to be notified when one is
// created
started, ok = m.jobStarts[jobID]
if !ok {
// if not, make and save the channel
started = make(chan struct{})
m.jobStarts[jobID] = started
}
}
m.jobsMtx.Unlock()
if started != nil {
// if the wg doesn't exist, wait for it
select {
case <-started:
case <-stop:
return
}
m.jobsMtx.Lock()
wg, ok = m.jobWaits[jobID]
m.jobsMtx.Unlock()
if !ok {
// if there is no wg, it was created and deleted before we could
// read it, we're done
return
}
}
// wait for the job to finish
wg.Wait()
}()
return ch
} | [
"func",
"(",
"m",
"*",
"Mux",
")",
"jobDoneCh",
"(",
"jobID",
"string",
",",
"stop",
"<-",
"chan",
"struct",
"{",
"}",
")",
"<-",
"chan",
"struct",
"{",
"}",
"{",
"ch",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"defer",
"close",
"(",
"ch",
")",
"\n",
"var",
"started",
"chan",
"struct",
"{",
"}",
"\n",
"m",
".",
"jobsMtx",
".",
"Lock",
"(",
")",
"\n",
"// check if there is already a WaitGroup",
"wg",
",",
"ok",
":=",
"m",
".",
"jobWaits",
"[",
"jobID",
"]",
"\n",
"if",
"!",
"ok",
"{",
"// if not, check if there is a channel to be notified when one is",
"// created",
"started",
",",
"ok",
"=",
"m",
".",
"jobStarts",
"[",
"jobID",
"]",
"\n",
"if",
"!",
"ok",
"{",
"// if not, make and save the channel",
"started",
"=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"m",
".",
"jobStarts",
"[",
"jobID",
"]",
"=",
"started",
"\n",
"}",
"\n",
"}",
"\n",
"m",
".",
"jobsMtx",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"started",
"!=",
"nil",
"{",
"// if the wg doesn't exist, wait for it",
"select",
"{",
"case",
"<-",
"started",
":",
"case",
"<-",
"stop",
":",
"return",
"\n",
"}",
"\n",
"m",
".",
"jobsMtx",
".",
"Lock",
"(",
")",
"\n",
"wg",
",",
"ok",
"=",
"m",
".",
"jobWaits",
"[",
"jobID",
"]",
"\n",
"m",
".",
"jobsMtx",
".",
"Unlock",
"(",
")",
"\n",
"if",
"!",
"ok",
"{",
"// if there is no wg, it was created and deleted before we could",
"// read it, we're done",
"return",
"\n",
"}",
"\n",
"}",
"\n\n",
"// wait for the job to finish",
"wg",
".",
"Wait",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"return",
"ch",
"\n",
"}"
] | // jobDoneCh returns a channel that is closed when all of the streams we are
// following from the job have been closed. It will never unblock if the job has
// already finished. | [
"jobDoneCh",
"returns",
"a",
"channel",
"that",
"is",
"closed",
"when",
"all",
"of",
"the",
"streams",
"we",
"are",
"following",
"from",
"the",
"job",
"have",
"been",
"closed",
".",
"It",
"will",
"never",
"unblock",
"if",
"the",
"job",
"has",
"already",
"finished",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/host/logmux/logmux.go#L407-L448 | train |
flynn/flynn | host/logmux/logmux.go | logFiles | func (m *Mux) logFiles(app string) (map[string][]string, error) {
files, err := ioutil.ReadDir(m.logDir)
if err != nil {
return nil, err
}
res := make(map[string][]string)
for _, f := range files {
n := f.Name()
if f.IsDir() || !strings.HasSuffix(n, ".log") || !appIDPrefixPattern.MatchString(n) || !strings.HasPrefix(n, app) {
continue
}
appID := n[:36]
res[appID] = append(res[appID], filepath.Join(m.logDir, n))
}
return res, nil
} | go | func (m *Mux) logFiles(app string) (map[string][]string, error) {
files, err := ioutil.ReadDir(m.logDir)
if err != nil {
return nil, err
}
res := make(map[string][]string)
for _, f := range files {
n := f.Name()
if f.IsDir() || !strings.HasSuffix(n, ".log") || !appIDPrefixPattern.MatchString(n) || !strings.HasPrefix(n, app) {
continue
}
appID := n[:36]
res[appID] = append(res[appID], filepath.Join(m.logDir, n))
}
return res, nil
} | [
"func",
"(",
"m",
"*",
"Mux",
")",
"logFiles",
"(",
"app",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
",",
"error",
")",
"{",
"files",
",",
"err",
":=",
"ioutil",
".",
"ReadDir",
"(",
"m",
".",
"logDir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"res",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
")",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"files",
"{",
"n",
":=",
"f",
".",
"Name",
"(",
")",
"\n",
"if",
"f",
".",
"IsDir",
"(",
")",
"||",
"!",
"strings",
".",
"HasSuffix",
"(",
"n",
",",
"\"",
"\"",
")",
"||",
"!",
"appIDPrefixPattern",
".",
"MatchString",
"(",
"n",
")",
"||",
"!",
"strings",
".",
"HasPrefix",
"(",
"n",
",",
"app",
")",
"{",
"continue",
"\n",
"}",
"\n",
"appID",
":=",
"n",
"[",
":",
"36",
"]",
"\n",
"res",
"[",
"appID",
"]",
"=",
"append",
"(",
"res",
"[",
"appID",
"]",
",",
"filepath",
".",
"Join",
"(",
"m",
".",
"logDir",
",",
"n",
")",
")",
"\n",
"}",
"\n\n",
"return",
"res",
",",
"nil",
"\n",
"}"
] | // logFiles returns a list of app IDs and the list of log file names associated
// with them, from oldest to newest. There is always at least one file, the
// current log for the app. | [
"logFiles",
"returns",
"a",
"list",
"of",
"app",
"IDs",
"and",
"the",
"list",
"of",
"log",
"file",
"names",
"associated",
"with",
"them",
"from",
"oldest",
"to",
"newest",
".",
"There",
"is",
"always",
"at",
"least",
"one",
"file",
"the",
"current",
"log",
"for",
"the",
"app",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/host/logmux/logmux.go#L620-L637 | train |
flynn/flynn | host/logmux/logmux.go | Release | func (l *appLog) Release() {
l.mtx.Lock()
defer l.mtx.Unlock()
l.refs--
if l.refs == 0 {
// we're the last user, clean it up
l.l.Close()
l.m.appLogsMtx.Lock()
delete(l.m.appLogs, l.appID)
l.m.appLogsMtx.Unlock()
}
} | go | func (l *appLog) Release() {
l.mtx.Lock()
defer l.mtx.Unlock()
l.refs--
if l.refs == 0 {
// we're the last user, clean it up
l.l.Close()
l.m.appLogsMtx.Lock()
delete(l.m.appLogs, l.appID)
l.m.appLogsMtx.Unlock()
}
} | [
"func",
"(",
"l",
"*",
"appLog",
")",
"Release",
"(",
")",
"{",
"l",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"l",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n",
"l",
".",
"refs",
"--",
"\n",
"if",
"l",
".",
"refs",
"==",
"0",
"{",
"// we're the last user, clean it up",
"l",
".",
"l",
".",
"Close",
"(",
")",
"\n",
"l",
".",
"m",
".",
"appLogsMtx",
".",
"Lock",
"(",
")",
"\n",
"delete",
"(",
"l",
".",
"m",
".",
"appLogs",
",",
"l",
".",
"appID",
")",
"\n",
"l",
".",
"m",
".",
"appLogsMtx",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // Release releases the app log, when the last job releases an app log, it is
// closed. | [
"Release",
"releases",
"the",
"app",
"log",
"when",
"the",
"last",
"job",
"releases",
"an",
"app",
"log",
"it",
"is",
"closed",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/host/logmux/logmux.go#L684-L695 | train |
flynn/flynn | router/tree.go | Insert | func (n *node) Insert(path string, backend *httpRoute) {
cur := n
for part, i := slice(path, 0); ; part, i = slice(path, i) {
if part != "" {
child, _ := cur.children[part]
if child == nil {
// insert node if it doesn't exist
child = &node{children: make(map[string]*node, 0)}
cur.children[part] = child
}
cur = child
}
if i == -1 {
break
}
}
cur.backend = backend // finally set the backend for this node
} | go | func (n *node) Insert(path string, backend *httpRoute) {
cur := n
for part, i := slice(path, 0); ; part, i = slice(path, i) {
if part != "" {
child, _ := cur.children[part]
if child == nil {
// insert node if it doesn't exist
child = &node{children: make(map[string]*node, 0)}
cur.children[part] = child
}
cur = child
}
if i == -1 {
break
}
}
cur.backend = backend // finally set the backend for this node
} | [
"func",
"(",
"n",
"*",
"node",
")",
"Insert",
"(",
"path",
"string",
",",
"backend",
"*",
"httpRoute",
")",
"{",
"cur",
":=",
"n",
"\n",
"for",
"part",
",",
"i",
":=",
"slice",
"(",
"path",
",",
"0",
")",
";",
";",
"part",
",",
"i",
"=",
"slice",
"(",
"path",
",",
"i",
")",
"{",
"if",
"part",
"!=",
"\"",
"\"",
"{",
"child",
",",
"_",
":=",
"cur",
".",
"children",
"[",
"part",
"]",
"\n",
"if",
"child",
"==",
"nil",
"{",
"// insert node if it doesn't exist",
"child",
"=",
"&",
"node",
"{",
"children",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"node",
",",
"0",
")",
"}",
"\n",
"cur",
".",
"children",
"[",
"part",
"]",
"=",
"child",
"\n",
"}",
"\n",
"cur",
"=",
"child",
"\n",
"}",
"\n",
"if",
"i",
"==",
"-",
"1",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"cur",
".",
"backend",
"=",
"backend",
"// finally set the backend for this node",
"\n",
"}"
] | // insert a new route into the tree, replacing entry if it exists | [
"insert",
"a",
"new",
"route",
"into",
"the",
"tree",
"replacing",
"entry",
"if",
"it",
"exists"
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/router/tree.go#L20-L37 | train |
flynn/flynn | router/tree.go | Lookup | func (n *node) Lookup(path string) *httpRoute {
cur := n
prev := n
for part, i := slice(path, 0); ; part, i = slice(path, i) {
if part != "" {
cur = cur.children[part]
if cur == nil {
// can't progress any deeper, return last backend we saw
return prev.backend
}
if cur.backend != nil {
prev = cur // update last seen backend
}
}
if i == -1 {
break
}
}
if cur.backend != nil {
return cur.backend
}
return prev.backend
} | go | func (n *node) Lookup(path string) *httpRoute {
cur := n
prev := n
for part, i := slice(path, 0); ; part, i = slice(path, i) {
if part != "" {
cur = cur.children[part]
if cur == nil {
// can't progress any deeper, return last backend we saw
return prev.backend
}
if cur.backend != nil {
prev = cur // update last seen backend
}
}
if i == -1 {
break
}
}
if cur.backend != nil {
return cur.backend
}
return prev.backend
} | [
"func",
"(",
"n",
"*",
"node",
")",
"Lookup",
"(",
"path",
"string",
")",
"*",
"httpRoute",
"{",
"cur",
":=",
"n",
"\n",
"prev",
":=",
"n",
"\n",
"for",
"part",
",",
"i",
":=",
"slice",
"(",
"path",
",",
"0",
")",
";",
";",
"part",
",",
"i",
"=",
"slice",
"(",
"path",
",",
"i",
")",
"{",
"if",
"part",
"!=",
"\"",
"\"",
"{",
"cur",
"=",
"cur",
".",
"children",
"[",
"part",
"]",
"\n",
"if",
"cur",
"==",
"nil",
"{",
"// can't progress any deeper, return last backend we saw",
"return",
"prev",
".",
"backend",
"\n",
"}",
"\n",
"if",
"cur",
".",
"backend",
"!=",
"nil",
"{",
"prev",
"=",
"cur",
"// update last seen backend",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"i",
"==",
"-",
"1",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"cur",
".",
"backend",
"!=",
"nil",
"{",
"return",
"cur",
".",
"backend",
"\n",
"}",
"\n",
"return",
"prev",
".",
"backend",
"\n",
"}"
] | // lookup returns the best match for a given path | [
"lookup",
"returns",
"the",
"best",
"match",
"for",
"a",
"given",
"path"
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/router/tree.go#L40-L62 | train |
flynn/flynn | router/tree.go | slice | func slice(path string, start int) (segment string, next int) {
if len(path) == 0 || start < 0 || start >= len(path) {
return "", -1
}
end := strings.IndexRune(path[start:], '/')
if end == -1 {
return path[start:], -1
}
if path[start:start+end] == "/" {
return "", start + end + 1
}
return path[start : start+end], start + end + 1
} | go | func slice(path string, start int) (segment string, next int) {
if len(path) == 0 || start < 0 || start >= len(path) {
return "", -1
}
end := strings.IndexRune(path[start:], '/')
if end == -1 {
return path[start:], -1
}
if path[start:start+end] == "/" {
return "", start + end + 1
}
return path[start : start+end], start + end + 1
} | [
"func",
"slice",
"(",
"path",
"string",
",",
"start",
"int",
")",
"(",
"segment",
"string",
",",
"next",
"int",
")",
"{",
"if",
"len",
"(",
"path",
")",
"==",
"0",
"||",
"start",
"<",
"0",
"||",
"start",
">=",
"len",
"(",
"path",
")",
"{",
"return",
"\"",
"\"",
",",
"-",
"1",
"\n",
"}",
"\n",
"end",
":=",
"strings",
".",
"IndexRune",
"(",
"path",
"[",
"start",
":",
"]",
",",
"'/'",
")",
"\n",
"if",
"end",
"==",
"-",
"1",
"{",
"return",
"path",
"[",
"start",
":",
"]",
",",
"-",
"1",
"\n",
"}",
"\n",
"if",
"path",
"[",
"start",
":",
"start",
"+",
"end",
"]",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"start",
"+",
"end",
"+",
"1",
"\n",
"}",
"\n",
"return",
"path",
"[",
"start",
":",
"start",
"+",
"end",
"]",
",",
"start",
"+",
"end",
"+",
"1",
"\n",
"}"
] | // slices string into path segments performing 0 heap allocation | [
"slices",
"string",
"into",
"path",
"segments",
"performing",
"0",
"heap",
"allocation"
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/router/tree.go#L99-L111 | train |
flynn/flynn | controller/events.go | Notify | func (e *EventSubscriber) Notify(event *ct.Event) {
if len(e.objectTypes) > 0 {
foundType := false
for _, typ := range e.objectTypes {
if typ == string(event.ObjectType) {
foundType = true
break
}
}
if !foundType {
return
}
}
if e.objectID != "" && e.objectID != event.ObjectID {
return
}
select {
case e.queue <- event:
default:
// Run in a goroutine to avoid deadlock with Notify
go e.CloseWithError(ErrEventBufferOverflow)
}
} | go | func (e *EventSubscriber) Notify(event *ct.Event) {
if len(e.objectTypes) > 0 {
foundType := false
for _, typ := range e.objectTypes {
if typ == string(event.ObjectType) {
foundType = true
break
}
}
if !foundType {
return
}
}
if e.objectID != "" && e.objectID != event.ObjectID {
return
}
select {
case e.queue <- event:
default:
// Run in a goroutine to avoid deadlock with Notify
go e.CloseWithError(ErrEventBufferOverflow)
}
} | [
"func",
"(",
"e",
"*",
"EventSubscriber",
")",
"Notify",
"(",
"event",
"*",
"ct",
".",
"Event",
")",
"{",
"if",
"len",
"(",
"e",
".",
"objectTypes",
")",
">",
"0",
"{",
"foundType",
":=",
"false",
"\n",
"for",
"_",
",",
"typ",
":=",
"range",
"e",
".",
"objectTypes",
"{",
"if",
"typ",
"==",
"string",
"(",
"event",
".",
"ObjectType",
")",
"{",
"foundType",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"foundType",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"e",
".",
"objectID",
"!=",
"\"",
"\"",
"&&",
"e",
".",
"objectID",
"!=",
"event",
".",
"ObjectID",
"{",
"return",
"\n",
"}",
"\n",
"select",
"{",
"case",
"e",
".",
"queue",
"<-",
"event",
":",
"default",
":",
"// Run in a goroutine to avoid deadlock with Notify",
"go",
"e",
".",
"CloseWithError",
"(",
"ErrEventBufferOverflow",
")",
"\n",
"}",
"\n",
"}"
] | // Notify filters the event based on it's type and objectID and then pushes
// it to the event queue. | [
"Notify",
"filters",
"the",
"event",
"based",
"on",
"it",
"s",
"type",
"and",
"objectID",
"and",
"then",
"pushes",
"it",
"to",
"the",
"event",
"queue",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/controller/events.go#L328-L350 | train |
flynn/flynn | controller/events.go | loop | func (e *EventSubscriber) loop() {
defer close(e.Events)
for {
select {
case <-e.stop:
return
case event := <-e.queue:
e.Events <- event
}
}
} | go | func (e *EventSubscriber) loop() {
defer close(e.Events)
for {
select {
case <-e.stop:
return
case event := <-e.queue:
e.Events <- event
}
}
} | [
"func",
"(",
"e",
"*",
"EventSubscriber",
")",
"loop",
"(",
")",
"{",
"defer",
"close",
"(",
"e",
".",
"Events",
")",
"\n",
"for",
"{",
"select",
"{",
"case",
"<-",
"e",
".",
"stop",
":",
"return",
"\n",
"case",
"event",
":=",
"<-",
"e",
".",
"queue",
":",
"e",
".",
"Events",
"<-",
"event",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // loop pops events off the queue and sends them to the Events channel. | [
"loop",
"pops",
"events",
"off",
"the",
"queue",
"and",
"sends",
"them",
"to",
"the",
"Events",
"channel",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/controller/events.go#L353-L363 | train |
flynn/flynn | controller/events.go | Close | func (e *EventSubscriber) Close() {
e.l.Unsubscribe(e)
e.stopOnce.Do(func() { close(e.stop) })
} | go | func (e *EventSubscriber) Close() {
e.l.Unsubscribe(e)
e.stopOnce.Do(func() { close(e.stop) })
} | [
"func",
"(",
"e",
"*",
"EventSubscriber",
")",
"Close",
"(",
")",
"{",
"e",
".",
"l",
".",
"Unsubscribe",
"(",
"e",
")",
"\n",
"e",
".",
"stopOnce",
".",
"Do",
"(",
"func",
"(",
")",
"{",
"close",
"(",
"e",
".",
"stop",
")",
"}",
")",
"\n",
"}"
] | // Close unsubscribes from the EventListener and stops the loop. | [
"Close",
"unsubscribes",
"from",
"the",
"EventListener",
"and",
"stops",
"the",
"loop",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/controller/events.go#L366-L369 | train |
flynn/flynn | controller/events.go | CloseWithError | func (e *EventSubscriber) CloseWithError(err error) {
e.errOnce.Do(func() { e.Err = err })
e.Close()
} | go | func (e *EventSubscriber) CloseWithError(err error) {
e.errOnce.Do(func() { e.Err = err })
e.Close()
} | [
"func",
"(",
"e",
"*",
"EventSubscriber",
")",
"CloseWithError",
"(",
"err",
"error",
")",
"{",
"e",
".",
"errOnce",
".",
"Do",
"(",
"func",
"(",
")",
"{",
"e",
".",
"Err",
"=",
"err",
"}",
")",
"\n",
"e",
".",
"Close",
"(",
")",
"\n",
"}"
] | // CloseWithError sets the Err field and then closes the subscriber. | [
"CloseWithError",
"sets",
"the",
"Err",
"field",
"and",
"then",
"closes",
"the",
"subscriber",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/controller/events.go#L372-L375 | train |
flynn/flynn | controller/events.go | Subscribe | func (e *EventListener) Subscribe(appID string, objectTypes []string, objectID string) (*EventSubscriber, error) {
e.subMtx.Lock()
defer e.subMtx.Unlock()
if e.IsClosed() {
return nil, errors.New("event listener closed")
}
s := &EventSubscriber{
Events: make(chan *ct.Event),
l: e,
queue: make(chan *ct.Event, eventBufferSize),
stop: make(chan struct{}),
appID: appID,
objectTypes: objectTypes,
objectID: objectID,
}
go s.loop()
if _, ok := e.subscribers[appID]; !ok {
e.subscribers[appID] = make(map[*EventSubscriber]struct{})
}
e.subscribers[appID][s] = struct{}{}
return s, nil
} | go | func (e *EventListener) Subscribe(appID string, objectTypes []string, objectID string) (*EventSubscriber, error) {
e.subMtx.Lock()
defer e.subMtx.Unlock()
if e.IsClosed() {
return nil, errors.New("event listener closed")
}
s := &EventSubscriber{
Events: make(chan *ct.Event),
l: e,
queue: make(chan *ct.Event, eventBufferSize),
stop: make(chan struct{}),
appID: appID,
objectTypes: objectTypes,
objectID: objectID,
}
go s.loop()
if _, ok := e.subscribers[appID]; !ok {
e.subscribers[appID] = make(map[*EventSubscriber]struct{})
}
e.subscribers[appID][s] = struct{}{}
return s, nil
} | [
"func",
"(",
"e",
"*",
"EventListener",
")",
"Subscribe",
"(",
"appID",
"string",
",",
"objectTypes",
"[",
"]",
"string",
",",
"objectID",
"string",
")",
"(",
"*",
"EventSubscriber",
",",
"error",
")",
"{",
"e",
".",
"subMtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"e",
".",
"subMtx",
".",
"Unlock",
"(",
")",
"\n",
"if",
"e",
".",
"IsClosed",
"(",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"s",
":=",
"&",
"EventSubscriber",
"{",
"Events",
":",
"make",
"(",
"chan",
"*",
"ct",
".",
"Event",
")",
",",
"l",
":",
"e",
",",
"queue",
":",
"make",
"(",
"chan",
"*",
"ct",
".",
"Event",
",",
"eventBufferSize",
")",
",",
"stop",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"appID",
":",
"appID",
",",
"objectTypes",
":",
"objectTypes",
",",
"objectID",
":",
"objectID",
",",
"}",
"\n",
"go",
"s",
".",
"loop",
"(",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"e",
".",
"subscribers",
"[",
"appID",
"]",
";",
"!",
"ok",
"{",
"e",
".",
"subscribers",
"[",
"appID",
"]",
"=",
"make",
"(",
"map",
"[",
"*",
"EventSubscriber",
"]",
"struct",
"{",
"}",
")",
"\n",
"}",
"\n",
"e",
".",
"subscribers",
"[",
"appID",
"]",
"[",
"s",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"return",
"s",
",",
"nil",
"\n",
"}"
] | // Subscribe creates and returns an EventSubscriber for the given app, type and object.
// Using an empty string for appID subscribes to all apps | [
"Subscribe",
"creates",
"and",
"returns",
"an",
"EventSubscriber",
"for",
"the",
"given",
"app",
"type",
"and",
"object",
".",
"Using",
"an",
"empty",
"string",
"for",
"appID",
"subscribes",
"to",
"all",
"apps"
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/controller/events.go#L400-L421 | train |
flynn/flynn | controller/events.go | Unsubscribe | func (e *EventListener) Unsubscribe(s *EventSubscriber) {
e.subMtx.Lock()
defer e.subMtx.Unlock()
if subs, ok := e.subscribers[s.appID]; ok {
delete(subs, s)
if len(subs) == 0 {
delete(e.subscribers, s.appID)
}
}
} | go | func (e *EventListener) Unsubscribe(s *EventSubscriber) {
e.subMtx.Lock()
defer e.subMtx.Unlock()
if subs, ok := e.subscribers[s.appID]; ok {
delete(subs, s)
if len(subs) == 0 {
delete(e.subscribers, s.appID)
}
}
} | [
"func",
"(",
"e",
"*",
"EventListener",
")",
"Unsubscribe",
"(",
"s",
"*",
"EventSubscriber",
")",
"{",
"e",
".",
"subMtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"e",
".",
"subMtx",
".",
"Unlock",
"(",
")",
"\n",
"if",
"subs",
",",
"ok",
":=",
"e",
".",
"subscribers",
"[",
"s",
".",
"appID",
"]",
";",
"ok",
"{",
"delete",
"(",
"subs",
",",
"s",
")",
"\n",
"if",
"len",
"(",
"subs",
")",
"==",
"0",
"{",
"delete",
"(",
"e",
".",
"subscribers",
",",
"s",
".",
"appID",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Unsubscribe unsubscribes the given subscriber. | [
"Unsubscribe",
"unsubscribes",
"the",
"given",
"subscriber",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/controller/events.go#L424-L433 | train |
flynn/flynn | controller/events.go | Listen | func (e *EventListener) Listen() error {
log := logger.New("fn", "EventListener.Listen")
listener, err := e.eventRepo.db.Listen("events", log)
if err != nil {
e.CloseWithError(err)
return err
}
go func() {
for {
select {
case n, ok := <-listener.Notify:
if !ok {
e.CloseWithError(listener.Err)
return
}
idApp := strings.SplitN(n.Payload, ":", 2)
if len(idApp) < 1 {
log.Error(fmt.Sprintf("invalid event notification: %q", n.Payload))
continue
}
id, err := strconv.ParseInt(idApp[0], 10, 64)
if err != nil {
log.Error(fmt.Sprintf("invalid event notification: %q", n.Payload), "err", err)
continue
}
event, err := e.eventRepo.GetEvent(id)
if err != nil {
log.Error(fmt.Sprintf("invalid event notification: %q", n.Payload), "err", err)
continue
}
e.Notify(event)
case <-e.doneCh:
listener.Close()
return
}
}
}()
return nil
} | go | func (e *EventListener) Listen() error {
log := logger.New("fn", "EventListener.Listen")
listener, err := e.eventRepo.db.Listen("events", log)
if err != nil {
e.CloseWithError(err)
return err
}
go func() {
for {
select {
case n, ok := <-listener.Notify:
if !ok {
e.CloseWithError(listener.Err)
return
}
idApp := strings.SplitN(n.Payload, ":", 2)
if len(idApp) < 1 {
log.Error(fmt.Sprintf("invalid event notification: %q", n.Payload))
continue
}
id, err := strconv.ParseInt(idApp[0], 10, 64)
if err != nil {
log.Error(fmt.Sprintf("invalid event notification: %q", n.Payload), "err", err)
continue
}
event, err := e.eventRepo.GetEvent(id)
if err != nil {
log.Error(fmt.Sprintf("invalid event notification: %q", n.Payload), "err", err)
continue
}
e.Notify(event)
case <-e.doneCh:
listener.Close()
return
}
}
}()
return nil
} | [
"func",
"(",
"e",
"*",
"EventListener",
")",
"Listen",
"(",
")",
"error",
"{",
"log",
":=",
"logger",
".",
"New",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"listener",
",",
"err",
":=",
"e",
".",
"eventRepo",
".",
"db",
".",
"Listen",
"(",
"\"",
"\"",
",",
"log",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"e",
".",
"CloseWithError",
"(",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"go",
"func",
"(",
")",
"{",
"for",
"{",
"select",
"{",
"case",
"n",
",",
"ok",
":=",
"<-",
"listener",
".",
"Notify",
":",
"if",
"!",
"ok",
"{",
"e",
".",
"CloseWithError",
"(",
"listener",
".",
"Err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"idApp",
":=",
"strings",
".",
"SplitN",
"(",
"n",
".",
"Payload",
",",
"\"",
"\"",
",",
"2",
")",
"\n",
"if",
"len",
"(",
"idApp",
")",
"<",
"1",
"{",
"log",
".",
"Error",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"n",
".",
"Payload",
")",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"id",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"idApp",
"[",
"0",
"]",
",",
"10",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Error",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"n",
".",
"Payload",
")",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"event",
",",
"err",
":=",
"e",
".",
"eventRepo",
".",
"GetEvent",
"(",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Error",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"n",
".",
"Payload",
")",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"e",
".",
"Notify",
"(",
"event",
")",
"\n",
"case",
"<-",
"e",
".",
"doneCh",
":",
"listener",
".",
"Close",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Listen creates a postgres listener for events and starts a goroutine to
// forward the events to subscribers. | [
"Listen",
"creates",
"a",
"postgres",
"listener",
"for",
"events",
"and",
"starts",
"a",
"goroutine",
"to",
"forward",
"the",
"events",
"to",
"subscribers",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/controller/events.go#L437-L475 | train |
flynn/flynn | controller/events.go | Notify | func (e *EventListener) Notify(event *ct.Event) {
e.subMtx.RLock()
defer e.subMtx.RUnlock()
if subs, ok := e.subscribers[event.AppID]; ok {
for sub := range subs {
sub.Notify(event)
}
}
if event.AppID != "" {
// Ensure subscribers not filtering by app get the event
if subs, ok := e.subscribers[""]; ok {
for sub := range subs {
sub.Notify(event)
}
}
}
} | go | func (e *EventListener) Notify(event *ct.Event) {
e.subMtx.RLock()
defer e.subMtx.RUnlock()
if subs, ok := e.subscribers[event.AppID]; ok {
for sub := range subs {
sub.Notify(event)
}
}
if event.AppID != "" {
// Ensure subscribers not filtering by app get the event
if subs, ok := e.subscribers[""]; ok {
for sub := range subs {
sub.Notify(event)
}
}
}
} | [
"func",
"(",
"e",
"*",
"EventListener",
")",
"Notify",
"(",
"event",
"*",
"ct",
".",
"Event",
")",
"{",
"e",
".",
"subMtx",
".",
"RLock",
"(",
")",
"\n",
"defer",
"e",
".",
"subMtx",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"subs",
",",
"ok",
":=",
"e",
".",
"subscribers",
"[",
"event",
".",
"AppID",
"]",
";",
"ok",
"{",
"for",
"sub",
":=",
"range",
"subs",
"{",
"sub",
".",
"Notify",
"(",
"event",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"event",
".",
"AppID",
"!=",
"\"",
"\"",
"{",
"// Ensure subscribers not filtering by app get the event",
"if",
"subs",
",",
"ok",
":=",
"e",
".",
"subscribers",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"for",
"sub",
":=",
"range",
"subs",
"{",
"sub",
".",
"Notify",
"(",
"event",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Notify notifies all sbscribers of the given event. | [
"Notify",
"notifies",
"all",
"sbscribers",
"of",
"the",
"given",
"event",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/controller/events.go#L478-L494 | train |
flynn/flynn | controller/events.go | IsClosed | func (e *EventListener) IsClosed() bool {
e.closedMtx.RLock()
defer e.closedMtx.RUnlock()
return e.closed
} | go | func (e *EventListener) IsClosed() bool {
e.closedMtx.RLock()
defer e.closedMtx.RUnlock()
return e.closed
} | [
"func",
"(",
"e",
"*",
"EventListener",
")",
"IsClosed",
"(",
")",
"bool",
"{",
"e",
".",
"closedMtx",
".",
"RLock",
"(",
")",
"\n",
"defer",
"e",
".",
"closedMtx",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"e",
".",
"closed",
"\n",
"}"
] | // IsClosed returns whether or not the listener is closed. | [
"IsClosed",
"returns",
"whether",
"or",
"not",
"the",
"listener",
"is",
"closed",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/controller/events.go#L497-L501 | train |
flynn/flynn | controller/events.go | CloseWithError | func (e *EventListener) CloseWithError(err error) {
e.closedMtx.Lock()
if e.closed {
e.closedMtx.Unlock()
return
}
e.closed = true
e.closedMtx.Unlock()
e.subMtx.RLock()
defer e.subMtx.RUnlock()
subscribers := e.subscribers
for _, subs := range subscribers {
for sub := range subs {
go sub.CloseWithError(err)
}
}
close(e.doneCh)
} | go | func (e *EventListener) CloseWithError(err error) {
e.closedMtx.Lock()
if e.closed {
e.closedMtx.Unlock()
return
}
e.closed = true
e.closedMtx.Unlock()
e.subMtx.RLock()
defer e.subMtx.RUnlock()
subscribers := e.subscribers
for _, subs := range subscribers {
for sub := range subs {
go sub.CloseWithError(err)
}
}
close(e.doneCh)
} | [
"func",
"(",
"e",
"*",
"EventListener",
")",
"CloseWithError",
"(",
"err",
"error",
")",
"{",
"e",
".",
"closedMtx",
".",
"Lock",
"(",
")",
"\n",
"if",
"e",
".",
"closed",
"{",
"e",
".",
"closedMtx",
".",
"Unlock",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"e",
".",
"closed",
"=",
"true",
"\n",
"e",
".",
"closedMtx",
".",
"Unlock",
"(",
")",
"\n\n",
"e",
".",
"subMtx",
".",
"RLock",
"(",
")",
"\n",
"defer",
"e",
".",
"subMtx",
".",
"RUnlock",
"(",
")",
"\n",
"subscribers",
":=",
"e",
".",
"subscribers",
"\n",
"for",
"_",
",",
"subs",
":=",
"range",
"subscribers",
"{",
"for",
"sub",
":=",
"range",
"subs",
"{",
"go",
"sub",
".",
"CloseWithError",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"close",
"(",
"e",
".",
"doneCh",
")",
"\n",
"}"
] | // CloseWithError marks the listener as closed and closes all subscribers
// with the given error. | [
"CloseWithError",
"marks",
"the",
"listener",
"as",
"closed",
"and",
"closes",
"all",
"subscribers",
"with",
"the",
"given",
"error",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/controller/events.go#L505-L523 | train |
flynn/flynn | pkg/rpcplus/server.go | prepareMethod | func prepareMethod(method reflect.Method) *methodType {
mtype := method.Type
mname := method.Name
var replyType, argType, contextType reflect.Type
stream := false
// Method must be exported.
if method.PkgPath != "" {
return nil
}
switch mtype.NumIn() {
case 3:
// normal method
argType = mtype.In(1)
replyType = mtype.In(2)
contextType = nil
case 4:
// method that takes a context
argType = mtype.In(2)
replyType = mtype.In(3)
contextType = mtype.In(1)
default:
log.Println("method", mname, "of", mtype, "has wrong number of ins:", mtype.NumIn())
return nil
}
// First arg need not be a pointer.
if !isExportedOrBuiltinType(argType) {
log.Println(mname, "argument type not exported:", argType)
return nil
}
// the second argument will tell us if it's a streaming call
// or a regular call
if replyType == typeOfStream {
// this is a streaming call
stream = true
} else if replyType.Kind() != reflect.Ptr {
log.Println("method", mname, "reply type not a pointer:", replyType)
return nil
}
// Reply type must be exported.
if !isExportedOrBuiltinType(replyType) {
log.Println("method", mname, "reply type not exported:", replyType)
return nil
}
// Method needs one out.
if mtype.NumOut() != 1 {
log.Println("method", mname, "has wrong number of outs:", mtype.NumOut())
return nil
}
// The return type of the method must be error.
if returnType := mtype.Out(0); returnType != typeOfError {
log.Println("method", mname, "returns", returnType.String(), "not error")
return nil
}
return &methodType{method: method, ArgType: argType, ReplyType: replyType, ContextType: contextType, stream: stream}
} | go | func prepareMethod(method reflect.Method) *methodType {
mtype := method.Type
mname := method.Name
var replyType, argType, contextType reflect.Type
stream := false
// Method must be exported.
if method.PkgPath != "" {
return nil
}
switch mtype.NumIn() {
case 3:
// normal method
argType = mtype.In(1)
replyType = mtype.In(2)
contextType = nil
case 4:
// method that takes a context
argType = mtype.In(2)
replyType = mtype.In(3)
contextType = mtype.In(1)
default:
log.Println("method", mname, "of", mtype, "has wrong number of ins:", mtype.NumIn())
return nil
}
// First arg need not be a pointer.
if !isExportedOrBuiltinType(argType) {
log.Println(mname, "argument type not exported:", argType)
return nil
}
// the second argument will tell us if it's a streaming call
// or a regular call
if replyType == typeOfStream {
// this is a streaming call
stream = true
} else if replyType.Kind() != reflect.Ptr {
log.Println("method", mname, "reply type not a pointer:", replyType)
return nil
}
// Reply type must be exported.
if !isExportedOrBuiltinType(replyType) {
log.Println("method", mname, "reply type not exported:", replyType)
return nil
}
// Method needs one out.
if mtype.NumOut() != 1 {
log.Println("method", mname, "has wrong number of outs:", mtype.NumOut())
return nil
}
// The return type of the method must be error.
if returnType := mtype.Out(0); returnType != typeOfError {
log.Println("method", mname, "returns", returnType.String(), "not error")
return nil
}
return &methodType{method: method, ArgType: argType, ReplyType: replyType, ContextType: contextType, stream: stream}
} | [
"func",
"prepareMethod",
"(",
"method",
"reflect",
".",
"Method",
")",
"*",
"methodType",
"{",
"mtype",
":=",
"method",
".",
"Type",
"\n",
"mname",
":=",
"method",
".",
"Name",
"\n",
"var",
"replyType",
",",
"argType",
",",
"contextType",
"reflect",
".",
"Type",
"\n\n",
"stream",
":=",
"false",
"\n",
"// Method must be exported.",
"if",
"method",
".",
"PkgPath",
"!=",
"\"",
"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"switch",
"mtype",
".",
"NumIn",
"(",
")",
"{",
"case",
"3",
":",
"// normal method",
"argType",
"=",
"mtype",
".",
"In",
"(",
"1",
")",
"\n",
"replyType",
"=",
"mtype",
".",
"In",
"(",
"2",
")",
"\n",
"contextType",
"=",
"nil",
"\n",
"case",
"4",
":",
"// method that takes a context",
"argType",
"=",
"mtype",
".",
"In",
"(",
"2",
")",
"\n",
"replyType",
"=",
"mtype",
".",
"In",
"(",
"3",
")",
"\n",
"contextType",
"=",
"mtype",
".",
"In",
"(",
"1",
")",
"\n",
"default",
":",
"log",
".",
"Println",
"(",
"\"",
"\"",
",",
"mname",
",",
"\"",
"\"",
",",
"mtype",
",",
"\"",
"\"",
",",
"mtype",
".",
"NumIn",
"(",
")",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"// First arg need not be a pointer.",
"if",
"!",
"isExportedOrBuiltinType",
"(",
"argType",
")",
"{",
"log",
".",
"Println",
"(",
"mname",
",",
"\"",
"\"",
",",
"argType",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"// the second argument will tell us if it's a streaming call",
"// or a regular call",
"if",
"replyType",
"==",
"typeOfStream",
"{",
"// this is a streaming call",
"stream",
"=",
"true",
"\n",
"}",
"else",
"if",
"replyType",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Ptr",
"{",
"log",
".",
"Println",
"(",
"\"",
"\"",
",",
"mname",
",",
"\"",
"\"",
",",
"replyType",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Reply type must be exported.",
"if",
"!",
"isExportedOrBuiltinType",
"(",
"replyType",
")",
"{",
"log",
".",
"Println",
"(",
"\"",
"\"",
",",
"mname",
",",
"\"",
"\"",
",",
"replyType",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"// Method needs one out.",
"if",
"mtype",
".",
"NumOut",
"(",
")",
"!=",
"1",
"{",
"log",
".",
"Println",
"(",
"\"",
"\"",
",",
"mname",
",",
"\"",
"\"",
",",
"mtype",
".",
"NumOut",
"(",
")",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"// The return type of the method must be error.",
"if",
"returnType",
":=",
"mtype",
".",
"Out",
"(",
"0",
")",
";",
"returnType",
"!=",
"typeOfError",
"{",
"log",
".",
"Println",
"(",
"\"",
"\"",
",",
"mname",
",",
"\"",
"\"",
",",
"returnType",
".",
"String",
"(",
")",
",",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"&",
"methodType",
"{",
"method",
":",
"method",
",",
"ArgType",
":",
"argType",
",",
"ReplyType",
":",
"replyType",
",",
"ContextType",
":",
"contextType",
",",
"stream",
":",
"stream",
"}",
"\n",
"}"
] | // prepareMethod returns a methodType for the provided method or nil
// in case if the method was unsuitable. | [
"prepareMethod",
"returns",
"a",
"methodType",
"for",
"the",
"provided",
"method",
"or",
"nil",
"in",
"case",
"if",
"the",
"method",
"was",
"unsuitable",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/rpcplus/server.go#L261-L320 | train |
flynn/flynn | pkg/rpcplus/server.go | ServeConnWithContext | func (server *Server) ServeConnWithContext(conn io.ReadWriteCloser, context interface{}) {
buf := bufio.NewWriter(conn)
srv := &gobServerCodec{conn, gob.NewDecoder(conn), gob.NewEncoder(buf), buf}
server.ServeCodecWithContext(srv, context)
} | go | func (server *Server) ServeConnWithContext(conn io.ReadWriteCloser, context interface{}) {
buf := bufio.NewWriter(conn)
srv := &gobServerCodec{conn, gob.NewDecoder(conn), gob.NewEncoder(buf), buf}
server.ServeCodecWithContext(srv, context)
} | [
"func",
"(",
"server",
"*",
"Server",
")",
"ServeConnWithContext",
"(",
"conn",
"io",
".",
"ReadWriteCloser",
",",
"context",
"interface",
"{",
"}",
")",
"{",
"buf",
":=",
"bufio",
".",
"NewWriter",
"(",
"conn",
")",
"\n",
"srv",
":=",
"&",
"gobServerCodec",
"{",
"conn",
",",
"gob",
".",
"NewDecoder",
"(",
"conn",
")",
",",
"gob",
".",
"NewEncoder",
"(",
"buf",
")",
",",
"buf",
"}",
"\n",
"server",
".",
"ServeCodecWithContext",
"(",
"srv",
",",
"context",
")",
"\n",
"}"
] | // ServeConnWithContext is like ServeConn but makes it possible to
// pass a connection context to the RPC methods. | [
"ServeConnWithContext",
"is",
"like",
"ServeConn",
"but",
"makes",
"it",
"possible",
"to",
"pass",
"a",
"connection",
"context",
"to",
"the",
"RPC",
"methods",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/rpcplus/server.go#L538-L542 | train |
flynn/flynn | pkg/rpcplus/server.go | ServeCodecWithContext | func (server *Server) ServeCodecWithContext(codec ServerCodec, context interface{}) {
sending := new(sync.Mutex)
eof := make(chan struct{})
stopChans := make(map[uint64]chan struct{})
var stopChansMtx sync.Mutex
var contextVal reflect.Value
if context != nil {
contextVal = reflect.ValueOf(context)
} else {
contextVal = reflect.New(server.contextType)
}
for {
service, mtype, req, argv, replyv, keepReading, err := server.readRequest(codec)
if err != nil {
if err == errCloseStream {
go func() {
stopChansMtx.Lock()
stop, ok := stopChans[req.Seq]
delete(stopChans, req.Seq)
stopChansMtx.Unlock()
if !ok {
return
}
close(stop)
}()
continue
}
if !keepReading {
break
}
// send a response if we actually managed to read a header.
if req != nil {
server.sendResponse(sending, req, invalidRequest, codec, err.Error(), true)
server.freeRequest(req)
}
continue
}
done := make(chan struct{})
stop := make(chan struct{})
stopChansMtx.Lock()
stopChans[req.Seq] = stop
stopChansMtx.Unlock()
go func(seq uint64) {
<-done
stopChansMtx.Lock()
delete(stopChans, seq)
stopChansMtx.Unlock()
}(req.Seq)
go service.call(call{
server: server,
sending: sending,
mtype: mtype,
req: req,
argv: argv,
replyv: replyv,
codec: codec,
context: contextVal,
eof: eof,
done: done,
stop: stop,
})
}
close(eof)
codec.Close()
} | go | func (server *Server) ServeCodecWithContext(codec ServerCodec, context interface{}) {
sending := new(sync.Mutex)
eof := make(chan struct{})
stopChans := make(map[uint64]chan struct{})
var stopChansMtx sync.Mutex
var contextVal reflect.Value
if context != nil {
contextVal = reflect.ValueOf(context)
} else {
contextVal = reflect.New(server.contextType)
}
for {
service, mtype, req, argv, replyv, keepReading, err := server.readRequest(codec)
if err != nil {
if err == errCloseStream {
go func() {
stopChansMtx.Lock()
stop, ok := stopChans[req.Seq]
delete(stopChans, req.Seq)
stopChansMtx.Unlock()
if !ok {
return
}
close(stop)
}()
continue
}
if !keepReading {
break
}
// send a response if we actually managed to read a header.
if req != nil {
server.sendResponse(sending, req, invalidRequest, codec, err.Error(), true)
server.freeRequest(req)
}
continue
}
done := make(chan struct{})
stop := make(chan struct{})
stopChansMtx.Lock()
stopChans[req.Seq] = stop
stopChansMtx.Unlock()
go func(seq uint64) {
<-done
stopChansMtx.Lock()
delete(stopChans, seq)
stopChansMtx.Unlock()
}(req.Seq)
go service.call(call{
server: server,
sending: sending,
mtype: mtype,
req: req,
argv: argv,
replyv: replyv,
codec: codec,
context: contextVal,
eof: eof,
done: done,
stop: stop,
})
}
close(eof)
codec.Close()
} | [
"func",
"(",
"server",
"*",
"Server",
")",
"ServeCodecWithContext",
"(",
"codec",
"ServerCodec",
",",
"context",
"interface",
"{",
"}",
")",
"{",
"sending",
":=",
"new",
"(",
"sync",
".",
"Mutex",
")",
"\n",
"eof",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n\n",
"stopChans",
":=",
"make",
"(",
"map",
"[",
"uint64",
"]",
"chan",
"struct",
"{",
"}",
")",
"\n",
"var",
"stopChansMtx",
"sync",
".",
"Mutex",
"\n\n",
"var",
"contextVal",
"reflect",
".",
"Value",
"\n",
"if",
"context",
"!=",
"nil",
"{",
"contextVal",
"=",
"reflect",
".",
"ValueOf",
"(",
"context",
")",
"\n",
"}",
"else",
"{",
"contextVal",
"=",
"reflect",
".",
"New",
"(",
"server",
".",
"contextType",
")",
"\n",
"}",
"\n",
"for",
"{",
"service",
",",
"mtype",
",",
"req",
",",
"argv",
",",
"replyv",
",",
"keepReading",
",",
"err",
":=",
"server",
".",
"readRequest",
"(",
"codec",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"errCloseStream",
"{",
"go",
"func",
"(",
")",
"{",
"stopChansMtx",
".",
"Lock",
"(",
")",
"\n",
"stop",
",",
"ok",
":=",
"stopChans",
"[",
"req",
".",
"Seq",
"]",
"\n",
"delete",
"(",
"stopChans",
",",
"req",
".",
"Seq",
")",
"\n",
"stopChansMtx",
".",
"Unlock",
"(",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\n",
"}",
"\n",
"close",
"(",
"stop",
")",
"\n",
"}",
"(",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"!",
"keepReading",
"{",
"break",
"\n",
"}",
"\n",
"// send a response if we actually managed to read a header.",
"if",
"req",
"!=",
"nil",
"{",
"server",
".",
"sendResponse",
"(",
"sending",
",",
"req",
",",
"invalidRequest",
",",
"codec",
",",
"err",
".",
"Error",
"(",
")",
",",
"true",
")",
"\n",
"server",
".",
"freeRequest",
"(",
"req",
")",
"\n",
"}",
"\n",
"continue",
"\n",
"}",
"\n\n",
"done",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"stop",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"stopChansMtx",
".",
"Lock",
"(",
")",
"\n",
"stopChans",
"[",
"req",
".",
"Seq",
"]",
"=",
"stop",
"\n",
"stopChansMtx",
".",
"Unlock",
"(",
")",
"\n\n",
"go",
"func",
"(",
"seq",
"uint64",
")",
"{",
"<-",
"done",
"\n",
"stopChansMtx",
".",
"Lock",
"(",
")",
"\n",
"delete",
"(",
"stopChans",
",",
"seq",
")",
"\n",
"stopChansMtx",
".",
"Unlock",
"(",
")",
"\n",
"}",
"(",
"req",
".",
"Seq",
")",
"\n",
"go",
"service",
".",
"call",
"(",
"call",
"{",
"server",
":",
"server",
",",
"sending",
":",
"sending",
",",
"mtype",
":",
"mtype",
",",
"req",
":",
"req",
",",
"argv",
":",
"argv",
",",
"replyv",
":",
"replyv",
",",
"codec",
":",
"codec",
",",
"context",
":",
"contextVal",
",",
"eof",
":",
"eof",
",",
"done",
":",
"done",
",",
"stop",
":",
"stop",
",",
"}",
")",
"\n",
"}",
"\n",
"close",
"(",
"eof",
")",
"\n",
"codec",
".",
"Close",
"(",
")",
"\n",
"}"
] | // ServeCodecWithContext is like ServeCodec but it makes it possible
// to pass a connection context to the RPC methods. | [
"ServeCodecWithContext",
"is",
"like",
"ServeCodec",
"but",
"it",
"makes",
"it",
"possible",
"to",
"pass",
"a",
"connection",
"context",
"to",
"the",
"RPC",
"methods",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/rpcplus/server.go#L552-L620 | train |
flynn/flynn | pkg/rpcplus/server.go | Accept | func (server *Server) Accept(lis net.Listener) {
for {
conn, err := lis.Accept()
if err != nil {
log.Fatal("rpc.Serve: accept:", err.Error()) // TODO(r): exit?
}
go server.ServeConn(conn)
}
} | go | func (server *Server) Accept(lis net.Listener) {
for {
conn, err := lis.Accept()
if err != nil {
log.Fatal("rpc.Serve: accept:", err.Error()) // TODO(r): exit?
}
go server.ServeConn(conn)
}
} | [
"func",
"(",
"server",
"*",
"Server",
")",
"Accept",
"(",
"lis",
"net",
".",
"Listener",
")",
"{",
"for",
"{",
"conn",
",",
"err",
":=",
"lis",
".",
"Accept",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatal",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"// TODO(r): exit?",
"\n",
"}",
"\n",
"go",
"server",
".",
"ServeConn",
"(",
"conn",
")",
"\n",
"}",
"\n",
"}"
] | // Accept accepts connections on the listener and serves requests
// for each incoming connection. Accept blocks; the caller typically
// invokes it in a go statement. | [
"Accept",
"accepts",
"connections",
"on",
"the",
"listener",
"and",
"serves",
"requests",
"for",
"each",
"incoming",
"connection",
".",
"Accept",
"blocks",
";",
"the",
"caller",
"typically",
"invokes",
"it",
"in",
"a",
"go",
"statement",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/rpcplus/server.go#L742-L750 | train |
flynn/flynn | pkg/rpcplus/server.go | ServeHTTP | func (server *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if req.Method != "CONNECT" {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusMethodNotAllowed)
io.WriteString(w, "405 must CONNECT\n")
return
}
conn, _, err := w.(http.Hijacker).Hijack()
if err != nil {
log.Print("rpc hijacking ", req.RemoteAddr, ": ", err.Error())
return
}
io.WriteString(conn, "HTTP/1.0 "+connected+"\n\n")
server.ServeConn(conn)
} | go | func (server *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if req.Method != "CONNECT" {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusMethodNotAllowed)
io.WriteString(w, "405 must CONNECT\n")
return
}
conn, _, err := w.(http.Hijacker).Hijack()
if err != nil {
log.Print("rpc hijacking ", req.RemoteAddr, ": ", err.Error())
return
}
io.WriteString(conn, "HTTP/1.0 "+connected+"\n\n")
server.ServeConn(conn)
} | [
"func",
"(",
"server",
"*",
"Server",
")",
"ServeHTTP",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"req",
".",
"Method",
"!=",
"\"",
"\"",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusMethodNotAllowed",
")",
"\n",
"io",
".",
"WriteString",
"(",
"w",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"conn",
",",
"_",
",",
"err",
":=",
"w",
".",
"(",
"http",
".",
"Hijacker",
")",
".",
"Hijack",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Print",
"(",
"\"",
"\"",
",",
"req",
".",
"RemoteAddr",
",",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"io",
".",
"WriteString",
"(",
"conn",
",",
"\"",
"\"",
"+",
"connected",
"+",
"\"",
"\\n",
"\\n",
"\"",
")",
"\n",
"server",
".",
"ServeConn",
"(",
"conn",
")",
"\n",
"}"
] | // ServeHTTP implements an http.Handler that answers RPC requests. | [
"ServeHTTP",
"implements",
"an",
"http",
".",
"Handler",
"that",
"answers",
"RPC",
"requests",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/rpcplus/server.go#L812-L826 | train |
flynn/flynn | appliance/mariadb/process.go | Backup | func (p *Process) Backup() (io.ReadCloser, error) {
r := &backupReadCloser{}
cmd := exec.Command(
filepath.Join(p.BinDir, "innobackupex"),
"--defaults-file="+p.ConfigPath(),
"--host=127.0.0.1",
"--port="+p.Port,
"--user=flynn",
"--password="+p.Password,
"--socket=",
"--stream=xbstream",
".",
)
cmd.Dir = p.DataDir
cmd.Stderr = &r.stderr
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
if err := cmd.Start(); err != nil {
stdout.Close()
return nil, err
}
// Attach to reader wrapper.
r.cmd = cmd
r.stdout = stdout
return r, nil
} | go | func (p *Process) Backup() (io.ReadCloser, error) {
r := &backupReadCloser{}
cmd := exec.Command(
filepath.Join(p.BinDir, "innobackupex"),
"--defaults-file="+p.ConfigPath(),
"--host=127.0.0.1",
"--port="+p.Port,
"--user=flynn",
"--password="+p.Password,
"--socket=",
"--stream=xbstream",
".",
)
cmd.Dir = p.DataDir
cmd.Stderr = &r.stderr
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
if err := cmd.Start(); err != nil {
stdout.Close()
return nil, err
}
// Attach to reader wrapper.
r.cmd = cmd
r.stdout = stdout
return r, nil
} | [
"func",
"(",
"p",
"*",
"Process",
")",
"Backup",
"(",
")",
"(",
"io",
".",
"ReadCloser",
",",
"error",
")",
"{",
"r",
":=",
"&",
"backupReadCloser",
"{",
"}",
"\n\n",
"cmd",
":=",
"exec",
".",
"Command",
"(",
"filepath",
".",
"Join",
"(",
"p",
".",
"BinDir",
",",
"\"",
"\"",
")",
",",
"\"",
"\"",
"+",
"p",
".",
"ConfigPath",
"(",
")",
",",
"\"",
"\"",
",",
"\"",
"\"",
"+",
"p",
".",
"Port",
",",
"\"",
"\"",
",",
"\"",
"\"",
"+",
"p",
".",
"Password",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
")",
"\n",
"cmd",
".",
"Dir",
"=",
"p",
".",
"DataDir",
"\n",
"cmd",
".",
"Stderr",
"=",
"&",
"r",
".",
"stderr",
"\n\n",
"stdout",
",",
"err",
":=",
"cmd",
".",
"StdoutPipe",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"cmd",
".",
"Start",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"stdout",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Attach to reader wrapper.",
"r",
".",
"cmd",
"=",
"cmd",
"\n",
"r",
".",
"stdout",
"=",
"stdout",
"\n\n",
"return",
"r",
",",
"nil",
"\n",
"}"
] | // Backup returns a reader for streaming a backup in xbstream format. | [
"Backup",
"returns",
"a",
"reader",
"for",
"streaming",
"a",
"backup",
"in",
"xbstream",
"format",
"."
] | b4b05fce92da5fbc53b272362d87b994b88a3869 | https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/appliance/mariadb/process.go#L289-L320 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.