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/auth/helpers.go
CertPool
func (t *TestTLSServer) CertPool() (*x509.CertPool, error) { tlsConfig, err := t.Identity.TLSConfig(t.AuthServer.CipherSuites) if err != nil { return nil, trace.Wrap(err) } return tlsConfig.RootCAs, nil }
go
func (t *TestTLSServer) CertPool() (*x509.CertPool, error) { tlsConfig, err := t.Identity.TLSConfig(t.AuthServer.CipherSuites) if err != nil { return nil, trace.Wrap(err) } return tlsConfig.RootCAs, nil }
[ "func", "(", "t", "*", "TestTLSServer", ")", "CertPool", "(", ")", "(", "*", "x509", ".", "CertPool", ",", "error", ")", "{", "tlsConfig", ",", "err", ":=", "t", ".", "Identity", ".", "TLSConfig", "(", "t", ".", "AuthServer", ".", "CipherSuites", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "tlsConfig", ".", "RootCAs", ",", "nil", "\n", "}" ]
// CertPool returns cert pool that auth server represents
[ "CertPool", "returns", "cert", "pool", "that", "auth", "server", "represents" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/helpers.go#L528-L534
train
gravitational/teleport
lib/auth/helpers.go
ClientTLSConfig
func (t *TestTLSServer) ClientTLSConfig(identity TestIdentity) (*tls.Config, error) { tlsConfig, err := t.Identity.TLSConfig(t.AuthServer.CipherSuites) if err != nil { return nil, trace.Wrap(err) } if identity.I != nil { cert, err := t.AuthServer.NewCertificate(identity) if err != nil { return nil, trace.Wrap(err) } tlsConfig.Certificates = []tls.Certificate{*cert} } else { // this client is not authenticated, which means that auth // server should apply Nop builtin role tlsConfig.Certificates = nil } return tlsConfig, nil }
go
func (t *TestTLSServer) ClientTLSConfig(identity TestIdentity) (*tls.Config, error) { tlsConfig, err := t.Identity.TLSConfig(t.AuthServer.CipherSuites) if err != nil { return nil, trace.Wrap(err) } if identity.I != nil { cert, err := t.AuthServer.NewCertificate(identity) if err != nil { return nil, trace.Wrap(err) } tlsConfig.Certificates = []tls.Certificate{*cert} } else { // this client is not authenticated, which means that auth // server should apply Nop builtin role tlsConfig.Certificates = nil } return tlsConfig, nil }
[ "func", "(", "t", "*", "TestTLSServer", ")", "ClientTLSConfig", "(", "identity", "TestIdentity", ")", "(", "*", "tls", ".", "Config", ",", "error", ")", "{", "tlsConfig", ",", "err", ":=", "t", ".", "Identity", ".", "TLSConfig", "(", "t", ".", "AuthServer", ".", "CipherSuites", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "identity", ".", "I", "!=", "nil", "{", "cert", ",", "err", ":=", "t", ".", "AuthServer", ".", "NewCertificate", "(", "identity", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "tlsConfig", ".", "Certificates", "=", "[", "]", "tls", ".", "Certificate", "{", "*", "cert", "}", "\n", "}", "else", "{", "// this client is not authenticated, which means that auth", "// server should apply Nop builtin role", "tlsConfig", ".", "Certificates", "=", "nil", "\n", "}", "\n", "return", "tlsConfig", ",", "nil", "\n", "}" ]
// ClientTLSConfig returns client TLS config based on the identity
[ "ClientTLSConfig", "returns", "client", "TLS", "config", "based", "on", "the", "identity" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/helpers.go#L537-L554
train
gravitational/teleport
lib/auth/helpers.go
CloneClient
func (t *TestTLSServer) CloneClient(clt *Client) *Client { addr := []utils.NetAddr{{Addr: t.Addr().String(), AddrNetwork: t.Addr().Network()}} newClient, err := NewTLSClient(ClientConfig{Addrs: addr, TLS: clt.TLSConfig()}) if err != nil { panic(err) } return newClient }
go
func (t *TestTLSServer) CloneClient(clt *Client) *Client { addr := []utils.NetAddr{{Addr: t.Addr().String(), AddrNetwork: t.Addr().Network()}} newClient, err := NewTLSClient(ClientConfig{Addrs: addr, TLS: clt.TLSConfig()}) if err != nil { panic(err) } return newClient }
[ "func", "(", "t", "*", "TestTLSServer", ")", "CloneClient", "(", "clt", "*", "Client", ")", "*", "Client", "{", "addr", ":=", "[", "]", "utils", ".", "NetAddr", "{", "{", "Addr", ":", "t", ".", "Addr", "(", ")", ".", "String", "(", ")", ",", "AddrNetwork", ":", "t", ".", "Addr", "(", ")", ".", "Network", "(", ")", "}", "}", "\n", "newClient", ",", "err", ":=", "NewTLSClient", "(", "ClientConfig", "{", "Addrs", ":", "addr", ",", "TLS", ":", "clt", ".", "TLSConfig", "(", ")", "}", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "newClient", "\n", "}" ]
// CloneClient uses the same credentials as the passed client // but forces the client to be recreated
[ "CloneClient", "uses", "the", "same", "credentials", "as", "the", "passed", "client", "but", "forces", "the", "client", "to", "be", "recreated" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/helpers.go#L558-L565
train
gravitational/teleport
lib/auth/helpers.go
NewClient
func (t *TestTLSServer) NewClient(identity TestIdentity) (*Client, error) { tlsConfig, err := t.ClientTLSConfig(identity) if err != nil { return nil, trace.Wrap(err) } addrs := []utils.NetAddr{utils.FromAddr(t.Listener.Addr())} return NewTLSClient(ClientConfig{Addrs: addrs, TLS: tlsConfig}) }
go
func (t *TestTLSServer) NewClient(identity TestIdentity) (*Client, error) { tlsConfig, err := t.ClientTLSConfig(identity) if err != nil { return nil, trace.Wrap(err) } addrs := []utils.NetAddr{utils.FromAddr(t.Listener.Addr())} return NewTLSClient(ClientConfig{Addrs: addrs, TLS: tlsConfig}) }
[ "func", "(", "t", "*", "TestTLSServer", ")", "NewClient", "(", "identity", "TestIdentity", ")", "(", "*", "Client", ",", "error", ")", "{", "tlsConfig", ",", "err", ":=", "t", ".", "ClientTLSConfig", "(", "identity", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "addrs", ":=", "[", "]", "utils", ".", "NetAddr", "{", "utils", ".", "FromAddr", "(", "t", ".", "Listener", ".", "Addr", "(", ")", ")", "}", "\n", "return", "NewTLSClient", "(", "ClientConfig", "{", "Addrs", ":", "addrs", ",", "TLS", ":", "tlsConfig", "}", ")", "\n", "}" ]
// NewClient returns new client to test server authenticated with identity
[ "NewClient", "returns", "new", "client", "to", "test", "server", "authenticated", "with", "identity" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/helpers.go#L568-L575
train
gravitational/teleport
lib/auth/helpers.go
Start
func (t *TestTLSServer) Start() error { var err error if t.Listener == nil { t.Listener, err = net.Listen("tcp", "127.0.0.1:0") if err != nil { return trace.Wrap(err) } } go t.TLSServer.Serve(t.Listener) return nil }
go
func (t *TestTLSServer) Start() error { var err error if t.Listener == nil { t.Listener, err = net.Listen("tcp", "127.0.0.1:0") if err != nil { return trace.Wrap(err) } } go t.TLSServer.Serve(t.Listener) return nil }
[ "func", "(", "t", "*", "TestTLSServer", ")", "Start", "(", ")", "error", "{", "var", "err", "error", "\n", "if", "t", ".", "Listener", "==", "nil", "{", "t", ".", "Listener", ",", "err", "=", "net", ".", "Listen", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n", "go", "t", ".", "TLSServer", ".", "Serve", "(", "t", ".", "Listener", ")", "\n", "return", "nil", "\n", "}" ]
// Start starts TLS server on loopback address on the first lisenting socket
[ "Start", "starts", "TLS", "server", "on", "loopback", "address", "on", "the", "first", "lisenting", "socket" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/helpers.go#L583-L593
train
gravitational/teleport
lib/auth/helpers.go
Close
func (t *TestTLSServer) Close() error { err := t.TLSServer.Close() if t.Listener != nil { t.Listener.Close() } if t.AuthServer.Backend != nil { t.AuthServer.Backend.Close() } return err }
go
func (t *TestTLSServer) Close() error { err := t.TLSServer.Close() if t.Listener != nil { t.Listener.Close() } if t.AuthServer.Backend != nil { t.AuthServer.Backend.Close() } return err }
[ "func", "(", "t", "*", "TestTLSServer", ")", "Close", "(", ")", "error", "{", "err", ":=", "t", ".", "TLSServer", ".", "Close", "(", ")", "\n", "if", "t", ".", "Listener", "!=", "nil", "{", "t", ".", "Listener", ".", "Close", "(", ")", "\n", "}", "\n", "if", "t", ".", "AuthServer", ".", "Backend", "!=", "nil", "{", "t", ".", "AuthServer", ".", "Backend", ".", "Close", "(", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Close closes the listener and HTTP server
[ "Close", "closes", "the", "listener", "and", "HTTP", "server" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/helpers.go#L596-L605
train
gravitational/teleport
lib/auth/helpers.go
Stop
func (t *TestTLSServer) Stop() error { err := t.TLSServer.Close() if t.Listener != nil { t.Listener.Close() } return err }
go
func (t *TestTLSServer) Stop() error { err := t.TLSServer.Close() if t.Listener != nil { t.Listener.Close() } return err }
[ "func", "(", "t", "*", "TestTLSServer", ")", "Stop", "(", ")", "error", "{", "err", ":=", "t", ".", "TLSServer", ".", "Close", "(", ")", "\n", "if", "t", ".", "Listener", "!=", "nil", "{", "t", ".", "Listener", ".", "Close", "(", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Stop stops listening server, but does not close the auth backend
[ "Stop", "stops", "listening", "server", "but", "does", "not", "close", "the", "auth", "backend" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/helpers.go#L608-L614
train
gravitational/teleport
lib/auth/helpers.go
NewServerIdentity
func NewServerIdentity(clt *AuthServer, hostID string, role teleport.Role) (*Identity, error) { keys, err := clt.GenerateServerKeys(GenerateServerKeysRequest{ HostID: hostID, NodeName: hostID, Roles: teleport.Roles{teleport.RoleAuth}, }) if err != nil { return nil, trace.Wrap(err) } return ReadIdentityFromKeyPair(keys) }
go
func NewServerIdentity(clt *AuthServer, hostID string, role teleport.Role) (*Identity, error) { keys, err := clt.GenerateServerKeys(GenerateServerKeysRequest{ HostID: hostID, NodeName: hostID, Roles: teleport.Roles{teleport.RoleAuth}, }) if err != nil { return nil, trace.Wrap(err) } return ReadIdentityFromKeyPair(keys) }
[ "func", "NewServerIdentity", "(", "clt", "*", "AuthServer", ",", "hostID", "string", ",", "role", "teleport", ".", "Role", ")", "(", "*", "Identity", ",", "error", ")", "{", "keys", ",", "err", ":=", "clt", ".", "GenerateServerKeys", "(", "GenerateServerKeysRequest", "{", "HostID", ":", "hostID", ",", "NodeName", ":", "hostID", ",", "Roles", ":", "teleport", ".", "Roles", "{", "teleport", ".", "RoleAuth", "}", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "ReadIdentityFromKeyPair", "(", "keys", ")", "\n", "}" ]
// NewServerIdentity generates new server identity, used in tests
[ "NewServerIdentity", "generates", "new", "server", "identity", "used", "in", "tests" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/helpers.go#L617-L627
train
gravitational/teleport
lib/auth/helpers.go
CreateUserAndRole
func CreateUserAndRole(clt clt, username string, allowedLogins []string) (services.User, services.Role, error) { user, err := services.NewUser(username) if err != nil { return nil, nil, trace.Wrap(err) } role := services.RoleForUser(user) role.SetLogins(services.Allow, []string{user.GetName()}) err = clt.UpsertRole(role) if err != nil { return nil, nil, trace.Wrap(err) } user.AddRole(role.GetName()) err = clt.UpsertUser(user) if err != nil { return nil, nil, trace.Wrap(err) } return user, role, nil }
go
func CreateUserAndRole(clt clt, username string, allowedLogins []string) (services.User, services.Role, error) { user, err := services.NewUser(username) if err != nil { return nil, nil, trace.Wrap(err) } role := services.RoleForUser(user) role.SetLogins(services.Allow, []string{user.GetName()}) err = clt.UpsertRole(role) if err != nil { return nil, nil, trace.Wrap(err) } user.AddRole(role.GetName()) err = clt.UpsertUser(user) if err != nil { return nil, nil, trace.Wrap(err) } return user, role, nil }
[ "func", "CreateUserAndRole", "(", "clt", "clt", ",", "username", "string", ",", "allowedLogins", "[", "]", "string", ")", "(", "services", ".", "User", ",", "services", ".", "Role", ",", "error", ")", "{", "user", ",", "err", ":=", "services", ".", "NewUser", "(", "username", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "role", ":=", "services", ".", "RoleForUser", "(", "user", ")", "\n", "role", ".", "SetLogins", "(", "services", ".", "Allow", ",", "[", "]", "string", "{", "user", ".", "GetName", "(", ")", "}", ")", "\n", "err", "=", "clt", ".", "UpsertRole", "(", "role", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "user", ".", "AddRole", "(", "role", ".", "GetName", "(", ")", ")", "\n", "err", "=", "clt", ".", "UpsertUser", "(", "user", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "user", ",", "role", ",", "nil", "\n", "}" ]
// CreateUserAndRole creates user and role and assignes role to a user, used in tests
[ "CreateUserAndRole", "creates", "user", "and", "role", "and", "assignes", "role", "to", "a", "user", "used", "in", "tests" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/helpers.go#L637-L654
train
gravitational/teleport
lib/auth/helpers.go
CreateUserAndRoleWithoutRoles
func CreateUserAndRoleWithoutRoles(clt clt, username string, allowedLogins []string) (services.User, services.Role, error) { user, err := services.NewUser(username) if err != nil { return nil, nil, trace.Wrap(err) } role := services.RoleForUser(user) set := services.MakeRuleSet(role.GetRules(services.Allow)) delete(set, services.KindRole) role.SetRules(services.Allow, set.Slice()) role.SetLogins(services.Allow, []string{user.GetName()}) err = clt.UpsertRole(role) if err != nil { return nil, nil, trace.Wrap(err) } user.AddRole(role.GetName()) err = clt.UpsertUser(user) if err != nil { return nil, nil, trace.Wrap(err) } return user, role, nil }
go
func CreateUserAndRoleWithoutRoles(clt clt, username string, allowedLogins []string) (services.User, services.Role, error) { user, err := services.NewUser(username) if err != nil { return nil, nil, trace.Wrap(err) } role := services.RoleForUser(user) set := services.MakeRuleSet(role.GetRules(services.Allow)) delete(set, services.KindRole) role.SetRules(services.Allow, set.Slice()) role.SetLogins(services.Allow, []string{user.GetName()}) err = clt.UpsertRole(role) if err != nil { return nil, nil, trace.Wrap(err) } user.AddRole(role.GetName()) err = clt.UpsertUser(user) if err != nil { return nil, nil, trace.Wrap(err) } return user, role, nil }
[ "func", "CreateUserAndRoleWithoutRoles", "(", "clt", "clt", ",", "username", "string", ",", "allowedLogins", "[", "]", "string", ")", "(", "services", ".", "User", ",", "services", ".", "Role", ",", "error", ")", "{", "user", ",", "err", ":=", "services", ".", "NewUser", "(", "username", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "role", ":=", "services", ".", "RoleForUser", "(", "user", ")", "\n", "set", ":=", "services", ".", "MakeRuleSet", "(", "role", ".", "GetRules", "(", "services", ".", "Allow", ")", ")", "\n", "delete", "(", "set", ",", "services", ".", "KindRole", ")", "\n", "role", ".", "SetRules", "(", "services", ".", "Allow", ",", "set", ".", "Slice", "(", ")", ")", "\n", "role", ".", "SetLogins", "(", "services", ".", "Allow", ",", "[", "]", "string", "{", "user", ".", "GetName", "(", ")", "}", ")", "\n", "err", "=", "clt", ".", "UpsertRole", "(", "role", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "user", ".", "AddRole", "(", "role", ".", "GetName", "(", ")", ")", "\n", "err", "=", "clt", ".", "UpsertUser", "(", "user", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "return", "user", ",", "role", ",", "nil", "\n", "}" ]
// CreateUserAndRoleWithoutRoles creates user and role, but does not assign user to a role, used in tests
[ "CreateUserAndRoleWithoutRoles", "creates", "user", "and", "role", "but", "does", "not", "assign", "user", "to", "a", "role", "used", "in", "tests" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/helpers.go#L657-L680
train
gravitational/teleport
lib/events/uploader.go
CheckAndSetDefaults
func (cfg *UploaderConfig) CheckAndSetDefaults() error { if cfg.ServerID == "" { return trace.BadParameter("missing parameter ServerID") } if cfg.AuditLog == nil { return trace.BadParameter("missing parameter AuditLog") } if cfg.DataDir == "" { return trace.BadParameter("missing parameter DataDir") } if cfg.Namespace == "" { return trace.BadParameter("missing parameter Namespace") } if cfg.ConcurrentUploads <= 0 { cfg.ConcurrentUploads = defaults.UploaderConcurrentUploads } if cfg.ScanPeriod <= 0 { cfg.ScanPeriod = defaults.UploaderScanPeriod } if cfg.Context == nil { cfg.Context = context.TODO() } if cfg.Clock == nil { cfg.Clock = clockwork.NewRealClock() } return nil }
go
func (cfg *UploaderConfig) CheckAndSetDefaults() error { if cfg.ServerID == "" { return trace.BadParameter("missing parameter ServerID") } if cfg.AuditLog == nil { return trace.BadParameter("missing parameter AuditLog") } if cfg.DataDir == "" { return trace.BadParameter("missing parameter DataDir") } if cfg.Namespace == "" { return trace.BadParameter("missing parameter Namespace") } if cfg.ConcurrentUploads <= 0 { cfg.ConcurrentUploads = defaults.UploaderConcurrentUploads } if cfg.ScanPeriod <= 0 { cfg.ScanPeriod = defaults.UploaderScanPeriod } if cfg.Context == nil { cfg.Context = context.TODO() } if cfg.Clock == nil { cfg.Clock = clockwork.NewRealClock() } return nil }
[ "func", "(", "cfg", "*", "UploaderConfig", ")", "CheckAndSetDefaults", "(", ")", "error", "{", "if", "cfg", ".", "ServerID", "==", "\"", "\"", "{", "return", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cfg", ".", "AuditLog", "==", "nil", "{", "return", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cfg", ".", "DataDir", "==", "\"", "\"", "{", "return", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cfg", ".", "Namespace", "==", "\"", "\"", "{", "return", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cfg", ".", "ConcurrentUploads", "<=", "0", "{", "cfg", ".", "ConcurrentUploads", "=", "defaults", ".", "UploaderConcurrentUploads", "\n", "}", "\n", "if", "cfg", ".", "ScanPeriod", "<=", "0", "{", "cfg", ".", "ScanPeriod", "=", "defaults", ".", "UploaderScanPeriod", "\n", "}", "\n", "if", "cfg", ".", "Context", "==", "nil", "{", "cfg", ".", "Context", "=", "context", ".", "TODO", "(", ")", "\n", "}", "\n", "if", "cfg", ".", "Clock", "==", "nil", "{", "cfg", ".", "Clock", "=", "clockwork", ".", "NewRealClock", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CheckAndSetDefaults checks and sets default values of UploaderConfig
[ "CheckAndSetDefaults", "checks", "and", "sets", "default", "values", "of", "UploaderConfig" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/uploader.go#L80-L106
train
gravitational/teleport
lib/events/uploader.go
NewUploader
func NewUploader(cfg UploaderConfig) (*Uploader, error) { if err := cfg.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } ctx, cancel := context.WithCancel(cfg.Context) uploader := &Uploader{ UploaderConfig: cfg, Entry: log.WithFields(log.Fields{ trace.Component: teleport.ComponentAuditLog, }), cancel: cancel, ctx: ctx, semaphore: make(chan struct{}, cfg.ConcurrentUploads), scanDir: filepath.Join(cfg.DataDir, cfg.ServerID, SessionLogsDir, cfg.Namespace), } return uploader, nil }
go
func NewUploader(cfg UploaderConfig) (*Uploader, error) { if err := cfg.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } ctx, cancel := context.WithCancel(cfg.Context) uploader := &Uploader{ UploaderConfig: cfg, Entry: log.WithFields(log.Fields{ trace.Component: teleport.ComponentAuditLog, }), cancel: cancel, ctx: ctx, semaphore: make(chan struct{}, cfg.ConcurrentUploads), scanDir: filepath.Join(cfg.DataDir, cfg.ServerID, SessionLogsDir, cfg.Namespace), } return uploader, nil }
[ "func", "NewUploader", "(", "cfg", "UploaderConfig", ")", "(", "*", "Uploader", ",", "error", ")", "{", "if", "err", ":=", "cfg", ".", "CheckAndSetDefaults", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "ctx", ",", "cancel", ":=", "context", ".", "WithCancel", "(", "cfg", ".", "Context", ")", "\n", "uploader", ":=", "&", "Uploader", "{", "UploaderConfig", ":", "cfg", ",", "Entry", ":", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "trace", ".", "Component", ":", "teleport", ".", "ComponentAuditLog", ",", "}", ")", ",", "cancel", ":", "cancel", ",", "ctx", ":", "ctx", ",", "semaphore", ":", "make", "(", "chan", "struct", "{", "}", ",", "cfg", ".", "ConcurrentUploads", ")", ",", "scanDir", ":", "filepath", ".", "Join", "(", "cfg", ".", "DataDir", ",", "cfg", ".", "ServerID", ",", "SessionLogsDir", ",", "cfg", ".", "Namespace", ")", ",", "}", "\n", "return", "uploader", ",", "nil", "\n", "}" ]
// NewUploader creates new disk based session logger
[ "NewUploader", "creates", "new", "disk", "based", "session", "logger" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/uploader.go#L109-L126
train
gravitational/teleport
lib/events/uploader.go
Scan
func (u *Uploader) Scan() error { df, err := os.Open(u.scanDir) err = trace.ConvertSystemError(err) if err != nil { return trace.Wrap(err) } defer df.Close() entries, err := df.Readdir(-1) if err != nil { return trace.ConvertSystemError(err) } var count int for i := range entries { fi := entries[i] if fi.IsDir() { continue } if !strings.HasSuffix(fi.Name(), "completed") { continue } parts := strings.Split(fi.Name(), ".") if len(parts) < 2 { u.Debugf("Uploader, skipping unknown file: %v", fi.Name()) continue } sessionID := session.ID(parts[0]) lockFilePath := filepath.Join(u.scanDir, fi.Name()) if err := u.uploadFile(lockFilePath, sessionID); err != nil { if trace.IsCompareFailed(err) { u.Debugf("Uploader detected locked file %v, another process is uploading it.", lockFilePath) continue } return trace.Wrap(err) } count += 1 } return nil }
go
func (u *Uploader) Scan() error { df, err := os.Open(u.scanDir) err = trace.ConvertSystemError(err) if err != nil { return trace.Wrap(err) } defer df.Close() entries, err := df.Readdir(-1) if err != nil { return trace.ConvertSystemError(err) } var count int for i := range entries { fi := entries[i] if fi.IsDir() { continue } if !strings.HasSuffix(fi.Name(), "completed") { continue } parts := strings.Split(fi.Name(), ".") if len(parts) < 2 { u.Debugf("Uploader, skipping unknown file: %v", fi.Name()) continue } sessionID := session.ID(parts[0]) lockFilePath := filepath.Join(u.scanDir, fi.Name()) if err := u.uploadFile(lockFilePath, sessionID); err != nil { if trace.IsCompareFailed(err) { u.Debugf("Uploader detected locked file %v, another process is uploading it.", lockFilePath) continue } return trace.Wrap(err) } count += 1 } return nil }
[ "func", "(", "u", "*", "Uploader", ")", "Scan", "(", ")", "error", "{", "df", ",", "err", ":=", "os", ".", "Open", "(", "u", ".", "scanDir", ")", "\n", "err", "=", "trace", ".", "ConvertSystemError", "(", "err", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "defer", "df", ".", "Close", "(", ")", "\n", "entries", ",", "err", ":=", "df", ".", "Readdir", "(", "-", "1", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "ConvertSystemError", "(", "err", ")", "\n", "}", "\n", "var", "count", "int", "\n", "for", "i", ":=", "range", "entries", "{", "fi", ":=", "entries", "[", "i", "]", "\n", "if", "fi", ".", "IsDir", "(", ")", "{", "continue", "\n", "}", "\n", "if", "!", "strings", ".", "HasSuffix", "(", "fi", ".", "Name", "(", ")", ",", "\"", "\"", ")", "{", "continue", "\n", "}", "\n", "parts", ":=", "strings", ".", "Split", "(", "fi", ".", "Name", "(", ")", ",", "\"", "\"", ")", "\n", "if", "len", "(", "parts", ")", "<", "2", "{", "u", ".", "Debugf", "(", "\"", "\"", ",", "fi", ".", "Name", "(", ")", ")", "\n", "continue", "\n", "}", "\n", "sessionID", ":=", "session", ".", "ID", "(", "parts", "[", "0", "]", ")", "\n", "lockFilePath", ":=", "filepath", ".", "Join", "(", "u", ".", "scanDir", ",", "fi", ".", "Name", "(", ")", ")", "\n", "if", "err", ":=", "u", ".", "uploadFile", "(", "lockFilePath", ",", "sessionID", ")", ";", "err", "!=", "nil", "{", "if", "trace", ".", "IsCompareFailed", "(", "err", ")", "{", "u", ".", "Debugf", "(", "\"", "\"", ",", "lockFilePath", ")", "\n", "continue", "\n", "}", "\n", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "count", "+=", "1", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Scan scans the directory and uploads recordings
[ "Scan", "scans", "the", "directory", "and", "uploads", "recordings" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/uploader.go#L272-L309
train
gravitational/teleport
lib/client/api.go
MakeDefaultConfig
func MakeDefaultConfig() *Config { return &Config{ Stdout: os.Stdout, Stderr: os.Stderr, Stdin: os.Stdin, } }
go
func MakeDefaultConfig() *Config { return &Config{ Stdout: os.Stdout, Stderr: os.Stderr, Stdin: os.Stdin, } }
[ "func", "MakeDefaultConfig", "(", ")", "*", "Config", "{", "return", "&", "Config", "{", "Stdout", ":", "os", ".", "Stdout", ",", "Stderr", ":", "os", ".", "Stderr", ",", "Stdin", ":", "os", ".", "Stdin", ",", "}", "\n", "}" ]
// MakeDefaultConfig returns default client config
[ "MakeDefaultConfig", "returns", "default", "client", "config" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L255-L261
train
gravitational/teleport
lib/client/api.go
IsExpired
func (p *ProfileStatus) IsExpired(clock clockwork.Clock) bool { return p.ValidUntil.Sub(clock.Now()) <= 0 }
go
func (p *ProfileStatus) IsExpired(clock clockwork.Clock) bool { return p.ValidUntil.Sub(clock.Now()) <= 0 }
[ "func", "(", "p", "*", "ProfileStatus", ")", "IsExpired", "(", "clock", "clockwork", ".", "Clock", ")", "bool", "{", "return", "p", ".", "ValidUntil", ".", "Sub", "(", "clock", ".", "Now", "(", ")", ")", "<=", "0", "\n", "}" ]
// IsExpired returns true if profile is not expired yet
[ "IsExpired", "returns", "true", "if", "profile", "is", "not", "expired", "yet" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L289-L291
train
gravitational/teleport
lib/client/api.go
RetryWithRelogin
func RetryWithRelogin(ctx context.Context, tc *TeleportClient, fn func() error) error { err := fn() if err == nil { return nil } // Assume that failed handshake is a result of expired credentials, // retry the login procedure if !utils.IsHandshakeFailedError(err) && !utils.IsCertExpiredError(err) && !trace.IsBadParameter(err) && trace.IsTrustError(err) { return err } key, err := tc.Login(ctx, true) if err != nil { if trace.IsTrustError(err) { return trace.Wrap(err, "refusing to connect to untrusted proxy %v without --insecure flag\n", tc.Config.SSHProxyAddr) } return trace.Wrap(err) } // Save profile to record proxy credentials if err := tc.SaveProfile(key.ProxyHost, "", ProfileCreateNew|ProfileMakeCurrent); err != nil { log.Warningf("Failed to save profile: %v", err) return trace.Wrap(err) } // Override client's auth methods, current cluster and user name authMethod, err := key.AsAuthMethod() if err != nil { return trace.Wrap(err) } // After successful login we have local agent updated with latest // and greatest auth information, setup client to try only this new // method fetched from key, to isolate the retry tc.Config.AuthMethods = []ssh.AuthMethod{authMethod} return fn() }
go
func RetryWithRelogin(ctx context.Context, tc *TeleportClient, fn func() error) error { err := fn() if err == nil { return nil } // Assume that failed handshake is a result of expired credentials, // retry the login procedure if !utils.IsHandshakeFailedError(err) && !utils.IsCertExpiredError(err) && !trace.IsBadParameter(err) && trace.IsTrustError(err) { return err } key, err := tc.Login(ctx, true) if err != nil { if trace.IsTrustError(err) { return trace.Wrap(err, "refusing to connect to untrusted proxy %v without --insecure flag\n", tc.Config.SSHProxyAddr) } return trace.Wrap(err) } // Save profile to record proxy credentials if err := tc.SaveProfile(key.ProxyHost, "", ProfileCreateNew|ProfileMakeCurrent); err != nil { log.Warningf("Failed to save profile: %v", err) return trace.Wrap(err) } // Override client's auth methods, current cluster and user name authMethod, err := key.AsAuthMethod() if err != nil { return trace.Wrap(err) } // After successful login we have local agent updated with latest // and greatest auth information, setup client to try only this new // method fetched from key, to isolate the retry tc.Config.AuthMethods = []ssh.AuthMethod{authMethod} return fn() }
[ "func", "RetryWithRelogin", "(", "ctx", "context", ".", "Context", ",", "tc", "*", "TeleportClient", ",", "fn", "func", "(", ")", "error", ")", "error", "{", "err", ":=", "fn", "(", ")", "\n", "if", "err", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "// Assume that failed handshake is a result of expired credentials,", "// retry the login procedure", "if", "!", "utils", ".", "IsHandshakeFailedError", "(", "err", ")", "&&", "!", "utils", ".", "IsCertExpiredError", "(", "err", ")", "&&", "!", "trace", ".", "IsBadParameter", "(", "err", ")", "&&", "trace", ".", "IsTrustError", "(", "err", ")", "{", "return", "err", "\n", "}", "\n", "key", ",", "err", ":=", "tc", ".", "Login", "(", "ctx", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "if", "trace", ".", "IsTrustError", "(", "err", ")", "{", "return", "trace", ".", "Wrap", "(", "err", ",", "\"", "\\n", "\"", ",", "tc", ".", "Config", ".", "SSHProxyAddr", ")", "\n", "}", "\n", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "// Save profile to record proxy credentials", "if", "err", ":=", "tc", ".", "SaveProfile", "(", "key", ".", "ProxyHost", ",", "\"", "\"", ",", "ProfileCreateNew", "|", "ProfileMakeCurrent", ")", ";", "err", "!=", "nil", "{", "log", ".", "Warningf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "// Override client's auth methods, current cluster and user name", "authMethod", ",", "err", ":=", "key", ".", "AsAuthMethod", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "// After successful login we have local agent updated with latest", "// and greatest auth information, setup client to try only this new", "// method fetched from key, to isolate the retry", "tc", ".", "Config", ".", "AuthMethods", "=", "[", "]", "ssh", ".", "AuthMethod", "{", "authMethod", "}", "\n", "return", "fn", "(", ")", "\n", "}" ]
// RetryWithRelogin is a helper error handling method, // attempts to relogin and retry the function once
[ "RetryWithRelogin", "is", "a", "helper", "error", "handling", "method", "attempts", "to", "relogin", "and", "retry", "the", "function", "once" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L295-L327
train
gravitational/teleport
lib/client/api.go
fullProfileName
func fullProfileName(profileDir string, proxyHost string) (string, error) { var err error var profileName string // If no profile name was passed in, try and extract the active profile from // the ~/.tsh/profile symlink. If one was passed in, append .yaml to name. if proxyHost == "" { profileName, err = os.Readlink(filepath.Join(profileDir, "profile")) if err != nil { return "", trace.ConvertSystemError(err) } } else { profileName = proxyHost + ".yaml" } // Make sure the profile requested actually exists. _, err = os.Stat(filepath.Join(profileDir, profileName)) if err != nil { return "", trace.ConvertSystemError(err) } return profileName, nil }
go
func fullProfileName(profileDir string, proxyHost string) (string, error) { var err error var profileName string // If no profile name was passed in, try and extract the active profile from // the ~/.tsh/profile symlink. If one was passed in, append .yaml to name. if proxyHost == "" { profileName, err = os.Readlink(filepath.Join(profileDir, "profile")) if err != nil { return "", trace.ConvertSystemError(err) } } else { profileName = proxyHost + ".yaml" } // Make sure the profile requested actually exists. _, err = os.Stat(filepath.Join(profileDir, profileName)) if err != nil { return "", trace.ConvertSystemError(err) } return profileName, nil }
[ "func", "fullProfileName", "(", "profileDir", "string", ",", "proxyHost", "string", ")", "(", "string", ",", "error", ")", "{", "var", "err", "error", "\n", "var", "profileName", "string", "\n\n", "// If no profile name was passed in, try and extract the active profile from", "// the ~/.tsh/profile symlink. If one was passed in, append .yaml to name.", "if", "proxyHost", "==", "\"", "\"", "{", "profileName", ",", "err", "=", "os", ".", "Readlink", "(", "filepath", ".", "Join", "(", "profileDir", ",", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "trace", ".", "ConvertSystemError", "(", "err", ")", "\n", "}", "\n", "}", "else", "{", "profileName", "=", "proxyHost", "+", "\"", "\"", "\n", "}", "\n\n", "// Make sure the profile requested actually exists.", "_", ",", "err", "=", "os", ".", "Stat", "(", "filepath", ".", "Join", "(", "profileDir", ",", "profileName", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "trace", ".", "ConvertSystemError", "(", "err", ")", "\n", "}", "\n\n", "return", "profileName", ",", "nil", "\n", "}" ]
// fullProfileName takes a profile directory and the host the user is trying // to connect to and returns the name of the profile file.
[ "fullProfileName", "takes", "a", "profile", "directory", "and", "the", "host", "the", "user", "is", "trying", "to", "connect", "to", "and", "returns", "the", "name", "of", "the", "profile", "file", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L401-L423
train
gravitational/teleport
lib/client/api.go
Status
func Status(profileDir string, proxyHost string) (*ProfileStatus, []*ProfileStatus, error) { var err error var profile *ProfileStatus var others []*ProfileStatus // remove ports from proxy host, because profile name is stored // by host name if proxyHost != "" { proxyHost, err = utils.Host(proxyHost) if err != nil { return nil, nil, trace.Wrap(err) } } // Construct the full path to the profile requested and make sure it exists. profileDir = FullProfilePath(profileDir) stat, err := os.Stat(profileDir) if err != nil { return nil, nil, trace.Wrap(err) } if !stat.IsDir() { return nil, nil, trace.BadParameter("profile path not a directory") } // Construct the name of the profile requested. If an empty string was // passed in, the name of the active profile will be extracted from the // ~/.tsh/profile symlink. profileName, err := fullProfileName(profileDir, proxyHost) if err != nil { if trace.IsNotFound(err) { return nil, nil, trace.NotFound("not logged in") } return nil, nil, trace.Wrap(err) } // Read in the active profile first. If readProfile returns trace.NotFound, // that means the profile may have been corrupted (for example keys were // deleted but profile exists), treat this as the user not being logged in. profile, err = readProfile(profileDir, profileName) if err != nil { if !trace.IsNotFound(err) { return nil, nil, trace.Wrap(err) } // Make sure the profile is nil, which tsh uses to detect that no // active profile exists. profile = nil } // Next, get list of all other available profiles. Filter out logged in // profile if it exists and return a slice of *ProfileStatus. files, err := ioutil.ReadDir(profileDir) if err != nil { return nil, nil, trace.Wrap(err) } for _, file := range files { if file.IsDir() { continue } if file.Mode()&os.ModeSymlink != 0 { continue } if !strings.HasSuffix(file.Name(), ".yaml") { continue } if file.Name() == profileName { continue } ps, err := readProfile(profileDir, file.Name()) if err != nil { // parts of profile are missing? // status skips these files if trace.IsNotFound(err) { continue } return nil, nil, trace.Wrap(err) } others = append(others, ps) } return profile, others, nil }
go
func Status(profileDir string, proxyHost string) (*ProfileStatus, []*ProfileStatus, error) { var err error var profile *ProfileStatus var others []*ProfileStatus // remove ports from proxy host, because profile name is stored // by host name if proxyHost != "" { proxyHost, err = utils.Host(proxyHost) if err != nil { return nil, nil, trace.Wrap(err) } } // Construct the full path to the profile requested and make sure it exists. profileDir = FullProfilePath(profileDir) stat, err := os.Stat(profileDir) if err != nil { return nil, nil, trace.Wrap(err) } if !stat.IsDir() { return nil, nil, trace.BadParameter("profile path not a directory") } // Construct the name of the profile requested. If an empty string was // passed in, the name of the active profile will be extracted from the // ~/.tsh/profile symlink. profileName, err := fullProfileName(profileDir, proxyHost) if err != nil { if trace.IsNotFound(err) { return nil, nil, trace.NotFound("not logged in") } return nil, nil, trace.Wrap(err) } // Read in the active profile first. If readProfile returns trace.NotFound, // that means the profile may have been corrupted (for example keys were // deleted but profile exists), treat this as the user not being logged in. profile, err = readProfile(profileDir, profileName) if err != nil { if !trace.IsNotFound(err) { return nil, nil, trace.Wrap(err) } // Make sure the profile is nil, which tsh uses to detect that no // active profile exists. profile = nil } // Next, get list of all other available profiles. Filter out logged in // profile if it exists and return a slice of *ProfileStatus. files, err := ioutil.ReadDir(profileDir) if err != nil { return nil, nil, trace.Wrap(err) } for _, file := range files { if file.IsDir() { continue } if file.Mode()&os.ModeSymlink != 0 { continue } if !strings.HasSuffix(file.Name(), ".yaml") { continue } if file.Name() == profileName { continue } ps, err := readProfile(profileDir, file.Name()) if err != nil { // parts of profile are missing? // status skips these files if trace.IsNotFound(err) { continue } return nil, nil, trace.Wrap(err) } others = append(others, ps) } return profile, others, nil }
[ "func", "Status", "(", "profileDir", "string", ",", "proxyHost", "string", ")", "(", "*", "ProfileStatus", ",", "[", "]", "*", "ProfileStatus", ",", "error", ")", "{", "var", "err", "error", "\n", "var", "profile", "*", "ProfileStatus", "\n", "var", "others", "[", "]", "*", "ProfileStatus", "\n\n", "// remove ports from proxy host, because profile name is stored", "// by host name", "if", "proxyHost", "!=", "\"", "\"", "{", "proxyHost", ",", "err", "=", "utils", ".", "Host", "(", "proxyHost", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n\n", "// Construct the full path to the profile requested and make sure it exists.", "profileDir", "=", "FullProfilePath", "(", "profileDir", ")", "\n", "stat", ",", "err", ":=", "os", ".", "Stat", "(", "profileDir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "!", "stat", ".", "IsDir", "(", ")", "{", "return", "nil", ",", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Construct the name of the profile requested. If an empty string was", "// passed in, the name of the active profile will be extracted from the", "// ~/.tsh/profile symlink.", "profileName", ",", "err", ":=", "fullProfileName", "(", "profileDir", ",", "proxyHost", ")", "\n", "if", "err", "!=", "nil", "{", "if", "trace", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", ",", "nil", ",", "trace", ".", "NotFound", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", ",", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "// Read in the active profile first. If readProfile returns trace.NotFound,", "// that means the profile may have been corrupted (for example keys were", "// deleted but profile exists), treat this as the user not being logged in.", "profile", ",", "err", "=", "readProfile", "(", "profileDir", ",", "profileName", ")", "\n", "if", "err", "!=", "nil", "{", "if", "!", "trace", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", ",", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "// Make sure the profile is nil, which tsh uses to detect that no", "// active profile exists.", "profile", "=", "nil", "\n", "}", "\n\n", "// Next, get list of all other available profiles. Filter out logged in", "// profile if it exists and return a slice of *ProfileStatus.", "files", ",", "err", ":=", "ioutil", ".", "ReadDir", "(", "profileDir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "for", "_", ",", "file", ":=", "range", "files", "{", "if", "file", ".", "IsDir", "(", ")", "{", "continue", "\n", "}", "\n", "if", "file", ".", "Mode", "(", ")", "&", "os", ".", "ModeSymlink", "!=", "0", "{", "continue", "\n", "}", "\n", "if", "!", "strings", ".", "HasSuffix", "(", "file", ".", "Name", "(", ")", ",", "\"", "\"", ")", "{", "continue", "\n", "}", "\n", "if", "file", ".", "Name", "(", ")", "==", "profileName", "{", "continue", "\n", "}", "\n", "ps", ",", "err", ":=", "readProfile", "(", "profileDir", ",", "file", ".", "Name", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "// parts of profile are missing?", "// status skips these files", "if", "trace", ".", "IsNotFound", "(", "err", ")", "{", "continue", "\n", "}", "\n", "return", "nil", ",", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "others", "=", "append", "(", "others", ",", "ps", ")", "\n", "}", "\n\n", "return", "profile", ",", "others", ",", "nil", "\n", "}" ]
// Status returns the active profile as well as a list of available profiles.
[ "Status", "returns", "the", "active", "profile", "as", "well", "as", "a", "list", "of", "available", "profiles", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L426-L506
train
gravitational/teleport
lib/client/api.go
KubeProxyHostPort
func (c *Config) KubeProxyHostPort() (string, int) { if c.KubeProxyAddr != "" { addr, err := utils.ParseAddr(c.KubeProxyAddr) if err == nil { return addr.Host(), addr.Port(defaults.KubeProxyListenPort) } } webProxyHost, _ := c.WebProxyHostPort() return webProxyHost, defaults.KubeProxyListenPort }
go
func (c *Config) KubeProxyHostPort() (string, int) { if c.KubeProxyAddr != "" { addr, err := utils.ParseAddr(c.KubeProxyAddr) if err == nil { return addr.Host(), addr.Port(defaults.KubeProxyListenPort) } } webProxyHost, _ := c.WebProxyHostPort() return webProxyHost, defaults.KubeProxyListenPort }
[ "func", "(", "c", "*", "Config", ")", "KubeProxyHostPort", "(", ")", "(", "string", ",", "int", ")", "{", "if", "c", ".", "KubeProxyAddr", "!=", "\"", "\"", "{", "addr", ",", "err", ":=", "utils", ".", "ParseAddr", "(", "c", ".", "KubeProxyAddr", ")", "\n", "if", "err", "==", "nil", "{", "return", "addr", ".", "Host", "(", ")", ",", "addr", ".", "Port", "(", "defaults", ".", "KubeProxyListenPort", ")", "\n", "}", "\n", "}", "\n\n", "webProxyHost", ",", "_", ":=", "c", ".", "WebProxyHostPort", "(", ")", "\n", "return", "webProxyHost", ",", "defaults", ".", "KubeProxyListenPort", "\n", "}" ]
// KubeProxyHostPort returns the host and port of the Kubernetes proxy.
[ "KubeProxyHostPort", "returns", "the", "host", "and", "port", "of", "the", "Kubernetes", "proxy", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L656-L666
train
gravitational/teleport
lib/client/api.go
WebProxyHostPort
func (c *Config) WebProxyHostPort() (string, int) { if c.WebProxyAddr != "" { addr, err := utils.ParseAddr(c.WebProxyAddr) if err == nil { return addr.Host(), addr.Port(defaults.HTTPListenPort) } } webProxyHost, _ := c.WebProxyHostPort() return webProxyHost, defaults.HTTPListenPort }
go
func (c *Config) WebProxyHostPort() (string, int) { if c.WebProxyAddr != "" { addr, err := utils.ParseAddr(c.WebProxyAddr) if err == nil { return addr.Host(), addr.Port(defaults.HTTPListenPort) } } webProxyHost, _ := c.WebProxyHostPort() return webProxyHost, defaults.HTTPListenPort }
[ "func", "(", "c", "*", "Config", ")", "WebProxyHostPort", "(", ")", "(", "string", ",", "int", ")", "{", "if", "c", ".", "WebProxyAddr", "!=", "\"", "\"", "{", "addr", ",", "err", ":=", "utils", ".", "ParseAddr", "(", "c", ".", "WebProxyAddr", ")", "\n", "if", "err", "==", "nil", "{", "return", "addr", ".", "Host", "(", ")", ",", "addr", ".", "Port", "(", "defaults", ".", "HTTPListenPort", ")", "\n", "}", "\n", "}", "\n\n", "webProxyHost", ",", "_", ":=", "c", ".", "WebProxyHostPort", "(", ")", "\n", "return", "webProxyHost", ",", "defaults", ".", "HTTPListenPort", "\n", "}" ]
// WebProxyHostPort returns the host and port of the web proxy.
[ "WebProxyHostPort", "returns", "the", "host", "and", "port", "of", "the", "web", "proxy", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L669-L679
train
gravitational/teleport
lib/client/api.go
SSHProxyHostPort
func (c *Config) SSHProxyHostPort() (string, int) { if c.SSHProxyAddr != "" { addr, err := utils.ParseAddr(c.SSHProxyAddr) if err == nil { return addr.Host(), addr.Port(defaults.SSHProxyListenPort) } } webProxyHost, _ := c.WebProxyHostPort() return webProxyHost, defaults.SSHProxyListenPort }
go
func (c *Config) SSHProxyHostPort() (string, int) { if c.SSHProxyAddr != "" { addr, err := utils.ParseAddr(c.SSHProxyAddr) if err == nil { return addr.Host(), addr.Port(defaults.SSHProxyListenPort) } } webProxyHost, _ := c.WebProxyHostPort() return webProxyHost, defaults.SSHProxyListenPort }
[ "func", "(", "c", "*", "Config", ")", "SSHProxyHostPort", "(", ")", "(", "string", ",", "int", ")", "{", "if", "c", ".", "SSHProxyAddr", "!=", "\"", "\"", "{", "addr", ",", "err", ":=", "utils", ".", "ParseAddr", "(", "c", ".", "SSHProxyAddr", ")", "\n", "if", "err", "==", "nil", "{", "return", "addr", ".", "Host", "(", ")", ",", "addr", ".", "Port", "(", "defaults", ".", "SSHProxyListenPort", ")", "\n", "}", "\n", "}", "\n\n", "webProxyHost", ",", "_", ":=", "c", ".", "WebProxyHostPort", "(", ")", "\n", "return", "webProxyHost", ",", "defaults", ".", "SSHProxyListenPort", "\n", "}" ]
// SSHProxyHostPort returns the host and port of the SSH proxy.
[ "SSHProxyHostPort", "returns", "the", "host", "and", "port", "of", "the", "SSH", "proxy", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L682-L692
train
gravitational/teleport
lib/client/api.go
NewClient
func NewClient(c *Config) (tc *TeleportClient, err error) { // validate configuration if c.Username == "" { c.Username, err = Username() if err != nil { return nil, trace.Wrap(err) } log.Infof("No teleport login given. defaulting to %s", c.Username) } if c.WebProxyAddr == "" { return nil, trace.BadParameter("No proxy address specified, missed --proxy flag?") } if c.HostLogin == "" { c.HostLogin, err = Username() if err != nil { return nil, trace.Wrap(err) } log.Infof("no host login given. defaulting to %s", c.HostLogin) } if c.KeyTTL == 0 { c.KeyTTL = defaults.CertDuration } c.Namespace = services.ProcessNamespace(c.Namespace) tc = &TeleportClient{Config: *c} if tc.Stdout == nil { tc.Stdout = os.Stdout } if tc.Stderr == nil { tc.Stderr = os.Stderr } if tc.Stdin == nil { tc.Stdin = os.Stdin } // Create a buffered channel to hold events that occurred during this session. // This channel must be buffered because the SSH connection directly feeds // into it. Delays in pulling messages off the global SSH request channel // could lead to the connection hanging. tc.eventsCh = make(chan events.EventFields, 1024) // Create a client that can be used for the initial fetch of credentials. tc.credClient, err = NewCredentialsClient( c.WebProxyAddr, c.InsecureSkipVerify, loopbackPool(c.WebProxyAddr)) if err != nil { return nil, trace.Wrap(err) } // sometimes we need to use external auth without using local auth // methods, e.g. in automation daemons if c.SkipLocalAuth { if len(c.AuthMethods) == 0 { return nil, trace.BadParameter("SkipLocalAuth is true but no AuthMethods provided") } // if the client was passed an agent in the configuration and skip local auth, use // the passed in agent. if c.Agent != nil { tc.localAgent = &LocalKeyAgent{Agent: c.Agent} } } else { // initialize the local agent (auth agent which uses local SSH keys signed by the CA): webProxyHost, _ := tc.WebProxyHostPort() tc.localAgent, err = NewLocalAgent(c.KeysDir, webProxyHost, c.Username) if err != nil { return nil, trace.Wrap(err) } if tc.HostKeyCallback == nil { tc.HostKeyCallback = tc.localAgent.CheckHostSignature } } return tc, nil }
go
func NewClient(c *Config) (tc *TeleportClient, err error) { // validate configuration if c.Username == "" { c.Username, err = Username() if err != nil { return nil, trace.Wrap(err) } log.Infof("No teleport login given. defaulting to %s", c.Username) } if c.WebProxyAddr == "" { return nil, trace.BadParameter("No proxy address specified, missed --proxy flag?") } if c.HostLogin == "" { c.HostLogin, err = Username() if err != nil { return nil, trace.Wrap(err) } log.Infof("no host login given. defaulting to %s", c.HostLogin) } if c.KeyTTL == 0 { c.KeyTTL = defaults.CertDuration } c.Namespace = services.ProcessNamespace(c.Namespace) tc = &TeleportClient{Config: *c} if tc.Stdout == nil { tc.Stdout = os.Stdout } if tc.Stderr == nil { tc.Stderr = os.Stderr } if tc.Stdin == nil { tc.Stdin = os.Stdin } // Create a buffered channel to hold events that occurred during this session. // This channel must be buffered because the SSH connection directly feeds // into it. Delays in pulling messages off the global SSH request channel // could lead to the connection hanging. tc.eventsCh = make(chan events.EventFields, 1024) // Create a client that can be used for the initial fetch of credentials. tc.credClient, err = NewCredentialsClient( c.WebProxyAddr, c.InsecureSkipVerify, loopbackPool(c.WebProxyAddr)) if err != nil { return nil, trace.Wrap(err) } // sometimes we need to use external auth without using local auth // methods, e.g. in automation daemons if c.SkipLocalAuth { if len(c.AuthMethods) == 0 { return nil, trace.BadParameter("SkipLocalAuth is true but no AuthMethods provided") } // if the client was passed an agent in the configuration and skip local auth, use // the passed in agent. if c.Agent != nil { tc.localAgent = &LocalKeyAgent{Agent: c.Agent} } } else { // initialize the local agent (auth agent which uses local SSH keys signed by the CA): webProxyHost, _ := tc.WebProxyHostPort() tc.localAgent, err = NewLocalAgent(c.KeysDir, webProxyHost, c.Username) if err != nil { return nil, trace.Wrap(err) } if tc.HostKeyCallback == nil { tc.HostKeyCallback = tc.localAgent.CheckHostSignature } } return tc, nil }
[ "func", "NewClient", "(", "c", "*", "Config", ")", "(", "tc", "*", "TeleportClient", ",", "err", "error", ")", "{", "// validate configuration", "if", "c", ".", "Username", "==", "\"", "\"", "{", "c", ".", "Username", ",", "err", "=", "Username", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "c", ".", "Username", ")", "\n", "}", "\n", "if", "c", ".", "WebProxyAddr", "==", "\"", "\"", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "c", ".", "HostLogin", "==", "\"", "\"", "{", "c", ".", "HostLogin", ",", "err", "=", "Username", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "c", ".", "HostLogin", ")", "\n", "}", "\n", "if", "c", ".", "KeyTTL", "==", "0", "{", "c", ".", "KeyTTL", "=", "defaults", ".", "CertDuration", "\n", "}", "\n", "c", ".", "Namespace", "=", "services", ".", "ProcessNamespace", "(", "c", ".", "Namespace", ")", "\n\n", "tc", "=", "&", "TeleportClient", "{", "Config", ":", "*", "c", "}", "\n\n", "if", "tc", ".", "Stdout", "==", "nil", "{", "tc", ".", "Stdout", "=", "os", ".", "Stdout", "\n", "}", "\n", "if", "tc", ".", "Stderr", "==", "nil", "{", "tc", ".", "Stderr", "=", "os", ".", "Stderr", "\n", "}", "\n", "if", "tc", ".", "Stdin", "==", "nil", "{", "tc", ".", "Stdin", "=", "os", ".", "Stdin", "\n", "}", "\n\n", "// Create a buffered channel to hold events that occurred during this session.", "// This channel must be buffered because the SSH connection directly feeds", "// into it. Delays in pulling messages off the global SSH request channel", "// could lead to the connection hanging.", "tc", ".", "eventsCh", "=", "make", "(", "chan", "events", ".", "EventFields", ",", "1024", ")", "\n\n", "// Create a client that can be used for the initial fetch of credentials.", "tc", ".", "credClient", ",", "err", "=", "NewCredentialsClient", "(", "c", ".", "WebProxyAddr", ",", "c", ".", "InsecureSkipVerify", ",", "loopbackPool", "(", "c", ".", "WebProxyAddr", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "// sometimes we need to use external auth without using local auth", "// methods, e.g. in automation daemons", "if", "c", ".", "SkipLocalAuth", "{", "if", "len", "(", "c", ".", "AuthMethods", ")", "==", "0", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "// if the client was passed an agent in the configuration and skip local auth, use", "// the passed in agent.", "if", "c", ".", "Agent", "!=", "nil", "{", "tc", ".", "localAgent", "=", "&", "LocalKeyAgent", "{", "Agent", ":", "c", ".", "Agent", "}", "\n", "}", "\n", "}", "else", "{", "// initialize the local agent (auth agent which uses local SSH keys signed by the CA):", "webProxyHost", ",", "_", ":=", "tc", ".", "WebProxyHostPort", "(", ")", "\n", "tc", ".", "localAgent", ",", "err", "=", "NewLocalAgent", "(", "c", ".", "KeysDir", ",", "webProxyHost", ",", "c", ".", "Username", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "tc", ".", "HostKeyCallback", "==", "nil", "{", "tc", ".", "HostKeyCallback", "=", "tc", ".", "localAgent", ".", "CheckHostSignature", "\n", "}", "\n", "}", "\n\n", "return", "tc", ",", "nil", "\n", "}" ]
// NewClient creates a TeleportClient object and fully configures it
[ "NewClient", "creates", "a", "TeleportClient", "object", "and", "fully", "configures", "it" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L735-L810
train
gravitational/teleport
lib/client/api.go
accessPoint
func (tc *TeleportClient) accessPoint(clt auth.AccessPoint, proxyHostPort string, clusterName string) (auth.AccessPoint, error) { // If no caching policy was set or on Windows (where Teleport does not // support file locking at the moment), return direct access to the access // point. if tc.CachePolicy == nil || runtime.GOOS == teleport.WindowsOS { log.Debugf("not using caching access point") return clt, nil } return clt, nil }
go
func (tc *TeleportClient) accessPoint(clt auth.AccessPoint, proxyHostPort string, clusterName string) (auth.AccessPoint, error) { // If no caching policy was set or on Windows (where Teleport does not // support file locking at the moment), return direct access to the access // point. if tc.CachePolicy == nil || runtime.GOOS == teleport.WindowsOS { log.Debugf("not using caching access point") return clt, nil } return clt, nil }
[ "func", "(", "tc", "*", "TeleportClient", ")", "accessPoint", "(", "clt", "auth", ".", "AccessPoint", ",", "proxyHostPort", "string", ",", "clusterName", "string", ")", "(", "auth", ".", "AccessPoint", ",", "error", ")", "{", "// If no caching policy was set or on Windows (where Teleport does not", "// support file locking at the moment), return direct access to the access", "// point.", "if", "tc", ".", "CachePolicy", "==", "nil", "||", "runtime", ".", "GOOS", "==", "teleport", ".", "WindowsOS", "{", "log", ".", "Debugf", "(", "\"", "\"", ")", "\n", "return", "clt", ",", "nil", "\n", "}", "\n", "return", "clt", ",", "nil", "\n", "}" ]
// accessPoint returns access point based on the cache policy
[ "accessPoint", "returns", "access", "point", "based", "on", "the", "cache", "policy" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L813-L822
train
gravitational/teleport
lib/client/api.go
getTargetNodes
func (tc *TeleportClient) getTargetNodes(ctx context.Context, proxy *ProxyClient) ([]string, error) { var ( err error nodes []services.Server retval = make([]string, 0) ) if tc.Labels != nil && len(tc.Labels) > 0 { nodes, err = proxy.FindServersByLabels(ctx, tc.Namespace, tc.Labels) if err != nil { return nil, trace.Wrap(err) } for i := 0; i < len(nodes); i++ { retval = append(retval, nodes[i].GetAddr()) } } if len(nodes) == 0 { retval = append(retval, net.JoinHostPort(tc.Host, strconv.Itoa(tc.HostPort))) } return retval, nil }
go
func (tc *TeleportClient) getTargetNodes(ctx context.Context, proxy *ProxyClient) ([]string, error) { var ( err error nodes []services.Server retval = make([]string, 0) ) if tc.Labels != nil && len(tc.Labels) > 0 { nodes, err = proxy.FindServersByLabels(ctx, tc.Namespace, tc.Labels) if err != nil { return nil, trace.Wrap(err) } for i := 0; i < len(nodes); i++ { retval = append(retval, nodes[i].GetAddr()) } } if len(nodes) == 0 { retval = append(retval, net.JoinHostPort(tc.Host, strconv.Itoa(tc.HostPort))) } return retval, nil }
[ "func", "(", "tc", "*", "TeleportClient", ")", "getTargetNodes", "(", "ctx", "context", ".", "Context", ",", "proxy", "*", "ProxyClient", ")", "(", "[", "]", "string", ",", "error", ")", "{", "var", "(", "err", "error", "\n", "nodes", "[", "]", "services", ".", "Server", "\n", "retval", "=", "make", "(", "[", "]", "string", ",", "0", ")", "\n", ")", "\n", "if", "tc", ".", "Labels", "!=", "nil", "&&", "len", "(", "tc", ".", "Labels", ")", ">", "0", "{", "nodes", ",", "err", "=", "proxy", ".", "FindServersByLabels", "(", "ctx", ",", "tc", ".", "Namespace", ",", "tc", ".", "Labels", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "nodes", ")", ";", "i", "++", "{", "retval", "=", "append", "(", "retval", ",", "nodes", "[", "i", "]", ".", "GetAddr", "(", ")", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "nodes", ")", "==", "0", "{", "retval", "=", "append", "(", "retval", ",", "net", ".", "JoinHostPort", "(", "tc", ".", "Host", ",", "strconv", ".", "Itoa", "(", "tc", ".", "HostPort", ")", ")", ")", "\n", "}", "\n", "return", "retval", ",", "nil", "\n", "}" ]
// getTargetNodes returns a list of node addresses this SSH command needs to // operate on.
[ "getTargetNodes", "returns", "a", "list", "of", "node", "addresses", "this", "SSH", "command", "needs", "to", "operate", "on", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L830-L849
train
gravitational/teleport
lib/client/api.go
Play
func (tc *TeleportClient) Play(ctx context.Context, namespace, sessionId string) (err error) { if namespace == "" { return trace.BadParameter(auth.MissingNamespaceError) } sid, err := session.ParseID(sessionId) if err != nil { return fmt.Errorf("'%v' is not a valid session ID (must be GUID)", sid) } // connect to the auth server (site) who made the recording proxyClient, err := tc.ConnectToProxy(ctx) if err != nil { return trace.Wrap(err) } site, err := proxyClient.ConnectToCurrentCluster(ctx, false) if err != nil { return trace.Wrap(err) } // request events for that session (to get timing data) sessionEvents, err := site.GetSessionEvents(namespace, *sid, 0, true) if err != nil { return trace.Wrap(err) } // read the stream into a buffer: var stream []byte for err == nil { tmp, err := site.GetSessionChunk(namespace, *sid, len(stream), events.MaxChunkBytes) if err != nil { return trace.Wrap(err) } if len(tmp) == 0 { err = io.EOF break } stream = append(stream, tmp...) } // configure terminal for direct unbuffered echo-less input: if term.IsTerminal(0) { state, err := term.SetRawTerminal(0) if err != nil { return nil } defer term.RestoreTerminal(0, state) } player := newSessionPlayer(sessionEvents, stream) // keys: const ( keyCtrlC = 3 keyCtrlD = 4 keySpace = 32 keyLeft = 68 keyRight = 67 keyUp = 65 keyDown = 66 ) // playback control goroutine go func() { defer player.Stop() key := make([]byte, 1) for { _, err = os.Stdin.Read(key) if err != nil { return } switch key[0] { // Ctrl+C or Ctrl+D case keyCtrlC, keyCtrlD: return // Space key case keySpace: player.TogglePause() // <- arrow case keyLeft, keyDown: player.Rewind() // -> arrow case keyRight, keyUp: player.Forward() } } }() // player starts playing in its own goroutine player.Play() // wait for keypresses loop to end <-player.stopC fmt.Println("\n\nend of session playback") return trace.Wrap(err) }
go
func (tc *TeleportClient) Play(ctx context.Context, namespace, sessionId string) (err error) { if namespace == "" { return trace.BadParameter(auth.MissingNamespaceError) } sid, err := session.ParseID(sessionId) if err != nil { return fmt.Errorf("'%v' is not a valid session ID (must be GUID)", sid) } // connect to the auth server (site) who made the recording proxyClient, err := tc.ConnectToProxy(ctx) if err != nil { return trace.Wrap(err) } site, err := proxyClient.ConnectToCurrentCluster(ctx, false) if err != nil { return trace.Wrap(err) } // request events for that session (to get timing data) sessionEvents, err := site.GetSessionEvents(namespace, *sid, 0, true) if err != nil { return trace.Wrap(err) } // read the stream into a buffer: var stream []byte for err == nil { tmp, err := site.GetSessionChunk(namespace, *sid, len(stream), events.MaxChunkBytes) if err != nil { return trace.Wrap(err) } if len(tmp) == 0 { err = io.EOF break } stream = append(stream, tmp...) } // configure terminal for direct unbuffered echo-less input: if term.IsTerminal(0) { state, err := term.SetRawTerminal(0) if err != nil { return nil } defer term.RestoreTerminal(0, state) } player := newSessionPlayer(sessionEvents, stream) // keys: const ( keyCtrlC = 3 keyCtrlD = 4 keySpace = 32 keyLeft = 68 keyRight = 67 keyUp = 65 keyDown = 66 ) // playback control goroutine go func() { defer player.Stop() key := make([]byte, 1) for { _, err = os.Stdin.Read(key) if err != nil { return } switch key[0] { // Ctrl+C or Ctrl+D case keyCtrlC, keyCtrlD: return // Space key case keySpace: player.TogglePause() // <- arrow case keyLeft, keyDown: player.Rewind() // -> arrow case keyRight, keyUp: player.Forward() } } }() // player starts playing in its own goroutine player.Play() // wait for keypresses loop to end <-player.stopC fmt.Println("\n\nend of session playback") return trace.Wrap(err) }
[ "func", "(", "tc", "*", "TeleportClient", ")", "Play", "(", "ctx", "context", ".", "Context", ",", "namespace", ",", "sessionId", "string", ")", "(", "err", "error", ")", "{", "if", "namespace", "==", "\"", "\"", "{", "return", "trace", ".", "BadParameter", "(", "auth", ".", "MissingNamespaceError", ")", "\n", "}", "\n", "sid", ",", "err", ":=", "session", ".", "ParseID", "(", "sessionId", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "sid", ")", "\n", "}", "\n", "// connect to the auth server (site) who made the recording", "proxyClient", ",", "err", ":=", "tc", ".", "ConnectToProxy", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "site", ",", "err", ":=", "proxyClient", ".", "ConnectToCurrentCluster", "(", "ctx", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "// request events for that session (to get timing data)", "sessionEvents", ",", "err", ":=", "site", ".", "GetSessionEvents", "(", "namespace", ",", "*", "sid", ",", "0", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "// read the stream into a buffer:", "var", "stream", "[", "]", "byte", "\n", "for", "err", "==", "nil", "{", "tmp", ",", "err", ":=", "site", ".", "GetSessionChunk", "(", "namespace", ",", "*", "sid", ",", "len", "(", "stream", ")", ",", "events", ".", "MaxChunkBytes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "len", "(", "tmp", ")", "==", "0", "{", "err", "=", "io", ".", "EOF", "\n", "break", "\n", "}", "\n", "stream", "=", "append", "(", "stream", ",", "tmp", "...", ")", "\n", "}", "\n\n", "// configure terminal for direct unbuffered echo-less input:", "if", "term", ".", "IsTerminal", "(", "0", ")", "{", "state", ",", "err", ":=", "term", ".", "SetRawTerminal", "(", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n", "defer", "term", ".", "RestoreTerminal", "(", "0", ",", "state", ")", "\n", "}", "\n", "player", ":=", "newSessionPlayer", "(", "sessionEvents", ",", "stream", ")", "\n", "// keys:", "const", "(", "keyCtrlC", "=", "3", "\n", "keyCtrlD", "=", "4", "\n", "keySpace", "=", "32", "\n", "keyLeft", "=", "68", "\n", "keyRight", "=", "67", "\n", "keyUp", "=", "65", "\n", "keyDown", "=", "66", "\n", ")", "\n", "// playback control goroutine", "go", "func", "(", ")", "{", "defer", "player", ".", "Stop", "(", ")", "\n", "key", ":=", "make", "(", "[", "]", "byte", ",", "1", ")", "\n", "for", "{", "_", ",", "err", "=", "os", ".", "Stdin", ".", "Read", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "switch", "key", "[", "0", "]", "{", "// Ctrl+C or Ctrl+D", "case", "keyCtrlC", ",", "keyCtrlD", ":", "return", "\n", "// Space key", "case", "keySpace", ":", "player", ".", "TogglePause", "(", ")", "\n", "// <- arrow", "case", "keyLeft", ",", "keyDown", ":", "player", ".", "Rewind", "(", ")", "\n", "// -> arrow", "case", "keyRight", ",", "keyUp", ":", "player", ".", "Forward", "(", ")", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n\n", "// player starts playing in its own goroutine", "player", ".", "Play", "(", ")", "\n\n", "// wait for keypresses loop to end", "<-", "player", ".", "stopC", "\n", "fmt", ".", "Println", "(", "\"", "\\n", "\\n", "\"", ")", "\n", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}" ]
// Play replays the recorded session
[ "Play", "replays", "the", "recorded", "session" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L1019-L1108
train
gravitational/teleport
lib/client/api.go
ExecuteSCP
func (tc *TeleportClient) ExecuteSCP(ctx context.Context, cmd scp.Command) (err error) { // connect to proxy first: if !tc.Config.ProxySpecified() { return trace.BadParameter("proxy server is not specified") } proxyClient, err := tc.ConnectToProxy(ctx) if err != nil { return trace.Wrap(err) } defer proxyClient.Close() clusterInfo, err := proxyClient.currentCluster() if err != nil { return trace.Wrap(err) } // which nodes are we executing this commands on? nodeAddrs, err := tc.getTargetNodes(ctx, proxyClient) if err != nil { return trace.Wrap(err) } if len(nodeAddrs) == 0 { return trace.BadParameter("no target host specified") } nodeClient, err := proxyClient.ConnectToNode( ctx, nodeAddrs[0]+"@"+tc.Namespace+"@"+clusterInfo.Name, tc.Config.HostLogin, false) if err != nil { tc.ExitStatus = 1 return trace.Wrap(err) } err = nodeClient.ExecuteSCP(cmd) if err != nil { // converts SSH error code to tc.ExitStatus exitError, _ := trace.Unwrap(err).(*ssh.ExitError) if exitError != nil { tc.ExitStatus = exitError.ExitStatus() } return err } return nil }
go
func (tc *TeleportClient) ExecuteSCP(ctx context.Context, cmd scp.Command) (err error) { // connect to proxy first: if !tc.Config.ProxySpecified() { return trace.BadParameter("proxy server is not specified") } proxyClient, err := tc.ConnectToProxy(ctx) if err != nil { return trace.Wrap(err) } defer proxyClient.Close() clusterInfo, err := proxyClient.currentCluster() if err != nil { return trace.Wrap(err) } // which nodes are we executing this commands on? nodeAddrs, err := tc.getTargetNodes(ctx, proxyClient) if err != nil { return trace.Wrap(err) } if len(nodeAddrs) == 0 { return trace.BadParameter("no target host specified") } nodeClient, err := proxyClient.ConnectToNode( ctx, nodeAddrs[0]+"@"+tc.Namespace+"@"+clusterInfo.Name, tc.Config.HostLogin, false) if err != nil { tc.ExitStatus = 1 return trace.Wrap(err) } err = nodeClient.ExecuteSCP(cmd) if err != nil { // converts SSH error code to tc.ExitStatus exitError, _ := trace.Unwrap(err).(*ssh.ExitError) if exitError != nil { tc.ExitStatus = exitError.ExitStatus() } return err } return nil }
[ "func", "(", "tc", "*", "TeleportClient", ")", "ExecuteSCP", "(", "ctx", "context", ".", "Context", ",", "cmd", "scp", ".", "Command", ")", "(", "err", "error", ")", "{", "// connect to proxy first:", "if", "!", "tc", ".", "Config", ".", "ProxySpecified", "(", ")", "{", "return", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n\n", "proxyClient", ",", "err", ":=", "tc", ".", "ConnectToProxy", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "defer", "proxyClient", ".", "Close", "(", ")", "\n\n", "clusterInfo", ",", "err", ":=", "proxyClient", ".", "currentCluster", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "// which nodes are we executing this commands on?", "nodeAddrs", ",", "err", ":=", "tc", ".", "getTargetNodes", "(", "ctx", ",", "proxyClient", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "len", "(", "nodeAddrs", ")", "==", "0", "{", "return", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n\n", "nodeClient", ",", "err", ":=", "proxyClient", ".", "ConnectToNode", "(", "ctx", ",", "nodeAddrs", "[", "0", "]", "+", "\"", "\"", "+", "tc", ".", "Namespace", "+", "\"", "\"", "+", "clusterInfo", ".", "Name", ",", "tc", ".", "Config", ".", "HostLogin", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "tc", ".", "ExitStatus", "=", "1", "\n", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "err", "=", "nodeClient", ".", "ExecuteSCP", "(", "cmd", ")", "\n", "if", "err", "!=", "nil", "{", "// converts SSH error code to tc.ExitStatus", "exitError", ",", "_", ":=", "trace", ".", "Unwrap", "(", "err", ")", ".", "(", "*", "ssh", ".", "ExitError", ")", "\n", "if", "exitError", "!=", "nil", "{", "tc", ".", "ExitStatus", "=", "exitError", ".", "ExitStatus", "(", ")", "\n", "}", "\n", "return", "err", "\n\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// ExecuteSCP executes SCP command. It executes scp.Command using // lower-level API integrations that mimic SCP CLI command behavior
[ "ExecuteSCP", "executes", "SCP", "command", ".", "It", "executes", "scp", ".", "Command", "using", "lower", "-", "level", "API", "integrations", "that", "mimic", "SCP", "CLI", "command", "behavior" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L1112-L1160
train
gravitational/teleport
lib/client/api.go
ListNodes
func (tc *TeleportClient) ListNodes(ctx context.Context) ([]services.Server, error) { var err error // userhost is specified? that must be labels if tc.Host != "" { tc.Labels, err = ParseLabelSpec(tc.Host) if err != nil { return nil, trace.Wrap(err) } } // connect to the proxy and ask it to return a full list of servers proxyClient, err := tc.ConnectToProxy(ctx) if err != nil { return nil, trace.Wrap(err) } defer proxyClient.Close() return proxyClient.FindServersByLabels(ctx, tc.Namespace, tc.Labels) }
go
func (tc *TeleportClient) ListNodes(ctx context.Context) ([]services.Server, error) { var err error // userhost is specified? that must be labels if tc.Host != "" { tc.Labels, err = ParseLabelSpec(tc.Host) if err != nil { return nil, trace.Wrap(err) } } // connect to the proxy and ask it to return a full list of servers proxyClient, err := tc.ConnectToProxy(ctx) if err != nil { return nil, trace.Wrap(err) } defer proxyClient.Close() return proxyClient.FindServersByLabels(ctx, tc.Namespace, tc.Labels) }
[ "func", "(", "tc", "*", "TeleportClient", ")", "ListNodes", "(", "ctx", "context", ".", "Context", ")", "(", "[", "]", "services", ".", "Server", ",", "error", ")", "{", "var", "err", "error", "\n", "// userhost is specified? that must be labels", "if", "tc", ".", "Host", "!=", "\"", "\"", "{", "tc", ".", "Labels", ",", "err", "=", "ParseLabelSpec", "(", "tc", ".", "Host", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n\n", "// connect to the proxy and ask it to return a full list of servers", "proxyClient", ",", "err", ":=", "tc", ".", "ConnectToProxy", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "defer", "proxyClient", ".", "Close", "(", ")", "\n\n", "return", "proxyClient", ".", "FindServersByLabels", "(", "ctx", ",", "tc", ".", "Namespace", ",", "tc", ".", "Labels", ")", "\n", "}" ]
// ListNodes returns a list of nodes connected to a proxy
[ "ListNodes", "returns", "a", "list", "of", "nodes", "connected", "to", "a", "proxy" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L1295-L1313
train
gravitational/teleport
lib/client/api.go
runCommand
func (tc *TeleportClient) runCommand( ctx context.Context, siteName string, nodeAddresses []string, proxyClient *ProxyClient, command []string) error { resultsC := make(chan error, len(nodeAddresses)) for _, address := range nodeAddresses { go func(address string) { var ( err error nodeSession *NodeSession ) defer func() { resultsC <- err }() var nodeClient *NodeClient nodeClient, err = proxyClient.ConnectToNode(ctx, address+"@"+tc.Namespace+"@"+siteName, tc.Config.HostLogin, false) if err != nil { fmt.Fprintln(tc.Stderr, err) return } defer nodeClient.Close() // run the command on one node: if len(nodeAddresses) > 1 { fmt.Printf("Running command on %v:\n", address) } nodeSession, err = newSession(nodeClient, nil, tc.Config.Env, tc.Stdin, tc.Stdout, tc.Stderr) if err != nil { log.Error(err) return } defer nodeSession.Close() if err = nodeSession.runCommand(ctx, command, tc.OnShellCreated, tc.Config.Interactive); err != nil { originErr := trace.Unwrap(err) exitErr, ok := originErr.(*ssh.ExitError) if ok { tc.ExitStatus = exitErr.ExitStatus() } else { // if an error occurs, but no exit status is passed back, GoSSH returns // a generic error like this. in this case the error message is printed // to stderr by the remote process so we have to quietly return 1: if strings.Contains(originErr.Error(), "exited without exit status") { tc.ExitStatus = 1 } } } }(address) } var lastError error for range nodeAddresses { if err := <-resultsC; err != nil { lastError = err } } return trace.Wrap(lastError) }
go
func (tc *TeleportClient) runCommand( ctx context.Context, siteName string, nodeAddresses []string, proxyClient *ProxyClient, command []string) error { resultsC := make(chan error, len(nodeAddresses)) for _, address := range nodeAddresses { go func(address string) { var ( err error nodeSession *NodeSession ) defer func() { resultsC <- err }() var nodeClient *NodeClient nodeClient, err = proxyClient.ConnectToNode(ctx, address+"@"+tc.Namespace+"@"+siteName, tc.Config.HostLogin, false) if err != nil { fmt.Fprintln(tc.Stderr, err) return } defer nodeClient.Close() // run the command on one node: if len(nodeAddresses) > 1 { fmt.Printf("Running command on %v:\n", address) } nodeSession, err = newSession(nodeClient, nil, tc.Config.Env, tc.Stdin, tc.Stdout, tc.Stderr) if err != nil { log.Error(err) return } defer nodeSession.Close() if err = nodeSession.runCommand(ctx, command, tc.OnShellCreated, tc.Config.Interactive); err != nil { originErr := trace.Unwrap(err) exitErr, ok := originErr.(*ssh.ExitError) if ok { tc.ExitStatus = exitErr.ExitStatus() } else { // if an error occurs, but no exit status is passed back, GoSSH returns // a generic error like this. in this case the error message is printed // to stderr by the remote process so we have to quietly return 1: if strings.Contains(originErr.Error(), "exited without exit status") { tc.ExitStatus = 1 } } } }(address) } var lastError error for range nodeAddresses { if err := <-resultsC; err != nil { lastError = err } } return trace.Wrap(lastError) }
[ "func", "(", "tc", "*", "TeleportClient", ")", "runCommand", "(", "ctx", "context", ".", "Context", ",", "siteName", "string", ",", "nodeAddresses", "[", "]", "string", ",", "proxyClient", "*", "ProxyClient", ",", "command", "[", "]", "string", ")", "error", "{", "resultsC", ":=", "make", "(", "chan", "error", ",", "len", "(", "nodeAddresses", ")", ")", "\n", "for", "_", ",", "address", ":=", "range", "nodeAddresses", "{", "go", "func", "(", "address", "string", ")", "{", "var", "(", "err", "error", "\n", "nodeSession", "*", "NodeSession", "\n", ")", "\n", "defer", "func", "(", ")", "{", "resultsC", "<-", "err", "\n", "}", "(", ")", "\n", "var", "nodeClient", "*", "NodeClient", "\n", "nodeClient", ",", "err", "=", "proxyClient", ".", "ConnectToNode", "(", "ctx", ",", "address", "+", "\"", "\"", "+", "tc", ".", "Namespace", "+", "\"", "\"", "+", "siteName", ",", "tc", ".", "Config", ".", "HostLogin", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Fprintln", "(", "tc", ".", "Stderr", ",", "err", ")", "\n", "return", "\n", "}", "\n", "defer", "nodeClient", ".", "Close", "(", ")", "\n\n", "// run the command on one node:", "if", "len", "(", "nodeAddresses", ")", ">", "1", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "address", ")", "\n", "}", "\n", "nodeSession", ",", "err", "=", "newSession", "(", "nodeClient", ",", "nil", ",", "tc", ".", "Config", ".", "Env", ",", "tc", ".", "Stdin", ",", "tc", ".", "Stdout", ",", "tc", ".", "Stderr", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Error", "(", "err", ")", "\n", "return", "\n", "}", "\n", "defer", "nodeSession", ".", "Close", "(", ")", "\n", "if", "err", "=", "nodeSession", ".", "runCommand", "(", "ctx", ",", "command", ",", "tc", ".", "OnShellCreated", ",", "tc", ".", "Config", ".", "Interactive", ")", ";", "err", "!=", "nil", "{", "originErr", ":=", "trace", ".", "Unwrap", "(", "err", ")", "\n", "exitErr", ",", "ok", ":=", "originErr", ".", "(", "*", "ssh", ".", "ExitError", ")", "\n", "if", "ok", "{", "tc", ".", "ExitStatus", "=", "exitErr", ".", "ExitStatus", "(", ")", "\n", "}", "else", "{", "// if an error occurs, but no exit status is passed back, GoSSH returns", "// a generic error like this. in this case the error message is printed", "// to stderr by the remote process so we have to quietly return 1:", "if", "strings", ".", "Contains", "(", "originErr", ".", "Error", "(", ")", ",", "\"", "\"", ")", "{", "tc", ".", "ExitStatus", "=", "1", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "(", "address", ")", "\n", "}", "\n", "var", "lastError", "error", "\n", "for", "range", "nodeAddresses", "{", "if", "err", ":=", "<-", "resultsC", ";", "err", "!=", "nil", "{", "lastError", "=", "err", "\n", "}", "\n", "}", "\n", "return", "trace", ".", "Wrap", "(", "lastError", ")", "\n", "}" ]
// runCommand executes a given bash command on a bunch of remote nodes
[ "runCommand", "executes", "a", "given", "bash", "command", "on", "a", "bunch", "of", "remote", "nodes" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L1316-L1370
train
gravitational/teleport
lib/client/api.go
getProxySSHPrincipal
func (tc *TeleportClient) getProxySSHPrincipal() string { proxyPrincipal := tc.Config.HostLogin if tc.DefaultPrincipal != "" { proxyPrincipal = tc.DefaultPrincipal } // see if we already have a signed key in the cache, we'll use that instead if !tc.Config.SkipLocalAuth && tc.LocalAgent() != nil { signers, err := tc.LocalAgent().Signers() if err != nil || len(signers) == 0 { return proxyPrincipal } cert, ok := signers[0].PublicKey().(*ssh.Certificate) if ok && len(cert.ValidPrincipals) > 0 { return cert.ValidPrincipals[0] } } return proxyPrincipal }
go
func (tc *TeleportClient) getProxySSHPrincipal() string { proxyPrincipal := tc.Config.HostLogin if tc.DefaultPrincipal != "" { proxyPrincipal = tc.DefaultPrincipal } // see if we already have a signed key in the cache, we'll use that instead if !tc.Config.SkipLocalAuth && tc.LocalAgent() != nil { signers, err := tc.LocalAgent().Signers() if err != nil || len(signers) == 0 { return proxyPrincipal } cert, ok := signers[0].PublicKey().(*ssh.Certificate) if ok && len(cert.ValidPrincipals) > 0 { return cert.ValidPrincipals[0] } } return proxyPrincipal }
[ "func", "(", "tc", "*", "TeleportClient", ")", "getProxySSHPrincipal", "(", ")", "string", "{", "proxyPrincipal", ":=", "tc", ".", "Config", ".", "HostLogin", "\n", "if", "tc", ".", "DefaultPrincipal", "!=", "\"", "\"", "{", "proxyPrincipal", "=", "tc", ".", "DefaultPrincipal", "\n", "}", "\n", "// see if we already have a signed key in the cache, we'll use that instead", "if", "!", "tc", ".", "Config", ".", "SkipLocalAuth", "&&", "tc", ".", "LocalAgent", "(", ")", "!=", "nil", "{", "signers", ",", "err", ":=", "tc", ".", "LocalAgent", "(", ")", ".", "Signers", "(", ")", "\n", "if", "err", "!=", "nil", "||", "len", "(", "signers", ")", "==", "0", "{", "return", "proxyPrincipal", "\n", "}", "\n", "cert", ",", "ok", ":=", "signers", "[", "0", "]", ".", "PublicKey", "(", ")", ".", "(", "*", "ssh", ".", "Certificate", ")", "\n", "if", "ok", "&&", "len", "(", "cert", ".", "ValidPrincipals", ")", ">", "0", "{", "return", "cert", ".", "ValidPrincipals", "[", "0", "]", "\n", "}", "\n", "}", "\n", "return", "proxyPrincipal", "\n", "}" ]
// getProxyLogin determines which SSH principal to use when connecting to proxy.
[ "getProxyLogin", "determines", "which", "SSH", "principal", "to", "use", "when", "connecting", "to", "proxy", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L1391-L1408
train
gravitational/teleport
lib/client/api.go
ConnectToProxy
func (tc *TeleportClient) ConnectToProxy(ctx context.Context) (*ProxyClient, error) { var err error var proxyClient *ProxyClient // Use connectContext and the cancel function to signal when a response is // returned from connectToProxy. connectContext, cancel := context.WithCancel(context.Background()) go func() { defer cancel() proxyClient, err = tc.connectToProxy(ctx) }() select { // ConnectToProxy returned a result, return that back to the caller. case <-connectContext.Done(): return proxyClient, trace.Wrap(err) // The passed in context timed out. This is often due to the network being // down and the user hitting Ctrl-C. case <-ctx.Done(): return nil, trace.ConnectionProblem(ctx.Err(), "connection canceled") } }
go
func (tc *TeleportClient) ConnectToProxy(ctx context.Context) (*ProxyClient, error) { var err error var proxyClient *ProxyClient // Use connectContext and the cancel function to signal when a response is // returned from connectToProxy. connectContext, cancel := context.WithCancel(context.Background()) go func() { defer cancel() proxyClient, err = tc.connectToProxy(ctx) }() select { // ConnectToProxy returned a result, return that back to the caller. case <-connectContext.Done(): return proxyClient, trace.Wrap(err) // The passed in context timed out. This is often due to the network being // down and the user hitting Ctrl-C. case <-ctx.Done(): return nil, trace.ConnectionProblem(ctx.Err(), "connection canceled") } }
[ "func", "(", "tc", "*", "TeleportClient", ")", "ConnectToProxy", "(", "ctx", "context", ".", "Context", ")", "(", "*", "ProxyClient", ",", "error", ")", "{", "var", "err", "error", "\n", "var", "proxyClient", "*", "ProxyClient", "\n\n", "// Use connectContext and the cancel function to signal when a response is", "// returned from connectToProxy.", "connectContext", ",", "cancel", ":=", "context", ".", "WithCancel", "(", "context", ".", "Background", "(", ")", ")", "\n", "go", "func", "(", ")", "{", "defer", "cancel", "(", ")", "\n", "proxyClient", ",", "err", "=", "tc", ".", "connectToProxy", "(", "ctx", ")", "\n", "}", "(", ")", "\n\n", "select", "{", "// ConnectToProxy returned a result, return that back to the caller.", "case", "<-", "connectContext", ".", "Done", "(", ")", ":", "return", "proxyClient", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "// The passed in context timed out. This is often due to the network being", "// down and the user hitting Ctrl-C.", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "nil", ",", "trace", ".", "ConnectionProblem", "(", "ctx", ".", "Err", "(", ")", ",", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// ConnectToProxy will dial to the proxy server and return a ProxyClient when // successful. If the passed in context is canceled, this function will return // a trace.ConnectionProblem right away.
[ "ConnectToProxy", "will", "dial", "to", "the", "proxy", "server", "and", "return", "a", "ProxyClient", "when", "successful", ".", "If", "the", "passed", "in", "context", "is", "canceled", "this", "function", "will", "return", "a", "trace", ".", "ConnectionProblem", "right", "away", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L1423-L1444
train
gravitational/teleport
lib/client/api.go
connectToProxy
func (tc *TeleportClient) connectToProxy(ctx context.Context) (*ProxyClient, error) { var err error proxyPrincipal := tc.getProxySSHPrincipal() sshConfig := &ssh.ClientConfig{ User: proxyPrincipal, HostKeyCallback: tc.HostKeyCallback, } // helper to create a ProxyClient struct makeProxyClient := func(sshClient *ssh.Client, m ssh.AuthMethod) *ProxyClient { return &ProxyClient{ teleportClient: tc, Client: sshClient, proxyAddress: tc.Config.SSHProxyAddr, proxyPrincipal: proxyPrincipal, hostKeyCallback: sshConfig.HostKeyCallback, authMethod: m, hostLogin: tc.Config.HostLogin, siteName: tc.Config.SiteName, clientAddr: tc.ClientAddr, } } successMsg := fmt.Sprintf("Successful auth with proxy %v", tc.Config.SSHProxyAddr) // try to authenticate using every non interactive auth method we have: for i, m := range tc.authMethods() { log.Infof("Connecting proxy=%v login='%v' method=%d", tc.Config.SSHProxyAddr, sshConfig.User, i) var sshClient *ssh.Client sshConfig.Auth = []ssh.AuthMethod{m} sshClient, err = ssh.Dial("tcp", tc.Config.SSHProxyAddr, sshConfig) if err != nil { return nil, trace.Wrap(err) } log.Infof(successMsg) return makeProxyClient(sshClient, m), nil } // we have exhausted all auth existing auth methods and local login // is disabled in configuration, or the user refused connecting to untrusted hosts if err == nil { err = trace.BadParameter("failed to authenticate with proxy %v", tc.Config.SSHProxyAddr) } return nil, trace.Wrap(err) }
go
func (tc *TeleportClient) connectToProxy(ctx context.Context) (*ProxyClient, error) { var err error proxyPrincipal := tc.getProxySSHPrincipal() sshConfig := &ssh.ClientConfig{ User: proxyPrincipal, HostKeyCallback: tc.HostKeyCallback, } // helper to create a ProxyClient struct makeProxyClient := func(sshClient *ssh.Client, m ssh.AuthMethod) *ProxyClient { return &ProxyClient{ teleportClient: tc, Client: sshClient, proxyAddress: tc.Config.SSHProxyAddr, proxyPrincipal: proxyPrincipal, hostKeyCallback: sshConfig.HostKeyCallback, authMethod: m, hostLogin: tc.Config.HostLogin, siteName: tc.Config.SiteName, clientAddr: tc.ClientAddr, } } successMsg := fmt.Sprintf("Successful auth with proxy %v", tc.Config.SSHProxyAddr) // try to authenticate using every non interactive auth method we have: for i, m := range tc.authMethods() { log.Infof("Connecting proxy=%v login='%v' method=%d", tc.Config.SSHProxyAddr, sshConfig.User, i) var sshClient *ssh.Client sshConfig.Auth = []ssh.AuthMethod{m} sshClient, err = ssh.Dial("tcp", tc.Config.SSHProxyAddr, sshConfig) if err != nil { return nil, trace.Wrap(err) } log.Infof(successMsg) return makeProxyClient(sshClient, m), nil } // we have exhausted all auth existing auth methods and local login // is disabled in configuration, or the user refused connecting to untrusted hosts if err == nil { err = trace.BadParameter("failed to authenticate with proxy %v", tc.Config.SSHProxyAddr) } return nil, trace.Wrap(err) }
[ "func", "(", "tc", "*", "TeleportClient", ")", "connectToProxy", "(", "ctx", "context", ".", "Context", ")", "(", "*", "ProxyClient", ",", "error", ")", "{", "var", "err", "error", "\n\n", "proxyPrincipal", ":=", "tc", ".", "getProxySSHPrincipal", "(", ")", "\n", "sshConfig", ":=", "&", "ssh", ".", "ClientConfig", "{", "User", ":", "proxyPrincipal", ",", "HostKeyCallback", ":", "tc", ".", "HostKeyCallback", ",", "}", "\n\n", "// helper to create a ProxyClient struct", "makeProxyClient", ":=", "func", "(", "sshClient", "*", "ssh", ".", "Client", ",", "m", "ssh", ".", "AuthMethod", ")", "*", "ProxyClient", "{", "return", "&", "ProxyClient", "{", "teleportClient", ":", "tc", ",", "Client", ":", "sshClient", ",", "proxyAddress", ":", "tc", ".", "Config", ".", "SSHProxyAddr", ",", "proxyPrincipal", ":", "proxyPrincipal", ",", "hostKeyCallback", ":", "sshConfig", ".", "HostKeyCallback", ",", "authMethod", ":", "m", ",", "hostLogin", ":", "tc", ".", "Config", ".", "HostLogin", ",", "siteName", ":", "tc", ".", "Config", ".", "SiteName", ",", "clientAddr", ":", "tc", ".", "ClientAddr", ",", "}", "\n", "}", "\n", "successMsg", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "tc", ".", "Config", ".", "SSHProxyAddr", ")", "\n", "// try to authenticate using every non interactive auth method we have:", "for", "i", ",", "m", ":=", "range", "tc", ".", "authMethods", "(", ")", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "tc", ".", "Config", ".", "SSHProxyAddr", ",", "sshConfig", ".", "User", ",", "i", ")", "\n", "var", "sshClient", "*", "ssh", ".", "Client", "\n\n", "sshConfig", ".", "Auth", "=", "[", "]", "ssh", ".", "AuthMethod", "{", "m", "}", "\n", "sshClient", ",", "err", "=", "ssh", ".", "Dial", "(", "\"", "\"", ",", "tc", ".", "Config", ".", "SSHProxyAddr", ",", "sshConfig", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "log", ".", "Infof", "(", "successMsg", ")", "\n", "return", "makeProxyClient", "(", "sshClient", ",", "m", ")", ",", "nil", "\n", "}", "\n", "// we have exhausted all auth existing auth methods and local login", "// is disabled in configuration, or the user refused connecting to untrusted hosts", "if", "err", "==", "nil", "{", "err", "=", "trace", ".", "BadParameter", "(", "\"", "\"", ",", "tc", ".", "Config", ".", "SSHProxyAddr", ")", "\n", "}", "\n", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}" ]
// connectToProxy will dial to the proxy server and return a ProxyClient when // successful.
[ "connectToProxy", "will", "dial", "to", "the", "proxy", "server", "and", "return", "a", "ProxyClient", "when", "successful", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L1448-L1491
train
gravitational/teleport
lib/client/api.go
Logout
func (tc *TeleportClient) Logout() error { err := tc.localAgent.DeleteKey() if err != nil { return trace.Wrap(err) } return nil }
go
func (tc *TeleportClient) Logout() error { err := tc.localAgent.DeleteKey() if err != nil { return trace.Wrap(err) } return nil }
[ "func", "(", "tc", "*", "TeleportClient", ")", "Logout", "(", ")", "error", "{", "err", ":=", "tc", ".", "localAgent", ".", "DeleteKey", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Logout removes certificate and key for the currently logged in user from // the filesystem and agent.
[ "Logout", "removes", "certificate", "and", "key", "for", "the", "currently", "logged", "in", "user", "from", "the", "filesystem", "and", "agent", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L1495-L1502
train
gravitational/teleport
lib/client/api.go
LogoutAll
func (tc *TeleportClient) LogoutAll() error { err := tc.localAgent.DeleteKeys() if err != nil { return trace.Wrap(err) } return nil }
go
func (tc *TeleportClient) LogoutAll() error { err := tc.localAgent.DeleteKeys() if err != nil { return trace.Wrap(err) } return nil }
[ "func", "(", "tc", "*", "TeleportClient", ")", "LogoutAll", "(", ")", "error", "{", "err", ":=", "tc", ".", "localAgent", ".", "DeleteKeys", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// LogoutAll removes all certificates for all users from the filesystem // and agent.
[ "LogoutAll", "removes", "all", "certificates", "for", "all", "users", "from", "the", "filesystem", "and", "agent", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L1506-L1512
train
gravitational/teleport
lib/client/api.go
GetTrustedCA
func (tc *TeleportClient) GetTrustedCA(ctx context.Context, clusterName string) ([]services.CertAuthority, error) { // Connect to the proxy. if !tc.Config.ProxySpecified() { return nil, trace.BadParameter("proxy server is not specified") } proxyClient, err := tc.ConnectToProxy(ctx) if err != nil { return nil, trace.Wrap(err) } defer proxyClient.Close() // Get a client to the Auth Server. clt, err := proxyClient.ClusterAccessPoint(ctx, clusterName, true) if err != nil { return nil, trace.Wrap(err) } // Get the list of host certificates that this cluster knows about. return clt.GetCertAuthorities(services.HostCA, false) }
go
func (tc *TeleportClient) GetTrustedCA(ctx context.Context, clusterName string) ([]services.CertAuthority, error) { // Connect to the proxy. if !tc.Config.ProxySpecified() { return nil, trace.BadParameter("proxy server is not specified") } proxyClient, err := tc.ConnectToProxy(ctx) if err != nil { return nil, trace.Wrap(err) } defer proxyClient.Close() // Get a client to the Auth Server. clt, err := proxyClient.ClusterAccessPoint(ctx, clusterName, true) if err != nil { return nil, trace.Wrap(err) } // Get the list of host certificates that this cluster knows about. return clt.GetCertAuthorities(services.HostCA, false) }
[ "func", "(", "tc", "*", "TeleportClient", ")", "GetTrustedCA", "(", "ctx", "context", ".", "Context", ",", "clusterName", "string", ")", "(", "[", "]", "services", ".", "CertAuthority", ",", "error", ")", "{", "// Connect to the proxy.", "if", "!", "tc", ".", "Config", ".", "ProxySpecified", "(", ")", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "proxyClient", ",", "err", ":=", "tc", ".", "ConnectToProxy", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "defer", "proxyClient", ".", "Close", "(", ")", "\n\n", "// Get a client to the Auth Server.", "clt", ",", "err", ":=", "proxyClient", ".", "ClusterAccessPoint", "(", "ctx", ",", "clusterName", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "// Get the list of host certificates that this cluster knows about.", "return", "clt", ".", "GetCertAuthorities", "(", "services", ".", "HostCA", ",", "false", ")", "\n", "}" ]
// GetTrustedCA returns a list of host certificate authorities // trusted by the cluster client is authenticated with.
[ "GetTrustedCA", "returns", "a", "list", "of", "host", "certificate", "authorities", "trusted", "by", "the", "cluster", "client", "is", "authenticated", "with", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L1631-L1650
train
gravitational/teleport
lib/client/api.go
applyProxySettings
func (tc *TeleportClient) applyProxySettings(proxySettings ProxySettings) error { // Kubernetes proxy settings. if proxySettings.Kube.Enabled && proxySettings.Kube.PublicAddr != "" && tc.KubeProxyAddr == "" { _, err := utils.ParseAddr(proxySettings.Kube.PublicAddr) if err != nil { return trace.BadParameter( "failed to parse value received from the server: %q, contact your administrator for help", proxySettings.Kube.PublicAddr) } tc.KubeProxyAddr = proxySettings.Kube.PublicAddr } else if proxySettings.Kube.Enabled && tc.KubeProxyAddr == "" { webProxyHost, _ := tc.WebProxyHostPort() tc.KubeProxyAddr = fmt.Sprintf("%s:%d", webProxyHost, defaults.KubeProxyListenPort) } // Read in settings for HTTP endpoint of the proxy. if proxySettings.SSH.PublicAddr != "" { addr, err := utils.ParseAddr(proxySettings.SSH.PublicAddr) if err != nil { return trace.BadParameter( "failed to parse value received from the server: %q, contact your administrator for help", proxySettings.SSH.PublicAddr) } tc.WebProxyAddr = net.JoinHostPort(addr.Host(), strconv.Itoa(addr.Port(defaults.HTTPListenPort))) // Update local agent (that reads/writes to ~/.tsh) with the new address // of the web proxy. This will control where the keys are stored on disk // after login. tc.localAgent.UpdateProxyHost(addr.Host()) } // Read in settings for the SSH endpoint of the proxy. // // If listen_addr is set, take host from ProxyWebHost and port from what // was set. This is to maintain backward compatibility when Teleport only // supported public_addr. if proxySettings.SSH.ListenAddr != "" { addr, err := utils.ParseAddr(proxySettings.SSH.ListenAddr) if err != nil { return trace.BadParameter( "failed to parse value received from the server: %q, contact your administrator for help", proxySettings.SSH.ListenAddr) } webProxyHost, _ := tc.WebProxyHostPort() tc.SSHProxyAddr = net.JoinHostPort(webProxyHost, strconv.Itoa(addr.Port(defaults.SSHProxyListenPort))) } // If ssh_public_addr is set, override settings from listen_addr. if proxySettings.SSH.SSHPublicAddr != "" { addr, err := utils.ParseAddr(proxySettings.SSH.SSHPublicAddr) if err != nil { return trace.BadParameter( "failed to parse value received from the server: %q, contact your administrator for help", proxySettings.SSH.ListenAddr) } tc.SSHProxyAddr = net.JoinHostPort(addr.Host(), strconv.Itoa(addr.Port(defaults.SSHProxyListenPort))) } return nil }
go
func (tc *TeleportClient) applyProxySettings(proxySettings ProxySettings) error { // Kubernetes proxy settings. if proxySettings.Kube.Enabled && proxySettings.Kube.PublicAddr != "" && tc.KubeProxyAddr == "" { _, err := utils.ParseAddr(proxySettings.Kube.PublicAddr) if err != nil { return trace.BadParameter( "failed to parse value received from the server: %q, contact your administrator for help", proxySettings.Kube.PublicAddr) } tc.KubeProxyAddr = proxySettings.Kube.PublicAddr } else if proxySettings.Kube.Enabled && tc.KubeProxyAddr == "" { webProxyHost, _ := tc.WebProxyHostPort() tc.KubeProxyAddr = fmt.Sprintf("%s:%d", webProxyHost, defaults.KubeProxyListenPort) } // Read in settings for HTTP endpoint of the proxy. if proxySettings.SSH.PublicAddr != "" { addr, err := utils.ParseAddr(proxySettings.SSH.PublicAddr) if err != nil { return trace.BadParameter( "failed to parse value received from the server: %q, contact your administrator for help", proxySettings.SSH.PublicAddr) } tc.WebProxyAddr = net.JoinHostPort(addr.Host(), strconv.Itoa(addr.Port(defaults.HTTPListenPort))) // Update local agent (that reads/writes to ~/.tsh) with the new address // of the web proxy. This will control where the keys are stored on disk // after login. tc.localAgent.UpdateProxyHost(addr.Host()) } // Read in settings for the SSH endpoint of the proxy. // // If listen_addr is set, take host from ProxyWebHost and port from what // was set. This is to maintain backward compatibility when Teleport only // supported public_addr. if proxySettings.SSH.ListenAddr != "" { addr, err := utils.ParseAddr(proxySettings.SSH.ListenAddr) if err != nil { return trace.BadParameter( "failed to parse value received from the server: %q, contact your administrator for help", proxySettings.SSH.ListenAddr) } webProxyHost, _ := tc.WebProxyHostPort() tc.SSHProxyAddr = net.JoinHostPort(webProxyHost, strconv.Itoa(addr.Port(defaults.SSHProxyListenPort))) } // If ssh_public_addr is set, override settings from listen_addr. if proxySettings.SSH.SSHPublicAddr != "" { addr, err := utils.ParseAddr(proxySettings.SSH.SSHPublicAddr) if err != nil { return trace.BadParameter( "failed to parse value received from the server: %q, contact your administrator for help", proxySettings.SSH.ListenAddr) } tc.SSHProxyAddr = net.JoinHostPort(addr.Host(), strconv.Itoa(addr.Port(defaults.SSHProxyListenPort))) } return nil }
[ "func", "(", "tc", "*", "TeleportClient", ")", "applyProxySettings", "(", "proxySettings", "ProxySettings", ")", "error", "{", "// Kubernetes proxy settings.", "if", "proxySettings", ".", "Kube", ".", "Enabled", "&&", "proxySettings", ".", "Kube", ".", "PublicAddr", "!=", "\"", "\"", "&&", "tc", ".", "KubeProxyAddr", "==", "\"", "\"", "{", "_", ",", "err", ":=", "utils", ".", "ParseAddr", "(", "proxySettings", ".", "Kube", ".", "PublicAddr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "BadParameter", "(", "\"", "\"", ",", "proxySettings", ".", "Kube", ".", "PublicAddr", ")", "\n", "}", "\n", "tc", ".", "KubeProxyAddr", "=", "proxySettings", ".", "Kube", ".", "PublicAddr", "\n", "}", "else", "if", "proxySettings", ".", "Kube", ".", "Enabled", "&&", "tc", ".", "KubeProxyAddr", "==", "\"", "\"", "{", "webProxyHost", ",", "_", ":=", "tc", ".", "WebProxyHostPort", "(", ")", "\n", "tc", ".", "KubeProxyAddr", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "webProxyHost", ",", "defaults", ".", "KubeProxyListenPort", ")", "\n", "}", "\n\n", "// Read in settings for HTTP endpoint of the proxy.", "if", "proxySettings", ".", "SSH", ".", "PublicAddr", "!=", "\"", "\"", "{", "addr", ",", "err", ":=", "utils", ".", "ParseAddr", "(", "proxySettings", ".", "SSH", ".", "PublicAddr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "BadParameter", "(", "\"", "\"", ",", "proxySettings", ".", "SSH", ".", "PublicAddr", ")", "\n", "}", "\n", "tc", ".", "WebProxyAddr", "=", "net", ".", "JoinHostPort", "(", "addr", ".", "Host", "(", ")", ",", "strconv", ".", "Itoa", "(", "addr", ".", "Port", "(", "defaults", ".", "HTTPListenPort", ")", ")", ")", "\n\n", "// Update local agent (that reads/writes to ~/.tsh) with the new address", "// of the web proxy. This will control where the keys are stored on disk", "// after login.", "tc", ".", "localAgent", ".", "UpdateProxyHost", "(", "addr", ".", "Host", "(", ")", ")", "\n", "}", "\n", "// Read in settings for the SSH endpoint of the proxy.", "//", "// If listen_addr is set, take host from ProxyWebHost and port from what", "// was set. This is to maintain backward compatibility when Teleport only", "// supported public_addr.", "if", "proxySettings", ".", "SSH", ".", "ListenAddr", "!=", "\"", "\"", "{", "addr", ",", "err", ":=", "utils", ".", "ParseAddr", "(", "proxySettings", ".", "SSH", ".", "ListenAddr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "BadParameter", "(", "\"", "\"", ",", "proxySettings", ".", "SSH", ".", "ListenAddr", ")", "\n", "}", "\n", "webProxyHost", ",", "_", ":=", "tc", ".", "WebProxyHostPort", "(", ")", "\n", "tc", ".", "SSHProxyAddr", "=", "net", ".", "JoinHostPort", "(", "webProxyHost", ",", "strconv", ".", "Itoa", "(", "addr", ".", "Port", "(", "defaults", ".", "SSHProxyListenPort", ")", ")", ")", "\n", "}", "\n", "// If ssh_public_addr is set, override settings from listen_addr.", "if", "proxySettings", ".", "SSH", ".", "SSHPublicAddr", "!=", "\"", "\"", "{", "addr", ",", "err", ":=", "utils", ".", "ParseAddr", "(", "proxySettings", ".", "SSH", ".", "SSHPublicAddr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "BadParameter", "(", "\"", "\"", ",", "proxySettings", ".", "SSH", ".", "ListenAddr", ")", "\n", "}", "\n", "tc", ".", "SSHProxyAddr", "=", "net", ".", "JoinHostPort", "(", "addr", ".", "Host", "(", ")", ",", "strconv", ".", "Itoa", "(", "addr", ".", "Port", "(", "defaults", ".", "SSHProxyListenPort", ")", ")", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// applyProxySettings updates configuration changes based on the advertised // proxy settings, user supplied values take precedence - will be preserved // if set
[ "applyProxySettings", "updates", "configuration", "changes", "based", "on", "the", "advertised", "proxy", "settings", "user", "supplied", "values", "take", "precedence", "-", "will", "be", "preserved", "if", "set" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L1681-L1738
train
gravitational/teleport
lib/client/api.go
AddTrustedCA
func (tc *TeleportClient) AddTrustedCA(ca services.CertAuthority) error { err := tc.LocalAgent().AddHostSignersToCache(auth.AuthoritiesToTrustedCerts([]services.CertAuthority{ca})) if err != nil { return trace.Wrap(err) } // only host CA has TLS certificates, user CA will overwrite trusted certs // to empty file if called if ca.GetType() == services.HostCA { err = tc.LocalAgent().SaveCerts(auth.AuthoritiesToTrustedCerts([]services.CertAuthority{ca})) if err != nil { return trace.Wrap(err) } } return nil }
go
func (tc *TeleportClient) AddTrustedCA(ca services.CertAuthority) error { err := tc.LocalAgent().AddHostSignersToCache(auth.AuthoritiesToTrustedCerts([]services.CertAuthority{ca})) if err != nil { return trace.Wrap(err) } // only host CA has TLS certificates, user CA will overwrite trusted certs // to empty file if called if ca.GetType() == services.HostCA { err = tc.LocalAgent().SaveCerts(auth.AuthoritiesToTrustedCerts([]services.CertAuthority{ca})) if err != nil { return trace.Wrap(err) } } return nil }
[ "func", "(", "tc", "*", "TeleportClient", ")", "AddTrustedCA", "(", "ca", "services", ".", "CertAuthority", ")", "error", "{", "err", ":=", "tc", ".", "LocalAgent", "(", ")", ".", "AddHostSignersToCache", "(", "auth", ".", "AuthoritiesToTrustedCerts", "(", "[", "]", "services", ".", "CertAuthority", "{", "ca", "}", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "// only host CA has TLS certificates, user CA will overwrite trusted certs", "// to empty file if called", "if", "ca", ".", "GetType", "(", ")", "==", "services", ".", "HostCA", "{", "err", "=", "tc", ".", "LocalAgent", "(", ")", ".", "SaveCerts", "(", "auth", ".", "AuthoritiesToTrustedCerts", "(", "[", "]", "services", ".", "CertAuthority", "{", "ca", "}", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Adds a new CA as trusted CA for this client, used in tests
[ "Adds", "a", "new", "CA", "as", "trusted", "CA", "for", "this", "client", "used", "in", "tests" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L1763-L1779
train
gravitational/teleport
lib/client/api.go
directLogin
func (tc *TeleportClient) directLogin(ctx context.Context, secondFactorType string, pub []byte) (*auth.SSHLoginResponse, error) { var err error var password string var otpToken string password, err = tc.AskPassword() if err != nil { return nil, trace.Wrap(err) } // only ask for a second factor if it's enabled if secondFactorType != teleport.OFF { otpToken, err = tc.AskOTP() if err != nil { return nil, trace.Wrap(err) } } // ask the CA (via proxy) to sign our public key: response, err := tc.credClient.SSHAgentLogin( ctx, tc.Config.Username, password, otpToken, pub, tc.KeyTTL, tc.CertificateFormat) return response, trace.Wrap(err) }
go
func (tc *TeleportClient) directLogin(ctx context.Context, secondFactorType string, pub []byte) (*auth.SSHLoginResponse, error) { var err error var password string var otpToken string password, err = tc.AskPassword() if err != nil { return nil, trace.Wrap(err) } // only ask for a second factor if it's enabled if secondFactorType != teleport.OFF { otpToken, err = tc.AskOTP() if err != nil { return nil, trace.Wrap(err) } } // ask the CA (via proxy) to sign our public key: response, err := tc.credClient.SSHAgentLogin( ctx, tc.Config.Username, password, otpToken, pub, tc.KeyTTL, tc.CertificateFormat) return response, trace.Wrap(err) }
[ "func", "(", "tc", "*", "TeleportClient", ")", "directLogin", "(", "ctx", "context", ".", "Context", ",", "secondFactorType", "string", ",", "pub", "[", "]", "byte", ")", "(", "*", "auth", ".", "SSHLoginResponse", ",", "error", ")", "{", "var", "err", "error", "\n\n", "var", "password", "string", "\n", "var", "otpToken", "string", "\n\n", "password", ",", "err", "=", "tc", ".", "AskPassword", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "// only ask for a second factor if it's enabled", "if", "secondFactorType", "!=", "teleport", ".", "OFF", "{", "otpToken", ",", "err", "=", "tc", ".", "AskOTP", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n\n", "// ask the CA (via proxy) to sign our public key:", "response", ",", "err", ":=", "tc", ".", "credClient", ".", "SSHAgentLogin", "(", "ctx", ",", "tc", ".", "Config", ".", "Username", ",", "password", ",", "otpToken", ",", "pub", ",", "tc", ".", "KeyTTL", ",", "tc", ".", "CertificateFormat", ")", "\n\n", "return", "response", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}" ]
// directLogin asks for a password + HOTP token, makes a request to CA via proxy
[ "directLogin", "asks", "for", "a", "password", "+", "HOTP", "token", "makes", "a", "request", "to", "CA", "via", "proxy" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L1786-L1816
train
gravitational/teleport
lib/client/api.go
ssoLogin
func (tc *TeleportClient) ssoLogin(ctx context.Context, connectorID string, pub []byte, protocol string) (*auth.SSHLoginResponse, error) { log.Debugf("samlLogin start") // ask the CA (via proxy) to sign our public key: response, err := tc.credClient.SSHAgentSSOLogin(SSHLogin{ Context: ctx, ConnectorID: connectorID, PubKey: pub, TTL: tc.KeyTTL, Protocol: protocol, Compatibility: tc.CertificateFormat, BindAddr: tc.BindAddr, }) return response, trace.Wrap(err) }
go
func (tc *TeleportClient) ssoLogin(ctx context.Context, connectorID string, pub []byte, protocol string) (*auth.SSHLoginResponse, error) { log.Debugf("samlLogin start") // ask the CA (via proxy) to sign our public key: response, err := tc.credClient.SSHAgentSSOLogin(SSHLogin{ Context: ctx, ConnectorID: connectorID, PubKey: pub, TTL: tc.KeyTTL, Protocol: protocol, Compatibility: tc.CertificateFormat, BindAddr: tc.BindAddr, }) return response, trace.Wrap(err) }
[ "func", "(", "tc", "*", "TeleportClient", ")", "ssoLogin", "(", "ctx", "context", ".", "Context", ",", "connectorID", "string", ",", "pub", "[", "]", "byte", ",", "protocol", "string", ")", "(", "*", "auth", ".", "SSHLoginResponse", ",", "error", ")", "{", "log", ".", "Debugf", "(", "\"", "\"", ")", "\n", "// ask the CA (via proxy) to sign our public key:", "response", ",", "err", ":=", "tc", ".", "credClient", ".", "SSHAgentSSOLogin", "(", "SSHLogin", "{", "Context", ":", "ctx", ",", "ConnectorID", ":", "connectorID", ",", "PubKey", ":", "pub", ",", "TTL", ":", "tc", ".", "KeyTTL", ",", "Protocol", ":", "protocol", ",", "Compatibility", ":", "tc", ".", "CertificateFormat", ",", "BindAddr", ":", "tc", ".", "BindAddr", ",", "}", ")", "\n", "return", "response", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}" ]
// samlLogin opens browser window and uses OIDC or SAML redirect cycle with browser
[ "samlLogin", "opens", "browser", "window", "and", "uses", "OIDC", "or", "SAML", "redirect", "cycle", "with", "browser" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L1819-L1832
train
gravitational/teleport
lib/client/api.go
u2fLogin
func (tc *TeleportClient) u2fLogin(ctx context.Context, pub []byte) (*auth.SSHLoginResponse, error) { // U2F login requires the official u2f-host executable _, err := exec.LookPath("u2f-host") if err != nil { return nil, trace.Wrap(err) } password, err := tc.AskPassword() if err != nil { return nil, trace.Wrap(err) } response, err := tc.credClient.SSHAgentU2FLogin( ctx, tc.Config.Username, password, pub, tc.KeyTTL, tc.CertificateFormat) return response, trace.Wrap(err) }
go
func (tc *TeleportClient) u2fLogin(ctx context.Context, pub []byte) (*auth.SSHLoginResponse, error) { // U2F login requires the official u2f-host executable _, err := exec.LookPath("u2f-host") if err != nil { return nil, trace.Wrap(err) } password, err := tc.AskPassword() if err != nil { return nil, trace.Wrap(err) } response, err := tc.credClient.SSHAgentU2FLogin( ctx, tc.Config.Username, password, pub, tc.KeyTTL, tc.CertificateFormat) return response, trace.Wrap(err) }
[ "func", "(", "tc", "*", "TeleportClient", ")", "u2fLogin", "(", "ctx", "context", ".", "Context", ",", "pub", "[", "]", "byte", ")", "(", "*", "auth", ".", "SSHLoginResponse", ",", "error", ")", "{", "// U2F login requires the official u2f-host executable", "_", ",", "err", ":=", "exec", ".", "LookPath", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "password", ",", "err", ":=", "tc", ".", "AskPassword", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "response", ",", "err", ":=", "tc", ".", "credClient", ".", "SSHAgentU2FLogin", "(", "ctx", ",", "tc", ".", "Config", ".", "Username", ",", "password", ",", "pub", ",", "tc", ".", "KeyTTL", ",", "tc", ".", "CertificateFormat", ")", "\n\n", "return", "response", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}" ]
// directLogin asks for a password and performs the challenge-response authentication
[ "directLogin", "asks", "for", "a", "password", "and", "performs", "the", "challenge", "-", "response", "authentication" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L1835-L1856
train
gravitational/teleport
lib/client/api.go
SendEvent
func (tc *TeleportClient) SendEvent(ctx context.Context, e events.EventFields) error { // Try and send the event to the eventsCh. If blocking, keep blocking until // the passed in context in canceled. select { case tc.eventsCh <- e: return nil case <-ctx.Done(): return trace.Wrap(ctx.Err()) } }
go
func (tc *TeleportClient) SendEvent(ctx context.Context, e events.EventFields) error { // Try and send the event to the eventsCh. If blocking, keep blocking until // the passed in context in canceled. select { case tc.eventsCh <- e: return nil case <-ctx.Done(): return trace.Wrap(ctx.Err()) } }
[ "func", "(", "tc", "*", "TeleportClient", ")", "SendEvent", "(", "ctx", "context", ".", "Context", ",", "e", "events", ".", "EventFields", ")", "error", "{", "// Try and send the event to the eventsCh. If blocking, keep blocking until", "// the passed in context in canceled.", "select", "{", "case", "tc", ".", "eventsCh", "<-", "e", ":", "return", "nil", "\n", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "trace", ".", "Wrap", "(", "ctx", ".", "Err", "(", ")", ")", "\n", "}", "\n", "}" ]
// SendEvent adds a events.EventFields to the channel.
[ "SendEvent", "adds", "a", "events", ".", "EventFields", "to", "the", "channel", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L1859-L1868
train
gravitational/teleport
lib/client/api.go
loopbackPool
func loopbackPool(proxyAddr string) *x509.CertPool { if !utils.IsLoopback(proxyAddr) { log.Debugf("not using loopback pool for remote proxy addr: %v", proxyAddr) return nil } log.Debugf("attempting to use loopback pool for local proxy addr: %v", proxyAddr) certPool := x509.NewCertPool() certPath := filepath.Join(defaults.DataDir, defaults.SelfSignedCertPath) pemByte, err := ioutil.ReadFile(certPath) if err != nil { log.Debugf("could not open any path in: %v", certPath) return nil } for { var block *pem.Block block, pemByte = pem.Decode(pemByte) if block == nil { break } cert, err := x509.ParseCertificate(block.Bytes) if err != nil { log.Debugf("could not parse cert in: %v, err: %v", certPath, err) return nil } certPool.AddCert(cert) } log.Debugf("using local pool for loopback proxy: %v, err: %v", certPath, err) return certPool }
go
func loopbackPool(proxyAddr string) *x509.CertPool { if !utils.IsLoopback(proxyAddr) { log.Debugf("not using loopback pool for remote proxy addr: %v", proxyAddr) return nil } log.Debugf("attempting to use loopback pool for local proxy addr: %v", proxyAddr) certPool := x509.NewCertPool() certPath := filepath.Join(defaults.DataDir, defaults.SelfSignedCertPath) pemByte, err := ioutil.ReadFile(certPath) if err != nil { log.Debugf("could not open any path in: %v", certPath) return nil } for { var block *pem.Block block, pemByte = pem.Decode(pemByte) if block == nil { break } cert, err := x509.ParseCertificate(block.Bytes) if err != nil { log.Debugf("could not parse cert in: %v, err: %v", certPath, err) return nil } certPool.AddCert(cert) } log.Debugf("using local pool for loopback proxy: %v, err: %v", certPath, err) return certPool }
[ "func", "loopbackPool", "(", "proxyAddr", "string", ")", "*", "x509", ".", "CertPool", "{", "if", "!", "utils", ".", "IsLoopback", "(", "proxyAddr", ")", "{", "log", ".", "Debugf", "(", "\"", "\"", ",", "proxyAddr", ")", "\n", "return", "nil", "\n", "}", "\n", "log", ".", "Debugf", "(", "\"", "\"", ",", "proxyAddr", ")", "\n", "certPool", ":=", "x509", ".", "NewCertPool", "(", ")", "\n\n", "certPath", ":=", "filepath", ".", "Join", "(", "defaults", ".", "DataDir", ",", "defaults", ".", "SelfSignedCertPath", ")", "\n", "pemByte", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "certPath", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Debugf", "(", "\"", "\"", ",", "certPath", ")", "\n", "return", "nil", "\n", "}", "\n\n", "for", "{", "var", "block", "*", "pem", ".", "Block", "\n", "block", ",", "pemByte", "=", "pem", ".", "Decode", "(", "pemByte", ")", "\n", "if", "block", "==", "nil", "{", "break", "\n", "}", "\n", "cert", ",", "err", ":=", "x509", ".", "ParseCertificate", "(", "block", ".", "Bytes", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Debugf", "(", "\"", "\"", ",", "certPath", ",", "err", ")", "\n", "return", "nil", "\n", "}", "\n", "certPool", ".", "AddCert", "(", "cert", ")", "\n", "}", "\n", "log", ".", "Debugf", "(", "\"", "\"", ",", "certPath", ",", "err", ")", "\n", "return", "certPool", "\n", "}" ]
// loopbackPool reads trusted CAs if it finds it in a predefined location // and will work only if target proxy address is loopback
[ "loopbackPool", "reads", "trusted", "CAs", "if", "it", "finds", "it", "in", "a", "predefined", "location", "and", "will", "work", "only", "if", "target", "proxy", "address", "is", "loopback" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L1878-L1908
train
gravitational/teleport
lib/client/api.go
connectToSSHAgent
func connectToSSHAgent() agent.Agent { socketPath := os.Getenv(teleport.SSHAuthSock) conn, err := agentconn.Dial(socketPath) if err != nil { log.Errorf("[KEY AGENT] Unable to connect to SSH agent on socket: %q.", socketPath) return nil } log.Infof("[KEY AGENT] Connected to the system agent: %q", socketPath) return agent.NewClient(conn) }
go
func connectToSSHAgent() agent.Agent { socketPath := os.Getenv(teleport.SSHAuthSock) conn, err := agentconn.Dial(socketPath) if err != nil { log.Errorf("[KEY AGENT] Unable to connect to SSH agent on socket: %q.", socketPath) return nil } log.Infof("[KEY AGENT] Connected to the system agent: %q", socketPath) return agent.NewClient(conn) }
[ "func", "connectToSSHAgent", "(", ")", "agent", ".", "Agent", "{", "socketPath", ":=", "os", ".", "Getenv", "(", "teleport", ".", "SSHAuthSock", ")", "\n", "conn", ",", "err", ":=", "agentconn", ".", "Dial", "(", "socketPath", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "socketPath", ")", "\n", "return", "nil", "\n", "}", "\n\n", "log", ".", "Infof", "(", "\"", "\"", ",", "socketPath", ")", "\n", "return", "agent", ".", "NewClient", "(", "conn", ")", "\n", "}" ]
// connectToSSHAgent connects to the local SSH agent and returns a agent.Agent.
[ "connectToSSHAgent", "connects", "to", "the", "local", "SSH", "agent", "and", "returns", "a", "agent", ".", "Agent", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L1911-L1921
train
gravitational/teleport
lib/client/api.go
Username
func Username() (string, error) { u, err := user.Current() if err != nil { return "", trace.Wrap(err) } return u.Username, nil }
go
func Username() (string, error) { u, err := user.Current() if err != nil { return "", trace.Wrap(err) } return u.Username, nil }
[ "func", "Username", "(", ")", "(", "string", ",", "error", ")", "{", "u", ",", "err", ":=", "user", ".", "Current", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "u", ".", "Username", ",", "nil", "\n", "}" ]
// Username returns the current user's username
[ "Username", "returns", "the", "current", "user", "s", "username" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L1924-L1930
train
gravitational/teleport
lib/client/api.go
AskOTP
func (tc *TeleportClient) AskOTP() (token string, err error) { fmt.Printf("Enter your OTP token:\n") token, err = lineFromConsole() if err != nil { fmt.Fprintln(tc.Stderr, err) return "", trace.Wrap(err) } return token, nil }
go
func (tc *TeleportClient) AskOTP() (token string, err error) { fmt.Printf("Enter your OTP token:\n") token, err = lineFromConsole() if err != nil { fmt.Fprintln(tc.Stderr, err) return "", trace.Wrap(err) } return token, nil }
[ "func", "(", "tc", "*", "TeleportClient", ")", "AskOTP", "(", ")", "(", "token", "string", ",", "err", "error", ")", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ")", "\n", "token", ",", "err", "=", "lineFromConsole", "(", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Fprintln", "(", "tc", ".", "Stderr", ",", "err", ")", "\n", "return", "\"", "\"", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "token", ",", "nil", "\n", "}" ]
// AskOTP prompts the user to enter the OTP token.
[ "AskOTP", "prompts", "the", "user", "to", "enter", "the", "OTP", "token", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L1933-L1941
train
gravitational/teleport
lib/client/api.go
AskPassword
func (tc *TeleportClient) AskPassword() (pwd string, err error) { fmt.Printf("Enter password for Teleport user %v:\n", tc.Config.Username) pwd, err = passwordFromConsole() if err != nil { fmt.Fprintln(tc.Stderr, err) return "", trace.Wrap(err) } return pwd, nil }
go
func (tc *TeleportClient) AskPassword() (pwd string, err error) { fmt.Printf("Enter password for Teleport user %v:\n", tc.Config.Username) pwd, err = passwordFromConsole() if err != nil { fmt.Fprintln(tc.Stderr, err) return "", trace.Wrap(err) } return pwd, nil }
[ "func", "(", "tc", "*", "TeleportClient", ")", "AskPassword", "(", ")", "(", "pwd", "string", ",", "err", "error", ")", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "tc", ".", "Config", ".", "Username", ")", "\n", "pwd", ",", "err", "=", "passwordFromConsole", "(", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Fprintln", "(", "tc", ".", "Stderr", ",", "err", ")", "\n", "return", "\"", "\"", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "return", "pwd", ",", "nil", "\n", "}" ]
// AskPassword prompts the user to enter the password
[ "AskPassword", "prompts", "the", "user", "to", "enter", "the", "password" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L1944-L1953
train
gravitational/teleport
lib/client/api.go
passwordFromConsole
func passwordFromConsole() (string, error) { fd := syscall.Stdin state, err := terminal.GetState(int(fd)) // intercept Ctr+C and restore terminal sigCh := make(chan os.Signal, 1) closeCh := make(chan int) if err != nil { log.Warnf("failed reading terminal state: %v", err) } else { signal.Notify(sigCh, syscall.SIGINT) go func() { select { case <-sigCh: terminal.Restore(int(fd), state) os.Exit(1) case <-closeCh: } }() } defer func() { close(closeCh) }() bytes, err := terminal.ReadPassword(int(fd)) return string(bytes), err }
go
func passwordFromConsole() (string, error) { fd := syscall.Stdin state, err := terminal.GetState(int(fd)) // intercept Ctr+C and restore terminal sigCh := make(chan os.Signal, 1) closeCh := make(chan int) if err != nil { log.Warnf("failed reading terminal state: %v", err) } else { signal.Notify(sigCh, syscall.SIGINT) go func() { select { case <-sigCh: terminal.Restore(int(fd), state) os.Exit(1) case <-closeCh: } }() } defer func() { close(closeCh) }() bytes, err := terminal.ReadPassword(int(fd)) return string(bytes), err }
[ "func", "passwordFromConsole", "(", ")", "(", "string", ",", "error", ")", "{", "fd", ":=", "syscall", ".", "Stdin", "\n", "state", ",", "err", ":=", "terminal", ".", "GetState", "(", "int", "(", "fd", ")", ")", "\n\n", "// intercept Ctr+C and restore terminal", "sigCh", ":=", "make", "(", "chan", "os", ".", "Signal", ",", "1", ")", "\n", "closeCh", ":=", "make", "(", "chan", "int", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Warnf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "else", "{", "signal", ".", "Notify", "(", "sigCh", ",", "syscall", ".", "SIGINT", ")", "\n", "go", "func", "(", ")", "{", "select", "{", "case", "<-", "sigCh", ":", "terminal", ".", "Restore", "(", "int", "(", "fd", ")", ",", "state", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "case", "<-", "closeCh", ":", "}", "\n", "}", "(", ")", "\n", "}", "\n", "defer", "func", "(", ")", "{", "close", "(", "closeCh", ")", "\n", "}", "(", ")", "\n\n", "bytes", ",", "err", ":=", "terminal", ".", "ReadPassword", "(", "int", "(", "fd", ")", ")", "\n", "return", "string", "(", "bytes", ")", ",", "err", "\n", "}" ]
// passwordFromConsole reads from stdin without echoing typed characters to stdout
[ "passwordFromConsole", "reads", "from", "stdin", "without", "echoing", "typed", "characters", "to", "stdout" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L1956-L1982
train
gravitational/teleport
lib/client/api.go
lineFromConsole
func lineFromConsole() (string, error) { bytes, _, err := bufio.NewReader(os.Stdin).ReadLine() return string(bytes), err }
go
func lineFromConsole() (string, error) { bytes, _, err := bufio.NewReader(os.Stdin).ReadLine() return string(bytes), err }
[ "func", "lineFromConsole", "(", ")", "(", "string", ",", "error", ")", "{", "bytes", ",", "_", ",", "err", ":=", "bufio", ".", "NewReader", "(", "os", ".", "Stdin", ")", ".", "ReadLine", "(", ")", "\n", "return", "string", "(", "bytes", ")", ",", "err", "\n", "}" ]
// lineFromConsole reads a line from stdin
[ "lineFromConsole", "reads", "a", "line", "from", "stdin" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L1985-L1988
train
gravitational/teleport
lib/client/api.go
String
func (fp DynamicForwardedPorts) String() (retval []string) { for _, p := range fp { retval = append(retval, p.ToString()) } return retval }
go
func (fp DynamicForwardedPorts) String() (retval []string) { for _, p := range fp { retval = append(retval, p.ToString()) } return retval }
[ "func", "(", "fp", "DynamicForwardedPorts", ")", "String", "(", ")", "(", "retval", "[", "]", "string", ")", "{", "for", "_", ",", "p", ":=", "range", "fp", "{", "retval", "=", "append", "(", "retval", ",", "p", ".", "ToString", "(", ")", ")", "\n", "}", "\n", "return", "retval", "\n", "}" ]
// String returns the same string spec which can be parsed by // ParseDynamicPortForwardSpec.
[ "String", "returns", "the", "same", "string", "spec", "which", "can", "be", "parsed", "by", "ParseDynamicPortForwardSpec", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L2097-L2102
train
gravitational/teleport
lib/client/api.go
InsecureSkipHostKeyChecking
func InsecureSkipHostKeyChecking(host string, remote net.Addr, key ssh.PublicKey) error { return nil }
go
func InsecureSkipHostKeyChecking(host string, remote net.Addr, key ssh.PublicKey) error { return nil }
[ "func", "InsecureSkipHostKeyChecking", "(", "host", "string", ",", "remote", "net", ".", "Addr", ",", "key", "ssh", ".", "PublicKey", ")", "error", "{", "return", "nil", "\n", "}" ]
// InsecureSkipHostKeyChecking is used when the user passes in // "StrictHostKeyChecking yes".
[ "InsecureSkipHostKeyChecking", "is", "used", "when", "the", "user", "passes", "in", "StrictHostKeyChecking", "yes", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/api.go#L2137-L2139
train
gravitational/teleport
lib/reversetunnel/conn.go
OpenChannel
func (c *remoteConn) OpenChannel(name string, data []byte) (ssh.Channel, error) { channel, _, err := c.sconn.OpenChannel(name, data) if err != nil { return nil, trace.Wrap(err) } return channel, nil }
go
func (c *remoteConn) OpenChannel(name string, data []byte) (ssh.Channel, error) { channel, _, err := c.sconn.OpenChannel(name, data) if err != nil { return nil, trace.Wrap(err) } return channel, nil }
[ "func", "(", "c", "*", "remoteConn", ")", "OpenChannel", "(", "name", "string", ",", "data", "[", "]", "byte", ")", "(", "ssh", ".", "Channel", ",", "error", ")", "{", "channel", ",", "_", ",", "err", ":=", "c", ".", "sconn", ".", "OpenChannel", "(", "name", ",", "data", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "return", "channel", ",", "nil", "\n", "}" ]
// OpenChannel will open a SSH channel to the remote side.
[ "OpenChannel", "will", "open", "a", "SSH", "channel", "to", "the", "remote", "side", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/conn.go#L149-L156
train
gravitational/teleport
lib/reversetunnel/conn.go
ChannelConn
func (c *remoteConn) ChannelConn(channel ssh.Channel) net.Conn { return utils.NewChConn(c.sconn, channel) }
go
func (c *remoteConn) ChannelConn(channel ssh.Channel) net.Conn { return utils.NewChConn(c.sconn, channel) }
[ "func", "(", "c", "*", "remoteConn", ")", "ChannelConn", "(", "channel", "ssh", ".", "Channel", ")", "net", ".", "Conn", "{", "return", "utils", ".", "NewChConn", "(", "c", ".", "sconn", ",", "channel", ")", "\n", "}" ]
// ChannelConn creates a net.Conn over a SSH channel.
[ "ChannelConn", "creates", "a", "net", ".", "Conn", "over", "a", "SSH", "channel", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/conn.go#L159-L161
train
gravitational/teleport
lib/reversetunnel/conn.go
findAndSend
func (c *remoteConn) findAndSend() error { // Find all proxies that don't have a connection to a remote agent. If all // proxies have connections, return right away. disconnectedProxies, err := c.findDisconnectedProxies() if err != nil { return trace.Wrap(err) } if len(disconnectedProxies) == 0 { return nil } c.log.Debugf("Proxy %v sending %v discovery request with tunnel ID: %v and disconnected proxies: %v.", c.proxyName, string(c.tunnelType), c.tunnelID, Proxies(disconnectedProxies)) req := discoveryRequest{ TunnelID: c.tunnelID, Type: string(c.tunnelType), Proxies: disconnectedProxies, } err = c.sendDiscoveryRequests(req) if err != nil { return trace.Wrap(err) } return nil }
go
func (c *remoteConn) findAndSend() error { // Find all proxies that don't have a connection to a remote agent. If all // proxies have connections, return right away. disconnectedProxies, err := c.findDisconnectedProxies() if err != nil { return trace.Wrap(err) } if len(disconnectedProxies) == 0 { return nil } c.log.Debugf("Proxy %v sending %v discovery request with tunnel ID: %v and disconnected proxies: %v.", c.proxyName, string(c.tunnelType), c.tunnelID, Proxies(disconnectedProxies)) req := discoveryRequest{ TunnelID: c.tunnelID, Type: string(c.tunnelType), Proxies: disconnectedProxies, } err = c.sendDiscoveryRequests(req) if err != nil { return trace.Wrap(err) } return nil }
[ "func", "(", "c", "*", "remoteConn", ")", "findAndSend", "(", ")", "error", "{", "// Find all proxies that don't have a connection to a remote agent. If all", "// proxies have connections, return right away.", "disconnectedProxies", ",", "err", ":=", "c", ".", "findDisconnectedProxies", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "len", "(", "disconnectedProxies", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "c", ".", "log", ".", "Debugf", "(", "\"", "\"", ",", "c", ".", "proxyName", ",", "string", "(", "c", ".", "tunnelType", ")", ",", "c", ".", "tunnelID", ",", "Proxies", "(", "disconnectedProxies", ")", ")", "\n\n", "req", ":=", "discoveryRequest", "{", "TunnelID", ":", "c", ".", "tunnelID", ",", "Type", ":", "string", "(", "c", ".", "tunnelType", ")", ",", "Proxies", ":", "disconnectedProxies", ",", "}", "\n\n", "err", "=", "c", ".", "sendDiscoveryRequests", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// sendDiscovery requests sends special "Discovery Requests" back to the // connected agent. Discovery request consists of the proxies that are part // of the cluster, but did not receive the connection from the agent. Agent // will act on a discovery request attempting to establish connection to the // proxies that were not discovered.
[ "sendDiscovery", "requests", "sends", "special", "Discovery", "Requests", "back", "to", "the", "connected", "agent", ".", "Discovery", "request", "consists", "of", "the", "proxies", "that", "are", "part", "of", "the", "cluster", "but", "did", "not", "receive", "the", "connection", "from", "the", "agent", ".", "Agent", "will", "act", "on", "a", "discovery", "request", "attempting", "to", "establish", "connection", "to", "the", "proxies", "that", "were", "not", "discovered", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/conn.go#L232-L258
train
gravitational/teleport
lib/reversetunnel/conn.go
findDisconnectedProxies
func (c *remoteConn) findDisconnectedProxies() ([]services.Server, error) { // Find all proxies that have connection from the remote domain. conns, err := c.accessPoint.GetTunnelConnections(c.clusterName, services.SkipValidation()) if err != nil { return nil, trace.Wrap(err) } connected := make(map[string]bool) for _, conn := range conns { if c.isOnline(conn) { connected[conn.GetProxyName()] = true } } // Build a list of local proxies that do not have a remote connection to them. var missing []services.Server proxies, err := c.accessPoint.GetProxies() if err != nil { return nil, trace.Wrap(err) } for i := range proxies { proxy := proxies[i] // A proxy should never add itself to the list of missing proxies. if proxy.GetName() == c.proxyName { continue } if !connected[proxy.GetName()] { missing = append(missing, proxy) } } return missing, nil }
go
func (c *remoteConn) findDisconnectedProxies() ([]services.Server, error) { // Find all proxies that have connection from the remote domain. conns, err := c.accessPoint.GetTunnelConnections(c.clusterName, services.SkipValidation()) if err != nil { return nil, trace.Wrap(err) } connected := make(map[string]bool) for _, conn := range conns { if c.isOnline(conn) { connected[conn.GetProxyName()] = true } } // Build a list of local proxies that do not have a remote connection to them. var missing []services.Server proxies, err := c.accessPoint.GetProxies() if err != nil { return nil, trace.Wrap(err) } for i := range proxies { proxy := proxies[i] // A proxy should never add itself to the list of missing proxies. if proxy.GetName() == c.proxyName { continue } if !connected[proxy.GetName()] { missing = append(missing, proxy) } } return missing, nil }
[ "func", "(", "c", "*", "remoteConn", ")", "findDisconnectedProxies", "(", ")", "(", "[", "]", "services", ".", "Server", ",", "error", ")", "{", "// Find all proxies that have connection from the remote domain.", "conns", ",", "err", ":=", "c", ".", "accessPoint", ".", "GetTunnelConnections", "(", "c", ".", "clusterName", ",", "services", ".", "SkipValidation", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "connected", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "for", "_", ",", "conn", ":=", "range", "conns", "{", "if", "c", ".", "isOnline", "(", "conn", ")", "{", "connected", "[", "conn", ".", "GetProxyName", "(", ")", "]", "=", "true", "\n", "}", "\n", "}", "\n\n", "// Build a list of local proxies that do not have a remote connection to them.", "var", "missing", "[", "]", "services", ".", "Server", "\n", "proxies", ",", "err", ":=", "c", ".", "accessPoint", ".", "GetProxies", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "for", "i", ":=", "range", "proxies", "{", "proxy", ":=", "proxies", "[", "i", "]", "\n\n", "// A proxy should never add itself to the list of missing proxies.", "if", "proxy", ".", "GetName", "(", ")", "==", "c", ".", "proxyName", "{", "continue", "\n", "}", "\n\n", "if", "!", "connected", "[", "proxy", ".", "GetName", "(", ")", "]", "{", "missing", "=", "append", "(", "missing", ",", "proxy", ")", "\n", "}", "\n", "}", "\n\n", "return", "missing", ",", "nil", "\n", "}" ]
// findDisconnectedProxies finds proxies that do not have inbound reverse tunnel // connections.
[ "findDisconnectedProxies", "finds", "proxies", "that", "do", "not", "have", "inbound", "reverse", "tunnel", "connections", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/conn.go#L262-L295
train
gravitational/teleport
lib/reversetunnel/conn.go
sendDiscoveryRequests
func (c *remoteConn) sendDiscoveryRequests(req discoveryRequest) error { discoveryCh, err := c.openDiscoveryChannel() if err != nil { return trace.Wrap(err) } // Marshal and send the request. If the connection failed, mark the // connection as invalid so it will be removed later. payload, err := marshalDiscoveryRequest(req) if err != nil { return trace.Wrap(err) } _, err = discoveryCh.SendRequest(chanDiscoveryReq, false, payload) if err != nil { c.markInvalid(err) return trace.Wrap(err) } return nil }
go
func (c *remoteConn) sendDiscoveryRequests(req discoveryRequest) error { discoveryCh, err := c.openDiscoveryChannel() if err != nil { return trace.Wrap(err) } // Marshal and send the request. If the connection failed, mark the // connection as invalid so it will be removed later. payload, err := marshalDiscoveryRequest(req) if err != nil { return trace.Wrap(err) } _, err = discoveryCh.SendRequest(chanDiscoveryReq, false, payload) if err != nil { c.markInvalid(err) return trace.Wrap(err) } return nil }
[ "func", "(", "c", "*", "remoteConn", ")", "sendDiscoveryRequests", "(", "req", "discoveryRequest", ")", "error", "{", "discoveryCh", ",", "err", ":=", "c", ".", "openDiscoveryChannel", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "// Marshal and send the request. If the connection failed, mark the", "// connection as invalid so it will be removed later.", "payload", ",", "err", ":=", "marshalDiscoveryRequest", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "_", ",", "err", "=", "discoveryCh", ".", "SendRequest", "(", "chanDiscoveryReq", ",", "false", ",", "payload", ")", "\n", "if", "err", "!=", "nil", "{", "c", ".", "markInvalid", "(", "err", ")", "\n", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// sendDiscoveryRequests sends a discovery request with missing proxies.
[ "sendDiscoveryRequests", "sends", "a", "discovery", "request", "with", "missing", "proxies", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/conn.go#L298-L317
train
gravitational/teleport
lib/reversetunnel/conn.go
TunnelAuthDialer
func TunnelAuthDialer(proxyAddr string, sshConfig *ssh.ClientConfig) auth.DialContext { return func(ctx context.Context, network string, addr string) (net.Conn, error) { // Connect to the reverse tunnel server. dialer := proxy.DialerFromEnvironment(proxyAddr) sconn, err := dialer.Dial("tcp", proxyAddr, sshConfig) if err != nil { return nil, trace.Wrap(err) } conn, err := connectProxyTransport(sconn.Conn, RemoteAuthServer) if err != nil { return nil, trace.Wrap(err) } return conn, nil } }
go
func TunnelAuthDialer(proxyAddr string, sshConfig *ssh.ClientConfig) auth.DialContext { return func(ctx context.Context, network string, addr string) (net.Conn, error) { // Connect to the reverse tunnel server. dialer := proxy.DialerFromEnvironment(proxyAddr) sconn, err := dialer.Dial("tcp", proxyAddr, sshConfig) if err != nil { return nil, trace.Wrap(err) } conn, err := connectProxyTransport(sconn.Conn, RemoteAuthServer) if err != nil { return nil, trace.Wrap(err) } return conn, nil } }
[ "func", "TunnelAuthDialer", "(", "proxyAddr", "string", ",", "sshConfig", "*", "ssh", ".", "ClientConfig", ")", "auth", ".", "DialContext", "{", "return", "func", "(", "ctx", "context", ".", "Context", ",", "network", "string", ",", "addr", "string", ")", "(", "net", ".", "Conn", ",", "error", ")", "{", "// Connect to the reverse tunnel server.", "dialer", ":=", "proxy", ".", "DialerFromEnvironment", "(", "proxyAddr", ")", "\n", "sconn", ",", "err", ":=", "dialer", ".", "Dial", "(", "\"", "\"", ",", "proxyAddr", ",", "sshConfig", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "conn", ",", "err", ":=", "connectProxyTransport", "(", "sconn", ".", "Conn", ",", "RemoteAuthServer", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "conn", ",", "nil", "\n", "}", "\n", "}" ]
// TunnelAuthDialer connects to the Auth Server through the reverse tunnel.
[ "TunnelAuthDialer", "connects", "to", "the", "Auth", "Server", "through", "the", "reverse", "tunnel", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/conn.go#L341-L356
train
gravitational/teleport
lib/reversetunnel/conn.go
connectProxyTransport
func connectProxyTransport(sconn ssh.Conn, addr string) (net.Conn, error) { channel, _, err := sconn.OpenChannel(chanTransport, nil) if err != nil { return nil, trace.Wrap(err) } // Send a special SSH out-of-band request called "teleport-transport" // the agent on the other side will create a new TCP/IP connection to // 'addr' on its network and will start proxying that connection over // this SSH channel. ok, err := channel.SendRequest(chanTransportDialReq, true, []byte(addr)) if err != nil { return nil, trace.Wrap(err) } if !ok { defer channel.Close() // Pull the error message from the tunnel client (remote cluster) // passed to us via stderr. errMessage, _ := ioutil.ReadAll(channel.Stderr()) if errMessage == nil { errMessage = []byte("failed connecting to " + addr) } return nil, trace.Errorf(strings.TrimSpace(string(errMessage))) } return utils.NewChConn(sconn, channel), nil }
go
func connectProxyTransport(sconn ssh.Conn, addr string) (net.Conn, error) { channel, _, err := sconn.OpenChannel(chanTransport, nil) if err != nil { return nil, trace.Wrap(err) } // Send a special SSH out-of-band request called "teleport-transport" // the agent on the other side will create a new TCP/IP connection to // 'addr' on its network and will start proxying that connection over // this SSH channel. ok, err := channel.SendRequest(chanTransportDialReq, true, []byte(addr)) if err != nil { return nil, trace.Wrap(err) } if !ok { defer channel.Close() // Pull the error message from the tunnel client (remote cluster) // passed to us via stderr. errMessage, _ := ioutil.ReadAll(channel.Stderr()) if errMessage == nil { errMessage = []byte("failed connecting to " + addr) } return nil, trace.Errorf(strings.TrimSpace(string(errMessage))) } return utils.NewChConn(sconn, channel), nil }
[ "func", "connectProxyTransport", "(", "sconn", "ssh", ".", "Conn", ",", "addr", "string", ")", "(", "net", ".", "Conn", ",", "error", ")", "{", "channel", ",", "_", ",", "err", ":=", "sconn", ".", "OpenChannel", "(", "chanTransport", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "// Send a special SSH out-of-band request called \"teleport-transport\"", "// the agent on the other side will create a new TCP/IP connection to", "// 'addr' on its network and will start proxying that connection over", "// this SSH channel.", "ok", ",", "err", ":=", "channel", ".", "SendRequest", "(", "chanTransportDialReq", ",", "true", ",", "[", "]", "byte", "(", "addr", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "!", "ok", "{", "defer", "channel", ".", "Close", "(", ")", "\n\n", "// Pull the error message from the tunnel client (remote cluster)", "// passed to us via stderr.", "errMessage", ",", "_", ":=", "ioutil", ".", "ReadAll", "(", "channel", ".", "Stderr", "(", ")", ")", "\n", "if", "errMessage", "==", "nil", "{", "errMessage", "=", "[", "]", "byte", "(", "\"", "\"", "+", "addr", ")", "\n", "}", "\n", "return", "nil", ",", "trace", ".", "Errorf", "(", "strings", ".", "TrimSpace", "(", "string", "(", "errMessage", ")", ")", ")", "\n", "}", "\n\n", "return", "utils", ".", "NewChConn", "(", "sconn", ",", "channel", ")", ",", "nil", "\n", "}" ]
// connectProxyTransport opens a channel over the remote tunnel and connects // to the requested host.
[ "connectProxyTransport", "opens", "a", "channel", "over", "the", "remote", "tunnel", "and", "connects", "to", "the", "requested", "host", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/conn.go#L360-L387
train
gravitational/teleport
lib/service/service.go
Close
func (c *Connector) Close() error { if c.Client != nil { return c.Close() } return nil }
go
func (c *Connector) Close() error { if c.Client != nil { return c.Close() } return nil }
[ "func", "(", "c", "*", "Connector", ")", "Close", "(", ")", "error", "{", "if", "c", ".", "Client", "!=", "nil", "{", "return", "c", ".", "Close", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Close closes resources associated with connector
[ "Close", "closes", "resources", "associated", "with", "connector" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/service.go#L179-L184
train
gravitational/teleport
lib/service/service.go
getConnectors
func (process *TeleportProcess) getConnectors() []*Connector { process.Lock() defer process.Unlock() out := make([]*Connector, 0, len(process.connectors)) for role := range process.connectors { out = append(out, process.connectors[role]) } return out }
go
func (process *TeleportProcess) getConnectors() []*Connector { process.Lock() defer process.Unlock() out := make([]*Connector, 0, len(process.connectors)) for role := range process.connectors { out = append(out, process.connectors[role]) } return out }
[ "func", "(", "process", "*", "TeleportProcess", ")", "getConnectors", "(", ")", "[", "]", "*", "Connector", "{", "process", ".", "Lock", "(", ")", "\n", "defer", "process", ".", "Unlock", "(", ")", "\n\n", "out", ":=", "make", "(", "[", "]", "*", "Connector", ",", "0", ",", "len", "(", "process", ".", "connectors", ")", ")", "\n", "for", "role", ":=", "range", "process", ".", "connectors", "{", "out", "=", "append", "(", "out", ",", "process", ".", "connectors", "[", "role", "]", ")", "\n", "}", "\n", "return", "out", "\n", "}" ]
// getConnectors returns a copy of the identities registered for auth server
[ "getConnectors", "returns", "a", "copy", "of", "the", "identities", "registered", "for", "auth", "server" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/service.go#L279-L288
train
gravitational/teleport
lib/service/service.go
addConnector
func (process *TeleportProcess) addConnector(connector *Connector) { process.Lock() defer process.Unlock() process.connectors[connector.ClientIdentity.ID.Role] = connector }
go
func (process *TeleportProcess) addConnector(connector *Connector) { process.Lock() defer process.Unlock() process.connectors[connector.ClientIdentity.ID.Role] = connector }
[ "func", "(", "process", "*", "TeleportProcess", ")", "addConnector", "(", "connector", "*", "Connector", ")", "{", "process", ".", "Lock", "(", ")", "\n", "defer", "process", ".", "Unlock", "(", ")", "\n\n", "process", ".", "connectors", "[", "connector", ".", "ClientIdentity", ".", "ID", ".", "Role", "]", "=", "connector", "\n", "}" ]
// addConnector adds connector to registered connectors list, // it will overwrite the connector for the same role
[ "addConnector", "adds", "connector", "to", "registered", "connectors", "list", "it", "will", "overwrite", "the", "connector", "for", "the", "same", "role" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/service.go#L292-L297
train
gravitational/teleport
lib/service/service.go
Run
func Run(ctx context.Context, cfg Config, newTeleport NewProcess) error { if newTeleport == nil { newTeleport = newTeleportProcess } copyCfg := cfg srv, err := newTeleport(&copyCfg) if err != nil { return trace.Wrap(err, "initialization failed") } if srv == nil { return trace.BadParameter("process has returned nil server") } if err := srv.Start(); err != nil { return trace.Wrap(err, "startup failed") } // Wait and reload until called exit. for { srv, err = waitAndReload(ctx, cfg, srv, newTeleport) if err != nil { // This error means that was a clean shutdown // and no reload is necessary. if err == ErrTeleportExited { return nil } return trace.Wrap(err) } } }
go
func Run(ctx context.Context, cfg Config, newTeleport NewProcess) error { if newTeleport == nil { newTeleport = newTeleportProcess } copyCfg := cfg srv, err := newTeleport(&copyCfg) if err != nil { return trace.Wrap(err, "initialization failed") } if srv == nil { return trace.BadParameter("process has returned nil server") } if err := srv.Start(); err != nil { return trace.Wrap(err, "startup failed") } // Wait and reload until called exit. for { srv, err = waitAndReload(ctx, cfg, srv, newTeleport) if err != nil { // This error means that was a clean shutdown // and no reload is necessary. if err == ErrTeleportExited { return nil } return trace.Wrap(err) } } }
[ "func", "Run", "(", "ctx", "context", ".", "Context", ",", "cfg", "Config", ",", "newTeleport", "NewProcess", ")", "error", "{", "if", "newTeleport", "==", "nil", "{", "newTeleport", "=", "newTeleportProcess", "\n", "}", "\n", "copyCfg", ":=", "cfg", "\n", "srv", ",", "err", ":=", "newTeleport", "(", "&", "copyCfg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "srv", "==", "nil", "{", "return", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "err", ":=", "srv", ".", "Start", "(", ")", ";", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "// Wait and reload until called exit.", "for", "{", "srv", ",", "err", "=", "waitAndReload", "(", "ctx", ",", "cfg", ",", "srv", ",", "newTeleport", ")", "\n", "if", "err", "!=", "nil", "{", "// This error means that was a clean shutdown", "// and no reload is necessary.", "if", "err", "==", "ErrTeleportExited", "{", "return", "nil", "\n", "}", "\n", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Run starts teleport processes, waits for signals // and handles internal process reloads.
[ "Run", "starts", "teleport", "processes", "waits", "for", "signals", "and", "handles", "internal", "process", "reloads", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/service.go#L379-L406
train
gravitational/teleport
lib/service/service.go
notifyParent
func (process *TeleportProcess) notifyParent() { signalPipe, err := process.importSignalPipe() if err != nil { if !trace.IsNotFound(err) { process.Warningf("Failed to import signal pipe") } process.Debugf("No signal pipe to import, must be first Teleport process.") return } defer signalPipe.Close() ctx, cancel := context.WithTimeout(process.ExitContext(), signalPipeTimeout) defer cancel() eventC := make(chan Event, 1) process.WaitForEvent(ctx, TeleportReadyEvent, eventC) select { case <-eventC: process.Infof("New service has started successfully.") case <-ctx.Done(): process.Errorf("Timeout waiting for a forked process to start: %v. Initiating self-shutdown.", ctx.Err()) if err := process.Close(); err != nil { process.Warningf("Failed to shutdown process: %v.", err) } return } if err := process.writeToSignalPipe(signalPipe, fmt.Sprintf("Process %v has started.", os.Getpid())); err != nil { process.Warningf("Failed to write to signal pipe: %v", err) // despite the failure, it's ok to proceed, // it could mean that the parent process has crashed and the pipe // is no longer valid. } }
go
func (process *TeleportProcess) notifyParent() { signalPipe, err := process.importSignalPipe() if err != nil { if !trace.IsNotFound(err) { process.Warningf("Failed to import signal pipe") } process.Debugf("No signal pipe to import, must be first Teleport process.") return } defer signalPipe.Close() ctx, cancel := context.WithTimeout(process.ExitContext(), signalPipeTimeout) defer cancel() eventC := make(chan Event, 1) process.WaitForEvent(ctx, TeleportReadyEvent, eventC) select { case <-eventC: process.Infof("New service has started successfully.") case <-ctx.Done(): process.Errorf("Timeout waiting for a forked process to start: %v. Initiating self-shutdown.", ctx.Err()) if err := process.Close(); err != nil { process.Warningf("Failed to shutdown process: %v.", err) } return } if err := process.writeToSignalPipe(signalPipe, fmt.Sprintf("Process %v has started.", os.Getpid())); err != nil { process.Warningf("Failed to write to signal pipe: %v", err) // despite the failure, it's ok to proceed, // it could mean that the parent process has crashed and the pipe // is no longer valid. } }
[ "func", "(", "process", "*", "TeleportProcess", ")", "notifyParent", "(", ")", "{", "signalPipe", ",", "err", ":=", "process", ".", "importSignalPipe", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "!", "trace", ".", "IsNotFound", "(", "err", ")", "{", "process", ".", "Warningf", "(", "\"", "\"", ")", "\n", "}", "\n", "process", ".", "Debugf", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "defer", "signalPipe", ".", "Close", "(", ")", "\n\n", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "process", ".", "ExitContext", "(", ")", ",", "signalPipeTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n\n", "eventC", ":=", "make", "(", "chan", "Event", ",", "1", ")", "\n", "process", ".", "WaitForEvent", "(", "ctx", ",", "TeleportReadyEvent", ",", "eventC", ")", "\n", "select", "{", "case", "<-", "eventC", ":", "process", ".", "Infof", "(", "\"", "\"", ")", "\n", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "process", ".", "Errorf", "(", "\"", "\"", ",", "ctx", ".", "Err", "(", ")", ")", "\n", "if", "err", ":=", "process", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "process", ".", "Warningf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "\n", "}", "\n\n", "if", "err", ":=", "process", ".", "writeToSignalPipe", "(", "signalPipe", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "os", ".", "Getpid", "(", ")", ")", ")", ";", "err", "!=", "nil", "{", "process", ".", "Warningf", "(", "\"", "\"", ",", "err", ")", "\n", "// despite the failure, it's ok to proceed,", "// it could mean that the parent process has crashed and the pipe", "// is no longer valid.", "}", "\n", "}" ]
// notifyParent notifies parent process that this process has started // by writing to in-memory pipe used by communication channel.
[ "notifyParent", "notifies", "parent", "process", "that", "this", "process", "has", "started", "by", "writing", "to", "in", "-", "memory", "pipe", "used", "by", "communication", "channel", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/service.go#L666-L699
train
gravitational/teleport
lib/service/service.go
adminCreds
func adminCreds() (*int, *int, error) { if runtime.GOOS != teleport.LinuxOS { return nil, nil, nil } // if the user member of adm linux group, // make audit log folder readable by admins isAdmin, err := utils.IsGroupMember(teleport.LinuxAdminGID) if err != nil { return nil, nil, trace.Wrap(err) } if !isAdmin { return nil, nil, nil } uid := os.Getuid() gid := teleport.LinuxAdminGID return &uid, &gid, nil }
go
func adminCreds() (*int, *int, error) { if runtime.GOOS != teleport.LinuxOS { return nil, nil, nil } // if the user member of adm linux group, // make audit log folder readable by admins isAdmin, err := utils.IsGroupMember(teleport.LinuxAdminGID) if err != nil { return nil, nil, trace.Wrap(err) } if !isAdmin { return nil, nil, nil } uid := os.Getuid() gid := teleport.LinuxAdminGID return &uid, &gid, nil }
[ "func", "adminCreds", "(", ")", "(", "*", "int", ",", "*", "int", ",", "error", ")", "{", "if", "runtime", ".", "GOOS", "!=", "teleport", ".", "LinuxOS", "{", "return", "nil", ",", "nil", ",", "nil", "\n", "}", "\n", "// if the user member of adm linux group,", "// make audit log folder readable by admins", "isAdmin", ",", "err", ":=", "utils", ".", "IsGroupMember", "(", "teleport", ".", "LinuxAdminGID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "!", "isAdmin", "{", "return", "nil", ",", "nil", ",", "nil", "\n", "}", "\n", "uid", ":=", "os", ".", "Getuid", "(", ")", "\n", "gid", ":=", "teleport", ".", "LinuxAdminGID", "\n", "return", "&", "uid", ",", "&", "gid", ",", "nil", "\n", "}" ]
// adminCreds returns admin UID and GID settings based on the OS
[ "adminCreds", "returns", "admin", "UID", "and", "GID", "settings", "based", "on", "the", "OS" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/service.go#L714-L730
train
gravitational/teleport
lib/service/service.go
initUploadHandler
func initUploadHandler(auditConfig services.AuditConfig) (events.UploadHandler, error) { if auditConfig.AuditSessionsURI == "" { return nil, trace.NotFound("no upload handler is setup") } uri, err := utils.ParseSessionsURI(auditConfig.AuditSessionsURI) if err != nil { return nil, trace.Wrap(err) } switch uri.Scheme { case teleport.SchemeS3: region := auditConfig.Region if uriRegion := uri.Query().Get(teleport.Region); uriRegion != "" { region = uriRegion } handler, err := s3sessions.NewHandler(s3sessions.Config{ Bucket: uri.Host, Region: region, Path: uri.Path, }) if err != nil { return nil, trace.Wrap(err) } return handler, nil case teleport.SchemeFile: if err := os.MkdirAll(uri.Path, teleport.SharedDirMode); err != nil { return nil, trace.ConvertSystemError(err) } handler, err := filesessions.NewHandler(filesessions.Config{ Directory: uri.Path, }) if err != nil { return nil, trace.Wrap(err) } return handler, nil default: return nil, trace.BadParameter( "unsupported scheme for audit_sesions_uri: %q, currently supported schemes are %q and %q", uri.Scheme, teleport.SchemeS3, teleport.SchemeFile) } }
go
func initUploadHandler(auditConfig services.AuditConfig) (events.UploadHandler, error) { if auditConfig.AuditSessionsURI == "" { return nil, trace.NotFound("no upload handler is setup") } uri, err := utils.ParseSessionsURI(auditConfig.AuditSessionsURI) if err != nil { return nil, trace.Wrap(err) } switch uri.Scheme { case teleport.SchemeS3: region := auditConfig.Region if uriRegion := uri.Query().Get(teleport.Region); uriRegion != "" { region = uriRegion } handler, err := s3sessions.NewHandler(s3sessions.Config{ Bucket: uri.Host, Region: region, Path: uri.Path, }) if err != nil { return nil, trace.Wrap(err) } return handler, nil case teleport.SchemeFile: if err := os.MkdirAll(uri.Path, teleport.SharedDirMode); err != nil { return nil, trace.ConvertSystemError(err) } handler, err := filesessions.NewHandler(filesessions.Config{ Directory: uri.Path, }) if err != nil { return nil, trace.Wrap(err) } return handler, nil default: return nil, trace.BadParameter( "unsupported scheme for audit_sesions_uri: %q, currently supported schemes are %q and %q", uri.Scheme, teleport.SchemeS3, teleport.SchemeFile) } }
[ "func", "initUploadHandler", "(", "auditConfig", "services", ".", "AuditConfig", ")", "(", "events", ".", "UploadHandler", ",", "error", ")", "{", "if", "auditConfig", ".", "AuditSessionsURI", "==", "\"", "\"", "{", "return", "nil", ",", "trace", ".", "NotFound", "(", "\"", "\"", ")", "\n", "}", "\n", "uri", ",", "err", ":=", "utils", ".", "ParseSessionsURI", "(", "auditConfig", ".", "AuditSessionsURI", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "switch", "uri", ".", "Scheme", "{", "case", "teleport", ".", "SchemeS3", ":", "region", ":=", "auditConfig", ".", "Region", "\n", "if", "uriRegion", ":=", "uri", ".", "Query", "(", ")", ".", "Get", "(", "teleport", ".", "Region", ")", ";", "uriRegion", "!=", "\"", "\"", "{", "region", "=", "uriRegion", "\n", "}", "\n", "handler", ",", "err", ":=", "s3sessions", ".", "NewHandler", "(", "s3sessions", ".", "Config", "{", "Bucket", ":", "uri", ".", "Host", ",", "Region", ":", "region", ",", "Path", ":", "uri", ".", "Path", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "handler", ",", "nil", "\n", "case", "teleport", ".", "SchemeFile", ":", "if", "err", ":=", "os", ".", "MkdirAll", "(", "uri", ".", "Path", ",", "teleport", ".", "SharedDirMode", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "ConvertSystemError", "(", "err", ")", "\n", "}", "\n", "handler", ",", "err", ":=", "filesessions", ".", "NewHandler", "(", "filesessions", ".", "Config", "{", "Directory", ":", "uri", ".", "Path", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "handler", ",", "nil", "\n", "default", ":", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ",", "uri", ".", "Scheme", ",", "teleport", ".", "SchemeS3", ",", "teleport", ".", "SchemeFile", ")", "\n", "}", "\n", "}" ]
// initUploadHandler initializes upload handler based on the config settings, // currently the only upload handler supported is S3 // the call can return trace.NotFOund if no upload handler is setup
[ "initUploadHandler", "initializes", "upload", "handler", "based", "on", "the", "config", "settings", "currently", "the", "only", "upload", "handler", "supported", "is", "S3", "the", "call", "can", "return", "trace", ".", "NotFOund", "if", "no", "upload", "handler", "is", "setup" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/service.go#L735-L775
train
gravitational/teleport
lib/service/service.go
initExternalLog
func initExternalLog(auditConfig services.AuditConfig) (events.IAuditLog, error) { if auditConfig.AuditTableName != "" { log.Warningf("Please note that 'audit_table_name' is deprecated and will be removed in several releases. Use audit_events_uri: '%v://%v' instead.", dynamo.GetName(), auditConfig.AuditTableName) if len(auditConfig.AuditEventsURI) != 0 { return nil, trace.BadParameter("Detected configuration specifying 'audit_table_name' and 'audit_events_uri' at the same time. Please migrate your config to use 'audit_events_uri' only.") } auditConfig.AuditEventsURI = []string{fmt.Sprintf("%v://%v", dynamo.GetName(), auditConfig.AuditTableName)} } if len(auditConfig.AuditEventsURI) > 0 && !auditConfig.ShouldUploadSessions() { return nil, trace.BadParameter("please specify audit_sessions_uri when using external audit backends") } var hasNonFileLog bool var loggers []events.IAuditLog for _, eventsURI := range auditConfig.AuditEventsURI { uri, err := utils.ParseSessionsURI(eventsURI) if err != nil { return nil, trace.Wrap(err) } switch uri.Scheme { case dynamo.GetName(): hasNonFileLog = true logger, err := dynamoevents.New(dynamoevents.Config{ Tablename: uri.Host, Region: auditConfig.Region, }) if err != nil { return nil, trace.Wrap(err) } loggers = append(loggers, logger) case teleport.SchemeFile: if err := os.MkdirAll(uri.Path, teleport.SharedDirMode); err != nil { return nil, trace.ConvertSystemError(err) } logger, err := events.NewFileLog(events.FileLogConfig{ Dir: uri.Path, }) if err != nil { return nil, trace.Wrap(err) } loggers = append(loggers, logger) default: return nil, trace.BadParameter( "unsupported scheme for audit_events_uri: %q, currently supported schemes are %q and %q", uri.Scheme, dynamo.GetName(), teleport.SchemeFile) } } // only file external loggers are prohibited (they are not supposed // to be used on their own, only in combo with external loggers) // they also don't implement certain features, so they are going // to be inefficient switch len(loggers) { case 0: return nil, trace.NotFound("no external log is defined") case 1: if !hasNonFileLog { return nil, trace.BadParameter("file:// log can not be used on it's own, can be only used in combination with external session logs, e.g. dynamodb://") } return loggers[0], nil default: if !hasNonFileLog { return nil, trace.BadParameter("file:// log can not be used on it's own, can be only used in combination with external session logs, e.g. dynamodb://") } return events.NewMultiLog(loggers...), nil } }
go
func initExternalLog(auditConfig services.AuditConfig) (events.IAuditLog, error) { if auditConfig.AuditTableName != "" { log.Warningf("Please note that 'audit_table_name' is deprecated and will be removed in several releases. Use audit_events_uri: '%v://%v' instead.", dynamo.GetName(), auditConfig.AuditTableName) if len(auditConfig.AuditEventsURI) != 0 { return nil, trace.BadParameter("Detected configuration specifying 'audit_table_name' and 'audit_events_uri' at the same time. Please migrate your config to use 'audit_events_uri' only.") } auditConfig.AuditEventsURI = []string{fmt.Sprintf("%v://%v", dynamo.GetName(), auditConfig.AuditTableName)} } if len(auditConfig.AuditEventsURI) > 0 && !auditConfig.ShouldUploadSessions() { return nil, trace.BadParameter("please specify audit_sessions_uri when using external audit backends") } var hasNonFileLog bool var loggers []events.IAuditLog for _, eventsURI := range auditConfig.AuditEventsURI { uri, err := utils.ParseSessionsURI(eventsURI) if err != nil { return nil, trace.Wrap(err) } switch uri.Scheme { case dynamo.GetName(): hasNonFileLog = true logger, err := dynamoevents.New(dynamoevents.Config{ Tablename: uri.Host, Region: auditConfig.Region, }) if err != nil { return nil, trace.Wrap(err) } loggers = append(loggers, logger) case teleport.SchemeFile: if err := os.MkdirAll(uri.Path, teleport.SharedDirMode); err != nil { return nil, trace.ConvertSystemError(err) } logger, err := events.NewFileLog(events.FileLogConfig{ Dir: uri.Path, }) if err != nil { return nil, trace.Wrap(err) } loggers = append(loggers, logger) default: return nil, trace.BadParameter( "unsupported scheme for audit_events_uri: %q, currently supported schemes are %q and %q", uri.Scheme, dynamo.GetName(), teleport.SchemeFile) } } // only file external loggers are prohibited (they are not supposed // to be used on their own, only in combo with external loggers) // they also don't implement certain features, so they are going // to be inefficient switch len(loggers) { case 0: return nil, trace.NotFound("no external log is defined") case 1: if !hasNonFileLog { return nil, trace.BadParameter("file:// log can not be used on it's own, can be only used in combination with external session logs, e.g. dynamodb://") } return loggers[0], nil default: if !hasNonFileLog { return nil, trace.BadParameter("file:// log can not be used on it's own, can be only used in combination with external session logs, e.g. dynamodb://") } return events.NewMultiLog(loggers...), nil } }
[ "func", "initExternalLog", "(", "auditConfig", "services", ".", "AuditConfig", ")", "(", "events", ".", "IAuditLog", ",", "error", ")", "{", "if", "auditConfig", ".", "AuditTableName", "!=", "\"", "\"", "{", "log", ".", "Warningf", "(", "\"", "\"", ",", "dynamo", ".", "GetName", "(", ")", ",", "auditConfig", ".", "AuditTableName", ")", "\n", "if", "len", "(", "auditConfig", ".", "AuditEventsURI", ")", "!=", "0", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "auditConfig", ".", "AuditEventsURI", "=", "[", "]", "string", "{", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "dynamo", ".", "GetName", "(", ")", ",", "auditConfig", ".", "AuditTableName", ")", "}", "\n", "}", "\n", "if", "len", "(", "auditConfig", ".", "AuditEventsURI", ")", ">", "0", "&&", "!", "auditConfig", ".", "ShouldUploadSessions", "(", ")", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "var", "hasNonFileLog", "bool", "\n", "var", "loggers", "[", "]", "events", ".", "IAuditLog", "\n", "for", "_", ",", "eventsURI", ":=", "range", "auditConfig", ".", "AuditEventsURI", "{", "uri", ",", "err", ":=", "utils", ".", "ParseSessionsURI", "(", "eventsURI", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "switch", "uri", ".", "Scheme", "{", "case", "dynamo", ".", "GetName", "(", ")", ":", "hasNonFileLog", "=", "true", "\n", "logger", ",", "err", ":=", "dynamoevents", ".", "New", "(", "dynamoevents", ".", "Config", "{", "Tablename", ":", "uri", ".", "Host", ",", "Region", ":", "auditConfig", ".", "Region", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "loggers", "=", "append", "(", "loggers", ",", "logger", ")", "\n", "case", "teleport", ".", "SchemeFile", ":", "if", "err", ":=", "os", ".", "MkdirAll", "(", "uri", ".", "Path", ",", "teleport", ".", "SharedDirMode", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "ConvertSystemError", "(", "err", ")", "\n", "}", "\n", "logger", ",", "err", ":=", "events", ".", "NewFileLog", "(", "events", ".", "FileLogConfig", "{", "Dir", ":", "uri", ".", "Path", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "loggers", "=", "append", "(", "loggers", ",", "logger", ")", "\n", "default", ":", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ",", "uri", ".", "Scheme", ",", "dynamo", ".", "GetName", "(", ")", ",", "teleport", ".", "SchemeFile", ")", "\n", "}", "\n", "}", "\n", "// only file external loggers are prohibited (they are not supposed", "// to be used on their own, only in combo with external loggers)", "// they also don't implement certain features, so they are going", "// to be inefficient", "switch", "len", "(", "loggers", ")", "{", "case", "0", ":", "return", "nil", ",", "trace", ".", "NotFound", "(", "\"", "\"", ")", "\n", "case", "1", ":", "if", "!", "hasNonFileLog", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "loggers", "[", "0", "]", ",", "nil", "\n", "default", ":", "if", "!", "hasNonFileLog", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "events", ".", "NewMultiLog", "(", "loggers", "...", ")", ",", "nil", "\n", "}", "\n", "}" ]
// initExternalLog initializes external storage, if the storage is not // setup, returns nil
[ "initExternalLog", "initializes", "external", "storage", "if", "the", "storage", "is", "not", "setup", "returns", "nil" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/service.go#L779-L843
train
gravitational/teleport
lib/service/service.go
onExit
func (process *TeleportProcess) onExit(serviceName string, callback func(interface{})) { process.RegisterFunc(serviceName, func() error { eventC := make(chan Event) process.WaitForEvent(context.TODO(), TeleportExitEvent, eventC) select { case event := <-eventC: callback(event.Payload) } return nil }) }
go
func (process *TeleportProcess) onExit(serviceName string, callback func(interface{})) { process.RegisterFunc(serviceName, func() error { eventC := make(chan Event) process.WaitForEvent(context.TODO(), TeleportExitEvent, eventC) select { case event := <-eventC: callback(event.Payload) } return nil }) }
[ "func", "(", "process", "*", "TeleportProcess", ")", "onExit", "(", "serviceName", "string", ",", "callback", "func", "(", "interface", "{", "}", ")", ")", "{", "process", ".", "RegisterFunc", "(", "serviceName", ",", "func", "(", ")", "error", "{", "eventC", ":=", "make", "(", "chan", "Event", ")", "\n", "process", ".", "WaitForEvent", "(", "context", ".", "TODO", "(", ")", ",", "TeleportExitEvent", ",", "eventC", ")", "\n", "select", "{", "case", "event", ":=", "<-", "eventC", ":", "callback", "(", "event", ".", "Payload", ")", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "}" ]
// onExit allows individual services to register a callback function which will be // called when Teleport Process is asked to exit. Usually services terminate themselves // when the callback is called
[ "onExit", "allows", "individual", "services", "to", "register", "a", "callback", "function", "which", "will", "be", "called", "when", "Teleport", "Process", "is", "asked", "to", "exit", ".", "Usually", "services", "terminate", "themselves", "when", "the", "callback", "is", "called" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/service.go#L1160-L1170
train
gravitational/teleport
lib/service/service.go
newAccessCache
func (process *TeleportProcess) newAccessCache(cfg accessCacheConfig) (*cache.Cache, error) { if err := cfg.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } var cacheBackend backend.Backend if cfg.inMemory { mem, err := memory.New(memory.Config{ Context: process.ExitContext(), EventsOff: !cfg.events, Mirror: true, }) if err != nil { return nil, trace.Wrap(err) } cacheBackend = mem } else { path := filepath.Join(append([]string{process.Config.DataDir, "cache"}, cfg.cacheName...)...) if err := os.MkdirAll(path, teleport.SharedDirMode); err != nil { return nil, trace.ConvertSystemError(err) } liteBackend, err := lite.NewWithConfig(process.ExitContext(), lite.Config{ Path: path, EventsOff: !cfg.events, Memory: false, Mirror: true, PollStreamPeriod: 100 * time.Millisecond, }) if err != nil { return nil, trace.Wrap(err) } cacheBackend = liteBackend } reporter, err := backend.NewReporter(backend.ReporterConfig{ Component: teleport.ComponentCache, Backend: cacheBackend, TrackTopRequests: process.Config.Debug, }) if err != nil { return nil, trace.Wrap(err) } return cache.New(cfg.setup(cache.Config{ Context: process.ExitContext(), Backend: reporter, Events: cfg.services, ClusterConfig: cfg.services, Provisioner: cfg.services, Trust: cfg.services, Users: cfg.services, Access: cfg.services, Presence: cfg.services, Component: teleport.Component(append(cfg.cacheName, process.id, teleport.ComponentCache)...), MetricComponent: teleport.Component(append(cfg.cacheName, teleport.ComponentCache)...), })) }
go
func (process *TeleportProcess) newAccessCache(cfg accessCacheConfig) (*cache.Cache, error) { if err := cfg.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } var cacheBackend backend.Backend if cfg.inMemory { mem, err := memory.New(memory.Config{ Context: process.ExitContext(), EventsOff: !cfg.events, Mirror: true, }) if err != nil { return nil, trace.Wrap(err) } cacheBackend = mem } else { path := filepath.Join(append([]string{process.Config.DataDir, "cache"}, cfg.cacheName...)...) if err := os.MkdirAll(path, teleport.SharedDirMode); err != nil { return nil, trace.ConvertSystemError(err) } liteBackend, err := lite.NewWithConfig(process.ExitContext(), lite.Config{ Path: path, EventsOff: !cfg.events, Memory: false, Mirror: true, PollStreamPeriod: 100 * time.Millisecond, }) if err != nil { return nil, trace.Wrap(err) } cacheBackend = liteBackend } reporter, err := backend.NewReporter(backend.ReporterConfig{ Component: teleport.ComponentCache, Backend: cacheBackend, TrackTopRequests: process.Config.Debug, }) if err != nil { return nil, trace.Wrap(err) } return cache.New(cfg.setup(cache.Config{ Context: process.ExitContext(), Backend: reporter, Events: cfg.services, ClusterConfig: cfg.services, Provisioner: cfg.services, Trust: cfg.services, Users: cfg.services, Access: cfg.services, Presence: cfg.services, Component: teleport.Component(append(cfg.cacheName, process.id, teleport.ComponentCache)...), MetricComponent: teleport.Component(append(cfg.cacheName, teleport.ComponentCache)...), })) }
[ "func", "(", "process", "*", "TeleportProcess", ")", "newAccessCache", "(", "cfg", "accessCacheConfig", ")", "(", "*", "cache", ".", "Cache", ",", "error", ")", "{", "if", "err", ":=", "cfg", ".", "CheckAndSetDefaults", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "var", "cacheBackend", "backend", ".", "Backend", "\n", "if", "cfg", ".", "inMemory", "{", "mem", ",", "err", ":=", "memory", ".", "New", "(", "memory", ".", "Config", "{", "Context", ":", "process", ".", "ExitContext", "(", ")", ",", "EventsOff", ":", "!", "cfg", ".", "events", ",", "Mirror", ":", "true", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "cacheBackend", "=", "mem", "\n", "}", "else", "{", "path", ":=", "filepath", ".", "Join", "(", "append", "(", "[", "]", "string", "{", "process", ".", "Config", ".", "DataDir", ",", "\"", "\"", "}", ",", "cfg", ".", "cacheName", "...", ")", "...", ")", "\n", "if", "err", ":=", "os", ".", "MkdirAll", "(", "path", ",", "teleport", ".", "SharedDirMode", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "ConvertSystemError", "(", "err", ")", "\n", "}", "\n", "liteBackend", ",", "err", ":=", "lite", ".", "NewWithConfig", "(", "process", ".", "ExitContext", "(", ")", ",", "lite", ".", "Config", "{", "Path", ":", "path", ",", "EventsOff", ":", "!", "cfg", ".", "events", ",", "Memory", ":", "false", ",", "Mirror", ":", "true", ",", "PollStreamPeriod", ":", "100", "*", "time", ".", "Millisecond", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "cacheBackend", "=", "liteBackend", "\n", "}", "\n", "reporter", ",", "err", ":=", "backend", ".", "NewReporter", "(", "backend", ".", "ReporterConfig", "{", "Component", ":", "teleport", ".", "ComponentCache", ",", "Backend", ":", "cacheBackend", ",", "TrackTopRequests", ":", "process", ".", "Config", ".", "Debug", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "return", "cache", ".", "New", "(", "cfg", ".", "setup", "(", "cache", ".", "Config", "{", "Context", ":", "process", ".", "ExitContext", "(", ")", ",", "Backend", ":", "reporter", ",", "Events", ":", "cfg", ".", "services", ",", "ClusterConfig", ":", "cfg", ".", "services", ",", "Provisioner", ":", "cfg", ".", "services", ",", "Trust", ":", "cfg", ".", "services", ",", "Users", ":", "cfg", ".", "services", ",", "Access", ":", "cfg", ".", "services", ",", "Presence", ":", "cfg", ".", "services", ",", "Component", ":", "teleport", ".", "Component", "(", "append", "(", "cfg", ".", "cacheName", ",", "process", ".", "id", ",", "teleport", ".", "ComponentCache", ")", "...", ")", ",", "MetricComponent", ":", "teleport", ".", "Component", "(", "append", "(", "cfg", ".", "cacheName", ",", "teleport", ".", "ComponentCache", ")", "...", ")", ",", "}", ")", ")", "\n", "}" ]
// newAccessCache returns new local cache access point
[ "newAccessCache", "returns", "new", "local", "cache", "access", "point" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/service.go#L1209-L1264
train
gravitational/teleport
lib/service/service.go
setupCachePolicy
func (process *TeleportProcess) setupCachePolicy(in cache.SetupConfigFn) cache.SetupConfigFn { return func(c cache.Config) cache.Config { config := in(c) config.PreferRecent = cache.PreferRecent{ Enabled: process.Config.CachePolicy.Enabled, NeverExpires: process.Config.CachePolicy.NeverExpires, MaxTTL: process.Config.CachePolicy.TTL, } return config } }
go
func (process *TeleportProcess) setupCachePolicy(in cache.SetupConfigFn) cache.SetupConfigFn { return func(c cache.Config) cache.Config { config := in(c) config.PreferRecent = cache.PreferRecent{ Enabled: process.Config.CachePolicy.Enabled, NeverExpires: process.Config.CachePolicy.NeverExpires, MaxTTL: process.Config.CachePolicy.TTL, } return config } }
[ "func", "(", "process", "*", "TeleportProcess", ")", "setupCachePolicy", "(", "in", "cache", ".", "SetupConfigFn", ")", "cache", ".", "SetupConfigFn", "{", "return", "func", "(", "c", "cache", ".", "Config", ")", "cache", ".", "Config", "{", "config", ":=", "in", "(", "c", ")", "\n", "config", ".", "PreferRecent", "=", "cache", ".", "PreferRecent", "{", "Enabled", ":", "process", ".", "Config", ".", "CachePolicy", ".", "Enabled", ",", "NeverExpires", ":", "process", ".", "Config", ".", "CachePolicy", ".", "NeverExpires", ",", "MaxTTL", ":", "process", ".", "Config", ".", "CachePolicy", ".", "TTL", ",", "}", "\n", "return", "config", "\n", "}", "\n", "}" ]
// setupCachePolicy sets up cache policy based on teleport configuration, // it is a wrapper function, that sets up configuration
[ "setupCachePolicy", "sets", "up", "cache", "policy", "based", "on", "teleport", "configuration", "it", "is", "a", "wrapper", "function", "that", "sets", "up", "configuration" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/service.go#L1268-L1278
train
gravitational/teleport
lib/service/service.go
newLocalCacheForProxy
func (process *TeleportProcess) newLocalCacheForProxy(clt auth.ClientI, cacheName []string) (auth.AccessPoint, error) { return process.newLocalCache(clt, cache.ForProxy, cacheName) }
go
func (process *TeleportProcess) newLocalCacheForProxy(clt auth.ClientI, cacheName []string) (auth.AccessPoint, error) { return process.newLocalCache(clt, cache.ForProxy, cacheName) }
[ "func", "(", "process", "*", "TeleportProcess", ")", "newLocalCacheForProxy", "(", "clt", "auth", ".", "ClientI", ",", "cacheName", "[", "]", "string", ")", "(", "auth", ".", "AccessPoint", ",", "error", ")", "{", "return", "process", ".", "newLocalCache", "(", "clt", ",", "cache", ".", "ForProxy", ",", "cacheName", ")", "\n", "}" ]
// newAccessPointCache returns new instance of access point configured for proxy
[ "newAccessPointCache", "returns", "new", "instance", "of", "access", "point", "configured", "for", "proxy" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/service.go#L1281-L1283
train
gravitational/teleport
lib/service/service.go
newLocalCache
func (process *TeleportProcess) newLocalCache(clt auth.ClientI, setupConfig cache.SetupConfigFn, cacheName []string) (auth.AccessPoint, error) { // if caching is disabled, return access point if !process.Config.CachePolicy.Enabled { return clt, nil } cache, err := process.newAccessCache(accessCacheConfig{ services: clt, setup: process.setupCachePolicy(setupConfig), cacheName: cacheName, }) if err != nil { return nil, trace.Wrap(err) } return auth.NewWrapper(clt, cache), nil }
go
func (process *TeleportProcess) newLocalCache(clt auth.ClientI, setupConfig cache.SetupConfigFn, cacheName []string) (auth.AccessPoint, error) { // if caching is disabled, return access point if !process.Config.CachePolicy.Enabled { return clt, nil } cache, err := process.newAccessCache(accessCacheConfig{ services: clt, setup: process.setupCachePolicy(setupConfig), cacheName: cacheName, }) if err != nil { return nil, trace.Wrap(err) } return auth.NewWrapper(clt, cache), nil }
[ "func", "(", "process", "*", "TeleportProcess", ")", "newLocalCache", "(", "clt", "auth", ".", "ClientI", ",", "setupConfig", "cache", ".", "SetupConfigFn", ",", "cacheName", "[", "]", "string", ")", "(", "auth", ".", "AccessPoint", ",", "error", ")", "{", "// if caching is disabled, return access point", "if", "!", "process", ".", "Config", ".", "CachePolicy", ".", "Enabled", "{", "return", "clt", ",", "nil", "\n", "}", "\n", "cache", ",", "err", ":=", "process", ".", "newAccessCache", "(", "accessCacheConfig", "{", "services", ":", "clt", ",", "setup", ":", "process", ".", "setupCachePolicy", "(", "setupConfig", ")", ",", "cacheName", ":", "cacheName", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "auth", ".", "NewWrapper", "(", "clt", ",", "cache", ")", ",", "nil", "\n", "}" ]
// newAccessPointCache returns new instance of access point
[ "newAccessPointCache", "returns", "new", "instance", "of", "access", "point" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/service.go#L1286-L1300
train
gravitational/teleport
lib/service/service.go
registerWithAuthServer
func (process *TeleportProcess) registerWithAuthServer(role teleport.Role, eventName string) { serviceName := strings.ToLower(role.String()) process.RegisterCriticalFunc(fmt.Sprintf("register.%v", serviceName), func() error { connector, err := process.reconnectToAuthService(role) if err != nil { return trace.Wrap(err) } process.onExit(fmt.Sprintf("auth.client.%v", serviceName), func(interface{}) { process.Debugf("Closed client for %v.", role) err := connector.Client.Close() if err != nil { process.Debugf("Failed to close client: %v", err) } }) process.BroadcastEvent(Event{Name: eventName, Payload: connector}) return nil }) }
go
func (process *TeleportProcess) registerWithAuthServer(role teleport.Role, eventName string) { serviceName := strings.ToLower(role.String()) process.RegisterCriticalFunc(fmt.Sprintf("register.%v", serviceName), func() error { connector, err := process.reconnectToAuthService(role) if err != nil { return trace.Wrap(err) } process.onExit(fmt.Sprintf("auth.client.%v", serviceName), func(interface{}) { process.Debugf("Closed client for %v.", role) err := connector.Client.Close() if err != nil { process.Debugf("Failed to close client: %v", err) } }) process.BroadcastEvent(Event{Name: eventName, Payload: connector}) return nil }) }
[ "func", "(", "process", "*", "TeleportProcess", ")", "registerWithAuthServer", "(", "role", "teleport", ".", "Role", ",", "eventName", "string", ")", "{", "serviceName", ":=", "strings", ".", "ToLower", "(", "role", ".", "String", "(", ")", ")", "\n", "process", ".", "RegisterCriticalFunc", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "serviceName", ")", ",", "func", "(", ")", "error", "{", "connector", ",", "err", ":=", "process", ".", "reconnectToAuthService", "(", "role", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "process", ".", "onExit", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "serviceName", ")", ",", "func", "(", "interface", "{", "}", ")", "{", "process", ".", "Debugf", "(", "\"", "\"", ",", "role", ")", "\n", "err", ":=", "connector", ".", "Client", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "process", ".", "Debugf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", ")", "\n", "process", ".", "BroadcastEvent", "(", "Event", "{", "Name", ":", "eventName", ",", "Payload", ":", "connector", "}", ")", "\n", "return", "nil", "\n", "}", ")", "\n", "}" ]
// registerWithAuthServer uses one time provisioning token obtained earlier // from the server to get a pair of SSH keys signed by Auth server host // certificate authority
[ "registerWithAuthServer", "uses", "one", "time", "provisioning", "token", "obtained", "earlier", "from", "the", "server", "to", "get", "a", "pair", "of", "SSH", "keys", "signed", "by", "Auth", "server", "host", "certificate", "authority" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/service.go#L1521-L1538
train
gravitational/teleport
lib/service/service.go
getAdditionalPrincipals
func (process *TeleportProcess) getAdditionalPrincipals(role teleport.Role) ([]string, []string, error) { var principals []string var dnsNames []string if process.Config.Hostname != "" { principals = append(principals, process.Config.Hostname) } var addrs []utils.NetAddr switch role { case teleport.RoleProxy: addrs = append(process.Config.Proxy.PublicAddrs, utils.NetAddr{Addr: reversetunnel.RemoteKubeProxy}) addrs = append(addrs, process.Config.Proxy.SSHPublicAddrs...) addrs = append(addrs, process.Config.Proxy.TunnelPublicAddrs...) addrs = append(addrs, process.Config.Proxy.Kube.PublicAddrs...) // Automatically add wildcards for every proxy public address for k8s SNI routing if process.Config.Proxy.Kube.Enabled { for _, publicAddr := range utils.JoinAddrSlices(process.Config.Proxy.PublicAddrs, process.Config.Proxy.Kube.PublicAddrs) { host, err := utils.Host(publicAddr.Addr) if err != nil { return nil, nil, trace.Wrap(err) } if ip := net.ParseIP(host); ip == nil { dnsNames = append(dnsNames, "*."+host) } } } case teleport.RoleAuth, teleport.RoleAdmin: addrs = process.Config.Auth.PublicAddrs case teleport.RoleNode: addrs = process.Config.SSH.PublicAddrs // If advertise IP is set, add it to the list of principals. Otherwise // add in the default (0.0.0.0) which will be replaced by the Auth Server // when a host certificate is issued. if process.Config.AdvertiseIP != "" { advertiseIP, err := utils.ParseAddr(process.Config.AdvertiseIP) if err != nil { return nil, nil, trace.Wrap(err) } addrs = append(addrs, *advertiseIP) } else { addrs = append(addrs, process.Config.SSH.Addr) } } for _, addr := range addrs { host, err := utils.Host(addr.Addr) if err != nil { return nil, nil, trace.Wrap(err) } principals = append(principals, host) } return principals, dnsNames, nil }
go
func (process *TeleportProcess) getAdditionalPrincipals(role teleport.Role) ([]string, []string, error) { var principals []string var dnsNames []string if process.Config.Hostname != "" { principals = append(principals, process.Config.Hostname) } var addrs []utils.NetAddr switch role { case teleport.RoleProxy: addrs = append(process.Config.Proxy.PublicAddrs, utils.NetAddr{Addr: reversetunnel.RemoteKubeProxy}) addrs = append(addrs, process.Config.Proxy.SSHPublicAddrs...) addrs = append(addrs, process.Config.Proxy.TunnelPublicAddrs...) addrs = append(addrs, process.Config.Proxy.Kube.PublicAddrs...) // Automatically add wildcards for every proxy public address for k8s SNI routing if process.Config.Proxy.Kube.Enabled { for _, publicAddr := range utils.JoinAddrSlices(process.Config.Proxy.PublicAddrs, process.Config.Proxy.Kube.PublicAddrs) { host, err := utils.Host(publicAddr.Addr) if err != nil { return nil, nil, trace.Wrap(err) } if ip := net.ParseIP(host); ip == nil { dnsNames = append(dnsNames, "*."+host) } } } case teleport.RoleAuth, teleport.RoleAdmin: addrs = process.Config.Auth.PublicAddrs case teleport.RoleNode: addrs = process.Config.SSH.PublicAddrs // If advertise IP is set, add it to the list of principals. Otherwise // add in the default (0.0.0.0) which will be replaced by the Auth Server // when a host certificate is issued. if process.Config.AdvertiseIP != "" { advertiseIP, err := utils.ParseAddr(process.Config.AdvertiseIP) if err != nil { return nil, nil, trace.Wrap(err) } addrs = append(addrs, *advertiseIP) } else { addrs = append(addrs, process.Config.SSH.Addr) } } for _, addr := range addrs { host, err := utils.Host(addr.Addr) if err != nil { return nil, nil, trace.Wrap(err) } principals = append(principals, host) } return principals, dnsNames, nil }
[ "func", "(", "process", "*", "TeleportProcess", ")", "getAdditionalPrincipals", "(", "role", "teleport", ".", "Role", ")", "(", "[", "]", "string", ",", "[", "]", "string", ",", "error", ")", "{", "var", "principals", "[", "]", "string", "\n", "var", "dnsNames", "[", "]", "string", "\n", "if", "process", ".", "Config", ".", "Hostname", "!=", "\"", "\"", "{", "principals", "=", "append", "(", "principals", ",", "process", ".", "Config", ".", "Hostname", ")", "\n", "}", "\n", "var", "addrs", "[", "]", "utils", ".", "NetAddr", "\n", "switch", "role", "{", "case", "teleport", ".", "RoleProxy", ":", "addrs", "=", "append", "(", "process", ".", "Config", ".", "Proxy", ".", "PublicAddrs", ",", "utils", ".", "NetAddr", "{", "Addr", ":", "reversetunnel", ".", "RemoteKubeProxy", "}", ")", "\n", "addrs", "=", "append", "(", "addrs", ",", "process", ".", "Config", ".", "Proxy", ".", "SSHPublicAddrs", "...", ")", "\n", "addrs", "=", "append", "(", "addrs", ",", "process", ".", "Config", ".", "Proxy", ".", "TunnelPublicAddrs", "...", ")", "\n", "addrs", "=", "append", "(", "addrs", ",", "process", ".", "Config", ".", "Proxy", ".", "Kube", ".", "PublicAddrs", "...", ")", "\n", "// Automatically add wildcards for every proxy public address for k8s SNI routing", "if", "process", ".", "Config", ".", "Proxy", ".", "Kube", ".", "Enabled", "{", "for", "_", ",", "publicAddr", ":=", "range", "utils", ".", "JoinAddrSlices", "(", "process", ".", "Config", ".", "Proxy", ".", "PublicAddrs", ",", "process", ".", "Config", ".", "Proxy", ".", "Kube", ".", "PublicAddrs", ")", "{", "host", ",", "err", ":=", "utils", ".", "Host", "(", "publicAddr", ".", "Addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "ip", ":=", "net", ".", "ParseIP", "(", "host", ")", ";", "ip", "==", "nil", "{", "dnsNames", "=", "append", "(", "dnsNames", ",", "\"", "\"", "+", "host", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "case", "teleport", ".", "RoleAuth", ",", "teleport", ".", "RoleAdmin", ":", "addrs", "=", "process", ".", "Config", ".", "Auth", ".", "PublicAddrs", "\n", "case", "teleport", ".", "RoleNode", ":", "addrs", "=", "process", ".", "Config", ".", "SSH", ".", "PublicAddrs", "\n", "// If advertise IP is set, add it to the list of principals. Otherwise", "// add in the default (0.0.0.0) which will be replaced by the Auth Server", "// when a host certificate is issued.", "if", "process", ".", "Config", ".", "AdvertiseIP", "!=", "\"", "\"", "{", "advertiseIP", ",", "err", ":=", "utils", ".", "ParseAddr", "(", "process", ".", "Config", ".", "AdvertiseIP", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "addrs", "=", "append", "(", "addrs", ",", "*", "advertiseIP", ")", "\n", "}", "else", "{", "addrs", "=", "append", "(", "addrs", ",", "process", ".", "Config", ".", "SSH", ".", "Addr", ")", "\n", "}", "\n", "}", "\n", "for", "_", ",", "addr", ":=", "range", "addrs", "{", "host", ",", "err", ":=", "utils", ".", "Host", "(", "addr", ".", "Addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "principals", "=", "append", "(", "principals", ",", "host", ")", "\n", "}", "\n", "return", "principals", ",", "dnsNames", ",", "nil", "\n", "}" ]
// getAdditionalPrincipals returns a list of additional principals to add // to role's service certificates.
[ "getAdditionalPrincipals", "returns", "a", "list", "of", "additional", "principals", "to", "add", "to", "role", "s", "service", "certificates", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/service.go#L1698-L1748
train
gravitational/teleport
lib/service/service.go
initAuthStorage
func (process *TeleportProcess) initAuthStorage() (bk backend.Backend, err error) { bc := &process.Config.Auth.StorageConfig process.Debugf("Using %v backend.", bc.Type) switch bc.Type { case lite.GetName(): bk, err = lite.New(context.TODO(), bc.Params) // legacy bolt backend, import all data into SQLite and return // SQLite data case boltbk.GetName(): litebk, err := lite.New(context.TODO(), bc.Params) if err != nil { return nil, trace.Wrap(err) } err = legacy.Import(context.TODO(), litebk, func() (legacy.Exporter, error) { return boltbk.New(legacy.Params(bc.Params)) }) if err != nil { return nil, trace.Wrap(err) } bk = litebk // legacy filesystem backend, import all data into SQLite and return // SQLite data case dir.GetName(): litebk, err := lite.New(context.TODO(), bc.Params) if err != nil { return nil, trace.Wrap(err) } err = legacy.Import(context.TODO(), litebk, func() (legacy.Exporter, error) { return dir.New(legacy.Params(bc.Params)) }) if err != nil { return nil, trace.Wrap(err) } bk = litebk // DynamoDB backend: case dynamo.GetName(): bk, err = dynamo.New(context.TODO(), bc.Params) // etcd backend: case etcdbk.GetName(): bk, err = etcdbk.New(context.TODO(), bc.Params) default: err = trace.BadParameter("unsupported secrets storage type: %q", bc.Type) } if err != nil { return nil, trace.Wrap(err) } reporter, err := backend.NewReporter(backend.ReporterConfig{ Component: teleport.ComponentBackend, Backend: backend.NewSanitizer(bk), TrackTopRequests: process.Config.Debug, }) if err != nil { return nil, trace.Wrap(err) } process.setReporter(reporter) return reporter, nil }
go
func (process *TeleportProcess) initAuthStorage() (bk backend.Backend, err error) { bc := &process.Config.Auth.StorageConfig process.Debugf("Using %v backend.", bc.Type) switch bc.Type { case lite.GetName(): bk, err = lite.New(context.TODO(), bc.Params) // legacy bolt backend, import all data into SQLite and return // SQLite data case boltbk.GetName(): litebk, err := lite.New(context.TODO(), bc.Params) if err != nil { return nil, trace.Wrap(err) } err = legacy.Import(context.TODO(), litebk, func() (legacy.Exporter, error) { return boltbk.New(legacy.Params(bc.Params)) }) if err != nil { return nil, trace.Wrap(err) } bk = litebk // legacy filesystem backend, import all data into SQLite and return // SQLite data case dir.GetName(): litebk, err := lite.New(context.TODO(), bc.Params) if err != nil { return nil, trace.Wrap(err) } err = legacy.Import(context.TODO(), litebk, func() (legacy.Exporter, error) { return dir.New(legacy.Params(bc.Params)) }) if err != nil { return nil, trace.Wrap(err) } bk = litebk // DynamoDB backend: case dynamo.GetName(): bk, err = dynamo.New(context.TODO(), bc.Params) // etcd backend: case etcdbk.GetName(): bk, err = etcdbk.New(context.TODO(), bc.Params) default: err = trace.BadParameter("unsupported secrets storage type: %q", bc.Type) } if err != nil { return nil, trace.Wrap(err) } reporter, err := backend.NewReporter(backend.ReporterConfig{ Component: teleport.ComponentBackend, Backend: backend.NewSanitizer(bk), TrackTopRequests: process.Config.Debug, }) if err != nil { return nil, trace.Wrap(err) } process.setReporter(reporter) return reporter, nil }
[ "func", "(", "process", "*", "TeleportProcess", ")", "initAuthStorage", "(", ")", "(", "bk", "backend", ".", "Backend", ",", "err", "error", ")", "{", "bc", ":=", "&", "process", ".", "Config", ".", "Auth", ".", "StorageConfig", "\n", "process", ".", "Debugf", "(", "\"", "\"", ",", "bc", ".", "Type", ")", "\n", "switch", "bc", ".", "Type", "{", "case", "lite", ".", "GetName", "(", ")", ":", "bk", ",", "err", "=", "lite", ".", "New", "(", "context", ".", "TODO", "(", ")", ",", "bc", ".", "Params", ")", "\n", "// legacy bolt backend, import all data into SQLite and return", "// SQLite data", "case", "boltbk", ".", "GetName", "(", ")", ":", "litebk", ",", "err", ":=", "lite", ".", "New", "(", "context", ".", "TODO", "(", ")", ",", "bc", ".", "Params", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "err", "=", "legacy", ".", "Import", "(", "context", ".", "TODO", "(", ")", ",", "litebk", ",", "func", "(", ")", "(", "legacy", ".", "Exporter", ",", "error", ")", "{", "return", "boltbk", ".", "New", "(", "legacy", ".", "Params", "(", "bc", ".", "Params", ")", ")", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "bk", "=", "litebk", "\n", "// legacy filesystem backend, import all data into SQLite and return", "// SQLite data", "case", "dir", ".", "GetName", "(", ")", ":", "litebk", ",", "err", ":=", "lite", ".", "New", "(", "context", ".", "TODO", "(", ")", ",", "bc", ".", "Params", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "err", "=", "legacy", ".", "Import", "(", "context", ".", "TODO", "(", ")", ",", "litebk", ",", "func", "(", ")", "(", "legacy", ".", "Exporter", ",", "error", ")", "{", "return", "dir", ".", "New", "(", "legacy", ".", "Params", "(", "bc", ".", "Params", ")", ")", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "bk", "=", "litebk", "\n", "// DynamoDB backend:", "case", "dynamo", ".", "GetName", "(", ")", ":", "bk", ",", "err", "=", "dynamo", ".", "New", "(", "context", ".", "TODO", "(", ")", ",", "bc", ".", "Params", ")", "\n", "// etcd backend:", "case", "etcdbk", ".", "GetName", "(", ")", ":", "bk", ",", "err", "=", "etcdbk", ".", "New", "(", "context", ".", "TODO", "(", ")", ",", "bc", ".", "Params", ")", "\n", "default", ":", "err", "=", "trace", ".", "BadParameter", "(", "\"", "\"", ",", "bc", ".", "Type", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "reporter", ",", "err", ":=", "backend", ".", "NewReporter", "(", "backend", ".", "ReporterConfig", "{", "Component", ":", "teleport", ".", "ComponentBackend", ",", "Backend", ":", "backend", ".", "NewSanitizer", "(", "bk", ")", ",", "TrackTopRequests", ":", "process", ".", "Config", ".", "Debug", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "process", ".", "setReporter", "(", "reporter", ")", "\n", "return", "reporter", ",", "nil", "\n", "}" ]
// initAuthStorage initializes the storage backend for the auth service.
[ "initAuthStorage", "initializes", "the", "storage", "backend", "for", "the", "auth", "service", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/service.go#L2225-L2281
train
gravitational/teleport
lib/service/service.go
WaitWithContext
func (process *TeleportProcess) WaitWithContext(ctx context.Context) { local, cancel := context.WithCancel(ctx) go func() { defer cancel() process.Supervisor.Wait() }() select { case <-local.Done(): return } }
go
func (process *TeleportProcess) WaitWithContext(ctx context.Context) { local, cancel := context.WithCancel(ctx) go func() { defer cancel() process.Supervisor.Wait() }() select { case <-local.Done(): return } }
[ "func", "(", "process", "*", "TeleportProcess", ")", "WaitWithContext", "(", "ctx", "context", ".", "Context", ")", "{", "local", ",", "cancel", ":=", "context", ".", "WithCancel", "(", "ctx", ")", "\n", "go", "func", "(", ")", "{", "defer", "cancel", "(", ")", "\n", "process", ".", "Supervisor", ".", "Wait", "(", ")", "\n", "}", "(", ")", "\n", "select", "{", "case", "<-", "local", ".", "Done", "(", ")", ":", "return", "\n", "}", "\n", "}" ]
// WaitWithContext waits until all internal services stop.
[ "WaitWithContext", "waits", "until", "all", "internal", "services", "stop", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/service.go#L2296-L2306
train
gravitational/teleport
lib/service/service.go
StartShutdown
func (process *TeleportProcess) StartShutdown(ctx context.Context) context.Context { process.BroadcastEvent(Event{Name: TeleportExitEvent, Payload: ctx}) localCtx, cancel := context.WithCancel(ctx) go func() { defer cancel() process.Supervisor.Wait() process.Debugf("All supervisor functions are completed.") localAuth := process.getLocalAuth() if localAuth != nil { if err := process.localAuth.Close(); err != nil { process.Warningf("Failed closing auth server: %v.", err) } } }() go process.printShutdownStatus(localCtx) return localCtx }
go
func (process *TeleportProcess) StartShutdown(ctx context.Context) context.Context { process.BroadcastEvent(Event{Name: TeleportExitEvent, Payload: ctx}) localCtx, cancel := context.WithCancel(ctx) go func() { defer cancel() process.Supervisor.Wait() process.Debugf("All supervisor functions are completed.") localAuth := process.getLocalAuth() if localAuth != nil { if err := process.localAuth.Close(); err != nil { process.Warningf("Failed closing auth server: %v.", err) } } }() go process.printShutdownStatus(localCtx) return localCtx }
[ "func", "(", "process", "*", "TeleportProcess", ")", "StartShutdown", "(", "ctx", "context", ".", "Context", ")", "context", ".", "Context", "{", "process", ".", "BroadcastEvent", "(", "Event", "{", "Name", ":", "TeleportExitEvent", ",", "Payload", ":", "ctx", "}", ")", "\n", "localCtx", ",", "cancel", ":=", "context", ".", "WithCancel", "(", "ctx", ")", "\n", "go", "func", "(", ")", "{", "defer", "cancel", "(", ")", "\n", "process", ".", "Supervisor", ".", "Wait", "(", ")", "\n", "process", ".", "Debugf", "(", "\"", "\"", ")", "\n", "localAuth", ":=", "process", ".", "getLocalAuth", "(", ")", "\n", "if", "localAuth", "!=", "nil", "{", "if", "err", ":=", "process", ".", "localAuth", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "process", ".", "Warningf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "go", "process", ".", "printShutdownStatus", "(", "localCtx", ")", "\n", "return", "localCtx", "\n", "}" ]
// StartShutdown launches non-blocking graceful shutdown process that signals // completion, returns context that will be closed once the shutdown is done
[ "StartShutdown", "launches", "non", "-", "blocking", "graceful", "shutdown", "process", "that", "signals", "completion", "returns", "context", "that", "will", "be", "closed", "once", "the", "shutdown", "is", "done" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/service.go#L2310-L2326
train
gravitational/teleport
lib/service/service.go
Shutdown
func (process *TeleportProcess) Shutdown(ctx context.Context) { localCtx := process.StartShutdown(ctx) // wait until parent context closes select { case <-localCtx.Done(): process.Debugf("Process completed.") } }
go
func (process *TeleportProcess) Shutdown(ctx context.Context) { localCtx := process.StartShutdown(ctx) // wait until parent context closes select { case <-localCtx.Done(): process.Debugf("Process completed.") } }
[ "func", "(", "process", "*", "TeleportProcess", ")", "Shutdown", "(", "ctx", "context", ".", "Context", ")", "{", "localCtx", ":=", "process", ".", "StartShutdown", "(", "ctx", ")", "\n", "// wait until parent context closes", "select", "{", "case", "<-", "localCtx", ".", "Done", "(", ")", ":", "process", ".", "Debugf", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// Shutdown launches graceful shutdown process and waits // for it to complete
[ "Shutdown", "launches", "graceful", "shutdown", "process", "and", "waits", "for", "it", "to", "complete" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/service.go#L2330-L2337
train
gravitational/teleport
lib/service/service.go
Close
func (process *TeleportProcess) Close() error { process.BroadcastEvent(Event{Name: TeleportExitEvent}) process.Config.Keygen.Close() var errors []error localAuth := process.getLocalAuth() if localAuth != nil { errors = append(errors, process.localAuth.Close()) } if process.storage != nil { errors = append(errors, process.storage.Close()) } return trace.NewAggregate(errors...) }
go
func (process *TeleportProcess) Close() error { process.BroadcastEvent(Event{Name: TeleportExitEvent}) process.Config.Keygen.Close() var errors []error localAuth := process.getLocalAuth() if localAuth != nil { errors = append(errors, process.localAuth.Close()) } if process.storage != nil { errors = append(errors, process.storage.Close()) } return trace.NewAggregate(errors...) }
[ "func", "(", "process", "*", "TeleportProcess", ")", "Close", "(", ")", "error", "{", "process", ".", "BroadcastEvent", "(", "Event", "{", "Name", ":", "TeleportExitEvent", "}", ")", "\n\n", "process", ".", "Config", ".", "Keygen", ".", "Close", "(", ")", "\n\n", "var", "errors", "[", "]", "error", "\n", "localAuth", ":=", "process", ".", "getLocalAuth", "(", ")", "\n", "if", "localAuth", "!=", "nil", "{", "errors", "=", "append", "(", "errors", ",", "process", ".", "localAuth", ".", "Close", "(", ")", ")", "\n", "}", "\n\n", "if", "process", ".", "storage", "!=", "nil", "{", "errors", "=", "append", "(", "errors", ",", "process", ".", "storage", ".", "Close", "(", ")", ")", "\n", "}", "\n\n", "return", "trace", ".", "NewAggregate", "(", "errors", "...", ")", "\n", "}" ]
// Close broadcasts close signals and exits immediately
[ "Close", "broadcasts", "close", "signals", "and", "exits", "immediately" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/service.go#L2340-L2356
train
gravitational/teleport
lib/service/service.go
initSelfSignedHTTPSCert
func initSelfSignedHTTPSCert(cfg *Config) (err error) { log.Warningf("No TLS Keys provided, using self signed certificate.") keyPath := filepath.Join(cfg.DataDir, defaults.SelfSignedKeyPath) certPath := filepath.Join(cfg.DataDir, defaults.SelfSignedCertPath) cfg.Proxy.TLSKey = keyPath cfg.Proxy.TLSCert = certPath // return the existing pair if they have already been generated: _, err = tls.LoadX509KeyPair(certPath, keyPath) if err == nil { return nil } if !os.IsNotExist(err) { return trace.Wrap(err, "unrecognized error reading certs") } log.Warningf("Generating self signed key and cert to %v %v.", keyPath, certPath) creds, err := utils.GenerateSelfSignedCert([]string{cfg.Hostname, "localhost"}) if err != nil { return trace.Wrap(err) } if err := ioutil.WriteFile(keyPath, creds.PrivateKey, 0600); err != nil { return trace.Wrap(err, "error writing key PEM") } if err := ioutil.WriteFile(certPath, creds.Cert, 0600); err != nil { return trace.Wrap(err, "error writing key PEM") } return nil }
go
func initSelfSignedHTTPSCert(cfg *Config) (err error) { log.Warningf("No TLS Keys provided, using self signed certificate.") keyPath := filepath.Join(cfg.DataDir, defaults.SelfSignedKeyPath) certPath := filepath.Join(cfg.DataDir, defaults.SelfSignedCertPath) cfg.Proxy.TLSKey = keyPath cfg.Proxy.TLSCert = certPath // return the existing pair if they have already been generated: _, err = tls.LoadX509KeyPair(certPath, keyPath) if err == nil { return nil } if !os.IsNotExist(err) { return trace.Wrap(err, "unrecognized error reading certs") } log.Warningf("Generating self signed key and cert to %v %v.", keyPath, certPath) creds, err := utils.GenerateSelfSignedCert([]string{cfg.Hostname, "localhost"}) if err != nil { return trace.Wrap(err) } if err := ioutil.WriteFile(keyPath, creds.PrivateKey, 0600); err != nil { return trace.Wrap(err, "error writing key PEM") } if err := ioutil.WriteFile(certPath, creds.Cert, 0600); err != nil { return trace.Wrap(err, "error writing key PEM") } return nil }
[ "func", "initSelfSignedHTTPSCert", "(", "cfg", "*", "Config", ")", "(", "err", "error", ")", "{", "log", ".", "Warningf", "(", "\"", "\"", ")", "\n\n", "keyPath", ":=", "filepath", ".", "Join", "(", "cfg", ".", "DataDir", ",", "defaults", ".", "SelfSignedKeyPath", ")", "\n", "certPath", ":=", "filepath", ".", "Join", "(", "cfg", ".", "DataDir", ",", "defaults", ".", "SelfSignedCertPath", ")", "\n\n", "cfg", ".", "Proxy", ".", "TLSKey", "=", "keyPath", "\n", "cfg", ".", "Proxy", ".", "TLSCert", "=", "certPath", "\n\n", "// return the existing pair if they have already been generated:", "_", ",", "err", "=", "tls", ".", "LoadX509KeyPair", "(", "certPath", ",", "keyPath", ")", "\n", "if", "err", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "if", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "trace", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "log", ".", "Warningf", "(", "\"", "\"", ",", "keyPath", ",", "certPath", ")", "\n\n", "creds", ",", "err", ":=", "utils", ".", "GenerateSelfSignedCert", "(", "[", "]", "string", "{", "cfg", ".", "Hostname", ",", "\"", "\"", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "ioutil", ".", "WriteFile", "(", "keyPath", ",", "creds", ".", "PrivateKey", ",", "0600", ")", ";", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "err", ":=", "ioutil", ".", "WriteFile", "(", "certPath", ",", "creds", ".", "Cert", ",", "0600", ")", ";", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// initSelfSignedHTTPSCert generates and self-signs a TLS key+cert pair for https connection // to the proxy server.
[ "initSelfSignedHTTPSCert", "generates", "and", "self", "-", "signs", "a", "TLS", "key", "+", "cert", "pair", "for", "https", "connection", "to", "the", "proxy", "server", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/service.go#L2401-L2432
train
gravitational/teleport
lib/kube/utils/utils.go
GetKubeClient
func GetKubeClient(configPath string) (client *kubernetes.Clientset, config *rest.Config, err error) { // if path to kubeconfig was provided, init config from it if configPath != "" { config, err = clientcmd.BuildConfigFromFlags("", configPath) if err != nil { return nil, nil, trace.Wrap(err) } } else { // otherwise attempt to init as if connecting from cluster config, err = rest.InClusterConfig() if err != nil { return nil, nil, trace.Wrap(err) } } client, err = kubernetes.NewForConfig(config) if err != nil { return nil, nil, trace.Wrap(err) } return client, config, nil }
go
func GetKubeClient(configPath string) (client *kubernetes.Clientset, config *rest.Config, err error) { // if path to kubeconfig was provided, init config from it if configPath != "" { config, err = clientcmd.BuildConfigFromFlags("", configPath) if err != nil { return nil, nil, trace.Wrap(err) } } else { // otherwise attempt to init as if connecting from cluster config, err = rest.InClusterConfig() if err != nil { return nil, nil, trace.Wrap(err) } } client, err = kubernetes.NewForConfig(config) if err != nil { return nil, nil, trace.Wrap(err) } return client, config, nil }
[ "func", "GetKubeClient", "(", "configPath", "string", ")", "(", "client", "*", "kubernetes", ".", "Clientset", ",", "config", "*", "rest", ".", "Config", ",", "err", "error", ")", "{", "// if path to kubeconfig was provided, init config from it", "if", "configPath", "!=", "\"", "\"", "{", "config", ",", "err", "=", "clientcmd", ".", "BuildConfigFromFlags", "(", "\"", "\"", ",", "configPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "else", "{", "// otherwise attempt to init as if connecting from cluster", "config", ",", "err", "=", "rest", ".", "InClusterConfig", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n\n", "client", ",", "err", "=", "kubernetes", ".", "NewForConfig", "(", "config", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "client", ",", "config", ",", "nil", "\n", "}" ]
// GetKubeClient returns instance of client to the kubernetes cluster // using in-cluster configuration if available and falling back to // configuration file under configPath otherwise
[ "GetKubeClient", "returns", "instance", "of", "client", "to", "the", "kubernetes", "cluster", "using", "in", "-", "cluster", "configuration", "if", "available", "and", "falling", "back", "to", "configuration", "file", "under", "configPath", "otherwise" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/utils/utils.go#L16-L36
train
gravitational/teleport
lib/kube/utils/utils.go
GetKubeConfig
func GetKubeConfig(configPath string) (*rest.Config, error) { // if path to kubeconfig was provided, init config from it if configPath != "" { return clientcmd.BuildConfigFromFlags("", configPath) } return rest.InClusterConfig() }
go
func GetKubeConfig(configPath string) (*rest.Config, error) { // if path to kubeconfig was provided, init config from it if configPath != "" { return clientcmd.BuildConfigFromFlags("", configPath) } return rest.InClusterConfig() }
[ "func", "GetKubeConfig", "(", "configPath", "string", ")", "(", "*", "rest", ".", "Config", ",", "error", ")", "{", "// if path to kubeconfig was provided, init config from it", "if", "configPath", "!=", "\"", "\"", "{", "return", "clientcmd", ".", "BuildConfigFromFlags", "(", "\"", "\"", ",", "configPath", ")", "\n", "}", "\n", "return", "rest", ".", "InClusterConfig", "(", ")", "\n", "}" ]
// GetKubeConfig returns kubernetes configuration // from configPath file or, by default reads in-cluster configuration
[ "GetKubeConfig", "returns", "kubernetes", "configuration", "from", "configPath", "file", "or", "by", "default", "reads", "in", "-", "cluster", "configuration" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/utils/utils.go#L40-L46
train
gravitational/teleport
lib/services/provisioning.go
MustCreateProvisionToken
func MustCreateProvisionToken(token string, roles teleport.Roles, expires time.Time) ProvisionToken { t, err := NewProvisionToken(token, roles, expires) if err != nil { panic(err) } return t }
go
func MustCreateProvisionToken(token string, roles teleport.Roles, expires time.Time) ProvisionToken { t, err := NewProvisionToken(token, roles, expires) if err != nil { panic(err) } return t }
[ "func", "MustCreateProvisionToken", "(", "token", "string", ",", "roles", "teleport", ".", "Roles", ",", "expires", "time", ".", "Time", ")", "ProvisionToken", "{", "t", ",", "err", ":=", "NewProvisionToken", "(", "token", ",", "roles", ",", "expires", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "t", "\n", "}" ]
// MustCreateProvisionToken returns a new valid provision token // or panics, used in testes
[ "MustCreateProvisionToken", "returns", "a", "new", "valid", "provision", "token", "or", "panics", "used", "in", "testes" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/provisioning.go#L33-L39
train
gravitational/teleport
lib/services/provisioning.go
NewProvisionToken
func NewProvisionToken(token string, roles teleport.Roles, expires time.Time) (ProvisionToken, error) { t := &ProvisionTokenV2{ Kind: KindToken, Version: V2, Metadata: Metadata{ Name: token, Expires: &expires, Namespace: defaults.Namespace, }, Spec: ProvisionTokenSpecV2{ Roles: roles, }, } if err := t.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } return t, nil }
go
func NewProvisionToken(token string, roles teleport.Roles, expires time.Time) (ProvisionToken, error) { t := &ProvisionTokenV2{ Kind: KindToken, Version: V2, Metadata: Metadata{ Name: token, Expires: &expires, Namespace: defaults.Namespace, }, Spec: ProvisionTokenSpecV2{ Roles: roles, }, } if err := t.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } return t, nil }
[ "func", "NewProvisionToken", "(", "token", "string", ",", "roles", "teleport", ".", "Roles", ",", "expires", "time", ".", "Time", ")", "(", "ProvisionToken", ",", "error", ")", "{", "t", ":=", "&", "ProvisionTokenV2", "{", "Kind", ":", "KindToken", ",", "Version", ":", "V2", ",", "Metadata", ":", "Metadata", "{", "Name", ":", "token", ",", "Expires", ":", "&", "expires", ",", "Namespace", ":", "defaults", ".", "Namespace", ",", "}", ",", "Spec", ":", "ProvisionTokenSpecV2", "{", "Roles", ":", "roles", ",", "}", ",", "}", "\n", "if", "err", ":=", "t", ".", "CheckAndSetDefaults", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "t", ",", "nil", "\n", "}" ]
// NewProvisionToken returns a new instance of provision token resource
[ "NewProvisionToken", "returns", "a", "new", "instance", "of", "provision", "token", "resource" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/provisioning.go#L42-L59
train
gravitational/teleport
lib/services/provisioning.go
ProvisionTokensToV1
func ProvisionTokensToV1(in []ProvisionToken) []ProvisionTokenV1 { if in == nil { return nil } out := make([]ProvisionTokenV1, len(in)) for i := range in { out[i] = *in[i].V1() } return out }
go
func ProvisionTokensToV1(in []ProvisionToken) []ProvisionTokenV1 { if in == nil { return nil } out := make([]ProvisionTokenV1, len(in)) for i := range in { out[i] = *in[i].V1() } return out }
[ "func", "ProvisionTokensToV1", "(", "in", "[", "]", "ProvisionToken", ")", "[", "]", "ProvisionTokenV1", "{", "if", "in", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "out", ":=", "make", "(", "[", "]", "ProvisionTokenV1", ",", "len", "(", "in", ")", ")", "\n", "for", "i", ":=", "range", "in", "{", "out", "[", "i", "]", "=", "*", "in", "[", "i", "]", ".", "V1", "(", ")", "\n", "}", "\n", "return", "out", "\n", "}" ]
// ProvisionTokensToV1 converts provision tokens to V1 list
[ "ProvisionTokensToV1", "converts", "provision", "tokens", "to", "V1", "list" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/provisioning.go#L97-L106
train
gravitational/teleport
lib/services/provisioning.go
ProvisionTokensFromV1
func ProvisionTokensFromV1(in []ProvisionTokenV1) []ProvisionToken { if in == nil { return nil } out := make([]ProvisionToken, len(in)) for i := range in { out[i] = in[i].V2() } return out }
go
func ProvisionTokensFromV1(in []ProvisionTokenV1) []ProvisionToken { if in == nil { return nil } out := make([]ProvisionToken, len(in)) for i := range in { out[i] = in[i].V2() } return out }
[ "func", "ProvisionTokensFromV1", "(", "in", "[", "]", "ProvisionTokenV1", ")", "[", "]", "ProvisionToken", "{", "if", "in", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "out", ":=", "make", "(", "[", "]", "ProvisionToken", ",", "len", "(", "in", ")", ")", "\n", "for", "i", ":=", "range", "in", "{", "out", "[", "i", "]", "=", "in", "[", "i", "]", ".", "V2", "(", ")", "\n", "}", "\n", "return", "out", "\n", "}" ]
// ProvisionTokensFromV1 converts V1 provision tokens to resource list
[ "ProvisionTokensFromV1", "converts", "V1", "provision", "tokens", "to", "resource", "list" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/provisioning.go#L109-L118
train
gravitational/teleport
lib/services/provisioning.go
SetRoles
func (p *ProvisionTokenV2) SetRoles(r teleport.Roles) { p.Spec.Roles = r }
go
func (p *ProvisionTokenV2) SetRoles(r teleport.Roles) { p.Spec.Roles = r }
[ "func", "(", "p", "*", "ProvisionTokenV2", ")", "SetRoles", "(", "r", "teleport", ".", "Roles", ")", "{", "p", ".", "Spec", ".", "Roles", "=", "r", "\n", "}" ]
// SetRoles sets teleport roles
[ "SetRoles", "sets", "teleport", "roles" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/provisioning.go#L149-L151
train
gravitational/teleport
lib/services/provisioning.go
UnmarshalProvisionToken
func UnmarshalProvisionToken(data []byte, opts ...MarshalOption) (ProvisionToken, error) { if len(data) == 0 { return nil, trace.BadParameter("missing provision token data") } cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } var h ResourceHeader err = utils.FastUnmarshal(data, &h) if err != nil { return nil, trace.Wrap(err) } switch h.Version { case "": var p ProvisionTokenV1 err := utils.FastUnmarshal(data, &p) if err != nil { return nil, trace.Wrap(err) } v2 := p.V2() if cfg.ID != 0 { v2.SetResourceID(cfg.ID) } return v2, nil case V2: var p ProvisionTokenV2 if cfg.SkipValidation { if err := utils.FastUnmarshal(data, &p); err != nil { return nil, trace.BadParameter(err.Error()) } } else { if err := utils.UnmarshalWithSchema(GetProvisionTokenSchema(), &p, data); err != nil { return nil, trace.BadParameter(err.Error()) } } if err := p.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } if cfg.ID != 0 { p.SetResourceID(cfg.ID) } return &p, nil } return nil, trace.BadParameter("server resource version %v is not supported", h.Version) }
go
func UnmarshalProvisionToken(data []byte, opts ...MarshalOption) (ProvisionToken, error) { if len(data) == 0 { return nil, trace.BadParameter("missing provision token data") } cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } var h ResourceHeader err = utils.FastUnmarshal(data, &h) if err != nil { return nil, trace.Wrap(err) } switch h.Version { case "": var p ProvisionTokenV1 err := utils.FastUnmarshal(data, &p) if err != nil { return nil, trace.Wrap(err) } v2 := p.V2() if cfg.ID != 0 { v2.SetResourceID(cfg.ID) } return v2, nil case V2: var p ProvisionTokenV2 if cfg.SkipValidation { if err := utils.FastUnmarshal(data, &p); err != nil { return nil, trace.BadParameter(err.Error()) } } else { if err := utils.UnmarshalWithSchema(GetProvisionTokenSchema(), &p, data); err != nil { return nil, trace.BadParameter(err.Error()) } } if err := p.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } if cfg.ID != 0 { p.SetResourceID(cfg.ID) } return &p, nil } return nil, trace.BadParameter("server resource version %v is not supported", h.Version) }
[ "func", "UnmarshalProvisionToken", "(", "data", "[", "]", "byte", ",", "opts", "...", "MarshalOption", ")", "(", "ProvisionToken", ",", "error", ")", "{", "if", "len", "(", "data", ")", "==", "0", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n\n", "cfg", ",", "err", ":=", "collectOptions", "(", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "var", "h", "ResourceHeader", "\n", "err", "=", "utils", ".", "FastUnmarshal", "(", "data", ",", "&", "h", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "switch", "h", ".", "Version", "{", "case", "\"", "\"", ":", "var", "p", "ProvisionTokenV1", "\n", "err", ":=", "utils", ".", "FastUnmarshal", "(", "data", ",", "&", "p", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "v2", ":=", "p", ".", "V2", "(", ")", "\n", "if", "cfg", ".", "ID", "!=", "0", "{", "v2", ".", "SetResourceID", "(", "cfg", ".", "ID", ")", "\n", "}", "\n", "return", "v2", ",", "nil", "\n", "case", "V2", ":", "var", "p", "ProvisionTokenV2", "\n", "if", "cfg", ".", "SkipValidation", "{", "if", "err", ":=", "utils", ".", "FastUnmarshal", "(", "data", ",", "&", "p", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}", "else", "{", "if", "err", ":=", "utils", ".", "UnmarshalWithSchema", "(", "GetProvisionTokenSchema", "(", ")", ",", "&", "p", ",", "data", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "p", ".", "CheckAndSetDefaults", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "cfg", ".", "ID", "!=", "0", "{", "p", ".", "SetResourceID", "(", "cfg", ".", "ID", ")", "\n", "}", "\n", "return", "&", "p", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ",", "h", ".", "Version", ")", "\n", "}" ]
// UnmarshalProvisionToken unmarshals provision token from JSON or YAML, // sets defaults and checks the schema
[ "UnmarshalProvisionToken", "unmarshals", "provision", "token", "from", "JSON", "or", "YAML", "sets", "defaults", "and", "checks", "the", "schema" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/provisioning.go#L281-L329
train
gravitational/teleport
lib/services/provisioning.go
MarshalProvisionToken
func MarshalProvisionToken(t ProvisionToken, opts ...MarshalOption) ([]byte, error) { cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } type token1 interface { V1() *ProvisionTokenV1 } type token2 interface { V2() *ProvisionTokenV2 } version := cfg.GetVersion() switch version { case V1: v, ok := t.(token1) if !ok { return nil, trace.BadParameter("don't know how to marshal %v", V1) } return utils.FastMarshal(v.V1()) case V2: v, ok := t.(token2) if !ok { return nil, trace.BadParameter("don't know how to marshal %v", V2) } return utils.FastMarshal(v.V2()) default: return nil, trace.BadParameter("version %v is not supported", version) } }
go
func MarshalProvisionToken(t ProvisionToken, opts ...MarshalOption) ([]byte, error) { cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } type token1 interface { V1() *ProvisionTokenV1 } type token2 interface { V2() *ProvisionTokenV2 } version := cfg.GetVersion() switch version { case V1: v, ok := t.(token1) if !ok { return nil, trace.BadParameter("don't know how to marshal %v", V1) } return utils.FastMarshal(v.V1()) case V2: v, ok := t.(token2) if !ok { return nil, trace.BadParameter("don't know how to marshal %v", V2) } return utils.FastMarshal(v.V2()) default: return nil, trace.BadParameter("version %v is not supported", version) } }
[ "func", "MarshalProvisionToken", "(", "t", "ProvisionToken", ",", "opts", "...", "MarshalOption", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "cfg", ",", "err", ":=", "collectOptions", "(", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "type", "token1", "interface", "{", "V1", "(", ")", "*", "ProvisionTokenV1", "\n", "}", "\n", "type", "token2", "interface", "{", "V2", "(", ")", "*", "ProvisionTokenV2", "\n", "}", "\n", "version", ":=", "cfg", ".", "GetVersion", "(", ")", "\n", "switch", "version", "{", "case", "V1", ":", "v", ",", "ok", ":=", "t", ".", "(", "token1", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ",", "V1", ")", "\n", "}", "\n", "return", "utils", ".", "FastMarshal", "(", "v", ".", "V1", "(", ")", ")", "\n", "case", "V2", ":", "v", ",", "ok", ":=", "t", ".", "(", "token2", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ",", "V2", ")", "\n", "}", "\n", "return", "utils", ".", "FastMarshal", "(", "v", ".", "V2", "(", ")", ")", "\n", "default", ":", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ",", "version", ")", "\n", "}", "\n", "}" ]
// MarshalProvisionToken marshals provisioning token into JSON.
[ "MarshalProvisionToken", "marshals", "provisioning", "token", "into", "JSON", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/provisioning.go#L332-L360
train
gravitational/teleport
lib/utils/proxy/proxy.go
NewClientConnWithDeadline
func NewClientConnWithDeadline(conn net.Conn, addr string, config *ssh.ClientConfig) (*ssh.Client, error) { if config.Timeout > 0 { conn.SetReadDeadline(time.Now().Add(config.Timeout)) } c, chans, reqs, err := ssh.NewClientConn(conn, addr, config) if err != nil { return nil, err } if config.Timeout > 0 { conn.SetReadDeadline(time.Time{}) } return ssh.NewClient(c, chans, reqs), nil }
go
func NewClientConnWithDeadline(conn net.Conn, addr string, config *ssh.ClientConfig) (*ssh.Client, error) { if config.Timeout > 0 { conn.SetReadDeadline(time.Now().Add(config.Timeout)) } c, chans, reqs, err := ssh.NewClientConn(conn, addr, config) if err != nil { return nil, err } if config.Timeout > 0 { conn.SetReadDeadline(time.Time{}) } return ssh.NewClient(c, chans, reqs), nil }
[ "func", "NewClientConnWithDeadline", "(", "conn", "net", ".", "Conn", ",", "addr", "string", ",", "config", "*", "ssh", ".", "ClientConfig", ")", "(", "*", "ssh", ".", "Client", ",", "error", ")", "{", "if", "config", ".", "Timeout", ">", "0", "{", "conn", ".", "SetReadDeadline", "(", "time", ".", "Now", "(", ")", ".", "Add", "(", "config", ".", "Timeout", ")", ")", "\n", "}", "\n", "c", ",", "chans", ",", "reqs", ",", "err", ":=", "ssh", ".", "NewClientConn", "(", "conn", ",", "addr", ",", "config", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "config", ".", "Timeout", ">", "0", "{", "conn", ".", "SetReadDeadline", "(", "time", ".", "Time", "{", "}", ")", "\n", "}", "\n", "return", "ssh", ".", "NewClient", "(", "c", ",", "chans", ",", "reqs", ")", ",", "nil", "\n", "}" ]
// NewClientConnWithDeadline establishes new client connection with specified deadline
[ "NewClientConnWithDeadline", "establishes", "new", "client", "connection", "with", "specified", "deadline" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/proxy/proxy.go#L41-L53
train
gravitational/teleport
lib/utils/proxy/proxy.go
DialWithDeadline
func DialWithDeadline(network string, addr string, config *ssh.ClientConfig) (*ssh.Client, error) { conn, err := net.DialTimeout(network, addr, config.Timeout) if err != nil { return nil, err } return NewClientConnWithDeadline(conn, addr, config) }
go
func DialWithDeadline(network string, addr string, config *ssh.ClientConfig) (*ssh.Client, error) { conn, err := net.DialTimeout(network, addr, config.Timeout) if err != nil { return nil, err } return NewClientConnWithDeadline(conn, addr, config) }
[ "func", "DialWithDeadline", "(", "network", "string", ",", "addr", "string", ",", "config", "*", "ssh", ".", "ClientConfig", ")", "(", "*", "ssh", ".", "Client", ",", "error", ")", "{", "conn", ",", "err", ":=", "net", ".", "DialTimeout", "(", "network", ",", "addr", ",", "config", ".", "Timeout", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "NewClientConnWithDeadline", "(", "conn", ",", "addr", ",", "config", ")", "\n", "}" ]
// DialWithDeadline works around the case when net.DialWithTimeout // succeeds, but key exchange hangs. Setting deadline on connection // prevents this case from happening
[ "DialWithDeadline", "works", "around", "the", "case", "when", "net", ".", "DialWithTimeout", "succeeds", "but", "key", "exchange", "hangs", ".", "Setting", "deadline", "on", "connection", "prevents", "this", "case", "from", "happening" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/proxy/proxy.go#L58-L64
train
gravitational/teleport
lib/utils/proxy/proxy.go
Dial
func (d directDial) Dial(network string, addr string, config *ssh.ClientConfig) (*ssh.Client, error) { return DialWithDeadline(network, addr, config) }
go
func (d directDial) Dial(network string, addr string, config *ssh.ClientConfig) (*ssh.Client, error) { return DialWithDeadline(network, addr, config) }
[ "func", "(", "d", "directDial", ")", "Dial", "(", "network", "string", ",", "addr", "string", ",", "config", "*", "ssh", ".", "ClientConfig", ")", "(", "*", "ssh", ".", "Client", ",", "error", ")", "{", "return", "DialWithDeadline", "(", "network", ",", "addr", ",", "config", ")", "\n", "}" ]
// Dial calls ssh.Dial directly.
[ "Dial", "calls", "ssh", ".", "Dial", "directly", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/proxy/proxy.go#L78-L80
train
gravitational/teleport
lib/utils/proxy/proxy.go
Dial
func (d proxyDial) Dial(network string, addr string, config *ssh.ClientConfig) (*ssh.Client, error) { // Build a proxy connection first. pconn, err := dialProxy(context.Background(), d.proxyHost, addr) if err != nil { return nil, trace.Wrap(err) } if config.Timeout > 0 { pconn.SetReadDeadline(time.Now().Add(config.Timeout)) } // Do the same as ssh.Dial but pass in proxy connection. c, chans, reqs, err := ssh.NewClientConn(pconn, addr, config) if err != nil { return nil, trace.Wrap(err) } if config.Timeout > 0 { pconn.SetReadDeadline(time.Time{}) } return ssh.NewClient(c, chans, reqs), nil }
go
func (d proxyDial) Dial(network string, addr string, config *ssh.ClientConfig) (*ssh.Client, error) { // Build a proxy connection first. pconn, err := dialProxy(context.Background(), d.proxyHost, addr) if err != nil { return nil, trace.Wrap(err) } if config.Timeout > 0 { pconn.SetReadDeadline(time.Now().Add(config.Timeout)) } // Do the same as ssh.Dial but pass in proxy connection. c, chans, reqs, err := ssh.NewClientConn(pconn, addr, config) if err != nil { return nil, trace.Wrap(err) } if config.Timeout > 0 { pconn.SetReadDeadline(time.Time{}) } return ssh.NewClient(c, chans, reqs), nil }
[ "func", "(", "d", "proxyDial", ")", "Dial", "(", "network", "string", ",", "addr", "string", ",", "config", "*", "ssh", ".", "ClientConfig", ")", "(", "*", "ssh", ".", "Client", ",", "error", ")", "{", "// Build a proxy connection first.", "pconn", ",", "err", ":=", "dialProxy", "(", "context", ".", "Background", "(", ")", ",", "d", ".", "proxyHost", ",", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "config", ".", "Timeout", ">", "0", "{", "pconn", ".", "SetReadDeadline", "(", "time", ".", "Now", "(", ")", ".", "Add", "(", "config", ".", "Timeout", ")", ")", "\n", "}", "\n", "// Do the same as ssh.Dial but pass in proxy connection.", "c", ",", "chans", ",", "reqs", ",", "err", ":=", "ssh", ".", "NewClientConn", "(", "pconn", ",", "addr", ",", "config", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "config", ".", "Timeout", ">", "0", "{", "pconn", ".", "SetReadDeadline", "(", "time", ".", "Time", "{", "}", ")", "\n", "}", "\n", "return", "ssh", ".", "NewClient", "(", "c", ",", "chans", ",", "reqs", ")", ",", "nil", "\n", "}" ]
// Dial first connects to a proxy, then uses the connection to establish a new // SSH connection.
[ "Dial", "first", "connects", "to", "a", "proxy", "then", "uses", "the", "connection", "to", "establish", "a", "new", "SSH", "connection", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/proxy/proxy.go#L105-L123
train
gravitational/teleport
lib/utils/proxy/proxy.go
DialerFromEnvironment
func DialerFromEnvironment(addr string) Dialer { // Try and get proxy addr from the environment. proxyAddr := getProxyAddress(addr) // If no proxy settings are in environment return regular ssh dialer, // otherwise return a proxy dialer. if proxyAddr == "" { log.Debugf("No proxy set in environment, returning direct dialer.") return directDial{} } log.Debugf("Found proxy %q in environment, returning proxy dialer.", proxyAddr) return proxyDial{proxyHost: proxyAddr} }
go
func DialerFromEnvironment(addr string) Dialer { // Try and get proxy addr from the environment. proxyAddr := getProxyAddress(addr) // If no proxy settings are in environment return regular ssh dialer, // otherwise return a proxy dialer. if proxyAddr == "" { log.Debugf("No proxy set in environment, returning direct dialer.") return directDial{} } log.Debugf("Found proxy %q in environment, returning proxy dialer.", proxyAddr) return proxyDial{proxyHost: proxyAddr} }
[ "func", "DialerFromEnvironment", "(", "addr", "string", ")", "Dialer", "{", "// Try and get proxy addr from the environment.", "proxyAddr", ":=", "getProxyAddress", "(", "addr", ")", "\n\n", "// If no proxy settings are in environment return regular ssh dialer,", "// otherwise return a proxy dialer.", "if", "proxyAddr", "==", "\"", "\"", "{", "log", ".", "Debugf", "(", "\"", "\"", ")", "\n", "return", "directDial", "{", "}", "\n", "}", "\n", "log", ".", "Debugf", "(", "\"", "\"", ",", "proxyAddr", ")", "\n", "return", "proxyDial", "{", "proxyHost", ":", "proxyAddr", "}", "\n", "}" ]
// DialerFromEnvironment returns a Dial function. If the https_proxy or http_proxy // environment variable are set, it returns a function that will dial through // said proxy server. If neither variable is set, it will connect to the SSH // server directly.
[ "DialerFromEnvironment", "returns", "a", "Dial", "function", ".", "If", "the", "https_proxy", "or", "http_proxy", "environment", "variable", "are", "set", "it", "returns", "a", "function", "that", "will", "dial", "through", "said", "proxy", "server", ".", "If", "neither", "variable", "is", "set", "it", "will", "connect", "to", "the", "SSH", "server", "directly", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/proxy/proxy.go#L129-L141
train
gravitational/teleport
lib/backend/etcdbk/etcd.go
New
func New(ctx context.Context, params backend.Params) (*EtcdBackend, error) { var err error if params == nil { return nil, trace.BadParameter("missing etcd configuration") } // convert generic backend parameters structure to etcd config: var cfg *Config if err = utils.ObjectToStruct(params, &cfg); err != nil { return nil, trace.BadParameter("invalid etcd configuration: %v", err) } if err = cfg.Validate(); err != nil { return nil, trace.Wrap(err) } buf, err := backend.NewCircularBuffer(ctx, cfg.BufferSize) if err != nil { return nil, trace.Wrap(err) } closeCtx, cancel := context.WithCancel(ctx) watchStarted, signalWatchStart := context.WithCancel(ctx) b := &EtcdBackend{ Entry: log.WithFields(log.Fields{trace.Component: GetName()}), cfg: cfg, nodes: cfg.Nodes, cancelC: make(chan bool, 1), stopC: make(chan bool, 1), clock: clockwork.NewRealClock(), cancel: cancel, ctx: closeCtx, watchStarted: watchStarted, signalWatchStart: signalWatchStart, buf: buf, } if err = b.reconnect(); err != nil { return nil, trace.Wrap(err) } // Wrap backend in a input sanitizer and return it. return b, nil }
go
func New(ctx context.Context, params backend.Params) (*EtcdBackend, error) { var err error if params == nil { return nil, trace.BadParameter("missing etcd configuration") } // convert generic backend parameters structure to etcd config: var cfg *Config if err = utils.ObjectToStruct(params, &cfg); err != nil { return nil, trace.BadParameter("invalid etcd configuration: %v", err) } if err = cfg.Validate(); err != nil { return nil, trace.Wrap(err) } buf, err := backend.NewCircularBuffer(ctx, cfg.BufferSize) if err != nil { return nil, trace.Wrap(err) } closeCtx, cancel := context.WithCancel(ctx) watchStarted, signalWatchStart := context.WithCancel(ctx) b := &EtcdBackend{ Entry: log.WithFields(log.Fields{trace.Component: GetName()}), cfg: cfg, nodes: cfg.Nodes, cancelC: make(chan bool, 1), stopC: make(chan bool, 1), clock: clockwork.NewRealClock(), cancel: cancel, ctx: closeCtx, watchStarted: watchStarted, signalWatchStart: signalWatchStart, buf: buf, } if err = b.reconnect(); err != nil { return nil, trace.Wrap(err) } // Wrap backend in a input sanitizer and return it. return b, nil }
[ "func", "New", "(", "ctx", "context", ".", "Context", ",", "params", "backend", ".", "Params", ")", "(", "*", "EtcdBackend", ",", "error", ")", "{", "var", "err", "error", "\n", "if", "params", "==", "nil", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// convert generic backend parameters structure to etcd config:", "var", "cfg", "*", "Config", "\n", "if", "err", "=", "utils", ".", "ObjectToStruct", "(", "params", ",", "&", "cfg", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "err", "=", "cfg", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "buf", ",", "err", ":=", "backend", ".", "NewCircularBuffer", "(", "ctx", ",", "cfg", ".", "BufferSize", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "closeCtx", ",", "cancel", ":=", "context", ".", "WithCancel", "(", "ctx", ")", "\n", "watchStarted", ",", "signalWatchStart", ":=", "context", ".", "WithCancel", "(", "ctx", ")", "\n", "b", ":=", "&", "EtcdBackend", "{", "Entry", ":", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "trace", ".", "Component", ":", "GetName", "(", ")", "}", ")", ",", "cfg", ":", "cfg", ",", "nodes", ":", "cfg", ".", "Nodes", ",", "cancelC", ":", "make", "(", "chan", "bool", ",", "1", ")", ",", "stopC", ":", "make", "(", "chan", "bool", ",", "1", ")", ",", "clock", ":", "clockwork", ".", "NewRealClock", "(", ")", ",", "cancel", ":", "cancel", ",", "ctx", ":", "closeCtx", ",", "watchStarted", ":", "watchStarted", ",", "signalWatchStart", ":", "signalWatchStart", ",", "buf", ":", "buf", ",", "}", "\n", "if", "err", "=", "b", ".", "reconnect", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "// Wrap backend in a input sanitizer and return it.", "return", "b", ",", "nil", "\n", "}" ]
// New returns new instance of Etcd-powered backend
[ "New", "returns", "new", "instance", "of", "Etcd", "-", "powered", "backend" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/etcdbk/etcd.go#L168-L207
train
gravitational/teleport
lib/backend/etcdbk/etcd.go
KeepAlive
func (b *EtcdBackend) KeepAlive(ctx context.Context, lease backend.Lease, expires time.Time) error { if lease.ID == 0 { return trace.BadParameter("lease is not specified") } re, err := b.client.Get(ctx, prependPrefix(lease.Key), clientv3.WithSerializable(), clientv3.WithKeysOnly()) if err != nil { return convertErr(err) } if len(re.Kvs) == 0 { return trace.NotFound("item %q is not found", string(lease.Key)) } // instead of keep-alive on the old lease, setup a new lease // because we would like the event to be generated // which does not happen in case of lease keep-alive var opts []clientv3.OpOption var newLease backend.Lease if err := b.setupLease(ctx, backend.Item{Expires: expires}, &newLease, &opts); err != nil { return trace.Wrap(err) } opts = append(opts, clientv3.WithIgnoreValue()) kv := re.Kvs[0] _, err = b.client.Put(ctx, string(kv.Key), "", opts...) return convertErr(err) }
go
func (b *EtcdBackend) KeepAlive(ctx context.Context, lease backend.Lease, expires time.Time) error { if lease.ID == 0 { return trace.BadParameter("lease is not specified") } re, err := b.client.Get(ctx, prependPrefix(lease.Key), clientv3.WithSerializable(), clientv3.WithKeysOnly()) if err != nil { return convertErr(err) } if len(re.Kvs) == 0 { return trace.NotFound("item %q is not found", string(lease.Key)) } // instead of keep-alive on the old lease, setup a new lease // because we would like the event to be generated // which does not happen in case of lease keep-alive var opts []clientv3.OpOption var newLease backend.Lease if err := b.setupLease(ctx, backend.Item{Expires: expires}, &newLease, &opts); err != nil { return trace.Wrap(err) } opts = append(opts, clientv3.WithIgnoreValue()) kv := re.Kvs[0] _, err = b.client.Put(ctx, string(kv.Key), "", opts...) return convertErr(err) }
[ "func", "(", "b", "*", "EtcdBackend", ")", "KeepAlive", "(", "ctx", "context", ".", "Context", ",", "lease", "backend", ".", "Lease", ",", "expires", "time", ".", "Time", ")", "error", "{", "if", "lease", ".", "ID", "==", "0", "{", "return", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "re", ",", "err", ":=", "b", ".", "client", ".", "Get", "(", "ctx", ",", "prependPrefix", "(", "lease", ".", "Key", ")", ",", "clientv3", ".", "WithSerializable", "(", ")", ",", "clientv3", ".", "WithKeysOnly", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "convertErr", "(", "err", ")", "\n", "}", "\n", "if", "len", "(", "re", ".", "Kvs", ")", "==", "0", "{", "return", "trace", ".", "NotFound", "(", "\"", "\"", ",", "string", "(", "lease", ".", "Key", ")", ")", "\n", "}", "\n", "// instead of keep-alive on the old lease, setup a new lease", "// because we would like the event to be generated", "// which does not happen in case of lease keep-alive", "var", "opts", "[", "]", "clientv3", ".", "OpOption", "\n", "var", "newLease", "backend", ".", "Lease", "\n", "if", "err", ":=", "b", ".", "setupLease", "(", "ctx", ",", "backend", ".", "Item", "{", "Expires", ":", "expires", "}", ",", "&", "newLease", ",", "&", "opts", ")", ";", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "opts", "=", "append", "(", "opts", ",", "clientv3", ".", "WithIgnoreValue", "(", ")", ")", "\n", "kv", ":=", "re", ".", "Kvs", "[", "0", "]", "\n", "_", ",", "err", "=", "b", ".", "client", ".", "Put", "(", "ctx", ",", "string", "(", "kv", ".", "Key", ")", ",", "\"", "\"", ",", "opts", "...", ")", "\n", "return", "convertErr", "(", "err", ")", "\n", "}" ]
// KeepAlive updates TTL on the lease ID
[ "KeepAlive", "updates", "TTL", "on", "the", "lease", "ID" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/etcdbk/etcd.go#L487-L510
train
gravitational/teleport
lib/backend/etcdbk/etcd.go
seconds
func seconds(ttl time.Duration) int64 { i := int64(ttl / time.Second) if i <= 0 { i = 1 } return i }
go
func seconds(ttl time.Duration) int64 { i := int64(ttl / time.Second) if i <= 0 { i = 1 } return i }
[ "func", "seconds", "(", "ttl", "time", ".", "Duration", ")", "int64", "{", "i", ":=", "int64", "(", "ttl", "/", "time", ".", "Second", ")", "\n", "if", "i", "<=", "0", "{", "i", "=", "1", "\n", "}", "\n", "return", "i", "\n", "}" ]
// seconds converts duration to seconds, rounds up to 1 second
[ "seconds", "converts", "duration", "to", "seconds", "rounds", "up", "to", "1", "second" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/etcdbk/etcd.go#L606-L612
train
gravitational/teleport
tool/tctl/common/auth_command.go
GenerateKeys
func (a *AuthCommand) GenerateKeys() error { keygen, err := native.New(context.TODO(), native.PrecomputeKeys(0)) if err != nil { return trace.Wrap(err) } defer keygen.Close() privBytes, pubBytes, err := keygen.GenerateKeyPair("") if err != nil { return trace.Wrap(err) } err = ioutil.WriteFile(a.genPubPath, pubBytes, 0600) if err != nil { return trace.Wrap(err) } err = ioutil.WriteFile(a.genPrivPath, privBytes, 0600) if err != nil { return trace.Wrap(err) } fmt.Printf("wrote public key to: %v and private key to: %v\n", a.genPubPath, a.genPrivPath) return nil }
go
func (a *AuthCommand) GenerateKeys() error { keygen, err := native.New(context.TODO(), native.PrecomputeKeys(0)) if err != nil { return trace.Wrap(err) } defer keygen.Close() privBytes, pubBytes, err := keygen.GenerateKeyPair("") if err != nil { return trace.Wrap(err) } err = ioutil.WriteFile(a.genPubPath, pubBytes, 0600) if err != nil { return trace.Wrap(err) } err = ioutil.WriteFile(a.genPrivPath, privBytes, 0600) if err != nil { return trace.Wrap(err) } fmt.Printf("wrote public key to: %v and private key to: %v\n", a.genPubPath, a.genPrivPath) return nil }
[ "func", "(", "a", "*", "AuthCommand", ")", "GenerateKeys", "(", ")", "error", "{", "keygen", ",", "err", ":=", "native", ".", "New", "(", "context", ".", "TODO", "(", ")", ",", "native", ".", "PrecomputeKeys", "(", "0", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "defer", "keygen", ".", "Close", "(", ")", "\n", "privBytes", ",", "pubBytes", ",", "err", ":=", "keygen", ".", "GenerateKeyPair", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "err", "=", "ioutil", ".", "WriteFile", "(", "a", ".", "genPubPath", ",", "pubBytes", ",", "0600", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "err", "=", "ioutil", ".", "WriteFile", "(", "a", ".", "genPrivPath", ",", "privBytes", ",", "0600", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "a", ".", "genPubPath", ",", "a", ".", "genPrivPath", ")", "\n", "return", "nil", "\n", "}" ]
// GenerateKeys generates a new keypair
[ "GenerateKeys", "generates", "a", "new", "keypair" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/auth_command.go#L219-L241
train
gravitational/teleport
tool/tctl/common/auth_command.go
GenerateAndSignKeys
func (a *AuthCommand) GenerateAndSignKeys(clusterApi auth.ClientI) error { switch { case a.genUser != "" && a.genHost == "": return a.generateUserKeys(clusterApi) case a.genUser == "" && a.genHost != "": return a.generateHostKeys(clusterApi) default: return trace.BadParameter("--user or --host must be specified") } }
go
func (a *AuthCommand) GenerateAndSignKeys(clusterApi auth.ClientI) error { switch { case a.genUser != "" && a.genHost == "": return a.generateUserKeys(clusterApi) case a.genUser == "" && a.genHost != "": return a.generateHostKeys(clusterApi) default: return trace.BadParameter("--user or --host must be specified") } }
[ "func", "(", "a", "*", "AuthCommand", ")", "GenerateAndSignKeys", "(", "clusterApi", "auth", ".", "ClientI", ")", "error", "{", "switch", "{", "case", "a", ".", "genUser", "!=", "\"", "\"", "&&", "a", ".", "genHost", "==", "\"", "\"", ":", "return", "a", ".", "generateUserKeys", "(", "clusterApi", ")", "\n", "case", "a", ".", "genUser", "==", "\"", "\"", "&&", "a", ".", "genHost", "!=", "\"", "\"", ":", "return", "a", ".", "generateHostKeys", "(", "clusterApi", ")", "\n", "default", ":", "return", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// GenerateAndSignKeys generates a new keypair and signs it for role
[ "GenerateAndSignKeys", "generates", "a", "new", "keypair", "and", "signs", "it", "for", "role" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/auth_command.go#L244-L253
train
gravitational/teleport
tool/tctl/common/auth_command.go
RotateCertAuthority
func (a *AuthCommand) RotateCertAuthority(client auth.ClientI) error { req := auth.RotateRequest{ Type: services.CertAuthType(a.rotateType), GracePeriod: &a.rotateGracePeriod, TargetPhase: a.rotateTargetPhase, } if a.rotateManualMode { req.Mode = services.RotationModeManual } else { req.Mode = services.RotationModeAuto } if err := client.RotateCertAuthority(req); err != nil { return err } if a.rotateTargetPhase != "" { fmt.Printf("Updated rotation phase to %q. To check status use 'tctl status'\n", a.rotateTargetPhase) } else { fmt.Printf("Initiated certificate authority rotation. To check status use 'tctl status'\n") } return nil }
go
func (a *AuthCommand) RotateCertAuthority(client auth.ClientI) error { req := auth.RotateRequest{ Type: services.CertAuthType(a.rotateType), GracePeriod: &a.rotateGracePeriod, TargetPhase: a.rotateTargetPhase, } if a.rotateManualMode { req.Mode = services.RotationModeManual } else { req.Mode = services.RotationModeAuto } if err := client.RotateCertAuthority(req); err != nil { return err } if a.rotateTargetPhase != "" { fmt.Printf("Updated rotation phase to %q. To check status use 'tctl status'\n", a.rotateTargetPhase) } else { fmt.Printf("Initiated certificate authority rotation. To check status use 'tctl status'\n") } return nil }
[ "func", "(", "a", "*", "AuthCommand", ")", "RotateCertAuthority", "(", "client", "auth", ".", "ClientI", ")", "error", "{", "req", ":=", "auth", ".", "RotateRequest", "{", "Type", ":", "services", ".", "CertAuthType", "(", "a", ".", "rotateType", ")", ",", "GracePeriod", ":", "&", "a", ".", "rotateGracePeriod", ",", "TargetPhase", ":", "a", ".", "rotateTargetPhase", ",", "}", "\n", "if", "a", ".", "rotateManualMode", "{", "req", ".", "Mode", "=", "services", ".", "RotationModeManual", "\n", "}", "else", "{", "req", ".", "Mode", "=", "services", ".", "RotationModeAuto", "\n", "}", "\n", "if", "err", ":=", "client", ".", "RotateCertAuthority", "(", "req", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "a", ".", "rotateTargetPhase", "!=", "\"", "\"", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "a", ".", "rotateTargetPhase", ")", "\n", "}", "else", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// RotateCertAuthority starts or restarts certificate authority rotation process
[ "RotateCertAuthority", "starts", "or", "restarts", "certificate", "authority", "rotation", "process" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/auth_command.go#L256-L277
train
gravitational/teleport
lib/backend/legacy/legacy.go
CollectOptions
func CollectOptions(opts []OpOption) (*OpConfig, error) { cfg := OpConfig{} for _, o := range opts { if err := o(&cfg); err != nil { return nil, trace.Wrap(err) } } return &cfg, nil }
go
func CollectOptions(opts []OpOption) (*OpConfig, error) { cfg := OpConfig{} for _, o := range opts { if err := o(&cfg); err != nil { return nil, trace.Wrap(err) } } return &cfg, nil }
[ "func", "CollectOptions", "(", "opts", "[", "]", "OpOption", ")", "(", "*", "OpConfig", ",", "error", ")", "{", "cfg", ":=", "OpConfig", "{", "}", "\n", "for", "_", ",", "o", ":=", "range", "opts", "{", "if", "err", ":=", "o", "(", "&", "cfg", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "&", "cfg", ",", "nil", "\n", "}" ]
// CollectOptions collects all options from functional // arg and returns config
[ "CollectOptions", "collects", "all", "options", "from", "functional", "arg", "and", "returns", "config" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/legacy.go#L96-L104
train
gravitational/teleport
lib/backend/legacy/legacy.go
ValidateLockTTL
func ValidateLockTTL(ttl time.Duration) error { if ttl == Forever || ttl > MaxLockDuration { return trace.BadParameter("locks cannot exceed %v", MaxLockDuration) } return nil }
go
func ValidateLockTTL(ttl time.Duration) error { if ttl == Forever || ttl > MaxLockDuration { return trace.BadParameter("locks cannot exceed %v", MaxLockDuration) } return nil }
[ "func", "ValidateLockTTL", "(", "ttl", "time", ".", "Duration", ")", "error", "{", "if", "ttl", "==", "Forever", "||", "ttl", ">", "MaxLockDuration", "{", "return", "trace", ".", "BadParameter", "(", "\"", "\"", ",", "MaxLockDuration", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ValidateLockTTL helper allows all backends to validate lock TTL parameter
[ "ValidateLockTTL", "helper", "allows", "all", "backends", "to", "validate", "lock", "TTL", "parameter" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/legacy.go#L160-L165
train
gravitational/teleport
lib/backend/legacy/legacy.go
TTL
func TTL(clock clockwork.Clock, t time.Time) time.Duration { if t.IsZero() { return Forever } diff := t.UTC().Sub(clock.Now().UTC()) if diff < 0 { return Forever } return diff }
go
func TTL(clock clockwork.Clock, t time.Time) time.Duration { if t.IsZero() { return Forever } diff := t.UTC().Sub(clock.Now().UTC()) if diff < 0 { return Forever } return diff }
[ "func", "TTL", "(", "clock", "clockwork", ".", "Clock", ",", "t", "time", ".", "Time", ")", "time", ".", "Duration", "{", "if", "t", ".", "IsZero", "(", ")", "{", "return", "Forever", "\n", "}", "\n", "diff", ":=", "t", ".", "UTC", "(", ")", ".", "Sub", "(", "clock", ".", "Now", "(", ")", ".", "UTC", "(", ")", ")", "\n", "if", "diff", "<", "0", "{", "return", "Forever", "\n", "}", "\n", "return", "diff", "\n", "}" ]
// TTL converts time to TTL from current time supplied // by provider, if t is zero, returns forever
[ "TTL", "converts", "time", "to", "TTL", "from", "current", "time", "supplied", "by", "provider", "if", "t", "is", "zero", "returns", "forever" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/legacy.go#L180-L189
train