repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
sequence | docstring
stringlengths 6
2.61k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 85
252
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
gravitational/teleport | lib/reversetunnel/agent.go | connectedTo | func (a *Agent) connectedTo(proxy services.Server) bool {
principals := a.getPrincipals()
proxyID := fmt.Sprintf("%v.%v", proxy.GetName(), a.ClusterName)
if _, ok := principals[proxyID]; ok {
return true
}
return false
} | go | func (a *Agent) connectedTo(proxy services.Server) bool {
principals := a.getPrincipals()
proxyID := fmt.Sprintf("%v.%v", proxy.GetName(), a.ClusterName)
if _, ok := principals[proxyID]; ok {
return true
}
return false
} | [
"func",
"(",
"a",
"*",
"Agent",
")",
"connectedTo",
"(",
"proxy",
"services",
".",
"Server",
")",
"bool",
"{",
"principals",
":=",
"a",
".",
"getPrincipals",
"(",
")",
"\n",
"proxyID",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"proxy",
".",
"GetName",
"(",
")",
",",
"a",
".",
"ClusterName",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"principals",
"[",
"proxyID",
"]",
";",
"ok",
"{",
"return",
"true",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // connectedTo returns true if connected services.Server passed in. | [
"connectedTo",
"returns",
"true",
"if",
"connected",
"services",
".",
"Server",
"passed",
"in",
"."
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/agent.go#L230-L237 | train |
gravitational/teleport | lib/reversetunnel/agent.go | connectedToRightProxy | func (a *Agent) connectedToRightProxy() bool {
for _, proxy := range a.DiscoverProxies {
if a.connectedTo(proxy) {
return true
}
}
return false
} | go | func (a *Agent) connectedToRightProxy() bool {
for _, proxy := range a.DiscoverProxies {
if a.connectedTo(proxy) {
return true
}
}
return false
} | [
"func",
"(",
"a",
"*",
"Agent",
")",
"connectedToRightProxy",
"(",
")",
"bool",
"{",
"for",
"_",
",",
"proxy",
":=",
"range",
"a",
".",
"DiscoverProxies",
"{",
"if",
"a",
".",
"connectedTo",
"(",
"proxy",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // connectedToRightProxy returns true if it connected to a proxy in the
// discover list. | [
"connectedToRightProxy",
"returns",
"true",
"if",
"it",
"connected",
"to",
"a",
"proxy",
"in",
"the",
"discover",
"list",
"."
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/agent.go#L241-L248 | train |
gravitational/teleport | lib/reversetunnel/agent.go | run | func (a *Agent) run() {
defer a.setState(agentStateDisconnected)
if len(a.DiscoverProxies) != 0 {
a.setStateAndPrincipals(agentStateDiscovering, nil)
} else {
a.setStateAndPrincipals(agentStateConnecting, nil)
}
// Try and connect to remote cluster.
conn, err := a.connect()
if err != nil || conn == nil {
a.Warningf("Failed to create remote tunnel: %v, conn: %v.", err, conn)
return
}
// Successfully connected to remote cluster.
a.Infof("Connected to %s", conn.RemoteAddr())
if len(a.DiscoverProxies) != 0 {
// If not connected to a proxy in the discover list (which means we
// connected to a proxy we already have a connection to), try again.
if !a.connectedToRightProxy() {
a.Debugf("Missed, connected to %v instead of %v.", a.getPrincipalsList(), Proxies(a.DiscoverProxies))
conn.Close()
return
}
a.setState(agentStateDiscovered)
} else {
a.setState(agentStateConnected)
}
// Notify waiters that the agent has connected.
if a.EventsC != nil {
select {
case a.EventsC <- ConnectedEvent:
case <-a.ctx.Done():
a.Debug("Context is closing.")
return
default:
}
}
// A connection has been established start processing requests. Note that
// this function blocks while the connection is up. It will unblock when
// the connection is closed either due to intermittent connectivity issues
// or permanent loss of a proxy.
err = a.processRequests(conn)
if err != nil {
a.Warnf("Unable to continue processesing requests: %v.", err)
return
}
} | go | func (a *Agent) run() {
defer a.setState(agentStateDisconnected)
if len(a.DiscoverProxies) != 0 {
a.setStateAndPrincipals(agentStateDiscovering, nil)
} else {
a.setStateAndPrincipals(agentStateConnecting, nil)
}
// Try and connect to remote cluster.
conn, err := a.connect()
if err != nil || conn == nil {
a.Warningf("Failed to create remote tunnel: %v, conn: %v.", err, conn)
return
}
// Successfully connected to remote cluster.
a.Infof("Connected to %s", conn.RemoteAddr())
if len(a.DiscoverProxies) != 0 {
// If not connected to a proxy in the discover list (which means we
// connected to a proxy we already have a connection to), try again.
if !a.connectedToRightProxy() {
a.Debugf("Missed, connected to %v instead of %v.", a.getPrincipalsList(), Proxies(a.DiscoverProxies))
conn.Close()
return
}
a.setState(agentStateDiscovered)
} else {
a.setState(agentStateConnected)
}
// Notify waiters that the agent has connected.
if a.EventsC != nil {
select {
case a.EventsC <- ConnectedEvent:
case <-a.ctx.Done():
a.Debug("Context is closing.")
return
default:
}
}
// A connection has been established start processing requests. Note that
// this function blocks while the connection is up. It will unblock when
// the connection is closed either due to intermittent connectivity issues
// or permanent loss of a proxy.
err = a.processRequests(conn)
if err != nil {
a.Warnf("Unable to continue processesing requests: %v.", err)
return
}
} | [
"func",
"(",
"a",
"*",
"Agent",
")",
"run",
"(",
")",
"{",
"defer",
"a",
".",
"setState",
"(",
"agentStateDisconnected",
")",
"\n\n",
"if",
"len",
"(",
"a",
".",
"DiscoverProxies",
")",
"!=",
"0",
"{",
"a",
".",
"setStateAndPrincipals",
"(",
"agentStateDiscovering",
",",
"nil",
")",
"\n",
"}",
"else",
"{",
"a",
".",
"setStateAndPrincipals",
"(",
"agentStateConnecting",
",",
"nil",
")",
"\n",
"}",
"\n\n",
"// Try and connect to remote cluster.",
"conn",
",",
"err",
":=",
"a",
".",
"connect",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"conn",
"==",
"nil",
"{",
"a",
".",
"Warningf",
"(",
"\"",
"\"",
",",
"err",
",",
"conn",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Successfully connected to remote cluster.",
"a",
".",
"Infof",
"(",
"\"",
"\"",
",",
"conn",
".",
"RemoteAddr",
"(",
")",
")",
"\n",
"if",
"len",
"(",
"a",
".",
"DiscoverProxies",
")",
"!=",
"0",
"{",
"// If not connected to a proxy in the discover list (which means we",
"// connected to a proxy we already have a connection to), try again.",
"if",
"!",
"a",
".",
"connectedToRightProxy",
"(",
")",
"{",
"a",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"a",
".",
"getPrincipalsList",
"(",
")",
",",
"Proxies",
"(",
"a",
".",
"DiscoverProxies",
")",
")",
"\n\n",
"conn",
".",
"Close",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"a",
".",
"setState",
"(",
"agentStateDiscovered",
")",
"\n",
"}",
"else",
"{",
"a",
".",
"setState",
"(",
"agentStateConnected",
")",
"\n",
"}",
"\n\n",
"// Notify waiters that the agent has connected.",
"if",
"a",
".",
"EventsC",
"!=",
"nil",
"{",
"select",
"{",
"case",
"a",
".",
"EventsC",
"<-",
"ConnectedEvent",
":",
"case",
"<-",
"a",
".",
"ctx",
".",
"Done",
"(",
")",
":",
"a",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"default",
":",
"}",
"\n",
"}",
"\n\n",
"// A connection has been established start processing requests. Note that",
"// this function blocks while the connection is up. It will unblock when",
"// the connection is closed either due to intermittent connectivity issues",
"// or permanent loss of a proxy.",
"err",
"=",
"a",
".",
"processRequests",
"(",
"conn",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"a",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}"
] | // run is the main agent loop. It tries to establish a connection to the
// remote proxy and then process requests that come over the tunnel.
//
// Once run connects to a proxy it starts processing requests from the proxy
// via SSH channels opened by the remote Proxy.
//
// Agent sends periodic heartbeats back to the Proxy and that is how Proxy
// determines disconnects. | [
"run",
"is",
"the",
"main",
"agent",
"loop",
".",
"It",
"tries",
"to",
"establish",
"a",
"connection",
"to",
"the",
"remote",
"proxy",
"and",
"then",
"process",
"requests",
"that",
"come",
"over",
"the",
"tunnel",
".",
"Once",
"run",
"connects",
"to",
"a",
"proxy",
"it",
"starts",
"processing",
"requests",
"from",
"the",
"proxy",
"via",
"SSH",
"channels",
"opened",
"by",
"the",
"remote",
"Proxy",
".",
"Agent",
"sends",
"periodic",
"heartbeats",
"back",
"to",
"the",
"Proxy",
"and",
"that",
"is",
"how",
"Proxy",
"determines",
"disconnects",
"."
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/agent.go#L324-L376 | train |
gravitational/teleport | lib/reversetunnel/agent.go | processRequests | func (a *Agent) processRequests(conn *ssh.Client) error {
defer conn.Close()
ticker := time.NewTicker(defaults.ReverseTunnelAgentHeartbeatPeriod)
defer ticker.Stop()
hb, reqC, err := conn.OpenChannel(chanHeartbeat, nil)
if err != nil {
return trace.Wrap(err)
}
newTransportC := conn.HandleChannelOpen(chanTransport)
newDiscoveryC := conn.HandleChannelOpen(chanDiscovery)
// send first ping right away, then start a ping timer:
hb.SendRequest("ping", false, nil)
for {
select {
// need to exit:
case <-a.ctx.Done():
return trace.ConnectionProblem(nil, "heartbeat: agent is stopped")
// time to ping:
case <-ticker.C:
bytes, _ := a.Clock.Now().UTC().MarshalText()
_, err := hb.SendRequest("ping", false, bytes)
if err != nil {
a.Error(err)
return trace.Wrap(err)
}
a.Debugf("Ping -> %v.", conn.RemoteAddr())
// ssh channel closed:
case req := <-reqC:
if req == nil {
return trace.ConnectionProblem(nil, "heartbeat: connection closed")
}
// new transport request:
case nch := <-newTransportC:
if nch == nil {
continue
}
a.Debugf("Transport request: %v.", nch.ChannelType())
ch, req, err := nch.Accept()
if err != nil {
a.Warningf("Failed to accept request: %v.", err)
continue
}
go proxyTransport(&transportParams{
log: a.Entry,
closeContext: a.ctx,
authClient: a.Client,
kubeDialAddr: a.KubeDialAddr,
channel: ch,
requestCh: req,
sconn: conn.Conn,
server: a.Server,
component: teleport.ComponentReverseTunnelAgent,
})
// new discovery request
case nch := <-newDiscoveryC:
if nch == nil {
continue
}
a.Debugf("discovery request: %v", nch.ChannelType())
ch, req, err := nch.Accept()
if err != nil {
a.Warningf("failed to accept request: %v", err)
continue
}
go a.handleDiscovery(ch, req)
}
}
} | go | func (a *Agent) processRequests(conn *ssh.Client) error {
defer conn.Close()
ticker := time.NewTicker(defaults.ReverseTunnelAgentHeartbeatPeriod)
defer ticker.Stop()
hb, reqC, err := conn.OpenChannel(chanHeartbeat, nil)
if err != nil {
return trace.Wrap(err)
}
newTransportC := conn.HandleChannelOpen(chanTransport)
newDiscoveryC := conn.HandleChannelOpen(chanDiscovery)
// send first ping right away, then start a ping timer:
hb.SendRequest("ping", false, nil)
for {
select {
// need to exit:
case <-a.ctx.Done():
return trace.ConnectionProblem(nil, "heartbeat: agent is stopped")
// time to ping:
case <-ticker.C:
bytes, _ := a.Clock.Now().UTC().MarshalText()
_, err := hb.SendRequest("ping", false, bytes)
if err != nil {
a.Error(err)
return trace.Wrap(err)
}
a.Debugf("Ping -> %v.", conn.RemoteAddr())
// ssh channel closed:
case req := <-reqC:
if req == nil {
return trace.ConnectionProblem(nil, "heartbeat: connection closed")
}
// new transport request:
case nch := <-newTransportC:
if nch == nil {
continue
}
a.Debugf("Transport request: %v.", nch.ChannelType())
ch, req, err := nch.Accept()
if err != nil {
a.Warningf("Failed to accept request: %v.", err)
continue
}
go proxyTransport(&transportParams{
log: a.Entry,
closeContext: a.ctx,
authClient: a.Client,
kubeDialAddr: a.KubeDialAddr,
channel: ch,
requestCh: req,
sconn: conn.Conn,
server: a.Server,
component: teleport.ComponentReverseTunnelAgent,
})
// new discovery request
case nch := <-newDiscoveryC:
if nch == nil {
continue
}
a.Debugf("discovery request: %v", nch.ChannelType())
ch, req, err := nch.Accept()
if err != nil {
a.Warningf("failed to accept request: %v", err)
continue
}
go a.handleDiscovery(ch, req)
}
}
} | [
"func",
"(",
"a",
"*",
"Agent",
")",
"processRequests",
"(",
"conn",
"*",
"ssh",
".",
"Client",
")",
"error",
"{",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n",
"ticker",
":=",
"time",
".",
"NewTicker",
"(",
"defaults",
".",
"ReverseTunnelAgentHeartbeatPeriod",
")",
"\n",
"defer",
"ticker",
".",
"Stop",
"(",
")",
"\n\n",
"hb",
",",
"reqC",
",",
"err",
":=",
"conn",
".",
"OpenChannel",
"(",
"chanHeartbeat",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"newTransportC",
":=",
"conn",
".",
"HandleChannelOpen",
"(",
"chanTransport",
")",
"\n",
"newDiscoveryC",
":=",
"conn",
".",
"HandleChannelOpen",
"(",
"chanDiscovery",
")",
"\n\n",
"// send first ping right away, then start a ping timer:",
"hb",
".",
"SendRequest",
"(",
"\"",
"\"",
",",
"false",
",",
"nil",
")",
"\n\n",
"for",
"{",
"select",
"{",
"// need to exit:",
"case",
"<-",
"a",
".",
"ctx",
".",
"Done",
"(",
")",
":",
"return",
"trace",
".",
"ConnectionProblem",
"(",
"nil",
",",
"\"",
"\"",
")",
"\n",
"// time to ping:",
"case",
"<-",
"ticker",
".",
"C",
":",
"bytes",
",",
"_",
":=",
"a",
".",
"Clock",
".",
"Now",
"(",
")",
".",
"UTC",
"(",
")",
".",
"MarshalText",
"(",
")",
"\n",
"_",
",",
"err",
":=",
"hb",
".",
"SendRequest",
"(",
"\"",
"\"",
",",
"false",
",",
"bytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"a",
".",
"Error",
"(",
"err",
")",
"\n",
"return",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"a",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"conn",
".",
"RemoteAddr",
"(",
")",
")",
"\n",
"// ssh channel closed:",
"case",
"req",
":=",
"<-",
"reqC",
":",
"if",
"req",
"==",
"nil",
"{",
"return",
"trace",
".",
"ConnectionProblem",
"(",
"nil",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// new transport request:",
"case",
"nch",
":=",
"<-",
"newTransportC",
":",
"if",
"nch",
"==",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"a",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"nch",
".",
"ChannelType",
"(",
")",
")",
"\n",
"ch",
",",
"req",
",",
"err",
":=",
"nch",
".",
"Accept",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"a",
".",
"Warningf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"go",
"proxyTransport",
"(",
"&",
"transportParams",
"{",
"log",
":",
"a",
".",
"Entry",
",",
"closeContext",
":",
"a",
".",
"ctx",
",",
"authClient",
":",
"a",
".",
"Client",
",",
"kubeDialAddr",
":",
"a",
".",
"KubeDialAddr",
",",
"channel",
":",
"ch",
",",
"requestCh",
":",
"req",
",",
"sconn",
":",
"conn",
".",
"Conn",
",",
"server",
":",
"a",
".",
"Server",
",",
"component",
":",
"teleport",
".",
"ComponentReverseTunnelAgent",
",",
"}",
")",
"\n",
"// new discovery request",
"case",
"nch",
":=",
"<-",
"newDiscoveryC",
":",
"if",
"nch",
"==",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"a",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"nch",
".",
"ChannelType",
"(",
")",
")",
"\n",
"ch",
",",
"req",
",",
"err",
":=",
"nch",
".",
"Accept",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"a",
".",
"Warningf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"go",
"a",
".",
"handleDiscovery",
"(",
"ch",
",",
"req",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // processRequests is a blocking function which runs in a loop sending heartbeats
// to the given SSH connection and processes inbound requests from the
// remote proxy | [
"processRequests",
"is",
"a",
"blocking",
"function",
"which",
"runs",
"in",
"a",
"loop",
"sending",
"heartbeats",
"to",
"the",
"given",
"SSH",
"connection",
"and",
"processes",
"inbound",
"requests",
"from",
"the",
"remote",
"proxy"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/agent.go#L384-L454 | train |
gravitational/teleport | lib/utils/retry.go | NewLinear | func NewLinear(cfg LinearConfig) (*Linear, error) {
if err := cfg.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
closedChan := make(chan time.Time)
close(closedChan)
return &Linear{LinearConfig: cfg, closedChan: closedChan}, nil
} | go | func NewLinear(cfg LinearConfig) (*Linear, error) {
if err := cfg.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
closedChan := make(chan time.Time)
close(closedChan)
return &Linear{LinearConfig: cfg, closedChan: closedChan}, nil
} | [
"func",
"NewLinear",
"(",
"cfg",
"LinearConfig",
")",
"(",
"*",
"Linear",
",",
"error",
")",
"{",
"if",
"err",
":=",
"cfg",
".",
"CheckAndSetDefaults",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"closedChan",
":=",
"make",
"(",
"chan",
"time",
".",
"Time",
")",
"\n",
"close",
"(",
"closedChan",
")",
"\n",
"return",
"&",
"Linear",
"{",
"LinearConfig",
":",
"cfg",
",",
"closedChan",
":",
"closedChan",
"}",
",",
"nil",
"\n",
"}"
] | // NewLinear returns a new instance of linear retry | [
"NewLinear",
"returns",
"a",
"new",
"instance",
"of",
"linear",
"retry"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/retry.go#L66-L73 | train |
gravitational/teleport | lib/utils/retry.go | Duration | func (r *Linear) Duration() time.Duration {
a := r.First + time.Duration(r.attempt)*r.Step
if a < 0 {
return 0
}
if a <= r.Max {
return a
}
return r.Max
} | go | func (r *Linear) Duration() time.Duration {
a := r.First + time.Duration(r.attempt)*r.Step
if a < 0 {
return 0
}
if a <= r.Max {
return a
}
return r.Max
} | [
"func",
"(",
"r",
"*",
"Linear",
")",
"Duration",
"(",
")",
"time",
".",
"Duration",
"{",
"a",
":=",
"r",
".",
"First",
"+",
"time",
".",
"Duration",
"(",
"r",
".",
"attempt",
")",
"*",
"r",
".",
"Step",
"\n",
"if",
"a",
"<",
"0",
"{",
"return",
"0",
"\n",
"}",
"\n",
"if",
"a",
"<=",
"r",
".",
"Max",
"{",
"return",
"a",
"\n",
"}",
"\n",
"return",
"r",
".",
"Max",
"\n",
"}"
] | // Duration returns retry duration based on state | [
"Duration",
"returns",
"retry",
"duration",
"based",
"on",
"state"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/retry.go#L98-L107 | train |
gravitational/teleport | lib/utils/retry.go | After | func (r *Linear) After() <-chan time.Time {
if r.Duration() == 0 {
return r.closedChan
}
return time.After(r.Duration())
} | go | func (r *Linear) After() <-chan time.Time {
if r.Duration() == 0 {
return r.closedChan
}
return time.After(r.Duration())
} | [
"func",
"(",
"r",
"*",
"Linear",
")",
"After",
"(",
")",
"<-",
"chan",
"time",
".",
"Time",
"{",
"if",
"r",
".",
"Duration",
"(",
")",
"==",
"0",
"{",
"return",
"r",
".",
"closedChan",
"\n",
"}",
"\n",
"return",
"time",
".",
"After",
"(",
"r",
".",
"Duration",
"(",
")",
")",
"\n",
"}"
] | // After returns channel that fires with timeout
// defined in Duration method, as a special case
// if Duration is 0 returns a closed channel | [
"After",
"returns",
"channel",
"that",
"fires",
"with",
"timeout",
"defined",
"in",
"Duration",
"method",
"as",
"a",
"special",
"case",
"if",
"Duration",
"is",
"0",
"returns",
"a",
"closed",
"channel"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/retry.go#L112-L117 | train |
gravitational/teleport | lib/utils/retry.go | String | func (r *Linear) String() string {
return fmt.Sprintf("Linear(attempt=%v, duration=%v)", r.attempt, r.Duration())
} | go | func (r *Linear) String() string {
return fmt.Sprintf("Linear(attempt=%v, duration=%v)", r.attempt, r.Duration())
} | [
"func",
"(",
"r",
"*",
"Linear",
")",
"String",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"r",
".",
"attempt",
",",
"r",
".",
"Duration",
"(",
")",
")",
"\n",
"}"
] | // String returns user-friendly representation of the LinearPeriod | [
"String",
"returns",
"user",
"-",
"friendly",
"representation",
"of",
"the",
"LinearPeriod"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/retry.go#L120-L122 | train |
gravitational/teleport | lib/shell/shell_unix.go | getLoginShell | func getLoginShell(username string) (string, error) {
// See if the username is valid.
_, err := user.Lookup(username)
if err != nil {
return "", trace.Wrap(err)
}
// Based on stdlib user/lookup_unix.go packages which does not return
// user shell: https://golang.org/src/os/user/lookup_unix.go
var pwd C.struct_passwd
var result *C.struct_passwd
bufSize := C.sysconf(C._SC_GETPW_R_SIZE_MAX)
if bufSize == -1 {
bufSize = 1024
}
if bufSize <= 0 || bufSize > 1<<20 {
return "", trace.BadParameter("lookupPosixShell: unreasonable _SC_GETPW_R_SIZE_MAX of %d", bufSize)
}
buf := C.malloc(C.size_t(bufSize))
defer C.free(buf)
var rv C.int
nameC := C.CString(username)
defer C.free(unsafe.Pointer(nameC))
rv = C.mygetpwnam_r(nameC,
&pwd,
(*C.char)(buf),
C.size_t(bufSize),
&result)
if rv != 0 || result == nil {
log.Errorf("lookupPosixShell: lookup username %s: %s", username, syscall.Errno(rv))
return "", trace.BadParameter("cannot determine shell for %s", username)
}
// If no shell was found, return trace.NotFound to allow the caller to set
// the default shell.
shellCmd := strings.TrimSpace(C.GoString(pwd.pw_shell))
if len(shellCmd) == 0 {
return "", trace.NotFound("no shell specified for %v", username)
}
return shellCmd, nil
} | go | func getLoginShell(username string) (string, error) {
// See if the username is valid.
_, err := user.Lookup(username)
if err != nil {
return "", trace.Wrap(err)
}
// Based on stdlib user/lookup_unix.go packages which does not return
// user shell: https://golang.org/src/os/user/lookup_unix.go
var pwd C.struct_passwd
var result *C.struct_passwd
bufSize := C.sysconf(C._SC_GETPW_R_SIZE_MAX)
if bufSize == -1 {
bufSize = 1024
}
if bufSize <= 0 || bufSize > 1<<20 {
return "", trace.BadParameter("lookupPosixShell: unreasonable _SC_GETPW_R_SIZE_MAX of %d", bufSize)
}
buf := C.malloc(C.size_t(bufSize))
defer C.free(buf)
var rv C.int
nameC := C.CString(username)
defer C.free(unsafe.Pointer(nameC))
rv = C.mygetpwnam_r(nameC,
&pwd,
(*C.char)(buf),
C.size_t(bufSize),
&result)
if rv != 0 || result == nil {
log.Errorf("lookupPosixShell: lookup username %s: %s", username, syscall.Errno(rv))
return "", trace.BadParameter("cannot determine shell for %s", username)
}
// If no shell was found, return trace.NotFound to allow the caller to set
// the default shell.
shellCmd := strings.TrimSpace(C.GoString(pwd.pw_shell))
if len(shellCmd) == 0 {
return "", trace.NotFound("no shell specified for %v", username)
}
return shellCmd, nil
} | [
"func",
"getLoginShell",
"(",
"username",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"// See if the username is valid.",
"_",
",",
"err",
":=",
"user",
".",
"Lookup",
"(",
"username",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// Based on stdlib user/lookup_unix.go packages which does not return",
"// user shell: https://golang.org/src/os/user/lookup_unix.go",
"var",
"pwd",
"C",
".",
"struct_passwd",
"\n",
"var",
"result",
"*",
"C",
".",
"struct_passwd",
"\n\n",
"bufSize",
":=",
"C",
".",
"sysconf",
"(",
"C",
".",
"_SC_GETPW_R_SIZE_MAX",
")",
"\n",
"if",
"bufSize",
"==",
"-",
"1",
"{",
"bufSize",
"=",
"1024",
"\n",
"}",
"\n",
"if",
"bufSize",
"<=",
"0",
"||",
"bufSize",
">",
"1",
"<<",
"20",
"{",
"return",
"\"",
"\"",
",",
"trace",
".",
"BadParameter",
"(",
"\"",
"\"",
",",
"bufSize",
")",
"\n",
"}",
"\n",
"buf",
":=",
"C",
".",
"malloc",
"(",
"C",
".",
"size_t",
"(",
"bufSize",
")",
")",
"\n",
"defer",
"C",
".",
"free",
"(",
"buf",
")",
"\n",
"var",
"rv",
"C",
".",
"int",
"\n",
"nameC",
":=",
"C",
".",
"CString",
"(",
"username",
")",
"\n",
"defer",
"C",
".",
"free",
"(",
"unsafe",
".",
"Pointer",
"(",
"nameC",
")",
")",
"\n",
"rv",
"=",
"C",
".",
"mygetpwnam_r",
"(",
"nameC",
",",
"&",
"pwd",
",",
"(",
"*",
"C",
".",
"char",
")",
"(",
"buf",
")",
",",
"C",
".",
"size_t",
"(",
"bufSize",
")",
",",
"&",
"result",
")",
"\n",
"if",
"rv",
"!=",
"0",
"||",
"result",
"==",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"username",
",",
"syscall",
".",
"Errno",
"(",
"rv",
")",
")",
"\n",
"return",
"\"",
"\"",
",",
"trace",
".",
"BadParameter",
"(",
"\"",
"\"",
",",
"username",
")",
"\n",
"}",
"\n\n",
"// If no shell was found, return trace.NotFound to allow the caller to set",
"// the default shell.",
"shellCmd",
":=",
"strings",
".",
"TrimSpace",
"(",
"C",
".",
"GoString",
"(",
"pwd",
".",
"pw_shell",
")",
")",
"\n",
"if",
"len",
"(",
"shellCmd",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
",",
"trace",
".",
"NotFound",
"(",
"\"",
"\"",
",",
"username",
")",
"\n",
"}",
"\n\n",
"return",
"shellCmd",
",",
"nil",
"\n",
"}"
] | // getLoginShell determines the login shell for a given username | [
"getLoginShell",
"determines",
"the",
"login",
"shell",
"for",
"a",
"given",
"username"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/shell/shell_unix.go#L46-L88 | train |
gravitational/teleport | lib/sshutils/fingerprint.go | AuthorizedKeyFingerprint | func AuthorizedKeyFingerprint(publicKey []byte) (string, error) {
key, _, _, _, err := ssh.ParseAuthorizedKey(publicKey)
if err != nil {
return "", trace.Wrap(err)
}
return Fingerprint(key), nil
} | go | func AuthorizedKeyFingerprint(publicKey []byte) (string, error) {
key, _, _, _, err := ssh.ParseAuthorizedKey(publicKey)
if err != nil {
return "", trace.Wrap(err)
}
return Fingerprint(key), nil
} | [
"func",
"AuthorizedKeyFingerprint",
"(",
"publicKey",
"[",
"]",
"byte",
")",
"(",
"string",
",",
"error",
")",
"{",
"key",
",",
"_",
",",
"_",
",",
"_",
",",
"err",
":=",
"ssh",
".",
"ParseAuthorizedKey",
"(",
"publicKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"Fingerprint",
"(",
"key",
")",
",",
"nil",
"\n",
"}"
] | // AuthorizedKeyFingerprint returns fingerprint from public key
// in authorized key format | [
"AuthorizedKeyFingerprint",
"returns",
"fingerprint",
"from",
"public",
"key",
"in",
"authorized",
"key",
"format"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/fingerprint.go#L15-L21 | train |
gravitational/teleport | lib/sshutils/fingerprint.go | PrivateKeyFingerprint | func PrivateKeyFingerprint(keyBytes []byte) (string, error) {
signer, err := ssh.ParsePrivateKey(keyBytes)
if err != nil {
return "", trace.Wrap(err)
}
return Fingerprint(signer.PublicKey()), nil
} | go | func PrivateKeyFingerprint(keyBytes []byte) (string, error) {
signer, err := ssh.ParsePrivateKey(keyBytes)
if err != nil {
return "", trace.Wrap(err)
}
return Fingerprint(signer.PublicKey()), nil
} | [
"func",
"PrivateKeyFingerprint",
"(",
"keyBytes",
"[",
"]",
"byte",
")",
"(",
"string",
",",
"error",
")",
"{",
"signer",
",",
"err",
":=",
"ssh",
".",
"ParsePrivateKey",
"(",
"keyBytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"Fingerprint",
"(",
"signer",
".",
"PublicKey",
"(",
")",
")",
",",
"nil",
"\n",
"}"
] | // PrivateKeyFingerprint returns fingerprint of the public key
// extracted from the PEM encoded private key | [
"PrivateKeyFingerprint",
"returns",
"fingerprint",
"of",
"the",
"public",
"key",
"extracted",
"from",
"the",
"PEM",
"encoded",
"private",
"key"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/fingerprint.go#L25-L31 | train |
gravitational/teleport | lib/utils/anonymizer.go | NewHMACAnonymizer | func NewHMACAnonymizer(key string) (*hmacAnonymizer, error) {
if strings.TrimSpace(key) == "" {
return nil, trace.BadParameter("HMAC key must not be empty")
}
return &hmacAnonymizer{
key: key,
}, nil
} | go | func NewHMACAnonymizer(key string) (*hmacAnonymizer, error) {
if strings.TrimSpace(key) == "" {
return nil, trace.BadParameter("HMAC key must not be empty")
}
return &hmacAnonymizer{
key: key,
}, nil
} | [
"func",
"NewHMACAnonymizer",
"(",
"key",
"string",
")",
"(",
"*",
"hmacAnonymizer",
",",
"error",
")",
"{",
"if",
"strings",
".",
"TrimSpace",
"(",
"key",
")",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"trace",
".",
"BadParameter",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"&",
"hmacAnonymizer",
"{",
"key",
":",
"key",
",",
"}",
",",
"nil",
"\n",
"}"
] | // NewHMACAnonymizer returns a new HMAC-based anonymizer | [
"NewHMACAnonymizer",
"returns",
"a",
"new",
"HMAC",
"-",
"based",
"anonymizer"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/anonymizer.go#L41-L48 | train |
gravitational/teleport | lib/utils/anonymizer.go | Anonymize | func (a *hmacAnonymizer) Anonymize(data []byte) string {
h := hmac.New(sha256.New, []byte(a.key))
h.Write(data)
return base64.StdEncoding.EncodeToString(h.Sum(nil))
} | go | func (a *hmacAnonymizer) Anonymize(data []byte) string {
h := hmac.New(sha256.New, []byte(a.key))
h.Write(data)
return base64.StdEncoding.EncodeToString(h.Sum(nil))
} | [
"func",
"(",
"a",
"*",
"hmacAnonymizer",
")",
"Anonymize",
"(",
"data",
"[",
"]",
"byte",
")",
"string",
"{",
"h",
":=",
"hmac",
".",
"New",
"(",
"sha256",
".",
"New",
",",
"[",
"]",
"byte",
"(",
"a",
".",
"key",
")",
")",
"\n",
"h",
".",
"Write",
"(",
"data",
")",
"\n",
"return",
"base64",
".",
"StdEncoding",
".",
"EncodeToString",
"(",
"h",
".",
"Sum",
"(",
"nil",
")",
")",
"\n",
"}"
] | // Anonymize anonymizes the provided data using HMAC | [
"Anonymize",
"anonymizes",
"the",
"provided",
"data",
"using",
"HMAC"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/anonymizer.go#L51-L55 | train |
gravitational/teleport | lib/utils/schema.go | UnmarshalWithSchema | func UnmarshalWithSchema(schemaDefinition string, object interface{}, data []byte) error {
schema, err := jsonschema.New([]byte(schemaDefinition))
if err != nil {
return trace.Wrap(err)
}
jsonData, err := ToJSON(data)
if err != nil {
return trace.Wrap(err)
}
raw := map[string]interface{}{}
if err := json.Unmarshal(jsonData, &raw); err != nil {
return trace.Wrap(err)
}
// schema will check format and set defaults
processed, err := schema.ProcessObject(raw)
if err != nil {
return trace.Wrap(err)
}
// since ProcessObject works with unstructured data, the
// data needs to be re-interpreted in structured form
bytes, err := json.Marshal(processed)
if err != nil {
return trace.Wrap(err)
}
if err := json.Unmarshal(bytes, object); err != nil {
return trace.Wrap(err)
}
return nil
} | go | func UnmarshalWithSchema(schemaDefinition string, object interface{}, data []byte) error {
schema, err := jsonschema.New([]byte(schemaDefinition))
if err != nil {
return trace.Wrap(err)
}
jsonData, err := ToJSON(data)
if err != nil {
return trace.Wrap(err)
}
raw := map[string]interface{}{}
if err := json.Unmarshal(jsonData, &raw); err != nil {
return trace.Wrap(err)
}
// schema will check format and set defaults
processed, err := schema.ProcessObject(raw)
if err != nil {
return trace.Wrap(err)
}
// since ProcessObject works with unstructured data, the
// data needs to be re-interpreted in structured form
bytes, err := json.Marshal(processed)
if err != nil {
return trace.Wrap(err)
}
if err := json.Unmarshal(bytes, object); err != nil {
return trace.Wrap(err)
}
return nil
} | [
"func",
"UnmarshalWithSchema",
"(",
"schemaDefinition",
"string",
",",
"object",
"interface",
"{",
"}",
",",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"schema",
",",
"err",
":=",
"jsonschema",
".",
"New",
"(",
"[",
"]",
"byte",
"(",
"schemaDefinition",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"jsonData",
",",
"err",
":=",
"ToJSON",
"(",
"data",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"raw",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"jsonData",
",",
"&",
"raw",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"// schema will check format and set defaults",
"processed",
",",
"err",
":=",
"schema",
".",
"ProcessObject",
"(",
"raw",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"// since ProcessObject works with unstructured data, the",
"// data needs to be re-interpreted in structured form",
"bytes",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"processed",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"bytes",
",",
"object",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // UnmarshalWithSchema processes YAML or JSON encoded object with JSON schema, sets defaults
// and unmarshals resulting object into given struct | [
"UnmarshalWithSchema",
"processes",
"YAML",
"or",
"JSON",
"encoded",
"object",
"with",
"JSON",
"schema",
"sets",
"defaults",
"and",
"unmarshals",
"resulting",
"object",
"into",
"given",
"struct"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/schema.go#L28-L57 | train |
gravitational/teleport | lib/events/archive.go | NewSessionArchive | func NewSessionArchive(dataDir, serverID, namespace string, sessionID session.ID) (io.ReadCloser, error) {
index, err := readSessionIndex(
dataDir, []string{serverID}, namespace, sessionID)
if err != nil {
return nil, trace.Wrap(err)
}
// io.Pipe allows to generate the archive part by part
// without writing to disk or generating it in memory
// at the pace which reader is ready to consume it
reader, writer := io.Pipe()
tarball := tar.NewWriter(writer)
go func() {
if err := writeSessionArchive(index, tarball, writer); err != nil {
log.Warningf("Failed to write archive: %v.", trace.DebugReport(err))
}
}()
return reader, nil
} | go | func NewSessionArchive(dataDir, serverID, namespace string, sessionID session.ID) (io.ReadCloser, error) {
index, err := readSessionIndex(
dataDir, []string{serverID}, namespace, sessionID)
if err != nil {
return nil, trace.Wrap(err)
}
// io.Pipe allows to generate the archive part by part
// without writing to disk or generating it in memory
// at the pace which reader is ready to consume it
reader, writer := io.Pipe()
tarball := tar.NewWriter(writer)
go func() {
if err := writeSessionArchive(index, tarball, writer); err != nil {
log.Warningf("Failed to write archive: %v.", trace.DebugReport(err))
}
}()
return reader, nil
} | [
"func",
"NewSessionArchive",
"(",
"dataDir",
",",
"serverID",
",",
"namespace",
"string",
",",
"sessionID",
"session",
".",
"ID",
")",
"(",
"io",
".",
"ReadCloser",
",",
"error",
")",
"{",
"index",
",",
"err",
":=",
"readSessionIndex",
"(",
"dataDir",
",",
"[",
"]",
"string",
"{",
"serverID",
"}",
",",
"namespace",
",",
"sessionID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// io.Pipe allows to generate the archive part by part",
"// without writing to disk or generating it in memory",
"// at the pace which reader is ready to consume it",
"reader",
",",
"writer",
":=",
"io",
".",
"Pipe",
"(",
")",
"\n",
"tarball",
":=",
"tar",
".",
"NewWriter",
"(",
"writer",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"if",
"err",
":=",
"writeSessionArchive",
"(",
"index",
",",
"tarball",
",",
"writer",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Warningf",
"(",
"\"",
"\"",
",",
"trace",
".",
"DebugReport",
"(",
"err",
")",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"return",
"reader",
",",
"nil",
"\n",
"}"
] | // NewSessionArchive returns generated tar archive with all components | [
"NewSessionArchive",
"returns",
"generated",
"tar",
"archive",
"with",
"all",
"components"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/archive.go#L30-L49 | train |
gravitational/teleport | lib/utils/certs.go | ParseSigningKeyStorePEM | func ParseSigningKeyStorePEM(keyPEM, certPEM string) (*SigningKeyStore, error) {
_, err := ParseCertificatePEM([]byte(certPEM))
if err != nil {
return nil, trace.Wrap(err)
}
key, err := ParsePrivateKeyPEM([]byte(keyPEM))
if err != nil {
return nil, trace.Wrap(err)
}
rsaKey, ok := key.(*rsa.PrivateKey)
if !ok {
return nil, trace.BadParameter("key of type %T is not supported, only RSA keys are supported for signatures", key)
}
certASN, _ := pem.Decode([]byte(certPEM))
if certASN == nil {
return nil, trace.BadParameter("expected PEM-encoded block")
}
return &SigningKeyStore{privateKey: rsaKey, cert: certASN.Bytes}, nil
} | go | func ParseSigningKeyStorePEM(keyPEM, certPEM string) (*SigningKeyStore, error) {
_, err := ParseCertificatePEM([]byte(certPEM))
if err != nil {
return nil, trace.Wrap(err)
}
key, err := ParsePrivateKeyPEM([]byte(keyPEM))
if err != nil {
return nil, trace.Wrap(err)
}
rsaKey, ok := key.(*rsa.PrivateKey)
if !ok {
return nil, trace.BadParameter("key of type %T is not supported, only RSA keys are supported for signatures", key)
}
certASN, _ := pem.Decode([]byte(certPEM))
if certASN == nil {
return nil, trace.BadParameter("expected PEM-encoded block")
}
return &SigningKeyStore{privateKey: rsaKey, cert: certASN.Bytes}, nil
} | [
"func",
"ParseSigningKeyStorePEM",
"(",
"keyPEM",
",",
"certPEM",
"string",
")",
"(",
"*",
"SigningKeyStore",
",",
"error",
")",
"{",
"_",
",",
"err",
":=",
"ParseCertificatePEM",
"(",
"[",
"]",
"byte",
"(",
"certPEM",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"key",
",",
"err",
":=",
"ParsePrivateKeyPEM",
"(",
"[",
"]",
"byte",
"(",
"keyPEM",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"rsaKey",
",",
"ok",
":=",
"key",
".",
"(",
"*",
"rsa",
".",
"PrivateKey",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"trace",
".",
"BadParameter",
"(",
"\"",
"\"",
",",
"key",
")",
"\n",
"}",
"\n",
"certASN",
",",
"_",
":=",
"pem",
".",
"Decode",
"(",
"[",
"]",
"byte",
"(",
"certPEM",
")",
")",
"\n",
"if",
"certASN",
"==",
"nil",
"{",
"return",
"nil",
",",
"trace",
".",
"BadParameter",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"&",
"SigningKeyStore",
"{",
"privateKey",
":",
"rsaKey",
",",
"cert",
":",
"certASN",
".",
"Bytes",
"}",
",",
"nil",
"\n",
"}"
] | // ParseSigningKeyStore parses signing key store from PEM encoded key pair | [
"ParseSigningKeyStore",
"parses",
"signing",
"key",
"store",
"from",
"PEM",
"encoded",
"key",
"pair"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/certs.go#L36-L54 | train |
gravitational/teleport | lib/utils/certs.go | ParseCertificateRequestPEM | func ParseCertificateRequestPEM(bytes []byte) (*x509.CertificateRequest, error) {
block, _ := pem.Decode(bytes)
if block == nil {
return nil, trace.BadParameter("expected PEM-encoded block")
}
csr, err := x509.ParseCertificateRequest(block.Bytes)
if err != nil {
return nil, trace.BadParameter(err.Error())
}
return csr, nil
} | go | func ParseCertificateRequestPEM(bytes []byte) (*x509.CertificateRequest, error) {
block, _ := pem.Decode(bytes)
if block == nil {
return nil, trace.BadParameter("expected PEM-encoded block")
}
csr, err := x509.ParseCertificateRequest(block.Bytes)
if err != nil {
return nil, trace.BadParameter(err.Error())
}
return csr, nil
} | [
"func",
"ParseCertificateRequestPEM",
"(",
"bytes",
"[",
"]",
"byte",
")",
"(",
"*",
"x509",
".",
"CertificateRequest",
",",
"error",
")",
"{",
"block",
",",
"_",
":=",
"pem",
".",
"Decode",
"(",
"bytes",
")",
"\n",
"if",
"block",
"==",
"nil",
"{",
"return",
"nil",
",",
"trace",
".",
"BadParameter",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"csr",
",",
"err",
":=",
"x509",
".",
"ParseCertificateRequest",
"(",
"block",
".",
"Bytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"trace",
".",
"BadParameter",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"csr",
",",
"nil",
"\n",
"}"
] | // ParseCertificateRequestPEM parses PEM-encoded certificate signing request | [
"ParseCertificateRequestPEM",
"parses",
"PEM",
"-",
"encoded",
"certificate",
"signing",
"request"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/certs.go#L105-L115 | train |
gravitational/teleport | lib/utils/certs.go | ParseCertificatePEM | func ParseCertificatePEM(bytes []byte) (*x509.Certificate, error) {
block, _ := pem.Decode(bytes)
if block == nil {
return nil, trace.BadParameter("expected PEM-encoded block")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, trace.BadParameter(err.Error())
}
return cert, nil
} | go | func ParseCertificatePEM(bytes []byte) (*x509.Certificate, error) {
block, _ := pem.Decode(bytes)
if block == nil {
return nil, trace.BadParameter("expected PEM-encoded block")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, trace.BadParameter(err.Error())
}
return cert, nil
} | [
"func",
"ParseCertificatePEM",
"(",
"bytes",
"[",
"]",
"byte",
")",
"(",
"*",
"x509",
".",
"Certificate",
",",
"error",
")",
"{",
"block",
",",
"_",
":=",
"pem",
".",
"Decode",
"(",
"bytes",
")",
"\n",
"if",
"block",
"==",
"nil",
"{",
"return",
"nil",
",",
"trace",
".",
"BadParameter",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"cert",
",",
"err",
":=",
"x509",
".",
"ParseCertificate",
"(",
"block",
".",
"Bytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"trace",
".",
"BadParameter",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"cert",
",",
"nil",
"\n",
"}"
] | // ParseCertificatePEM parses PEM-encoded certificate | [
"ParseCertificatePEM",
"parses",
"PEM",
"-",
"encoded",
"certificate"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/certs.go#L118-L128 | train |
gravitational/teleport | lib/utils/certs.go | ParsePrivateKeyPEM | func ParsePrivateKeyPEM(bytes []byte) (crypto.Signer, error) {
block, _ := pem.Decode(bytes)
if block == nil {
return nil, trace.BadParameter("expected PEM-encoded block")
}
return ParsePrivateKeyDER(block.Bytes)
} | go | func ParsePrivateKeyPEM(bytes []byte) (crypto.Signer, error) {
block, _ := pem.Decode(bytes)
if block == nil {
return nil, trace.BadParameter("expected PEM-encoded block")
}
return ParsePrivateKeyDER(block.Bytes)
} | [
"func",
"ParsePrivateKeyPEM",
"(",
"bytes",
"[",
"]",
"byte",
")",
"(",
"crypto",
".",
"Signer",
",",
"error",
")",
"{",
"block",
",",
"_",
":=",
"pem",
".",
"Decode",
"(",
"bytes",
")",
"\n",
"if",
"block",
"==",
"nil",
"{",
"return",
"nil",
",",
"trace",
".",
"BadParameter",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"ParsePrivateKeyDER",
"(",
"block",
".",
"Bytes",
")",
"\n",
"}"
] | // ParsePrivateKeyPEM parses PEM-encoded private key | [
"ParsePrivateKeyPEM",
"parses",
"PEM",
"-",
"encoded",
"private",
"key"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/certs.go#L131-L137 | train |
gravitational/teleport | lib/utils/certs.go | ParsePrivateKeyDER | func ParsePrivateKeyDER(der []byte) (crypto.Signer, error) {
generalKey, err := x509.ParsePKCS8PrivateKey(der)
if err != nil {
generalKey, err = x509.ParsePKCS1PrivateKey(der)
if err != nil {
generalKey, err = x509.ParseECPrivateKey(der)
if err != nil {
logrus.Errorf("Failed to parse key: %v.", err)
return nil, trace.BadParameter("failed parsing private key")
}
}
}
switch generalKey.(type) {
case *rsa.PrivateKey:
return generalKey.(*rsa.PrivateKey), nil
case *ecdsa.PrivateKey:
return generalKey.(*ecdsa.PrivateKey), nil
}
return nil, trace.BadParameter("unsupported private key type")
} | go | func ParsePrivateKeyDER(der []byte) (crypto.Signer, error) {
generalKey, err := x509.ParsePKCS8PrivateKey(der)
if err != nil {
generalKey, err = x509.ParsePKCS1PrivateKey(der)
if err != nil {
generalKey, err = x509.ParseECPrivateKey(der)
if err != nil {
logrus.Errorf("Failed to parse key: %v.", err)
return nil, trace.BadParameter("failed parsing private key")
}
}
}
switch generalKey.(type) {
case *rsa.PrivateKey:
return generalKey.(*rsa.PrivateKey), nil
case *ecdsa.PrivateKey:
return generalKey.(*ecdsa.PrivateKey), nil
}
return nil, trace.BadParameter("unsupported private key type")
} | [
"func",
"ParsePrivateKeyDER",
"(",
"der",
"[",
"]",
"byte",
")",
"(",
"crypto",
".",
"Signer",
",",
"error",
")",
"{",
"generalKey",
",",
"err",
":=",
"x509",
".",
"ParsePKCS8PrivateKey",
"(",
"der",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"generalKey",
",",
"err",
"=",
"x509",
".",
"ParsePKCS1PrivateKey",
"(",
"der",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"generalKey",
",",
"err",
"=",
"x509",
".",
"ParseECPrivateKey",
"(",
"der",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"trace",
".",
"BadParameter",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"switch",
"generalKey",
".",
"(",
"type",
")",
"{",
"case",
"*",
"rsa",
".",
"PrivateKey",
":",
"return",
"generalKey",
".",
"(",
"*",
"rsa",
".",
"PrivateKey",
")",
",",
"nil",
"\n",
"case",
"*",
"ecdsa",
".",
"PrivateKey",
":",
"return",
"generalKey",
".",
"(",
"*",
"ecdsa",
".",
"PrivateKey",
")",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"trace",
".",
"BadParameter",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // ParsePrivateKeyDER parses unencrypted DER-encoded private key | [
"ParsePrivateKeyDER",
"parses",
"unencrypted",
"DER",
"-",
"encoded",
"private",
"key"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/certs.go#L140-L161 | train |
gravitational/teleport | lib/utils/certs.go | ReadCertificateChain | func ReadCertificateChain(certificateChainBytes []byte) ([]*x509.Certificate, error) {
// build the certificate chain next
var certificateBlock *pem.Block
var remainingBytes []byte = bytes.TrimSpace(certificateChainBytes)
var certificateChain [][]byte
for {
certificateBlock, remainingBytes = pem.Decode(remainingBytes)
if certificateBlock == nil || certificateBlock.Type != pemBlockCertificate {
return nil, trace.NotFound("no PEM data found")
}
certificateChain = append(certificateChain, certificateBlock.Bytes)
if len(remainingBytes) == 0 {
break
}
}
// build a concatenated certificate chain
var buf bytes.Buffer
for _, cc := range certificateChain {
_, err := buf.Write(cc)
if err != nil {
return nil, trace.Wrap(err)
}
}
// parse the chain and get a slice of x509.Certificates.
x509Chain, err := x509.ParseCertificates(buf.Bytes())
if err != nil {
return nil, trace.Wrap(err)
}
return x509Chain, nil
} | go | func ReadCertificateChain(certificateChainBytes []byte) ([]*x509.Certificate, error) {
// build the certificate chain next
var certificateBlock *pem.Block
var remainingBytes []byte = bytes.TrimSpace(certificateChainBytes)
var certificateChain [][]byte
for {
certificateBlock, remainingBytes = pem.Decode(remainingBytes)
if certificateBlock == nil || certificateBlock.Type != pemBlockCertificate {
return nil, trace.NotFound("no PEM data found")
}
certificateChain = append(certificateChain, certificateBlock.Bytes)
if len(remainingBytes) == 0 {
break
}
}
// build a concatenated certificate chain
var buf bytes.Buffer
for _, cc := range certificateChain {
_, err := buf.Write(cc)
if err != nil {
return nil, trace.Wrap(err)
}
}
// parse the chain and get a slice of x509.Certificates.
x509Chain, err := x509.ParseCertificates(buf.Bytes())
if err != nil {
return nil, trace.Wrap(err)
}
return x509Chain, nil
} | [
"func",
"ReadCertificateChain",
"(",
"certificateChainBytes",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"*",
"x509",
".",
"Certificate",
",",
"error",
")",
"{",
"// build the certificate chain next",
"var",
"certificateBlock",
"*",
"pem",
".",
"Block",
"\n",
"var",
"remainingBytes",
"[",
"]",
"byte",
"=",
"bytes",
".",
"TrimSpace",
"(",
"certificateChainBytes",
")",
"\n",
"var",
"certificateChain",
"[",
"]",
"[",
"]",
"byte",
"\n\n",
"for",
"{",
"certificateBlock",
",",
"remainingBytes",
"=",
"pem",
".",
"Decode",
"(",
"remainingBytes",
")",
"\n",
"if",
"certificateBlock",
"==",
"nil",
"||",
"certificateBlock",
".",
"Type",
"!=",
"pemBlockCertificate",
"{",
"return",
"nil",
",",
"trace",
".",
"NotFound",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"certificateChain",
"=",
"append",
"(",
"certificateChain",
",",
"certificateBlock",
".",
"Bytes",
")",
"\n\n",
"if",
"len",
"(",
"remainingBytes",
")",
"==",
"0",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"// build a concatenated certificate chain",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"for",
"_",
",",
"cc",
":=",
"range",
"certificateChain",
"{",
"_",
",",
"err",
":=",
"buf",
".",
"Write",
"(",
"cc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// parse the chain and get a slice of x509.Certificates.",
"x509Chain",
",",
"err",
":=",
"x509",
".",
"ParseCertificates",
"(",
"buf",
".",
"Bytes",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"x509Chain",
",",
"nil",
"\n",
"}"
] | // ReadCertificateChain parses PEM encoded bytes that can contain one or
// multiple certificates and returns a slice of x509.Certificate. | [
"ReadCertificateChain",
"parses",
"PEM",
"encoded",
"bytes",
"that",
"can",
"contain",
"one",
"or",
"multiple",
"certificates",
"and",
"returns",
"a",
"slice",
"of",
"x509",
".",
"Certificate",
"."
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/certs.go#L226-L260 | train |
gravitational/teleport | lib/utils/loadbalancer.go | NewLoadBalancer | func NewLoadBalancer(ctx context.Context, frontend NetAddr, backends ...NetAddr) (*LoadBalancer, error) {
if ctx == nil {
return nil, trace.BadParameter("missing parameter context")
}
waitCtx, waitCancel := context.WithCancel(ctx)
return &LoadBalancer{
frontend: frontend,
ctx: ctx,
backends: backends,
currentIndex: -1,
waitCtx: waitCtx,
waitCancel: waitCancel,
Entry: log.WithFields(log.Fields{
trace.Component: "loadbalancer",
trace.ComponentFields: log.Fields{
"listen": frontend.String(),
},
}),
connections: make(map[NetAddr]map[int64]net.Conn),
}, nil
} | go | func NewLoadBalancer(ctx context.Context, frontend NetAddr, backends ...NetAddr) (*LoadBalancer, error) {
if ctx == nil {
return nil, trace.BadParameter("missing parameter context")
}
waitCtx, waitCancel := context.WithCancel(ctx)
return &LoadBalancer{
frontend: frontend,
ctx: ctx,
backends: backends,
currentIndex: -1,
waitCtx: waitCtx,
waitCancel: waitCancel,
Entry: log.WithFields(log.Fields{
trace.Component: "loadbalancer",
trace.ComponentFields: log.Fields{
"listen": frontend.String(),
},
}),
connections: make(map[NetAddr]map[int64]net.Conn),
}, nil
} | [
"func",
"NewLoadBalancer",
"(",
"ctx",
"context",
".",
"Context",
",",
"frontend",
"NetAddr",
",",
"backends",
"...",
"NetAddr",
")",
"(",
"*",
"LoadBalancer",
",",
"error",
")",
"{",
"if",
"ctx",
"==",
"nil",
"{",
"return",
"nil",
",",
"trace",
".",
"BadParameter",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"waitCtx",
",",
"waitCancel",
":=",
"context",
".",
"WithCancel",
"(",
"ctx",
")",
"\n",
"return",
"&",
"LoadBalancer",
"{",
"frontend",
":",
"frontend",
",",
"ctx",
":",
"ctx",
",",
"backends",
":",
"backends",
",",
"currentIndex",
":",
"-",
"1",
",",
"waitCtx",
":",
"waitCtx",
",",
"waitCancel",
":",
"waitCancel",
",",
"Entry",
":",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"trace",
".",
"Component",
":",
"\"",
"\"",
",",
"trace",
".",
"ComponentFields",
":",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"frontend",
".",
"String",
"(",
")",
",",
"}",
",",
"}",
")",
",",
"connections",
":",
"make",
"(",
"map",
"[",
"NetAddr",
"]",
"map",
"[",
"int64",
"]",
"net",
".",
"Conn",
")",
",",
"}",
",",
"nil",
"\n",
"}"
] | // NewLoadBalancer returns new load balancer listening on frontend
// and redirecting requests to backends using round robin algo | [
"NewLoadBalancer",
"returns",
"new",
"load",
"balancer",
"listening",
"on",
"frontend",
"and",
"redirecting",
"requests",
"to",
"backends",
"using",
"round",
"robin",
"algo"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/loadbalancer.go#L32-L52 | train |
gravitational/teleport | lib/utils/loadbalancer.go | trackConnection | func (l *LoadBalancer) trackConnection(backend NetAddr, conn net.Conn) int64 {
l.Lock()
defer l.Unlock()
l.connID += 1
tracker, ok := l.connections[backend]
if !ok {
tracker = make(map[int64]net.Conn)
l.connections[backend] = tracker
}
tracker[l.connID] = conn
return l.connID
} | go | func (l *LoadBalancer) trackConnection(backend NetAddr, conn net.Conn) int64 {
l.Lock()
defer l.Unlock()
l.connID += 1
tracker, ok := l.connections[backend]
if !ok {
tracker = make(map[int64]net.Conn)
l.connections[backend] = tracker
}
tracker[l.connID] = conn
return l.connID
} | [
"func",
"(",
"l",
"*",
"LoadBalancer",
")",
"trackConnection",
"(",
"backend",
"NetAddr",
",",
"conn",
"net",
".",
"Conn",
")",
"int64",
"{",
"l",
".",
"Lock",
"(",
")",
"\n",
"defer",
"l",
".",
"Unlock",
"(",
")",
"\n",
"l",
".",
"connID",
"+=",
"1",
"\n",
"tracker",
",",
"ok",
":=",
"l",
".",
"connections",
"[",
"backend",
"]",
"\n",
"if",
"!",
"ok",
"{",
"tracker",
"=",
"make",
"(",
"map",
"[",
"int64",
"]",
"net",
".",
"Conn",
")",
"\n",
"l",
".",
"connections",
"[",
"backend",
"]",
"=",
"tracker",
"\n",
"}",
"\n",
"tracker",
"[",
"l",
".",
"connID",
"]",
"=",
"conn",
"\n",
"return",
"l",
".",
"connID",
"\n",
"}"
] | // trackeConnection adds connection to the connection tracker | [
"trackeConnection",
"adds",
"connection",
"to",
"the",
"connection",
"tracker"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/loadbalancer.go#L72-L83 | train |
gravitational/teleport | lib/utils/loadbalancer.go | untrackConnection | func (l *LoadBalancer) untrackConnection(backend NetAddr, id int64) {
l.Lock()
defer l.Unlock()
tracker, ok := l.connections[backend]
if !ok {
return
}
delete(tracker, id)
} | go | func (l *LoadBalancer) untrackConnection(backend NetAddr, id int64) {
l.Lock()
defer l.Unlock()
tracker, ok := l.connections[backend]
if !ok {
return
}
delete(tracker, id)
} | [
"func",
"(",
"l",
"*",
"LoadBalancer",
")",
"untrackConnection",
"(",
"backend",
"NetAddr",
",",
"id",
"int64",
")",
"{",
"l",
".",
"Lock",
"(",
")",
"\n",
"defer",
"l",
".",
"Unlock",
"(",
")",
"\n",
"tracker",
",",
"ok",
":=",
"l",
".",
"connections",
"[",
"backend",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\n",
"}",
"\n",
"delete",
"(",
"tracker",
",",
"id",
")",
"\n",
"}"
] | // untrackConnection removes connection from connection tracker | [
"untrackConnection",
"removes",
"connection",
"from",
"connection",
"tracker"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/loadbalancer.go#L86-L94 | train |
gravitational/teleport | lib/utils/loadbalancer.go | dropConnections | func (l *LoadBalancer) dropConnections(backend NetAddr) {
tracker := l.connections[backend]
for _, conn := range tracker {
conn.Close()
}
delete(l.connections, backend)
} | go | func (l *LoadBalancer) dropConnections(backend NetAddr) {
tracker := l.connections[backend]
for _, conn := range tracker {
conn.Close()
}
delete(l.connections, backend)
} | [
"func",
"(",
"l",
"*",
"LoadBalancer",
")",
"dropConnections",
"(",
"backend",
"NetAddr",
")",
"{",
"tracker",
":=",
"l",
".",
"connections",
"[",
"backend",
"]",
"\n",
"for",
"_",
",",
"conn",
":=",
"range",
"tracker",
"{",
"conn",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"delete",
"(",
"l",
".",
"connections",
",",
"backend",
")",
"\n",
"}"
] | // dropConnections drops connections associated with backend | [
"dropConnections",
"drops",
"connections",
"associated",
"with",
"backend"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/loadbalancer.go#L97-L103 | train |
gravitational/teleport | lib/utils/loadbalancer.go | AddBackend | func (l *LoadBalancer) AddBackend(b NetAddr) {
l.Lock()
defer l.Unlock()
l.backends = append(l.backends, b)
l.Debugf("backends %v", l.backends)
} | go | func (l *LoadBalancer) AddBackend(b NetAddr) {
l.Lock()
defer l.Unlock()
l.backends = append(l.backends, b)
l.Debugf("backends %v", l.backends)
} | [
"func",
"(",
"l",
"*",
"LoadBalancer",
")",
"AddBackend",
"(",
"b",
"NetAddr",
")",
"{",
"l",
".",
"Lock",
"(",
")",
"\n",
"defer",
"l",
".",
"Unlock",
"(",
")",
"\n",
"l",
".",
"backends",
"=",
"append",
"(",
"l",
".",
"backends",
",",
"b",
")",
"\n",
"l",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"l",
".",
"backends",
")",
"\n",
"}"
] | // AddBackend adds backend | [
"AddBackend",
"adds",
"backend"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/loadbalancer.go#L106-L111 | train |
gravitational/teleport | lib/utils/loadbalancer.go | RemoveBackend | func (l *LoadBalancer) RemoveBackend(b NetAddr) {
l.Lock()
defer l.Unlock()
l.currentIndex = -1
for i := range l.backends {
if l.backends[i].Equals(b) {
l.backends = append(l.backends[:i], l.backends[i+1:]...)
l.dropConnections(b)
return
}
}
} | go | func (l *LoadBalancer) RemoveBackend(b NetAddr) {
l.Lock()
defer l.Unlock()
l.currentIndex = -1
for i := range l.backends {
if l.backends[i].Equals(b) {
l.backends = append(l.backends[:i], l.backends[i+1:]...)
l.dropConnections(b)
return
}
}
} | [
"func",
"(",
"l",
"*",
"LoadBalancer",
")",
"RemoveBackend",
"(",
"b",
"NetAddr",
")",
"{",
"l",
".",
"Lock",
"(",
")",
"\n",
"defer",
"l",
".",
"Unlock",
"(",
")",
"\n",
"l",
".",
"currentIndex",
"=",
"-",
"1",
"\n",
"for",
"i",
":=",
"range",
"l",
".",
"backends",
"{",
"if",
"l",
".",
"backends",
"[",
"i",
"]",
".",
"Equals",
"(",
"b",
")",
"{",
"l",
".",
"backends",
"=",
"append",
"(",
"l",
".",
"backends",
"[",
":",
"i",
"]",
",",
"l",
".",
"backends",
"[",
"i",
"+",
"1",
":",
"]",
"...",
")",
"\n",
"l",
".",
"dropConnections",
"(",
"b",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // RemoveBackend removes backend | [
"RemoveBackend",
"removes",
"backend"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/loadbalancer.go#L114-L125 | train |
gravitational/teleport | lib/utils/loadbalancer.go | ListenAndServe | func (l *LoadBalancer) ListenAndServe() error {
if err := l.Listen(); err != nil {
return trace.Wrap(err)
}
return l.Serve()
} | go | func (l *LoadBalancer) ListenAndServe() error {
if err := l.Listen(); err != nil {
return trace.Wrap(err)
}
return l.Serve()
} | [
"func",
"(",
"l",
"*",
"LoadBalancer",
")",
"ListenAndServe",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"l",
".",
"Listen",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"l",
".",
"Serve",
"(",
")",
"\n",
"}"
] | // ListenAndServe starts listening socket and serves connections on it | [
"ListenAndServe",
"starts",
"listening",
"socket",
"and",
"serves",
"connections",
"on",
"it"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/loadbalancer.go#L162-L167 | train |
gravitational/teleport | lib/utils/loadbalancer.go | Listen | func (l *LoadBalancer) Listen() error {
var err error
l.listener, err = net.Listen(l.frontend.AddrNetwork, l.frontend.Addr)
if err != nil {
return trace.ConvertSystemError(err)
}
l.Debugf("created listening socket")
return nil
} | go | func (l *LoadBalancer) Listen() error {
var err error
l.listener, err = net.Listen(l.frontend.AddrNetwork, l.frontend.Addr)
if err != nil {
return trace.ConvertSystemError(err)
}
l.Debugf("created listening socket")
return nil
} | [
"func",
"(",
"l",
"*",
"LoadBalancer",
")",
"Listen",
"(",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"l",
".",
"listener",
",",
"err",
"=",
"net",
".",
"Listen",
"(",
"l",
".",
"frontend",
".",
"AddrNetwork",
",",
"l",
".",
"frontend",
".",
"Addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"trace",
".",
"ConvertSystemError",
"(",
"err",
")",
"\n",
"}",
"\n",
"l",
".",
"Debugf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Listen creates a listener on the frontend addr | [
"Listen",
"creates",
"a",
"listener",
"on",
"the",
"frontend",
"addr"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/loadbalancer.go#L170-L178 | train |
gravitational/teleport | lib/utils/loadbalancer.go | Serve | func (l *LoadBalancer) Serve() error {
defer l.waitCancel()
backoffTimer := time.NewTicker(5 * time.Second)
defer backoffTimer.Stop()
for {
conn, err := l.listener.Accept()
if err != nil {
if l.isClosed() {
return trace.ConnectionProblem(nil, "listener is closed")
}
select {
case <-backoffTimer.C:
l.Debugf("backoff on network error")
case <-l.ctx.Done():
return trace.ConnectionProblem(nil, "context is closing")
}
}
go l.forwardConnection(conn)
}
} | go | func (l *LoadBalancer) Serve() error {
defer l.waitCancel()
backoffTimer := time.NewTicker(5 * time.Second)
defer backoffTimer.Stop()
for {
conn, err := l.listener.Accept()
if err != nil {
if l.isClosed() {
return trace.ConnectionProblem(nil, "listener is closed")
}
select {
case <-backoffTimer.C:
l.Debugf("backoff on network error")
case <-l.ctx.Done():
return trace.ConnectionProblem(nil, "context is closing")
}
}
go l.forwardConnection(conn)
}
} | [
"func",
"(",
"l",
"*",
"LoadBalancer",
")",
"Serve",
"(",
")",
"error",
"{",
"defer",
"l",
".",
"waitCancel",
"(",
")",
"\n",
"backoffTimer",
":=",
"time",
".",
"NewTicker",
"(",
"5",
"*",
"time",
".",
"Second",
")",
"\n",
"defer",
"backoffTimer",
".",
"Stop",
"(",
")",
"\n",
"for",
"{",
"conn",
",",
"err",
":=",
"l",
".",
"listener",
".",
"Accept",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"l",
".",
"isClosed",
"(",
")",
"{",
"return",
"trace",
".",
"ConnectionProblem",
"(",
"nil",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"select",
"{",
"case",
"<-",
"backoffTimer",
".",
"C",
":",
"l",
".",
"Debugf",
"(",
"\"",
"\"",
")",
"\n",
"case",
"<-",
"l",
".",
"ctx",
".",
"Done",
"(",
")",
":",
"return",
"trace",
".",
"ConnectionProblem",
"(",
"nil",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"go",
"l",
".",
"forwardConnection",
"(",
"conn",
")",
"\n",
"}",
"\n",
"}"
] | // Serve starts accepting connections | [
"Serve",
"starts",
"accepting",
"connections"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/loadbalancer.go#L181-L200 | train |
gravitational/teleport | lib/events/sessionlog.go | NewDiskSessionLogger | func NewDiskSessionLogger(cfg DiskSessionLoggerConfig) (*DiskSessionLogger, error) {
if err := cfg.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
var err error
sessionDir := filepath.Join(cfg.DataDir, cfg.ServerID, SessionLogsDir, cfg.Namespace)
indexFile, err := os.OpenFile(
filepath.Join(sessionDir, fmt.Sprintf("%v.index", cfg.SessionID.String())), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0640)
if err != nil {
return nil, trace.Wrap(err)
}
sessionLogger := &DiskSessionLogger{
DiskSessionLoggerConfig: cfg,
Entry: log.WithFields(log.Fields{
trace.Component: teleport.ComponentAuditLog,
trace.ComponentFields: log.Fields{
"sid": cfg.SessionID,
},
}),
sessionDir: sessionDir,
indexFile: indexFile,
lastEventIndex: -1,
lastChunkIndex: -1,
}
return sessionLogger, nil
} | go | func NewDiskSessionLogger(cfg DiskSessionLoggerConfig) (*DiskSessionLogger, error) {
if err := cfg.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
var err error
sessionDir := filepath.Join(cfg.DataDir, cfg.ServerID, SessionLogsDir, cfg.Namespace)
indexFile, err := os.OpenFile(
filepath.Join(sessionDir, fmt.Sprintf("%v.index", cfg.SessionID.String())), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0640)
if err != nil {
return nil, trace.Wrap(err)
}
sessionLogger := &DiskSessionLogger{
DiskSessionLoggerConfig: cfg,
Entry: log.WithFields(log.Fields{
trace.Component: teleport.ComponentAuditLog,
trace.ComponentFields: log.Fields{
"sid": cfg.SessionID,
},
}),
sessionDir: sessionDir,
indexFile: indexFile,
lastEventIndex: -1,
lastChunkIndex: -1,
}
return sessionLogger, nil
} | [
"func",
"NewDiskSessionLogger",
"(",
"cfg",
"DiskSessionLoggerConfig",
")",
"(",
"*",
"DiskSessionLogger",
",",
"error",
")",
"{",
"if",
"err",
":=",
"cfg",
".",
"CheckAndSetDefaults",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"var",
"err",
"error",
"\n\n",
"sessionDir",
":=",
"filepath",
".",
"Join",
"(",
"cfg",
".",
"DataDir",
",",
"cfg",
".",
"ServerID",
",",
"SessionLogsDir",
",",
"cfg",
".",
"Namespace",
")",
"\n",
"indexFile",
",",
"err",
":=",
"os",
".",
"OpenFile",
"(",
"filepath",
".",
"Join",
"(",
"sessionDir",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"cfg",
".",
"SessionID",
".",
"String",
"(",
")",
")",
")",
",",
"os",
".",
"O_WRONLY",
"|",
"os",
".",
"O_CREATE",
"|",
"os",
".",
"O_APPEND",
",",
"0640",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"sessionLogger",
":=",
"&",
"DiskSessionLogger",
"{",
"DiskSessionLoggerConfig",
":",
"cfg",
",",
"Entry",
":",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"trace",
".",
"Component",
":",
"teleport",
".",
"ComponentAuditLog",
",",
"trace",
".",
"ComponentFields",
":",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"cfg",
".",
"SessionID",
",",
"}",
",",
"}",
")",
",",
"sessionDir",
":",
"sessionDir",
",",
"indexFile",
":",
"indexFile",
",",
"lastEventIndex",
":",
"-",
"1",
",",
"lastChunkIndex",
":",
"-",
"1",
",",
"}",
"\n",
"return",
"sessionLogger",
",",
"nil",
"\n",
"}"
] | // NewDiskSessionLogger creates new disk based session logger | [
"NewDiskSessionLogger",
"creates",
"new",
"disk",
"based",
"session",
"logger"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/sessionlog.go#L80-L107 | train |
gravitational/teleport | lib/events/sessionlog.go | Finalize | func (sl *DiskSessionLogger) Finalize() error {
sl.Lock()
defer sl.Unlock()
return sl.finalize()
} | go | func (sl *DiskSessionLogger) Finalize() error {
sl.Lock()
defer sl.Unlock()
return sl.finalize()
} | [
"func",
"(",
"sl",
"*",
"DiskSessionLogger",
")",
"Finalize",
"(",
")",
"error",
"{",
"sl",
".",
"Lock",
"(",
")",
"\n",
"defer",
"sl",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"sl",
".",
"finalize",
"(",
")",
"\n",
"}"
] | // Finalize is called by the session when it's closing. This is where we're
// releasing audit resources associated with the session | [
"Finalize",
"is",
"called",
"by",
"the",
"session",
"when",
"it",
"s",
"closing",
".",
"This",
"is",
"where",
"we",
"re",
"releasing",
"audit",
"resources",
"associated",
"with",
"the",
"session"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/sessionlog.go#L163-L168 | train |
gravitational/teleport | lib/events/sessionlog.go | flush | func (sl *DiskSessionLogger) flush() error {
var err, err2 error
if sl.RecordSessions && sl.chunksFile != nil {
err = sl.chunksFile.Flush()
}
if sl.eventsFile != nil {
err2 = sl.eventsFile.Flush()
}
return trace.NewAggregate(err, err2)
} | go | func (sl *DiskSessionLogger) flush() error {
var err, err2 error
if sl.RecordSessions && sl.chunksFile != nil {
err = sl.chunksFile.Flush()
}
if sl.eventsFile != nil {
err2 = sl.eventsFile.Flush()
}
return trace.NewAggregate(err, err2)
} | [
"func",
"(",
"sl",
"*",
"DiskSessionLogger",
")",
"flush",
"(",
")",
"error",
"{",
"var",
"err",
",",
"err2",
"error",
"\n\n",
"if",
"sl",
".",
"RecordSessions",
"&&",
"sl",
".",
"chunksFile",
"!=",
"nil",
"{",
"err",
"=",
"sl",
".",
"chunksFile",
".",
"Flush",
"(",
")",
"\n",
"}",
"\n",
"if",
"sl",
".",
"eventsFile",
"!=",
"nil",
"{",
"err2",
"=",
"sl",
".",
"eventsFile",
".",
"Flush",
"(",
")",
"\n",
"}",
"\n",
"return",
"trace",
".",
"NewAggregate",
"(",
"err",
",",
"err2",
")",
"\n",
"}"
] | // flush is used to flush gzip frames to file, otherwise
// some attempts to read the file could fail | [
"flush",
"is",
"used",
"to",
"flush",
"gzip",
"frames",
"to",
"file",
"otherwise",
"some",
"attempts",
"to",
"read",
"the",
"file",
"could",
"fail"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/sessionlog.go#L172-L182 | train |
gravitational/teleport | lib/events/sessionlog.go | eventsFileName | func eventsFileName(dataDir string, sessionID session.ID, eventIndex int64) string {
return filepath.Join(dataDir, fmt.Sprintf("%v-%v.events.gz", sessionID.String(), eventIndex))
} | go | func eventsFileName(dataDir string, sessionID session.ID, eventIndex int64) string {
return filepath.Join(dataDir, fmt.Sprintf("%v-%v.events.gz", sessionID.String(), eventIndex))
} | [
"func",
"eventsFileName",
"(",
"dataDir",
"string",
",",
"sessionID",
"session",
".",
"ID",
",",
"eventIndex",
"int64",
")",
"string",
"{",
"return",
"filepath",
".",
"Join",
"(",
"dataDir",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"sessionID",
".",
"String",
"(",
")",
",",
"eventIndex",
")",
")",
"\n",
"}"
] | // eventsFileName consists of session id and the first global event index recorded there | [
"eventsFileName",
"consists",
"of",
"session",
"id",
"and",
"the",
"first",
"global",
"event",
"index",
"recorded",
"there"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/sessionlog.go#L215-L217 | train |
gravitational/teleport | lib/events/sessionlog.go | chunksFileName | func chunksFileName(dataDir string, sessionID session.ID, offset int64) string {
return filepath.Join(dataDir, fmt.Sprintf("%v-%v.chunks.gz", sessionID.String(), offset))
} | go | func chunksFileName(dataDir string, sessionID session.ID, offset int64) string {
return filepath.Join(dataDir, fmt.Sprintf("%v-%v.chunks.gz", sessionID.String(), offset))
} | [
"func",
"chunksFileName",
"(",
"dataDir",
"string",
",",
"sessionID",
"session",
".",
"ID",
",",
"offset",
"int64",
")",
"string",
"{",
"return",
"filepath",
".",
"Join",
"(",
"dataDir",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"sessionID",
".",
"String",
"(",
")",
",",
"offset",
")",
")",
"\n",
"}"
] | // chunksFileName consists of session id and the first global offset recorded | [
"chunksFileName",
"consists",
"of",
"session",
"id",
"and",
"the",
"first",
"global",
"offset",
"recorded"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/sessionlog.go#L220-L222 | train |
gravitational/teleport | lib/events/sessionlog.go | PostSessionSlice | func (sl *DiskSessionLogger) PostSessionSlice(slice SessionSlice) error {
sl.Lock()
defer sl.Unlock()
for i := range slice.Chunks {
_, err := sl.writeChunk(slice.SessionID, slice.Chunks[i])
if err != nil {
return trace.Wrap(err)
}
}
return sl.flush()
} | go | func (sl *DiskSessionLogger) PostSessionSlice(slice SessionSlice) error {
sl.Lock()
defer sl.Unlock()
for i := range slice.Chunks {
_, err := sl.writeChunk(slice.SessionID, slice.Chunks[i])
if err != nil {
return trace.Wrap(err)
}
}
return sl.flush()
} | [
"func",
"(",
"sl",
"*",
"DiskSessionLogger",
")",
"PostSessionSlice",
"(",
"slice",
"SessionSlice",
")",
"error",
"{",
"sl",
".",
"Lock",
"(",
")",
"\n",
"defer",
"sl",
".",
"Unlock",
"(",
")",
"\n\n",
"for",
"i",
":=",
"range",
"slice",
".",
"Chunks",
"{",
"_",
",",
"err",
":=",
"sl",
".",
"writeChunk",
"(",
"slice",
".",
"SessionID",
",",
"slice",
".",
"Chunks",
"[",
"i",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"sl",
".",
"flush",
"(",
")",
"\n",
"}"
] | // PostSessionSlice takes series of events associated with the session
// and writes them to events files and data file for future replays | [
"PostSessionSlice",
"takes",
"series",
"of",
"events",
"associated",
"with",
"the",
"session",
"and",
"writes",
"them",
"to",
"events",
"files",
"and",
"data",
"file",
"for",
"future",
"replays"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/sessionlog.go#L292-L303 | train |
gravitational/teleport | lib/events/sessionlog.go | EventFromChunk | func EventFromChunk(sessionID string, chunk *SessionChunk) (EventFields, error) {
var fields EventFields
eventStart := time.Unix(0, chunk.Time).In(time.UTC).Round(time.Millisecond)
err := json.Unmarshal(chunk.Data, &fields)
if err != nil {
return nil, trace.Wrap(err)
}
fields[SessionEventID] = sessionID
fields[EventIndex] = chunk.EventIndex
fields[EventTime] = eventStart
fields[EventType] = chunk.EventType
if fields[EventID] == "" {
fields[EventID] = uuid.New()
}
return fields, nil
} | go | func EventFromChunk(sessionID string, chunk *SessionChunk) (EventFields, error) {
var fields EventFields
eventStart := time.Unix(0, chunk.Time).In(time.UTC).Round(time.Millisecond)
err := json.Unmarshal(chunk.Data, &fields)
if err != nil {
return nil, trace.Wrap(err)
}
fields[SessionEventID] = sessionID
fields[EventIndex] = chunk.EventIndex
fields[EventTime] = eventStart
fields[EventType] = chunk.EventType
if fields[EventID] == "" {
fields[EventID] = uuid.New()
}
return fields, nil
} | [
"func",
"EventFromChunk",
"(",
"sessionID",
"string",
",",
"chunk",
"*",
"SessionChunk",
")",
"(",
"EventFields",
",",
"error",
")",
"{",
"var",
"fields",
"EventFields",
"\n",
"eventStart",
":=",
"time",
".",
"Unix",
"(",
"0",
",",
"chunk",
".",
"Time",
")",
".",
"In",
"(",
"time",
".",
"UTC",
")",
".",
"Round",
"(",
"time",
".",
"Millisecond",
")",
"\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"chunk",
".",
"Data",
",",
"&",
"fields",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"fields",
"[",
"SessionEventID",
"]",
"=",
"sessionID",
"\n",
"fields",
"[",
"EventIndex",
"]",
"=",
"chunk",
".",
"EventIndex",
"\n",
"fields",
"[",
"EventTime",
"]",
"=",
"eventStart",
"\n",
"fields",
"[",
"EventType",
"]",
"=",
"chunk",
".",
"EventType",
"\n",
"if",
"fields",
"[",
"EventID",
"]",
"==",
"\"",
"\"",
"{",
"fields",
"[",
"EventID",
"]",
"=",
"uuid",
".",
"New",
"(",
")",
"\n",
"}",
"\n",
"return",
"fields",
",",
"nil",
"\n",
"}"
] | // EventFromChunk returns event converted from session chunk | [
"EventFromChunk",
"returns",
"event",
"converted",
"from",
"session",
"chunk"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/sessionlog.go#L306-L321 | train |
gravitational/teleport | lib/events/sessionlog.go | Close | func (f *gzipWriter) Close() error {
var errors []error
if f.Writer != nil {
errors = append(errors, f.Writer.Close())
f.Writer.Reset(ioutil.Discard)
writerPool.Put(f.Writer)
f.Writer = nil
}
if f.file != nil {
errors = append(errors, f.file.Close())
f.file = nil
}
return trace.NewAggregate(errors...)
} | go | func (f *gzipWriter) Close() error {
var errors []error
if f.Writer != nil {
errors = append(errors, f.Writer.Close())
f.Writer.Reset(ioutil.Discard)
writerPool.Put(f.Writer)
f.Writer = nil
}
if f.file != nil {
errors = append(errors, f.file.Close())
f.file = nil
}
return trace.NewAggregate(errors...)
} | [
"func",
"(",
"f",
"*",
"gzipWriter",
")",
"Close",
"(",
")",
"error",
"{",
"var",
"errors",
"[",
"]",
"error",
"\n",
"if",
"f",
".",
"Writer",
"!=",
"nil",
"{",
"errors",
"=",
"append",
"(",
"errors",
",",
"f",
".",
"Writer",
".",
"Close",
"(",
")",
")",
"\n",
"f",
".",
"Writer",
".",
"Reset",
"(",
"ioutil",
".",
"Discard",
")",
"\n",
"writerPool",
".",
"Put",
"(",
"f",
".",
"Writer",
")",
"\n",
"f",
".",
"Writer",
"=",
"nil",
"\n",
"}",
"\n",
"if",
"f",
".",
"file",
"!=",
"nil",
"{",
"errors",
"=",
"append",
"(",
"errors",
",",
"f",
".",
"file",
".",
"Close",
"(",
")",
")",
"\n",
"f",
".",
"file",
"=",
"nil",
"\n",
"}",
"\n",
"return",
"trace",
".",
"NewAggregate",
"(",
"errors",
"...",
")",
"\n",
"}"
] | // Close closes gzip writer and file | [
"Close",
"closes",
"gzip",
"writer",
"and",
"file"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/sessionlog.go#L421-L434 | train |
gravitational/teleport | lib/events/sessionlog.go | Close | func (f *gzipReader) Close() error {
var errors []error
if f.ReadCloser != nil {
errors = append(errors, f.ReadCloser.Close())
f.ReadCloser = nil
}
if f.file != nil {
errors = append(errors, f.file.Close())
f.file = nil
}
return trace.NewAggregate(errors...)
} | go | func (f *gzipReader) Close() error {
var errors []error
if f.ReadCloser != nil {
errors = append(errors, f.ReadCloser.Close())
f.ReadCloser = nil
}
if f.file != nil {
errors = append(errors, f.file.Close())
f.file = nil
}
return trace.NewAggregate(errors...)
} | [
"func",
"(",
"f",
"*",
"gzipReader",
")",
"Close",
"(",
")",
"error",
"{",
"var",
"errors",
"[",
"]",
"error",
"\n",
"if",
"f",
".",
"ReadCloser",
"!=",
"nil",
"{",
"errors",
"=",
"append",
"(",
"errors",
",",
"f",
".",
"ReadCloser",
".",
"Close",
"(",
")",
")",
"\n",
"f",
".",
"ReadCloser",
"=",
"nil",
"\n",
"}",
"\n",
"if",
"f",
".",
"file",
"!=",
"nil",
"{",
"errors",
"=",
"append",
"(",
"errors",
",",
"f",
".",
"file",
".",
"Close",
"(",
")",
")",
"\n",
"f",
".",
"file",
"=",
"nil",
"\n",
"}",
"\n",
"return",
"trace",
".",
"NewAggregate",
"(",
"errors",
"...",
")",
"\n",
"}"
] | // Close closes file and gzip writer | [
"Close",
"closes",
"file",
"and",
"gzip",
"writer"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/sessionlog.go#L463-L474 | train |
gravitational/teleport | lib/srv/heartbeat.go | String | func (h HeartbeatMode) String() string {
switch h {
case HeartbeatModeNode:
return "Node"
case HeartbeatModeProxy:
return "Proxy"
case HeartbeatModeAuth:
return "Auth"
default:
return fmt.Sprintf("<unknown: %v>", int(h))
}
} | go | func (h HeartbeatMode) String() string {
switch h {
case HeartbeatModeNode:
return "Node"
case HeartbeatModeProxy:
return "Proxy"
case HeartbeatModeAuth:
return "Auth"
default:
return fmt.Sprintf("<unknown: %v>", int(h))
}
} | [
"func",
"(",
"h",
"HeartbeatMode",
")",
"String",
"(",
")",
"string",
"{",
"switch",
"h",
"{",
"case",
"HeartbeatModeNode",
":",
"return",
"\"",
"\"",
"\n",
"case",
"HeartbeatModeProxy",
":",
"return",
"\"",
"\"",
"\n",
"case",
"HeartbeatModeAuth",
":",
"return",
"\"",
"\"",
"\n",
"default",
":",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"int",
"(",
"h",
")",
")",
"\n",
"}",
"\n",
"}"
] | // String returns user-friendly representation of the mode | [
"String",
"returns",
"user",
"-",
"friendly",
"representation",
"of",
"the",
"mode"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/heartbeat.go#L88-L99 | train |
gravitational/teleport | lib/srv/heartbeat.go | NewHeartbeat | func NewHeartbeat(cfg HeartbeatConfig) (*Heartbeat, error) {
if err := cfg.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
ctx, cancel := context.WithCancel(cfg.Context)
h := &Heartbeat{
cancelCtx: ctx,
cancel: cancel,
HeartbeatConfig: cfg,
Entry: log.WithFields(log.Fields{
trace.Component: teleport.Component(cfg.Component, "beat"),
}),
checkTicker: time.NewTicker(cfg.CheckPeriod),
announceC: make(chan struct{}, 1),
sendC: make(chan struct{}, 1),
}
h.Debugf("Starting %v heartbeat with announce period: %v, keep-alive period %v, poll period: %v", cfg.Mode, cfg.KeepAlivePeriod, cfg.AnnouncePeriod, cfg.CheckPeriod)
return h, nil
} | go | func NewHeartbeat(cfg HeartbeatConfig) (*Heartbeat, error) {
if err := cfg.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
ctx, cancel := context.WithCancel(cfg.Context)
h := &Heartbeat{
cancelCtx: ctx,
cancel: cancel,
HeartbeatConfig: cfg,
Entry: log.WithFields(log.Fields{
trace.Component: teleport.Component(cfg.Component, "beat"),
}),
checkTicker: time.NewTicker(cfg.CheckPeriod),
announceC: make(chan struct{}, 1),
sendC: make(chan struct{}, 1),
}
h.Debugf("Starting %v heartbeat with announce period: %v, keep-alive period %v, poll period: %v", cfg.Mode, cfg.KeepAlivePeriod, cfg.AnnouncePeriod, cfg.CheckPeriod)
return h, nil
} | [
"func",
"NewHeartbeat",
"(",
"cfg",
"HeartbeatConfig",
")",
"(",
"*",
"Heartbeat",
",",
"error",
")",
"{",
"if",
"err",
":=",
"cfg",
".",
"CheckAndSetDefaults",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"ctx",
",",
"cancel",
":=",
"context",
".",
"WithCancel",
"(",
"cfg",
".",
"Context",
")",
"\n",
"h",
":=",
"&",
"Heartbeat",
"{",
"cancelCtx",
":",
"ctx",
",",
"cancel",
":",
"cancel",
",",
"HeartbeatConfig",
":",
"cfg",
",",
"Entry",
":",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"trace",
".",
"Component",
":",
"teleport",
".",
"Component",
"(",
"cfg",
".",
"Component",
",",
"\"",
"\"",
")",
",",
"}",
")",
",",
"checkTicker",
":",
"time",
".",
"NewTicker",
"(",
"cfg",
".",
"CheckPeriod",
")",
",",
"announceC",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"1",
")",
",",
"sendC",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"1",
")",
",",
"}",
"\n",
"h",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"cfg",
".",
"Mode",
",",
"cfg",
".",
"KeepAlivePeriod",
",",
"cfg",
".",
"AnnouncePeriod",
",",
"cfg",
".",
"CheckPeriod",
")",
"\n",
"return",
"h",
",",
"nil",
"\n",
"}"
] | // NewHeartbeat returns a new instance of heartbeat | [
"NewHeartbeat",
"returns",
"a",
"new",
"instance",
"of",
"heartbeat"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/heartbeat.go#L114-L132 | train |
gravitational/teleport | lib/srv/heartbeat.go | Run | func (h *Heartbeat) Run() error {
defer func() {
h.reset(HeartbeatStateInit)
h.checkTicker.Stop()
}()
for {
if err := h.fetchAndAnnounce(); err != nil {
h.Warningf("Heartbeat failed %v.", err)
}
select {
case <-h.checkTicker.C:
case <-h.sendC:
h.Debugf("Asked check out of cycle")
case <-h.cancelCtx.Done():
h.Debugf("Heartbeat exited.")
return nil
}
}
} | go | func (h *Heartbeat) Run() error {
defer func() {
h.reset(HeartbeatStateInit)
h.checkTicker.Stop()
}()
for {
if err := h.fetchAndAnnounce(); err != nil {
h.Warningf("Heartbeat failed %v.", err)
}
select {
case <-h.checkTicker.C:
case <-h.sendC:
h.Debugf("Asked check out of cycle")
case <-h.cancelCtx.Done():
h.Debugf("Heartbeat exited.")
return nil
}
}
} | [
"func",
"(",
"h",
"*",
"Heartbeat",
")",
"Run",
"(",
")",
"error",
"{",
"defer",
"func",
"(",
")",
"{",
"h",
".",
"reset",
"(",
"HeartbeatStateInit",
")",
"\n",
"h",
".",
"checkTicker",
".",
"Stop",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"for",
"{",
"if",
"err",
":=",
"h",
".",
"fetchAndAnnounce",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"h",
".",
"Warningf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"select",
"{",
"case",
"<-",
"h",
".",
"checkTicker",
".",
"C",
":",
"case",
"<-",
"h",
".",
"sendC",
":",
"h",
".",
"Debugf",
"(",
"\"",
"\"",
")",
"\n",
"case",
"<-",
"h",
".",
"cancelCtx",
".",
"Done",
"(",
")",
":",
"h",
".",
"Debugf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Run periodically calls to announce presence,
// should be called explicitly in a separate goroutine | [
"Run",
"periodically",
"calls",
"to",
"announce",
"presence",
"should",
"be",
"called",
"explicitly",
"in",
"a",
"separate",
"goroutine"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/heartbeat.go#L233-L251 | train |
gravitational/teleport | lib/srv/heartbeat.go | reset | func (h *Heartbeat) reset(state KeepAliveState) {
h.setState(state)
h.nextAnnounce = time.Time{}
h.nextKeepAlive = time.Time{}
h.keepAlive = nil
if h.keepAliver != nil {
if err := h.keepAliver.Close(); err != nil {
h.Warningf("Failed to close keep aliver: %v", err)
}
h.keepAliver = nil
}
} | go | func (h *Heartbeat) reset(state KeepAliveState) {
h.setState(state)
h.nextAnnounce = time.Time{}
h.nextKeepAlive = time.Time{}
h.keepAlive = nil
if h.keepAliver != nil {
if err := h.keepAliver.Close(); err != nil {
h.Warningf("Failed to close keep aliver: %v", err)
}
h.keepAliver = nil
}
} | [
"func",
"(",
"h",
"*",
"Heartbeat",
")",
"reset",
"(",
"state",
"KeepAliveState",
")",
"{",
"h",
".",
"setState",
"(",
"state",
")",
"\n",
"h",
".",
"nextAnnounce",
"=",
"time",
".",
"Time",
"{",
"}",
"\n",
"h",
".",
"nextKeepAlive",
"=",
"time",
".",
"Time",
"{",
"}",
"\n",
"h",
".",
"keepAlive",
"=",
"nil",
"\n",
"if",
"h",
".",
"keepAliver",
"!=",
"nil",
"{",
"if",
"err",
":=",
"h",
".",
"keepAliver",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"h",
".",
"Warningf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"h",
".",
"keepAliver",
"=",
"nil",
"\n",
"}",
"\n",
"}"
] | // reset resets keep alive state
// and sends the state back to the initial state
// of sending full update | [
"reset",
"resets",
"keep",
"alive",
"state",
"and",
"sends",
"the",
"state",
"back",
"to",
"the",
"initial",
"state",
"of",
"sending",
"full",
"update"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/heartbeat.go#L276-L287 | train |
gravitational/teleport | lib/srv/heartbeat.go | fetch | func (h *Heartbeat) fetch() error {
// failed to fetch server info?
// reset to init state regardless of the current state
server, err := h.GetServerInfo()
if err != nil {
h.reset(HeartbeatStateInit)
return trace.Wrap(err)
}
switch h.state {
// in case of successfull state fetch, move to announce from init
case HeartbeatStateInit:
h.current = server
h.reset(HeartbeatStateAnnounce)
return nil
// nothing to do in announce state
case HeartbeatStateAnnounce:
return nil
case HeartbeatStateAnnounceWait:
// time to announce
if h.Clock.Now().UTC().After(h.nextAnnounce) {
h.current = server
h.reset(HeartbeatStateAnnounce)
return nil
}
result := services.CompareServers(h.current, server)
// server update happened, time to announce
if result == services.Different {
h.current = server
h.reset(HeartbeatStateAnnounce)
}
return nil
// nothing to do in keep alive state
case HeartbeatStateKeepAlive:
return nil
// Stay in keep alive state in case
// if there are no changes
case HeartbeatStateKeepAliveWait:
// time to send a new keep alive
if h.Clock.Now().UTC().After(h.nextKeepAlive) {
h.setState(HeartbeatStateKeepAlive)
return nil
}
result := services.CompareServers(h.current, server)
// server update happened, move to announce
if result == services.Different {
h.current = server
h.reset(HeartbeatStateAnnounce)
}
return nil
default:
return trace.BadParameter("unsupported state: %v", h.state)
}
} | go | func (h *Heartbeat) fetch() error {
// failed to fetch server info?
// reset to init state regardless of the current state
server, err := h.GetServerInfo()
if err != nil {
h.reset(HeartbeatStateInit)
return trace.Wrap(err)
}
switch h.state {
// in case of successfull state fetch, move to announce from init
case HeartbeatStateInit:
h.current = server
h.reset(HeartbeatStateAnnounce)
return nil
// nothing to do in announce state
case HeartbeatStateAnnounce:
return nil
case HeartbeatStateAnnounceWait:
// time to announce
if h.Clock.Now().UTC().After(h.nextAnnounce) {
h.current = server
h.reset(HeartbeatStateAnnounce)
return nil
}
result := services.CompareServers(h.current, server)
// server update happened, time to announce
if result == services.Different {
h.current = server
h.reset(HeartbeatStateAnnounce)
}
return nil
// nothing to do in keep alive state
case HeartbeatStateKeepAlive:
return nil
// Stay in keep alive state in case
// if there are no changes
case HeartbeatStateKeepAliveWait:
// time to send a new keep alive
if h.Clock.Now().UTC().After(h.nextKeepAlive) {
h.setState(HeartbeatStateKeepAlive)
return nil
}
result := services.CompareServers(h.current, server)
// server update happened, move to announce
if result == services.Different {
h.current = server
h.reset(HeartbeatStateAnnounce)
}
return nil
default:
return trace.BadParameter("unsupported state: %v", h.state)
}
} | [
"func",
"(",
"h",
"*",
"Heartbeat",
")",
"fetch",
"(",
")",
"error",
"{",
"// failed to fetch server info?",
"// reset to init state regardless of the current state",
"server",
",",
"err",
":=",
"h",
".",
"GetServerInfo",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"h",
".",
"reset",
"(",
"HeartbeatStateInit",
")",
"\n",
"return",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"switch",
"h",
".",
"state",
"{",
"// in case of successfull state fetch, move to announce from init",
"case",
"HeartbeatStateInit",
":",
"h",
".",
"current",
"=",
"server",
"\n",
"h",
".",
"reset",
"(",
"HeartbeatStateAnnounce",
")",
"\n",
"return",
"nil",
"\n",
"// nothing to do in announce state",
"case",
"HeartbeatStateAnnounce",
":",
"return",
"nil",
"\n",
"case",
"HeartbeatStateAnnounceWait",
":",
"// time to announce",
"if",
"h",
".",
"Clock",
".",
"Now",
"(",
")",
".",
"UTC",
"(",
")",
".",
"After",
"(",
"h",
".",
"nextAnnounce",
")",
"{",
"h",
".",
"current",
"=",
"server",
"\n",
"h",
".",
"reset",
"(",
"HeartbeatStateAnnounce",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"result",
":=",
"services",
".",
"CompareServers",
"(",
"h",
".",
"current",
",",
"server",
")",
"\n",
"// server update happened, time to announce",
"if",
"result",
"==",
"services",
".",
"Different",
"{",
"h",
".",
"current",
"=",
"server",
"\n",
"h",
".",
"reset",
"(",
"HeartbeatStateAnnounce",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"// nothing to do in keep alive state",
"case",
"HeartbeatStateKeepAlive",
":",
"return",
"nil",
"\n",
"// Stay in keep alive state in case",
"// if there are no changes",
"case",
"HeartbeatStateKeepAliveWait",
":",
"// time to send a new keep alive",
"if",
"h",
".",
"Clock",
".",
"Now",
"(",
")",
".",
"UTC",
"(",
")",
".",
"After",
"(",
"h",
".",
"nextKeepAlive",
")",
"{",
"h",
".",
"setState",
"(",
"HeartbeatStateKeepAlive",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"result",
":=",
"services",
".",
"CompareServers",
"(",
"h",
".",
"current",
",",
"server",
")",
"\n",
"// server update happened, move to announce",
"if",
"result",
"==",
"services",
".",
"Different",
"{",
"h",
".",
"current",
"=",
"server",
"\n",
"h",
".",
"reset",
"(",
"HeartbeatStateAnnounce",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"default",
":",
"return",
"trace",
".",
"BadParameter",
"(",
"\"",
"\"",
",",
"h",
".",
"state",
")",
"\n",
"}",
"\n",
"}"
] | // fetch, if succeeded updates or sets current server
// to the last received server | [
"fetch",
"if",
"succeeded",
"updates",
"or",
"sets",
"current",
"server",
"to",
"the",
"last",
"received",
"server"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/heartbeat.go#L291-L343 | train |
gravitational/teleport | lib/srv/heartbeat.go | fetchAndAnnounce | func (h *Heartbeat) fetchAndAnnounce() error {
if err := h.fetch(); err != nil {
return trace.Wrap(err)
}
if err := h.announce(); err != nil {
return trace.Wrap(err)
}
return nil
} | go | func (h *Heartbeat) fetchAndAnnounce() error {
if err := h.fetch(); err != nil {
return trace.Wrap(err)
}
if err := h.announce(); err != nil {
return trace.Wrap(err)
}
return nil
} | [
"func",
"(",
"h",
"*",
"Heartbeat",
")",
"fetchAndAnnounce",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"h",
".",
"fetch",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"h",
".",
"announce",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // fetchAndAnnounce fetches data about server
// and announces it to the server | [
"fetchAndAnnounce",
"fetches",
"data",
"about",
"server",
"and",
"announces",
"it",
"to",
"the",
"server"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/heartbeat.go#L433-L441 | train |
gravitational/teleport | lib/srv/heartbeat.go | ForceSend | func (h *Heartbeat) ForceSend(timeout time.Duration) error {
timeoutC := time.After(timeout)
select {
case h.sendC <- struct{}{}:
case <-timeoutC:
return trace.ConnectionProblem(nil, "timeout waiting for send")
}
select {
case <-h.announceC:
return nil
case <-timeoutC:
return trace.ConnectionProblem(nil, "timeout waiting for announce to be sent")
}
} | go | func (h *Heartbeat) ForceSend(timeout time.Duration) error {
timeoutC := time.After(timeout)
select {
case h.sendC <- struct{}{}:
case <-timeoutC:
return trace.ConnectionProblem(nil, "timeout waiting for send")
}
select {
case <-h.announceC:
return nil
case <-timeoutC:
return trace.ConnectionProblem(nil, "timeout waiting for announce to be sent")
}
} | [
"func",
"(",
"h",
"*",
"Heartbeat",
")",
"ForceSend",
"(",
"timeout",
"time",
".",
"Duration",
")",
"error",
"{",
"timeoutC",
":=",
"time",
".",
"After",
"(",
"timeout",
")",
"\n",
"select",
"{",
"case",
"h",
".",
"sendC",
"<-",
"struct",
"{",
"}",
"{",
"}",
":",
"case",
"<-",
"timeoutC",
":",
"return",
"trace",
".",
"ConnectionProblem",
"(",
"nil",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"select",
"{",
"case",
"<-",
"h",
".",
"announceC",
":",
"return",
"nil",
"\n",
"case",
"<-",
"timeoutC",
":",
"return",
"trace",
".",
"ConnectionProblem",
"(",
"nil",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}"
] | // ForceSend forces send cycle, used in tests, returns
// nil in case of success, error otherwise | [
"ForceSend",
"forces",
"send",
"cycle",
"used",
"in",
"tests",
"returns",
"nil",
"in",
"case",
"of",
"success",
"error",
"otherwise"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/heartbeat.go#L445-L458 | train |
gravitational/teleport | lib/events/dynamoevents/dynamoevents.go | deleteAllItems | func (b *Log) deleteAllItems() error {
out, err := b.svc.Scan(&dynamodb.ScanInput{TableName: aws.String(b.Tablename)})
if err != nil {
return trace.Wrap(err)
}
var requests []*dynamodb.WriteRequest
for _, item := range out.Items {
requests = append(requests, &dynamodb.WriteRequest{
DeleteRequest: &dynamodb.DeleteRequest{
Key: map[string]*dynamodb.AttributeValue{
keySessionID: item[keySessionID],
keyEventIndex: item[keyEventIndex],
},
},
})
}
if len(requests) == 0 {
return nil
}
req, _ := b.svc.BatchWriteItemRequest(&dynamodb.BatchWriteItemInput{
RequestItems: map[string][]*dynamodb.WriteRequest{
b.Tablename: requests,
},
})
err = req.Send()
err = convertError(err)
if err != nil {
return trace.Wrap(err)
}
return nil
} | go | func (b *Log) deleteAllItems() error {
out, err := b.svc.Scan(&dynamodb.ScanInput{TableName: aws.String(b.Tablename)})
if err != nil {
return trace.Wrap(err)
}
var requests []*dynamodb.WriteRequest
for _, item := range out.Items {
requests = append(requests, &dynamodb.WriteRequest{
DeleteRequest: &dynamodb.DeleteRequest{
Key: map[string]*dynamodb.AttributeValue{
keySessionID: item[keySessionID],
keyEventIndex: item[keyEventIndex],
},
},
})
}
if len(requests) == 0 {
return nil
}
req, _ := b.svc.BatchWriteItemRequest(&dynamodb.BatchWriteItemInput{
RequestItems: map[string][]*dynamodb.WriteRequest{
b.Tablename: requests,
},
})
err = req.Send()
err = convertError(err)
if err != nil {
return trace.Wrap(err)
}
return nil
} | [
"func",
"(",
"b",
"*",
"Log",
")",
"deleteAllItems",
"(",
")",
"error",
"{",
"out",
",",
"err",
":=",
"b",
".",
"svc",
".",
"Scan",
"(",
"&",
"dynamodb",
".",
"ScanInput",
"{",
"TableName",
":",
"aws",
".",
"String",
"(",
"b",
".",
"Tablename",
")",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"var",
"requests",
"[",
"]",
"*",
"dynamodb",
".",
"WriteRequest",
"\n",
"for",
"_",
",",
"item",
":=",
"range",
"out",
".",
"Items",
"{",
"requests",
"=",
"append",
"(",
"requests",
",",
"&",
"dynamodb",
".",
"WriteRequest",
"{",
"DeleteRequest",
":",
"&",
"dynamodb",
".",
"DeleteRequest",
"{",
"Key",
":",
"map",
"[",
"string",
"]",
"*",
"dynamodb",
".",
"AttributeValue",
"{",
"keySessionID",
":",
"item",
"[",
"keySessionID",
"]",
",",
"keyEventIndex",
":",
"item",
"[",
"keyEventIndex",
"]",
",",
"}",
",",
"}",
",",
"}",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"requests",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"req",
",",
"_",
":=",
"b",
".",
"svc",
".",
"BatchWriteItemRequest",
"(",
"&",
"dynamodb",
".",
"BatchWriteItemInput",
"{",
"RequestItems",
":",
"map",
"[",
"string",
"]",
"[",
"]",
"*",
"dynamodb",
".",
"WriteRequest",
"{",
"b",
".",
"Tablename",
":",
"requests",
",",
"}",
",",
"}",
")",
"\n",
"err",
"=",
"req",
".",
"Send",
"(",
")",
"\n",
"err",
"=",
"convertError",
"(",
"err",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // deleteAllItems deletes all items from the database, used in tests | [
"deleteAllItems",
"deletes",
"all",
"items",
"from",
"the",
"database",
"used",
"in",
"tests"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/dynamoevents/dynamoevents.go#L572-L602 | train |
gravitational/teleport | lib/services/local/events.go | NewEventsService | func NewEventsService(b backend.Backend) *EventsService {
return &EventsService{
Entry: logrus.WithFields(logrus.Fields{trace.Component: "Events"}),
backend: b,
}
} | go | func NewEventsService(b backend.Backend) *EventsService {
return &EventsService{
Entry: logrus.WithFields(logrus.Fields{trace.Component: "Events"}),
backend: b,
}
} | [
"func",
"NewEventsService",
"(",
"b",
"backend",
".",
"Backend",
")",
"*",
"EventsService",
"{",
"return",
"&",
"EventsService",
"{",
"Entry",
":",
"logrus",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"trace",
".",
"Component",
":",
"\"",
"\"",
"}",
")",
",",
"backend",
":",
"b",
",",
"}",
"\n",
"}"
] | // NewEventsService returns new events service instance | [
"NewEventsService",
"returns",
"new",
"events",
"service",
"instance"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/events.go#L39-L44 | train |
gravitational/teleport | lib/services/local/events.go | base | func base(key []byte, offset int) ([]byte, error) {
parts := bytes.Split(key, []byte{backend.Separator})
if len(parts) < offset+1 {
return nil, trace.NotFound("failed parsing %v", string(key))
}
return parts[len(parts)-offset-1], nil
} | go | func base(key []byte, offset int) ([]byte, error) {
parts := bytes.Split(key, []byte{backend.Separator})
if len(parts) < offset+1 {
return nil, trace.NotFound("failed parsing %v", string(key))
}
return parts[len(parts)-offset-1], nil
} | [
"func",
"base",
"(",
"key",
"[",
"]",
"byte",
",",
"offset",
"int",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"parts",
":=",
"bytes",
".",
"Split",
"(",
"key",
",",
"[",
"]",
"byte",
"{",
"backend",
".",
"Separator",
"}",
")",
"\n",
"if",
"len",
"(",
"parts",
")",
"<",
"offset",
"+",
"1",
"{",
"return",
"nil",
",",
"trace",
".",
"NotFound",
"(",
"\"",
"\"",
",",
"string",
"(",
"key",
")",
")",
"\n",
"}",
"\n",
"return",
"parts",
"[",
"len",
"(",
"parts",
")",
"-",
"offset",
"-",
"1",
"]",
",",
"nil",
"\n",
"}"
] | // base returns last element delimited by separator, index is
// is an index of the key part to get counting from the end | [
"base",
"returns",
"last",
"element",
"delimited",
"by",
"separator",
"index",
"is",
"is",
"an",
"index",
"of",
"the",
"key",
"part",
"to",
"get",
"counting",
"from",
"the",
"end"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/events.go#L715-L721 | train |
gravitational/teleport | lib/services/local/events.go | baseTwoKeys | func baseTwoKeys(key []byte) (string, string, error) {
parts := bytes.Split(key, []byte{backend.Separator})
if len(parts) < 2 {
return "", "", trace.NotFound("failed parsing %v", string(key))
}
return string(parts[len(parts)-2]), string(parts[len(parts)-1]), nil
} | go | func baseTwoKeys(key []byte) (string, string, error) {
parts := bytes.Split(key, []byte{backend.Separator})
if len(parts) < 2 {
return "", "", trace.NotFound("failed parsing %v", string(key))
}
return string(parts[len(parts)-2]), string(parts[len(parts)-1]), nil
} | [
"func",
"baseTwoKeys",
"(",
"key",
"[",
"]",
"byte",
")",
"(",
"string",
",",
"string",
",",
"error",
")",
"{",
"parts",
":=",
"bytes",
".",
"Split",
"(",
"key",
",",
"[",
"]",
"byte",
"{",
"backend",
".",
"Separator",
"}",
")",
"\n",
"if",
"len",
"(",
"parts",
")",
"<",
"2",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"trace",
".",
"NotFound",
"(",
"\"",
"\"",
",",
"string",
"(",
"key",
")",
")",
"\n",
"}",
"\n",
"return",
"string",
"(",
"parts",
"[",
"len",
"(",
"parts",
")",
"-",
"2",
"]",
")",
",",
"string",
"(",
"parts",
"[",
"len",
"(",
"parts",
")",
"-",
"1",
"]",
")",
",",
"nil",
"\n",
"}"
] | // baseTwoKeys returns two last keys | [
"baseTwoKeys",
"returns",
"two",
"last",
"keys"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/events.go#L724-L730 | train |
gravitational/teleport | lib/auth/api.go | NewWrapper | func NewWrapper(writer AccessPoint, cache ReadAccessPoint) AccessPoint {
return &Wrapper{
Write: writer,
ReadAccessPoint: cache,
}
} | go | func NewWrapper(writer AccessPoint, cache ReadAccessPoint) AccessPoint {
return &Wrapper{
Write: writer,
ReadAccessPoint: cache,
}
} | [
"func",
"NewWrapper",
"(",
"writer",
"AccessPoint",
",",
"cache",
"ReadAccessPoint",
")",
"AccessPoint",
"{",
"return",
"&",
"Wrapper",
"{",
"Write",
":",
"writer",
",",
"ReadAccessPoint",
":",
"cache",
",",
"}",
"\n",
"}"
] | // NewWrapper returns new access point wrapper | [
"NewWrapper",
"returns",
"new",
"access",
"point",
"wrapper"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/api.go#L142-L147 | train |
gravitational/teleport | lib/auth/api.go | UpsertNode | func (w *Wrapper) UpsertNode(s services.Server) (*services.KeepAlive, error) {
return w.Write.UpsertNode(s)
} | go | func (w *Wrapper) UpsertNode(s services.Server) (*services.KeepAlive, error) {
return w.Write.UpsertNode(s)
} | [
"func",
"(",
"w",
"*",
"Wrapper",
")",
"UpsertNode",
"(",
"s",
"services",
".",
"Server",
")",
"(",
"*",
"services",
".",
"KeepAlive",
",",
"error",
")",
"{",
"return",
"w",
".",
"Write",
".",
"UpsertNode",
"(",
"s",
")",
"\n",
"}"
] | // UpsertNode is part of auth.AccessPoint implementation | [
"UpsertNode",
"is",
"part",
"of",
"auth",
".",
"AccessPoint",
"implementation"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/api.go#L158-L160 | train |
gravitational/teleport | lib/auth/api.go | UpsertAuthServer | func (w *Wrapper) UpsertAuthServer(s services.Server) error {
return w.Write.UpsertAuthServer(s)
} | go | func (w *Wrapper) UpsertAuthServer(s services.Server) error {
return w.Write.UpsertAuthServer(s)
} | [
"func",
"(",
"w",
"*",
"Wrapper",
")",
"UpsertAuthServer",
"(",
"s",
"services",
".",
"Server",
")",
"error",
"{",
"return",
"w",
".",
"Write",
".",
"UpsertAuthServer",
"(",
"s",
")",
"\n",
"}"
] | // UpsertAuthServer is part of auth.AccessPoint implementation | [
"UpsertAuthServer",
"is",
"part",
"of",
"auth",
".",
"AccessPoint",
"implementation"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/api.go#L163-L165 | train |
gravitational/teleport | lib/auth/api.go | UpsertProxy | func (w *Wrapper) UpsertProxy(s services.Server) error {
return w.Write.UpsertProxy(s)
} | go | func (w *Wrapper) UpsertProxy(s services.Server) error {
return w.Write.UpsertProxy(s)
} | [
"func",
"(",
"w",
"*",
"Wrapper",
")",
"UpsertProxy",
"(",
"s",
"services",
".",
"Server",
")",
"error",
"{",
"return",
"w",
".",
"Write",
".",
"UpsertProxy",
"(",
"s",
")",
"\n",
"}"
] | // UpsertProxy is part of auth.AccessPoint implementation | [
"UpsertProxy",
"is",
"part",
"of",
"auth",
".",
"AccessPoint",
"implementation"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/api.go#L173-L175 | train |
gravitational/teleport | lib/auth/api.go | UpsertTunnelConnection | func (w *Wrapper) UpsertTunnelConnection(conn services.TunnelConnection) error {
return w.Write.UpsertTunnelConnection(conn)
} | go | func (w *Wrapper) UpsertTunnelConnection(conn services.TunnelConnection) error {
return w.Write.UpsertTunnelConnection(conn)
} | [
"func",
"(",
"w",
"*",
"Wrapper",
")",
"UpsertTunnelConnection",
"(",
"conn",
"services",
".",
"TunnelConnection",
")",
"error",
"{",
"return",
"w",
".",
"Write",
".",
"UpsertTunnelConnection",
"(",
"conn",
")",
"\n",
"}"
] | // UpsertTunnelConnection is a part of auth.AccessPoint implementation | [
"UpsertTunnelConnection",
"is",
"a",
"part",
"of",
"auth",
".",
"AccessPoint",
"implementation"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/api.go#L178-L180 | train |
gravitational/teleport | lib/auth/api.go | DeleteTunnelConnection | func (w *Wrapper) DeleteTunnelConnection(clusterName, connName string) error {
return w.Write.DeleteTunnelConnection(clusterName, connName)
} | go | func (w *Wrapper) DeleteTunnelConnection(clusterName, connName string) error {
return w.Write.DeleteTunnelConnection(clusterName, connName)
} | [
"func",
"(",
"w",
"*",
"Wrapper",
")",
"DeleteTunnelConnection",
"(",
"clusterName",
",",
"connName",
"string",
")",
"error",
"{",
"return",
"w",
".",
"Write",
".",
"DeleteTunnelConnection",
"(",
"clusterName",
",",
"connName",
")",
"\n",
"}"
] | // DeleteTunnelConnection is a part of auth.AccessPoint implementation | [
"DeleteTunnelConnection",
"is",
"a",
"part",
"of",
"auth",
".",
"AccessPoint",
"implementation"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/api.go#L183-L185 | train |
gravitational/teleport | lib/sshutils/server.go | SetShutdownPollPeriod | func SetShutdownPollPeriod(period time.Duration) ServerOption {
return func(s *Server) error {
s.shutdownPollPeriod = period
return nil
}
} | go | func SetShutdownPollPeriod(period time.Duration) ServerOption {
return func(s *Server) error {
s.shutdownPollPeriod = period
return nil
}
} | [
"func",
"SetShutdownPollPeriod",
"(",
"period",
"time",
".",
"Duration",
")",
"ServerOption",
"{",
"return",
"func",
"(",
"s",
"*",
"Server",
")",
"error",
"{",
"s",
".",
"shutdownPollPeriod",
"=",
"period",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // SetShutdownPollPeriod sets a polling period for graceful shutdowns of SSH servers | [
"SetShutdownPollPeriod",
"sets",
"a",
"polling",
"period",
"for",
"graceful",
"shutdowns",
"of",
"SSH",
"servers"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/server.go#L113-L118 | train |
gravitational/teleport | lib/sshutils/server.go | Wait | func (s *Server) Wait(ctx context.Context) {
select {
case <-s.closeContext.Done():
case <-ctx.Done():
}
} | go | func (s *Server) Wait(ctx context.Context) {
select {
case <-s.closeContext.Done():
case <-ctx.Done():
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"Wait",
"(",
"ctx",
"context",
".",
"Context",
")",
"{",
"select",
"{",
"case",
"<-",
"s",
".",
"closeContext",
".",
"Done",
"(",
")",
":",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"}",
"\n",
"}"
] | // Wait waits until server stops serving new connections
// on the listener socket | [
"Wait",
"waits",
"until",
"server",
"stops",
"serving",
"new",
"connections",
"on",
"the",
"listener",
"socket"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/server.go#L268-L273 | train |
gravitational/teleport | lib/sshutils/server.go | Shutdown | func (s *Server) Shutdown(ctx context.Context) error {
// close listener to stop receiving new connections
err := s.Close()
s.Wait(ctx)
activeConnections := s.trackConnections(0)
if activeConnections == 0 {
return err
}
s.Infof("Shutdown: waiting for %v connections to finish.", activeConnections)
lastReport := time.Time{}
ticker := time.NewTicker(s.shutdownPollPeriod)
defer ticker.Stop()
for {
select {
case <-ticker.C:
activeConnections = s.trackConnections(0)
if activeConnections == 0 {
return err
}
if time.Now().Sub(lastReport) > 10*s.shutdownPollPeriod {
s.Infof("Shutdown: waiting for %v connections to finish.", activeConnections)
lastReport = time.Now()
}
case <-ctx.Done():
s.Infof("Context cancelled wait, returning.")
return trace.ConnectionProblem(err, "context cancelled")
}
}
} | go | func (s *Server) Shutdown(ctx context.Context) error {
// close listener to stop receiving new connections
err := s.Close()
s.Wait(ctx)
activeConnections := s.trackConnections(0)
if activeConnections == 0 {
return err
}
s.Infof("Shutdown: waiting for %v connections to finish.", activeConnections)
lastReport := time.Time{}
ticker := time.NewTicker(s.shutdownPollPeriod)
defer ticker.Stop()
for {
select {
case <-ticker.C:
activeConnections = s.trackConnections(0)
if activeConnections == 0 {
return err
}
if time.Now().Sub(lastReport) > 10*s.shutdownPollPeriod {
s.Infof("Shutdown: waiting for %v connections to finish.", activeConnections)
lastReport = time.Now()
}
case <-ctx.Done():
s.Infof("Context cancelled wait, returning.")
return trace.ConnectionProblem(err, "context cancelled")
}
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"Shutdown",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"// close listener to stop receiving new connections",
"err",
":=",
"s",
".",
"Close",
"(",
")",
"\n",
"s",
".",
"Wait",
"(",
"ctx",
")",
"\n",
"activeConnections",
":=",
"s",
".",
"trackConnections",
"(",
"0",
")",
"\n",
"if",
"activeConnections",
"==",
"0",
"{",
"return",
"err",
"\n",
"}",
"\n",
"s",
".",
"Infof",
"(",
"\"",
"\"",
",",
"activeConnections",
")",
"\n",
"lastReport",
":=",
"time",
".",
"Time",
"{",
"}",
"\n",
"ticker",
":=",
"time",
".",
"NewTicker",
"(",
"s",
".",
"shutdownPollPeriod",
")",
"\n",
"defer",
"ticker",
".",
"Stop",
"(",
")",
"\n",
"for",
"{",
"select",
"{",
"case",
"<-",
"ticker",
".",
"C",
":",
"activeConnections",
"=",
"s",
".",
"trackConnections",
"(",
"0",
")",
"\n",
"if",
"activeConnections",
"==",
"0",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"time",
".",
"Now",
"(",
")",
".",
"Sub",
"(",
"lastReport",
")",
">",
"10",
"*",
"s",
".",
"shutdownPollPeriod",
"{",
"s",
".",
"Infof",
"(",
"\"",
"\"",
",",
"activeConnections",
")",
"\n",
"lastReport",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"}",
"\n",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"s",
".",
"Infof",
"(",
"\"",
"\"",
")",
"\n",
"return",
"trace",
".",
"ConnectionProblem",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Shutdown initiates graceful shutdown - waiting until all active
// connections will get closed | [
"Shutdown",
"initiates",
"graceful",
"shutdown",
"-",
"waiting",
"until",
"all",
"active",
"connections",
"will",
"get",
"closed"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/server.go#L277-L305 | train |
gravitational/teleport | lib/sshutils/server.go | validateHostSigner | func validateHostSigner(signer ssh.Signer) error {
cert, ok := signer.PublicKey().(*ssh.Certificate)
if !ok {
return trace.BadParameter("only host certificates supported")
}
if len(cert.ValidPrincipals) == 0 {
return trace.BadParameter("at least one valid principal is required in host certificate")
}
certChecker := utils.CertChecker{}
err := certChecker.CheckCert(cert.ValidPrincipals[0], cert)
if err != nil {
return trace.Wrap(err)
}
return nil
} | go | func validateHostSigner(signer ssh.Signer) error {
cert, ok := signer.PublicKey().(*ssh.Certificate)
if !ok {
return trace.BadParameter("only host certificates supported")
}
if len(cert.ValidPrincipals) == 0 {
return trace.BadParameter("at least one valid principal is required in host certificate")
}
certChecker := utils.CertChecker{}
err := certChecker.CheckCert(cert.ValidPrincipals[0], cert)
if err != nil {
return trace.Wrap(err)
}
return nil
} | [
"func",
"validateHostSigner",
"(",
"signer",
"ssh",
".",
"Signer",
")",
"error",
"{",
"cert",
",",
"ok",
":=",
"signer",
".",
"PublicKey",
"(",
")",
".",
"(",
"*",
"ssh",
".",
"Certificate",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"trace",
".",
"BadParameter",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"cert",
".",
"ValidPrincipals",
")",
"==",
"0",
"{",
"return",
"trace",
".",
"BadParameter",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"certChecker",
":=",
"utils",
".",
"CertChecker",
"{",
"}",
"\n",
"err",
":=",
"certChecker",
".",
"CheckCert",
"(",
"cert",
".",
"ValidPrincipals",
"[",
"0",
"]",
",",
"cert",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // validateHostSigner make sure the signer is a valid certificate. | [
"validateHostSigner",
"make",
"sure",
"the",
"signer",
"is",
"a",
"valid",
"certificate",
"."
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/server.go#L506-L522 | train |
gravitational/teleport | lib/sshutils/server.go | KeysEqual | func KeysEqual(ak, bk ssh.PublicKey) bool {
a := ssh.Marshal(ak)
b := ssh.Marshal(bk)
return (len(a) == len(b) && subtle.ConstantTimeCompare(a, b) == 1)
} | go | func KeysEqual(ak, bk ssh.PublicKey) bool {
a := ssh.Marshal(ak)
b := ssh.Marshal(bk)
return (len(a) == len(b) && subtle.ConstantTimeCompare(a, b) == 1)
} | [
"func",
"KeysEqual",
"(",
"ak",
",",
"bk",
"ssh",
".",
"PublicKey",
")",
"bool",
"{",
"a",
":=",
"ssh",
".",
"Marshal",
"(",
"ak",
")",
"\n",
"b",
":=",
"ssh",
".",
"Marshal",
"(",
"bk",
")",
"\n",
"return",
"(",
"len",
"(",
"a",
")",
"==",
"len",
"(",
"b",
")",
"&&",
"subtle",
".",
"ConstantTimeCompare",
"(",
"a",
",",
"b",
")",
"==",
"1",
")",
"\n",
"}"
] | // KeysEqual is constant time compare of the keys to avoid timing attacks | [
"KeysEqual",
"is",
"constant",
"time",
"compare",
"of",
"the",
"keys",
"to",
"avoid",
"timing",
"attacks"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/server.go#L528-L532 | train |
gravitational/teleport | lib/backend/backend.go | String | func (w *Watch) String() string {
return fmt.Sprintf("Watcher(name=%v, prefixes=%v)", w.Name, string(bytes.Join(w.Prefixes, []byte(", "))))
} | go | func (w *Watch) String() string {
return fmt.Sprintf("Watcher(name=%v, prefixes=%v)", w.Name, string(bytes.Join(w.Prefixes, []byte(", "))))
} | [
"func",
"(",
"w",
"*",
"Watch",
")",
"String",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"w",
".",
"Name",
",",
"string",
"(",
"bytes",
".",
"Join",
"(",
"w",
".",
"Prefixes",
",",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
")",
")",
")",
"\n",
"}"
] | // String returns a user-friendly description
// of the watcher | [
"String",
"returns",
"a",
"user",
"-",
"friendly",
"description",
"of",
"the",
"watcher"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/backend.go#L132-L134 | train |
gravitational/teleport | lib/backend/backend.go | GetString | func (p Params) GetString(key string) string {
v, ok := p[key]
if !ok {
return ""
}
s, _ := v.(string)
return s
} | go | func (p Params) GetString(key string) string {
v, ok := p[key]
if !ok {
return ""
}
s, _ := v.(string)
return s
} | [
"func",
"(",
"p",
"Params",
")",
"GetString",
"(",
"key",
"string",
")",
"string",
"{",
"v",
",",
"ok",
":=",
"p",
"[",
"key",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"s",
",",
"_",
":=",
"v",
".",
"(",
"string",
")",
"\n",
"return",
"s",
"\n",
"}"
] | // GetString returns a string value stored in Params map, or an empty string
// if nothing is found | [
"GetString",
"returns",
"a",
"string",
"value",
"stored",
"in",
"Params",
"map",
"or",
"an",
"empty",
"string",
"if",
"nothing",
"is",
"found"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/backend.go#L229-L236 | train |
gravitational/teleport | lib/backend/backend.go | RangeEnd | func RangeEnd(key []byte) []byte {
end := make([]byte, len(key))
copy(end, key)
for i := len(end) - 1; i >= 0; i-- {
if end[i] < 0xff {
end[i] = end[i] + 1
end = end[:i+1]
return end
}
}
// next key does not exist (e.g., 0xffff);
return noEnd
} | go | func RangeEnd(key []byte) []byte {
end := make([]byte, len(key))
copy(end, key)
for i := len(end) - 1; i >= 0; i-- {
if end[i] < 0xff {
end[i] = end[i] + 1
end = end[:i+1]
return end
}
}
// next key does not exist (e.g., 0xffff);
return noEnd
} | [
"func",
"RangeEnd",
"(",
"key",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"end",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"key",
")",
")",
"\n",
"copy",
"(",
"end",
",",
"key",
")",
"\n",
"for",
"i",
":=",
"len",
"(",
"end",
")",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
"{",
"if",
"end",
"[",
"i",
"]",
"<",
"0xff",
"{",
"end",
"[",
"i",
"]",
"=",
"end",
"[",
"i",
"]",
"+",
"1",
"\n",
"end",
"=",
"end",
"[",
":",
"i",
"+",
"1",
"]",
"\n",
"return",
"end",
"\n",
"}",
"\n",
"}",
"\n",
"// next key does not exist (e.g., 0xffff);",
"return",
"noEnd",
"\n",
"}"
] | // RangeEnd returns end of the range for given key | [
"RangeEnd",
"returns",
"end",
"of",
"the",
"range",
"for",
"given",
"key"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/backend.go#L242-L254 | train |
gravitational/teleport | lib/backend/backend.go | TTL | func TTL(clock clockwork.Clock, expires time.Time) time.Duration {
ttl := expires.Sub(clock.Now())
if ttl < time.Second {
return time.Second
}
return ttl
} | go | func TTL(clock clockwork.Clock, expires time.Time) time.Duration {
ttl := expires.Sub(clock.Now())
if ttl < time.Second {
return time.Second
}
return ttl
} | [
"func",
"TTL",
"(",
"clock",
"clockwork",
".",
"Clock",
",",
"expires",
"time",
".",
"Time",
")",
"time",
".",
"Duration",
"{",
"ttl",
":=",
"expires",
".",
"Sub",
"(",
"clock",
".",
"Now",
"(",
")",
")",
"\n",
"if",
"ttl",
"<",
"time",
".",
"Second",
"{",
"return",
"time",
".",
"Second",
"\n",
"}",
"\n",
"return",
"ttl",
"\n",
"}"
] | // TTL returns TTL in duration units, rounds up to one second | [
"TTL",
"returns",
"TTL",
"in",
"duration",
"units",
"rounds",
"up",
"to",
"one",
"second"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/backend.go#L279-L285 | train |
gravitational/teleport | lib/backend/backend.go | EarliestExpiry | func EarliestExpiry(times ...time.Time) time.Time {
if len(times) == 0 {
return time.Time{}
}
sort.Sort(earliest(times))
return times[0]
} | go | func EarliestExpiry(times ...time.Time) time.Time {
if len(times) == 0 {
return time.Time{}
}
sort.Sort(earliest(times))
return times[0]
} | [
"func",
"EarliestExpiry",
"(",
"times",
"...",
"time",
".",
"Time",
")",
"time",
".",
"Time",
"{",
"if",
"len",
"(",
"times",
")",
"==",
"0",
"{",
"return",
"time",
".",
"Time",
"{",
"}",
"\n",
"}",
"\n",
"sort",
".",
"Sort",
"(",
"earliest",
"(",
"times",
")",
")",
"\n",
"return",
"times",
"[",
"0",
"]",
"\n",
"}"
] | // EarliestExpiry returns first of the
// otherwise returns empty | [
"EarliestExpiry",
"returns",
"first",
"of",
"the",
"otherwise",
"returns",
"empty"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/backend.go#L289-L295 | train |
gravitational/teleport | lib/backend/backend.go | Expiry | func Expiry(clock clockwork.Clock, ttl time.Duration) time.Time {
if ttl == 0 {
return time.Time{}
}
return clock.Now().UTC().Add(ttl)
} | go | func Expiry(clock clockwork.Clock, ttl time.Duration) time.Time {
if ttl == 0 {
return time.Time{}
}
return clock.Now().UTC().Add(ttl)
} | [
"func",
"Expiry",
"(",
"clock",
"clockwork",
".",
"Clock",
",",
"ttl",
"time",
".",
"Duration",
")",
"time",
".",
"Time",
"{",
"if",
"ttl",
"==",
"0",
"{",
"return",
"time",
".",
"Time",
"{",
"}",
"\n",
"}",
"\n",
"return",
"clock",
".",
"Now",
"(",
")",
".",
"UTC",
"(",
")",
".",
"Add",
"(",
"ttl",
")",
"\n",
"}"
] | // Expiry converts ttl to expiry time, if ttl is 0
// returns empty time | [
"Expiry",
"converts",
"ttl",
"to",
"expiry",
"time",
"if",
"ttl",
"is",
"0",
"returns",
"empty",
"time"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/backend.go#L299-L304 | train |
gravitational/teleport | lib/utils/agentconn/agent_unix.go | Dial | func Dial(socket string) (net.Conn, error) {
conn, err := net.Dial("unix", socket)
if err != nil {
return nil, trace.Wrap(err)
}
return conn, nil
} | go | func Dial(socket string) (net.Conn, error) {
conn, err := net.Dial("unix", socket)
if err != nil {
return nil, trace.Wrap(err)
}
return conn, nil
} | [
"func",
"Dial",
"(",
"socket",
"string",
")",
"(",
"net",
".",
"Conn",
",",
"error",
")",
"{",
"conn",
",",
"err",
":=",
"net",
".",
"Dial",
"(",
"\"",
"\"",
",",
"socket",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"conn",
",",
"nil",
"\n",
"}"
] | // Dial creates net.Conn to a SSH agent listening on a Unix socket. | [
"Dial",
"creates",
"net",
".",
"Conn",
"to",
"a",
"SSH",
"agent",
"listening",
"on",
"a",
"Unix",
"socket",
"."
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/agentconn/agent_unix.go#L28-L35 | train |
gravitational/teleport | lib/services/authentication.go | NewAuthPreference | func NewAuthPreference(spec AuthPreferenceSpecV2) (AuthPreference, error) {
return &AuthPreferenceV2{
Kind: KindClusterAuthPreference,
Version: V2,
Metadata: Metadata{
Name: MetaNameClusterAuthPreference,
Namespace: defaults.Namespace,
},
Spec: spec,
}, nil
} | go | func NewAuthPreference(spec AuthPreferenceSpecV2) (AuthPreference, error) {
return &AuthPreferenceV2{
Kind: KindClusterAuthPreference,
Version: V2,
Metadata: Metadata{
Name: MetaNameClusterAuthPreference,
Namespace: defaults.Namespace,
},
Spec: spec,
}, nil
} | [
"func",
"NewAuthPreference",
"(",
"spec",
"AuthPreferenceSpecV2",
")",
"(",
"AuthPreference",
",",
"error",
")",
"{",
"return",
"&",
"AuthPreferenceV2",
"{",
"Kind",
":",
"KindClusterAuthPreference",
",",
"Version",
":",
"V2",
",",
"Metadata",
":",
"Metadata",
"{",
"Name",
":",
"MetaNameClusterAuthPreference",
",",
"Namespace",
":",
"defaults",
".",
"Namespace",
",",
"}",
",",
"Spec",
":",
"spec",
",",
"}",
",",
"nil",
"\n",
"}"
] | // NewAuthPreference is a convenience method to to create AuthPreferenceV2. | [
"NewAuthPreference",
"is",
"a",
"convenience",
"method",
"to",
"to",
"create",
"AuthPreferenceV2",
"."
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/authentication.go#L77-L87 | train |
gravitational/teleport | lib/services/authentication.go | GetU2F | func (c *AuthPreferenceV2) GetU2F() (*U2F, error) {
if c.Spec.U2F == nil {
return nil, trace.NotFound("U2F configuration not found")
}
return c.Spec.U2F, nil
} | go | func (c *AuthPreferenceV2) GetU2F() (*U2F, error) {
if c.Spec.U2F == nil {
return nil, trace.NotFound("U2F configuration not found")
}
return c.Spec.U2F, nil
} | [
"func",
"(",
"c",
"*",
"AuthPreferenceV2",
")",
"GetU2F",
"(",
")",
"(",
"*",
"U2F",
",",
"error",
")",
"{",
"if",
"c",
".",
"Spec",
".",
"U2F",
"==",
"nil",
"{",
"return",
"nil",
",",
"trace",
".",
"NotFound",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"c",
".",
"Spec",
".",
"U2F",
",",
"nil",
"\n",
"}"
] | // GetU2F gets the U2F configuration settings. | [
"GetU2F",
"gets",
"the",
"U2F",
"configuration",
"settings",
"."
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/authentication.go#L175-L180 | train |
gravitational/teleport | lib/services/authentication.go | CheckAndSetDefaults | func (c *AuthPreferenceV2) CheckAndSetDefaults() error {
// if nothing is passed in, set defaults
if c.Spec.Type == "" {
c.Spec.Type = teleport.Local
}
if c.Spec.SecondFactor == "" {
c.Spec.SecondFactor = teleport.OTP
}
// make sure type makes sense
switch c.Spec.Type {
case teleport.Local, teleport.OIDC, teleport.SAML, teleport.Github:
default:
return trace.BadParameter("authentication type %q not supported", c.Spec.Type)
}
// make sure second factor makes sense
switch c.Spec.SecondFactor {
case teleport.OFF, teleport.OTP, teleport.U2F:
default:
return trace.BadParameter("second factor type %q not supported", c.Spec.SecondFactor)
}
return nil
} | go | func (c *AuthPreferenceV2) CheckAndSetDefaults() error {
// if nothing is passed in, set defaults
if c.Spec.Type == "" {
c.Spec.Type = teleport.Local
}
if c.Spec.SecondFactor == "" {
c.Spec.SecondFactor = teleport.OTP
}
// make sure type makes sense
switch c.Spec.Type {
case teleport.Local, teleport.OIDC, teleport.SAML, teleport.Github:
default:
return trace.BadParameter("authentication type %q not supported", c.Spec.Type)
}
// make sure second factor makes sense
switch c.Spec.SecondFactor {
case teleport.OFF, teleport.OTP, teleport.U2F:
default:
return trace.BadParameter("second factor type %q not supported", c.Spec.SecondFactor)
}
return nil
} | [
"func",
"(",
"c",
"*",
"AuthPreferenceV2",
")",
"CheckAndSetDefaults",
"(",
")",
"error",
"{",
"// if nothing is passed in, set defaults",
"if",
"c",
".",
"Spec",
".",
"Type",
"==",
"\"",
"\"",
"{",
"c",
".",
"Spec",
".",
"Type",
"=",
"teleport",
".",
"Local",
"\n",
"}",
"\n",
"if",
"c",
".",
"Spec",
".",
"SecondFactor",
"==",
"\"",
"\"",
"{",
"c",
".",
"Spec",
".",
"SecondFactor",
"=",
"teleport",
".",
"OTP",
"\n",
"}",
"\n\n",
"// make sure type makes sense",
"switch",
"c",
".",
"Spec",
".",
"Type",
"{",
"case",
"teleport",
".",
"Local",
",",
"teleport",
".",
"OIDC",
",",
"teleport",
".",
"SAML",
",",
"teleport",
".",
"Github",
":",
"default",
":",
"return",
"trace",
".",
"BadParameter",
"(",
"\"",
"\"",
",",
"c",
".",
"Spec",
".",
"Type",
")",
"\n",
"}",
"\n\n",
"// make sure second factor makes sense",
"switch",
"c",
".",
"Spec",
".",
"SecondFactor",
"{",
"case",
"teleport",
".",
"OFF",
",",
"teleport",
".",
"OTP",
",",
"teleport",
".",
"U2F",
":",
"default",
":",
"return",
"trace",
".",
"BadParameter",
"(",
"\"",
"\"",
",",
"c",
".",
"Spec",
".",
"SecondFactor",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // CheckAndSetDefaults verifies the constraints for AuthPreference. | [
"CheckAndSetDefaults",
"verifies",
"the",
"constraints",
"for",
"AuthPreference",
"."
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/authentication.go#L188-L212 | train |
gravitational/teleport | lib/services/authentication.go | String | func (c *AuthPreferenceV2) String() string {
return fmt.Sprintf("AuthPreference(Type=%q,SecondFactor=%q)", c.Spec.Type, c.Spec.SecondFactor)
} | go | func (c *AuthPreferenceV2) String() string {
return fmt.Sprintf("AuthPreference(Type=%q,SecondFactor=%q)", c.Spec.Type, c.Spec.SecondFactor)
} | [
"func",
"(",
"c",
"*",
"AuthPreferenceV2",
")",
"String",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"c",
".",
"Spec",
".",
"Type",
",",
"c",
".",
"Spec",
".",
"SecondFactor",
")",
"\n",
"}"
] | // String represents a human readable version of authentication settings. | [
"String",
"represents",
"a",
"human",
"readable",
"version",
"of",
"authentication",
"settings",
"."
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/authentication.go#L215-L217 | train |
gravitational/teleport | lib/services/authentication.go | GetAuthPreferenceSchema | func GetAuthPreferenceSchema(extensionSchema string) string {
var authPreferenceSchema string
if authPreferenceSchema == "" {
authPreferenceSchema = fmt.Sprintf(AuthPreferenceSpecSchemaTemplate, "")
} else {
authPreferenceSchema = fmt.Sprintf(AuthPreferenceSpecSchemaTemplate, ","+extensionSchema)
}
return fmt.Sprintf(V2SchemaTemplate, MetadataSchema, authPreferenceSchema, DefaultDefinitions)
} | go | func GetAuthPreferenceSchema(extensionSchema string) string {
var authPreferenceSchema string
if authPreferenceSchema == "" {
authPreferenceSchema = fmt.Sprintf(AuthPreferenceSpecSchemaTemplate, "")
} else {
authPreferenceSchema = fmt.Sprintf(AuthPreferenceSpecSchemaTemplate, ","+extensionSchema)
}
return fmt.Sprintf(V2SchemaTemplate, MetadataSchema, authPreferenceSchema, DefaultDefinitions)
} | [
"func",
"GetAuthPreferenceSchema",
"(",
"extensionSchema",
"string",
")",
"string",
"{",
"var",
"authPreferenceSchema",
"string",
"\n",
"if",
"authPreferenceSchema",
"==",
"\"",
"\"",
"{",
"authPreferenceSchema",
"=",
"fmt",
".",
"Sprintf",
"(",
"AuthPreferenceSpecSchemaTemplate",
",",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"authPreferenceSchema",
"=",
"fmt",
".",
"Sprintf",
"(",
"AuthPreferenceSpecSchemaTemplate",
",",
"\"",
"\"",
"+",
"extensionSchema",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"V2SchemaTemplate",
",",
"MetadataSchema",
",",
"authPreferenceSchema",
",",
"DefaultDefinitions",
")",
"\n",
"}"
] | // GetAuthPreferenceSchema returns the schema with optionally injected
// schema for extensions. | [
"GetAuthPreferenceSchema",
"returns",
"the",
"schema",
"with",
"optionally",
"injected",
"schema",
"for",
"extensions",
"."
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/authentication.go#L277-L285 | train |
gravitational/teleport | lib/srv/regular/proxy.go | proxyToSite | func (t *proxySubsys) proxyToSite(
ctx *srv.ServerContext, site reversetunnel.RemoteSite, remoteAddr net.Addr, ch ssh.Channel) error {
conn, err := site.DialAuthServer()
if err != nil {
return trace.Wrap(err)
}
t.log.Infof("Connected to auth server: %v", conn.RemoteAddr())
go func() {
var err error
defer func() {
t.close(err)
}()
defer ch.Close()
_, err = io.Copy(ch, conn)
}()
go func() {
var err error
defer func() {
t.close(err)
}()
defer conn.Close()
_, err = io.Copy(conn, srv.NewTrackingReader(ctx, ch))
}()
return nil
} | go | func (t *proxySubsys) proxyToSite(
ctx *srv.ServerContext, site reversetunnel.RemoteSite, remoteAddr net.Addr, ch ssh.Channel) error {
conn, err := site.DialAuthServer()
if err != nil {
return trace.Wrap(err)
}
t.log.Infof("Connected to auth server: %v", conn.RemoteAddr())
go func() {
var err error
defer func() {
t.close(err)
}()
defer ch.Close()
_, err = io.Copy(ch, conn)
}()
go func() {
var err error
defer func() {
t.close(err)
}()
defer conn.Close()
_, err = io.Copy(conn, srv.NewTrackingReader(ctx, ch))
}()
return nil
} | [
"func",
"(",
"t",
"*",
"proxySubsys",
")",
"proxyToSite",
"(",
"ctx",
"*",
"srv",
".",
"ServerContext",
",",
"site",
"reversetunnel",
".",
"RemoteSite",
",",
"remoteAddr",
"net",
".",
"Addr",
",",
"ch",
"ssh",
".",
"Channel",
")",
"error",
"{",
"conn",
",",
"err",
":=",
"site",
".",
"DialAuthServer",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"t",
".",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"conn",
".",
"RemoteAddr",
"(",
")",
")",
"\n\n",
"go",
"func",
"(",
")",
"{",
"var",
"err",
"error",
"\n",
"defer",
"func",
"(",
")",
"{",
"t",
".",
"close",
"(",
"err",
")",
"\n",
"}",
"(",
")",
"\n",
"defer",
"ch",
".",
"Close",
"(",
")",
"\n",
"_",
",",
"err",
"=",
"io",
".",
"Copy",
"(",
"ch",
",",
"conn",
")",
"\n",
"}",
"(",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"var",
"err",
"error",
"\n",
"defer",
"func",
"(",
")",
"{",
"t",
".",
"close",
"(",
"err",
")",
"\n",
"}",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n",
"_",
",",
"err",
"=",
"io",
".",
"Copy",
"(",
"conn",
",",
"srv",
".",
"NewTrackingReader",
"(",
"ctx",
",",
"ch",
")",
")",
"\n\n",
"}",
"(",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // proxyToSite establishes a proxy connection from the connected SSH client to the
// auth server of the requested remote site | [
"proxyToSite",
"establishes",
"a",
"proxy",
"connection",
"from",
"the",
"connected",
"SSH",
"client",
"to",
"the",
"auth",
"server",
"of",
"the",
"requested",
"remote",
"site"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/regular/proxy.go#L198-L226 | train |
gravitational/teleport | lib/utils/tls.go | ListenTLS | func ListenTLS(address string, certFile, keyFile string, cipherSuites []uint16) (net.Listener, error) {
tlsConfig, err := CreateTLSConfiguration(certFile, keyFile, cipherSuites)
if err != nil {
return nil, trace.Wrap(err)
}
return tls.Listen("tcp", address, tlsConfig)
} | go | func ListenTLS(address string, certFile, keyFile string, cipherSuites []uint16) (net.Listener, error) {
tlsConfig, err := CreateTLSConfiguration(certFile, keyFile, cipherSuites)
if err != nil {
return nil, trace.Wrap(err)
}
return tls.Listen("tcp", address, tlsConfig)
} | [
"func",
"ListenTLS",
"(",
"address",
"string",
",",
"certFile",
",",
"keyFile",
"string",
",",
"cipherSuites",
"[",
"]",
"uint16",
")",
"(",
"net",
".",
"Listener",
",",
"error",
")",
"{",
"tlsConfig",
",",
"err",
":=",
"CreateTLSConfiguration",
"(",
"certFile",
",",
"keyFile",
",",
"cipherSuites",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"tls",
".",
"Listen",
"(",
"\"",
"\"",
",",
"address",
",",
"tlsConfig",
")",
"\n",
"}"
] | // ListenTLS sets up TLS listener for the http handler, starts listening
// on a TCP socket and returns the socket which is ready to be used
// for http.Serve | [
"ListenTLS",
"sets",
"up",
"TLS",
"listener",
"for",
"the",
"http",
"handler",
"starts",
"listening",
"on",
"a",
"TCP",
"socket",
"and",
"returns",
"the",
"socket",
"which",
"is",
"ready",
"to",
"be",
"used",
"for",
"http",
".",
"Serve"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/tls.go#L41-L47 | train |
gravitational/teleport | lib/utils/tls.go | TLSConfig | func TLSConfig(cipherSuites []uint16) *tls.Config {
config := &tls.Config{}
// If ciphers suites were passed in, use them. Otherwise use the the
// Go defaults.
if len(cipherSuites) > 0 {
config.CipherSuites = cipherSuites
}
// Pick the servers preferred ciphersuite, not the clients.
config.PreferServerCipherSuites = true
config.MinVersion = tls.VersionTLS12
config.SessionTicketsDisabled = false
config.ClientSessionCache = tls.NewLRUClientSessionCache(
DefaultLRUCapacity)
return config
} | go | func TLSConfig(cipherSuites []uint16) *tls.Config {
config := &tls.Config{}
// If ciphers suites were passed in, use them. Otherwise use the the
// Go defaults.
if len(cipherSuites) > 0 {
config.CipherSuites = cipherSuites
}
// Pick the servers preferred ciphersuite, not the clients.
config.PreferServerCipherSuites = true
config.MinVersion = tls.VersionTLS12
config.SessionTicketsDisabled = false
config.ClientSessionCache = tls.NewLRUClientSessionCache(
DefaultLRUCapacity)
return config
} | [
"func",
"TLSConfig",
"(",
"cipherSuites",
"[",
"]",
"uint16",
")",
"*",
"tls",
".",
"Config",
"{",
"config",
":=",
"&",
"tls",
".",
"Config",
"{",
"}",
"\n\n",
"// If ciphers suites were passed in, use them. Otherwise use the the",
"// Go defaults.",
"if",
"len",
"(",
"cipherSuites",
")",
">",
"0",
"{",
"config",
".",
"CipherSuites",
"=",
"cipherSuites",
"\n",
"}",
"\n\n",
"// Pick the servers preferred ciphersuite, not the clients.",
"config",
".",
"PreferServerCipherSuites",
"=",
"true",
"\n\n",
"config",
".",
"MinVersion",
"=",
"tls",
".",
"VersionTLS12",
"\n",
"config",
".",
"SessionTicketsDisabled",
"=",
"false",
"\n",
"config",
".",
"ClientSessionCache",
"=",
"tls",
".",
"NewLRUClientSessionCache",
"(",
"DefaultLRUCapacity",
")",
"\n",
"return",
"config",
"\n",
"}"
] | // TLSConfig returns default TLS configuration strong defaults. | [
"TLSConfig",
"returns",
"default",
"TLS",
"configuration",
"strong",
"defaults",
"."
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/tls.go#L50-L67 | train |
gravitational/teleport | lib/utils/tls.go | CreateTLSConfiguration | func CreateTLSConfiguration(certFile, keyFile string, cipherSuites []uint16) (*tls.Config, error) {
config := TLSConfig(cipherSuites)
if _, err := os.Stat(certFile); err != nil {
return nil, trace.BadParameter("certificate is not accessible by '%v'", certFile)
}
if _, err := os.Stat(keyFile); err != nil {
return nil, trace.BadParameter("certificate is not accessible by '%v'", certFile)
}
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, trace.Wrap(err)
}
config.Certificates = []tls.Certificate{cert}
return config, nil
} | go | func CreateTLSConfiguration(certFile, keyFile string, cipherSuites []uint16) (*tls.Config, error) {
config := TLSConfig(cipherSuites)
if _, err := os.Stat(certFile); err != nil {
return nil, trace.BadParameter("certificate is not accessible by '%v'", certFile)
}
if _, err := os.Stat(keyFile); err != nil {
return nil, trace.BadParameter("certificate is not accessible by '%v'", certFile)
}
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, trace.Wrap(err)
}
config.Certificates = []tls.Certificate{cert}
return config, nil
} | [
"func",
"CreateTLSConfiguration",
"(",
"certFile",
",",
"keyFile",
"string",
",",
"cipherSuites",
"[",
"]",
"uint16",
")",
"(",
"*",
"tls",
".",
"Config",
",",
"error",
")",
"{",
"config",
":=",
"TLSConfig",
"(",
"cipherSuites",
")",
"\n\n",
"if",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"certFile",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"trace",
".",
"BadParameter",
"(",
"\"",
"\"",
",",
"certFile",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"keyFile",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"trace",
".",
"BadParameter",
"(",
"\"",
"\"",
",",
"certFile",
")",
"\n",
"}",
"\n\n",
"cert",
",",
"err",
":=",
"tls",
".",
"LoadX509KeyPair",
"(",
"certFile",
",",
"keyFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"config",
".",
"Certificates",
"=",
"[",
"]",
"tls",
".",
"Certificate",
"{",
"cert",
"}",
"\n\n",
"return",
"config",
",",
"nil",
"\n",
"}"
] | // CreateTLSConfiguration sets up default TLS configuration | [
"CreateTLSConfiguration",
"sets",
"up",
"default",
"TLS",
"configuration"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/tls.go#L70-L87 | train |
gravitational/teleport | lib/utils/tls.go | GenerateSelfSignedCert | func GenerateSelfSignedCert(hostNames []string) (*TLSCredentials, error) {
priv, err := rsa.GenerateKey(rand.Reader, teleport.RSAKeySize)
if err != nil {
return nil, trace.Wrap(err)
}
notBefore := time.Now()
notAfter := notBefore.Add(time.Hour * 24 * 365 * 10) // 10 years
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, trace.Wrap(err)
}
entity := pkix.Name{
CommonName: "localhost",
Country: []string{"US"},
Organization: []string{"localhost"},
}
template := x509.Certificate{
SerialNumber: serialNumber,
Issuer: entity,
Subject: entity,
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
BasicConstraintsValid: true,
IsCA: true,
}
// collect IP addresses localhost resolves to and add them to the cert. template:
template.DNSNames = append(hostNames, "localhost.local")
ips, _ := net.LookupIP("localhost")
if ips != nil {
template.IPAddresses = ips
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
if err != nil {
return nil, trace.Wrap(err)
}
publicKeyBytes, err := x509.MarshalPKIXPublicKey(priv.Public())
if err != nil {
log.Error(err)
return nil, trace.Wrap(err)
}
return &TLSCredentials{
PublicKey: pem.EncodeToMemory(&pem.Block{Type: "RSA PUBLIC KEY", Bytes: publicKeyBytes}),
PrivateKey: pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)}),
Cert: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes}),
}, nil
} | go | func GenerateSelfSignedCert(hostNames []string) (*TLSCredentials, error) {
priv, err := rsa.GenerateKey(rand.Reader, teleport.RSAKeySize)
if err != nil {
return nil, trace.Wrap(err)
}
notBefore := time.Now()
notAfter := notBefore.Add(time.Hour * 24 * 365 * 10) // 10 years
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, trace.Wrap(err)
}
entity := pkix.Name{
CommonName: "localhost",
Country: []string{"US"},
Organization: []string{"localhost"},
}
template := x509.Certificate{
SerialNumber: serialNumber,
Issuer: entity,
Subject: entity,
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
BasicConstraintsValid: true,
IsCA: true,
}
// collect IP addresses localhost resolves to and add them to the cert. template:
template.DNSNames = append(hostNames, "localhost.local")
ips, _ := net.LookupIP("localhost")
if ips != nil {
template.IPAddresses = ips
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
if err != nil {
return nil, trace.Wrap(err)
}
publicKeyBytes, err := x509.MarshalPKIXPublicKey(priv.Public())
if err != nil {
log.Error(err)
return nil, trace.Wrap(err)
}
return &TLSCredentials{
PublicKey: pem.EncodeToMemory(&pem.Block{Type: "RSA PUBLIC KEY", Bytes: publicKeyBytes}),
PrivateKey: pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)}),
Cert: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes}),
}, nil
} | [
"func",
"GenerateSelfSignedCert",
"(",
"hostNames",
"[",
"]",
"string",
")",
"(",
"*",
"TLSCredentials",
",",
"error",
")",
"{",
"priv",
",",
"err",
":=",
"rsa",
".",
"GenerateKey",
"(",
"rand",
".",
"Reader",
",",
"teleport",
".",
"RSAKeySize",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"notBefore",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"notAfter",
":=",
"notBefore",
".",
"Add",
"(",
"time",
".",
"Hour",
"*",
"24",
"*",
"365",
"*",
"10",
")",
"// 10 years",
"\n\n",
"serialNumberLimit",
":=",
"new",
"(",
"big",
".",
"Int",
")",
".",
"Lsh",
"(",
"big",
".",
"NewInt",
"(",
"1",
")",
",",
"128",
")",
"\n",
"serialNumber",
",",
"err",
":=",
"rand",
".",
"Int",
"(",
"rand",
".",
"Reader",
",",
"serialNumberLimit",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"entity",
":=",
"pkix",
".",
"Name",
"{",
"CommonName",
":",
"\"",
"\"",
",",
"Country",
":",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
",",
"Organization",
":",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
",",
"}",
"\n\n",
"template",
":=",
"x509",
".",
"Certificate",
"{",
"SerialNumber",
":",
"serialNumber",
",",
"Issuer",
":",
"entity",
",",
"Subject",
":",
"entity",
",",
"NotBefore",
":",
"notBefore",
",",
"NotAfter",
":",
"notAfter",
",",
"KeyUsage",
":",
"x509",
".",
"KeyUsageKeyEncipherment",
"|",
"x509",
".",
"KeyUsageDigitalSignature",
"|",
"x509",
".",
"KeyUsageCertSign",
",",
"BasicConstraintsValid",
":",
"true",
",",
"IsCA",
":",
"true",
",",
"}",
"\n\n",
"// collect IP addresses localhost resolves to and add them to the cert. template:",
"template",
".",
"DNSNames",
"=",
"append",
"(",
"hostNames",
",",
"\"",
"\"",
")",
"\n",
"ips",
",",
"_",
":=",
"net",
".",
"LookupIP",
"(",
"\"",
"\"",
")",
"\n",
"if",
"ips",
"!=",
"nil",
"{",
"template",
".",
"IPAddresses",
"=",
"ips",
"\n",
"}",
"\n",
"derBytes",
",",
"err",
":=",
"x509",
".",
"CreateCertificate",
"(",
"rand",
".",
"Reader",
",",
"&",
"template",
",",
"&",
"template",
",",
"&",
"priv",
".",
"PublicKey",
",",
"priv",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"publicKeyBytes",
",",
"err",
":=",
"x509",
".",
"MarshalPKIXPublicKey",
"(",
"priv",
".",
"Public",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Error",
"(",
"err",
")",
"\n",
"return",
"nil",
",",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"TLSCredentials",
"{",
"PublicKey",
":",
"pem",
".",
"EncodeToMemory",
"(",
"&",
"pem",
".",
"Block",
"{",
"Type",
":",
"\"",
"\"",
",",
"Bytes",
":",
"publicKeyBytes",
"}",
")",
",",
"PrivateKey",
":",
"pem",
".",
"EncodeToMemory",
"(",
"&",
"pem",
".",
"Block",
"{",
"Type",
":",
"\"",
"\"",
",",
"Bytes",
":",
"x509",
".",
"MarshalPKCS1PrivateKey",
"(",
"priv",
")",
"}",
")",
",",
"Cert",
":",
"pem",
".",
"EncodeToMemory",
"(",
"&",
"pem",
".",
"Block",
"{",
"Type",
":",
"\"",
"\"",
",",
"Bytes",
":",
"derBytes",
"}",
")",
",",
"}",
",",
"nil",
"\n",
"}"
] | // GenerateSelfSignedCert generates a self signed certificate that
// is valid for given domain names and ips, returns PEM-encoded bytes with key and cert | [
"GenerateSelfSignedCert",
"generates",
"a",
"self",
"signed",
"certificate",
"that",
"is",
"valid",
"for",
"given",
"domain",
"names",
"and",
"ips",
"returns",
"PEM",
"-",
"encoded",
"bytes",
"with",
"key",
"and",
"cert"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/tls.go#L100-L153 | train |
gravitational/teleport | lib/utils/tls.go | CipherSuiteMapping | func CipherSuiteMapping(cipherSuites []string) ([]uint16, error) {
out := make([]uint16, 0, len(cipherSuites))
for _, cs := range cipherSuites {
c, ok := cipherSuiteMapping[cs]
if !ok {
return nil, trace.BadParameter("cipher suite not supported: %v", cs)
}
out = append(out, c)
}
return out, nil
} | go | func CipherSuiteMapping(cipherSuites []string) ([]uint16, error) {
out := make([]uint16, 0, len(cipherSuites))
for _, cs := range cipherSuites {
c, ok := cipherSuiteMapping[cs]
if !ok {
return nil, trace.BadParameter("cipher suite not supported: %v", cs)
}
out = append(out, c)
}
return out, nil
} | [
"func",
"CipherSuiteMapping",
"(",
"cipherSuites",
"[",
"]",
"string",
")",
"(",
"[",
"]",
"uint16",
",",
"error",
")",
"{",
"out",
":=",
"make",
"(",
"[",
"]",
"uint16",
",",
"0",
",",
"len",
"(",
"cipherSuites",
")",
")",
"\n\n",
"for",
"_",
",",
"cs",
":=",
"range",
"cipherSuites",
"{",
"c",
",",
"ok",
":=",
"cipherSuiteMapping",
"[",
"cs",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"trace",
".",
"BadParameter",
"(",
"\"",
"\"",
",",
"cs",
")",
"\n",
"}",
"\n\n",
"out",
"=",
"append",
"(",
"out",
",",
"c",
")",
"\n",
"}",
"\n\n",
"return",
"out",
",",
"nil",
"\n",
"}"
] | // CipherSuiteMapping transforms Teleport formatted cipher suites strings
// into uint16 IDs. | [
"CipherSuiteMapping",
"transforms",
"Teleport",
"formatted",
"cipher",
"suites",
"strings",
"into",
"uint16",
"IDs",
"."
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/tls.go#L157-L170 | train |
gravitational/teleport | lib/srv/term.go | NewTerminal | func NewTerminal(ctx *ServerContext) (Terminal, error) {
// It doesn't matter what mode the cluster is in, if this is a Teleport node
// return a local terminal.
if ctx.srv.Component() == teleport.ComponentNode {
return newLocalTerminal(ctx)
}
// If this is not a Teleport node, find out what mode the cluster is in and
// return the correct terminal.
if ctx.ClusterConfig.GetSessionRecording() == services.RecordAtProxy {
return newRemoteTerminal(ctx)
}
return newLocalTerminal(ctx)
} | go | func NewTerminal(ctx *ServerContext) (Terminal, error) {
// It doesn't matter what mode the cluster is in, if this is a Teleport node
// return a local terminal.
if ctx.srv.Component() == teleport.ComponentNode {
return newLocalTerminal(ctx)
}
// If this is not a Teleport node, find out what mode the cluster is in and
// return the correct terminal.
if ctx.ClusterConfig.GetSessionRecording() == services.RecordAtProxy {
return newRemoteTerminal(ctx)
}
return newLocalTerminal(ctx)
} | [
"func",
"NewTerminal",
"(",
"ctx",
"*",
"ServerContext",
")",
"(",
"Terminal",
",",
"error",
")",
"{",
"// It doesn't matter what mode the cluster is in, if this is a Teleport node",
"// return a local terminal.",
"if",
"ctx",
".",
"srv",
".",
"Component",
"(",
")",
"==",
"teleport",
".",
"ComponentNode",
"{",
"return",
"newLocalTerminal",
"(",
"ctx",
")",
"\n",
"}",
"\n\n",
"// If this is not a Teleport node, find out what mode the cluster is in and",
"// return the correct terminal.",
"if",
"ctx",
".",
"ClusterConfig",
".",
"GetSessionRecording",
"(",
")",
"==",
"services",
".",
"RecordAtProxy",
"{",
"return",
"newRemoteTerminal",
"(",
"ctx",
")",
"\n",
"}",
"\n",
"return",
"newLocalTerminal",
"(",
"ctx",
")",
"\n",
"}"
] | // NewTerminal returns a new terminal. Terminal can be local or remote
// depending on cluster configuration. | [
"NewTerminal",
"returns",
"a",
"new",
"terminal",
".",
"Terminal",
"can",
"be",
"local",
"or",
"remote",
"depending",
"on",
"cluster",
"configuration",
"."
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/term.go#L95-L108 | train |
gravitational/teleport | lib/srv/term.go | newLocalTerminal | func newLocalTerminal(ctx *ServerContext) (*terminal, error) {
var err error
t := &terminal{
log: log.WithFields(log.Fields{
trace.Component: teleport.ComponentLocalTerm,
}),
ctx: ctx,
}
// Open PTY and corresponding TTY.
t.pty, t.tty, err = pty.Open()
if err != nil {
log.Warnf("Could not start PTY %v", err)
return nil, err
}
// Set the TTY owner. Failure is not fatal, for example Teleport is running
// on a read-only filesystem, but logging is useful for diagnostic purposes.
err = t.setOwner()
if err != nil {
log.Debugf("Unable to set TTY owner: %v.\n", err)
}
return t, nil
} | go | func newLocalTerminal(ctx *ServerContext) (*terminal, error) {
var err error
t := &terminal{
log: log.WithFields(log.Fields{
trace.Component: teleport.ComponentLocalTerm,
}),
ctx: ctx,
}
// Open PTY and corresponding TTY.
t.pty, t.tty, err = pty.Open()
if err != nil {
log.Warnf("Could not start PTY %v", err)
return nil, err
}
// Set the TTY owner. Failure is not fatal, for example Teleport is running
// on a read-only filesystem, but logging is useful for diagnostic purposes.
err = t.setOwner()
if err != nil {
log.Debugf("Unable to set TTY owner: %v.\n", err)
}
return t, nil
} | [
"func",
"newLocalTerminal",
"(",
"ctx",
"*",
"ServerContext",
")",
"(",
"*",
"terminal",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n\n",
"t",
":=",
"&",
"terminal",
"{",
"log",
":",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"trace",
".",
"Component",
":",
"teleport",
".",
"ComponentLocalTerm",
",",
"}",
")",
",",
"ctx",
":",
"ctx",
",",
"}",
"\n\n",
"// Open PTY and corresponding TTY.",
"t",
".",
"pty",
",",
"t",
".",
"tty",
",",
"err",
"=",
"pty",
".",
"Open",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Set the TTY owner. Failure is not fatal, for example Teleport is running",
"// on a read-only filesystem, but logging is useful for diagnostic purposes.",
"err",
"=",
"t",
".",
"setOwner",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\\n",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"t",
",",
"nil",
"\n",
"}"
] | // NewLocalTerminal creates and returns a local PTY. | [
"NewLocalTerminal",
"creates",
"and",
"returns",
"a",
"local",
"PTY",
"."
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/term.go#L128-L153 | train |
gravitational/teleport | lib/srv/term.go | Run | func (t *terminal) Run() error {
defer t.closeTTY()
cmd, err := prepareInteractiveCommand(t.ctx)
if err != nil {
return trace.Wrap(err)
}
t.cmd = cmd
cmd.Stdout = t.tty
cmd.Stdin = t.tty
cmd.Stderr = t.tty
cmd.SysProcAttr.Setctty = true
cmd.SysProcAttr.Setsid = true
err = cmd.Start()
if err != nil {
return trace.Wrap(err)
}
return nil
} | go | func (t *terminal) Run() error {
defer t.closeTTY()
cmd, err := prepareInteractiveCommand(t.ctx)
if err != nil {
return trace.Wrap(err)
}
t.cmd = cmd
cmd.Stdout = t.tty
cmd.Stdin = t.tty
cmd.Stderr = t.tty
cmd.SysProcAttr.Setctty = true
cmd.SysProcAttr.Setsid = true
err = cmd.Start()
if err != nil {
return trace.Wrap(err)
}
return nil
} | [
"func",
"(",
"t",
"*",
"terminal",
")",
"Run",
"(",
")",
"error",
"{",
"defer",
"t",
".",
"closeTTY",
"(",
")",
"\n\n",
"cmd",
",",
"err",
":=",
"prepareInteractiveCommand",
"(",
"t",
".",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"t",
".",
"cmd",
"=",
"cmd",
"\n\n",
"cmd",
".",
"Stdout",
"=",
"t",
".",
"tty",
"\n",
"cmd",
".",
"Stdin",
"=",
"t",
".",
"tty",
"\n",
"cmd",
".",
"Stderr",
"=",
"t",
".",
"tty",
"\n",
"cmd",
".",
"SysProcAttr",
".",
"Setctty",
"=",
"true",
"\n",
"cmd",
".",
"SysProcAttr",
".",
"Setsid",
"=",
"true",
"\n\n",
"err",
"=",
"cmd",
".",
"Start",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Run will run the terminal. | [
"Run",
"will",
"run",
"the",
"terminal",
"."
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/term.go#L162-L183 | train |
gravitational/teleport | lib/srv/term.go | Wait | func (t *terminal) Wait() (*ExecResult, error) {
err := t.cmd.Wait()
if err != nil {
if exitErr, ok := err.(*exec.ExitError); ok {
status := exitErr.Sys().(syscall.WaitStatus)
return &ExecResult{Code: status.ExitStatus(), Command: t.cmd.Path}, nil
}
return nil, err
}
status, ok := t.cmd.ProcessState.Sys().(syscall.WaitStatus)
if !ok {
return nil, trace.Errorf("unknown exit status: %T(%v)", t.cmd.ProcessState.Sys(), t.cmd.ProcessState.Sys())
}
return &ExecResult{
Code: status.ExitStatus(),
Command: t.cmd.Path,
}, nil
} | go | func (t *terminal) Wait() (*ExecResult, error) {
err := t.cmd.Wait()
if err != nil {
if exitErr, ok := err.(*exec.ExitError); ok {
status := exitErr.Sys().(syscall.WaitStatus)
return &ExecResult{Code: status.ExitStatus(), Command: t.cmd.Path}, nil
}
return nil, err
}
status, ok := t.cmd.ProcessState.Sys().(syscall.WaitStatus)
if !ok {
return nil, trace.Errorf("unknown exit status: %T(%v)", t.cmd.ProcessState.Sys(), t.cmd.ProcessState.Sys())
}
return &ExecResult{
Code: status.ExitStatus(),
Command: t.cmd.Path,
}, nil
} | [
"func",
"(",
"t",
"*",
"terminal",
")",
"Wait",
"(",
")",
"(",
"*",
"ExecResult",
",",
"error",
")",
"{",
"err",
":=",
"t",
".",
"cmd",
".",
"Wait",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"exitErr",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"exec",
".",
"ExitError",
")",
";",
"ok",
"{",
"status",
":=",
"exitErr",
".",
"Sys",
"(",
")",
".",
"(",
"syscall",
".",
"WaitStatus",
")",
"\n",
"return",
"&",
"ExecResult",
"{",
"Code",
":",
"status",
".",
"ExitStatus",
"(",
")",
",",
"Command",
":",
"t",
".",
"cmd",
".",
"Path",
"}",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"status",
",",
"ok",
":=",
"t",
".",
"cmd",
".",
"ProcessState",
".",
"Sys",
"(",
")",
".",
"(",
"syscall",
".",
"WaitStatus",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"trace",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"t",
".",
"cmd",
".",
"ProcessState",
".",
"Sys",
"(",
")",
",",
"t",
".",
"cmd",
".",
"ProcessState",
".",
"Sys",
"(",
")",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"ExecResult",
"{",
"Code",
":",
"status",
".",
"ExitStatus",
"(",
")",
",",
"Command",
":",
"t",
".",
"cmd",
".",
"Path",
",",
"}",
",",
"nil",
"\n",
"}"
] | // Wait will block until the terminal is complete. | [
"Wait",
"will",
"block",
"until",
"the",
"terminal",
"is",
"complete",
"."
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/term.go#L186-L205 | train |
gravitational/teleport | lib/srv/term.go | Kill | func (t *terminal) Kill() error {
if t.cmd.Process != nil {
if err := t.cmd.Process.Kill(); err != nil {
if err.Error() != "os: process already finished" {
return trace.Wrap(err)
}
}
}
return nil
} | go | func (t *terminal) Kill() error {
if t.cmd.Process != nil {
if err := t.cmd.Process.Kill(); err != nil {
if err.Error() != "os: process already finished" {
return trace.Wrap(err)
}
}
}
return nil
} | [
"func",
"(",
"t",
"*",
"terminal",
")",
"Kill",
"(",
")",
"error",
"{",
"if",
"t",
".",
"cmd",
".",
"Process",
"!=",
"nil",
"{",
"if",
"err",
":=",
"t",
".",
"cmd",
".",
"Process",
".",
"Kill",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"err",
".",
"Error",
"(",
")",
"!=",
"\"",
"\"",
"{",
"return",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Kill will force kill the terminal. | [
"Kill",
"will",
"force",
"kill",
"the",
"terminal",
"."
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/term.go#L208-L218 | train |
gravitational/teleport | lib/srv/term.go | Close | func (t *terminal) Close() error {
var err error
// note, pty is closed in the copying goroutine,
// not here to avoid data races
if t.tty != nil {
if e := t.tty.Close(); e != nil {
err = e
}
}
go t.closePTY()
return trace.Wrap(err)
} | go | func (t *terminal) Close() error {
var err error
// note, pty is closed in the copying goroutine,
// not here to avoid data races
if t.tty != nil {
if e := t.tty.Close(); e != nil {
err = e
}
}
go t.closePTY()
return trace.Wrap(err)
} | [
"func",
"(",
"t",
"*",
"terminal",
")",
"Close",
"(",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"// note, pty is closed in the copying goroutine,",
"// not here to avoid data races",
"if",
"t",
".",
"tty",
"!=",
"nil",
"{",
"if",
"e",
":=",
"t",
".",
"tty",
".",
"Close",
"(",
")",
";",
"e",
"!=",
"nil",
"{",
"err",
"=",
"e",
"\n",
"}",
"\n",
"}",
"\n",
"go",
"t",
".",
"closePTY",
"(",
")",
"\n",
"return",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}"
] | // Close will free resources associated with the terminal. | [
"Close",
"will",
"free",
"resources",
"associated",
"with",
"the",
"terminal",
"."
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/term.go#L231-L242 | train |
gravitational/teleport | lib/srv/term.go | GetWinSize | func (t *terminal) GetWinSize() (*term.Winsize, error) {
t.mu.Lock()
defer t.mu.Unlock()
if t.pty == nil {
return nil, trace.NotFound("no pty")
}
ws, err := term.GetWinsize(t.pty.Fd())
if err != nil {
return nil, trace.Wrap(err)
}
return ws, nil
} | go | func (t *terminal) GetWinSize() (*term.Winsize, error) {
t.mu.Lock()
defer t.mu.Unlock()
if t.pty == nil {
return nil, trace.NotFound("no pty")
}
ws, err := term.GetWinsize(t.pty.Fd())
if err != nil {
return nil, trace.Wrap(err)
}
return ws, nil
} | [
"func",
"(",
"t",
"*",
"terminal",
")",
"GetWinSize",
"(",
")",
"(",
"*",
"term",
".",
"Winsize",
",",
"error",
")",
"{",
"t",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"t",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"t",
".",
"pty",
"==",
"nil",
"{",
"return",
"nil",
",",
"trace",
".",
"NotFound",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"ws",
",",
"err",
":=",
"term",
".",
"GetWinsize",
"(",
"t",
".",
"pty",
".",
"Fd",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"ws",
",",
"nil",
"\n",
"}"
] | // GetWinSize returns the window size of the terminal. | [
"GetWinSize",
"returns",
"the",
"window",
"size",
"of",
"the",
"terminal",
"."
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/term.go#L264-L275 | train |
gravitational/teleport | lib/srv/term.go | SetWinSize | func (t *terminal) SetWinSize(params rsession.TerminalParams) error {
t.mu.Lock()
defer t.mu.Unlock()
if t.pty == nil {
return trace.NotFound("no pty")
}
if err := term.SetWinsize(t.pty.Fd(), params.Winsize()); err != nil {
return trace.Wrap(err)
}
t.params = params
return nil
} | go | func (t *terminal) SetWinSize(params rsession.TerminalParams) error {
t.mu.Lock()
defer t.mu.Unlock()
if t.pty == nil {
return trace.NotFound("no pty")
}
if err := term.SetWinsize(t.pty.Fd(), params.Winsize()); err != nil {
return trace.Wrap(err)
}
t.params = params
return nil
} | [
"func",
"(",
"t",
"*",
"terminal",
")",
"SetWinSize",
"(",
"params",
"rsession",
".",
"TerminalParams",
")",
"error",
"{",
"t",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"t",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"t",
".",
"pty",
"==",
"nil",
"{",
"return",
"trace",
".",
"NotFound",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"term",
".",
"SetWinsize",
"(",
"t",
".",
"pty",
".",
"Fd",
"(",
")",
",",
"params",
".",
"Winsize",
"(",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"t",
".",
"params",
"=",
"params",
"\n",
"return",
"nil",
"\n",
"}"
] | // SetWinSize sets the window size of the terminal. | [
"SetWinSize",
"sets",
"the",
"window",
"size",
"of",
"the",
"terminal",
"."
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/term.go#L278-L289 | train |
gravitational/teleport | lib/srv/term.go | GetTerminalParams | func (t *terminal) GetTerminalParams() rsession.TerminalParams {
t.mu.Lock()
defer t.mu.Unlock()
return t.params
} | go | func (t *terminal) GetTerminalParams() rsession.TerminalParams {
t.mu.Lock()
defer t.mu.Unlock()
return t.params
} | [
"func",
"(",
"t",
"*",
"terminal",
")",
"GetTerminalParams",
"(",
")",
"rsession",
".",
"TerminalParams",
"{",
"t",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"t",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"t",
".",
"params",
"\n",
"}"
] | // GetTerminalParams is a fast call to get cached terminal parameters
// and avoid extra system call. | [
"GetTerminalParams",
"is",
"a",
"fast",
"call",
"to",
"get",
"cached",
"terminal",
"parameters",
"and",
"avoid",
"extra",
"system",
"call",
"."
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/term.go#L293-L297 | train |
gravitational/teleport | lib/srv/term.go | SetTermType | func (t *terminal) SetTermType(term string) {
if term == "" {
term = defaultTerm
}
t.termType = term
} | go | func (t *terminal) SetTermType(term string) {
if term == "" {
term = defaultTerm
}
t.termType = term
} | [
"func",
"(",
"t",
"*",
"terminal",
")",
"SetTermType",
"(",
"term",
"string",
")",
"{",
"if",
"term",
"==",
"\"",
"\"",
"{",
"term",
"=",
"defaultTerm",
"\n",
"}",
"\n",
"t",
".",
"termType",
"=",
"term",
"\n",
"}"
] | // SetTermType sets the terminal type from "req-pty" request. | [
"SetTermType",
"sets",
"the",
"terminal",
"type",
"from",
"req",
"-",
"pty",
"request",
"."
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/term.go#L305-L310 | train |
gravitational/teleport | lib/srv/term.go | setOwner | func (t *terminal) setOwner() error {
uid, gid, mode, err := getOwner(t.ctx.Identity.Login, user.Lookup, user.LookupGroup)
if err != nil {
return trace.Wrap(err)
}
err = os.Chown(t.tty.Name(), uid, gid)
if err != nil {
return trace.Wrap(err)
}
err = os.Chmod(t.tty.Name(), mode)
if err != nil {
return trace.Wrap(err)
}
log.Debugf("Set permissions on %v to %v:%v with mode %v.", t.tty.Name(), uid, gid, mode)
return nil
} | go | func (t *terminal) setOwner() error {
uid, gid, mode, err := getOwner(t.ctx.Identity.Login, user.Lookup, user.LookupGroup)
if err != nil {
return trace.Wrap(err)
}
err = os.Chown(t.tty.Name(), uid, gid)
if err != nil {
return trace.Wrap(err)
}
err = os.Chmod(t.tty.Name(), mode)
if err != nil {
return trace.Wrap(err)
}
log.Debugf("Set permissions on %v to %v:%v with mode %v.", t.tty.Name(), uid, gid, mode)
return nil
} | [
"func",
"(",
"t",
"*",
"terminal",
")",
"setOwner",
"(",
")",
"error",
"{",
"uid",
",",
"gid",
",",
"mode",
",",
"err",
":=",
"getOwner",
"(",
"t",
".",
"ctx",
".",
"Identity",
".",
"Login",
",",
"user",
".",
"Lookup",
",",
"user",
".",
"LookupGroup",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"err",
"=",
"os",
".",
"Chown",
"(",
"t",
".",
"tty",
".",
"Name",
"(",
")",
",",
"uid",
",",
"gid",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"err",
"=",
"os",
".",
"Chmod",
"(",
"t",
".",
"tty",
".",
"Name",
"(",
")",
",",
"mode",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"t",
".",
"tty",
".",
"Name",
"(",
")",
",",
"uid",
",",
"gid",
",",
"mode",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // setOwner changes the owner and mode of the TTY. | [
"setOwner",
"changes",
"the",
"owner",
"and",
"mode",
"of",
"the",
"TTY",
"."
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/term.go#L355-L373 | train |
gravitational/teleport | lib/srv/term.go | prepareRemoteSession | func (t *remoteTerminal) prepareRemoteSession(session *ssh.Session, ctx *ServerContext) {
envs := map[string]string{
teleport.SSHTeleportUser: ctx.Identity.TeleportUser,
teleport.SSHSessionWebproxyAddr: ctx.ProxyPublicAddress(),
teleport.SSHTeleportHostUUID: ctx.srv.ID(),
teleport.SSHTeleportClusterName: ctx.ClusterName,
teleport.SSHSessionID: string(ctx.session.id),
}
for k, v := range envs {
if err := session.Setenv(k, v); err != nil {
t.log.Debugf("Unable to set environment variable: %v: %v", k, v)
}
}
} | go | func (t *remoteTerminal) prepareRemoteSession(session *ssh.Session, ctx *ServerContext) {
envs := map[string]string{
teleport.SSHTeleportUser: ctx.Identity.TeleportUser,
teleport.SSHSessionWebproxyAddr: ctx.ProxyPublicAddress(),
teleport.SSHTeleportHostUUID: ctx.srv.ID(),
teleport.SSHTeleportClusterName: ctx.ClusterName,
teleport.SSHSessionID: string(ctx.session.id),
}
for k, v := range envs {
if err := session.Setenv(k, v); err != nil {
t.log.Debugf("Unable to set environment variable: %v: %v", k, v)
}
}
} | [
"func",
"(",
"t",
"*",
"remoteTerminal",
")",
"prepareRemoteSession",
"(",
"session",
"*",
"ssh",
".",
"Session",
",",
"ctx",
"*",
"ServerContext",
")",
"{",
"envs",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"teleport",
".",
"SSHTeleportUser",
":",
"ctx",
".",
"Identity",
".",
"TeleportUser",
",",
"teleport",
".",
"SSHSessionWebproxyAddr",
":",
"ctx",
".",
"ProxyPublicAddress",
"(",
")",
",",
"teleport",
".",
"SSHTeleportHostUUID",
":",
"ctx",
".",
"srv",
".",
"ID",
"(",
")",
",",
"teleport",
".",
"SSHTeleportClusterName",
":",
"ctx",
".",
"ClusterName",
",",
"teleport",
".",
"SSHSessionID",
":",
"string",
"(",
"ctx",
".",
"session",
".",
"id",
")",
",",
"}",
"\n\n",
"for",
"k",
",",
"v",
":=",
"range",
"envs",
"{",
"if",
"err",
":=",
"session",
".",
"Setenv",
"(",
"k",
",",
"v",
")",
";",
"err",
"!=",
"nil",
"{",
"t",
".",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"k",
",",
"v",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // prepareRemoteSession prepares the more session for execution. | [
"prepareRemoteSession",
"prepares",
"the",
"more",
"session",
"for",
"execution",
"."
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/term.go#L586-L600 | train |
gravitational/teleport | lib/auth/auth.go | NewAuthServer | func NewAuthServer(cfg *InitConfig, opts ...AuthServerOption) (*AuthServer, error) {
if cfg.Trust == nil {
cfg.Trust = local.NewCAService(cfg.Backend)
}
if cfg.Presence == nil {
cfg.Presence = local.NewPresenceService(cfg.Backend)
}
if cfg.Provisioner == nil {
cfg.Provisioner = local.NewProvisioningService(cfg.Backend)
}
if cfg.Identity == nil {
cfg.Identity = local.NewIdentityService(cfg.Backend)
}
if cfg.Access == nil {
cfg.Access = local.NewAccessService(cfg.Backend)
}
if cfg.ClusterConfiguration == nil {
cfg.ClusterConfiguration = local.NewClusterConfigurationService(cfg.Backend)
}
if cfg.Events == nil {
cfg.Events = local.NewEventsService(cfg.Backend)
}
if cfg.AuditLog == nil {
cfg.AuditLog = events.NewDiscardAuditLog()
}
limiter, err := limiter.NewConnectionsLimiter(limiter.LimiterConfig{
MaxConnections: defaults.LimiterMaxConcurrentSignatures,
})
if err != nil {
return nil, trace.Wrap(err)
}
closeCtx, cancelFunc := context.WithCancel(context.TODO())
as := AuthServer{
bk: cfg.Backend,
limiter: limiter,
Authority: cfg.Authority,
AuthServiceName: cfg.AuthServiceName,
oidcClients: make(map[string]*oidcClient),
samlProviders: make(map[string]*samlProvider),
githubClients: make(map[string]*githubClient),
cancelFunc: cancelFunc,
closeCtx: closeCtx,
AuthServices: AuthServices{
Trust: cfg.Trust,
Presence: cfg.Presence,
Provisioner: cfg.Provisioner,
Identity: cfg.Identity,
Access: cfg.Access,
ClusterConfiguration: cfg.ClusterConfiguration,
IAuditLog: cfg.AuditLog,
Events: cfg.Events,
},
}
for _, o := range opts {
o(&as)
}
if as.clock == nil {
as.clock = clockwork.NewRealClock()
}
return &as, nil
} | go | func NewAuthServer(cfg *InitConfig, opts ...AuthServerOption) (*AuthServer, error) {
if cfg.Trust == nil {
cfg.Trust = local.NewCAService(cfg.Backend)
}
if cfg.Presence == nil {
cfg.Presence = local.NewPresenceService(cfg.Backend)
}
if cfg.Provisioner == nil {
cfg.Provisioner = local.NewProvisioningService(cfg.Backend)
}
if cfg.Identity == nil {
cfg.Identity = local.NewIdentityService(cfg.Backend)
}
if cfg.Access == nil {
cfg.Access = local.NewAccessService(cfg.Backend)
}
if cfg.ClusterConfiguration == nil {
cfg.ClusterConfiguration = local.NewClusterConfigurationService(cfg.Backend)
}
if cfg.Events == nil {
cfg.Events = local.NewEventsService(cfg.Backend)
}
if cfg.AuditLog == nil {
cfg.AuditLog = events.NewDiscardAuditLog()
}
limiter, err := limiter.NewConnectionsLimiter(limiter.LimiterConfig{
MaxConnections: defaults.LimiterMaxConcurrentSignatures,
})
if err != nil {
return nil, trace.Wrap(err)
}
closeCtx, cancelFunc := context.WithCancel(context.TODO())
as := AuthServer{
bk: cfg.Backend,
limiter: limiter,
Authority: cfg.Authority,
AuthServiceName: cfg.AuthServiceName,
oidcClients: make(map[string]*oidcClient),
samlProviders: make(map[string]*samlProvider),
githubClients: make(map[string]*githubClient),
cancelFunc: cancelFunc,
closeCtx: closeCtx,
AuthServices: AuthServices{
Trust: cfg.Trust,
Presence: cfg.Presence,
Provisioner: cfg.Provisioner,
Identity: cfg.Identity,
Access: cfg.Access,
ClusterConfiguration: cfg.ClusterConfiguration,
IAuditLog: cfg.AuditLog,
Events: cfg.Events,
},
}
for _, o := range opts {
o(&as)
}
if as.clock == nil {
as.clock = clockwork.NewRealClock()
}
return &as, nil
} | [
"func",
"NewAuthServer",
"(",
"cfg",
"*",
"InitConfig",
",",
"opts",
"...",
"AuthServerOption",
")",
"(",
"*",
"AuthServer",
",",
"error",
")",
"{",
"if",
"cfg",
".",
"Trust",
"==",
"nil",
"{",
"cfg",
".",
"Trust",
"=",
"local",
".",
"NewCAService",
"(",
"cfg",
".",
"Backend",
")",
"\n",
"}",
"\n",
"if",
"cfg",
".",
"Presence",
"==",
"nil",
"{",
"cfg",
".",
"Presence",
"=",
"local",
".",
"NewPresenceService",
"(",
"cfg",
".",
"Backend",
")",
"\n",
"}",
"\n",
"if",
"cfg",
".",
"Provisioner",
"==",
"nil",
"{",
"cfg",
".",
"Provisioner",
"=",
"local",
".",
"NewProvisioningService",
"(",
"cfg",
".",
"Backend",
")",
"\n",
"}",
"\n",
"if",
"cfg",
".",
"Identity",
"==",
"nil",
"{",
"cfg",
".",
"Identity",
"=",
"local",
".",
"NewIdentityService",
"(",
"cfg",
".",
"Backend",
")",
"\n",
"}",
"\n",
"if",
"cfg",
".",
"Access",
"==",
"nil",
"{",
"cfg",
".",
"Access",
"=",
"local",
".",
"NewAccessService",
"(",
"cfg",
".",
"Backend",
")",
"\n",
"}",
"\n",
"if",
"cfg",
".",
"ClusterConfiguration",
"==",
"nil",
"{",
"cfg",
".",
"ClusterConfiguration",
"=",
"local",
".",
"NewClusterConfigurationService",
"(",
"cfg",
".",
"Backend",
")",
"\n",
"}",
"\n",
"if",
"cfg",
".",
"Events",
"==",
"nil",
"{",
"cfg",
".",
"Events",
"=",
"local",
".",
"NewEventsService",
"(",
"cfg",
".",
"Backend",
")",
"\n",
"}",
"\n",
"if",
"cfg",
".",
"AuditLog",
"==",
"nil",
"{",
"cfg",
".",
"AuditLog",
"=",
"events",
".",
"NewDiscardAuditLog",
"(",
")",
"\n",
"}",
"\n\n",
"limiter",
",",
"err",
":=",
"limiter",
".",
"NewConnectionsLimiter",
"(",
"limiter",
".",
"LimiterConfig",
"{",
"MaxConnections",
":",
"defaults",
".",
"LimiterMaxConcurrentSignatures",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"closeCtx",
",",
"cancelFunc",
":=",
"context",
".",
"WithCancel",
"(",
"context",
".",
"TODO",
"(",
")",
")",
"\n",
"as",
":=",
"AuthServer",
"{",
"bk",
":",
"cfg",
".",
"Backend",
",",
"limiter",
":",
"limiter",
",",
"Authority",
":",
"cfg",
".",
"Authority",
",",
"AuthServiceName",
":",
"cfg",
".",
"AuthServiceName",
",",
"oidcClients",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"oidcClient",
")",
",",
"samlProviders",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"samlProvider",
")",
",",
"githubClients",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"githubClient",
")",
",",
"cancelFunc",
":",
"cancelFunc",
",",
"closeCtx",
":",
"closeCtx",
",",
"AuthServices",
":",
"AuthServices",
"{",
"Trust",
":",
"cfg",
".",
"Trust",
",",
"Presence",
":",
"cfg",
".",
"Presence",
",",
"Provisioner",
":",
"cfg",
".",
"Provisioner",
",",
"Identity",
":",
"cfg",
".",
"Identity",
",",
"Access",
":",
"cfg",
".",
"Access",
",",
"ClusterConfiguration",
":",
"cfg",
".",
"ClusterConfiguration",
",",
"IAuditLog",
":",
"cfg",
".",
"AuditLog",
",",
"Events",
":",
"cfg",
".",
"Events",
",",
"}",
",",
"}",
"\n",
"for",
"_",
",",
"o",
":=",
"range",
"opts",
"{",
"o",
"(",
"&",
"as",
")",
"\n",
"}",
"\n",
"if",
"as",
".",
"clock",
"==",
"nil",
"{",
"as",
".",
"clock",
"=",
"clockwork",
".",
"NewRealClock",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"as",
",",
"nil",
"\n",
"}"
] | // NewAuthServer creates and configures a new AuthServer instance | [
"NewAuthServer",
"creates",
"and",
"configures",
"a",
"new",
"AuthServer",
"instance"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L62-L125 | train |
gravitational/teleport | lib/auth/auth.go | SetCache | func (a *AuthServer) SetCache(clt AuthCache) {
a.lock.Lock()
defer a.lock.Unlock()
a.cache = clt
} | go | func (a *AuthServer) SetCache(clt AuthCache) {
a.lock.Lock()
defer a.lock.Unlock()
a.cache = clt
} | [
"func",
"(",
"a",
"*",
"AuthServer",
")",
"SetCache",
"(",
"clt",
"AuthCache",
")",
"{",
"a",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"a",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"a",
".",
"cache",
"=",
"clt",
"\n",
"}"
] | // SetCache sets cache used by auth server | [
"SetCache",
"sets",
"cache",
"used",
"by",
"auth",
"server"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L212-L216 | train |
gravitational/teleport | lib/auth/auth.go | GetCache | func (a *AuthServer) GetCache() AuthCache {
a.lock.RLock()
defer a.lock.RUnlock()
if a.cache == nil {
return &a.AuthServices
}
return a.cache
} | go | func (a *AuthServer) GetCache() AuthCache {
a.lock.RLock()
defer a.lock.RUnlock()
if a.cache == nil {
return &a.AuthServices
}
return a.cache
} | [
"func",
"(",
"a",
"*",
"AuthServer",
")",
"GetCache",
"(",
")",
"AuthCache",
"{",
"a",
".",
"lock",
".",
"RLock",
"(",
")",
"\n",
"defer",
"a",
".",
"lock",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"a",
".",
"cache",
"==",
"nil",
"{",
"return",
"&",
"a",
".",
"AuthServices",
"\n",
"}",
"\n",
"return",
"a",
".",
"cache",
"\n",
"}"
] | // GetCache returns cache used by auth server | [
"GetCache",
"returns",
"cache",
"used",
"by",
"auth",
"server"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L219-L226 | train |
gravitational/teleport | lib/auth/auth.go | runPeriodicOperations | func (a *AuthServer) runPeriodicOperations() {
// run periodic functions with a semi-random period
// to avoid contention on the database in case if there are multiple
// auth servers running - so they don't compete trying
// to update the same resources.
r := rand.New(rand.NewSource(a.GetClock().Now().UnixNano()))
period := defaults.HighResPollingPeriod + time.Duration(r.Intn(int(defaults.HighResPollingPeriod/time.Second)))*time.Second
log.Debugf("Ticking with period: %v.", period)
ticker := time.NewTicker(period)
defer ticker.Stop()
for {
select {
case <-a.closeCtx.Done():
return
case <-ticker.C:
err := a.autoRotateCertAuthorities()
if err != nil {
if trace.IsCompareFailed(err) {
log.Debugf("Cert authority has been updated concurrently: %v.", err)
} else {
log.Errorf("Failed to perform cert rotation check: %v.", err)
}
}
}
}
} | go | func (a *AuthServer) runPeriodicOperations() {
// run periodic functions with a semi-random period
// to avoid contention on the database in case if there are multiple
// auth servers running - so they don't compete trying
// to update the same resources.
r := rand.New(rand.NewSource(a.GetClock().Now().UnixNano()))
period := defaults.HighResPollingPeriod + time.Duration(r.Intn(int(defaults.HighResPollingPeriod/time.Second)))*time.Second
log.Debugf("Ticking with period: %v.", period)
ticker := time.NewTicker(period)
defer ticker.Stop()
for {
select {
case <-a.closeCtx.Done():
return
case <-ticker.C:
err := a.autoRotateCertAuthorities()
if err != nil {
if trace.IsCompareFailed(err) {
log.Debugf("Cert authority has been updated concurrently: %v.", err)
} else {
log.Errorf("Failed to perform cert rotation check: %v.", err)
}
}
}
}
} | [
"func",
"(",
"a",
"*",
"AuthServer",
")",
"runPeriodicOperations",
"(",
")",
"{",
"// run periodic functions with a semi-random period",
"// to avoid contention on the database in case if there are multiple",
"// auth servers running - so they don't compete trying",
"// to update the same resources.",
"r",
":=",
"rand",
".",
"New",
"(",
"rand",
".",
"NewSource",
"(",
"a",
".",
"GetClock",
"(",
")",
".",
"Now",
"(",
")",
".",
"UnixNano",
"(",
")",
")",
")",
"\n",
"period",
":=",
"defaults",
".",
"HighResPollingPeriod",
"+",
"time",
".",
"Duration",
"(",
"r",
".",
"Intn",
"(",
"int",
"(",
"defaults",
".",
"HighResPollingPeriod",
"/",
"time",
".",
"Second",
")",
")",
")",
"*",
"time",
".",
"Second",
"\n",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"period",
")",
"\n",
"ticker",
":=",
"time",
".",
"NewTicker",
"(",
"period",
")",
"\n",
"defer",
"ticker",
".",
"Stop",
"(",
")",
"\n",
"for",
"{",
"select",
"{",
"case",
"<-",
"a",
".",
"closeCtx",
".",
"Done",
"(",
")",
":",
"return",
"\n",
"case",
"<-",
"ticker",
".",
"C",
":",
"err",
":=",
"a",
".",
"autoRotateCertAuthorities",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"trace",
".",
"IsCompareFailed",
"(",
"err",
")",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"else",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // runPeriodicOperations runs some periodic bookkeeping operations
// performed by auth server | [
"runPeriodicOperations",
"runs",
"some",
"periodic",
"bookkeeping",
"operations",
"performed",
"by",
"auth",
"server"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L230-L255 | train |
gravitational/teleport | lib/auth/auth.go | SetClock | func (a *AuthServer) SetClock(clock clockwork.Clock) {
a.lock.Lock()
defer a.lock.Unlock()
a.clock = clock
} | go | func (a *AuthServer) SetClock(clock clockwork.Clock) {
a.lock.Lock()
defer a.lock.Unlock()
a.clock = clock
} | [
"func",
"(",
"a",
"*",
"AuthServer",
")",
"SetClock",
"(",
"clock",
"clockwork",
".",
"Clock",
")",
"{",
"a",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"a",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"a",
".",
"clock",
"=",
"clock",
"\n",
"}"
] | // SetClock sets clock, used in tests | [
"SetClock",
"sets",
"clock",
"used",
"in",
"tests"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L272-L276 | train |
gravitational/teleport | lib/auth/auth.go | GetClusterConfig | func (a *AuthServer) GetClusterConfig(opts ...services.MarshalOption) (services.ClusterConfig, error) {
return a.GetCache().GetClusterConfig(opts...)
} | go | func (a *AuthServer) GetClusterConfig(opts ...services.MarshalOption) (services.ClusterConfig, error) {
return a.GetCache().GetClusterConfig(opts...)
} | [
"func",
"(",
"a",
"*",
"AuthServer",
")",
"GetClusterConfig",
"(",
"opts",
"...",
"services",
".",
"MarshalOption",
")",
"(",
"services",
".",
"ClusterConfig",
",",
"error",
")",
"{",
"return",
"a",
".",
"GetCache",
"(",
")",
".",
"GetClusterConfig",
"(",
"opts",
"...",
")",
"\n",
"}"
] | // GetClusterConfig gets ClusterConfig from the backend. | [
"GetClusterConfig",
"gets",
"ClusterConfig",
"from",
"the",
"backend",
"."
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L284-L286 | train |
gravitational/teleport | lib/auth/auth.go | GetClusterName | func (a *AuthServer) GetClusterName(opts ...services.MarshalOption) (services.ClusterName, error) {
return a.GetCache().GetClusterName(opts...)
} | go | func (a *AuthServer) GetClusterName(opts ...services.MarshalOption) (services.ClusterName, error) {
return a.GetCache().GetClusterName(opts...)
} | [
"func",
"(",
"a",
"*",
"AuthServer",
")",
"GetClusterName",
"(",
"opts",
"...",
"services",
".",
"MarshalOption",
")",
"(",
"services",
".",
"ClusterName",
",",
"error",
")",
"{",
"return",
"a",
".",
"GetCache",
"(",
")",
".",
"GetClusterName",
"(",
"opts",
"...",
")",
"\n",
"}"
] | // GetClusterName returns the domain name that identifies this authority server.
// Also known as "cluster name" | [
"GetClusterName",
"returns",
"the",
"domain",
"name",
"that",
"identifies",
"this",
"authority",
"server",
".",
"Also",
"known",
"as",
"cluster",
"name"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L290-L292 | train |
gravitational/teleport | lib/auth/auth.go | GetDomainName | func (a *AuthServer) GetDomainName() (string, error) {
clusterName, err := a.GetClusterName()
if err != nil {
return "", trace.Wrap(err)
}
return clusterName.GetClusterName(), nil
} | go | func (a *AuthServer) GetDomainName() (string, error) {
clusterName, err := a.GetClusterName()
if err != nil {
return "", trace.Wrap(err)
}
return clusterName.GetClusterName(), nil
} | [
"func",
"(",
"a",
"*",
"AuthServer",
")",
"GetDomainName",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"clusterName",
",",
"err",
":=",
"a",
".",
"GetClusterName",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"clusterName",
".",
"GetClusterName",
"(",
")",
",",
"nil",
"\n",
"}"
] | // GetDomainName returns the domain name that identifies this authority server.
// Also known as "cluster name" | [
"GetDomainName",
"returns",
"the",
"domain",
"name",
"that",
"identifies",
"this",
"authority",
"server",
".",
"Also",
"known",
"as",
"cluster",
"name"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L296-L302 | train |
gravitational/teleport | lib/auth/auth.go | GenerateUserCerts | func (a *AuthServer) GenerateUserCerts(key []byte, username string, ttl time.Duration, compatibility string) ([]byte, []byte, error) {
user, err := a.Identity.GetUser(username)
if err != nil {
return nil, nil, trace.Wrap(err)
}
checker, err := services.FetchRoles(user.GetRoles(), a.Access, user.GetTraits())
if err != nil {
return nil, nil, trace.Wrap(err)
}
certs, err := a.generateUserCert(certRequest{
user: user,
roles: checker,
ttl: ttl,
compatibility: compatibility,
publicKey: key,
})
if err != nil {
return nil, nil, trace.Wrap(err)
}
return certs.ssh, certs.tls, nil
} | go | func (a *AuthServer) GenerateUserCerts(key []byte, username string, ttl time.Duration, compatibility string) ([]byte, []byte, error) {
user, err := a.Identity.GetUser(username)
if err != nil {
return nil, nil, trace.Wrap(err)
}
checker, err := services.FetchRoles(user.GetRoles(), a.Access, user.GetTraits())
if err != nil {
return nil, nil, trace.Wrap(err)
}
certs, err := a.generateUserCert(certRequest{
user: user,
roles: checker,
ttl: ttl,
compatibility: compatibility,
publicKey: key,
})
if err != nil {
return nil, nil, trace.Wrap(err)
}
return certs.ssh, certs.tls, nil
} | [
"func",
"(",
"a",
"*",
"AuthServer",
")",
"GenerateUserCerts",
"(",
"key",
"[",
"]",
"byte",
",",
"username",
"string",
",",
"ttl",
"time",
".",
"Duration",
",",
"compatibility",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"user",
",",
"err",
":=",
"a",
".",
"Identity",
".",
"GetUser",
"(",
"username",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"checker",
",",
"err",
":=",
"services",
".",
"FetchRoles",
"(",
"user",
".",
"GetRoles",
"(",
")",
",",
"a",
".",
"Access",
",",
"user",
".",
"GetTraits",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"certs",
",",
"err",
":=",
"a",
".",
"generateUserCert",
"(",
"certRequest",
"{",
"user",
":",
"user",
",",
"roles",
":",
"checker",
",",
"ttl",
":",
"ttl",
",",
"compatibility",
":",
"compatibility",
",",
"publicKey",
":",
"key",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"trace",
".",
"Wrap",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"certs",
".",
"ssh",
",",
"certs",
".",
"tls",
",",
"nil",
"\n",
"}"
] | // GenerateUserCerts is used to generate user certificate, used internally for tests | [
"GenerateUserCerts",
"is",
"used",
"to",
"generate",
"user",
"certificate",
"used",
"internally",
"for",
"tests"
] | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L407-L427 | train |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.