repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
flynn/flynn
discoverd/server/store.go
Snapshot
func (s *Store) Snapshot() (raft.FSMSnapshot, error) { s.mu.Lock() defer s.mu.Unlock() buf, err := json.Marshal(s.data) if err != nil { return nil, err } return &raftSnapshot{data: buf}, nil }
go
func (s *Store) Snapshot() (raft.FSMSnapshot, error) { s.mu.Lock() defer s.mu.Unlock() buf, err := json.Marshal(s.data) if err != nil { return nil, err } return &raftSnapshot{data: buf}, nil }
[ "func", "(", "s", "*", "Store", ")", "Snapshot", "(", ")", "(", "raft", ".", "FSMSnapshot", ",", "error", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "buf", ",", "err", ":=", "json", ".", "Marshal", "(", "s", ".", "data", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "raftSnapshot", "{", "data", ":", "buf", "}", ",", "nil", "\n", "}" ]
// Snapshot implements raft.FSM.
[ "Snapshot", "implements", "raft", ".", "FSM", "." ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/discoverd/server/store.go#L1007-L1016
train
flynn/flynn
discoverd/server/store.go
Restore
func (s *Store) Restore(r io.ReadCloser) error { s.mu.Lock() defer s.mu.Unlock() data := &raftData{} if err := json.NewDecoder(r).Decode(data); err != nil { return err } s.data = data return nil }
go
func (s *Store) Restore(r io.ReadCloser) error { s.mu.Lock() defer s.mu.Unlock() data := &raftData{} if err := json.NewDecoder(r).Decode(data); err != nil { return err } s.data = data return nil }
[ "func", "(", "s", "*", "Store", ")", "Restore", "(", "r", "io", ".", "ReadCloser", ")", "error", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "data", ":=", "&", "raftData", "{", "}", "\n", "if", "err", ":=", "json", ".", "NewDecoder", "(", "r", ")", ".", "Decode", "(", "data", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "s", ".", "data", "=", "data", "\n", "return", "nil", "\n", "}" ]
// Restore implements raft.FSM.
[ "Restore", "implements", "raft", ".", "FSM", "." ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/discoverd/server/store.go#L1019-L1029
train
flynn/flynn
discoverd/server/store.go
Subscribe
func (s *Store) Subscribe(service string, sendCurrent bool, kinds discoverd.EventKind, ch chan *discoverd.Event) stream.Stream { s.mu.Lock() defer s.mu.Unlock() // Create service subscription list if it doesn't exist yet. if _, ok := s.subscribers[service]; !ok { s.subscribers[service] = list.New() } // Create and add subscription. sub := &subscription{ kinds: kinds, ch: ch, store: s, service: service, } sub.el = s.subscribers[service].PushBack(sub) // Send current instances. if sendCurrent && kinds.Any(discoverd.EventKindUp) { for _, inst := range s.instances(service) { ch <- &discoverd.Event{ Service: service, Kind: discoverd.EventKindUp, Instance: inst, } // TODO: add a timeout to sends so that clients can't slow things down too much } } // Send current leader. if leader := s.serviceLeader(service); sendCurrent && kinds&discoverd.EventKindLeader != 0 && leader != nil { ch <- &discoverd.Event{ Service: service, Kind: discoverd.EventKindLeader, Instance: leader, } } // Send current service meta data. if meta := s.serviceMeta(service); sendCurrent && kinds.Any(discoverd.EventKindServiceMeta) && meta != nil { ch <- &discoverd.Event{ Service: service, Kind: discoverd.EventKindServiceMeta, ServiceMeta: meta, } } // Send current service. if sendCurrent && kinds.Any(discoverd.EventKindCurrent) { ch <- &discoverd.Event{ Service: service, Kind: discoverd.EventKindCurrent, } } return sub }
go
func (s *Store) Subscribe(service string, sendCurrent bool, kinds discoverd.EventKind, ch chan *discoverd.Event) stream.Stream { s.mu.Lock() defer s.mu.Unlock() // Create service subscription list if it doesn't exist yet. if _, ok := s.subscribers[service]; !ok { s.subscribers[service] = list.New() } // Create and add subscription. sub := &subscription{ kinds: kinds, ch: ch, store: s, service: service, } sub.el = s.subscribers[service].PushBack(sub) // Send current instances. if sendCurrent && kinds.Any(discoverd.EventKindUp) { for _, inst := range s.instances(service) { ch <- &discoverd.Event{ Service: service, Kind: discoverd.EventKindUp, Instance: inst, } // TODO: add a timeout to sends so that clients can't slow things down too much } } // Send current leader. if leader := s.serviceLeader(service); sendCurrent && kinds&discoverd.EventKindLeader != 0 && leader != nil { ch <- &discoverd.Event{ Service: service, Kind: discoverd.EventKindLeader, Instance: leader, } } // Send current service meta data. if meta := s.serviceMeta(service); sendCurrent && kinds.Any(discoverd.EventKindServiceMeta) && meta != nil { ch <- &discoverd.Event{ Service: service, Kind: discoverd.EventKindServiceMeta, ServiceMeta: meta, } } // Send current service. if sendCurrent && kinds.Any(discoverd.EventKindCurrent) { ch <- &discoverd.Event{ Service: service, Kind: discoverd.EventKindCurrent, } } return sub }
[ "func", "(", "s", "*", "Store", ")", "Subscribe", "(", "service", "string", ",", "sendCurrent", "bool", ",", "kinds", "discoverd", ".", "EventKind", ",", "ch", "chan", "*", "discoverd", ".", "Event", ")", "stream", ".", "Stream", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "_", ",", "ok", ":=", "s", ".", "subscribers", "[", "service", "]", ";", "!", "ok", "{", "s", ".", "subscribers", "[", "service", "]", "=", "list", ".", "New", "(", ")", "\n", "}", "\n", "sub", ":=", "&", "subscription", "{", "kinds", ":", "kinds", ",", "ch", ":", "ch", ",", "store", ":", "s", ",", "service", ":", "service", ",", "}", "\n", "sub", ".", "el", "=", "s", ".", "subscribers", "[", "service", "]", ".", "PushBack", "(", "sub", ")", "\n", "if", "sendCurrent", "&&", "kinds", ".", "Any", "(", "discoverd", ".", "EventKindUp", ")", "{", "for", "_", ",", "inst", ":=", "range", "s", ".", "instances", "(", "service", ")", "{", "ch", "<-", "&", "discoverd", ".", "Event", "{", "Service", ":", "service", ",", "Kind", ":", "discoverd", ".", "EventKindUp", ",", "Instance", ":", "inst", ",", "}", "\n", "}", "\n", "}", "\n", "if", "leader", ":=", "s", ".", "serviceLeader", "(", "service", ")", ";", "sendCurrent", "&&", "kinds", "&", "discoverd", ".", "EventKindLeader", "!=", "0", "&&", "leader", "!=", "nil", "{", "ch", "<-", "&", "discoverd", ".", "Event", "{", "Service", ":", "service", ",", "Kind", ":", "discoverd", ".", "EventKindLeader", ",", "Instance", ":", "leader", ",", "}", "\n", "}", "\n", "if", "meta", ":=", "s", ".", "serviceMeta", "(", "service", ")", ";", "sendCurrent", "&&", "kinds", ".", "Any", "(", "discoverd", ".", "EventKindServiceMeta", ")", "&&", "meta", "!=", "nil", "{", "ch", "<-", "&", "discoverd", ".", "Event", "{", "Service", ":", "service", ",", "Kind", ":", "discoverd", ".", "EventKindServiceMeta", ",", "ServiceMeta", ":", "meta", ",", "}", "\n", "}", "\n", "if", "sendCurrent", "&&", "kinds", ".", "Any", "(", "discoverd", ".", "EventKindCurrent", ")", "{", "ch", "<-", "&", "discoverd", ".", "Event", "{", "Service", ":", "service", ",", "Kind", ":", "discoverd", ".", "EventKindCurrent", ",", "}", "\n", "}", "\n", "return", "sub", "\n", "}" ]
// Subscribe creates a subscription to events on a given service.
[ "Subscribe", "creates", "a", "subscription", "to", "events", "on", "a", "given", "service", "." ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/discoverd/server/store.go#L1032-L1089
train
flynn/flynn
discoverd/server/store.go
broadcast
func (s *Store) broadcast(event *discoverd.Event) { logBroadcast(event) // Retrieve list of subscribers for the service. l, ok := s.subscribers[event.Service] if !ok { return } // Iterate over each subscriber in the list. for el := l.Front(); el != nil; el = el.Next() { sub := el.Value.(*subscription) // Skip if event type is not subscribed to. if sub.kinds&event.Kind == 0 { continue } // Send event to subscriber. // If subscriber is blocked then close it. select { case sub.ch <- event: default: sub.err = ErrSendBlocked go sub.Close() } } }
go
func (s *Store) broadcast(event *discoverd.Event) { logBroadcast(event) // Retrieve list of subscribers for the service. l, ok := s.subscribers[event.Service] if !ok { return } // Iterate over each subscriber in the list. for el := l.Front(); el != nil; el = el.Next() { sub := el.Value.(*subscription) // Skip if event type is not subscribed to. if sub.kinds&event.Kind == 0 { continue } // Send event to subscriber. // If subscriber is blocked then close it. select { case sub.ch <- event: default: sub.err = ErrSendBlocked go sub.Close() } } }
[ "func", "(", "s", "*", "Store", ")", "broadcast", "(", "event", "*", "discoverd", ".", "Event", ")", "{", "logBroadcast", "(", "event", ")", "\n", "l", ",", "ok", ":=", "s", ".", "subscribers", "[", "event", ".", "Service", "]", "\n", "if", "!", "ok", "{", "return", "\n", "}", "\n", "for", "el", ":=", "l", ".", "Front", "(", ")", ";", "el", "!=", "nil", ";", "el", "=", "el", ".", "Next", "(", ")", "{", "sub", ":=", "el", ".", "Value", ".", "(", "*", "subscription", ")", "\n", "if", "sub", ".", "kinds", "&", "event", ".", "Kind", "==", "0", "{", "continue", "\n", "}", "\n", "select", "{", "case", "sub", ".", "ch", "<-", "event", ":", "default", ":", "sub", ".", "err", "=", "ErrSendBlocked", "\n", "go", "sub", ".", "Close", "(", ")", "\n", "}", "\n", "}", "\n", "}" ]
// broadcast sends an event to all subscribers. // Requires the mu lock to be obtained.
[ "broadcast", "sends", "an", "event", "to", "all", "subscribers", ".", "Requires", "the", "mu", "lock", "to", "be", "obtained", "." ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/discoverd/server/store.go#L1093-L1121
train
flynn/flynn
discoverd/server/store.go
Persist
func (ss *raftSnapshot) Persist(sink raft.SnapshotSink) error { // Write data to sink. if _, err := sink.Write(ss.data); err != nil { sink.Cancel() return err } // Close and exit. return sink.Close() }
go
func (ss *raftSnapshot) Persist(sink raft.SnapshotSink) error { // Write data to sink. if _, err := sink.Write(ss.data); err != nil { sink.Cancel() return err } // Close and exit. return sink.Close() }
[ "func", "(", "ss", "*", "raftSnapshot", ")", "Persist", "(", "sink", "raft", ".", "SnapshotSink", ")", "error", "{", "if", "_", ",", "err", ":=", "sink", ".", "Write", "(", "ss", ".", "data", ")", ";", "err", "!=", "nil", "{", "sink", ".", "Cancel", "(", ")", "\n", "return", "err", "\n", "}", "\n", "return", "sink", ".", "Close", "(", ")", "\n", "}" ]
// Persist writes the snapshot to the sink.
[ "Persist", "writes", "the", "snapshot", "to", "the", "sink", "." ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/discoverd/server/store.go#L1148-L1157
train
flynn/flynn
discoverd/server/store.go
ServiceInstances
func (d *raftData) ServiceInstances(service string) []*discoverd.Instance { a := make([]*discoverd.Instance, 0, len(d.Instances[service])) for _, i := range d.Instances[service] { a = append(a, i) } sort.Sort(instanceSlice(a)) return a }
go
func (d *raftData) ServiceInstances(service string) []*discoverd.Instance { a := make([]*discoverd.Instance, 0, len(d.Instances[service])) for _, i := range d.Instances[service] { a = append(a, i) } sort.Sort(instanceSlice(a)) return a }
[ "func", "(", "d", "*", "raftData", ")", "ServiceInstances", "(", "service", "string", ")", "[", "]", "*", "discoverd", ".", "Instance", "{", "a", ":=", "make", "(", "[", "]", "*", "discoverd", ".", "Instance", ",", "0", ",", "len", "(", "d", ".", "Instances", "[", "service", "]", ")", ")", "\n", "for", "_", ",", "i", ":=", "range", "d", ".", "Instances", "[", "service", "]", "{", "a", "=", "append", "(", "a", ",", "i", ")", "\n", "}", "\n", "sort", ".", "Sort", "(", "instanceSlice", "(", "a", ")", ")", "\n", "return", "a", "\n", "}" ]
// ServiceInstances returns the instances of a service in sorted order.
[ "ServiceInstances", "returns", "the", "instances", "of", "a", "service", "in", "sorted", "order", "." ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/discoverd/server/store.go#L1245-L1253
train
flynn/flynn
discoverd/server/store.go
ValidServiceName
func ValidServiceName(service string) error { // Blank service names are not allowed. if service == "" { return ErrUnsetService } // Service names must consist of the characters [a-z0-9-] for _, r := range service { if (r < 'a' || r > 'z') && (r < '0' || r > '9') && r != '-' { return ErrInvalidService } } return nil }
go
func ValidServiceName(service string) error { // Blank service names are not allowed. if service == "" { return ErrUnsetService } // Service names must consist of the characters [a-z0-9-] for _, r := range service { if (r < 'a' || r > 'z') && (r < '0' || r > '9') && r != '-' { return ErrInvalidService } } return nil }
[ "func", "ValidServiceName", "(", "service", "string", ")", "error", "{", "if", "service", "==", "\"\"", "{", "return", "ErrUnsetService", "\n", "}", "\n", "for", "_", ",", "r", ":=", "range", "service", "{", "if", "(", "r", "<", "'a'", "||", "r", ">", "'z'", ")", "&&", "(", "r", "<", "'0'", "||", "r", ">", "'9'", ")", "&&", "r", "!=", "'-'", "{", "return", "ErrInvalidService", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ValidServiceName returns nil if service is valid. Otherwise returns an error.
[ "ValidServiceName", "returns", "nil", "if", "service", "is", "valid", ".", "Otherwise", "returns", "an", "error", "." ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/discoverd/server/store.go#L1328-L1342
train
flynn/flynn
discoverd/server/store.go
Instances
func (s *ProxyStore) Instances(service string) ([]*discoverd.Instance, error) { host := s.Peers[rand.Intn(len(s.Peers))] client := discoverd.NewClientWithURL("http://" + host) return client.Service(service).Instances() }
go
func (s *ProxyStore) Instances(service string) ([]*discoverd.Instance, error) { host := s.Peers[rand.Intn(len(s.Peers))] client := discoverd.NewClientWithURL("http://" + host) return client.Service(service).Instances() }
[ "func", "(", "s", "*", "ProxyStore", ")", "Instances", "(", "service", "string", ")", "(", "[", "]", "*", "discoverd", ".", "Instance", ",", "error", ")", "{", "host", ":=", "s", ".", "Peers", "[", "rand", ".", "Intn", "(", "len", "(", "s", ".", "Peers", ")", ")", "]", "\n", "client", ":=", "discoverd", ".", "NewClientWithURL", "(", "\"http://\"", "+", "host", ")", "\n", "return", "client", ".", "Service", "(", "service", ")", ".", "Instances", "(", ")", "\n", "}" ]
// Instances returns a list of instances for a service.
[ "Instances", "returns", "a", "list", "of", "instances", "for", "a", "service", "." ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/discoverd/server/store.go#L1351-L1355
train
flynn/flynn
discoverd/server/store.go
newRaftLayer
func newRaftLayer(ln net.Listener, addr net.Addr) *raftLayer { return &raftLayer{ ln: ln, addr: addr, } }
go
func newRaftLayer(ln net.Listener, addr net.Addr) *raftLayer { return &raftLayer{ ln: ln, addr: addr, } }
[ "func", "newRaftLayer", "(", "ln", "net", ".", "Listener", ",", "addr", "net", ".", "Addr", ")", "*", "raftLayer", "{", "return", "&", "raftLayer", "{", "ln", ":", "ln", ",", "addr", ":", "addr", ",", "}", "\n", "}" ]
// newRaftLayer returns a new instance of raftLayer.
[ "newRaftLayer", "returns", "a", "new", "instance", "of", "raftLayer", "." ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/discoverd/server/store.go#L1374-L1379
train
flynn/flynn
pkg/rpcplus/client.go
CloseStream
func (c *Call) CloseStream() error { if !c.Stream { return errors.New("rpc: cannot close non-stream request") } <-c.sent c.client.sending.Lock() defer c.client.sending.Unlock() c.client.mutex.Lock() if c.client.shutdown { c.client.mutex.Unlock() return ErrShutdown } c.client.mutex.Unlock() c.client.request.ServiceMethod = "CloseStream" c.client.request.Seq = c.seq return c.client.codec.WriteRequest(&c.client.request, struct{}{}) }
go
func (c *Call) CloseStream() error { if !c.Stream { return errors.New("rpc: cannot close non-stream request") } <-c.sent c.client.sending.Lock() defer c.client.sending.Unlock() c.client.mutex.Lock() if c.client.shutdown { c.client.mutex.Unlock() return ErrShutdown } c.client.mutex.Unlock() c.client.request.ServiceMethod = "CloseStream" c.client.request.Seq = c.seq return c.client.codec.WriteRequest(&c.client.request, struct{}{}) }
[ "func", "(", "c", "*", "Call", ")", "CloseStream", "(", ")", "error", "{", "if", "!", "c", ".", "Stream", "{", "return", "errors", ".", "New", "(", "\"rpc: cannot close non-stream request\"", ")", "\n", "}", "\n", "<-", "c", ".", "sent", "\n", "c", ".", "client", ".", "sending", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "client", ".", "sending", ".", "Unlock", "(", ")", "\n", "c", ".", "client", ".", "mutex", ".", "Lock", "(", ")", "\n", "if", "c", ".", "client", ".", "shutdown", "{", "c", ".", "client", ".", "mutex", ".", "Unlock", "(", ")", "\n", "return", "ErrShutdown", "\n", "}", "\n", "c", ".", "client", ".", "mutex", ".", "Unlock", "(", ")", "\n", "c", ".", "client", ".", "request", ".", "ServiceMethod", "=", "\"CloseStream\"", "\n", "c", ".", "client", ".", "request", ".", "Seq", "=", "c", ".", "seq", "\n", "return", "c", ".", "client", ".", "codec", ".", "WriteRequest", "(", "&", "c", ".", "client", ".", "request", ",", "struct", "{", "}", "{", "}", ")", "\n", "}" ]
// CloseStream closes the associated stream
[ "CloseStream", "closes", "the", "associated", "stream" ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/rpcplus/client.go#L45-L63
train
flynn/flynn
pkg/rpcplus/client.go
NewClient
func NewClient(conn io.ReadWriteCloser) *Client { encBuf := bufio.NewWriter(conn) client := &gobClientCodec{conn, gob.NewDecoder(conn), gob.NewEncoder(encBuf), encBuf} return NewClientWithCodec(client) }
go
func NewClient(conn io.ReadWriteCloser) *Client { encBuf := bufio.NewWriter(conn) client := &gobClientCodec{conn, gob.NewDecoder(conn), gob.NewEncoder(encBuf), encBuf} return NewClientWithCodec(client) }
[ "func", "NewClient", "(", "conn", "io", ".", "ReadWriteCloser", ")", "*", "Client", "{", "encBuf", ":=", "bufio", ".", "NewWriter", "(", "conn", ")", "\n", "client", ":=", "&", "gobClientCodec", "{", "conn", ",", "gob", ".", "NewDecoder", "(", "conn", ")", ",", "gob", ".", "NewEncoder", "(", "encBuf", ")", ",", "encBuf", "}", "\n", "return", "NewClientWithCodec", "(", "client", ")", "\n", "}" ]
// NewClient returns a new Client to handle requests to the // set of services at the other end of the connection. // It adds a buffer to the write side of the connection so // the header and payload are sent as a unit.
[ "NewClient", "returns", "a", "new", "Client", "to", "handle", "requests", "to", "the", "set", "of", "services", "at", "the", "other", "end", "of", "the", "connection", ".", "It", "adds", "a", "buffer", "to", "the", "write", "side", "of", "the", "connection", "so", "the", "header", "and", "payload", "are", "sent", "as", "a", "unit", "." ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/rpcplus/client.go#L243-L247
train
flynn/flynn
pkg/rpcplus/client.go
DialHTTP
func DialHTTP(network, address string) (*Client, error) { return DialHTTPPath(network, address, DefaultRPCPath, nil) }
go
func DialHTTP(network, address string) (*Client, error) { return DialHTTPPath(network, address, DefaultRPCPath, nil) }
[ "func", "DialHTTP", "(", "network", ",", "address", "string", ")", "(", "*", "Client", ",", "error", ")", "{", "return", "DialHTTPPath", "(", "network", ",", "address", ",", "DefaultRPCPath", ",", "nil", ")", "\n", "}" ]
// DialHTTP connects to an HTTP RPC server at the specified network address // listening on the default HTTP RPC path.
[ "DialHTTP", "connects", "to", "an", "HTTP", "RPC", "server", "at", "the", "specified", "network", "address", "listening", "on", "the", "default", "HTTP", "RPC", "path", "." ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/rpcplus/client.go#L291-L293
train
flynn/flynn
pkg/rpcplus/client.go
DialHTTPPath
func DialHTTPPath(network, address, path string, dial DialFunc) (*Client, error) { if dial == nil { dial = net.Dial } var err error conn, err := dial(network, address) if err != nil { return nil, err } client, err := NewHTTPClient(conn, path, nil) if err != nil { conn.Close() return nil, &net.OpError{ Op: "dial-http", Net: network + " " + address, Addr: nil, Err: err, } } return client, nil }
go
func DialHTTPPath(network, address, path string, dial DialFunc) (*Client, error) { if dial == nil { dial = net.Dial } var err error conn, err := dial(network, address) if err != nil { return nil, err } client, err := NewHTTPClient(conn, path, nil) if err != nil { conn.Close() return nil, &net.OpError{ Op: "dial-http", Net: network + " " + address, Addr: nil, Err: err, } } return client, nil }
[ "func", "DialHTTPPath", "(", "network", ",", "address", ",", "path", "string", ",", "dial", "DialFunc", ")", "(", "*", "Client", ",", "error", ")", "{", "if", "dial", "==", "nil", "{", "dial", "=", "net", ".", "Dial", "\n", "}", "\n", "var", "err", "error", "\n", "conn", ",", "err", ":=", "dial", "(", "network", ",", "address", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "client", ",", "err", ":=", "NewHTTPClient", "(", "conn", ",", "path", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "conn", ".", "Close", "(", ")", "\n", "return", "nil", ",", "&", "net", ".", "OpError", "{", "Op", ":", "\"dial-http\"", ",", "Net", ":", "network", "+", "\" \"", "+", "address", ",", "Addr", ":", "nil", ",", "Err", ":", "err", ",", "}", "\n", "}", "\n", "return", "client", ",", "nil", "\n", "}" ]
// DialHTTPPath connects to an HTTP RPC server // at the specified network address and path.
[ "DialHTTPPath", "connects", "to", "an", "HTTP", "RPC", "server", "at", "the", "specified", "network", "address", "and", "path", "." ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/rpcplus/client.go#L299-L319
train
flynn/flynn
pkg/rpcplus/client.go
Dial
func Dial(network, address string) (*Client, error) { conn, err := net.Dial(network, address) if err != nil { return nil, err } return NewClient(conn), nil }
go
func Dial(network, address string) (*Client, error) { conn, err := net.Dial(network, address) if err != nil { return nil, err } return NewClient(conn), nil }
[ "func", "Dial", "(", "network", ",", "address", "string", ")", "(", "*", "Client", ",", "error", ")", "{", "conn", ",", "err", ":=", "net", ".", "Dial", "(", "network", ",", "address", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "NewClient", "(", "conn", ")", ",", "nil", "\n", "}" ]
// Dial connects to an RPC server at the specified network address.
[ "Dial", "connects", "to", "an", "RPC", "server", "at", "the", "specified", "network", "address", "." ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/rpcplus/client.go#L344-L350
train
flynn/flynn
pkg/rpcplus/client.go
StreamGo
func (client *Client) StreamGo(serviceMethod string, args interface{}, replyStream interface{}) *Call { // first check the replyStream object is a stream of pointers to a data structure typ := reflect.TypeOf(replyStream) // FIXME: check the direction of the channel, maybe? if typ.Kind() != reflect.Chan || typ.Elem().Kind() != reflect.Ptr { log.Panic("rpc: replyStream is not a channel of pointers") return nil } call := new(Call) call.ServiceMethod = serviceMethod call.Args = args call.Reply = replyStream call.Stream = true call.sent = make(chan struct{}) call.client = client client.send(call) return call }
go
func (client *Client) StreamGo(serviceMethod string, args interface{}, replyStream interface{}) *Call { // first check the replyStream object is a stream of pointers to a data structure typ := reflect.TypeOf(replyStream) // FIXME: check the direction of the channel, maybe? if typ.Kind() != reflect.Chan || typ.Elem().Kind() != reflect.Ptr { log.Panic("rpc: replyStream is not a channel of pointers") return nil } call := new(Call) call.ServiceMethod = serviceMethod call.Args = args call.Reply = replyStream call.Stream = true call.sent = make(chan struct{}) call.client = client client.send(call) return call }
[ "func", "(", "client", "*", "Client", ")", "StreamGo", "(", "serviceMethod", "string", ",", "args", "interface", "{", "}", ",", "replyStream", "interface", "{", "}", ")", "*", "Call", "{", "typ", ":=", "reflect", ".", "TypeOf", "(", "replyStream", ")", "\n", "if", "typ", ".", "Kind", "(", ")", "!=", "reflect", ".", "Chan", "||", "typ", ".", "Elem", "(", ")", ".", "Kind", "(", ")", "!=", "reflect", ".", "Ptr", "{", "log", ".", "Panic", "(", "\"rpc: replyStream is not a channel of pointers\"", ")", "\n", "return", "nil", "\n", "}", "\n", "call", ":=", "new", "(", "Call", ")", "\n", "call", ".", "ServiceMethod", "=", "serviceMethod", "\n", "call", ".", "Args", "=", "args", "\n", "call", ".", "Reply", "=", "replyStream", "\n", "call", ".", "Stream", "=", "true", "\n", "call", ".", "sent", "=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "call", ".", "client", "=", "client", "\n", "client", ".", "send", "(", "call", ")", "\n", "return", "call", "\n", "}" ]
// Go invokes the streaming function asynchronously. It returns the Call structure representing // the invocation.
[ "Go", "invokes", "the", "streaming", "function", "asynchronously", ".", "It", "returns", "the", "Call", "structure", "representing", "the", "invocation", "." ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/rpcplus/client.go#L390-L408
train
flynn/flynn
appliance/mariadb/dsn.go
String
func (dsn *DSN) String() string { u := url.URL{ Host: fmt.Sprintf("tcp(%s)", dsn.Host), Path: "/" + dsn.Database, RawQuery: url.Values{ "timeout": {dsn.Timeout.String()}, }.Encode(), } // Set password, if available. if dsn.Password == "" { u.User = url.User(dsn.User) } else { u.User = url.UserPassword(dsn.User, dsn.Password) } // Remove leading double-slash. return strings.TrimPrefix(u.String(), "//") }
go
func (dsn *DSN) String() string { u := url.URL{ Host: fmt.Sprintf("tcp(%s)", dsn.Host), Path: "/" + dsn.Database, RawQuery: url.Values{ "timeout": {dsn.Timeout.String()}, }.Encode(), } // Set password, if available. if dsn.Password == "" { u.User = url.User(dsn.User) } else { u.User = url.UserPassword(dsn.User, dsn.Password) } // Remove leading double-slash. return strings.TrimPrefix(u.String(), "//") }
[ "func", "(", "dsn", "*", "DSN", ")", "String", "(", ")", "string", "{", "u", ":=", "url", ".", "URL", "{", "Host", ":", "fmt", ".", "Sprintf", "(", "\"tcp(%s)\"", ",", "dsn", ".", "Host", ")", ",", "Path", ":", "\"/\"", "+", "dsn", ".", "Database", ",", "RawQuery", ":", "url", ".", "Values", "{", "\"timeout\"", ":", "{", "dsn", ".", "Timeout", ".", "String", "(", ")", "}", ",", "}", ".", "Encode", "(", ")", ",", "}", "\n", "if", "dsn", ".", "Password", "==", "\"\"", "{", "u", ".", "User", "=", "url", ".", "User", "(", "dsn", ".", "User", ")", "\n", "}", "else", "{", "u", ".", "User", "=", "url", ".", "UserPassword", "(", "dsn", ".", "User", ",", "dsn", ".", "Password", ")", "\n", "}", "\n", "return", "strings", ".", "TrimPrefix", "(", "u", ".", "String", "(", ")", ",", "\"//\"", ")", "\n", "}" ]
// String encodes dsn to a URL string format.
[ "String", "encodes", "dsn", "to", "a", "URL", "string", "format", "." ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/appliance/mariadb/dsn.go#L20-L38
train
flynn/flynn
flannel/main.go
pingLeases
func pingLeases(leases []subnet.SubnetLease) error { const workers = 5 const timeout = 1 * time.Second if len(leases) == 0 { return nil } work := make(chan subnet.SubnetLease) results := make(chan bool, workers) client := http.Client{Timeout: timeout} var wg sync.WaitGroup wg.Add(workers) for i := 0; i < workers; i++ { go func() { for l := range work { res, err := client.Get(fmt.Sprintf("http://%s:%s/ping", l.Network.IP, l.Attrs.HTTPPort)) if err == nil { res.Body.Close() } results <- err == nil && res.StatusCode == 200 } wg.Done() }() } go func() { wg.Wait() close(results) }() for _, l := range leases { select { case work <- l: case success := <-results: if success { close(work) return nil } } } close(work) for success := range results { if success { return nil } } return errors.New("failed to successfully ping a neighbor") }
go
func pingLeases(leases []subnet.SubnetLease) error { const workers = 5 const timeout = 1 * time.Second if len(leases) == 0 { return nil } work := make(chan subnet.SubnetLease) results := make(chan bool, workers) client := http.Client{Timeout: timeout} var wg sync.WaitGroup wg.Add(workers) for i := 0; i < workers; i++ { go func() { for l := range work { res, err := client.Get(fmt.Sprintf("http://%s:%s/ping", l.Network.IP, l.Attrs.HTTPPort)) if err == nil { res.Body.Close() } results <- err == nil && res.StatusCode == 200 } wg.Done() }() } go func() { wg.Wait() close(results) }() for _, l := range leases { select { case work <- l: case success := <-results: if success { close(work) return nil } } } close(work) for success := range results { if success { return nil } } return errors.New("failed to successfully ping a neighbor") }
[ "func", "pingLeases", "(", "leases", "[", "]", "subnet", ".", "SubnetLease", ")", "error", "{", "const", "workers", "=", "5", "\n", "const", "timeout", "=", "1", "*", "time", ".", "Second", "\n", "if", "len", "(", "leases", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "work", ":=", "make", "(", "chan", "subnet", ".", "SubnetLease", ")", "\n", "results", ":=", "make", "(", "chan", "bool", ",", "workers", ")", "\n", "client", ":=", "http", ".", "Client", "{", "Timeout", ":", "timeout", "}", "\n", "var", "wg", "sync", ".", "WaitGroup", "\n", "wg", ".", "Add", "(", "workers", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "workers", ";", "i", "++", "{", "go", "func", "(", ")", "{", "for", "l", ":=", "range", "work", "{", "res", ",", "err", ":=", "client", ".", "Get", "(", "fmt", ".", "Sprintf", "(", "\"http://%s:%s/ping\"", ",", "l", ".", "Network", ".", "IP", ",", "l", ".", "Attrs", ".", "HTTPPort", ")", ")", "\n", "if", "err", "==", "nil", "{", "res", ".", "Body", ".", "Close", "(", ")", "\n", "}", "\n", "results", "<-", "err", "==", "nil", "&&", "res", ".", "StatusCode", "==", "200", "\n", "}", "\n", "wg", ".", "Done", "(", ")", "\n", "}", "(", ")", "\n", "}", "\n", "go", "func", "(", ")", "{", "wg", ".", "Wait", "(", ")", "\n", "close", "(", "results", ")", "\n", "}", "(", ")", "\n", "for", "_", ",", "l", ":=", "range", "leases", "{", "select", "{", "case", "work", "<-", "l", ":", "case", "success", ":=", "<-", "results", ":", "if", "success", "{", "close", "(", "work", ")", "\n", "return", "nil", "\n", "}", "\n", "}", "\n", "}", "\n", "close", "(", "work", ")", "\n", "for", "success", ":=", "range", "results", "{", "if", "success", "{", "return", "nil", "\n", "}", "\n", "}", "\n", "return", "errors", ".", "New", "(", "\"failed to successfully ping a neighbor\"", ")", "\n", "}" ]
// ping neighbor leases five at a time, timeout 1 second, returning as soon as // one returns success.
[ "ping", "neighbor", "leases", "five", "at", "a", "time", "timeout", "1", "second", "returning", "as", "soon", "as", "one", "returns", "success", "." ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/flannel/main.go#L235-L286
train
flynn/flynn
controller/schema.go
migrateProcessData
func migrateProcessData(tx *postgres.DBTx) error { type Release struct { ID string // use map[string]interface{} for process types so we can just // update Volumes and Data and leave other fields untouched Processes map[string]map[string]interface{} } var releases []Release rows, err := tx.Query("SELECT release_id, processes FROM releases") if err != nil { return err } defer rows.Close() for rows.Next() { var release Release if err := rows.Scan(&release.ID, &release.Processes); err != nil { return err } releases = append(releases, release) } if err := rows.Err(); err != nil { return err } for _, release := range releases { for typ, proc := range release.Processes { v, ok := proc["data"] if !ok { continue } data, ok := v.(bool) if !ok || !data { continue } proc["volumes"] = []struct { Path string `json:"path"` }{ {Path: "/data"}, } delete(proc, "data") release.Processes[typ] = proc } // save the processes back to the db if err := tx.Exec("UPDATE releases SET processes = $1 WHERE release_id = $2", release.Processes, release.ID); err != nil { return err } } return nil }
go
func migrateProcessData(tx *postgres.DBTx) error { type Release struct { ID string // use map[string]interface{} for process types so we can just // update Volumes and Data and leave other fields untouched Processes map[string]map[string]interface{} } var releases []Release rows, err := tx.Query("SELECT release_id, processes FROM releases") if err != nil { return err } defer rows.Close() for rows.Next() { var release Release if err := rows.Scan(&release.ID, &release.Processes); err != nil { return err } releases = append(releases, release) } if err := rows.Err(); err != nil { return err } for _, release := range releases { for typ, proc := range release.Processes { v, ok := proc["data"] if !ok { continue } data, ok := v.(bool) if !ok || !data { continue } proc["volumes"] = []struct { Path string `json:"path"` }{ {Path: "/data"}, } delete(proc, "data") release.Processes[typ] = proc } // save the processes back to the db if err := tx.Exec("UPDATE releases SET processes = $1 WHERE release_id = $2", release.Processes, release.ID); err != nil { return err } } return nil }
[ "func", "migrateProcessData", "(", "tx", "*", "postgres", ".", "DBTx", ")", "error", "{", "type", "Release", "struct", "{", "ID", "string", "\n", "Processes", "map", "[", "string", "]", "map", "[", "string", "]", "interface", "{", "}", "\n", "}", "\n", "var", "releases", "[", "]", "Release", "\n", "rows", ",", "err", ":=", "tx", ".", "Query", "(", "\"SELECT release_id, processes FROM releases\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "rows", ".", "Close", "(", ")", "\n", "for", "rows", ".", "Next", "(", ")", "{", "var", "release", "Release", "\n", "if", "err", ":=", "rows", ".", "Scan", "(", "&", "release", ".", "ID", ",", "&", "release", ".", "Processes", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "releases", "=", "append", "(", "releases", ",", "release", ")", "\n", "}", "\n", "if", "err", ":=", "rows", ".", "Err", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "_", ",", "release", ":=", "range", "releases", "{", "for", "typ", ",", "proc", ":=", "range", "release", ".", "Processes", "{", "v", ",", "ok", ":=", "proc", "[", "\"data\"", "]", "\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n", "data", ",", "ok", ":=", "v", ".", "(", "bool", ")", "\n", "if", "!", "ok", "||", "!", "data", "{", "continue", "\n", "}", "\n", "proc", "[", "\"volumes\"", "]", "=", "[", "]", "struct", "{", "Path", "string", "`json:\"path\"`", "\n", "}", "{", "{", "Path", ":", "\"/data\"", "}", ",", "}", "\n", "delete", "(", "proc", ",", "\"data\"", ")", "\n", "release", ".", "Processes", "[", "typ", "]", "=", "proc", "\n", "}", "\n", "if", "err", ":=", "tx", ".", "Exec", "(", "\"UPDATE releases SET processes = $1 WHERE release_id = $2\"", ",", "release", ".", "Processes", ",", "release", ".", "ID", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// migrateProcessData populates ProcessType.Volumes if ProcessType.Data is set
[ "migrateProcessData", "populates", "ProcessType", ".", "Volumes", "if", "ProcessType", ".", "Data", "is", "set" ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/controller/schema.go#L636-L687
train
flynn/flynn
router/proxy/transport.go
Finalize
func (r *RequestTrace) Finalize(backend *router.Backend) { r.mtx.Lock() r.final = true r.Backend = backend r.mtx.Unlock() }
go
func (r *RequestTrace) Finalize(backend *router.Backend) { r.mtx.Lock() r.final = true r.Backend = backend r.mtx.Unlock() }
[ "func", "(", "r", "*", "RequestTrace", ")", "Finalize", "(", "backend", "*", "router", ".", "Backend", ")", "{", "r", ".", "mtx", ".", "Lock", "(", ")", "\n", "r", ".", "final", "=", "true", "\n", "r", ".", "Backend", "=", "backend", "\n", "r", ".", "mtx", ".", "Unlock", "(", ")", "\n", "}" ]
// Finalize safely finalizes the trace for read access.
[ "Finalize", "safely", "finalizes", "the", "trace", "for", "read", "access", "." ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/router/proxy/transport.go#L272-L277
train
flynn/flynn
router/proxy/transport.go
traceRequest
func traceRequest(req *http.Request) (*http.Request, *RequestTrace) { trace := &RequestTrace{} ct := &httptrace.ClientTrace{ GetConn: func(hostPort string) { trace.mtx.Lock() defer trace.mtx.Unlock() if trace.final { return } trace.ConnectStart = time.Now() }, GotConn: func(info httptrace.GotConnInfo) { trace.mtx.Lock() defer trace.mtx.Unlock() if trace.final { return } trace.ConnectDone = time.Now() trace.ReusedConn = info.Reused trace.WasIdleConn = info.WasIdle }, WroteHeaders: func() { trace.mtx.Lock() defer trace.mtx.Unlock() if trace.final { return } trace.HeadersWritten = time.Now() }, WroteRequest: func(info httptrace.WroteRequestInfo) { trace.mtx.Lock() defer trace.mtx.Unlock() if trace.final { return } trace.BodyWritten = time.Now() }, GotFirstResponseByte: func() { trace.mtx.Lock() defer trace.mtx.Unlock() if trace.final { return } trace.FirstByte = time.Now() }, } req = req.WithContext(httptrace.WithClientTrace(req.Context(), ct)) return req, trace }
go
func traceRequest(req *http.Request) (*http.Request, *RequestTrace) { trace := &RequestTrace{} ct := &httptrace.ClientTrace{ GetConn: func(hostPort string) { trace.mtx.Lock() defer trace.mtx.Unlock() if trace.final { return } trace.ConnectStart = time.Now() }, GotConn: func(info httptrace.GotConnInfo) { trace.mtx.Lock() defer trace.mtx.Unlock() if trace.final { return } trace.ConnectDone = time.Now() trace.ReusedConn = info.Reused trace.WasIdleConn = info.WasIdle }, WroteHeaders: func() { trace.mtx.Lock() defer trace.mtx.Unlock() if trace.final { return } trace.HeadersWritten = time.Now() }, WroteRequest: func(info httptrace.WroteRequestInfo) { trace.mtx.Lock() defer trace.mtx.Unlock() if trace.final { return } trace.BodyWritten = time.Now() }, GotFirstResponseByte: func() { trace.mtx.Lock() defer trace.mtx.Unlock() if trace.final { return } trace.FirstByte = time.Now() }, } req = req.WithContext(httptrace.WithClientTrace(req.Context(), ct)) return req, trace }
[ "func", "traceRequest", "(", "req", "*", "http", ".", "Request", ")", "(", "*", "http", ".", "Request", ",", "*", "RequestTrace", ")", "{", "trace", ":=", "&", "RequestTrace", "{", "}", "\n", "ct", ":=", "&", "httptrace", ".", "ClientTrace", "{", "GetConn", ":", "func", "(", "hostPort", "string", ")", "{", "trace", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "trace", ".", "mtx", ".", "Unlock", "(", ")", "\n", "if", "trace", ".", "final", "{", "return", "\n", "}", "\n", "trace", ".", "ConnectStart", "=", "time", ".", "Now", "(", ")", "\n", "}", ",", "GotConn", ":", "func", "(", "info", "httptrace", ".", "GotConnInfo", ")", "{", "trace", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "trace", ".", "mtx", ".", "Unlock", "(", ")", "\n", "if", "trace", ".", "final", "{", "return", "\n", "}", "\n", "trace", ".", "ConnectDone", "=", "time", ".", "Now", "(", ")", "\n", "trace", ".", "ReusedConn", "=", "info", ".", "Reused", "\n", "trace", ".", "WasIdleConn", "=", "info", ".", "WasIdle", "\n", "}", ",", "WroteHeaders", ":", "func", "(", ")", "{", "trace", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "trace", ".", "mtx", ".", "Unlock", "(", ")", "\n", "if", "trace", ".", "final", "{", "return", "\n", "}", "\n", "trace", ".", "HeadersWritten", "=", "time", ".", "Now", "(", ")", "\n", "}", ",", "WroteRequest", ":", "func", "(", "info", "httptrace", ".", "WroteRequestInfo", ")", "{", "trace", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "trace", ".", "mtx", ".", "Unlock", "(", ")", "\n", "if", "trace", ".", "final", "{", "return", "\n", "}", "\n", "trace", ".", "BodyWritten", "=", "time", ".", "Now", "(", ")", "\n", "}", ",", "GotFirstResponseByte", ":", "func", "(", ")", "{", "trace", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "trace", ".", "mtx", ".", "Unlock", "(", ")", "\n", "if", "trace", ".", "final", "{", "return", "\n", "}", "\n", "trace", ".", "FirstByte", "=", "time", ".", "Now", "(", ")", "\n", "}", ",", "}", "\n", "req", "=", "req", ".", "WithContext", "(", "httptrace", ".", "WithClientTrace", "(", "req", ".", "Context", "(", ")", ",", "ct", ")", ")", "\n", "return", "req", ",", "trace", "\n", "}" ]
// traceRequest sets up request tracing and returns the modified // request.
[ "traceRequest", "sets", "up", "request", "tracing", "and", "returns", "the", "modified", "request", "." ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/router/proxy/transport.go#L281-L329
train
flynn/flynn
controller/worker/deployment/context.go
execWithRetries
func (c *context) execWithRetries(query string, args ...interface{}) error { return execAttempts.Run(func() error { return c.db.Exec(query, args...) }) }
go
func (c *context) execWithRetries(query string, args ...interface{}) error { return execAttempts.Run(func() error { return c.db.Exec(query, args...) }) }
[ "func", "(", "c", "*", "context", ")", "execWithRetries", "(", "query", "string", ",", "args", "...", "interface", "{", "}", ")", "error", "{", "return", "execAttempts", ".", "Run", "(", "func", "(", ")", "error", "{", "return", "c", ".", "db", ".", "Exec", "(", "query", ",", "args", "...", ")", "\n", "}", ")", "\n", "}" ]
// Retry db queries in case postgres has been deployed
[ "Retry", "db", "queries", "in", "case", "postgres", "has", "been", "deployed" ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/controller/worker/deployment/context.go#L180-L184
train
flynn/flynn
pkg/mauth/compare/compare.go
UnmarshalBinary
func UnmarshalBinary(b []byte) (interface{}, error) { if len(b) < 1 { return nil, fmt.Errorf("compare: buffer to unmarshal is zero-length") } switch Type(b[0]) { case TypeFalse, TypeTrue: v := new(Bool) return *v, v.UnmarshalBinary(b) case TypeIntegers: v := new(Integers) return *v, v.UnmarshalBinary(b) case TypeStrings: v := new(Strings) return *v, v.UnmarshalBinary(b) case TypeRegexp: v := new(Regexp) return v, v.UnmarshalBinary(b) case TypeCIDRs: v := new(CIDRs) return *v, v.UnmarshalBinary(b) default: return nil, fmt.Errorf("compare: unknown type %d", b[0]) } }
go
func UnmarshalBinary(b []byte) (interface{}, error) { if len(b) < 1 { return nil, fmt.Errorf("compare: buffer to unmarshal is zero-length") } switch Type(b[0]) { case TypeFalse, TypeTrue: v := new(Bool) return *v, v.UnmarshalBinary(b) case TypeIntegers: v := new(Integers) return *v, v.UnmarshalBinary(b) case TypeStrings: v := new(Strings) return *v, v.UnmarshalBinary(b) case TypeRegexp: v := new(Regexp) return v, v.UnmarshalBinary(b) case TypeCIDRs: v := new(CIDRs) return *v, v.UnmarshalBinary(b) default: return nil, fmt.Errorf("compare: unknown type %d", b[0]) } }
[ "func", "UnmarshalBinary", "(", "b", "[", "]", "byte", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "if", "len", "(", "b", ")", "<", "1", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"compare: buffer to unmarshal is zero-length\"", ")", "\n", "}", "\n", "switch", "Type", "(", "b", "[", "0", "]", ")", "{", "case", "TypeFalse", ",", "TypeTrue", ":", "v", ":=", "new", "(", "Bool", ")", "\n", "return", "*", "v", ",", "v", ".", "UnmarshalBinary", "(", "b", ")", "\n", "case", "TypeIntegers", ":", "v", ":=", "new", "(", "Integers", ")", "\n", "return", "*", "v", ",", "v", ".", "UnmarshalBinary", "(", "b", ")", "\n", "case", "TypeStrings", ":", "v", ":=", "new", "(", "Strings", ")", "\n", "return", "*", "v", ",", "v", ".", "UnmarshalBinary", "(", "b", ")", "\n", "case", "TypeRegexp", ":", "v", ":=", "new", "(", "Regexp", ")", "\n", "return", "v", ",", "v", ".", "UnmarshalBinary", "(", "b", ")", "\n", "case", "TypeCIDRs", ":", "v", ":=", "new", "(", "CIDRs", ")", "\n", "return", "*", "v", ",", "v", ".", "UnmarshalBinary", "(", "b", ")", "\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"compare: unknown type %d\"", ",", "b", "[", "0", "]", ")", "\n", "}", "\n", "}" ]
// comparisons are encoded as a single type byte followed by zero or more bytes // that are specific to the comparison type. // // UINT8 - type // UINT8 0..n - bytes
[ "comparisons", "are", "encoded", "as", "a", "single", "type", "byte", "followed", "by", "zero", "or", "more", "bytes", "that", "are", "specific", "to", "the", "comparison", "type", ".", "UINT8", "-", "type", "UINT8", "0", "..", "n", "-", "bytes" ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/mauth/compare/compare.go#L29-L52
train
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", "c", ":=", "&", "closeNotifyConn", "{", "Conn", ":", "conn", ",", "r", ":", "pr", ",", "cnc", ":", "make", "(", "chan", "bool", ")", ",", "}", "\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", "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", "(", "\"unexpected close of discoverd event stream\"", ")", "\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", "if", "!", "tty", "{", "bar", ".", "Output", "=", "os", ".", "Stderr", "\n", "return", "bar", ",", "nil", "\n", "}", "\n", "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", "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", "len", "(", "barText", ")", ">", "0", "{", "spaces", ":=", "make", "(", "[", "]", "byte", ",", "len", "(", "barText", ")", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "barText", ")", ";", "i", "++", "{", "spaces", "[", "i", "]", "=", "' '", "\n", "}", "\n", "fmt", ".", "Fprint", "(", "stderr", ",", "\"\\r\"", ",", "\\r", ",", "string", "(", "spaces", ")", ")", "\n", "}", "\n", "\"\\r\"", "\n", "\\r", "\n", "fmt", ".", "Fprintln", "(", "out", ".", "Out", ",", "out", ".", "Text", ")", "}", "\n", "}", "\n", "}", "if", "len", "(", "barText", ")", ">", "0", "{", "fmt", ".", "Fprint", "(", "stderr", ",", "\"\\r\"", "+", "\\r", ")", "\n", "}", "\n", "barText", "\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", "(", "\"missing %q in tuf targets\"", ",", "name", ")", "\n", "}", "\n", "if", "target", ".", "Custom", "==", "nil", "||", "len", "(", "*", "target", ".", "Custom", ")", "==", "0", "{", "return", "\"\"", ",", "errors", ".", "New", "(", "\"missing custom metadata in tuf target\"", ")", "\n", "}", "\n", "var", "data", "struct", "{", "Version", "string", "\n", "}", "\n", "json", ".", "Unmarshal", "(", "*", "target", ".", "Custom", ",", "&", "data", ")", "\n", "if", "data", ".", "Version", "==", "\"\"", "{", "return", "\"\"", ",", "errors", ".", "New", "(", "\"missing version in tuf target\"", ")", "\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", "(", "\"fn\"", ",", "\"startTransitionToNormalMode\"", ")", "\n", "if", "p", ".", "Info", "(", ")", ".", "State", ".", "Primary", ".", "Meta", "[", "p", ".", "idKey", "]", "!=", "p", ".", "id", "||", "p", ".", "Info", "(", ")", ".", "Role", "!=", "RolePrimary", "{", "panic", "(", "\"startTransitionToNormalMode called when not primary\"", ")", "\n", "}", "\n", "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", "(", "\"would takeover but no peers present\"", ")", "\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", "log", ".", "Debug", "(", "\"transitioning to normal mode\"", ")", "\n", "p", ".", "startTakeoverWithPeer", "(", "\"transitioning to normal mode\"", ",", "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", "(", "\"fn\"", ",", "\"applyConfig\"", ")", "\n", "if", "p", ".", "online", "==", "nil", "{", "panic", "(", "\"applyConfig with database in unknown state\"", ")", "\n", "}", "\n", "config", ":=", "p", ".", "Config", "(", ")", "\n", "if", "p", ".", "applied", "!=", "nil", "&&", "p", ".", "applied", ".", "Equal", "(", "config", ")", "&&", "p", ".", "applied", ".", "State", ".", "Equal", "(", "config", ".", "State", ")", "{", "log", ".", "Info", "(", "\"skipping config apply, no changes\"", ")", "\n", "return", "nil", "\n", "}", "\n", "defer", "func", "(", ")", "{", "if", "err", "==", "nil", "{", "return", "\n", "}", "\n", "log", ".", "Error", "(", "\"error applying database config\"", ",", "\"err\"", ",", "err", ")", "\n", "t", ":=", "TimeNow", "(", ")", "\n", "p", ".", "setRetryPending", "(", "&", "t", ")", "\n", "p", ".", "applyConfigLater", "(", "1", "*", "time", ".", "Second", ")", "\n", "}", "(", ")", "\n", "log", ".", "Info", "(", "\"reconfiguring database\"", ")", "\n", "if", "err", ":=", "p", ".", "db", ".", "Reconfigure", "(", "config", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "config", ".", "Role", "!=", "RoleNone", "{", "if", "*", "p", ".", "online", "{", "log", ".", "Debug", "(", "\"skipping start, already online\"", ")", "\n", "}", "else", "{", "log", ".", "Debug", "(", "\"starting database\"", ")", "\n", "if", "err", ":=", "p", ".", "db", ".", "Start", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "else", "{", "if", "*", "p", ".", "online", "{", "log", ".", "Debug", "(", "\"stopping database\"", ")", "\n", "if", "err", ":=", "p", ".", "db", ".", "Stop", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "else", "{", "log", ".", "Debug", "(", "\"skipping stop, already offline\"", ")", "\n", "}", "\n", "}", "\n", "log", ".", "Info", "(", "\"applied database config\"", ")", "\n", "p", ".", "setRetryPending", "(", "nil", ")", "\n", "p", ".", "applied", "=", "config", "\n", "online", ":=", "config", ".", "Role", "!=", "RoleNone", "\n", "p", ".", "online", "=", "&", "online", "\n", "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", "{", "if", "other", ".", "Meta", "[", "p", ".", "idKey", "]", "==", "p", ".", "id", "{", "panic", "(", "\"peerIsPresent with self\"", ")", "\n", "}", "\n", "for", "_", ",", "peer", ":=", "range", "p", ".", "Info", "(", ")", ".", "Peers", "{", "if", "peer", ".", "Meta", "[", "p", ".", "idKey", "]", "==", "other", ".", "Meta", "[", "p", ".", "idKey", "]", "{", "return", "true", "\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", "(", "\"router: nil transport for proxy\"", ")", "\n", "}", "\n", "defer", "dconn", ".", "Close", "(", ")", "\n", "clientGone", ":=", "dconn", ".", "(", "http", ".", "CloseNotifier", ")", ".", "CloseNotify", "(", ")", "\n", "ctx", ",", "cancel", ":=", "context", ".", "WithCancel", "(", "ctx", ")", "\n", "defer", "cancel", "(", ")", "\n", "go", "func", "(", ")", "{", "select", "{", "case", "<-", "clientGone", ":", "cancel", "(", ")", "\n", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "}", "\n", "}", "(", ")", "\n", "l", ":=", "p", ".", "Logger", ".", "New", "(", "\"client_addr\"", ",", "dconn", ".", "RemoteAddr", "(", ")", ",", "\"host_addr\"", ",", "dconn", ".", "LocalAddr", "(", ")", ",", "\"proxy\"", ",", "\"tcp\"", ")", "\n", "uconn", ",", "err", ":=", "transport", ".", "Connect", "(", "ctx", ",", "l", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "defer", "uconn", ".", "Close", "(", ")", "\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", "(", "\"service stream closed unexpectedly: %s\"", ",", "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", "deploymentMeta", ",", "err", ":=", "d", ".", "decode", "(", "d", ".", "meta", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "deploymentMeta", ".", "States", "[", "addr", "]", "=", "DeploymentStateDone", "\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", "(", "\"service stream closed unexpectedly: %s\"", ",", "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", "(", "\"got service meta event\"", ",", "\"state\"", ",", "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", "(", "\"ignoring service meta even with wrong ID\"", ",", "\"expected\"", ",", "id", ",", "\"got\"", ",", "deploymentMeta", ".", "ID", ")", "\n", "}", "\n", "}", "\n", "case", "<-", "timeoutCh", ":", "return", "fmt", ".", "Errorf", "(", "\"timed out waiting for discoverd deployment (expected=%d actual=%d)\"", ",", "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", "(", "\"POST\"", ",", "\"/attach\"", ",", "http", ".", "Header", "{", "\"Upgrade\"", ":", "{", "\"flynn-attach/0\"", "}", "}", ",", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "attachState", ":=", "make", "(", "[", "]", "byte", ",", "1", ")", "\n", "if", "_", ",", "err", ":=", "rwc", ".", "Read", "(", "attachState", ")", ";", "err", "!=", "nil", "{", "rwc", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\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", "(", "\"cluster: unknown attach state: %d\"", ",", "attachState", ")", "\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", "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", "cn", ",", "err", ":=", "dialer", ".", "Retry", ".", "Dial", "(", "network", ",", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "conn", ":=", "Conn", "{", "Conn", ":", "tls", ".", "Client", "(", "cn", ",", "&", "conf", ")", ",", "Wire", ":", "cn", ",", "}", "\n", "if", "conf", ".", "ServerName", "==", "\"\"", "{", "conf", ".", "ServerName", ",", "_", ",", "_", "=", "net", ".", "SplitHostPort", "(", "addr", ")", "\n", "}", "\n", "if", "err", "=", "conn", ".", "Handshake", "(", ")", ";", "err", "!=", "nil", "{", "conn", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\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", "(", "\"pinned: underlying connection does not support CloseWrite\"", ")", "\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", "if", "idx", "<", "c", ".", "idx", "{", "return", "\n", "}", "\n", "c", ".", "idx", "=", "idx", "\n", "servers", "=", "formatURLs", "(", "servers", ")", "\n", "for", "_", ",", "s", ":=", "range", "servers", "{", "if", "_", ",", "ok", ":=", "c", ".", "servers", "[", "s", "]", ";", "!", "ok", "{", "c", ".", "servers", "[", "s", "]", "=", "c", ".", "httpClient", "(", "s", ")", "\n", "}", "\n", "}", "\n", "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", "saddr", ",", "typ", ",", "err", ":=", "sockaddr", "(", "proto", ",", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "fd", ",", "err", ":=", "syscall", ".", "Socket", "(", "typ", ",", "syscall", ".", "SOCK_STREAM", ",", "syscall", ".", "IPPROTO_TCP", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "setSockopt", "(", "fd", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "syscall", ".", "Bind", "(", "fd", ",", "saddr", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "syscall", ".", "Listen", "(", "fd", ",", "backlog", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "f", ":=", "os", ".", "NewFile", "(", "uintptr", "(", "fd", ")", ",", "proto", "+", "\":\"", "+", "addr", ")", "\n", "l", ",", "err", ":=", "net", ".", "FileListener", "(", "f", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "f", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "l", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\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", "(", "\"http://%s\"", ",", "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", "(", "\"app\"", ",", "\"redis\"", ")", ",", "}", "\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", "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", "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", "(", "\"unexpectedly exit\"", ",", "\"err\"", ",", "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", "(", "\"fn\"", ",", "\"writeConfig\"", ")", "\n", "logger", ".", "Info", "(", "\"writing\"", ")", "\n", "if", "err", ":=", "os", ".", "MkdirAll", "(", "filepath", ".", "Dir", "(", "p", ".", "ConfigPath", "(", ")", ")", ",", "0777", ")", ";", "err", "!=", "nil", "{", "logger", ".", "Error", "(", "\"cannot create config parent directory\"", ",", "\"err\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n", "f", ",", "err", ":=", "os", ".", "Create", "(", "p", ".", "ConfigPath", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Error", "(", "\"cannot create config file\"", ",", "\"err\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\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", "{", "if", "addr", "==", "\"\"", "{", "addr", "=", "fmt", ".", "Sprintf", "(", "\"localhost:%s\"", ",", "p", ".", "Port", ")", "\n", "}", "\n", "logger", ":=", "p", ".", "Logger", ".", "New", "(", "\"fn\"", ",", "\"ping\"", ",", "\"addr\"", ",", "addr", ",", "\"timeout\"", ",", "timeout", ")", "\n", "logger", ".", "Info", "(", "\"sending\"", ")", "\n", "timer", ":=", "time", ".", "NewTimer", "(", "timeout", ")", "\n", "defer", "timer", ".", "Stop", "(", ")", "\n", "ticker", ":=", "time", ".", "NewTicker", "(", "checkInterval", ")", "\n", "defer", "ticker", ".", "Stop", "(", ")", "\n", "for", "{", "if", "ok", ":=", "func", "(", ")", "bool", "{", "logger", ".", "Info", "(", "\"sending PING\"", ")", "\n", "conn", ",", "err", ":=", "redis", ".", "Dial", "(", "\"tcp\"", ",", "addr", ",", "redis", ".", "DialPassword", "(", "p", ".", "Password", ")", ",", "redis", ".", "DialConnectTimeout", "(", "timeout", ")", ",", "redis", ".", "DialReadTimeout", "(", "timeout", ")", ",", "redis", ".", "DialWriteTimeout", "(", "timeout", ")", ",", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Error", "(", "\"conn error\"", ",", "\"err\"", ",", "err", ")", "\n", "return", "false", "\n", "}", "\n", "defer", "conn", ".", "Close", "(", ")", "\n", "if", "_", ",", "err", ":=", "conn", ".", "Do", "(", "\"PING\"", ")", ";", "err", "!=", "nil", "{", "logger", ".", "Error", "(", "\"error getting upstream status\"", ",", "\"err\"", ",", "err", ")", "\n", "return", "false", "\n", "}", "\n", "logger", ".", "Info", "(", "\"PONG received\"", ")", "\n", "return", "true", "\n", "}", "(", ")", ";", "ok", "{", "return", "nil", "\n", "}", "\n", "select", "{", "case", "<-", "timer", ".", "C", ":", "logger", ".", "Info", "(", "\"timeout\"", ")", "\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", "{", "if", "addr", "==", "\"\"", "{", "addr", "=", "fmt", ".", "Sprintf", "(", "\"localhost:%s\"", ",", "p", ".", "Port", ")", "\n", "}", "\n", "logger", ":=", "p", ".", "Logger", ".", "New", "(", "\"fn\"", ",", "\"pingWait\"", ",", "\"addr\"", ",", "addr", ",", "\"timeout\"", ",", "timeout", ")", "\n", "ticker", ":=", "time", ".", "NewTicker", "(", "checkInterval", ")", "\n", "defer", "ticker", ".", "Stop", "(", ")", "\n", "timer", ":=", "time", ".", "NewTimer", "(", "timeout", ")", "\n", "defer", "timer", ".", "Stop", "(", ")", "\n", "for", "{", "select", "{", "case", "<-", "timer", ".", "C", ":", "return", "ErrTimeout", "\n", "case", "<-", "ticker", ".", "C", ":", "}", "\n", "if", "err", ":=", "p", ".", "ping", "(", "addr", ",", "timeout", ")", ";", "err", "!=", "nil", "{", "logger", ".", "Error", "(", "\"ping error\"", ",", "\"err\"", ",", "err", ")", "\n", "continue", "\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", "logger", ":=", "p", ".", "Logger", ".", "New", "(", "\"fn\"", ",", "\"Restore\"", ")", "\n", "logger", ".", "Info", "(", "\"begin restore\"", ")", "\n", "if", "p", ".", "running", "{", "logger", ".", "Info", "(", "\"stopping process\"", ")", "\n", "if", "err", ":=", "p", ".", "stop", "(", ")", ";", "err", "!=", "nil", "{", "logger", ".", "Error", "(", "\"error stopping process\"", ",", "\"err\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n", "}", "\n", "logger", ".", "Info", "(", "\"copying dump.rdb\"", ")", "\n", "if", "err", ":=", "func", "(", ")", "error", "{", "f", ",", "err", ":=", "os", ".", "Create", "(", "filepath", ".", "Join", "(", "p", ".", "DataDir", ",", "\"dump.rdb\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Error", "(", "\"error creating dump file\"", ",", "\"err\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n", "n", ",", "err", ":=", "io", ".", "Copy", "(", "f", ",", "r", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Error", "(", "\"error creating dump file\"", ",", "\"err\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n", "logger", ".", "Info", "(", "\"copy completed\"", ",", "\"n\"", ",", "n", ")", "\n", "return", "nil", "\n", "}", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "p", ".", "start", "(", ")", ";", "err", "!=", "nil", "{", "logger", ".", "Error", "(", "\"error restarting process\"", ",", "\"err\"", ",", "err", ")", "\n", "return", "err", "\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", ")", "{", "if", "addr", "==", "\"\"", "{", "addr", "=", "fmt", ".", "Sprintf", "(", "\"localhost:%s\"", ",", "p", ".", "Port", ")", "\n", "}", "\n", "logger", ":=", "p", ".", "Logger", ".", "New", "(", "\"fn\"", ",", "\"replInfo\"", ",", "\"addr\"", ",", "addr", ")", "\n", "logger", ".", "Info", "(", "\"sending INFO\"", ")", "\n", "conn", ",", "err", ":=", "redis", ".", "Dial", "(", "\"tcp\"", ",", "addr", ",", "redis", ".", "DialPassword", "(", "p", ".", "Password", ")", ",", "redis", ".", "DialConnectTimeout", "(", "timeout", ")", ",", "redis", ".", "DialReadTimeout", "(", "timeout", ")", ",", "redis", ".", "DialWriteTimeout", "(", "timeout", ")", ",", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Info", "(", "\"dial error\"", ",", "\"err\"", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "conn", ".", "Close", "(", ")", "\n", "reply", ",", "err", ":=", "conn", ".", "Do", "(", "\"INFO\"", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Error", "(", "\"info error\"", ",", "\"err\"", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "buf", ",", "ok", ":=", "reply", ".", "(", "[", "]", "byte", ")", "\n", "if", "!", "ok", "{", "logger", ".", "Error", "(", "\"info reply type error\"", ",", "\"type\"", ",", "fmt", ".", "Sprintf", "(", "\"%T\"", ",", "buf", ")", ")", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"unexpected INFO reply format: %T\"", ",", "buf", ")", "\n", "}", "\n", "info", ",", "err", ":=", "ParseRedisInfo", "(", "string", "(", "buf", ")", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Error", "(", "\"parse info error\"", ",", "\"err\"", ",", "err", ")", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"parse info: %s\"", ",", "err", ")", "\n", "}", "\n", "logger", ".", "Info", "(", "\"INFO received\"", ")", "\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", "scanner", ":=", "bufio", ".", "NewScanner", "(", "strings", ".", "NewReader", "(", "s", ")", ")", "\n", "for", "scanner", ".", "Scan", "(", ")", "{", "line", ":=", "scanner", ".", "Text", "(", ")", "\n", "if", "strings", ".", "HasPrefix", "(", "line", ",", "\"#\"", ")", "||", "line", "==", "\"\"", "{", "continue", "\n", "}", "\n", "a", ":=", "strings", ".", "SplitN", "(", "line", ",", "\":\"", ",", "2", ")", "\n", "if", "len", "(", "a", ")", "<", "2", "{", "continue", "\n", "}", "\n", "key", ",", "value", ":=", "strings", ".", "TrimSpace", "(", "a", "[", "0", "]", ")", ",", "strings", ".", "TrimSpace", "(", "a", "[", "1", "]", ")", "\n", "switch", "key", "{", "case", "\"role\"", ":", "info", ".", "Role", "=", "value", "\n", "case", "\"master_host\"", ":", "info", ".", "MasterHost", "=", "value", "\n", "case", "\"master_port\"", ":", "info", ".", "MasterPort", "=", "atoi", "(", "value", ")", "\n", "case", "\"master_link_status\"", ":", "info", ".", "MasterLinkStatus", "=", "value", "\n", "case", "\"master_last_io_seconds_ago\"", ":", "info", ".", "MasterLastIO", "=", "time", ".", "Duration", "(", "atoi", "(", "value", ")", ")", "*", "time", ".", "Second", "\n", "case", "\"master_sync_in_progress\"", ":", "info", ".", "MasterSyncInProgress", "=", "value", "==", "\"1\"", "\n", "case", "\"master_sync_left_bytes\"", ":", "info", ".", "MasterSyncLeftBytes", ",", "_", "=", "strconv", ".", "ParseInt", "(", "value", ",", "10", ",", "64", ")", "\n", "case", "\"master_sync_last_io_seconds_ago\"", ":", "info", ".", "MasterSyncLastIO", "=", "time", ".", "Duration", "(", "atoi", "(", "value", ")", ")", "*", "time", ".", "Second", "\n", "case", "\"master_link_down_since_seconds\"", ":", "info", ".", "MasterLinkDownSince", "=", "time", ".", "Duration", "(", "atoi", "(", "value", ")", ")", "*", "time", ".", "Second", "\n", "case", "\"connected_slaves\"", ":", "info", ".", "ConnectedSlaves", "=", "atoi", "(", "value", ")", "\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", "[", "\"web\"", "]", ";", "!", "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", "(", "\"unexpected resume message from child: %s\"", ",", "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", "(", "\"cluster: unknown host %q\"", ",", "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", "[", "\"id\"", "]", ",", "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", "{", "volumesBucket", ":=", "tx", ".", "Bucket", "(", "[", "]", "byte", "(", "\"volumes\"", ")", ")", "\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", "(", "\"failed to serialize volume info: %s\"", ",", "err", ")", "\n", "}", "\n", "err", "=", "volumesBucket", ".", "Put", "(", "k", ",", "b", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"could not persist volume info to boltdb: %s\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "providerBucket", ",", "err", ":=", "m", ".", "getProviderBucket", "(", "tx", ",", "m", ".", "providerIDs", "[", "vol", ".", "Provider", "(", ")", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"could not persist provider volume info to boltdb: %s\"", ",", "err", ")", "\n", "}", "\n", "providerVolumesBucket", ":=", "providerBucket", ".", "Bucket", "(", "[", "]", "byte", "(", "\"volumes\"", ")", ")", "\n", "if", "!", "volExists", "{", "providerVolumesBucket", ".", "Delete", "(", "k", ")", "\n", "}", "else", "{", "b", ",", "err", ":=", "vol", ".", "Provider", "(", ")", ".", "MarshalVolumeState", "(", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"failed to serialize provider volume info: %s\"", ",", "err", ")", "\n", "}", "\n", "err", "=", "providerVolumesBucket", ".", "Put", "(", "k", ",", "b", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"could not persist provider volume info to boltdb: %s\"", ",", "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", "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", "(", "\"failed to delete IPv4 addr %s from %s\"", ",", "old", ".", "String", "(", ")", ",", "link", ".", "Attrs", "(", ")", ".", "Name", ")", "\n", "}", "\n", "}", "\n", "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", ")", "\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", "if", "b", ".", "length", "==", "-", "1", "{", "return", "errors", ".", "New", "(", "\"buffer closed\"", ")", "\n", "}", "\n", "if", "b", ".", "head", "==", "nil", "{", "b", ".", "head", "=", "&", "message", "{", "Message", ":", "*", "m", "}", "\n", "b", ".", "tail", "=", "b", ".", "head", "\n", "}", "else", "{", "for", "other", ":=", "b", ".", "tail", ";", "other", "!=", "nil", ";", "other", "=", "other", ".", "prev", "{", "if", "m", ".", "Timestamp", ".", "Equal", "(", "other", ".", "Timestamp", ")", "&&", "bytes", ".", "Equal", "(", "m", ".", "StructuredData", ",", "other", ".", "StructuredData", ")", "{", "return", "nil", "\n", "}", "\n", "if", "m", ".", "Timestamp", ".", "Before", "(", "other", ".", "Timestamp", ")", "{", "if", "other", ".", "prev", "==", "nil", "{", "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", "{", "other", ".", "next", ".", "prev", "=", "msg", "\n", "msg", ".", "next", "=", "other", ".", "next", "\n", "}", "else", "{", "b", ".", "tail", "=", "msg", "\n", "}", "\n", "other", ".", "next", "=", "msg", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "b", ".", "length", "<", "b", ".", "capacity", "{", "b", ".", "length", "++", "\n", "}", "else", "{", "b", ".", "head", "=", "b", ".", "head", ".", "next", "\n", "b", ".", "head", ".", "prev", "=", "nil", "\n", "}", "\n", "for", "msgc", ":=", "range", "b", ".", "subs", "{", "select", "{", "case", "msgc", "<-", "m", ":", "default", ":", "}", "\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", "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", "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", "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", "go", "func", "(", ")", "{", "select", "{", "case", "<-", "donec", ":", "case", "<-", "b", ".", "donec", ":", "}", "\n", "b", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "b", ".", "mu", ".", "Unlock", "(", ")", "\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", "s", ":=", "&", "LogStream", "{", "m", ":", "m", ",", "log", ":", "r", ",", "done", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n", "s", ".", "closed", ".", "Store", "(", "false", ")", "\n", "m", ".", "jobsMtx", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "jobsMtx", ".", "Unlock", "(", ")", "\n", "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", "{", "go", "func", "(", ")", "{", "wg", ".", "Wait", "(", ")", "\n", "m", ".", "jobsMtx", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "jobsMtx", ".", "Unlock", "(", ")", "\n", "delete", "(", "m", ".", "jobWaits", ",", "config", ".", "JobID", ")", "\n", "}", "(", ")", "\n", "}", "\n", "if", "ch", ",", "ok", ":=", "m", ".", "jobStarts", "[", "config", ".", "JobID", "]", ";", "ok", "{", "close", "(", "ch", ")", "\n", "delete", "(", "m", ".", "jobStarts", ",", "config", ".", "JobID", ")", "\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