id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
142,400
decred/dcrdata
txhelpers/txhelpers.go
ValidateNetworkAddress
func ValidateNetworkAddress(address dcrutil.Address, p *chaincfg.Params) bool { return address.IsForNet(p) }
go
func ValidateNetworkAddress(address dcrutil.Address, p *chaincfg.Params) bool { return address.IsForNet(p) }
[ "func", "ValidateNetworkAddress", "(", "address", "dcrutil", ".", "Address", ",", "p", "*", "chaincfg", ".", "Params", ")", "bool", "{", "return", "address", ".", "IsForNet", "(", "p", ")", "\n", "}" ]
// ValidateNetworkAddress checks if the given address is valid on the given // network.
[ "ValidateNetworkAddress", "checks", "if", "the", "given", "address", "is", "valid", "on", "the", "given", "network", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/txhelpers.go#L1168-L1170
142,401
decred/dcrdata
txhelpers/txhelpers.go
AddressValidation
func AddressValidation(address string, params *chaincfg.Params) (dcrutil.Address, AddressType, AddressError) { // Decode and validate the address. addr, err := dcrutil.DecodeAddress(address) if err != nil { return nil, AddressTypeUnknown, AddressErrorDecodeFailed } // Detect when an address belonging to a different Decred network. if !ValidateNetworkAddress(addr, params) { return addr, AddressTypeUnknown, AddressErrorWrongNet } // Determine address type for this valid Decred address. Ignore the error // since DecodeAddress succeeded. _, netID, _ := base58.CheckDecode(address) var addrType AddressType switch netID { case params.PubKeyAddrID: addrType = AddressTypeP2PK case params.PubKeyHashAddrID: addrType = AddressTypeP2PKH case params.ScriptHashAddrID: addrType = AddressTypeP2SH case params.PKHEdwardsAddrID, params.PKHSchnorrAddrID: addrType = AddressTypeOther default: addrType = AddressTypeUnknown } // Check if the address is the zero pubkey hash address commonly used for // zero value sstxchange-tagged outputs. Return a special error value, but // the decoded address and address type are valid. if IsZeroHashP2PHKAddress(address, params) { return addr, addrType, AddressErrorZeroAddress } return addr, addrType, AddressErrorNoError }
go
func AddressValidation(address string, params *chaincfg.Params) (dcrutil.Address, AddressType, AddressError) { // Decode and validate the address. addr, err := dcrutil.DecodeAddress(address) if err != nil { return nil, AddressTypeUnknown, AddressErrorDecodeFailed } // Detect when an address belonging to a different Decred network. if !ValidateNetworkAddress(addr, params) { return addr, AddressTypeUnknown, AddressErrorWrongNet } // Determine address type for this valid Decred address. Ignore the error // since DecodeAddress succeeded. _, netID, _ := base58.CheckDecode(address) var addrType AddressType switch netID { case params.PubKeyAddrID: addrType = AddressTypeP2PK case params.PubKeyHashAddrID: addrType = AddressTypeP2PKH case params.ScriptHashAddrID: addrType = AddressTypeP2SH case params.PKHEdwardsAddrID, params.PKHSchnorrAddrID: addrType = AddressTypeOther default: addrType = AddressTypeUnknown } // Check if the address is the zero pubkey hash address commonly used for // zero value sstxchange-tagged outputs. Return a special error value, but // the decoded address and address type are valid. if IsZeroHashP2PHKAddress(address, params) { return addr, addrType, AddressErrorZeroAddress } return addr, addrType, AddressErrorNoError }
[ "func", "AddressValidation", "(", "address", "string", ",", "params", "*", "chaincfg", ".", "Params", ")", "(", "dcrutil", ".", "Address", ",", "AddressType", ",", "AddressError", ")", "{", "// Decode and validate the address.", "addr", ",", "err", ":=", "dcrutil", ".", "DecodeAddress", "(", "address", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "AddressTypeUnknown", ",", "AddressErrorDecodeFailed", "\n", "}", "\n\n", "// Detect when an address belonging to a different Decred network.", "if", "!", "ValidateNetworkAddress", "(", "addr", ",", "params", ")", "{", "return", "addr", ",", "AddressTypeUnknown", ",", "AddressErrorWrongNet", "\n", "}", "\n\n", "// Determine address type for this valid Decred address. Ignore the error", "// since DecodeAddress succeeded.", "_", ",", "netID", ",", "_", ":=", "base58", ".", "CheckDecode", "(", "address", ")", "\n\n", "var", "addrType", "AddressType", "\n", "switch", "netID", "{", "case", "params", ".", "PubKeyAddrID", ":", "addrType", "=", "AddressTypeP2PK", "\n", "case", "params", ".", "PubKeyHashAddrID", ":", "addrType", "=", "AddressTypeP2PKH", "\n", "case", "params", ".", "ScriptHashAddrID", ":", "addrType", "=", "AddressTypeP2SH", "\n", "case", "params", ".", "PKHEdwardsAddrID", ",", "params", ".", "PKHSchnorrAddrID", ":", "addrType", "=", "AddressTypeOther", "\n", "default", ":", "addrType", "=", "AddressTypeUnknown", "\n", "}", "\n\n", "// Check if the address is the zero pubkey hash address commonly used for", "// zero value sstxchange-tagged outputs. Return a special error value, but", "// the decoded address and address type are valid.", "if", "IsZeroHashP2PHKAddress", "(", "address", ",", "params", ")", "{", "return", "addr", ",", "addrType", ",", "AddressErrorZeroAddress", "\n", "}", "\n\n", "return", "addr", ",", "addrType", ",", "AddressErrorNoError", "\n", "}" ]
// AddressValidation performs several validation checks on the given address // string. Initially, decoding as a Decred address is attempted. If it fails to // decode, AddressErrorDecodeFailed is returned with AddressTypeUnknown. // If the address decoded successfully as a Decred address, it is checked // against the specified network. If it is the wrong network, // AddressErrorWrongNet is returned with AddressTypeUnknown. If the address is // the correct network, the address type is obtained. A final check is performed // to determine if the address is the zero pubkey hash address, in which case // AddressErrorZeroAddress is returned with the determined address type. If it // is another address, AddressErrorNoError is returned with the determined // address type.
[ "AddressValidation", "performs", "several", "validation", "checks", "on", "the", "given", "address", "string", ".", "Initially", "decoding", "as", "a", "Decred", "address", "is", "attempted", ".", "If", "it", "fails", "to", "decode", "AddressErrorDecodeFailed", "is", "returned", "with", "AddressTypeUnknown", ".", "If", "the", "address", "decoded", "successfully", "as", "a", "Decred", "address", "it", "is", "checked", "against", "the", "specified", "network", ".", "If", "it", "is", "the", "wrong", "network", "AddressErrorWrongNet", "is", "returned", "with", "AddressTypeUnknown", ".", "If", "the", "address", "is", "the", "correct", "network", "the", "address", "type", "is", "obtained", ".", "A", "final", "check", "is", "performed", "to", "determine", "if", "the", "address", "is", "the", "zero", "pubkey", "hash", "address", "in", "which", "case", "AddressErrorZeroAddress", "is", "returned", "with", "the", "determined", "address", "type", ".", "If", "it", "is", "another", "address", "AddressErrorNoError", "is", "returned", "with", "the", "determined", "address", "type", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/txhelpers/txhelpers.go#L1205-L1243
142,402
decred/dcrdata
db/dcrpg/internal/stakestmts.go
MakeVoteInsertStatement
func MakeVoteInsertStatement(checked, updateOnConflict bool) string { if !checked { return InsertVoteRow } if updateOnConflict { return UpsertVoteRow } return InsertVoteRowOnConflictDoNothing }
go
func MakeVoteInsertStatement(checked, updateOnConflict bool) string { if !checked { return InsertVoteRow } if updateOnConflict { return UpsertVoteRow } return InsertVoteRowOnConflictDoNothing }
[ "func", "MakeVoteInsertStatement", "(", "checked", ",", "updateOnConflict", "bool", ")", "string", "{", "if", "!", "checked", "{", "return", "InsertVoteRow", "\n", "}", "\n", "if", "updateOnConflict", "{", "return", "UpsertVoteRow", "\n", "}", "\n", "return", "InsertVoteRowOnConflictDoNothing", "\n", "}" ]
// MakeVoteInsertStatement returns the appropriate votes insert statement for // the desired conflict checking and handling behavior. See the description of // MakeTicketInsertStatement for details.
[ "MakeVoteInsertStatement", "returns", "the", "appropriate", "votes", "insert", "statement", "for", "the", "desired", "conflict", "checking", "and", "handling", "behavior", ".", "See", "the", "description", "of", "MakeTicketInsertStatement", "for", "details", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/internal/stakestmts.go#L532-L540
142,403
decred/dcrdata
db/dcrpg/internal/stakestmts.go
MakeMissInsertStatement
func MakeMissInsertStatement(checked, updateOnConflict bool) string { if !checked { return InsertMissRow } if updateOnConflict { return UpsertMissRow } return InsertMissRowOnConflictDoNothing }
go
func MakeMissInsertStatement(checked, updateOnConflict bool) string { if !checked { return InsertMissRow } if updateOnConflict { return UpsertMissRow } return InsertMissRowOnConflictDoNothing }
[ "func", "MakeMissInsertStatement", "(", "checked", ",", "updateOnConflict", "bool", ")", "string", "{", "if", "!", "checked", "{", "return", "InsertMissRow", "\n", "}", "\n", "if", "updateOnConflict", "{", "return", "UpsertMissRow", "\n", "}", "\n", "return", "InsertMissRowOnConflictDoNothing", "\n", "}" ]
// MakeMissInsertStatement returns the appropriate misses insert statement for // the desired conflict checking and handling behavior. See the description of // MakeTicketInsertStatement for details.
[ "MakeMissInsertStatement", "returns", "the", "appropriate", "misses", "insert", "statement", "for", "the", "desired", "conflict", "checking", "and", "handling", "behavior", ".", "See", "the", "description", "of", "MakeTicketInsertStatement", "for", "details", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/internal/stakestmts.go#L545-L553
142,404
nanomsg/mangos-v1
examples/websocket/subclient.go
subClient
func subClient(port int) { sock, err := sub.NewSocket() if err != nil { die("cannot make req socket: %v", err) } sock.AddTransport(ws.NewTransport()) if err = sock.SetOption(mangos.OptionSubscribe, []byte{}); err != nil { die("cannot set subscription: %v", err) } url := fmt.Sprintf("ws://127.0.0.1:%d/sub", port) if err = sock.Dial(url); err != nil { die("cannot dial req url: %v", err) } if m, err := sock.Recv(); err != nil { die("Cannot recv sub: %v", err) } else { fmt.Printf("%s\n", string(m)) } }
go
func subClient(port int) { sock, err := sub.NewSocket() if err != nil { die("cannot make req socket: %v", err) } sock.AddTransport(ws.NewTransport()) if err = sock.SetOption(mangos.OptionSubscribe, []byte{}); err != nil { die("cannot set subscription: %v", err) } url := fmt.Sprintf("ws://127.0.0.1:%d/sub", port) if err = sock.Dial(url); err != nil { die("cannot dial req url: %v", err) } if m, err := sock.Recv(); err != nil { die("Cannot recv sub: %v", err) } else { fmt.Printf("%s\n", string(m)) } }
[ "func", "subClient", "(", "port", "int", ")", "{", "sock", ",", "err", ":=", "sub", ".", "NewSocket", "(", ")", "\n", "if", "err", "!=", "nil", "{", "die", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "sock", ".", "AddTransport", "(", "ws", ".", "NewTransport", "(", ")", ")", "\n", "if", "err", "=", "sock", ".", "SetOption", "(", "mangos", ".", "OptionSubscribe", ",", "[", "]", "byte", "{", "}", ")", ";", "err", "!=", "nil", "{", "die", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "url", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "port", ")", "\n", "if", "err", "=", "sock", ".", "Dial", "(", "url", ")", ";", "err", "!=", "nil", "{", "die", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "m", ",", "err", ":=", "sock", ".", "Recv", "(", ")", ";", "err", "!=", "nil", "{", "die", "(", "\"", "\"", ",", "err", ")", "\n", "}", "else", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "string", "(", "m", ")", ")", "\n", "}", "\n", "}" ]
// subClient implements the client for SUB.
[ "subClient", "implements", "the", "client", "for", "SUB", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/examples/websocket/subclient.go#L26-L44
142,405
nanomsg/mangos-v1
protocol.go
ProtocolName
func ProtocolName(number uint16) string { names := map[uint16]string{ ProtoPair: "pair", ProtoPub: "pub", ProtoSub: "sub", ProtoReq: "req", ProtoRep: "rep", ProtoPush: "push", ProtoPull: "pull", ProtoSurveyor: "surveyor", ProtoRespondent: "respondent", ProtoBus: "bus"} return names[number] }
go
func ProtocolName(number uint16) string { names := map[uint16]string{ ProtoPair: "pair", ProtoPub: "pub", ProtoSub: "sub", ProtoReq: "req", ProtoRep: "rep", ProtoPush: "push", ProtoPull: "pull", ProtoSurveyor: "surveyor", ProtoRespondent: "respondent", ProtoBus: "bus"} return names[number] }
[ "func", "ProtocolName", "(", "number", "uint16", ")", "string", "{", "names", ":=", "map", "[", "uint16", "]", "string", "{", "ProtoPair", ":", "\"", "\"", ",", "ProtoPub", ":", "\"", "\"", ",", "ProtoSub", ":", "\"", "\"", ",", "ProtoReq", ":", "\"", "\"", ",", "ProtoRep", ":", "\"", "\"", ",", "ProtoPush", ":", "\"", "\"", ",", "ProtoPull", ":", "\"", "\"", ",", "ProtoSurveyor", ":", "\"", "\"", ",", "ProtoRespondent", ":", "\"", "\"", ",", "ProtoBus", ":", "\"", "\"", "}", "\n", "return", "names", "[", "number", "]", "\n", "}" ]
// ProtocolName returns the name corresponding to a given protocol number. // This is useful for transports like WebSocket, which use a text name // rather than the number in the handshake.
[ "ProtocolName", "returns", "the", "name", "corresponding", "to", "a", "given", "protocol", "number", ".", "This", "is", "useful", "for", "transports", "like", "WebSocket", "which", "use", "a", "text", "name", "rather", "than", "the", "number", "in", "the", "handshake", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/protocol.go#L180-L193
142,406
nanomsg/mangos-v1
protocol.go
ValidPeers
func ValidPeers(p1, p2 Protocol) bool { if p1.Number() != p2.PeerNumber() { return false } if p2.Number() != p1.PeerNumber() { return false } return true }
go
func ValidPeers(p1, p2 Protocol) bool { if p1.Number() != p2.PeerNumber() { return false } if p2.Number() != p1.PeerNumber() { return false } return true }
[ "func", "ValidPeers", "(", "p1", ",", "p2", "Protocol", ")", "bool", "{", "if", "p1", ".", "Number", "(", ")", "!=", "p2", ".", "PeerNumber", "(", ")", "{", "return", "false", "\n", "}", "\n", "if", "p2", ".", "Number", "(", ")", "!=", "p1", ".", "PeerNumber", "(", ")", "{", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// ValidPeers returns true if the two sockets are capable of // peering to one another. For example, REQ can peer with REP, // but not with BUS.
[ "ValidPeers", "returns", "true", "if", "the", "two", "sockets", "are", "capable", "of", "peering", "to", "one", "another", ".", "For", "example", "REQ", "can", "peer", "with", "REP", "but", "not", "with", "BUS", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/protocol.go#L198-L206
142,407
nanomsg/mangos-v1
transport/all/all.go
AddTransports
func AddTransports(sock mangos.Socket) { sock.AddTransport(tcp.NewTransport()) sock.AddTransport(inproc.NewTransport()) sock.AddTransport(ipc.NewTransport()) sock.AddTransport(tlstcp.NewTransport()) sock.AddTransport(ws.NewTransport()) sock.AddTransport(wss.NewTransport()) }
go
func AddTransports(sock mangos.Socket) { sock.AddTransport(tcp.NewTransport()) sock.AddTransport(inproc.NewTransport()) sock.AddTransport(ipc.NewTransport()) sock.AddTransport(tlstcp.NewTransport()) sock.AddTransport(ws.NewTransport()) sock.AddTransport(wss.NewTransport()) }
[ "func", "AddTransports", "(", "sock", "mangos", ".", "Socket", ")", "{", "sock", ".", "AddTransport", "(", "tcp", ".", "NewTransport", "(", ")", ")", "\n", "sock", ".", "AddTransport", "(", "inproc", ".", "NewTransport", "(", ")", ")", "\n", "sock", ".", "AddTransport", "(", "ipc", ".", "NewTransport", "(", ")", ")", "\n", "sock", ".", "AddTransport", "(", "tlstcp", ".", "NewTransport", "(", ")", ")", "\n", "sock", ".", "AddTransport", "(", "ws", ".", "NewTransport", "(", ")", ")", "\n", "sock", ".", "AddTransport", "(", "wss", ".", "NewTransport", "(", ")", ")", "\n", "}" ]
// AddTransports adds all known transports to the given socket.
[ "AddTransports", "adds", "all", "known", "transports", "to", "the", "given", "socket", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/transport/all/all.go#L31-L38
142,408
nanomsg/mangos-v1
transport/tcp/tcp.go
get
func (o options) get(name string) (interface{}, error) { v, ok := o[name] if !ok { return nil, mangos.ErrBadOption } return v, nil }
go
func (o options) get(name string) (interface{}, error) { v, ok := o[name] if !ok { return nil, mangos.ErrBadOption } return v, nil }
[ "func", "(", "o", "options", ")", "get", "(", "name", "string", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "v", ",", "ok", ":=", "o", "[", "name", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "mangos", ".", "ErrBadOption", "\n", "}", "\n", "return", "v", ",", "nil", "\n", "}" ]
// GetOption retrieves an option value.
[ "GetOption", "retrieves", "an", "option", "value", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/transport/tcp/tcp.go#L29-L35
142,409
nanomsg/mangos-v1
transport/ws/ws.go
set
func (o options) set(name string, val interface{}) error { switch name { case mangos.OptionNoDelay: fallthrough case mangos.OptionKeepAlive: switch v := val.(type) { case bool: o[name] = v return nil default: return mangos.ErrBadValue } case mangos.OptionTLSConfig: switch v := val.(type) { case *tls.Config: o[name] = v return nil default: return mangos.ErrBadValue } case OptionWebSocketCheckOrigin: switch v := val.(type) { case bool: o[name] = v return nil default: return mangos.ErrBadValue } } return mangos.ErrBadOption }
go
func (o options) set(name string, val interface{}) error { switch name { case mangos.OptionNoDelay: fallthrough case mangos.OptionKeepAlive: switch v := val.(type) { case bool: o[name] = v return nil default: return mangos.ErrBadValue } case mangos.OptionTLSConfig: switch v := val.(type) { case *tls.Config: o[name] = v return nil default: return mangos.ErrBadValue } case OptionWebSocketCheckOrigin: switch v := val.(type) { case bool: o[name] = v return nil default: return mangos.ErrBadValue } } return mangos.ErrBadOption }
[ "func", "(", "o", "options", ")", "set", "(", "name", "string", ",", "val", "interface", "{", "}", ")", "error", "{", "switch", "name", "{", "case", "mangos", ".", "OptionNoDelay", ":", "fallthrough", "\n", "case", "mangos", ".", "OptionKeepAlive", ":", "switch", "v", ":=", "val", ".", "(", "type", ")", "{", "case", "bool", ":", "o", "[", "name", "]", "=", "v", "\n", "return", "nil", "\n", "default", ":", "return", "mangos", ".", "ErrBadValue", "\n", "}", "\n", "case", "mangos", ".", "OptionTLSConfig", ":", "switch", "v", ":=", "val", ".", "(", "type", ")", "{", "case", "*", "tls", ".", "Config", ":", "o", "[", "name", "]", "=", "v", "\n", "return", "nil", "\n", "default", ":", "return", "mangos", ".", "ErrBadValue", "\n", "}", "\n", "case", "OptionWebSocketCheckOrigin", ":", "switch", "v", ":=", "val", ".", "(", "type", ")", "{", "case", "bool", ":", "o", "[", "name", "]", "=", "v", "\n", "return", "nil", "\n", "default", ":", "return", "mangos", ".", "ErrBadValue", "\n", "}", "\n", "}", "\n", "return", "mangos", ".", "ErrBadOption", "\n", "}" ]
// SetOption sets an option. We have none, so just ErrBadOption.
[ "SetOption", "sets", "an", "option", ".", "We", "have", "none", "so", "just", "ErrBadOption", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/transport/ws/ws.go#L91-L121
142,410
nanomsg/mangos-v1
protocol/req/req.go
nextID
func (r *req) nextID() uint32 { // The high order bit is "special", and must always be set. (This is // how the peer will detect the end of the backtrace.) v := r.nextid | 0x80000000 r.nextid++ return v }
go
func (r *req) nextID() uint32 { // The high order bit is "special", and must always be set. (This is // how the peer will detect the end of the backtrace.) v := r.nextid | 0x80000000 r.nextid++ return v }
[ "func", "(", "r", "*", "req", ")", "nextID", "(", ")", "uint32", "{", "// The high order bit is \"special\", and must always be set. (This is", "// how the peer will detect the end of the backtrace.)", "v", ":=", "r", ".", "nextid", "|", "0x80000000", "\n", "r", ".", "nextid", "++", "\n", "return", "v", "\n", "}" ]
// nextID returns the next request ID.
[ "nextID", "returns", "the", "next", "request", "ID", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/protocol/req/req.go#L68-L74
142,411
nanomsg/mangos-v1
protocol/req/req.go
resender
func (r *req) resender() { defer r.w.Done() cq := r.sock.CloseChannel() for { select { case <-r.waker.C: case <-cq: return } r.Lock() m := r.reqmsg if m == nil { r.Unlock() continue } m = m.Dup() r.Unlock() r.resend <- m r.Lock() if r.retry > 0 { r.waker.Reset(r.retry) } else { r.waker.Stop() } r.Unlock() } }
go
func (r *req) resender() { defer r.w.Done() cq := r.sock.CloseChannel() for { select { case <-r.waker.C: case <-cq: return } r.Lock() m := r.reqmsg if m == nil { r.Unlock() continue } m = m.Dup() r.Unlock() r.resend <- m r.Lock() if r.retry > 0 { r.waker.Reset(r.retry) } else { r.waker.Stop() } r.Unlock() } }
[ "func", "(", "r", "*", "req", ")", "resender", "(", ")", "{", "defer", "r", ".", "w", ".", "Done", "(", ")", "\n", "cq", ":=", "r", ".", "sock", ".", "CloseChannel", "(", ")", "\n\n", "for", "{", "select", "{", "case", "<-", "r", ".", "waker", ".", "C", ":", "case", "<-", "cq", ":", "return", "\n", "}", "\n\n", "r", ".", "Lock", "(", ")", "\n", "m", ":=", "r", ".", "reqmsg", "\n", "if", "m", "==", "nil", "{", "r", ".", "Unlock", "(", ")", "\n", "continue", "\n", "}", "\n", "m", "=", "m", ".", "Dup", "(", ")", "\n", "r", ".", "Unlock", "(", ")", "\n\n", "r", ".", "resend", "<-", "m", "\n", "r", ".", "Lock", "(", ")", "\n", "if", "r", ".", "retry", ">", "0", "{", "r", ".", "waker", ".", "Reset", "(", "r", ".", "retry", ")", "\n", "}", "else", "{", "r", ".", "waker", ".", "Stop", "(", ")", "\n", "}", "\n", "r", ".", "Unlock", "(", ")", "\n", "}", "\n", "}" ]
// resend sends the request message again, after a timer has expired.
[ "resend", "sends", "the", "request", "message", "again", "after", "a", "timer", "has", "expired", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/protocol/req/req.go#L77-L107
142,412
nanomsg/mangos-v1
protocol/bus/bus.go
Init
func (x *bus) Init(sock mangos.ProtocolSocket) { x.sock = sock x.peers = make(map[uint32]*busEp) x.w.Init() x.w.Add() go x.sender() }
go
func (x *bus) Init(sock mangos.ProtocolSocket) { x.sock = sock x.peers = make(map[uint32]*busEp) x.w.Init() x.w.Add() go x.sender() }
[ "func", "(", "x", "*", "bus", ")", "Init", "(", "sock", "mangos", ".", "ProtocolSocket", ")", "{", "x", ".", "sock", "=", "sock", "\n", "x", ".", "peers", "=", "make", "(", "map", "[", "uint32", "]", "*", "busEp", ")", "\n", "x", ".", "w", ".", "Init", "(", ")", "\n", "x", ".", "w", ".", "Add", "(", ")", "\n", "go", "x", ".", "sender", "(", ")", "\n", "}" ]
// Init implements the Protocol Init method.
[ "Init", "implements", "the", "Protocol", "Init", "method", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/protocol/bus/bus.go#L44-L50
142,413
nanomsg/mangos-v1
protocol/bus/bus.go
peerSender
func (pe *busEp) peerSender() { for { m := <-pe.q if m == nil { return } if pe.ep.SendMsg(m) != nil { m.Free() return } } }
go
func (pe *busEp) peerSender() { for { m := <-pe.q if m == nil { return } if pe.ep.SendMsg(m) != nil { m.Free() return } } }
[ "func", "(", "pe", "*", "busEp", ")", "peerSender", "(", ")", "{", "for", "{", "m", ":=", "<-", "pe", ".", "q", "\n", "if", "m", "==", "nil", "{", "return", "\n", "}", "\n", "if", "pe", ".", "ep", ".", "SendMsg", "(", "m", ")", "!=", "nil", "{", "m", ".", "Free", "(", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}" ]
// Bottom sender.
[ "Bottom", "sender", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/protocol/bus/bus.go#L69-L80
142,414
nanomsg/mangos-v1
compat/compat.go
NewSocket
func NewSocket(d Domain, p Protocol) (*Socket, error) { var s Socket var err error s.proto = p s.dom = d switch p { case PUB: s.sock, err = pub.NewSocket() case SUB: s.sock, err = sub.NewSocket() case PUSH: s.sock, err = push.NewSocket() case PULL: s.sock, err = pull.NewSocket() case REQ: s.sock, err = req.NewSocket() case REP: s.sock, err = rep.NewSocket() case SURVEYOR: s.sock, err = surveyor.NewSocket() case RESPONDENT: s.sock, err = respondent.NewSocket() case PAIR: s.sock, err = pair.NewSocket() case BUS: s.sock, err = bus.NewSocket() default: err = mangos.ErrBadProto } if err != nil { return nil, err } switch d { case AF_SP: case AF_SP_RAW: err = s.sock.SetOption(mangos.OptionRaw, true) default: err = errBadDomain } if err != nil { s.sock.Close() return nil, err } // Compat mode sockets should timeout on send if we don't have any pipes if err = s.sock.SetOption(mangos.OptionWriteQLen, 0); err != nil { s.sock.Close() return nil, err } s.rto = -1 s.sto = -1 all.AddTransports(s.sock) return &s, nil }
go
func NewSocket(d Domain, p Protocol) (*Socket, error) { var s Socket var err error s.proto = p s.dom = d switch p { case PUB: s.sock, err = pub.NewSocket() case SUB: s.sock, err = sub.NewSocket() case PUSH: s.sock, err = push.NewSocket() case PULL: s.sock, err = pull.NewSocket() case REQ: s.sock, err = req.NewSocket() case REP: s.sock, err = rep.NewSocket() case SURVEYOR: s.sock, err = surveyor.NewSocket() case RESPONDENT: s.sock, err = respondent.NewSocket() case PAIR: s.sock, err = pair.NewSocket() case BUS: s.sock, err = bus.NewSocket() default: err = mangos.ErrBadProto } if err != nil { return nil, err } switch d { case AF_SP: case AF_SP_RAW: err = s.sock.SetOption(mangos.OptionRaw, true) default: err = errBadDomain } if err != nil { s.sock.Close() return nil, err } // Compat mode sockets should timeout on send if we don't have any pipes if err = s.sock.SetOption(mangos.OptionWriteQLen, 0); err != nil { s.sock.Close() return nil, err } s.rto = -1 s.sto = -1 all.AddTransports(s.sock) return &s, nil }
[ "func", "NewSocket", "(", "d", "Domain", ",", "p", "Protocol", ")", "(", "*", "Socket", ",", "error", ")", "{", "var", "s", "Socket", "\n", "var", "err", "error", "\n\n", "s", ".", "proto", "=", "p", "\n", "s", ".", "dom", "=", "d", "\n\n", "switch", "p", "{", "case", "PUB", ":", "s", ".", "sock", ",", "err", "=", "pub", ".", "NewSocket", "(", ")", "\n", "case", "SUB", ":", "s", ".", "sock", ",", "err", "=", "sub", ".", "NewSocket", "(", ")", "\n", "case", "PUSH", ":", "s", ".", "sock", ",", "err", "=", "push", ".", "NewSocket", "(", ")", "\n", "case", "PULL", ":", "s", ".", "sock", ",", "err", "=", "pull", ".", "NewSocket", "(", ")", "\n", "case", "REQ", ":", "s", ".", "sock", ",", "err", "=", "req", ".", "NewSocket", "(", ")", "\n", "case", "REP", ":", "s", ".", "sock", ",", "err", "=", "rep", ".", "NewSocket", "(", ")", "\n", "case", "SURVEYOR", ":", "s", ".", "sock", ",", "err", "=", "surveyor", ".", "NewSocket", "(", ")", "\n", "case", "RESPONDENT", ":", "s", ".", "sock", ",", "err", "=", "respondent", ".", "NewSocket", "(", ")", "\n", "case", "PAIR", ":", "s", ".", "sock", ",", "err", "=", "pair", ".", "NewSocket", "(", ")", "\n", "case", "BUS", ":", "s", ".", "sock", ",", "err", "=", "bus", ".", "NewSocket", "(", ")", "\n", "default", ":", "err", "=", "mangos", ".", "ErrBadProto", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "switch", "d", "{", "case", "AF_SP", ":", "case", "AF_SP_RAW", ":", "err", "=", "s", ".", "sock", ".", "SetOption", "(", "mangos", ".", "OptionRaw", ",", "true", ")", "\n", "default", ":", "err", "=", "errBadDomain", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "s", ".", "sock", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Compat mode sockets should timeout on send if we don't have any pipes", "if", "err", "=", "s", ".", "sock", ".", "SetOption", "(", "mangos", ".", "OptionWriteQLen", ",", "0", ")", ";", "err", "!=", "nil", "{", "s", ".", "sock", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "s", ".", "rto", "=", "-", "1", "\n", "s", ".", "sto", "=", "-", "1", "\n", "all", ".", "AddTransports", "(", "s", ".", "sock", ")", "\n", "return", "&", "s", ",", "nil", "\n", "}" ]
// NewSocket allocates a new Socket. The Socket is the handle used to // access the underlying library.
[ "NewSocket", "allocates", "a", "new", "Socket", ".", "The", "Socket", "is", "the", "handle", "used", "to", "access", "the", "underlying", "library", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L113-L172
142,415
nanomsg/mangos-v1
compat/compat.go
Close
func (s *Socket) Close() error { if s.sock != nil { s.sock.Close() } return nil }
go
func (s *Socket) Close() error { if s.sock != nil { s.sock.Close() } return nil }
[ "func", "(", "s", "*", "Socket", ")", "Close", "(", ")", "error", "{", "if", "s", ".", "sock", "!=", "nil", "{", "s", ".", "sock", ".", "Close", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Close shuts down the socket.
[ "Close", "shuts", "down", "the", "socket", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L175-L180
142,416
nanomsg/mangos-v1
compat/compat.go
Send
func (s *Socket) Send(b []byte, flags int) (int, error) { if flags != 0 { return -1, errNoFlag } m := mangos.NewMessage(len(b)) m.Body = append(m.Body, b...) // Legacy nanomsg uses the opposite semantic for negative and // zero values than mangos. A bit unfortunate. switch { case s.sto > 0: s.sock.SetOption(mangos.OptionSendDeadline, s.sto) case s.sto == 0: s.sock.SetOption(mangos.OptionSendDeadline, -1) case s.sto < 0: s.sock.SetOption(mangos.OptionSendDeadline, 0) } return len(b), s.sock.SendMsg(m) }
go
func (s *Socket) Send(b []byte, flags int) (int, error) { if flags != 0 { return -1, errNoFlag } m := mangos.NewMessage(len(b)) m.Body = append(m.Body, b...) // Legacy nanomsg uses the opposite semantic for negative and // zero values than mangos. A bit unfortunate. switch { case s.sto > 0: s.sock.SetOption(mangos.OptionSendDeadline, s.sto) case s.sto == 0: s.sock.SetOption(mangos.OptionSendDeadline, -1) case s.sto < 0: s.sock.SetOption(mangos.OptionSendDeadline, 0) } return len(b), s.sock.SendMsg(m) }
[ "func", "(", "s", "*", "Socket", ")", "Send", "(", "b", "[", "]", "byte", ",", "flags", "int", ")", "(", "int", ",", "error", ")", "{", "if", "flags", "!=", "0", "{", "return", "-", "1", ",", "errNoFlag", "\n", "}", "\n\n", "m", ":=", "mangos", ".", "NewMessage", "(", "len", "(", "b", ")", ")", "\n", "m", ".", "Body", "=", "append", "(", "m", ".", "Body", ",", "b", "...", ")", "\n\n", "// Legacy nanomsg uses the opposite semantic for negative and", "// zero values than mangos. A bit unfortunate.", "switch", "{", "case", "s", ".", "sto", ">", "0", ":", "s", ".", "sock", ".", "SetOption", "(", "mangos", ".", "OptionSendDeadline", ",", "s", ".", "sto", ")", "\n", "case", "s", ".", "sto", "==", "0", ":", "s", ".", "sock", ".", "SetOption", "(", "mangos", ".", "OptionSendDeadline", ",", "-", "1", ")", "\n", "case", "s", ".", "sto", "<", "0", ":", "s", ".", "sock", ".", "SetOption", "(", "mangos", ".", "OptionSendDeadline", ",", "0", ")", "\n", "}", "\n\n", "return", "len", "(", "b", ")", ",", "s", ".", "sock", ".", "SendMsg", "(", "m", ")", "\n", "}" ]
// Send sends a message. For AF_SP_RAW messages the header must be // included in the argument. At this time, no flags are supported.
[ "Send", "sends", "a", "message", ".", "For", "AF_SP_RAW", "messages", "the", "header", "must", "be", "included", "in", "the", "argument", ".", "At", "this", "time", "no", "flags", "are", "supported", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L247-L268
142,417
nanomsg/mangos-v1
compat/compat.go
Linger
func (s *Socket) Linger() (time.Duration, error) { var t time.Duration return t, errNotSup }
go
func (s *Socket) Linger() (time.Duration, error) { var t time.Duration return t, errNotSup }
[ "func", "(", "s", "*", "Socket", ")", "Linger", "(", ")", "(", "time", ".", "Duration", ",", "error", ")", "{", "var", "t", "time", ".", "Duration", "\n", "return", "t", ",", "errNotSup", "\n", "}" ]
// Linger should set the TCP linger time, but at present is not supported.
[ "Linger", "should", "set", "the", "TCP", "linger", "time", "but", "at", "present", "is", "not", "supported", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L303-L306
142,418
nanomsg/mangos-v1
compat/compat.go
NewBusSocket
func NewBusSocket() (*BusSocket, error) { s, err := NewSocket(AF_SP, BUS) return &BusSocket{s}, err }
go
func NewBusSocket() (*BusSocket, error) { s, err := NewSocket(AF_SP, BUS) return &BusSocket{s}, err }
[ "func", "NewBusSocket", "(", ")", "(", "*", "BusSocket", ",", "error", ")", "{", "s", ",", "err", ":=", "NewSocket", "(", "AF_SP", ",", "BUS", ")", "\n", "return", "&", "BusSocket", "{", "s", "}", ",", "err", "\n", "}" ]
// NewBusSocket creates a BUS socket.
[ "NewBusSocket", "creates", "a", "BUS", "socket", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L352-L355
142,419
nanomsg/mangos-v1
compat/compat.go
NewPairSocket
func NewPairSocket() (*PairSocket, error) { s, err := NewSocket(AF_SP, PAIR) return &PairSocket{s}, err }
go
func NewPairSocket() (*PairSocket, error) { s, err := NewSocket(AF_SP, PAIR) return &PairSocket{s}, err }
[ "func", "NewPairSocket", "(", ")", "(", "*", "PairSocket", ",", "error", ")", "{", "s", ",", "err", ":=", "NewSocket", "(", "AF_SP", ",", "PAIR", ")", "\n", "return", "&", "PairSocket", "{", "s", "}", ",", "err", "\n", "}" ]
// NewPairSocket creates a PAIR socket.
[ "NewPairSocket", "creates", "a", "PAIR", "socket", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L363-L366
142,420
nanomsg/mangos-v1
compat/compat.go
NewPubSocket
func NewPubSocket() (*PubSocket, error) { s, err := NewSocket(AF_SP, PUB) return &PubSocket{s}, err }
go
func NewPubSocket() (*PubSocket, error) { s, err := NewSocket(AF_SP, PUB) return &PubSocket{s}, err }
[ "func", "NewPubSocket", "(", ")", "(", "*", "PubSocket", ",", "error", ")", "{", "s", ",", "err", ":=", "NewSocket", "(", "AF_SP", ",", "PUB", ")", "\n", "return", "&", "PubSocket", "{", "s", "}", ",", "err", "\n", "}" ]
// NewPubSocket creates a PUB socket.
[ "NewPubSocket", "creates", "a", "PUB", "socket", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L374-L377
142,421
nanomsg/mangos-v1
compat/compat.go
NewPullSocket
func NewPullSocket() (*PullSocket, error) { s, err := NewSocket(AF_SP, PULL) return &PullSocket{s}, err }
go
func NewPullSocket() (*PullSocket, error) { s, err := NewSocket(AF_SP, PULL) return &PullSocket{s}, err }
[ "func", "NewPullSocket", "(", ")", "(", "*", "PullSocket", ",", "error", ")", "{", "s", ",", "err", ":=", "NewSocket", "(", "AF_SP", ",", "PULL", ")", "\n", "return", "&", "PullSocket", "{", "s", "}", ",", "err", "\n", "}" ]
// NewPullSocket creates a PULL socket.
[ "NewPullSocket", "creates", "a", "PULL", "socket", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L385-L388
142,422
nanomsg/mangos-v1
compat/compat.go
NewPushSocket
func NewPushSocket() (*PushSocket, error) { s, err := NewSocket(AF_SP, PUSH) return &PushSocket{s}, err }
go
func NewPushSocket() (*PushSocket, error) { s, err := NewSocket(AF_SP, PUSH) return &PushSocket{s}, err }
[ "func", "NewPushSocket", "(", ")", "(", "*", "PushSocket", ",", "error", ")", "{", "s", ",", "err", ":=", "NewSocket", "(", "AF_SP", ",", "PUSH", ")", "\n", "return", "&", "PushSocket", "{", "s", "}", ",", "err", "\n", "}" ]
// NewPushSocket creates a PUSH socket.
[ "NewPushSocket", "creates", "a", "PUSH", "socket", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L396-L399
142,423
nanomsg/mangos-v1
compat/compat.go
NewRepSocket
func NewRepSocket() (*RepSocket, error) { s, err := NewSocket(AF_SP, REP) return &RepSocket{s}, err }
go
func NewRepSocket() (*RepSocket, error) { s, err := NewSocket(AF_SP, REP) return &RepSocket{s}, err }
[ "func", "NewRepSocket", "(", ")", "(", "*", "RepSocket", ",", "error", ")", "{", "s", ",", "err", ":=", "NewSocket", "(", "AF_SP", ",", "REP", ")", "\n", "return", "&", "RepSocket", "{", "s", "}", ",", "err", "\n", "}" ]
// NewRepSocket creates a REP socket.
[ "NewRepSocket", "creates", "a", "REP", "socket", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L407-L410
142,424
nanomsg/mangos-v1
compat/compat.go
NewReqSocket
func NewReqSocket() (*ReqSocket, error) { s, err := NewSocket(AF_SP, REQ) return &ReqSocket{s}, err }
go
func NewReqSocket() (*ReqSocket, error) { s, err := NewSocket(AF_SP, REQ) return &ReqSocket{s}, err }
[ "func", "NewReqSocket", "(", ")", "(", "*", "ReqSocket", ",", "error", ")", "{", "s", ",", "err", ":=", "NewSocket", "(", "AF_SP", ",", "REQ", ")", "\n", "return", "&", "ReqSocket", "{", "s", "}", ",", "err", "\n", "}" ]
// NewReqSocket creates a REQ socket.
[ "NewReqSocket", "creates", "a", "REQ", "socket", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L418-L421
142,425
nanomsg/mangos-v1
compat/compat.go
NewRespondentSocket
func NewRespondentSocket() (*RespondentSocket, error) { s, err := NewSocket(AF_SP, RESPONDENT) return &RespondentSocket{s}, err }
go
func NewRespondentSocket() (*RespondentSocket, error) { s, err := NewSocket(AF_SP, RESPONDENT) return &RespondentSocket{s}, err }
[ "func", "NewRespondentSocket", "(", ")", "(", "*", "RespondentSocket", ",", "error", ")", "{", "s", ",", "err", ":=", "NewSocket", "(", "AF_SP", ",", "RESPONDENT", ")", "\n", "return", "&", "RespondentSocket", "{", "s", "}", ",", "err", "\n", "}" ]
// NewRespondentSocket creates a RESPONDENT socket.
[ "NewRespondentSocket", "creates", "a", "RESPONDENT", "socket", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L429-L432
142,426
nanomsg/mangos-v1
compat/compat.go
Subscribe
func (s *SubSocket) Subscribe(topic string) error { return s.sock.SetOption(mangos.OptionSubscribe, topic) }
go
func (s *SubSocket) Subscribe(topic string) error { return s.sock.SetOption(mangos.OptionSubscribe, topic) }
[ "func", "(", "s", "*", "SubSocket", ")", "Subscribe", "(", "topic", "string", ")", "error", "{", "return", "s", ".", "sock", ".", "SetOption", "(", "mangos", ".", "OptionSubscribe", ",", "topic", ")", "\n", "}" ]
// Subscribe registers interest in a topic.
[ "Subscribe", "registers", "interest", "in", "a", "topic", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L440-L442
142,427
nanomsg/mangos-v1
compat/compat.go
Unsubscribe
func (s *SubSocket) Unsubscribe(topic string) error { return s.sock.SetOption(mangos.OptionUnsubscribe, topic) }
go
func (s *SubSocket) Unsubscribe(topic string) error { return s.sock.SetOption(mangos.OptionUnsubscribe, topic) }
[ "func", "(", "s", "*", "SubSocket", ")", "Unsubscribe", "(", "topic", "string", ")", "error", "{", "return", "s", ".", "sock", ".", "SetOption", "(", "mangos", ".", "OptionUnsubscribe", ",", "topic", ")", "\n", "}" ]
// Unsubscribe unregisters interest in a topic.
[ "Unsubscribe", "unregisters", "interest", "in", "a", "topic", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L445-L447
142,428
nanomsg/mangos-v1
compat/compat.go
NewSubSocket
func NewSubSocket() (*SubSocket, error) { s, err := NewSocket(AF_SP, SUB) return &SubSocket{s}, err }
go
func NewSubSocket() (*SubSocket, error) { s, err := NewSocket(AF_SP, SUB) return &SubSocket{s}, err }
[ "func", "NewSubSocket", "(", ")", "(", "*", "SubSocket", ",", "error", ")", "{", "s", ",", "err", ":=", "NewSocket", "(", "AF_SP", ",", "SUB", ")", "\n", "return", "&", "SubSocket", "{", "s", "}", ",", "err", "\n", "}" ]
// NewSubSocket creates a SUB socket.
[ "NewSubSocket", "creates", "a", "SUB", "socket", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L450-L453
142,429
nanomsg/mangos-v1
compat/compat.go
Deadline
func (s *SurveyorSocket) Deadline() (time.Duration, error) { var d time.Duration v, err := s.sock.GetOption(mangos.OptionSurveyTime) if err == nil { d = v.(time.Duration) } return d, err }
go
func (s *SurveyorSocket) Deadline() (time.Duration, error) { var d time.Duration v, err := s.sock.GetOption(mangos.OptionSurveyTime) if err == nil { d = v.(time.Duration) } return d, err }
[ "func", "(", "s", "*", "SurveyorSocket", ")", "Deadline", "(", ")", "(", "time", ".", "Duration", ",", "error", ")", "{", "var", "d", "time", ".", "Duration", "\n", "v", ",", "err", ":=", "s", ".", "sock", ".", "GetOption", "(", "mangos", ".", "OptionSurveyTime", ")", "\n", "if", "err", "==", "nil", "{", "d", "=", "v", ".", "(", "time", ".", "Duration", ")", "\n", "}", "\n", "return", "d", ",", "err", "\n", "}" ]
// Deadline returns the survey deadline on the socket. After this time, // responses from a survey will be discarded.
[ "Deadline", "returns", "the", "survey", "deadline", "on", "the", "socket", ".", "After", "this", "time", "responses", "from", "a", "survey", "will", "be", "discarded", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L462-L469
142,430
nanomsg/mangos-v1
compat/compat.go
SetDeadline
func (s *SurveyorSocket) SetDeadline(d time.Duration) error { return s.sock.SetOption(mangos.OptionSurveyTime, d) }
go
func (s *SurveyorSocket) SetDeadline(d time.Duration) error { return s.sock.SetOption(mangos.OptionSurveyTime, d) }
[ "func", "(", "s", "*", "SurveyorSocket", ")", "SetDeadline", "(", "d", "time", ".", "Duration", ")", "error", "{", "return", "s", ".", "sock", ".", "SetOption", "(", "mangos", ".", "OptionSurveyTime", ",", "d", ")", "\n", "}" ]
// SetDeadline sets the survey deadline on the socket. After this time, // responses from a survey will be discarded.
[ "SetDeadline", "sets", "the", "survey", "deadline", "on", "the", "socket", ".", "After", "this", "time", "responses", "from", "a", "survey", "will", "be", "discarded", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L473-L475
142,431
nanomsg/mangos-v1
compat/compat.go
NewSurveyorSocket
func NewSurveyorSocket() (*SurveyorSocket, error) { s, err := NewSocket(AF_SP, SURVEYOR) return &SurveyorSocket{s}, err }
go
func NewSurveyorSocket() (*SurveyorSocket, error) { s, err := NewSocket(AF_SP, SURVEYOR) return &SurveyorSocket{s}, err }
[ "func", "NewSurveyorSocket", "(", ")", "(", "*", "SurveyorSocket", ",", "error", ")", "{", "s", ",", "err", ":=", "NewSocket", "(", "AF_SP", ",", "SURVEYOR", ")", "\n", "return", "&", "SurveyorSocket", "{", "s", "}", ",", "err", "\n", "}" ]
// NewSurveyorSocket creates a SURVEYOR socket.
[ "NewSurveyorSocket", "creates", "a", "SURVEYOR", "socket", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L478-L481
142,432
nanomsg/mangos-v1
transport/ipc/ipc_unix.go
Dial
func (d *dialer) Dial() (mangos.Pipe, error) { conn, err := net.DialUnix("unix", nil, d.addr) if err != nil { return nil, err } return mangos.NewConnPipeIPC(conn, d.sock) }
go
func (d *dialer) Dial() (mangos.Pipe, error) { conn, err := net.DialUnix("unix", nil, d.addr) if err != nil { return nil, err } return mangos.NewConnPipeIPC(conn, d.sock) }
[ "func", "(", "d", "*", "dialer", ")", "Dial", "(", ")", "(", "mangos", ".", "Pipe", ",", "error", ")", "{", "conn", ",", "err", ":=", "net", ".", "DialUnix", "(", "\"", "\"", ",", "nil", ",", "d", ".", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "mangos", ".", "NewConnPipeIPC", "(", "conn", ",", "d", ".", "sock", ")", "\n", "}" ]
// Dial implements the PipeDialer Dial method
[ "Dial", "implements", "the", "PipeDialer", "Dial", "method" ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/transport/ipc/ipc_unix.go#L53-L60
142,433
nanomsg/mangos-v1
core.go
SendChannel
func (sock *socket) SendChannel() <-chan *Message { sock.Lock() defer sock.Unlock() return sock.uwq }
go
func (sock *socket) SendChannel() <-chan *Message { sock.Lock() defer sock.Unlock() return sock.uwq }
[ "func", "(", "sock", "*", "socket", ")", "SendChannel", "(", ")", "<-", "chan", "*", "Message", "{", "sock", ".", "Lock", "(", ")", "\n", "defer", "sock", ".", "Unlock", "(", ")", "\n", "return", "sock", ".", "uwq", "\n", "}" ]
// Implementation of ProtocolSocket bits on socket. This is the middle // API presented to Protocol implementations.
[ "Implementation", "of", "ProtocolSocket", "bits", "on", "socket", ".", "This", "is", "the", "middle", "API", "presented", "to", "Protocol", "implementations", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/core.go#L149-L153
142,434
nanomsg/mangos-v1
core.go
Close
func (sock *socket) Close() error { fin := time.Now().Add(sock.linger) DrainChannel(sock.uwq, fin) sock.Lock() if sock.closing { sock.Unlock() return ErrClosed } sock.closing = true close(sock.closeq) for _, l := range sock.listeners { l.l.Close() } pipes := sock.pipes sock.pipes = nil sock.Unlock() // A second drain, just to be sure. (We could have had device or // forwarded messages arrive since the last one.) DrainChannel(sock.uwq, fin) // And tell the protocol to shutdown and drain its pipes too. sock.proto.Shutdown(fin) for p := range pipes { p.Close() } return nil }
go
func (sock *socket) Close() error { fin := time.Now().Add(sock.linger) DrainChannel(sock.uwq, fin) sock.Lock() if sock.closing { sock.Unlock() return ErrClosed } sock.closing = true close(sock.closeq) for _, l := range sock.listeners { l.l.Close() } pipes := sock.pipes sock.pipes = nil sock.Unlock() // A second drain, just to be sure. (We could have had device or // forwarded messages arrive since the last one.) DrainChannel(sock.uwq, fin) // And tell the protocol to shutdown and drain its pipes too. sock.proto.Shutdown(fin) for p := range pipes { p.Close() } return nil }
[ "func", "(", "sock", "*", "socket", ")", "Close", "(", ")", "error", "{", "fin", ":=", "time", ".", "Now", "(", ")", ".", "Add", "(", "sock", ".", "linger", ")", "\n\n", "DrainChannel", "(", "sock", ".", "uwq", ",", "fin", ")", "\n\n", "sock", ".", "Lock", "(", ")", "\n", "if", "sock", ".", "closing", "{", "sock", ".", "Unlock", "(", ")", "\n", "return", "ErrClosed", "\n", "}", "\n", "sock", ".", "closing", "=", "true", "\n", "close", "(", "sock", ".", "closeq", ")", "\n\n", "for", "_", ",", "l", ":=", "range", "sock", ".", "listeners", "{", "l", ".", "l", ".", "Close", "(", ")", "\n", "}", "\n", "pipes", ":=", "sock", ".", "pipes", "\n", "sock", ".", "pipes", "=", "nil", "\n", "sock", ".", "Unlock", "(", ")", "\n\n", "// A second drain, just to be sure. (We could have had device or", "// forwarded messages arrive since the last one.)", "DrainChannel", "(", "sock", ".", "uwq", ",", "fin", ")", "\n\n", "// And tell the protocol to shutdown and drain its pipes too.", "sock", ".", "proto", ".", "Shutdown", "(", "fin", ")", "\n\n", "for", "p", ":=", "range", "pipes", "{", "p", ".", "Close", "(", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// // Implementation of Socket bits on socket. This is the upper API // presented to applications. //
[ "Implementation", "of", "Socket", "bits", "on", "socket", ".", "This", "is", "the", "upper", "API", "presented", "to", "applications", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/core.go#L186-L219
142,435
nanomsg/mangos-v1
core.go
String
func (sock *socket) String() string { return fmt.Sprintf("SOCKET[%s](%p)", sock.proto.Name(), sock) }
go
func (sock *socket) String() string { return fmt.Sprintf("SOCKET[%s](%p)", sock.proto.Name(), sock) }
[ "func", "(", "sock", "*", "socket", ")", "String", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "sock", ".", "proto", ".", "Name", "(", ")", ",", "sock", ")", "\n", "}" ]
// String just emits a very high level debug. This avoids // triggering race conditions from trying to print %v without // holding locks on structure members.
[ "String", "just", "emits", "a", "very", "high", "level", "debug", ".", "This", "avoids", "triggering", "race", "conditions", "from", "trying", "to", "print", "%v", "without", "holding", "locks", "on", "structure", "members", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/core.go#L280-L282
142,436
nanomsg/mangos-v1
core.go
dialer
func (d *dialer) dialer() { rtime := d.sock.reconntime rtmax := d.sock.reconnmax for { p, err := d.d.Dial() if err == nil { // reset retry time rtime = d.sock.reconntime d.sock.Lock() if d.closed { d.sock.Unlock() p.Close() return } d.sock.Unlock() if cp := d.sock.addPipe(p, d, nil); cp != nil { select { case <-d.sock.closeq: // parent socket closed case <-cp.closeq: // disconnect event case <-d.closeq: // dialer closed } } } // we're redialing here select { case <-d.closeq: // dialer closed if p != nil { p.Close() } return case <-d.sock.closeq: // exit if parent socket closed if p != nil { p.Close() } return case <-time.After(rtime): if rtmax > 0 { rtime *= 2 if rtime > rtmax { rtime = rtmax } } continue } } }
go
func (d *dialer) dialer() { rtime := d.sock.reconntime rtmax := d.sock.reconnmax for { p, err := d.d.Dial() if err == nil { // reset retry time rtime = d.sock.reconntime d.sock.Lock() if d.closed { d.sock.Unlock() p.Close() return } d.sock.Unlock() if cp := d.sock.addPipe(p, d, nil); cp != nil { select { case <-d.sock.closeq: // parent socket closed case <-cp.closeq: // disconnect event case <-d.closeq: // dialer closed } } } // we're redialing here select { case <-d.closeq: // dialer closed if p != nil { p.Close() } return case <-d.sock.closeq: // exit if parent socket closed if p != nil { p.Close() } return case <-time.After(rtime): if rtmax > 0 { rtime *= 2 if rtime > rtmax { rtime = rtmax } } continue } } }
[ "func", "(", "d", "*", "dialer", ")", "dialer", "(", ")", "{", "rtime", ":=", "d", ".", "sock", ".", "reconntime", "\n", "rtmax", ":=", "d", ".", "sock", ".", "reconnmax", "\n", "for", "{", "p", ",", "err", ":=", "d", ".", "d", ".", "Dial", "(", ")", "\n", "if", "err", "==", "nil", "{", "// reset retry time", "rtime", "=", "d", ".", "sock", ".", "reconntime", "\n", "d", ".", "sock", ".", "Lock", "(", ")", "\n", "if", "d", ".", "closed", "{", "d", ".", "sock", ".", "Unlock", "(", ")", "\n", "p", ".", "Close", "(", ")", "\n", "return", "\n", "}", "\n", "d", ".", "sock", ".", "Unlock", "(", ")", "\n", "if", "cp", ":=", "d", ".", "sock", ".", "addPipe", "(", "p", ",", "d", ",", "nil", ")", ";", "cp", "!=", "nil", "{", "select", "{", "case", "<-", "d", ".", "sock", ".", "closeq", ":", "// parent socket closed", "case", "<-", "cp", ".", "closeq", ":", "// disconnect event", "case", "<-", "d", ".", "closeq", ":", "// dialer closed", "}", "\n", "}", "\n", "}", "\n\n", "// we're redialing here", "select", "{", "case", "<-", "d", ".", "closeq", ":", "// dialer closed", "if", "p", "!=", "nil", "{", "p", ".", "Close", "(", ")", "\n", "}", "\n", "return", "\n", "case", "<-", "d", ".", "sock", ".", "closeq", ":", "// exit if parent socket closed", "if", "p", "!=", "nil", "{", "p", ".", "Close", "(", ")", "\n", "}", "\n", "return", "\n", "case", "<-", "time", ".", "After", "(", "rtime", ")", ":", "if", "rtmax", ">", "0", "{", "rtime", "*=", "2", "\n", "if", "rtime", ">", "rtmax", "{", "rtime", "=", "rtmax", "\n", "}", "\n", "}", "\n", "continue", "\n", "}", "\n", "}", "\n", "}" ]
// dialer is used to dial or redial from a goroutine.
[ "dialer", "is", "used", "to", "dial", "or", "redial", "from", "a", "goroutine", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/core.go#L614-L660
142,437
nanomsg/mangos-v1
core.go
serve
func (l *listener) serve() { for { select { case <-l.sock.closeq: return default: } // If the underlying PipeListener is closed, or not // listening, we expect to return back with an error. if pipe, err := l.l.Accept(); err == nil { l.sock.addPipe(pipe, nil, l) } else if err == ErrClosed { return } } }
go
func (l *listener) serve() { for { select { case <-l.sock.closeq: return default: } // If the underlying PipeListener is closed, or not // listening, we expect to return back with an error. if pipe, err := l.l.Accept(); err == nil { l.sock.addPipe(pipe, nil, l) } else if err == ErrClosed { return } } }
[ "func", "(", "l", "*", "listener", ")", "serve", "(", ")", "{", "for", "{", "select", "{", "case", "<-", "l", ".", "sock", ".", "closeq", ":", "return", "\n", "default", ":", "}", "\n\n", "// If the underlying PipeListener is closed, or not", "// listening, we expect to return back with an error.", "if", "pipe", ",", "err", ":=", "l", ".", "l", ".", "Accept", "(", ")", ";", "err", "==", "nil", "{", "l", ".", "sock", ".", "addPipe", "(", "pipe", ",", "nil", ",", "l", ")", "\n", "}", "else", "if", "err", "==", "ErrClosed", "{", "return", "\n", "}", "\n", "}", "\n", "}" ]
// serve spins in a loop, calling the accepter's Accept routine.
[ "serve", "spins", "in", "a", "loop", "calling", "the", "accepter", "s", "Accept", "routine", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/core.go#L677-L693
142,438
nanomsg/mangos-v1
protocol/pub/pub.go
sender
func (p *pub) sender() { defer p.w.Done() cq := p.sock.CloseChannel() sq := p.sock.SendChannel() for { select { case <-cq: return case m := <-sq: if m == nil { sq = p.sock.SendChannel() continue } p.Lock() for _, peer := range p.eps { m := m.Dup() select { case peer.q <- m: default: m.Free() } } p.Unlock() m.Free() } } }
go
func (p *pub) sender() { defer p.w.Done() cq := p.sock.CloseChannel() sq := p.sock.SendChannel() for { select { case <-cq: return case m := <-sq: if m == nil { sq = p.sock.SendChannel() continue } p.Lock() for _, peer := range p.eps { m := m.Dup() select { case peer.q <- m: default: m.Free() } } p.Unlock() m.Free() } } }
[ "func", "(", "p", "*", "pub", ")", "sender", "(", ")", "{", "defer", "p", ".", "w", ".", "Done", "(", ")", "\n\n", "cq", ":=", "p", ".", "sock", ".", "CloseChannel", "(", ")", "\n", "sq", ":=", "p", ".", "sock", ".", "SendChannel", "(", ")", "\n\n", "for", "{", "select", "{", "case", "<-", "cq", ":", "return", "\n\n", "case", "m", ":=", "<-", "sq", ":", "if", "m", "==", "nil", "{", "sq", "=", "p", ".", "sock", ".", "SendChannel", "(", ")", "\n", "continue", "\n", "}", "\n\n", "p", ".", "Lock", "(", ")", "\n", "for", "_", ",", "peer", ":=", "range", "p", ".", "eps", "{", "m", ":=", "m", ".", "Dup", "(", ")", "\n", "select", "{", "case", "peer", ".", "q", "<-", "m", ":", "default", ":", "m", ".", "Free", "(", ")", "\n", "}", "\n", "}", "\n", "p", ".", "Unlock", "(", ")", "\n", "m", ".", "Free", "(", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Top sender.
[ "Top", "sender", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/protocol/pub/pub.go#L85-L115
142,439
nanomsg/mangos-v1
message.go
Free
func (m *Message) Free() { if v := atomic.AddInt32(&m.refcnt, -1); v > 0 { return } for i := range messageCache { if m.bsize == messageCache[i].maxbody { messageCache[i].pool.Put(m) return } } }
go
func (m *Message) Free() { if v := atomic.AddInt32(&m.refcnt, -1); v > 0 { return } for i := range messageCache { if m.bsize == messageCache[i].maxbody { messageCache[i].pool.Put(m) return } } }
[ "func", "(", "m", "*", "Message", ")", "Free", "(", ")", "{", "if", "v", ":=", "atomic", ".", "AddInt32", "(", "&", "m", ".", "refcnt", ",", "-", "1", ")", ";", "v", ">", "0", "{", "return", "\n", "}", "\n", "for", "i", ":=", "range", "messageCache", "{", "if", "m", ".", "bsize", "==", "messageCache", "[", "i", "]", ".", "maxbody", "{", "messageCache", "[", "i", "]", ".", "pool", ".", "Put", "(", "m", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}" ]
// Free decrements the reference count on a message, and releases its // resources if no further references remain. While this is not // strictly necessary thanks to GC, doing so allows for the resources to // be recycled without engaging GC. This can have rather substantial // benefits for performance.
[ "Free", "decrements", "the", "reference", "count", "on", "a", "message", "and", "releases", "its", "resources", "if", "no", "further", "references", "remain", ".", "While", "this", "is", "not", "strictly", "necessary", "thanks", "to", "GC", "doing", "so", "allows", "for", "the", "resources", "to", "be", "recycled", "without", "engaging", "GC", ".", "This", "can", "have", "rather", "substantial", "benefits", "for", "performance", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/message.go#L115-L125
142,440
nanomsg/mangos-v1
message.go
Expired
func (m *Message) Expired() bool { if m.expire.IsZero() { return false } if m.expire.After(time.Now()) { return false } return true }
go
func (m *Message) Expired() bool { if m.expire.IsZero() { return false } if m.expire.After(time.Now()) { return false } return true }
[ "func", "(", "m", "*", "Message", ")", "Expired", "(", ")", "bool", "{", "if", "m", ".", "expire", ".", "IsZero", "(", ")", "{", "return", "false", "\n", "}", "\n", "if", "m", ".", "expire", ".", "After", "(", "time", ".", "Now", "(", ")", ")", "{", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// Expired returns true if the message has "expired". This is used by // transport implementations to discard messages that have been // stuck in the write queue for too long, and should be discarded rather // than delivered across the transport. This is only used on the TX // path, there is no sense of "expiration" on the RX path.
[ "Expired", "returns", "true", "if", "the", "message", "has", "expired", ".", "This", "is", "used", "by", "transport", "implementations", "to", "discard", "messages", "that", "have", "been", "stuck", "in", "the", "write", "queue", "for", "too", "long", "and", "should", "be", "discarded", "rather", "than", "delivered", "across", "the", "transport", ".", "This", "is", "only", "used", "on", "the", "TX", "path", "there", "is", "no", "sense", "of", "expiration", "on", "the", "RX", "path", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/message.go#L144-L152
142,441
nanomsg/mangos-v1
message.go
NewMessage
func NewMessage(sz int) *Message { var m *Message for i := range messageCache { if sz < messageCache[i].maxbody { m = messageCache[i].pool.Get().(*Message) break } } if m == nil { m = newMsg(sz) } m.refcnt = 1 m.Body = m.bbuf m.Header = m.hbuf return m }
go
func NewMessage(sz int) *Message { var m *Message for i := range messageCache { if sz < messageCache[i].maxbody { m = messageCache[i].pool.Get().(*Message) break } } if m == nil { m = newMsg(sz) } m.refcnt = 1 m.Body = m.bbuf m.Header = m.hbuf return m }
[ "func", "NewMessage", "(", "sz", "int", ")", "*", "Message", "{", "var", "m", "*", "Message", "\n", "for", "i", ":=", "range", "messageCache", "{", "if", "sz", "<", "messageCache", "[", "i", "]", ".", "maxbody", "{", "m", "=", "messageCache", "[", "i", "]", ".", "pool", ".", "Get", "(", ")", ".", "(", "*", "Message", ")", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "m", "==", "nil", "{", "m", "=", "newMsg", "(", "sz", ")", "\n", "}", "\n\n", "m", ".", "refcnt", "=", "1", "\n", "m", ".", "Body", "=", "m", ".", "bbuf", "\n", "m", ".", "Header", "=", "m", ".", "hbuf", "\n", "return", "m", "\n", "}" ]
// NewMessage is the supported way to obtain a new Message. This makes // use of a "cache" which greatly reduces the load on the garbage collector.
[ "NewMessage", "is", "the", "supported", "way", "to", "obtain", "a", "new", "Message", ".", "This", "makes", "use", "of", "a", "cache", "which", "greatly", "reduces", "the", "load", "on", "the", "garbage", "collector", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/message.go#L156-L172
142,442
nanomsg/mangos-v1
examples/websocket/reqclient.go
reqClient
func reqClient(port int) { sock, e := req.NewSocket() if e != nil { die("cannot make req socket: %v", e) } sock.AddTransport(ws.NewTransport()) url := fmt.Sprintf("ws://127.0.0.1:%d/req", port) if e = sock.Dial(url); e != nil { die("cannot dial req url: %v", e) } // Time for TCP connection set up time.Sleep(time.Millisecond * 10) if e = sock.Send([]byte("Hello")); e != nil { die("Cannot send req: %v", e) } if m, e := sock.Recv(); e != nil { die("Cannot recv reply: %v", e) } else { fmt.Printf("%s\n", string(m)) } }
go
func reqClient(port int) { sock, e := req.NewSocket() if e != nil { die("cannot make req socket: %v", e) } sock.AddTransport(ws.NewTransport()) url := fmt.Sprintf("ws://127.0.0.1:%d/req", port) if e = sock.Dial(url); e != nil { die("cannot dial req url: %v", e) } // Time for TCP connection set up time.Sleep(time.Millisecond * 10) if e = sock.Send([]byte("Hello")); e != nil { die("Cannot send req: %v", e) } if m, e := sock.Recv(); e != nil { die("Cannot recv reply: %v", e) } else { fmt.Printf("%s\n", string(m)) } }
[ "func", "reqClient", "(", "port", "int", ")", "{", "sock", ",", "e", ":=", "req", ".", "NewSocket", "(", ")", "\n", "if", "e", "!=", "nil", "{", "die", "(", "\"", "\"", ",", "e", ")", "\n", "}", "\n", "sock", ".", "AddTransport", "(", "ws", ".", "NewTransport", "(", ")", ")", "\n", "url", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "port", ")", "\n", "if", "e", "=", "sock", ".", "Dial", "(", "url", ")", ";", "e", "!=", "nil", "{", "die", "(", "\"", "\"", ",", "e", ")", "\n", "}", "\n", "// Time for TCP connection set up", "time", ".", "Sleep", "(", "time", ".", "Millisecond", "*", "10", ")", "\n", "if", "e", "=", "sock", ".", "Send", "(", "[", "]", "byte", "(", "\"", "\"", ")", ")", ";", "e", "!=", "nil", "{", "die", "(", "\"", "\"", ",", "e", ")", "\n", "}", "\n", "if", "m", ",", "e", ":=", "sock", ".", "Recv", "(", ")", ";", "e", "!=", "nil", "{", "die", "(", "\"", "\"", ",", "e", ")", "\n", "}", "else", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "string", "(", "m", ")", ")", "\n", "}", "\n", "}" ]
// reqClient implements the client for REQ.
[ "reqClient", "implements", "the", "client", "for", "REQ", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/examples/websocket/reqclient.go#L26-L46
142,443
nanomsg/mangos-v1
waiter.go
WaitAbsTimeout
func (cv *CondTimed) WaitAbsTimeout(when time.Time) bool { now := time.Now() if when.After(now) { return cv.WaitRelTimeout(when.Sub(now)) } return cv.WaitRelTimeout(time.Duration(0)) }
go
func (cv *CondTimed) WaitAbsTimeout(when time.Time) bool { now := time.Now() if when.After(now) { return cv.WaitRelTimeout(when.Sub(now)) } return cv.WaitRelTimeout(time.Duration(0)) }
[ "func", "(", "cv", "*", "CondTimed", ")", "WaitAbsTimeout", "(", "when", "time", ".", "Time", ")", "bool", "{", "now", ":=", "time", ".", "Now", "(", ")", "\n", "if", "when", ".", "After", "(", "now", ")", "{", "return", "cv", ".", "WaitRelTimeout", "(", "when", ".", "Sub", "(", "now", ")", ")", "\n", "}", "\n", "return", "cv", ".", "WaitRelTimeout", "(", "time", ".", "Duration", "(", "0", ")", ")", "\n", "}" ]
// WaitAbsTimeout is like WaitRelTimeout, but expires on an absolute time // instead of a relative one.
[ "WaitAbsTimeout", "is", "like", "WaitRelTimeout", "but", "expires", "on", "an", "absolute", "time", "instead", "of", "a", "relative", "one", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/waiter.go#L43-L49
142,444
nanomsg/mangos-v1
waiter.go
Wait
func (w *Waiter) Wait() { w.Lock() for w.cnt != 0 { w.cv.Wait() } w.Unlock() }
go
func (w *Waiter) Wait() { w.Lock() for w.cnt != 0 { w.cv.Wait() } w.Unlock() }
[ "func", "(", "w", "*", "Waiter", ")", "Wait", "(", ")", "{", "w", ".", "Lock", "(", ")", "\n", "for", "w", ".", "cnt", "!=", "0", "{", "w", ".", "cv", ".", "Wait", "(", ")", "\n", "}", "\n", "w", ".", "Unlock", "(", ")", "\n", "}" ]
// Wait waits without a timeout. It only completes when the count drops // to zero.
[ "Wait", "waits", "without", "a", "timeout", ".", "It", "only", "completes", "when", "the", "count", "drops", "to", "zero", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/waiter.go#L91-L97
142,445
nanomsg/mangos-v1
waiter.go
WaitRelTimeout
func (w *Waiter) WaitRelTimeout(d time.Duration) bool { w.Lock() for w.cnt != 0 { if !w.cv.WaitRelTimeout(d) { break } } done := w.cnt == 0 w.Unlock() return done }
go
func (w *Waiter) WaitRelTimeout(d time.Duration) bool { w.Lock() for w.cnt != 0 { if !w.cv.WaitRelTimeout(d) { break } } done := w.cnt == 0 w.Unlock() return done }
[ "func", "(", "w", "*", "Waiter", ")", "WaitRelTimeout", "(", "d", "time", ".", "Duration", ")", "bool", "{", "w", ".", "Lock", "(", ")", "\n", "for", "w", ".", "cnt", "!=", "0", "{", "if", "!", "w", ".", "cv", ".", "WaitRelTimeout", "(", "d", ")", "{", "break", "\n", "}", "\n", "}", "\n", "done", ":=", "w", ".", "cnt", "==", "0", "\n", "w", ".", "Unlock", "(", ")", "\n", "return", "done", "\n", "}" ]
// WaitRelTimeout waits until either the count drops to zero, or the timeout // expires. It returns true if the count is zero, false otherwise.
[ "WaitRelTimeout", "waits", "until", "either", "the", "count", "drops", "to", "zero", "or", "the", "timeout", "expires", ".", "It", "returns", "true", "if", "the", "count", "is", "zero", "false", "otherwise", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/waiter.go#L101-L111
142,446
nanomsg/mangos-v1
waiter.go
WaitAbsTimeout
func (w *Waiter) WaitAbsTimeout(t time.Time) bool { w.Lock() for w.cnt != 0 { if !w.cv.WaitAbsTimeout(t) { break } } done := w.cnt == 0 w.Unlock() return done }
go
func (w *Waiter) WaitAbsTimeout(t time.Time) bool { w.Lock() for w.cnt != 0 { if !w.cv.WaitAbsTimeout(t) { break } } done := w.cnt == 0 w.Unlock() return done }
[ "func", "(", "w", "*", "Waiter", ")", "WaitAbsTimeout", "(", "t", "time", ".", "Time", ")", "bool", "{", "w", ".", "Lock", "(", ")", "\n", "for", "w", ".", "cnt", "!=", "0", "{", "if", "!", "w", ".", "cv", ".", "WaitAbsTimeout", "(", "t", ")", "{", "break", "\n", "}", "\n", "}", "\n", "done", ":=", "w", ".", "cnt", "==", "0", "\n", "w", ".", "Unlock", "(", ")", "\n", "return", "done", "\n", "}" ]
// WaitAbsTimeout is like WaitRelTimeout, but waits until an absolute time.
[ "WaitAbsTimeout", "is", "like", "WaitRelTimeout", "but", "waits", "until", "an", "absolute", "time", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/waiter.go#L114-L124
142,447
nanomsg/mangos-v1
transport.go
ResolveTCPAddr
func ResolveTCPAddr(addr string) (*net.TCPAddr, error) { if strings.HasPrefix(addr, "*") { addr = addr[1:] } return net.ResolveTCPAddr("tcp", addr) }
go
func ResolveTCPAddr(addr string) (*net.TCPAddr, error) { if strings.HasPrefix(addr, "*") { addr = addr[1:] } return net.ResolveTCPAddr("tcp", addr) }
[ "func", "ResolveTCPAddr", "(", "addr", "string", ")", "(", "*", "net", ".", "TCPAddr", ",", "error", ")", "{", "if", "strings", ".", "HasPrefix", "(", "addr", ",", "\"", "\"", ")", "{", "addr", "=", "addr", "[", "1", ":", "]", "\n", "}", "\n", "return", "net", ".", "ResolveTCPAddr", "(", "\"", "\"", ",", "addr", ")", "\n", "}" ]
// ResolveTCPAddr is like net.ResolveTCPAddr, but it handles the // wildcard used in nanomsg URLs, replacing it with an empty // string to indicate that all local interfaces be used.
[ "ResolveTCPAddr", "is", "like", "net", ".", "ResolveTCPAddr", "but", "it", "handles", "the", "wildcard", "used", "in", "nanomsg", "URLs", "replacing", "it", "with", "an", "empty", "string", "to", "indicate", "that", "all", "local", "interfaces", "be", "used", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/transport.go#L157-L162
142,448
nanomsg/mangos-v1
conn.go
Close
func (p *conn) Close() error { p.Lock() defer p.Unlock() if p.IsOpen() { p.open = false return p.c.Close() } return nil }
go
func (p *conn) Close() error { p.Lock() defer p.Unlock() if p.IsOpen() { p.open = false return p.c.Close() } return nil }
[ "func", "(", "p", "*", "conn", ")", "Close", "(", ")", "error", "{", "p", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "Unlock", "(", ")", "\n", "if", "p", ".", "IsOpen", "(", ")", "{", "p", ".", "open", "=", "false", "\n", "return", "p", ".", "c", ".", "Close", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Close implements the Pipe Close method.
[ "Close", "implements", "the", "Pipe", "Close", "method", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/conn.go#L107-L115
142,449
nanomsg/mangos-v1
conn.go
NewConnPipe
func NewConnPipe(c net.Conn, sock Socket, props ...interface{}) (Pipe, error) { p := &conn{c: c, proto: sock.GetProtocol(), sock: sock} if err := p.handshake(props); err != nil { return nil, err } return p, nil }
go
func NewConnPipe(c net.Conn, sock Socket, props ...interface{}) (Pipe, error) { p := &conn{c: c, proto: sock.GetProtocol(), sock: sock} if err := p.handshake(props); err != nil { return nil, err } return p, nil }
[ "func", "NewConnPipe", "(", "c", "net", ".", "Conn", ",", "sock", "Socket", ",", "props", "...", "interface", "{", "}", ")", "(", "Pipe", ",", "error", ")", "{", "p", ":=", "&", "conn", "{", "c", ":", "c", ",", "proto", ":", "sock", ".", "GetProtocol", "(", ")", ",", "sock", ":", "sock", "}", "\n\n", "if", "err", ":=", "p", ".", "handshake", "(", "props", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "p", ",", "nil", "\n", "}" ]
// NewConnPipe allocates a new Pipe using the supplied net.Conn, and // initializes it. It performs the handshake required at the SP layer, // only returning the Pipe once the SP layer negotiation is complete. // // Stream oriented transports can utilize this to implement a Transport. // The implementation will also need to implement PipeDialer, PipeAccepter, // and the Transport enclosing structure. Using this layered interface, // the implementation needn't bother concerning itself with passing actual // SP messages once the lower layer connection is established.
[ "NewConnPipe", "allocates", "a", "new", "Pipe", "using", "the", "supplied", "net", ".", "Conn", "and", "initializes", "it", ".", "It", "performs", "the", "handshake", "required", "at", "the", "SP", "layer", "only", "returning", "the", "Pipe", "once", "the", "SP", "layer", "negotiation", "is", "complete", ".", "Stream", "oriented", "transports", "can", "utilize", "this", "to", "implement", "a", "Transport", ".", "The", "implementation", "will", "also", "need", "to", "implement", "PipeDialer", "PipeAccepter", "and", "the", "Transport", "enclosing", "structure", ".", "Using", "this", "layered", "interface", "the", "implementation", "needn", "t", "bother", "concerning", "itself", "with", "passing", "actual", "SP", "messages", "once", "the", "lower", "layer", "connection", "is", "established", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/conn.go#L138-L146
142,450
nanomsg/mangos-v1
conn.go
handshake
func (p *conn) handshake(props []interface{}) error { var err error p.props = make(map[string]interface{}) p.props[PropLocalAddr] = p.c.LocalAddr() p.props[PropRemoteAddr] = p.c.RemoteAddr() for len(props) >= 2 { switch name := props[0].(type) { case string: p.props[name] = props[1] default: return ErrBadProperty } props = props[2:] } if v, e := p.sock.GetOption(OptionMaxRecvSize); e == nil { // socket guarantees this is an integer p.maxrx = int64(v.(int)) } h := connHeader{S: 'S', P: 'P', Proto: p.proto.Number()} if err = binary.Write(p.c, binary.BigEndian, &h); err != nil { return err } if err = binary.Read(p.c, binary.BigEndian, &h); err != nil { p.c.Close() return err } if h.Zero != 0 || h.S != 'S' || h.P != 'P' || h.Rsvd != 0 { p.c.Close() return ErrBadHeader } // The only version number we support at present is "0", at offset 3. if h.Version != 0 { p.c.Close() return ErrBadVersion } // The protocol number lives as 16-bits (big-endian) at offset 4. if h.Proto != p.proto.PeerNumber() { p.c.Close() return ErrBadProto } p.open = true return nil }
go
func (p *conn) handshake(props []interface{}) error { var err error p.props = make(map[string]interface{}) p.props[PropLocalAddr] = p.c.LocalAddr() p.props[PropRemoteAddr] = p.c.RemoteAddr() for len(props) >= 2 { switch name := props[0].(type) { case string: p.props[name] = props[1] default: return ErrBadProperty } props = props[2:] } if v, e := p.sock.GetOption(OptionMaxRecvSize); e == nil { // socket guarantees this is an integer p.maxrx = int64(v.(int)) } h := connHeader{S: 'S', P: 'P', Proto: p.proto.Number()} if err = binary.Write(p.c, binary.BigEndian, &h); err != nil { return err } if err = binary.Read(p.c, binary.BigEndian, &h); err != nil { p.c.Close() return err } if h.Zero != 0 || h.S != 'S' || h.P != 'P' || h.Rsvd != 0 { p.c.Close() return ErrBadHeader } // The only version number we support at present is "0", at offset 3. if h.Version != 0 { p.c.Close() return ErrBadVersion } // The protocol number lives as 16-bits (big-endian) at offset 4. if h.Proto != p.proto.PeerNumber() { p.c.Close() return ErrBadProto } p.open = true return nil }
[ "func", "(", "p", "*", "conn", ")", "handshake", "(", "props", "[", "]", "interface", "{", "}", ")", "error", "{", "var", "err", "error", "\n\n", "p", ".", "props", "=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "p", ".", "props", "[", "PropLocalAddr", "]", "=", "p", ".", "c", ".", "LocalAddr", "(", ")", "\n", "p", ".", "props", "[", "PropRemoteAddr", "]", "=", "p", ".", "c", ".", "RemoteAddr", "(", ")", "\n\n", "for", "len", "(", "props", ")", ">=", "2", "{", "switch", "name", ":=", "props", "[", "0", "]", ".", "(", "type", ")", "{", "case", "string", ":", "p", ".", "props", "[", "name", "]", "=", "props", "[", "1", "]", "\n", "default", ":", "return", "ErrBadProperty", "\n", "}", "\n", "props", "=", "props", "[", "2", ":", "]", "\n", "}", "\n\n", "if", "v", ",", "e", ":=", "p", ".", "sock", ".", "GetOption", "(", "OptionMaxRecvSize", ")", ";", "e", "==", "nil", "{", "// socket guarantees this is an integer", "p", ".", "maxrx", "=", "int64", "(", "v", ".", "(", "int", ")", ")", "\n", "}", "\n\n", "h", ":=", "connHeader", "{", "S", ":", "'S'", ",", "P", ":", "'P'", ",", "Proto", ":", "p", ".", "proto", ".", "Number", "(", ")", "}", "\n", "if", "err", "=", "binary", ".", "Write", "(", "p", ".", "c", ",", "binary", ".", "BigEndian", ",", "&", "h", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", "=", "binary", ".", "Read", "(", "p", ".", "c", ",", "binary", ".", "BigEndian", ",", "&", "h", ")", ";", "err", "!=", "nil", "{", "p", ".", "c", ".", "Close", "(", ")", "\n", "return", "err", "\n", "}", "\n", "if", "h", ".", "Zero", "!=", "0", "||", "h", ".", "S", "!=", "'S'", "||", "h", ".", "P", "!=", "'P'", "||", "h", ".", "Rsvd", "!=", "0", "{", "p", ".", "c", ".", "Close", "(", ")", "\n", "return", "ErrBadHeader", "\n", "}", "\n", "// The only version number we support at present is \"0\", at offset 3.", "if", "h", ".", "Version", "!=", "0", "{", "p", ".", "c", ".", "Close", "(", ")", "\n", "return", "ErrBadVersion", "\n", "}", "\n\n", "// The protocol number lives as 16-bits (big-endian) at offset 4.", "if", "h", ".", "Proto", "!=", "p", ".", "proto", ".", "PeerNumber", "(", ")", "{", "p", ".", "c", ".", "Close", "(", ")", "\n", "return", "ErrBadProto", "\n", "}", "\n", "p", ".", "open", "=", "true", "\n", "return", "nil", "\n", "}" ]
// handshake establishes an SP connection between peers. Both sides must // send the header, then both sides must wait for the peer's header. // As a side effect, the peer's protocol number is stored in the conn. // Also, various properties are initialized.
[ "handshake", "establishes", "an", "SP", "connection", "between", "peers", ".", "Both", "sides", "must", "send", "the", "header", "then", "both", "sides", "must", "wait", "for", "the", "peer", "s", "header", ".", "As", "a", "side", "effect", "the", "peer", "s", "protocol", "number", "is", "stored", "in", "the", "conn", ".", "Also", "various", "properties", "are", "initialized", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/conn.go#L162-L209
142,451
nanomsg/mangos-v1
util.go
mkTimer
func mkTimer(deadline time.Duration) <-chan time.Time { if deadline == 0 { return nil } return time.After(deadline) }
go
func mkTimer(deadline time.Duration) <-chan time.Time { if deadline == 0 { return nil } return time.After(deadline) }
[ "func", "mkTimer", "(", "deadline", "time", ".", "Duration", ")", "<-", "chan", "time", ".", "Time", "{", "if", "deadline", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "return", "time", ".", "After", "(", "deadline", ")", "\n", "}" ]
// mkTimer creates a timer based upon a duration. If however // a zero valued duration is passed, then a nil channel is passed // i.e. never selectable. This allows the output to be readily used // with deadlines in network connections, etc.
[ "mkTimer", "creates", "a", "timer", "based", "upon", "a", "duration", ".", "If", "however", "a", "zero", "valued", "duration", "is", "passed", "then", "a", "nil", "channel", "is", "passed", "i", ".", "e", ".", "never", "selectable", ".", "This", "allows", "the", "output", "to", "be", "readily", "used", "with", "deadlines", "in", "network", "connections", "etc", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/util.go#L28-L35
142,452
nanomsg/mangos-v1
perf/throughput.go
ThroughputClient
func ThroughputClient(addr string, msgSize int, count int) { s, err := pair.NewSocket() if err != nil { log.Fatalf("Failed to make new pair socket: %v", err) } defer s.Close() all.AddTransports(s) d, err := s.NewDialer(addr, nil) if err != nil { log.Fatalf("Failed to make new dialer: %v", err) } // Disable TCP no delay, please! d.SetOption(mangos.OptionNoDelay, false) // Make sure we linger a bit on close... err = s.SetOption(mangos.OptionLinger, time.Second) if err != nil { log.Fatalf("Failed set Linger: %v", err) } err = d.Dial() if err != nil { log.Fatalf("Failed to dial: %v", err) } // 100 milliseconds to give TCP a chance to establish time.Sleep(time.Millisecond * 100) body := make([]byte, msgSize) for i := 0; i < msgSize; i++ { body[i] = 111 } // send the start message s.Send([]byte{}) for i := 0; i < count; i++ { if err = s.Send(body); err != nil { log.Fatalf("Failed SendMsg: %v", err) } } }
go
func ThroughputClient(addr string, msgSize int, count int) { s, err := pair.NewSocket() if err != nil { log.Fatalf("Failed to make new pair socket: %v", err) } defer s.Close() all.AddTransports(s) d, err := s.NewDialer(addr, nil) if err != nil { log.Fatalf("Failed to make new dialer: %v", err) } // Disable TCP no delay, please! d.SetOption(mangos.OptionNoDelay, false) // Make sure we linger a bit on close... err = s.SetOption(mangos.OptionLinger, time.Second) if err != nil { log.Fatalf("Failed set Linger: %v", err) } err = d.Dial() if err != nil { log.Fatalf("Failed to dial: %v", err) } // 100 milliseconds to give TCP a chance to establish time.Sleep(time.Millisecond * 100) body := make([]byte, msgSize) for i := 0; i < msgSize; i++ { body[i] = 111 } // send the start message s.Send([]byte{}) for i := 0; i < count; i++ { if err = s.Send(body); err != nil { log.Fatalf("Failed SendMsg: %v", err) } } }
[ "func", "ThroughputClient", "(", "addr", "string", ",", "msgSize", "int", ",", "count", "int", ")", "{", "s", ",", "err", ":=", "pair", ".", "NewSocket", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "defer", "s", ".", "Close", "(", ")", "\n\n", "all", ".", "AddTransports", "(", "s", ")", "\n", "d", ",", "err", ":=", "s", ".", "NewDialer", "(", "addr", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Disable TCP no delay, please!", "d", ".", "SetOption", "(", "mangos", ".", "OptionNoDelay", ",", "false", ")", "\n\n", "// Make sure we linger a bit on close...", "err", "=", "s", ".", "SetOption", "(", "mangos", ".", "OptionLinger", ",", "time", ".", "Second", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "err", "=", "d", ".", "Dial", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// 100 milliseconds to give TCP a chance to establish", "time", ".", "Sleep", "(", "time", ".", "Millisecond", "*", "100", ")", "\n\n", "body", ":=", "make", "(", "[", "]", "byte", ",", "msgSize", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "msgSize", ";", "i", "++", "{", "body", "[", "i", "]", "=", "111", "\n", "}", "\n\n", "// send the start message", "s", ".", "Send", "(", "[", "]", "byte", "{", "}", ")", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "count", ";", "i", "++", "{", "if", "err", "=", "s", ".", "Send", "(", "body", ")", ";", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}" ]
// ThroughputClient is the client side of the latency test. It simply sends // the requested number of packets of given size to the server. It corresponds // to remote_thr.
[ "ThroughputClient", "is", "the", "client", "side", "of", "the", "latency", "test", ".", "It", "simply", "sends", "the", "requested", "number", "of", "packets", "of", "given", "size", "to", "the", "server", ".", "It", "corresponds", "to", "remote_thr", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/perf/throughput.go#L94-L137
142,453
nanomsg/mangos-v1
protocol/respondent/respondent.go
sender
func (peer *respPeer) sender() { for { m := <-peer.q if m == nil { break } if peer.ep.SendMsg(m) != nil { m.Free() break } } }
go
func (peer *respPeer) sender() { for { m := <-peer.q if m == nil { break } if peer.ep.SendMsg(m) != nil { m.Free() break } } }
[ "func", "(", "peer", "*", "respPeer", ")", "sender", "(", ")", "{", "for", "{", "m", ":=", "<-", "peer", ".", "q", "\n", "if", "m", "==", "nil", "{", "break", "\n", "}", "\n", "if", "peer", ".", "ep", ".", "SendMsg", "(", "m", ")", "!=", "nil", "{", "m", ".", "Free", "(", ")", "\n", "break", "\n", "}", "\n", "}", "\n", "}" ]
// When sending, we should have the survey ID in the header.
[ "When", "sending", "we", "should", "have", "the", "survey", "ID", "in", "the", "header", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/protocol/respondent/respondent.go#L120-L131
142,454
nanomsg/mangos-v1
transport/ipc/ipc_windows.go
Dial
func (d *dialer) Dial() (mangos.Pipe, error) { conn, err := winio.DialPipe("\\\\.\\pipe\\"+d.path, nil) if err != nil { return nil, err } addr := pipeAddr(d.path) return mangos.NewConnPipeIPC(conn, d.sock, mangos.PropLocalAddr, addr, mangos.PropRemoteAddr, addr) }
go
func (d *dialer) Dial() (mangos.Pipe, error) { conn, err := winio.DialPipe("\\\\.\\pipe\\"+d.path, nil) if err != nil { return nil, err } addr := pipeAddr(d.path) return mangos.NewConnPipeIPC(conn, d.sock, mangos.PropLocalAddr, addr, mangos.PropRemoteAddr, addr) }
[ "func", "(", "d", "*", "dialer", ")", "Dial", "(", ")", "(", "mangos", ".", "Pipe", ",", "error", ")", "{", "conn", ",", "err", ":=", "winio", ".", "DialPipe", "(", "\"", "\\\\", "\\\\", "\\\\", "\\\\", "\"", "+", "d", ".", "path", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "addr", ":=", "pipeAddr", "(", "d", ".", "path", ")", "\n", "return", "mangos", ".", "NewConnPipeIPC", "(", "conn", ",", "d", ".", "sock", ",", "mangos", ".", "PropLocalAddr", ",", "addr", ",", "mangos", ".", "PropRemoteAddr", ",", "addr", ")", "\n", "}" ]
// Dial implements the PipeDialer Dial method.
[ "Dial", "implements", "the", "PipeDialer", "Dial", "method", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/transport/ipc/ipc_windows.go#L65-L74
142,455
nanomsg/mangos-v1
transport/ipc/ipc_windows.go
Close
func (l *listener) Close() error { if l.listener != nil { l.listener.Close() } return nil }
go
func (l *listener) Close() error { if l.listener != nil { l.listener.Close() } return nil }
[ "func", "(", "l", "*", "listener", ")", "Close", "(", ")", "error", "{", "if", "l", ".", "listener", "!=", "nil", "{", "l", ".", "listener", ".", "Close", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Close implements the PipeListener Close method.
[ "Close", "implements", "the", "PipeListener", "Close", "method", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/transport/ipc/ipc_windows.go#L141-L146
142,456
nanomsg/mangos-v1
transport/ipc/ipc_windows.go
SetOption
func (l *listener) SetOption(name string, val interface{}) error { switch name { case OptionInputBufferSize: switch v := val.(type) { case int32: l.config.InputBufferSize = v return nil default: return mangos.ErrBadValue } case OptionOutputBufferSize: switch v := val.(type) { case int32: l.config.OutputBufferSize = v return nil default: return mangos.ErrBadValue } case OptionSecurityDescriptor: switch v := val.(type) { case string: l.config.SecurityDescriptor = v return nil default: return mangos.ErrBadValue } default: return mangos.ErrBadOption } }
go
func (l *listener) SetOption(name string, val interface{}) error { switch name { case OptionInputBufferSize: switch v := val.(type) { case int32: l.config.InputBufferSize = v return nil default: return mangos.ErrBadValue } case OptionOutputBufferSize: switch v := val.(type) { case int32: l.config.OutputBufferSize = v return nil default: return mangos.ErrBadValue } case OptionSecurityDescriptor: switch v := val.(type) { case string: l.config.SecurityDescriptor = v return nil default: return mangos.ErrBadValue } default: return mangos.ErrBadOption } }
[ "func", "(", "l", "*", "listener", ")", "SetOption", "(", "name", "string", ",", "val", "interface", "{", "}", ")", "error", "{", "switch", "name", "{", "case", "OptionInputBufferSize", ":", "switch", "v", ":=", "val", ".", "(", "type", ")", "{", "case", "int32", ":", "l", ".", "config", ".", "InputBufferSize", "=", "v", "\n", "return", "nil", "\n", "default", ":", "return", "mangos", ".", "ErrBadValue", "\n", "}", "\n", "case", "OptionOutputBufferSize", ":", "switch", "v", ":=", "val", ".", "(", "type", ")", "{", "case", "int32", ":", "l", ".", "config", ".", "OutputBufferSize", "=", "v", "\n", "return", "nil", "\n", "default", ":", "return", "mangos", ".", "ErrBadValue", "\n", "}", "\n", "case", "OptionSecurityDescriptor", ":", "switch", "v", ":=", "val", ".", "(", "type", ")", "{", "case", "string", ":", "l", ".", "config", ".", "SecurityDescriptor", "=", "v", "\n", "return", "nil", "\n", "default", ":", "return", "mangos", ".", "ErrBadValue", "\n", "}", "\n", "default", ":", "return", "mangos", ".", "ErrBadOption", "\n", "}", "\n", "}" ]
// SetOption implements a stub PipeListener SetOption method.
[ "SetOption", "implements", "a", "stub", "PipeListener", "SetOption", "method", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/transport/ipc/ipc_windows.go#L149-L178
142,457
nanomsg/mangos-v1
transport/ipc/ipc_windows.go
GetOption
func (l *listener) GetOption(name string) (interface{}, error) { switch name { case OptionInputBufferSize: return l.config.InputBufferSize, nil case OptionOutputBufferSize: return l.config.OutputBufferSize, nil case OptionSecurityDescriptor: return l.config.SecurityDescriptor, nil } return nil, mangos.ErrBadOption }
go
func (l *listener) GetOption(name string) (interface{}, error) { switch name { case OptionInputBufferSize: return l.config.InputBufferSize, nil case OptionOutputBufferSize: return l.config.OutputBufferSize, nil case OptionSecurityDescriptor: return l.config.SecurityDescriptor, nil } return nil, mangos.ErrBadOption }
[ "func", "(", "l", "*", "listener", ")", "GetOption", "(", "name", "string", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "switch", "name", "{", "case", "OptionInputBufferSize", ":", "return", "l", ".", "config", ".", "InputBufferSize", ",", "nil", "\n", "case", "OptionOutputBufferSize", ":", "return", "l", ".", "config", ".", "OutputBufferSize", ",", "nil", "\n", "case", "OptionSecurityDescriptor", ":", "return", "l", ".", "config", ".", "SecurityDescriptor", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "mangos", ".", "ErrBadOption", "\n", "}" ]
// GetOption implements a stub PipeListener GetOption method.
[ "GetOption", "implements", "a", "stub", "PipeListener", "GetOption", "method", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/transport/ipc/ipc_windows.go#L181-L191
142,458
nanomsg/mangos-v1
device.go
forwarder
func forwarder(fromSock Socket, toSock Socket) { for { m, err := fromSock.RecvMsg() if err != nil { // Probably closed socket, nothing else we can do. return } err = toSock.SendMsg(m) if err != nil { return } } }
go
func forwarder(fromSock Socket, toSock Socket) { for { m, err := fromSock.RecvMsg() if err != nil { // Probably closed socket, nothing else we can do. return } err = toSock.SendMsg(m) if err != nil { return } } }
[ "func", "forwarder", "(", "fromSock", "Socket", ",", "toSock", "Socket", ")", "{", "for", "{", "m", ",", "err", ":=", "fromSock", ".", "RecvMsg", "(", ")", "\n", "if", "err", "!=", "nil", "{", "// Probably closed socket, nothing else we can do.", "return", "\n", "}", "\n\n", "err", "=", "toSock", ".", "SendMsg", "(", "m", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "\n", "}" ]
// Forwarder takes messages from one socket, and sends them to the other. // The sockets must be of compatible types, and must be in Raw mode.
[ "Forwarder", "takes", "messages", "from", "one", "socket", "and", "sends", "them", "to", "the", "other", ".", "The", "sockets", "must", "be", "of", "compatible", "types", "and", "must", "be", "in", "Raw", "mode", "." ]
b213a8e043f6541ad45f946a2e1c5d3617987985
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/device.go#L64-L77
142,459
trivago/gollum
producer/scribe.go
Produce
func (prod *Scribe) Produce(workers *sync.WaitGroup) { prod.AddMainWorker(workers) prod.BatchMessageLoop(workers, prod.sendBatch) }
go
func (prod *Scribe) Produce(workers *sync.WaitGroup) { prod.AddMainWorker(workers) prod.BatchMessageLoop(workers, prod.sendBatch) }
[ "func", "(", "prod", "*", "Scribe", ")", "Produce", "(", "workers", "*", "sync", ".", "WaitGroup", ")", "{", "prod", ".", "AddMainWorker", "(", "workers", ")", "\n", "prod", ".", "BatchMessageLoop", "(", "workers", ",", "prod", ".", "sendBatch", ")", "\n", "}" ]
// Produce writes to a buffer that is sent to scribe.
[ "Produce", "writes", "to", "a", "buffer", "that", "is", "sent", "to", "scribe", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/scribe.go#L279-L282
142,460
trivago/gollum
core/components/awsMultiClient.go
NewSessionWithOptions
func (client *AwsMultiClient) NewSessionWithOptions() (*session.Session, error) { sess, err := session.NewSessionWithOptions(session.Options{ Config: *client.config, SharedConfigState: session.SharedConfigEnable, }) if err != nil { return nil, err } if client.Credentials.assumeRole != "" { credentials := stscreds.NewCredentials(sess, client.Credentials.assumeRole) client.config.WithCredentials(credentials) } return sess, err }
go
func (client *AwsMultiClient) NewSessionWithOptions() (*session.Session, error) { sess, err := session.NewSessionWithOptions(session.Options{ Config: *client.config, SharedConfigState: session.SharedConfigEnable, }) if err != nil { return nil, err } if client.Credentials.assumeRole != "" { credentials := stscreds.NewCredentials(sess, client.Credentials.assumeRole) client.config.WithCredentials(credentials) } return sess, err }
[ "func", "(", "client", "*", "AwsMultiClient", ")", "NewSessionWithOptions", "(", ")", "(", "*", "session", ".", "Session", ",", "error", ")", "{", "sess", ",", "err", ":=", "session", ".", "NewSessionWithOptions", "(", "session", ".", "Options", "{", "Config", ":", "*", "client", ".", "config", ",", "SharedConfigState", ":", "session", ".", "SharedConfigEnable", ",", "}", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "client", ".", "Credentials", ".", "assumeRole", "!=", "\"", "\"", "{", "credentials", ":=", "stscreds", ".", "NewCredentials", "(", "sess", ",", "client", ".", "Credentials", ".", "assumeRole", ")", "\n", "client", ".", "config", ".", "WithCredentials", "(", "credentials", ")", "\n", "}", "\n\n", "return", "sess", ",", "err", "\n", "}" ]
// NewSessionWithOptions returns a instantiated asw session
[ "NewSessionWithOptions", "returns", "a", "instantiated", "asw", "session" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/components/awsMultiClient.go#L79-L95
142,461
trivago/gollum
core/components/awsMultiClient.go
CreateAwsCredentials
func (cred *AwsCredentials) CreateAwsCredentials() (*credentials.Credentials, error) { switch cred.credentialType { case credentialTypeEnv: return credentials.NewEnvCredentials(), nil case credentialTypeStatic: return credentials.NewStaticCredentials(cred.staticID, cred.staticSecret, cred.staticToken), nil case credentialTypeShared: return credentials.NewSharedCredentials(cred.sharedFile, cred.sharedProfile), nil case credentialTypeNone: return credentials.AnonymousCredentials, nil default: return credentials.AnonymousCredentials, fmt.Errorf("unknown CredentialType: %s", cred.credentialType) } }
go
func (cred *AwsCredentials) CreateAwsCredentials() (*credentials.Credentials, error) { switch cred.credentialType { case credentialTypeEnv: return credentials.NewEnvCredentials(), nil case credentialTypeStatic: return credentials.NewStaticCredentials(cred.staticID, cred.staticSecret, cred.staticToken), nil case credentialTypeShared: return credentials.NewSharedCredentials(cred.sharedFile, cred.sharedProfile), nil case credentialTypeNone: return credentials.AnonymousCredentials, nil default: return credentials.AnonymousCredentials, fmt.Errorf("unknown CredentialType: %s", cred.credentialType) } }
[ "func", "(", "cred", "*", "AwsCredentials", ")", "CreateAwsCredentials", "(", ")", "(", "*", "credentials", ".", "Credentials", ",", "error", ")", "{", "switch", "cred", ".", "credentialType", "{", "case", "credentialTypeEnv", ":", "return", "credentials", ".", "NewEnvCredentials", "(", ")", ",", "nil", "\n\n", "case", "credentialTypeStatic", ":", "return", "credentials", ".", "NewStaticCredentials", "(", "cred", ".", "staticID", ",", "cred", ".", "staticSecret", ",", "cred", ".", "staticToken", ")", ",", "nil", "\n\n", "case", "credentialTypeShared", ":", "return", "credentials", ".", "NewSharedCredentials", "(", "cred", ".", "sharedFile", ",", "cred", ".", "sharedProfile", ")", ",", "nil", "\n\n", "case", "credentialTypeNone", ":", "return", "credentials", ".", "AnonymousCredentials", ",", "nil", "\n\n", "default", ":", "return", "credentials", ".", "AnonymousCredentials", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "cred", ".", "credentialType", ")", "\n", "}", "\n", "}" ]
// CreateAwsCredentials returns aws credentials.Credentials for active settings
[ "CreateAwsCredentials", "returns", "aws", "credentials", ".", "Credentials", "for", "active", "settings" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/components/awsMultiClient.go#L136-L153
142,462
trivago/gollum
docs/generator/definition.go
add
func (list *DefinitionList) add(def *Definition) { list.slice = append(list.slice, def) }
go
func (list *DefinitionList) add(def *Definition) { list.slice = append(list.slice, def) }
[ "func", "(", "list", "*", "DefinitionList", ")", "add", "(", "def", "*", "Definition", ")", "{", "list", ".", "slice", "=", "append", "(", "list", ".", "slice", ",", "def", ")", "\n", "}" ]
// add appends the definition pointed to by `def` to this list
[ "add", "appends", "the", "definition", "pointed", "to", "by", "def", "to", "this", "list" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/docs/generator/definition.go#L123-L125
142,463
trivago/gollum
docs/generator/definition.go
getRST
func (list DefinitionList) getRST(paramFields bool, depth int) string { result := "" if len(list.desc) > 0 { result = fmt.Sprintf("%s\n", list.desc) } for _, def := range list.slice { // Heading if strings.Trim(def.name, " \t") != "" { result += indentLines("**"+def.name+"**", 2*depth) } else { // Nameless definition // FIXME: bullet lists or something result += "** (unnamed) **" } // Optional default value and unit if paramFields && (def.unit != "" || def.dfl != "") { // TODO: cleaner formatting result += " (" if def.dfl != "" { result += fmt.Sprintf("default: %s", def.dfl) } if def.dfl != "" && def.unit != "" { result += ", " } if def.unit != "" { result += fmt.Sprintf("unit: %s", def.unit) } result += ")" } result += "\n\n" // Body result += indentLines(docBulletsToRstBullets(def.desc), 2*(depth+1)) //result += def.desc result += "\n\n" // Children result += def.children.getRST(paramFields, depth+1) } //return indentLines(result, 2 * (depth + 1)) return result }
go
func (list DefinitionList) getRST(paramFields bool, depth int) string { result := "" if len(list.desc) > 0 { result = fmt.Sprintf("%s\n", list.desc) } for _, def := range list.slice { // Heading if strings.Trim(def.name, " \t") != "" { result += indentLines("**"+def.name+"**", 2*depth) } else { // Nameless definition // FIXME: bullet lists or something result += "** (unnamed) **" } // Optional default value and unit if paramFields && (def.unit != "" || def.dfl != "") { // TODO: cleaner formatting result += " (" if def.dfl != "" { result += fmt.Sprintf("default: %s", def.dfl) } if def.dfl != "" && def.unit != "" { result += ", " } if def.unit != "" { result += fmt.Sprintf("unit: %s", def.unit) } result += ")" } result += "\n\n" // Body result += indentLines(docBulletsToRstBullets(def.desc), 2*(depth+1)) //result += def.desc result += "\n\n" // Children result += def.children.getRST(paramFields, depth+1) } //return indentLines(result, 2 * (depth + 1)) return result }
[ "func", "(", "list", "DefinitionList", ")", "getRST", "(", "paramFields", "bool", ",", "depth", "int", ")", "string", "{", "result", ":=", "\"", "\"", "\n\n", "if", "len", "(", "list", ".", "desc", ")", ">", "0", "{", "result", "=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "list", ".", "desc", ")", "\n", "}", "\n\n", "for", "_", ",", "def", ":=", "range", "list", ".", "slice", "{", "// Heading", "if", "strings", ".", "Trim", "(", "def", ".", "name", ",", "\"", "\\t", "\"", ")", "!=", "\"", "\"", "{", "result", "+=", "indentLines", "(", "\"", "\"", "+", "def", ".", "name", "+", "\"", "\"", ",", "2", "*", "depth", ")", "\n\n", "}", "else", "{", "// Nameless definition", "// FIXME: bullet lists or something", "result", "+=", "\"", "\"", "\n", "}", "\n\n", "// Optional default value and unit", "if", "paramFields", "&&", "(", "def", ".", "unit", "!=", "\"", "\"", "||", "def", ".", "dfl", "!=", "\"", "\"", ")", "{", "// TODO: cleaner formatting", "result", "+=", "\"", "\"", "\n", "if", "def", ".", "dfl", "!=", "\"", "\"", "{", "result", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "def", ".", "dfl", ")", "\n", "}", "\n", "if", "def", ".", "dfl", "!=", "\"", "\"", "&&", "def", ".", "unit", "!=", "\"", "\"", "{", "result", "+=", "\"", "\"", "\n", "}", "\n", "if", "def", ".", "unit", "!=", "\"", "\"", "{", "result", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "def", ".", "unit", ")", "\n", "}", "\n", "result", "+=", "\"", "\"", "\n", "}", "\n", "result", "+=", "\"", "\\n", "\\n", "\"", "\n\n", "// Body", "result", "+=", "indentLines", "(", "docBulletsToRstBullets", "(", "def", ".", "desc", ")", ",", "2", "*", "(", "depth", "+", "1", ")", ")", "\n", "//result += def.desc", "result", "+=", "\"", "\\n", "\\n", "\"", "\n\n", "// Children", "result", "+=", "def", ".", "children", ".", "getRST", "(", "paramFields", ",", "depth", "+", "1", ")", "\n", "}", "\n\n", "//return indentLines(result, 2 * (depth + 1))", "return", "result", "\n", "}" ]
// getRST formats the DefinitionList as ReStructuredText
[ "getRST", "formats", "the", "DefinitionList", "as", "ReStructuredText" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/docs/generator/definition.go#L165-L211
142,464
trivago/gollum
docs/generator/definition.go
indentLines
func indentLines(source string, level int) string { return regexp.MustCompile("(?m:(^))").ReplaceAllString(source, strings.Repeat(" ", level)) }
go
func indentLines(source string, level int) string { return regexp.MustCompile("(?m:(^))").ReplaceAllString(source, strings.Repeat(" ", level)) }
[ "func", "indentLines", "(", "source", "string", ",", "level", "int", ")", "string", "{", "return", "regexp", ".", "MustCompile", "(", "\"", "\"", ")", ".", "ReplaceAllString", "(", "source", ",", "strings", ".", "Repeat", "(", "\"", "\"", ",", "level", ")", ")", "\n", "}" ]
// Inserts two spaces at the beginning of each line, making the string a blockquote in RST
[ "Inserts", "two", "spaces", "at", "the", "beginning", "of", "each", "line", "making", "the", "string", "a", "blockquote", "in", "RST" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/docs/generator/definition.go#L214-L216
142,465
trivago/gollum
core/filter.go
ApplyFilter
func (filters FilterArray) ApplyFilter(msg *Message) (FilterResult, error) { for _, filter := range filters { result, err := filter.ApplyFilter(msg) if err != nil { return result, err } if result != FilterResultMessageAccept { return result, nil } } return FilterResultMessageAccept, nil }
go
func (filters FilterArray) ApplyFilter(msg *Message) (FilterResult, error) { for _, filter := range filters { result, err := filter.ApplyFilter(msg) if err != nil { return result, err } if result != FilterResultMessageAccept { return result, nil } } return FilterResultMessageAccept, nil }
[ "func", "(", "filters", "FilterArray", ")", "ApplyFilter", "(", "msg", "*", "Message", ")", "(", "FilterResult", ",", "error", ")", "{", "for", "_", ",", "filter", ":=", "range", "filters", "{", "result", ",", "err", ":=", "filter", ".", "ApplyFilter", "(", "msg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "result", ",", "err", "\n", "}", "\n\n", "if", "result", "!=", "FilterResultMessageAccept", "{", "return", "result", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "FilterResultMessageAccept", ",", "nil", "\n", "}" ]
// ApplyFilter calls ApplyFilter on every filter // Return FilterResultMessageReject in case of an error or if one filter rejects
[ "ApplyFilter", "calls", "ApplyFilter", "on", "every", "filter", "Return", "FilterResultMessageReject", "in", "case", "of", "an", "error", "or", "if", "one", "filter", "rejects" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/filter.go#L28-L40
142,466
trivago/gollum
core/errors.go
NewModulateResultError
func NewModulateResultError(message string, values ...interface{}) ModulateResultError { return ModulateResultError{ message: fmt.Sprintf(message, values...), } }
go
func NewModulateResultError(message string, values ...interface{}) ModulateResultError { return ModulateResultError{ message: fmt.Sprintf(message, values...), } }
[ "func", "NewModulateResultError", "(", "message", "string", ",", "values", "...", "interface", "{", "}", ")", "ModulateResultError", "{", "return", "ModulateResultError", "{", "message", ":", "fmt", ".", "Sprintf", "(", "message", ",", "values", "...", ")", ",", "}", "\n", "}" ]
// NewModulateResultError creates a new ModulateResultError with the given // message.
[ "NewModulateResultError", "creates", "a", "new", "ModulateResultError", "with", "the", "given", "message", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/errors.go#L34-L38
142,467
trivago/gollum
producer/InfluxDB.go
sendBatch
func (prod *InfluxDB) sendBatch() core.AssemblyFunc { if prod.writer.isConnectionUp() { return prod.assembly.Write } else if prod.IsStopping() { return prod.assembly.Flush } return nil }
go
func (prod *InfluxDB) sendBatch() core.AssemblyFunc { if prod.writer.isConnectionUp() { return prod.assembly.Write } else if prod.IsStopping() { return prod.assembly.Flush } return nil }
[ "func", "(", "prod", "*", "InfluxDB", ")", "sendBatch", "(", ")", "core", ".", "AssemblyFunc", "{", "if", "prod", ".", "writer", ".", "isConnectionUp", "(", ")", "{", "return", "prod", ".", "assembly", ".", "Write", "\n", "}", "else", "if", "prod", ".", "IsStopping", "(", ")", "{", "return", "prod", ".", "assembly", ".", "Flush", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// sendBatch returns core.AssemblyFunc to flush batch
[ "sendBatch", "returns", "core", ".", "AssemblyFunc", "to", "flush", "batch" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/InfluxDB.go#L109-L117
142,468
trivago/gollum
producer/InfluxDB.go
Produce
func (prod *InfluxDB) Produce(workers *sync.WaitGroup) { prod.BatchMessageLoop(workers, prod.sendBatch) }
go
func (prod *InfluxDB) Produce(workers *sync.WaitGroup) { prod.BatchMessageLoop(workers, prod.sendBatch) }
[ "func", "(", "prod", "*", "InfluxDB", ")", "Produce", "(", "workers", "*", "sync", ".", "WaitGroup", ")", "{", "prod", ".", "BatchMessageLoop", "(", "workers", ",", "prod", ".", "sendBatch", ")", "\n", "}" ]
// Produce starts a bulk producer which will collect datapoints until either the buffer is full or a timeout has been reached. // The buffer limit does not describe the number of messages received from kafka but the size of the buffer content in KB.
[ "Produce", "starts", "a", "bulk", "producer", "which", "will", "collect", "datapoints", "until", "either", "the", "buffer", "is", "full", "or", "a", "timeout", "has", "been", "reached", ".", "The", "buffer", "limit", "does", "not", "describe", "the", "number", "of", "messages", "received", "from", "kafka", "but", "the", "size", "of", "the", "buffer", "content", "in", "KB", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/InfluxDB.go#L121-L123
142,469
trivago/gollum
docs/generator/gollumplugin.go
findGollumPlugins
func findGollumPlugins(pkgRoot *ast.Package) []GollumPlugin { // Generate a tree structure from the parse results returned by AST tree := NewTree(pkgRoot) // The tree looks like this: /** *ast.Package *ast.File *ast.Ident *ast.GenDecl *ast.ImportSpec *ast.BasicLit [....] *ast.GenDecl *ast.CommentGroup *ast.Comment *ast.TypeSpec *ast.Ident *ast.StructType *ast.FieldList *ast.Field *ast.Ident *ast.Ident [....[ **/ // Search pattern pattern := PatternNode{ Comparison: "*ast.GenDecl", Children: []PatternNode{ { Comparison: "*ast.CommentGroup", // Note: there are N pcs of "*ast.Comment" children // here but we don't need to match them }, { Comparison: "*ast.TypeSpec", Children: []PatternNode{ { Comparison: "*ast.Ident", Callback: func(astNode ast.Node) bool { // Checks that the name starts with a capital letter return ast.IsExported(astNode.(*ast.Ident).Name) }, }, { Comparison: "*ast.StructType", Children: []PatternNode{ { Comparison: "*ast.FieldList", // There are N pcs of "*ast.Field" children here }, }, }, }, }, }, } // Search the tree results := []GollumPlugin{} for _, genDecl := range tree.Search(pattern) { pst := GollumPlugin{ Pkg: pkgRoot.Name, // Indexes assumed based on the search pattern above Name: genDecl.Children[1].Children[0].AstNode.(*ast.Ident).Name, Comment: genDecl.Children[0].AstNode.(*ast.CommentGroup).Text(), Embeds: getGollumPluginEmbedList(pkgRoot.Name, genDecl.Children[1].Children[1].Children[0].AstNode.(*ast.FieldList), ), StructTagParams: getGollumPluginConfigParams( genDecl.Children[1].Children[1].Children[0].AstNode.(*ast.FieldList), ), } results = append(results, pst) } return results }
go
func findGollumPlugins(pkgRoot *ast.Package) []GollumPlugin { // Generate a tree structure from the parse results returned by AST tree := NewTree(pkgRoot) // The tree looks like this: /** *ast.Package *ast.File *ast.Ident *ast.GenDecl *ast.ImportSpec *ast.BasicLit [....] *ast.GenDecl *ast.CommentGroup *ast.Comment *ast.TypeSpec *ast.Ident *ast.StructType *ast.FieldList *ast.Field *ast.Ident *ast.Ident [....[ **/ // Search pattern pattern := PatternNode{ Comparison: "*ast.GenDecl", Children: []PatternNode{ { Comparison: "*ast.CommentGroup", // Note: there are N pcs of "*ast.Comment" children // here but we don't need to match them }, { Comparison: "*ast.TypeSpec", Children: []PatternNode{ { Comparison: "*ast.Ident", Callback: func(astNode ast.Node) bool { // Checks that the name starts with a capital letter return ast.IsExported(astNode.(*ast.Ident).Name) }, }, { Comparison: "*ast.StructType", Children: []PatternNode{ { Comparison: "*ast.FieldList", // There are N pcs of "*ast.Field" children here }, }, }, }, }, }, } // Search the tree results := []GollumPlugin{} for _, genDecl := range tree.Search(pattern) { pst := GollumPlugin{ Pkg: pkgRoot.Name, // Indexes assumed based on the search pattern above Name: genDecl.Children[1].Children[0].AstNode.(*ast.Ident).Name, Comment: genDecl.Children[0].AstNode.(*ast.CommentGroup).Text(), Embeds: getGollumPluginEmbedList(pkgRoot.Name, genDecl.Children[1].Children[1].Children[0].AstNode.(*ast.FieldList), ), StructTagParams: getGollumPluginConfigParams( genDecl.Children[1].Children[1].Children[0].AstNode.(*ast.FieldList), ), } results = append(results, pst) } return results }
[ "func", "findGollumPlugins", "(", "pkgRoot", "*", "ast", ".", "Package", ")", "[", "]", "GollumPlugin", "{", "// Generate a tree structure from the parse results returned by AST", "tree", ":=", "NewTree", "(", "pkgRoot", ")", "\n\n", "// The tree looks like this:", "/**\n\t\t*ast.Package\n\t\t *ast.File\n\t\t *ast.Ident\n\t\t *ast.GenDecl\n\t\t *ast.ImportSpec\n\t\t *ast.BasicLit\n\t\t [....]\n\t\t *ast.GenDecl\n\t\t *ast.CommentGroup\n\t\t *ast.Comment\n\t\t *ast.TypeSpec\n\t\t *ast.Ident\n\t\t *ast.StructType\n\t\t *ast.FieldList\n\t\t *ast.Field\n\t\t *ast.Ident\n\t\t *ast.Ident\n\t\t [....[\n\t**/", "// Search pattern", "pattern", ":=", "PatternNode", "{", "Comparison", ":", "\"", "\"", ",", "Children", ":", "[", "]", "PatternNode", "{", "{", "Comparison", ":", "\"", "\"", ",", "// Note: there are N pcs of \"*ast.Comment\" children", "// here but we don't need to match them", "}", ",", "{", "Comparison", ":", "\"", "\"", ",", "Children", ":", "[", "]", "PatternNode", "{", "{", "Comparison", ":", "\"", "\"", ",", "Callback", ":", "func", "(", "astNode", "ast", ".", "Node", ")", "bool", "{", "// Checks that the name starts with a capital letter", "return", "ast", ".", "IsExported", "(", "astNode", ".", "(", "*", "ast", ".", "Ident", ")", ".", "Name", ")", "\n", "}", ",", "}", ",", "{", "Comparison", ":", "\"", "\"", ",", "Children", ":", "[", "]", "PatternNode", "{", "{", "Comparison", ":", "\"", "\"", ",", "// There are N pcs of \"*ast.Field\" children here", "}", ",", "}", ",", "}", ",", "}", ",", "}", ",", "}", ",", "}", "\n\n", "// Search the tree", "results", ":=", "[", "]", "GollumPlugin", "{", "}", "\n", "for", "_", ",", "genDecl", ":=", "range", "tree", ".", "Search", "(", "pattern", ")", "{", "pst", ":=", "GollumPlugin", "{", "Pkg", ":", "pkgRoot", ".", "Name", ",", "// Indexes assumed based on the search pattern above", "Name", ":", "genDecl", ".", "Children", "[", "1", "]", ".", "Children", "[", "0", "]", ".", "AstNode", ".", "(", "*", "ast", ".", "Ident", ")", ".", "Name", ",", "Comment", ":", "genDecl", ".", "Children", "[", "0", "]", ".", "AstNode", ".", "(", "*", "ast", ".", "CommentGroup", ")", ".", "Text", "(", ")", ",", "Embeds", ":", "getGollumPluginEmbedList", "(", "pkgRoot", ".", "Name", ",", "genDecl", ".", "Children", "[", "1", "]", ".", "Children", "[", "1", "]", ".", "Children", "[", "0", "]", ".", "AstNode", ".", "(", "*", "ast", ".", "FieldList", ")", ",", ")", ",", "StructTagParams", ":", "getGollumPluginConfigParams", "(", "genDecl", ".", "Children", "[", "1", "]", ".", "Children", "[", "1", "]", ".", "Children", "[", "0", "]", ".", "AstNode", ".", "(", "*", "ast", ".", "FieldList", ")", ",", ")", ",", "}", "\n\n", "results", "=", "append", "(", "results", ",", "pst", ")", "\n", "}", "\n\n", "return", "results", "\n", "}" ]
// Searches the AST rooted at `pkgRoot` for struct types representing Gollum plugins
[ "Searches", "the", "AST", "rooted", "at", "pkgRoot", "for", "struct", "types", "representing", "Gollum", "plugins" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/docs/generator/gollumplugin.go#L27-L106
142,470
trivago/gollum
logger/console_formatter.go
NewConsoleFormatter
func NewConsoleFormatter() *prefixed.TextFormatter { f := prefixed.TextFormatter{} f.ForceColors = true f.FullTimestamp = true f.ForceFormatting = true f.TimestampFormat = "2006-01-02 15:04:05 MST" f.SetColorScheme(&prefixed.ColorScheme{ PrefixStyle: "blue+h", InfoLevelStyle: "white+h", DebugLevelStyle: "cyan", }) return &f }
go
func NewConsoleFormatter() *prefixed.TextFormatter { f := prefixed.TextFormatter{} f.ForceColors = true f.FullTimestamp = true f.ForceFormatting = true f.TimestampFormat = "2006-01-02 15:04:05 MST" f.SetColorScheme(&prefixed.ColorScheme{ PrefixStyle: "blue+h", InfoLevelStyle: "white+h", DebugLevelStyle: "cyan", }) return &f }
[ "func", "NewConsoleFormatter", "(", ")", "*", "prefixed", ".", "TextFormatter", "{", "f", ":=", "prefixed", ".", "TextFormatter", "{", "}", "\n\n", "f", ".", "ForceColors", "=", "true", "\n", "f", ".", "FullTimestamp", "=", "true", "\n", "f", ".", "ForceFormatting", "=", "true", "\n", "f", ".", "TimestampFormat", "=", "\"", "\"", "\n\n", "f", ".", "SetColorScheme", "(", "&", "prefixed", ".", "ColorScheme", "{", "PrefixStyle", ":", "\"", "\"", ",", "InfoLevelStyle", ":", "\"", "\"", ",", "DebugLevelStyle", ":", "\"", "\"", ",", "}", ")", "\n\n", "return", "&", "f", "\n", "}" ]
// NewConsoleFormatter returns a a ConsoleFormatter reference
[ "NewConsoleFormatter", "returns", "a", "a", "ConsoleFormatter", "reference" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/logger/console_formatter.go#L22-L37
142,471
trivago/gollum
core/formatter.go
ApplyFormatter
func (formatters FormatterArray) ApplyFormatter(msg *Message) error { for _, formatter := range formatters { if formatter.CanBeApplied(msg) { if err := formatter.ApplyFormatter(msg); err != nil { return err } } } return nil }
go
func (formatters FormatterArray) ApplyFormatter(msg *Message) error { for _, formatter := range formatters { if formatter.CanBeApplied(msg) { if err := formatter.ApplyFormatter(msg); err != nil { return err } } } return nil }
[ "func", "(", "formatters", "FormatterArray", ")", "ApplyFormatter", "(", "msg", "*", "Message", ")", "error", "{", "for", "_", ",", "formatter", ":=", "range", "formatters", "{", "if", "formatter", ".", "CanBeApplied", "(", "msg", ")", "{", "if", "err", ":=", "formatter", ".", "ApplyFormatter", "(", "msg", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ApplyFormatter calls ApplyFormatter on every formatter
[ "ApplyFormatter", "calls", "ApplyFormatter", "on", "every", "formatter" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/formatter.go#L33-L42
142,472
trivago/gollum
coordinator.go
NewCoordinator
func NewCoordinator() Coordinator { return Coordinator{ consumerWorker: new(sync.WaitGroup), producerWorker: new(sync.WaitGroup), state: coordinatorStateConfigure, } }
go
func NewCoordinator() Coordinator { return Coordinator{ consumerWorker: new(sync.WaitGroup), producerWorker: new(sync.WaitGroup), state: coordinatorStateConfigure, } }
[ "func", "NewCoordinator", "(", ")", "Coordinator", "{", "return", "Coordinator", "{", "consumerWorker", ":", "new", "(", "sync", ".", "WaitGroup", ")", ",", "producerWorker", ":", "new", "(", "sync", ".", "WaitGroup", ")", ",", "state", ":", "coordinatorStateConfigure", ",", "}", "\n", "}" ]
// NewCoordinator creates a new multplexer
[ "NewCoordinator", "creates", "a", "new", "multplexer" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/coordinator.go#L64-L70
142,473
trivago/gollum
coordinator.go
Configure
func (co *Coordinator) Configure(conf *core.Config) error { // Make sure the log is printed to the fallback device if we are stuck here logFallback := time.AfterFunc(time.Duration(3)*time.Second, func() { logrusHookBuffer.SetTargetWriter(logger.FallbackLogDevice) logrusHookBuffer.Purge() }) defer logFallback.Stop() // Initialize the plugins in the order of routers > producers > consumers // to match the order of reference between the different types. errors := tgo.NewErrorStack() errors.SetFormat(tgo.ErrorStackFormatCSV) if !co.configureRouters(conf) { errors.Pushf("At least one router failed to be configured") } if !co.configureProducers(conf) { errors.Pushf("At least one producer failed to be configured") } if !co.configureConsumers(conf) { errors.Pushf("At least one consumer failed to be configured") } if len(co.producers) == 0 { errors.Pushf("No valid producers found") } if len(co.consumers) <= 1 { errors.Pushf("No valid consumers found") } // As consumers might create new fallback router this is the first position // where we can add the wildcard producers to all streams. No new routers // created beyond this point must use StreamRegistry.AddWildcardProducersToRouter. core.StreamRegistry.AddAllWildcardProducersToAllRouters() return errors.OrNil() }
go
func (co *Coordinator) Configure(conf *core.Config) error { // Make sure the log is printed to the fallback device if we are stuck here logFallback := time.AfterFunc(time.Duration(3)*time.Second, func() { logrusHookBuffer.SetTargetWriter(logger.FallbackLogDevice) logrusHookBuffer.Purge() }) defer logFallback.Stop() // Initialize the plugins in the order of routers > producers > consumers // to match the order of reference between the different types. errors := tgo.NewErrorStack() errors.SetFormat(tgo.ErrorStackFormatCSV) if !co.configureRouters(conf) { errors.Pushf("At least one router failed to be configured") } if !co.configureProducers(conf) { errors.Pushf("At least one producer failed to be configured") } if !co.configureConsumers(conf) { errors.Pushf("At least one consumer failed to be configured") } if len(co.producers) == 0 { errors.Pushf("No valid producers found") } if len(co.consumers) <= 1 { errors.Pushf("No valid consumers found") } // As consumers might create new fallback router this is the first position // where we can add the wildcard producers to all streams. No new routers // created beyond this point must use StreamRegistry.AddWildcardProducersToRouter. core.StreamRegistry.AddAllWildcardProducersToAllRouters() return errors.OrNil() }
[ "func", "(", "co", "*", "Coordinator", ")", "Configure", "(", "conf", "*", "core", ".", "Config", ")", "error", "{", "// Make sure the log is printed to the fallback device if we are stuck here", "logFallback", ":=", "time", ".", "AfterFunc", "(", "time", ".", "Duration", "(", "3", ")", "*", "time", ".", "Second", ",", "func", "(", ")", "{", "logrusHookBuffer", ".", "SetTargetWriter", "(", "logger", ".", "FallbackLogDevice", ")", "\n", "logrusHookBuffer", ".", "Purge", "(", ")", "\n", "}", ")", "\n", "defer", "logFallback", ".", "Stop", "(", ")", "\n\n", "// Initialize the plugins in the order of routers > producers > consumers", "// to match the order of reference between the different types.", "errors", ":=", "tgo", ".", "NewErrorStack", "(", ")", "\n", "errors", ".", "SetFormat", "(", "tgo", ".", "ErrorStackFormatCSV", ")", "\n\n", "if", "!", "co", ".", "configureRouters", "(", "conf", ")", "{", "errors", ".", "Pushf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "!", "co", ".", "configureProducers", "(", "conf", ")", "{", "errors", ".", "Pushf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "!", "co", ".", "configureConsumers", "(", "conf", ")", "{", "errors", ".", "Pushf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "co", ".", "producers", ")", "==", "0", "{", "errors", ".", "Pushf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "co", ".", "consumers", ")", "<=", "1", "{", "errors", ".", "Pushf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// As consumers might create new fallback router this is the first position", "// where we can add the wildcard producers to all streams. No new routers", "// created beyond this point must use StreamRegistry.AddWildcardProducersToRouter.", "core", ".", "StreamRegistry", ".", "AddAllWildcardProducersToAllRouters", "(", ")", "\n", "return", "errors", ".", "OrNil", "(", ")", "\n", "}" ]
// Configure processes the config and instantiates all valid plugins
[ "Configure", "processes", "the", "config", "and", "instantiates", "all", "valid", "plugins" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/coordinator.go#L73-L108
142,474
trivago/gollum
coordinator.go
StartPlugins
func (co *Coordinator) StartPlugins() { // Launch routers for _, router := range co.routers { logrus.Debug("Starting ", reflect.TypeOf(router)) if err := router.Start(); err != nil { logrus.WithError(err).Errorf("Failed to start router of type '%s'", reflect.TypeOf(router)) } } // Launch producers co.state = coordinatorStateStartProducers for _, producer := range co.producers { producer := producer go tgo.WithRecoverShutdown(func() { logrus.Debug("Starting ", reflect.TypeOf(producer)) producer.Produce(co.producerWorker) }) } // Set final log target and purge the intermediate buffer if core.StreamRegistry.IsStreamRegistered(core.LogInternalStreamID) { // The _GOLLUM_ stream has listeners, so use LogConsumer to write to it if *flagLogColors == "always" { logrus.SetFormatter(logger.NewConsoleFormatter()) } logrusHookBuffer.SetTargetHook(co.logConsumer) logrusHookBuffer.Purge() } else { logrusHookBuffer.SetTargetWriter(logger.FallbackLogDevice) logrusHookBuffer.Purge() } // Launch consumers co.state = coordinatorStateStartConsumers for _, consumer := range co.consumers { consumer := consumer go tgo.WithRecoverShutdown(func() { logrus.Debug("Starting ", reflect.TypeOf(consumer)) consumer.Consume(co.consumerWorker) }) } }
go
func (co *Coordinator) StartPlugins() { // Launch routers for _, router := range co.routers { logrus.Debug("Starting ", reflect.TypeOf(router)) if err := router.Start(); err != nil { logrus.WithError(err).Errorf("Failed to start router of type '%s'", reflect.TypeOf(router)) } } // Launch producers co.state = coordinatorStateStartProducers for _, producer := range co.producers { producer := producer go tgo.WithRecoverShutdown(func() { logrus.Debug("Starting ", reflect.TypeOf(producer)) producer.Produce(co.producerWorker) }) } // Set final log target and purge the intermediate buffer if core.StreamRegistry.IsStreamRegistered(core.LogInternalStreamID) { // The _GOLLUM_ stream has listeners, so use LogConsumer to write to it if *flagLogColors == "always" { logrus.SetFormatter(logger.NewConsoleFormatter()) } logrusHookBuffer.SetTargetHook(co.logConsumer) logrusHookBuffer.Purge() } else { logrusHookBuffer.SetTargetWriter(logger.FallbackLogDevice) logrusHookBuffer.Purge() } // Launch consumers co.state = coordinatorStateStartConsumers for _, consumer := range co.consumers { consumer := consumer go tgo.WithRecoverShutdown(func() { logrus.Debug("Starting ", reflect.TypeOf(consumer)) consumer.Consume(co.consumerWorker) }) } }
[ "func", "(", "co", "*", "Coordinator", ")", "StartPlugins", "(", ")", "{", "// Launch routers", "for", "_", ",", "router", ":=", "range", "co", ".", "routers", "{", "logrus", ".", "Debug", "(", "\"", "\"", ",", "reflect", ".", "TypeOf", "(", "router", ")", ")", "\n", "if", "err", ":=", "router", ".", "Start", "(", ")", ";", "err", "!=", "nil", "{", "logrus", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "\"", "\"", ",", "reflect", ".", "TypeOf", "(", "router", ")", ")", "\n", "}", "\n", "}", "\n\n", "// Launch producers", "co", ".", "state", "=", "coordinatorStateStartProducers", "\n", "for", "_", ",", "producer", ":=", "range", "co", ".", "producers", "{", "producer", ":=", "producer", "\n", "go", "tgo", ".", "WithRecoverShutdown", "(", "func", "(", ")", "{", "logrus", ".", "Debug", "(", "\"", "\"", ",", "reflect", ".", "TypeOf", "(", "producer", ")", ")", "\n", "producer", ".", "Produce", "(", "co", ".", "producerWorker", ")", "\n", "}", ")", "\n", "}", "\n\n", "// Set final log target and purge the intermediate buffer", "if", "core", ".", "StreamRegistry", ".", "IsStreamRegistered", "(", "core", ".", "LogInternalStreamID", ")", "{", "// The _GOLLUM_ stream has listeners, so use LogConsumer to write to it", "if", "*", "flagLogColors", "==", "\"", "\"", "{", "logrus", ".", "SetFormatter", "(", "logger", ".", "NewConsoleFormatter", "(", ")", ")", "\n", "}", "\n", "logrusHookBuffer", ".", "SetTargetHook", "(", "co", ".", "logConsumer", ")", "\n", "logrusHookBuffer", ".", "Purge", "(", ")", "\n\n", "}", "else", "{", "logrusHookBuffer", ".", "SetTargetWriter", "(", "logger", ".", "FallbackLogDevice", ")", "\n", "logrusHookBuffer", ".", "Purge", "(", ")", "\n", "}", "\n\n", "// Launch consumers", "co", ".", "state", "=", "coordinatorStateStartConsumers", "\n", "for", "_", ",", "consumer", ":=", "range", "co", ".", "consumers", "{", "consumer", ":=", "consumer", "\n", "go", "tgo", ".", "WithRecoverShutdown", "(", "func", "(", ")", "{", "logrus", ".", "Debug", "(", "\"", "\"", ",", "reflect", ".", "TypeOf", "(", "consumer", ")", ")", "\n", "consumer", ".", "Consume", "(", "co", ".", "consumerWorker", ")", "\n", "}", ")", "\n", "}", "\n", "}" ]
// StartPlugins starts all plugins in the correct order.
[ "StartPlugins", "starts", "all", "plugins", "in", "the", "correct", "order", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/coordinator.go#L111-L153
142,475
trivago/gollum
coordinator.go
Run
func (co *Coordinator) Run() { co.signal = newSignalHandler() defer signal.Stop(co.signal) logrus.Info("We be nice to them, if they be nice to us. (startup)") for { sig := <-co.signal switch translateSignal(sig) { case signalExit: logrus.Info("Master betrayed us. Wicked. Tricksy, False. (signal)") return // ### return, exit requested ### case signalRoll: for _, consumer := range co.consumers { consumer.Control() <- core.PluginControlRoll } for _, producer := range co.producers { producer.Control() <- core.PluginControlRoll } default: } } }
go
func (co *Coordinator) Run() { co.signal = newSignalHandler() defer signal.Stop(co.signal) logrus.Info("We be nice to them, if they be nice to us. (startup)") for { sig := <-co.signal switch translateSignal(sig) { case signalExit: logrus.Info("Master betrayed us. Wicked. Tricksy, False. (signal)") return // ### return, exit requested ### case signalRoll: for _, consumer := range co.consumers { consumer.Control() <- core.PluginControlRoll } for _, producer := range co.producers { producer.Control() <- core.PluginControlRoll } default: } } }
[ "func", "(", "co", "*", "Coordinator", ")", "Run", "(", ")", "{", "co", ".", "signal", "=", "newSignalHandler", "(", ")", "\n", "defer", "signal", ".", "Stop", "(", "co", ".", "signal", ")", "\n\n", "logrus", ".", "Info", "(", "\"", "\"", ")", "\n\n", "for", "{", "sig", ":=", "<-", "co", ".", "signal", "\n", "switch", "translateSignal", "(", "sig", ")", "{", "case", "signalExit", ":", "logrus", ".", "Info", "(", "\"", "\"", ")", "\n", "return", "// ### return, exit requested ###", "\n\n", "case", "signalRoll", ":", "for", "_", ",", "consumer", ":=", "range", "co", ".", "consumers", "{", "consumer", ".", "Control", "(", ")", "<-", "core", ".", "PluginControlRoll", "\n", "}", "\n", "for", "_", ",", "producer", ":=", "range", "co", ".", "producers", "{", "producer", ".", "Control", "(", ")", "<-", "core", ".", "PluginControlRoll", "\n", "}", "\n\n", "default", ":", "}", "\n", "}", "\n", "}" ]
// Run is essentially the Coordinator main loop. // It listens for shutdown signals and updates global metrics
[ "Run", "is", "essentially", "the", "Coordinator", "main", "loop", ".", "It", "listens", "for", "shutdown", "signals", "and", "updates", "global", "metrics" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/coordinator.go#L157-L181
142,476
trivago/gollum
coordinator.go
Shutdown
func (co *Coordinator) Shutdown() { logrus.Info("Filthy little hobbites. They stole it from us. (shutdown)") stateAtShutdown := co.state co.state = coordinatorStateShutdown co.shutdownConsumers(stateAtShutdown) // Make sure remaining warning / errors are written to stderr logrus.Info("I'm not listening... I'm not listening... (flushing)") logrusHookBuffer.SetTargetWriter(logger.FallbackLogDevice) logrusHookBuffer.SetTargetHook(nil) logrusHookBuffer.Purge() // Shutdown producers co.shutdownProducers(stateAtShutdown) co.state = coordinatorStateStopped }
go
func (co *Coordinator) Shutdown() { logrus.Info("Filthy little hobbites. They stole it from us. (shutdown)") stateAtShutdown := co.state co.state = coordinatorStateShutdown co.shutdownConsumers(stateAtShutdown) // Make sure remaining warning / errors are written to stderr logrus.Info("I'm not listening... I'm not listening... (flushing)") logrusHookBuffer.SetTargetWriter(logger.FallbackLogDevice) logrusHookBuffer.SetTargetHook(nil) logrusHookBuffer.Purge() // Shutdown producers co.shutdownProducers(stateAtShutdown) co.state = coordinatorStateStopped }
[ "func", "(", "co", "*", "Coordinator", ")", "Shutdown", "(", ")", "{", "logrus", ".", "Info", "(", "\"", "\"", ")", "\n\n", "stateAtShutdown", ":=", "co", ".", "state", "\n", "co", ".", "state", "=", "coordinatorStateShutdown", "\n\n", "co", ".", "shutdownConsumers", "(", "stateAtShutdown", ")", "\n\n", "// Make sure remaining warning / errors are written to stderr", "logrus", ".", "Info", "(", "\"", "\"", ")", "\n", "logrusHookBuffer", ".", "SetTargetWriter", "(", "logger", ".", "FallbackLogDevice", ")", "\n", "logrusHookBuffer", ".", "SetTargetHook", "(", "nil", ")", "\n", "logrusHookBuffer", ".", "Purge", "(", ")", "\n\n", "// Shutdown producers", "co", ".", "shutdownProducers", "(", "stateAtShutdown", ")", "\n\n", "co", ".", "state", "=", "coordinatorStateStopped", "\n", "}" ]
// Shutdown all consumers and producers in a clean way. // The internal log is flushed after the consumers have been shut down so that // consumer related messages are still in the tlog. // Producers are flushed after flushing the log, so producer related shutdown // messages will be posted to stdout
[ "Shutdown", "all", "consumers", "and", "producers", "in", "a", "clean", "way", ".", "The", "internal", "log", "is", "flushed", "after", "the", "consumers", "have", "been", "shut", "down", "so", "that", "consumer", "related", "messages", "are", "still", "in", "the", "tlog", ".", "Producers", "are", "flushed", "after", "flushing", "the", "log", "so", "producer", "related", "shutdown", "messages", "will", "be", "posted", "to", "stdout" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/coordinator.go#L188-L206
142,477
trivago/gollum
core/simplerouter.go
Configure
func (router *SimpleRouter) Configure(conf PluginConfigReader) { router.id = conf.GetID() router.Logger = conf.GetLogger() if router.streamID == WildcardStreamID && strings.Index(router.id, GeneratedRouterPrefix) != 0 { router.Logger.Info("A wildcard stream configuration only affects the wildcard stream, not all routers") } }
go
func (router *SimpleRouter) Configure(conf PluginConfigReader) { router.id = conf.GetID() router.Logger = conf.GetLogger() if router.streamID == WildcardStreamID && strings.Index(router.id, GeneratedRouterPrefix) != 0 { router.Logger.Info("A wildcard stream configuration only affects the wildcard stream, not all routers") } }
[ "func", "(", "router", "*", "SimpleRouter", ")", "Configure", "(", "conf", "PluginConfigReader", ")", "{", "router", ".", "id", "=", "conf", ".", "GetID", "(", ")", "\n", "router", ".", "Logger", "=", "conf", ".", "GetLogger", "(", ")", "\n\n", "if", "router", ".", "streamID", "==", "WildcardStreamID", "&&", "strings", ".", "Index", "(", "router", ".", "id", ",", "GeneratedRouterPrefix", ")", "!=", "0", "{", "router", ".", "Logger", ".", "Info", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// Configure sets up all values required by SimpleRouter.
[ "Configure", "sets", "up", "all", "values", "required", "by", "SimpleRouter", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/simplerouter.go#L51-L58
142,478
trivago/gollum
core/simplerouter.go
AddProducer
func (router *SimpleRouter) AddProducer(producers ...Producer) { for _, prod := range producers { for _, inListProd := range router.Producers { if inListProd == prod { return // ### return, already in list ### } } router.Producers = append(router.Producers, prod) } }
go
func (router *SimpleRouter) AddProducer(producers ...Producer) { for _, prod := range producers { for _, inListProd := range router.Producers { if inListProd == prod { return // ### return, already in list ### } } router.Producers = append(router.Producers, prod) } }
[ "func", "(", "router", "*", "SimpleRouter", ")", "AddProducer", "(", "producers", "...", "Producer", ")", "{", "for", "_", ",", "prod", ":=", "range", "producers", "{", "for", "_", ",", "inListProd", ":=", "range", "router", ".", "Producers", "{", "if", "inListProd", "==", "prod", "{", "return", "// ### return, already in list ###", "\n", "}", "\n", "}", "\n", "router", ".", "Producers", "=", "append", "(", "router", ".", "Producers", ",", "prod", ")", "\n", "}", "\n", "}" ]
// AddProducer adds all producers to the list of known producers. // Duplicates will be filtered.
[ "AddProducer", "adds", "all", "producers", "to", "the", "list", "of", "known", "producers", ".", "Duplicates", "will", "be", "filtered", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/simplerouter.go#L92-L101
142,479
trivago/gollum
core/simplerouter.go
Modulate
func (router *SimpleRouter) Modulate(msg *Message) ModulateResult { mod := NewFilterModulator(router.filters) return mod.Modulate(msg) }
go
func (router *SimpleRouter) Modulate(msg *Message) ModulateResult { mod := NewFilterModulator(router.filters) return mod.Modulate(msg) }
[ "func", "(", "router", "*", "SimpleRouter", ")", "Modulate", "(", "msg", "*", "Message", ")", "ModulateResult", "{", "mod", ":=", "NewFilterModulator", "(", "router", ".", "filters", ")", "\n", "return", "mod", ".", "Modulate", "(", "msg", ")", "\n", "}" ]
// Modulate calls all modulators in their order of definition
[ "Modulate", "calls", "all", "modulators", "in", "their", "order", "of", "definition" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/simplerouter.go#L109-L112
142,480
trivago/gollum
producer/awss3/batchedFileWriter.go
init
func (w *BatchedFileWriter) init() { w.totalSize = 0 w.currentMultiPart = 0 w.completedParts = []*s3.CompletedPart{} w.activeBuffer = newS3ByteBuffer() w.createMultipartUpload() }
go
func (w *BatchedFileWriter) init() { w.totalSize = 0 w.currentMultiPart = 0 w.completedParts = []*s3.CompletedPart{} w.activeBuffer = newS3ByteBuffer() w.createMultipartUpload() }
[ "func", "(", "w", "*", "BatchedFileWriter", ")", "init", "(", ")", "{", "w", ".", "totalSize", "=", "0", "\n", "w", ".", "currentMultiPart", "=", "0", "\n", "w", ".", "completedParts", "=", "[", "]", "*", "s3", ".", "CompletedPart", "{", "}", "\n", "w", ".", "activeBuffer", "=", "newS3ByteBuffer", "(", ")", "\n\n", "w", ".", "createMultipartUpload", "(", ")", "\n", "}" ]
// init BatchedFileWriter struct
[ "init", "BatchedFileWriter", "struct" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/producer/awss3/batchedFileWriter.go#L78-L85
142,481
trivago/gollum
core/pluginregistry.go
GetPlugin
func (registry *pluginRegistry) GetPlugin(ID string) Plugin { registry.guard.RLock() plugin, exists := registry.plugins[ID] registry.guard.RUnlock() if exists { return plugin } return nil }
go
func (registry *pluginRegistry) GetPlugin(ID string) Plugin { registry.guard.RLock() plugin, exists := registry.plugins[ID] registry.guard.RUnlock() if exists { return plugin } return nil }
[ "func", "(", "registry", "*", "pluginRegistry", ")", "GetPlugin", "(", "ID", "string", ")", "Plugin", "{", "registry", ".", "guard", ".", "RLock", "(", ")", "\n", "plugin", ",", "exists", ":=", "registry", ".", "plugins", "[", "ID", "]", "\n", "registry", ".", "guard", ".", "RUnlock", "(", ")", "\n\n", "if", "exists", "{", "return", "plugin", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GetPlugin returns a plugin by name or nil if not found.
[ "GetPlugin", "returns", "a", "plugin", "by", "name", "or", "nil", "if", "not", "found", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginregistry.go#L47-L56
142,482
trivago/gollum
core/pluginregistry.go
GetPluginWithState
func (registry *pluginRegistry) GetPluginWithState(ID string) PluginWithState { plugin := registry.GetPlugin(ID) if pluginWithState, hasState := plugin.(PluginWithState); hasState { return pluginWithState } return nil }
go
func (registry *pluginRegistry) GetPluginWithState(ID string) PluginWithState { plugin := registry.GetPlugin(ID) if pluginWithState, hasState := plugin.(PluginWithState); hasState { return pluginWithState } return nil }
[ "func", "(", "registry", "*", "pluginRegistry", ")", "GetPluginWithState", "(", "ID", "string", ")", "PluginWithState", "{", "plugin", ":=", "registry", ".", "GetPlugin", "(", "ID", ")", "\n", "if", "pluginWithState", ",", "hasState", ":=", "plugin", ".", "(", "PluginWithState", ")", ";", "hasState", "{", "return", "pluginWithState", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GetPluginWithState returns a plugin by name if it has a state or nil.
[ "GetPluginWithState", "returns", "a", "plugin", "by", "name", "if", "it", "has", "a", "state", "or", "nil", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/pluginregistry.go#L59-L65
142,483
trivago/gollum
core/messagebatch.go
AppendOrBlock
func (batch *MessageBatch) AppendOrBlock(msg *Message) bool { spin := tsync.NewSpinner(tsync.SpinPriorityMedium) for !batch.IsClosed() { if batch.Append(msg) { return true // ### return, success ### } spin.Yield() } return false }
go
func (batch *MessageBatch) AppendOrBlock(msg *Message) bool { spin := tsync.NewSpinner(tsync.SpinPriorityMedium) for !batch.IsClosed() { if batch.Append(msg) { return true // ### return, success ### } spin.Yield() } return false }
[ "func", "(", "batch", "*", "MessageBatch", ")", "AppendOrBlock", "(", "msg", "*", "Message", ")", "bool", "{", "spin", ":=", "tsync", ".", "NewSpinner", "(", "tsync", ".", "SpinPriorityMedium", ")", "\n", "for", "!", "batch", ".", "IsClosed", "(", ")", "{", "if", "batch", ".", "Append", "(", "msg", ")", "{", "return", "true", "// ### return, success ###", "\n", "}", "\n", "spin", ".", "Yield", "(", ")", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// AppendOrBlock works like Append but will block until Append returns true. // If the batch was closed during this call, false is returned.
[ "AppendOrBlock", "works", "like", "Append", "but", "will", "block", "until", "Append", "returns", "true", ".", "If", "the", "batch", "was", "closed", "during", "this", "call", "false", "is", "returned", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/messagebatch.go#L110-L120
142,484
trivago/gollum
core/messagebatch.go
Touch
func (batch *MessageBatch) Touch() { atomic.StoreInt64(batch.lastFlush, time.Now().Unix()) }
go
func (batch *MessageBatch) Touch() { atomic.StoreInt64(batch.lastFlush, time.Now().Unix()) }
[ "func", "(", "batch", "*", "MessageBatch", ")", "Touch", "(", ")", "{", "atomic", ".", "StoreInt64", "(", "batch", ".", "lastFlush", ",", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", ")", "\n", "}" ]
// Touch resets the timer queried by ReachedTimeThreshold, i.e. this resets the // automatic flush timeout
[ "Touch", "resets", "the", "timer", "queried", "by", "ReachedTimeThreshold", "i", ".", "e", ".", "this", "resets", "the", "automatic", "flush", "timeout" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/messagebatch.go#L137-L139
142,485
trivago/gollum
core/messagebatch.go
Close
func (batch *MessageBatch) Close(assemble AssemblyFunc, timeout time.Duration) { atomic.StoreInt32(batch.closed, 1) batch.Flush(assemble) batch.WaitForFlush(timeout) }
go
func (batch *MessageBatch) Close(assemble AssemblyFunc, timeout time.Duration) { atomic.StoreInt32(batch.closed, 1) batch.Flush(assemble) batch.WaitForFlush(timeout) }
[ "func", "(", "batch", "*", "MessageBatch", ")", "Close", "(", "assemble", "AssemblyFunc", ",", "timeout", "time", ".", "Duration", ")", "{", "atomic", ".", "StoreInt32", "(", "batch", ".", "closed", ",", "1", ")", "\n", "batch", ".", "Flush", "(", "assemble", ")", "\n", "batch", ".", "WaitForFlush", "(", "timeout", ")", "\n", "}" ]
// Close disables Append, calls flush and waits for this call to finish. // Timeout is passed to WaitForFlush.
[ "Close", "disables", "Append", "calls", "flush", "and", "waits", "for", "this", "call", "to", "finish", ".", "Timeout", "is", "passed", "to", "WaitForFlush", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/messagebatch.go#L143-L147
142,486
trivago/gollum
core/messagebatch.go
AfterFlushDo
func (batch *MessageBatch) AfterFlushDo(callback func() error) error { batch.flushing.IncWhenDone() defer batch.flushing.Done() return callback() }
go
func (batch *MessageBatch) AfterFlushDo(callback func() error) error { batch.flushing.IncWhenDone() defer batch.flushing.Done() return callback() }
[ "func", "(", "batch", "*", "MessageBatch", ")", "AfterFlushDo", "(", "callback", "func", "(", ")", "error", ")", "error", "{", "batch", ".", "flushing", ".", "IncWhenDone", "(", ")", "\n", "defer", "batch", ".", "flushing", ".", "Done", "(", ")", "\n", "return", "callback", "(", ")", "\n", "}" ]
// AfterFlushDo calls a function after a currently running flush is done. // It also blocks any flush during the execution of callback. // Returns the error returned by callback
[ "AfterFlushDo", "calls", "a", "function", "after", "a", "currently", "running", "flush", "is", "done", ".", "It", "also", "blocks", "any", "flush", "during", "the", "execution", "of", "callback", ".", "Returns", "the", "error", "returned", "by", "callback" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/messagebatch.go#L201-L205
142,487
trivago/gollum
core/messagebatch.go
WaitForFlush
func (batch *MessageBatch) WaitForFlush(timeout time.Duration) { batch.flushing.WaitFor(timeout) }
go
func (batch *MessageBatch) WaitForFlush(timeout time.Duration) { batch.flushing.WaitFor(timeout) }
[ "func", "(", "batch", "*", "MessageBatch", ")", "WaitForFlush", "(", "timeout", "time", ".", "Duration", ")", "{", "batch", ".", "flushing", ".", "WaitFor", "(", "timeout", ")", "\n", "}" ]
// WaitForFlush blocks until the current flush command returns. // Passing a timeout > 0 will unblock this function after the given duration at // the latest.
[ "WaitForFlush", "blocks", "until", "the", "current", "flush", "command", "returns", ".", "Passing", "a", "timeout", ">", "0", "will", "unblock", "this", "function", "after", "the", "given", "duration", "at", "the", "latest", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/messagebatch.go#L210-L212
142,488
trivago/gollum
core/messagebatch.go
ReachedSizeThreshold
func (batch MessageBatch) ReachedSizeThreshold(size int) bool { activeIdx := atomic.LoadUint32(batch.activeSet) >> messageBatchIndexShift threshold := uint32(tmath.MaxI(size, len(batch.queue[activeIdx].messages))) return atomic.LoadUint32(batch.queue[activeIdx].doneCount) >= threshold }
go
func (batch MessageBatch) ReachedSizeThreshold(size int) bool { activeIdx := atomic.LoadUint32(batch.activeSet) >> messageBatchIndexShift threshold := uint32(tmath.MaxI(size, len(batch.queue[activeIdx].messages))) return atomic.LoadUint32(batch.queue[activeIdx].doneCount) >= threshold }
[ "func", "(", "batch", "MessageBatch", ")", "ReachedSizeThreshold", "(", "size", "int", ")", "bool", "{", "activeIdx", ":=", "atomic", ".", "LoadUint32", "(", "batch", ".", "activeSet", ")", ">>", "messageBatchIndexShift", "\n", "threshold", ":=", "uint32", "(", "tmath", ".", "MaxI", "(", "size", ",", "len", "(", "batch", ".", "queue", "[", "activeIdx", "]", ".", "messages", ")", ")", ")", "\n", "return", "atomic", ".", "LoadUint32", "(", "batch", ".", "queue", "[", "activeIdx", "]", ".", "doneCount", ")", ">=", "threshold", "\n", "}" ]
// ReachedSizeThreshold returns true if the bytes stored in the buffer are // above or equal to the size given. // If there is no data this function returns false.
[ "ReachedSizeThreshold", "returns", "true", "if", "the", "bytes", "stored", "in", "the", "buffer", "are", "above", "or", "equal", "to", "the", "size", "given", ".", "If", "there", "is", "no", "data", "this", "function", "returns", "false", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/messagebatch.go#L223-L227
142,489
trivago/gollum
core/messagebatch.go
ReachedTimeThreshold
func (batch MessageBatch) ReachedTimeThreshold(timeout time.Duration) bool { lastFlush := time.Unix(atomic.LoadInt64(batch.lastFlush), 0) return !batch.IsEmpty() && time.Since(lastFlush) > timeout }
go
func (batch MessageBatch) ReachedTimeThreshold(timeout time.Duration) bool { lastFlush := time.Unix(atomic.LoadInt64(batch.lastFlush), 0) return !batch.IsEmpty() && time.Since(lastFlush) > timeout }
[ "func", "(", "batch", "MessageBatch", ")", "ReachedTimeThreshold", "(", "timeout", "time", ".", "Duration", ")", "bool", "{", "lastFlush", ":=", "time", ".", "Unix", "(", "atomic", ".", "LoadInt64", "(", "batch", ".", "lastFlush", ")", ",", "0", ")", "\n", "return", "!", "batch", ".", "IsEmpty", "(", ")", "&&", "time", ".", "Since", "(", "lastFlush", ")", ">", "timeout", "\n", "}" ]
// ReachedTimeThreshold returns true if the last flush was more than timeout ago. // If there is no data this function returns false.
[ "ReachedTimeThreshold", "returns", "true", "if", "the", "last", "flush", "was", "more", "than", "timeout", "ago", ".", "If", "there", "is", "no", "data", "this", "function", "returns", "false", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/messagebatch.go#L231-L234
142,490
trivago/gollum
core/config.go
ReadConfig
func ReadConfig(buffer []byte) (*Config, error) { config := new(Config) if err := yaml.Unmarshal(buffer, &config.Values); err != nil { return nil, err } // As there might be multiple instances of the same plugin class we iterate // over an array here. hasError := false for pluginID, configValues := range config.Values { if typeName, _ := configValues.String("Type"); typeName == pluginAggregate { // aggregate behavior aggregateMap, err := configValues.MarshalMap("Plugins") if err != nil { hasError = true logrus.Error("Can't read 'Aggregate' configuration: ", err) continue } // loop through aggregated plugins and set them up for subPluginID, subConfigValues := range aggregateMap { subPluginsID := fmt.Sprintf("%s-%s", pluginID, subPluginID) subConfig, err := tcontainer.ConvertToMarshalMap(subConfigValues, nil) if err != nil { hasError = true logrus.Error("Error in plugin config ", subPluginsID, err) continue } // set up sub-plugin delete(configValues, "Type") delete(configValues, "Plugins") pluginConfig := NewPluginConfig(subPluginsID, "") pluginConfig.Read(configValues) pluginConfig.Read(subConfig) config.Plugins = append(config.Plugins, pluginConfig) } } else { // default behavior pluginConfig := NewPluginConfig(pluginID, "") pluginConfig.Read(configValues) config.Plugins = append(config.Plugins, pluginConfig) } } if hasError { return config, fmt.Errorf("configuration parsing produced errors") } return config, nil }
go
func ReadConfig(buffer []byte) (*Config, error) { config := new(Config) if err := yaml.Unmarshal(buffer, &config.Values); err != nil { return nil, err } // As there might be multiple instances of the same plugin class we iterate // over an array here. hasError := false for pluginID, configValues := range config.Values { if typeName, _ := configValues.String("Type"); typeName == pluginAggregate { // aggregate behavior aggregateMap, err := configValues.MarshalMap("Plugins") if err != nil { hasError = true logrus.Error("Can't read 'Aggregate' configuration: ", err) continue } // loop through aggregated plugins and set them up for subPluginID, subConfigValues := range aggregateMap { subPluginsID := fmt.Sprintf("%s-%s", pluginID, subPluginID) subConfig, err := tcontainer.ConvertToMarshalMap(subConfigValues, nil) if err != nil { hasError = true logrus.Error("Error in plugin config ", subPluginsID, err) continue } // set up sub-plugin delete(configValues, "Type") delete(configValues, "Plugins") pluginConfig := NewPluginConfig(subPluginsID, "") pluginConfig.Read(configValues) pluginConfig.Read(subConfig) config.Plugins = append(config.Plugins, pluginConfig) } } else { // default behavior pluginConfig := NewPluginConfig(pluginID, "") pluginConfig.Read(configValues) config.Plugins = append(config.Plugins, pluginConfig) } } if hasError { return config, fmt.Errorf("configuration parsing produced errors") } return config, nil }
[ "func", "ReadConfig", "(", "buffer", "[", "]", "byte", ")", "(", "*", "Config", ",", "error", ")", "{", "config", ":=", "new", "(", "Config", ")", "\n", "if", "err", ":=", "yaml", ".", "Unmarshal", "(", "buffer", ",", "&", "config", ".", "Values", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// As there might be multiple instances of the same plugin class we iterate", "// over an array here.", "hasError", ":=", "false", "\n", "for", "pluginID", ",", "configValues", ":=", "range", "config", ".", "Values", "{", "if", "typeName", ",", "_", ":=", "configValues", ".", "String", "(", "\"", "\"", ")", ";", "typeName", "==", "pluginAggregate", "{", "// aggregate behavior", "aggregateMap", ",", "err", ":=", "configValues", ".", "MarshalMap", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "hasError", "=", "true", "\n", "logrus", ".", "Error", "(", "\"", "\"", ",", "err", ")", "\n", "continue", "\n", "}", "\n\n", "// loop through aggregated plugins and set them up", "for", "subPluginID", ",", "subConfigValues", ":=", "range", "aggregateMap", "{", "subPluginsID", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "pluginID", ",", "subPluginID", ")", "\n", "subConfig", ",", "err", ":=", "tcontainer", ".", "ConvertToMarshalMap", "(", "subConfigValues", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "hasError", "=", "true", "\n", "logrus", ".", "Error", "(", "\"", "\"", ",", "subPluginsID", ",", "err", ")", "\n", "continue", "\n", "}", "\n\n", "// set up sub-plugin", "delete", "(", "configValues", ",", "\"", "\"", ")", "\n", "delete", "(", "configValues", ",", "\"", "\"", ")", "\n\n", "pluginConfig", ":=", "NewPluginConfig", "(", "subPluginsID", ",", "\"", "\"", ")", "\n", "pluginConfig", ".", "Read", "(", "configValues", ")", "\n", "pluginConfig", ".", "Read", "(", "subConfig", ")", "\n\n", "config", ".", "Plugins", "=", "append", "(", "config", ".", "Plugins", ",", "pluginConfig", ")", "\n", "}", "\n", "}", "else", "{", "// default behavior", "pluginConfig", ":=", "NewPluginConfig", "(", "pluginID", ",", "\"", "\"", ")", "\n", "pluginConfig", ".", "Read", "(", "configValues", ")", "\n", "config", ".", "Plugins", "=", "append", "(", "config", ".", "Plugins", ",", "pluginConfig", ")", "\n", "}", "\n", "}", "\n\n", "if", "hasError", "{", "return", "config", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "config", ",", "nil", "\n", "}" ]
// ReadConfig creates a config from a yaml byte stream.
[ "ReadConfig", "creates", "a", "config", "from", "a", "yaml", "byte", "stream", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/config.go#L44-L95
142,491
trivago/gollum
core/config.go
ReadConfigFromFile
func ReadConfigFromFile(path string) (*Config, error) { buffer, err := ioutil.ReadFile(path) if err != nil { return nil, err } return ReadConfig(buffer) }
go
func ReadConfigFromFile(path string) (*Config, error) { buffer, err := ioutil.ReadFile(path) if err != nil { return nil, err } return ReadConfig(buffer) }
[ "func", "ReadConfigFromFile", "(", "path", "string", ")", "(", "*", "Config", ",", "error", ")", "{", "buffer", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "ReadConfig", "(", "buffer", ")", "\n", "}" ]
// ReadConfigFromFile parses a YAML config file into a new Config struct.
[ "ReadConfigFromFile", "parses", "a", "YAML", "config", "file", "into", "a", "new", "Config", "struct", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/config.go#L98-L105
142,492
trivago/gollum
core/config.go
Validate
func (conf *Config) Validate() error { errors := tgo.NewErrorStack() errors.SetFormat(tgo.ErrorStackFormatCSV) for _, config := range conf.Plugins { if config.Typename == "" { errors.Pushf("Plugin type is not set for '%s'", config.ID) continue } pluginType := TypeRegistry.GetTypeOf(config.Typename) if pluginType == nil { if suggestion := suggestType(config.Typename); suggestion != "" { errors.Pushf("Type '%s' used for '%s' not found. Did you mean '%s'?", config.Typename, config.ID, suggestion) } else { errors.Pushf("Type '%s' used for '%s' not found", config.Typename, config.ID) } continue // ### continue ### } switch { case pluginType.Implements(consumerInterface): continue case pluginType.Implements(producerInterface): continue case pluginType.Implements(routerInterface): continue } errors.Pushf("Type '%s' used for '%s' does not implement a common interface", config.Typename, config.ID) getClosestMatch(pluginType, &errors) } return errors.OrNil() }
go
func (conf *Config) Validate() error { errors := tgo.NewErrorStack() errors.SetFormat(tgo.ErrorStackFormatCSV) for _, config := range conf.Plugins { if config.Typename == "" { errors.Pushf("Plugin type is not set for '%s'", config.ID) continue } pluginType := TypeRegistry.GetTypeOf(config.Typename) if pluginType == nil { if suggestion := suggestType(config.Typename); suggestion != "" { errors.Pushf("Type '%s' used for '%s' not found. Did you mean '%s'?", config.Typename, config.ID, suggestion) } else { errors.Pushf("Type '%s' used for '%s' not found", config.Typename, config.ID) } continue // ### continue ### } switch { case pluginType.Implements(consumerInterface): continue case pluginType.Implements(producerInterface): continue case pluginType.Implements(routerInterface): continue } errors.Pushf("Type '%s' used for '%s' does not implement a common interface", config.Typename, config.ID) getClosestMatch(pluginType, &errors) } return errors.OrNil() }
[ "func", "(", "conf", "*", "Config", ")", "Validate", "(", ")", "error", "{", "errors", ":=", "tgo", ".", "NewErrorStack", "(", ")", "\n", "errors", ".", "SetFormat", "(", "tgo", ".", "ErrorStackFormatCSV", ")", "\n\n", "for", "_", ",", "config", ":=", "range", "conf", ".", "Plugins", "{", "if", "config", ".", "Typename", "==", "\"", "\"", "{", "errors", ".", "Pushf", "(", "\"", "\"", ",", "config", ".", "ID", ")", "\n", "continue", "\n", "}", "\n\n", "pluginType", ":=", "TypeRegistry", ".", "GetTypeOf", "(", "config", ".", "Typename", ")", "\n", "if", "pluginType", "==", "nil", "{", "if", "suggestion", ":=", "suggestType", "(", "config", ".", "Typename", ")", ";", "suggestion", "!=", "\"", "\"", "{", "errors", ".", "Pushf", "(", "\"", "\"", ",", "config", ".", "Typename", ",", "config", ".", "ID", ",", "suggestion", ")", "\n", "}", "else", "{", "errors", ".", "Pushf", "(", "\"", "\"", ",", "config", ".", "Typename", ",", "config", ".", "ID", ")", "\n", "}", "\n\n", "continue", "// ### continue ###", "\n", "}", "\n\n", "switch", "{", "case", "pluginType", ".", "Implements", "(", "consumerInterface", ")", ":", "continue", "\n\n", "case", "pluginType", ".", "Implements", "(", "producerInterface", ")", ":", "continue", "\n\n", "case", "pluginType", ".", "Implements", "(", "routerInterface", ")", ":", "continue", "\n", "}", "\n\n", "errors", ".", "Pushf", "(", "\"", "\"", ",", "config", ".", "Typename", ",", "config", ".", "ID", ")", "\n", "getClosestMatch", "(", "pluginType", ",", "&", "errors", ")", "\n", "}", "\n\n", "return", "errors", ".", "OrNil", "(", ")", "\n", "}" ]
// Validate checks all plugin configs and plugins on validity. I.e. it checks // on mandatory fields and correct implementation of consumer, producer or // stream interface. It does NOT call configure for each plugin.
[ "Validate", "checks", "all", "plugin", "configs", "and", "plugins", "on", "validity", ".", "I", ".", "e", ".", "it", "checks", "on", "mandatory", "fields", "and", "correct", "implementation", "of", "consumer", "producer", "or", "stream", "interface", ".", "It", "does", "NOT", "call", "configure", "for", "each", "plugin", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/config.go#L110-L147
142,493
trivago/gollum
core/config.go
GetConsumers
func (conf *Config) GetConsumers() []PluginConfig { configs := []PluginConfig{} for _, config := range conf.Plugins { if !config.Enable || config.Typename == "" { continue // ### continue, disabled ### } pluginType := TypeRegistry.GetTypeOf(config.Typename) if pluginType == nil { continue // ### continue, unknown type ### } if pluginType.Implements(consumerInterface) { logrus.Debug("Found consumer ", config.ID) configs = append(configs, config) } } return configs }
go
func (conf *Config) GetConsumers() []PluginConfig { configs := []PluginConfig{} for _, config := range conf.Plugins { if !config.Enable || config.Typename == "" { continue // ### continue, disabled ### } pluginType := TypeRegistry.GetTypeOf(config.Typename) if pluginType == nil { continue // ### continue, unknown type ### } if pluginType.Implements(consumerInterface) { logrus.Debug("Found consumer ", config.ID) configs = append(configs, config) } } return configs }
[ "func", "(", "conf", "*", "Config", ")", "GetConsumers", "(", ")", "[", "]", "PluginConfig", "{", "configs", ":=", "[", "]", "PluginConfig", "{", "}", "\n\n", "for", "_", ",", "config", ":=", "range", "conf", ".", "Plugins", "{", "if", "!", "config", ".", "Enable", "||", "config", ".", "Typename", "==", "\"", "\"", "{", "continue", "// ### continue, disabled ###", "\n", "}", "\n\n", "pluginType", ":=", "TypeRegistry", ".", "GetTypeOf", "(", "config", ".", "Typename", ")", "\n", "if", "pluginType", "==", "nil", "{", "continue", "// ### continue, unknown type ###", "\n", "}", "\n\n", "if", "pluginType", ".", "Implements", "(", "consumerInterface", ")", "{", "logrus", ".", "Debug", "(", "\"", "\"", ",", "config", ".", "ID", ")", "\n", "configs", "=", "append", "(", "configs", ",", "config", ")", "\n", "}", "\n", "}", "\n\n", "return", "configs", "\n", "}" ]
// GetConsumers returns all consumer plugins from the config
[ "GetConsumers", "returns", "all", "consumer", "plugins", "from", "the", "config" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/config.go#L150-L170
142,494
trivago/gollum
core/config.go
GetRouters
func (conf *Config) GetRouters() []PluginConfig { configs := []PluginConfig{} for _, config := range conf.Plugins { if !config.Enable || config.Typename == "" { continue // ### continue, disabled ### } pluginType := TypeRegistry.GetTypeOf(config.Typename) if pluginType == nil { continue // ### continue, unknown type ### } if pluginType.Implements(routerInterface) { logrus.Debugf("Found router '%s'", config.ID) configs = append(configs, config) } } return configs }
go
func (conf *Config) GetRouters() []PluginConfig { configs := []PluginConfig{} for _, config := range conf.Plugins { if !config.Enable || config.Typename == "" { continue // ### continue, disabled ### } pluginType := TypeRegistry.GetTypeOf(config.Typename) if pluginType == nil { continue // ### continue, unknown type ### } if pluginType.Implements(routerInterface) { logrus.Debugf("Found router '%s'", config.ID) configs = append(configs, config) } } return configs }
[ "func", "(", "conf", "*", "Config", ")", "GetRouters", "(", ")", "[", "]", "PluginConfig", "{", "configs", ":=", "[", "]", "PluginConfig", "{", "}", "\n\n", "for", "_", ",", "config", ":=", "range", "conf", ".", "Plugins", "{", "if", "!", "config", ".", "Enable", "||", "config", ".", "Typename", "==", "\"", "\"", "{", "continue", "// ### continue, disabled ###", "\n", "}", "\n\n", "pluginType", ":=", "TypeRegistry", ".", "GetTypeOf", "(", "config", ".", "Typename", ")", "\n", "if", "pluginType", "==", "nil", "{", "continue", "// ### continue, unknown type ###", "\n", "}", "\n\n", "if", "pluginType", ".", "Implements", "(", "routerInterface", ")", "{", "logrus", ".", "Debugf", "(", "\"", "\"", ",", "config", ".", "ID", ")", "\n", "configs", "=", "append", "(", "configs", ",", "config", ")", "\n", "}", "\n", "}", "\n\n", "return", "configs", "\n", "}" ]
// GetRouters returns all stream plugins from the config
[ "GetRouters", "returns", "all", "stream", "plugins", "from", "the", "config" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/core/config.go#L196-L216
142,495
trivago/gollum
contrib/native/kafka/librdkafka/topic.go
Close
func (t *Topic) Close() { oldQueueLen := C.int(0x7FFFFFFF) queueLen := C.rd_kafka_outq_len(t.client.handle) // Wait as long as we're flushing for queueLen > 0 && queueLen < oldQueueLen { C.rd_kafka_poll(t.client.handle, 1000) oldQueueLen = queueLen queueLen = C.rd_kafka_outq_len(t.client.handle) } if queueLen > 0 { Log.Printf("%d messages have been lost as the internal queue for %s could not be flushed", queueLen, t.name) } C.rd_kafka_topic_destroy(t.handle) }
go
func (t *Topic) Close() { oldQueueLen := C.int(0x7FFFFFFF) queueLen := C.rd_kafka_outq_len(t.client.handle) // Wait as long as we're flushing for queueLen > 0 && queueLen < oldQueueLen { C.rd_kafka_poll(t.client.handle, 1000) oldQueueLen = queueLen queueLen = C.rd_kafka_outq_len(t.client.handle) } if queueLen > 0 { Log.Printf("%d messages have been lost as the internal queue for %s could not be flushed", queueLen, t.name) } C.rd_kafka_topic_destroy(t.handle) }
[ "func", "(", "t", "*", "Topic", ")", "Close", "(", ")", "{", "oldQueueLen", ":=", "C", ".", "int", "(", "0x7FFFFFFF", ")", "\n", "queueLen", ":=", "C", ".", "rd_kafka_outq_len", "(", "t", ".", "client", ".", "handle", ")", "\n\n", "// Wait as long as we're flushing", "for", "queueLen", ">", "0", "&&", "queueLen", "<", "oldQueueLen", "{", "C", ".", "rd_kafka_poll", "(", "t", ".", "client", ".", "handle", ",", "1000", ")", "\n", "oldQueueLen", "=", "queueLen", "\n", "queueLen", "=", "C", ".", "rd_kafka_outq_len", "(", "t", ".", "client", ".", "handle", ")", "\n", "}", "\n\n", "if", "queueLen", ">", "0", "{", "Log", ".", "Printf", "(", "\"", "\"", ",", "queueLen", ",", "t", ".", "name", ")", "\n", "}", "\n", "C", ".", "rd_kafka_topic_destroy", "(", "t", ".", "handle", ")", "\n", "}" ]
// Close frees the internal handle and tries to flush the queue.
[ "Close", "frees", "the", "internal", "handle", "and", "tries", "to", "flush", "the", "queue", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/contrib/native/kafka/librdkafka/topic.go#L44-L59
142,496
trivago/gollum
main.go
initLogrus
func initLogrus() func() { // Initialize logger.LogrusHookBuffer logrusHookBuffer = logger.NewLogrusHookBuffer() // Initialize logging. All logging is done via logrusHookBuffer; // logrus's output writer is always set to ioutil.Discard. logrus.AddHook(&logrusHookBuffer) logrus.SetOutput(ioutil.Discard) logrus.SetLevel(getLogrusLevel(*flagLoglevel)) switch *flagLogColors { case "never", "auto", "always": default: fmt.Printf("Invalid parameter for -log-colors: '%s'\n", *flagLogColors) *flagLogColors = "auto" } if *flagLogColors == "always" || (*flagLogColors == "auto" && terminal.IsTerminal(int(logger.FallbackLogDevice.Fd()))) { // Logrus doesn't know the final log device, so we hint the color option here logrus.SetFormatter(logger.NewConsoleFormatter()) } // make sure logs are purged at exit return func() { logrusHookBuffer.SetTargetWriter(logger.FallbackLogDevice) logrusHookBuffer.Purge() } }
go
func initLogrus() func() { // Initialize logger.LogrusHookBuffer logrusHookBuffer = logger.NewLogrusHookBuffer() // Initialize logging. All logging is done via logrusHookBuffer; // logrus's output writer is always set to ioutil.Discard. logrus.AddHook(&logrusHookBuffer) logrus.SetOutput(ioutil.Discard) logrus.SetLevel(getLogrusLevel(*flagLoglevel)) switch *flagLogColors { case "never", "auto", "always": default: fmt.Printf("Invalid parameter for -log-colors: '%s'\n", *flagLogColors) *flagLogColors = "auto" } if *flagLogColors == "always" || (*flagLogColors == "auto" && terminal.IsTerminal(int(logger.FallbackLogDevice.Fd()))) { // Logrus doesn't know the final log device, so we hint the color option here logrus.SetFormatter(logger.NewConsoleFormatter()) } // make sure logs are purged at exit return func() { logrusHookBuffer.SetTargetWriter(logger.FallbackLogDevice) logrusHookBuffer.Purge() } }
[ "func", "initLogrus", "(", ")", "func", "(", ")", "{", "// Initialize logger.LogrusHookBuffer", "logrusHookBuffer", "=", "logger", ".", "NewLogrusHookBuffer", "(", ")", "\n\n", "// Initialize logging. All logging is done via logrusHookBuffer;", "// logrus's output writer is always set to ioutil.Discard.", "logrus", ".", "AddHook", "(", "&", "logrusHookBuffer", ")", "\n", "logrus", ".", "SetOutput", "(", "ioutil", ".", "Discard", ")", "\n", "logrus", ".", "SetLevel", "(", "getLogrusLevel", "(", "*", "flagLoglevel", ")", ")", "\n\n", "switch", "*", "flagLogColors", "{", "case", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ":", "default", ":", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "*", "flagLogColors", ")", "\n", "*", "flagLogColors", "=", "\"", "\"", "\n", "}", "\n\n", "if", "*", "flagLogColors", "==", "\"", "\"", "||", "(", "*", "flagLogColors", "==", "\"", "\"", "&&", "terminal", ".", "IsTerminal", "(", "int", "(", "logger", ".", "FallbackLogDevice", ".", "Fd", "(", ")", ")", ")", ")", "{", "// Logrus doesn't know the final log device, so we hint the color option here", "logrus", ".", "SetFormatter", "(", "logger", ".", "NewConsoleFormatter", "(", ")", ")", "\n", "}", "\n\n", "// make sure logs are purged at exit", "return", "func", "(", ")", "{", "logrusHookBuffer", ".", "SetTargetWriter", "(", "logger", ".", "FallbackLogDevice", ")", "\n", "logrusHookBuffer", ".", "Purge", "(", ")", "\n", "}", "\n", "}" ]
// initLogrus initializes the logging framework
[ "initLogrus", "initializes", "the", "logging", "framework" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/main.go#L155-L183
142,497
trivago/gollum
main.go
readConfig
func readConfig(configFile string) *core.Config { if *flagHelp || configFile == "" { logrus.Error("Please provide a config file") return nil } config, err := core.ReadConfigFromFile(configFile) if err != nil { logrus.WithError(err).Error("Failed to read config") return nil } if err := config.Validate(); err != nil { logrus.WithError(err).Error("Config validation failed") return nil } return config }
go
func readConfig(configFile string) *core.Config { if *flagHelp || configFile == "" { logrus.Error("Please provide a config file") return nil } config, err := core.ReadConfigFromFile(configFile) if err != nil { logrus.WithError(err).Error("Failed to read config") return nil } if err := config.Validate(); err != nil { logrus.WithError(err).Error("Config validation failed") return nil } return config }
[ "func", "readConfig", "(", "configFile", "string", ")", "*", "core", ".", "Config", "{", "if", "*", "flagHelp", "||", "configFile", "==", "\"", "\"", "{", "logrus", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n\n", "config", ",", "err", ":=", "core", ".", "ReadConfigFromFile", "(", "configFile", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n\n", "if", "err", ":=", "config", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "logrus", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n\n", "return", "config", "\n", "}" ]
// readConfig reads and checks the config file for errors.
[ "readConfig", "reads", "and", "checks", "the", "config", "file", "for", "errors", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/main.go#L186-L204
142,498
trivago/gollum
main.go
configureRuntime
func configureRuntime() { if *flagPidFile != "" { err := ioutil.WriteFile(*flagPidFile, []byte(strconv.Itoa(os.Getpid())), 0644) if err != nil { logrus.WithError(err).Error("Failed to write pid file") } } if *flagNumCPU == 0 { runtime.GOMAXPROCS(runtime.NumCPU()) } else { runtime.GOMAXPROCS(*flagNumCPU) } if *flagProfile { time.AfterFunc(time.Second*3, printProfile) } if *flagTrace { core.ActivateMessageTrace() } }
go
func configureRuntime() { if *flagPidFile != "" { err := ioutil.WriteFile(*flagPidFile, []byte(strconv.Itoa(os.Getpid())), 0644) if err != nil { logrus.WithError(err).Error("Failed to write pid file") } } if *flagNumCPU == 0 { runtime.GOMAXPROCS(runtime.NumCPU()) } else { runtime.GOMAXPROCS(*flagNumCPU) } if *flagProfile { time.AfterFunc(time.Second*3, printProfile) } if *flagTrace { core.ActivateMessageTrace() } }
[ "func", "configureRuntime", "(", ")", "{", "if", "*", "flagPidFile", "!=", "\"", "\"", "{", "err", ":=", "ioutil", ".", "WriteFile", "(", "*", "flagPidFile", ",", "[", "]", "byte", "(", "strconv", ".", "Itoa", "(", "os", ".", "Getpid", "(", ")", ")", ")", ",", "0644", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "if", "*", "flagNumCPU", "==", "0", "{", "runtime", ".", "GOMAXPROCS", "(", "runtime", ".", "NumCPU", "(", ")", ")", "\n", "}", "else", "{", "runtime", ".", "GOMAXPROCS", "(", "*", "flagNumCPU", ")", "\n", "}", "\n\n", "if", "*", "flagProfile", "{", "time", ".", "AfterFunc", "(", "time", ".", "Second", "*", "3", ",", "printProfile", ")", "\n", "}", "\n\n", "if", "*", "flagTrace", "{", "core", ".", "ActivateMessageTrace", "(", ")", "\n", "}", "\n", "}" ]
// configureRuntime does various different settings that affect runtime // behavior or enables global functionality
[ "configureRuntime", "does", "various", "different", "settings", "that", "affect", "runtime", "behavior", "or", "enables", "global", "functionality" ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/main.go#L208-L229
142,499
trivago/gollum
main.go
startMetricsService
func startMetricsService() func() { if *flagMetricsAddress == "" { return nil } address, err := parseAddress(*flagMetricsAddress) if err != nil { logrus.WithError(err).Error("Failed to parse metrics address") return nil } metricsType := "prometheus" if *flagMetricsType != "" { metricsType = strings.ToLower(*flagMetricsType) } switch metricsType { case "prometheus": return startPrometheusMetricsService(address) default: logrus.Errorf("Unknown metrics type: %s", metricsType) return nil } }
go
func startMetricsService() func() { if *flagMetricsAddress == "" { return nil } address, err := parseAddress(*flagMetricsAddress) if err != nil { logrus.WithError(err).Error("Failed to parse metrics address") return nil } metricsType := "prometheus" if *flagMetricsType != "" { metricsType = strings.ToLower(*flagMetricsType) } switch metricsType { case "prometheus": return startPrometheusMetricsService(address) default: logrus.Errorf("Unknown metrics type: %s", metricsType) return nil } }
[ "func", "startMetricsService", "(", ")", "func", "(", ")", "{", "if", "*", "flagMetricsAddress", "==", "\"", "\"", "{", "return", "nil", "\n", "}", "\n\n", "address", ",", "err", ":=", "parseAddress", "(", "*", "flagMetricsAddress", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n\n", "metricsType", ":=", "\"", "\"", "\n", "if", "*", "flagMetricsType", "!=", "\"", "\"", "{", "metricsType", "=", "strings", ".", "ToLower", "(", "*", "flagMetricsType", ")", "\n", "}", "\n\n", "switch", "metricsType", "{", "case", "\"", "\"", ":", "return", "startPrometheusMetricsService", "(", "address", ")", "\n\n", "default", ":", "logrus", ".", "Errorf", "(", "\"", "\"", ",", "metricsType", ")", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// startMetricsService creates a metric endpoint if requested. // The returned function should be deferred if not nil.
[ "startMetricsService", "creates", "a", "metric", "endpoint", "if", "requested", ".", "The", "returned", "function", "should", "be", "deferred", "if", "not", "nil", "." ]
de2faa584cd526bb852e8a4b693982ba4216757f
https://github.com/trivago/gollum/blob/de2faa584cd526bb852e8a4b693982ba4216757f/main.go#L233-L257