repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
gravitational/teleport
lib/client/keystore.go
DeleteKeys
func (fs *FSLocalKeyStore) DeleteKeys() error { dirPath := filepath.Join(fs.KeyDir, sessionKeyDir) err := os.RemoveAll(dirPath) if err != nil { return trace.Wrap(err) } return nil }
go
func (fs *FSLocalKeyStore) DeleteKeys() error { dirPath := filepath.Join(fs.KeyDir, sessionKeyDir) err := os.RemoveAll(dirPath) if err != nil { return trace.Wrap(err) } return nil }
[ "func", "(", "fs", "*", "FSLocalKeyStore", ")", "DeleteKeys", "(", ")", "error", "{", "dirPath", ":=", "filepath", ".", "Join", "(", "fs", ".", "KeyDir", ",", "sessionKeyDir", ")", "\n", "err", ":=", "os", ".", "RemoveAll", "(", "dirPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// DeleteKeys removes all session keys from disk.
[ "DeleteKeys", "removes", "all", "session", "keys", "from", "disk", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/keystore.go#L191-L200
train
gravitational/teleport
lib/client/keystore.go
GetKey
func (fs *FSLocalKeyStore) GetKey(proxyHost string, username string) (*Key, error) { dirPath, err := fs.dirFor(proxyHost, false) if err != nil { return nil, trace.Wrap(err) } _, err = ioutil.ReadDir(dirPath) if err != nil { return nil, trace.NotFound("no session keys for %v in %v", username, proxyHost) } certFile := filepath.Join(dirPath, username+fileExtCert) cert, err := ioutil.ReadFile(certFile) if err != nil { fs.log.Error(err) return nil, trace.Wrap(err) } tlsCertFile := filepath.Join(dirPath, username+fileExtTLSCert) tlsCert, err := ioutil.ReadFile(tlsCertFile) if err != nil { fs.log.Error(err) return nil, trace.Wrap(err) } pub, err := ioutil.ReadFile(filepath.Join(dirPath, username+fileExtPub)) if err != nil { fs.log.Error(err) return nil, trace.Wrap(err) } priv, err := ioutil.ReadFile(filepath.Join(dirPath, username)) if err != nil { fs.log.Error(err) return nil, trace.Wrap(err) } key := &Key{Pub: pub, Priv: priv, Cert: cert, ProxyHost: proxyHost, TLSCert: tlsCert} // Validate the key loaded from disk. err = key.CheckCert() if err != nil { // KeyStore should return expired certificates as well if !utils.IsCertExpiredError(err) { return nil, trace.Wrap(err) } } sshCertExpiration, err := key.CertValidBefore() if err != nil { return nil, trace.Wrap(err) } tlsCertExpiration, err := key.TLSCertValidBefore() if err != nil { return nil, trace.Wrap(err) } // Note, we may be returning expired certificates here, that is okay. If the // certificates is expired, it's the responsibility of the TeleportClient to // perform cleanup of the certificates and the profile. fs.log.Debugf("Returning SSH certificate %q valid until %q, TLS certificate %q valid until %q.", certFile, sshCertExpiration, tlsCertFile, tlsCertExpiration) return key, nil }
go
func (fs *FSLocalKeyStore) GetKey(proxyHost string, username string) (*Key, error) { dirPath, err := fs.dirFor(proxyHost, false) if err != nil { return nil, trace.Wrap(err) } _, err = ioutil.ReadDir(dirPath) if err != nil { return nil, trace.NotFound("no session keys for %v in %v", username, proxyHost) } certFile := filepath.Join(dirPath, username+fileExtCert) cert, err := ioutil.ReadFile(certFile) if err != nil { fs.log.Error(err) return nil, trace.Wrap(err) } tlsCertFile := filepath.Join(dirPath, username+fileExtTLSCert) tlsCert, err := ioutil.ReadFile(tlsCertFile) if err != nil { fs.log.Error(err) return nil, trace.Wrap(err) } pub, err := ioutil.ReadFile(filepath.Join(dirPath, username+fileExtPub)) if err != nil { fs.log.Error(err) return nil, trace.Wrap(err) } priv, err := ioutil.ReadFile(filepath.Join(dirPath, username)) if err != nil { fs.log.Error(err) return nil, trace.Wrap(err) } key := &Key{Pub: pub, Priv: priv, Cert: cert, ProxyHost: proxyHost, TLSCert: tlsCert} // Validate the key loaded from disk. err = key.CheckCert() if err != nil { // KeyStore should return expired certificates as well if !utils.IsCertExpiredError(err) { return nil, trace.Wrap(err) } } sshCertExpiration, err := key.CertValidBefore() if err != nil { return nil, trace.Wrap(err) } tlsCertExpiration, err := key.TLSCertValidBefore() if err != nil { return nil, trace.Wrap(err) } // Note, we may be returning expired certificates here, that is okay. If the // certificates is expired, it's the responsibility of the TeleportClient to // perform cleanup of the certificates and the profile. fs.log.Debugf("Returning SSH certificate %q valid until %q, TLS certificate %q valid until %q.", certFile, sshCertExpiration, tlsCertFile, tlsCertExpiration) return key, nil }
[ "func", "(", "fs", "*", "FSLocalKeyStore", ")", "GetKey", "(", "proxyHost", "string", ",", "username", "string", ")", "(", "*", "Key", ",", "error", ")", "{", "dirPath", ",", "err", ":=", "fs", ".", "dirFor", "(", "proxyHost", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "_", ",", "err", "=", "ioutil", ".", "ReadDir", "(", "dirPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "NotFound", "(", "\"no session keys for %v in %v\"", ",", "username", ",", "proxyHost", ")", "\n", "}", "\n", "certFile", ":=", "filepath", ".", "Join", "(", "dirPath", ",", "username", "+", "fileExtCert", ")", "\n", "cert", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "certFile", ")", "\n", "if", "err", "!=", "nil", "{", "fs", ".", "log", ".", "Error", "(", "err", ")", "\n", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "tlsCertFile", ":=", "filepath", ".", "Join", "(", "dirPath", ",", "username", "+", "fileExtTLSCert", ")", "\n", "tlsCert", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "tlsCertFile", ")", "\n", "if", "err", "!=", "nil", "{", "fs", ".", "log", ".", "Error", "(", "err", ")", "\n", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "pub", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "filepath", ".", "Join", "(", "dirPath", ",", "username", "+", "fileExtPub", ")", ")", "\n", "if", "err", "!=", "nil", "{", "fs", ".", "log", ".", "Error", "(", "err", ")", "\n", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "priv", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "filepath", ".", "Join", "(", "dirPath", ",", "username", ")", ")", "\n", "if", "err", "!=", "nil", "{", "fs", ".", "log", ".", "Error", "(", "err", ")", "\n", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "key", ":=", "&", "Key", "{", "Pub", ":", "pub", ",", "Priv", ":", "priv", ",", "Cert", ":", "cert", ",", "ProxyHost", ":", "proxyHost", ",", "TLSCert", ":", "tlsCert", "}", "\n", "err", "=", "key", ".", "CheckCert", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "!", "utils", ".", "IsCertExpiredError", "(", "err", ")", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n", "sshCertExpiration", ",", "err", ":=", "key", ".", "CertValidBefore", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "tlsCertExpiration", ",", "err", ":=", "key", ".", "TLSCertValidBefore", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "fs", ".", "log", ".", "Debugf", "(", "\"Returning SSH certificate %q valid until %q, TLS certificate %q valid until %q.\"", ",", "certFile", ",", "sshCertExpiration", ",", "tlsCertFile", ",", "tlsCertExpiration", ")", "\n", "return", "key", ",", "nil", "\n", "}" ]
// GetKey returns a key for a given host. If the key is not found, // returns trace.NotFound error.
[ "GetKey", "returns", "a", "key", "for", "a", "given", "host", ".", "If", "the", "key", "is", "not", "found", "returns", "trace", ".", "NotFound", "error", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/keystore.go#L204-L263
train
gravitational/teleport
lib/client/keystore.go
SaveCerts
func (fs *FSLocalKeyStore) SaveCerts(proxy string, cas []auth.TrustedCerts) error { dir, err := fs.dirFor(proxy, true) if err != nil { return trace.Wrap(err) } fp, err := os.OpenFile(filepath.Join(dir, fileNameTLSCerts), os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0640) if err != nil { return trace.Wrap(err) } defer fp.Sync() defer fp.Close() for _, ca := range cas { for _, cert := range ca.TLSCertificates { _, err := fp.Write(cert) if err != nil { return trace.ConvertSystemError(err) } _, err = fp.WriteString("\n") if err != nil { return trace.ConvertSystemError(err) } } } return nil }
go
func (fs *FSLocalKeyStore) SaveCerts(proxy string, cas []auth.TrustedCerts) error { dir, err := fs.dirFor(proxy, true) if err != nil { return trace.Wrap(err) } fp, err := os.OpenFile(filepath.Join(dir, fileNameTLSCerts), os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0640) if err != nil { return trace.Wrap(err) } defer fp.Sync() defer fp.Close() for _, ca := range cas { for _, cert := range ca.TLSCertificates { _, err := fp.Write(cert) if err != nil { return trace.ConvertSystemError(err) } _, err = fp.WriteString("\n") if err != nil { return trace.ConvertSystemError(err) } } } return nil }
[ "func", "(", "fs", "*", "FSLocalKeyStore", ")", "SaveCerts", "(", "proxy", "string", ",", "cas", "[", "]", "auth", ".", "TrustedCerts", ")", "error", "{", "dir", ",", "err", ":=", "fs", ".", "dirFor", "(", "proxy", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "fp", ",", "err", ":=", "os", ".", "OpenFile", "(", "filepath", ".", "Join", "(", "dir", ",", "fileNameTLSCerts", ")", ",", "os", ".", "O_CREATE", "|", "os", ".", "O_RDWR", "|", "os", ".", "O_TRUNC", ",", "0640", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "defer", "fp", ".", "Sync", "(", ")", "\n", "defer", "fp", ".", "Close", "(", ")", "\n", "for", "_", ",", "ca", ":=", "range", "cas", "{", "for", "_", ",", "cert", ":=", "range", "ca", ".", "TLSCertificates", "{", "_", ",", "err", ":=", "fp", ".", "Write", "(", "cert", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "ConvertSystemError", "(", "err", ")", "\n", "}", "\n", "_", ",", "err", "=", "fp", ".", "WriteString", "(", "\"\\n\"", ")", "\n", "\\n", "\n", "}", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "ConvertSystemError", "(", "err", ")", "\n", "}", "\n", "}" ]
// SaveCerts saves trusted TLS certificates of certificate authorities
[ "SaveCerts", "saves", "trusted", "TLS", "certificates", "of", "certificate", "authorities" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/keystore.go#L266-L290
train
gravitational/teleport
lib/client/keystore.go
GetCertsPEM
func (fs *FSLocalKeyStore) GetCertsPEM(proxy string) ([]byte, error) { dir, err := fs.dirFor(proxy, false) if err != nil { return nil, trace.Wrap(err) } return ioutil.ReadFile(filepath.Join(dir, fileNameTLSCerts)) }
go
func (fs *FSLocalKeyStore) GetCertsPEM(proxy string) ([]byte, error) { dir, err := fs.dirFor(proxy, false) if err != nil { return nil, trace.Wrap(err) } return ioutil.ReadFile(filepath.Join(dir, fileNameTLSCerts)) }
[ "func", "(", "fs", "*", "FSLocalKeyStore", ")", "GetCertsPEM", "(", "proxy", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "dir", ",", "err", ":=", "fs", ".", "dirFor", "(", "proxy", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "ioutil", ".", "ReadFile", "(", "filepath", ".", "Join", "(", "dir", ",", "fileNameTLSCerts", ")", ")", "\n", "}" ]
// GetCertsPEM returns trusted TLS certificates of certificate authorities PEM block
[ "GetCertsPEM", "returns", "trusted", "TLS", "certificates", "of", "certificate", "authorities", "PEM", "block" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/keystore.go#L293-L299
train
gravitational/teleport
lib/client/keystore.go
GetCerts
func (fs *FSLocalKeyStore) GetCerts(proxy string) (*x509.CertPool, error) { dir, err := fs.dirFor(proxy, false) if err != nil { return nil, trace.Wrap(err) } bytes, err := ioutil.ReadFile(filepath.Join(dir, fileNameTLSCerts)) if err != nil { return nil, trace.ConvertSystemError(err) } pool := x509.NewCertPool() for len(bytes) > 0 { var block *pem.Block block, bytes = pem.Decode(bytes) if block == nil { break } if block.Type != "CERTIFICATE" || len(block.Headers) != 0 { fs.log.Debugf("Skipping PEM block type=%v headers=%v.", block.Type, block.Headers) continue } cert, err := x509.ParseCertificate(block.Bytes) if err != nil { return nil, trace.BadParameter("failed to parse certificate: %v", err) } fs.log.Debugf("Adding trusted cluster certificate authority %q to trusted pool.", cert.Issuer) pool.AddCert(cert) } return pool, nil }
go
func (fs *FSLocalKeyStore) GetCerts(proxy string) (*x509.CertPool, error) { dir, err := fs.dirFor(proxy, false) if err != nil { return nil, trace.Wrap(err) } bytes, err := ioutil.ReadFile(filepath.Join(dir, fileNameTLSCerts)) if err != nil { return nil, trace.ConvertSystemError(err) } pool := x509.NewCertPool() for len(bytes) > 0 { var block *pem.Block block, bytes = pem.Decode(bytes) if block == nil { break } if block.Type != "CERTIFICATE" || len(block.Headers) != 0 { fs.log.Debugf("Skipping PEM block type=%v headers=%v.", block.Type, block.Headers) continue } cert, err := x509.ParseCertificate(block.Bytes) if err != nil { return nil, trace.BadParameter("failed to parse certificate: %v", err) } fs.log.Debugf("Adding trusted cluster certificate authority %q to trusted pool.", cert.Issuer) pool.AddCert(cert) } return pool, nil }
[ "func", "(", "fs", "*", "FSLocalKeyStore", ")", "GetCerts", "(", "proxy", "string", ")", "(", "*", "x509", ".", "CertPool", ",", "error", ")", "{", "dir", ",", "err", ":=", "fs", ".", "dirFor", "(", "proxy", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "bytes", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "filepath", ".", "Join", "(", "dir", ",", "fileNameTLSCerts", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "ConvertSystemError", "(", "err", ")", "\n", "}", "\n", "pool", ":=", "x509", ".", "NewCertPool", "(", ")", "\n", "for", "len", "(", "bytes", ")", ">", "0", "{", "var", "block", "*", "pem", ".", "Block", "\n", "block", ",", "bytes", "=", "pem", ".", "Decode", "(", "bytes", ")", "\n", "if", "block", "==", "nil", "{", "break", "\n", "}", "\n", "if", "block", ".", "Type", "!=", "\"CERTIFICATE\"", "||", "len", "(", "block", ".", "Headers", ")", "!=", "0", "{", "fs", ".", "log", ".", "Debugf", "(", "\"Skipping PEM block type=%v headers=%v.\"", ",", "block", ".", "Type", ",", "block", ".", "Headers", ")", "\n", "continue", "\n", "}", "\n", "cert", ",", "err", ":=", "x509", ".", "ParseCertificate", "(", "block", ".", "Bytes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"failed to parse certificate: %v\"", ",", "err", ")", "\n", "}", "\n", "fs", ".", "log", ".", "Debugf", "(", "\"Adding trusted cluster certificate authority %q to trusted pool.\"", ",", "cert", ".", "Issuer", ")", "\n", "pool", ".", "AddCert", "(", "cert", ")", "\n", "}", "\n", "return", "pool", ",", "nil", "\n", "}" ]
// GetCerts returns trusted TLS certificates of certificate authorities
[ "GetCerts", "returns", "trusted", "TLS", "certificates", "of", "certificate", "authorities" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/keystore.go#L302-L331
train
gravitational/teleport
lib/client/keystore.go
AddKnownHostKeys
func (fs *FSLocalKeyStore) AddKnownHostKeys(hostname string, hostKeys []ssh.PublicKey) error { fp, err := os.OpenFile(filepath.Join(fs.KeyDir, fileNameKnownHosts), os.O_CREATE|os.O_RDWR, 0640) if err != nil { return trace.Wrap(err) } defer fp.Sync() defer fp.Close() // read all existing entries into a map (this removes any pre-existing dupes) entries := make(map[string]int) output := make([]string, 0) scanner := bufio.NewScanner(fp) for scanner.Scan() { line := scanner.Text() if _, exists := entries[line]; !exists { output = append(output, line) entries[line] = 1 } } // add every host key to the list of entries for i := range hostKeys { fs.log.Debugf("Adding known host %s with key: %v", hostname, sshutils.Fingerprint(hostKeys[i])) bytes := ssh.MarshalAuthorizedKey(hostKeys[i]) line := strings.TrimSpace(fmt.Sprintf("%s %s", hostname, bytes)) if _, exists := entries[line]; !exists { output = append(output, line) } } // re-create the file: _, err = fp.Seek(0, 0) if err != nil { return trace.Wrap(err) } if err = fp.Truncate(0); err != nil { return trace.Wrap(err) } for _, line := range output { fmt.Fprintf(fp, "%s\n", line) } return nil }
go
func (fs *FSLocalKeyStore) AddKnownHostKeys(hostname string, hostKeys []ssh.PublicKey) error { fp, err := os.OpenFile(filepath.Join(fs.KeyDir, fileNameKnownHosts), os.O_CREATE|os.O_RDWR, 0640) if err != nil { return trace.Wrap(err) } defer fp.Sync() defer fp.Close() // read all existing entries into a map (this removes any pre-existing dupes) entries := make(map[string]int) output := make([]string, 0) scanner := bufio.NewScanner(fp) for scanner.Scan() { line := scanner.Text() if _, exists := entries[line]; !exists { output = append(output, line) entries[line] = 1 } } // add every host key to the list of entries for i := range hostKeys { fs.log.Debugf("Adding known host %s with key: %v", hostname, sshutils.Fingerprint(hostKeys[i])) bytes := ssh.MarshalAuthorizedKey(hostKeys[i]) line := strings.TrimSpace(fmt.Sprintf("%s %s", hostname, bytes)) if _, exists := entries[line]; !exists { output = append(output, line) } } // re-create the file: _, err = fp.Seek(0, 0) if err != nil { return trace.Wrap(err) } if err = fp.Truncate(0); err != nil { return trace.Wrap(err) } for _, line := range output { fmt.Fprintf(fp, "%s\n", line) } return nil }
[ "func", "(", "fs", "*", "FSLocalKeyStore", ")", "AddKnownHostKeys", "(", "hostname", "string", ",", "hostKeys", "[", "]", "ssh", ".", "PublicKey", ")", "error", "{", "fp", ",", "err", ":=", "os", ".", "OpenFile", "(", "filepath", ".", "Join", "(", "fs", ".", "KeyDir", ",", "fileNameKnownHosts", ")", ",", "os", ".", "O_CREATE", "|", "os", ".", "O_RDWR", ",", "0640", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "defer", "fp", ".", "Sync", "(", ")", "\n", "defer", "fp", ".", "Close", "(", ")", "\n", "entries", ":=", "make", "(", "map", "[", "string", "]", "int", ")", "\n", "output", ":=", "make", "(", "[", "]", "string", ",", "0", ")", "\n", "scanner", ":=", "bufio", ".", "NewScanner", "(", "fp", ")", "\n", "for", "scanner", ".", "Scan", "(", ")", "{", "line", ":=", "scanner", ".", "Text", "(", ")", "\n", "if", "_", ",", "exists", ":=", "entries", "[", "line", "]", ";", "!", "exists", "{", "output", "=", "append", "(", "output", ",", "line", ")", "\n", "entries", "[", "line", "]", "=", "1", "\n", "}", "\n", "}", "\n", "for", "i", ":=", "range", "hostKeys", "{", "fs", ".", "log", ".", "Debugf", "(", "\"Adding known host %s with key: %v\"", ",", "hostname", ",", "sshutils", ".", "Fingerprint", "(", "hostKeys", "[", "i", "]", ")", ")", "\n", "bytes", ":=", "ssh", ".", "MarshalAuthorizedKey", "(", "hostKeys", "[", "i", "]", ")", "\n", "line", ":=", "strings", ".", "TrimSpace", "(", "fmt", ".", "Sprintf", "(", "\"%s %s\"", ",", "hostname", ",", "bytes", ")", ")", "\n", "if", "_", ",", "exists", ":=", "entries", "[", "line", "]", ";", "!", "exists", "{", "output", "=", "append", "(", "output", ",", "line", ")", "\n", "}", "\n", "}", "\n", "_", ",", "err", "=", "fp", ".", "Seek", "(", "0", ",", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "err", "=", "fp", ".", "Truncate", "(", "0", ")", ";", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "for", "_", ",", "line", ":=", "range", "output", "{", "fmt", ".", "Fprintf", "(", "fp", ",", "\"%s\\n\"", ",", "\\n", ")", "\n", "}", "\n", "line", "\n", "}" ]
// AddKnownHostKeys adds a new entry to 'known_hosts' file
[ "AddKnownHostKeys", "adds", "a", "new", "entry", "to", "known_hosts", "file" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/keystore.go#L334-L373
train
gravitational/teleport
lib/client/keystore.go
GetKnownHostKeys
func (fs *FSLocalKeyStore) GetKnownHostKeys(hostname string) ([]ssh.PublicKey, error) { bytes, err := ioutil.ReadFile(filepath.Join(fs.KeyDir, fileNameKnownHosts)) if err != nil { if os.IsNotExist(err) { return nil, nil } return nil, trace.Wrap(err) } var ( pubKey ssh.PublicKey retval []ssh.PublicKey = make([]ssh.PublicKey, 0) hosts []string hostMatch bool ) for err == nil { _, hosts, pubKey, _, bytes, err = ssh.ParseKnownHosts(bytes) if err == nil { hostMatch = (hostname == "") if !hostMatch { for i := range hosts { if hosts[i] == hostname { hostMatch = true break } } } if hostMatch { retval = append(retval, pubKey) } } } if err != io.EOF { return nil, trace.Wrap(err) } return retval, nil }
go
func (fs *FSLocalKeyStore) GetKnownHostKeys(hostname string) ([]ssh.PublicKey, error) { bytes, err := ioutil.ReadFile(filepath.Join(fs.KeyDir, fileNameKnownHosts)) if err != nil { if os.IsNotExist(err) { return nil, nil } return nil, trace.Wrap(err) } var ( pubKey ssh.PublicKey retval []ssh.PublicKey = make([]ssh.PublicKey, 0) hosts []string hostMatch bool ) for err == nil { _, hosts, pubKey, _, bytes, err = ssh.ParseKnownHosts(bytes) if err == nil { hostMatch = (hostname == "") if !hostMatch { for i := range hosts { if hosts[i] == hostname { hostMatch = true break } } } if hostMatch { retval = append(retval, pubKey) } } } if err != io.EOF { return nil, trace.Wrap(err) } return retval, nil }
[ "func", "(", "fs", "*", "FSLocalKeyStore", ")", "GetKnownHostKeys", "(", "hostname", "string", ")", "(", "[", "]", "ssh", ".", "PublicKey", ",", "error", ")", "{", "bytes", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "filepath", ".", "Join", "(", "fs", ".", "KeyDir", ",", "fileNameKnownHosts", ")", ")", "\n", "if", "err", "!=", "nil", "{", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "var", "(", "pubKey", "ssh", ".", "PublicKey", "\n", "retval", "[", "]", "ssh", ".", "PublicKey", "=", "make", "(", "[", "]", "ssh", ".", "PublicKey", ",", "0", ")", "\n", "hosts", "[", "]", "string", "\n", "hostMatch", "bool", "\n", ")", "\n", "for", "err", "==", "nil", "{", "_", ",", "hosts", ",", "pubKey", ",", "_", ",", "bytes", ",", "err", "=", "ssh", ".", "ParseKnownHosts", "(", "bytes", ")", "\n", "if", "err", "==", "nil", "{", "hostMatch", "=", "(", "hostname", "==", "\"\"", ")", "\n", "if", "!", "hostMatch", "{", "for", "i", ":=", "range", "hosts", "{", "if", "hosts", "[", "i", "]", "==", "hostname", "{", "hostMatch", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "hostMatch", "{", "retval", "=", "append", "(", "retval", ",", "pubKey", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "err", "!=", "io", ".", "EOF", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "retval", ",", "nil", "\n", "}" ]
// GetKnownHostKeys returns all known public keys from 'known_hosts'
[ "GetKnownHostKeys", "returns", "all", "known", "public", "keys", "from", "known_hosts" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/keystore.go#L376-L411
train
gravitational/teleport
tool/tctl/common/node_command.go
Initialize
func (c *NodeCommand) Initialize(app *kingpin.Application, config *service.Config) { c.config = config // add node command nodes := app.Command("nodes", "Issue invites for other nodes to join the cluster") c.nodeAdd = nodes.Command("add", "Generate a node invitation token") c.nodeAdd.Flag("roles", "Comma-separated list of roles for the new node to assume [node]").Default("node").StringVar(&c.roles) c.nodeAdd.Flag("ttl", "Time to live for a generated token").Default(defaults.ProvisioningTokenTTL.String()).DurationVar(&c.ttl) c.nodeAdd.Flag("token", "Custom token to use, autogenerated if not provided").StringVar(&c.token) c.nodeAdd.Flag("format", "Output format, 'text' or 'json'").Hidden().Default("text").StringVar(&c.format) c.nodeAdd.Alias(AddNodeHelp) c.nodeList = nodes.Command("ls", "List all active SSH nodes within the cluster") c.nodeList.Flag("namespace", "Namespace of the nodes").Default(defaults.Namespace).StringVar(&c.namespace) c.nodeList.Alias(ListNodesHelp) }
go
func (c *NodeCommand) Initialize(app *kingpin.Application, config *service.Config) { c.config = config // add node command nodes := app.Command("nodes", "Issue invites for other nodes to join the cluster") c.nodeAdd = nodes.Command("add", "Generate a node invitation token") c.nodeAdd.Flag("roles", "Comma-separated list of roles for the new node to assume [node]").Default("node").StringVar(&c.roles) c.nodeAdd.Flag("ttl", "Time to live for a generated token").Default(defaults.ProvisioningTokenTTL.String()).DurationVar(&c.ttl) c.nodeAdd.Flag("token", "Custom token to use, autogenerated if not provided").StringVar(&c.token) c.nodeAdd.Flag("format", "Output format, 'text' or 'json'").Hidden().Default("text").StringVar(&c.format) c.nodeAdd.Alias(AddNodeHelp) c.nodeList = nodes.Command("ls", "List all active SSH nodes within the cluster") c.nodeList.Flag("namespace", "Namespace of the nodes").Default(defaults.Namespace).StringVar(&c.namespace) c.nodeList.Alias(ListNodesHelp) }
[ "func", "(", "c", "*", "NodeCommand", ")", "Initialize", "(", "app", "*", "kingpin", ".", "Application", ",", "config", "*", "service", ".", "Config", ")", "{", "c", ".", "config", "=", "config", "\n", "nodes", ":=", "app", ".", "Command", "(", "\"nodes\"", ",", "\"Issue invites for other nodes to join the cluster\"", ")", "\n", "c", ".", "nodeAdd", "=", "nodes", ".", "Command", "(", "\"add\"", ",", "\"Generate a node invitation token\"", ")", "\n", "c", ".", "nodeAdd", ".", "Flag", "(", "\"roles\"", ",", "\"Comma-separated list of roles for the new node to assume [node]\"", ")", ".", "Default", "(", "\"node\"", ")", ".", "StringVar", "(", "&", "c", ".", "roles", ")", "\n", "c", ".", "nodeAdd", ".", "Flag", "(", "\"ttl\"", ",", "\"Time to live for a generated token\"", ")", ".", "Default", "(", "defaults", ".", "ProvisioningTokenTTL", ".", "String", "(", ")", ")", ".", "DurationVar", "(", "&", "c", ".", "ttl", ")", "\n", "c", ".", "nodeAdd", ".", "Flag", "(", "\"token\"", ",", "\"Custom token to use, autogenerated if not provided\"", ")", ".", "StringVar", "(", "&", "c", ".", "token", ")", "\n", "c", ".", "nodeAdd", ".", "Flag", "(", "\"format\"", ",", "\"Output format, 'text' or 'json'\"", ")", ".", "Hidden", "(", ")", ".", "Default", "(", "\"text\"", ")", ".", "StringVar", "(", "&", "c", ".", "format", ")", "\n", "c", ".", "nodeAdd", ".", "Alias", "(", "AddNodeHelp", ")", "\n", "c", ".", "nodeList", "=", "nodes", ".", "Command", "(", "\"ls\"", ",", "\"List all active SSH nodes within the cluster\"", ")", "\n", "c", ".", "nodeList", ".", "Flag", "(", "\"namespace\"", ",", "\"Namespace of the nodes\"", ")", ".", "Default", "(", "defaults", ".", "Namespace", ")", ".", "StringVar", "(", "&", "c", ".", "namespace", ")", "\n", "c", ".", "nodeList", ".", "Alias", "(", "ListNodesHelp", ")", "\n", "}" ]
// Initialize allows NodeCommand to plug itself into the CLI parser
[ "Initialize", "allows", "NodeCommand", "to", "plug", "itself", "into", "the", "CLI", "parser" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/node_command.go#L57-L72
train
gravitational/teleport
tool/tctl/common/node_command.go
Invite
func (c *NodeCommand) Invite(client auth.ClientI) error { // parse --roles flag roles, err := teleport.ParseRoles(c.roles) if err != nil { return trace.Wrap(err) } token, err := client.GenerateToken(auth.GenerateTokenRequest{Roles: roles, TTL: c.ttl, Token: c.token}) if err != nil { return trace.Wrap(err) } // Calculate the CA pin for this cluster. The CA pin is used by the client // to verify the identity of the Auth Server. caPin, err := calculateCAPin(client) if err != nil { return trace.Wrap(err) } authServers, err := client.GetAuthServers() if err != nil { return trace.Wrap(err) } if len(authServers) == 0 { return trace.Errorf("This cluster does not have any auth servers running.") } // output format swtich: if c.format == "text" { if roles.Include(teleport.RoleTrustedCluster) || roles.Include(teleport.LegacyClusterTokenType) { fmt.Printf(trustedClusterMessage, token, int(c.ttl.Minutes())) } else { fmt.Printf(nodeMessage, token, int(c.ttl.Minutes()), strings.ToLower(roles.String()), token, caPin, authServers[0].GetAddr(), int(c.ttl.Minutes()), authServers[0].GetAddr(), ) } } else { // Always return a list, otherwise we'll break users tooling. See #1846 for // more details. tokens := []string{token} out, err := json.Marshal(tokens) if err != nil { return trace.Wrap(err, "failed to marshal token") } fmt.Printf(string(out)) } return nil }
go
func (c *NodeCommand) Invite(client auth.ClientI) error { // parse --roles flag roles, err := teleport.ParseRoles(c.roles) if err != nil { return trace.Wrap(err) } token, err := client.GenerateToken(auth.GenerateTokenRequest{Roles: roles, TTL: c.ttl, Token: c.token}) if err != nil { return trace.Wrap(err) } // Calculate the CA pin for this cluster. The CA pin is used by the client // to verify the identity of the Auth Server. caPin, err := calculateCAPin(client) if err != nil { return trace.Wrap(err) } authServers, err := client.GetAuthServers() if err != nil { return trace.Wrap(err) } if len(authServers) == 0 { return trace.Errorf("This cluster does not have any auth servers running.") } // output format swtich: if c.format == "text" { if roles.Include(teleport.RoleTrustedCluster) || roles.Include(teleport.LegacyClusterTokenType) { fmt.Printf(trustedClusterMessage, token, int(c.ttl.Minutes())) } else { fmt.Printf(nodeMessage, token, int(c.ttl.Minutes()), strings.ToLower(roles.String()), token, caPin, authServers[0].GetAddr(), int(c.ttl.Minutes()), authServers[0].GetAddr(), ) } } else { // Always return a list, otherwise we'll break users tooling. See #1846 for // more details. tokens := []string{token} out, err := json.Marshal(tokens) if err != nil { return trace.Wrap(err, "failed to marshal token") } fmt.Printf(string(out)) } return nil }
[ "func", "(", "c", "*", "NodeCommand", ")", "Invite", "(", "client", "auth", ".", "ClientI", ")", "error", "{", "roles", ",", "err", ":=", "teleport", ".", "ParseRoles", "(", "c", ".", "roles", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "token", ",", "err", ":=", "client", ".", "GenerateToken", "(", "auth", ".", "GenerateTokenRequest", "{", "Roles", ":", "roles", ",", "TTL", ":", "c", ".", "ttl", ",", "Token", ":", "c", ".", "token", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "caPin", ",", "err", ":=", "calculateCAPin", "(", "client", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "authServers", ",", "err", ":=", "client", ".", "GetAuthServers", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "len", "(", "authServers", ")", "==", "0", "{", "return", "trace", ".", "Errorf", "(", "\"This cluster does not have any auth servers running.\"", ")", "\n", "}", "\n", "if", "c", ".", "format", "==", "\"text\"", "{", "if", "roles", ".", "Include", "(", "teleport", ".", "RoleTrustedCluster", ")", "||", "roles", ".", "Include", "(", "teleport", ".", "LegacyClusterTokenType", ")", "{", "fmt", ".", "Printf", "(", "trustedClusterMessage", ",", "token", ",", "int", "(", "c", ".", "ttl", ".", "Minutes", "(", ")", ")", ")", "\n", "}", "else", "{", "fmt", ".", "Printf", "(", "nodeMessage", ",", "token", ",", "int", "(", "c", ".", "ttl", ".", "Minutes", "(", ")", ")", ",", "strings", ".", "ToLower", "(", "roles", ".", "String", "(", ")", ")", ",", "token", ",", "caPin", ",", "authServers", "[", "0", "]", ".", "GetAddr", "(", ")", ",", "int", "(", "c", ".", "ttl", ".", "Minutes", "(", ")", ")", ",", "authServers", "[", "0", "]", ".", "GetAddr", "(", ")", ",", ")", "\n", "}", "\n", "}", "else", "{", "tokens", ":=", "[", "]", "string", "{", "token", "}", "\n", "out", ",", "err", ":=", "json", ".", "Marshal", "(", "tokens", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ",", "\"failed to marshal token\"", ")", "\n", "}", "\n", "fmt", ".", "Printf", "(", "string", "(", "out", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Invite generates a token which can be used to add another SSH node // to a cluster
[ "Invite", "generates", "a", "token", "which", "can", "be", "used", "to", "add", "another", "SSH", "node", "to", "a", "cluster" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/node_command.go#L113-L166
train
gravitational/teleport
tool/tctl/common/node_command.go
ListActive
func (c *NodeCommand) ListActive(client auth.ClientI) error { nodes, err := client.GetNodes(c.namespace, services.SkipValidation()) if err != nil { return trace.Wrap(err) } coll := &serverCollection{servers: nodes} coll.writeText(os.Stdout) return nil }
go
func (c *NodeCommand) ListActive(client auth.ClientI) error { nodes, err := client.GetNodes(c.namespace, services.SkipValidation()) if err != nil { return trace.Wrap(err) } coll := &serverCollection{servers: nodes} coll.writeText(os.Stdout) return nil }
[ "func", "(", "c", "*", "NodeCommand", ")", "ListActive", "(", "client", "auth", ".", "ClientI", ")", "error", "{", "nodes", ",", "err", ":=", "client", ".", "GetNodes", "(", "c", ".", "namespace", ",", "services", ".", "SkipValidation", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "coll", ":=", "&", "serverCollection", "{", "servers", ":", "nodes", "}", "\n", "coll", ".", "writeText", "(", "os", ".", "Stdout", ")", "\n", "return", "nil", "\n", "}" ]
// ListActive retreives the list of nodes who recently sent heartbeats to // to a cluster and prints it to stdout
[ "ListActive", "retreives", "the", "list", "of", "nodes", "who", "recently", "sent", "heartbeats", "to", "to", "a", "cluster", "and", "prints", "it", "to", "stdout" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/node_command.go#L170-L178
train
gravitational/teleport
lib/client/hotp_mock.go
GetTokenFromHOTPMockFile
func GetTokenFromHOTPMockFile(path string) (token string, e error) { otp, err := LoadHOTPMockFromFile(path) if err != nil { return "", trace.Wrap(err) } token = otp.OTP() err = otp.SaveToFile(path) if err != nil { return "", trace.Wrap(err) } return token, nil }
go
func GetTokenFromHOTPMockFile(path string) (token string, e error) { otp, err := LoadHOTPMockFromFile(path) if err != nil { return "", trace.Wrap(err) } token = otp.OTP() err = otp.SaveToFile(path) if err != nil { return "", trace.Wrap(err) } return token, nil }
[ "func", "GetTokenFromHOTPMockFile", "(", "path", "string", ")", "(", "token", "string", ",", "e", "error", ")", "{", "otp", ",", "err", ":=", "LoadHOTPMockFromFile", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "token", "=", "otp", ".", "OTP", "(", ")", "\n", "err", "=", "otp", ".", "SaveToFile", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "token", ",", "nil", "\n", "}" ]
// GetTokenFromHOTPMockFile opens HOTPMock from file, gets token value, // increases hotp and saves it to the file. Returns hotp token value.
[ "GetTokenFromHOTPMockFile", "opens", "HOTPMock", "from", "file", "gets", "token", "value", "increases", "hotp", "and", "saves", "it", "to", "the", "file", ".", "Returns", "hotp", "token", "value", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/hotp_mock.go#L73-L87
train
gravitational/teleport
lib/utils/proxy/noproxy.go
useProxy
func useProxy(addr string) bool { if len(addr) == 0 { return true } var noProxy string for _, env := range []string{teleport.NoProxy, strings.ToLower(teleport.NoProxy)} { noProxy = os.Getenv(env) if noProxy != "" { break } } if noProxy == "" { return true } if noProxy == "*" { return false } addr = strings.ToLower(strings.TrimSpace(addr)) if hasPort(addr) { addr = addr[:strings.LastIndex(addr, ":")] } for _, p := range strings.Split(noProxy, ",") { p = strings.ToLower(strings.TrimSpace(p)) if len(p) == 0 { continue } if hasPort(p) { p = p[:strings.LastIndex(p, ":")] } if addr == p { return false } if len(p) == 0 { // There is no host part, likely the entry is malformed; ignore. continue } if p[0] == '.' && (strings.HasSuffix(addr, p) || addr == p[1:]) { // no_proxy ".foo.com" matches "bar.foo.com" or "foo.com" return false } if p[0] != '.' && strings.HasSuffix(addr, p) && addr[len(addr)-len(p)-1] == '.' { // no_proxy "foo.com" matches "bar.foo.com" return false } } return true }
go
func useProxy(addr string) bool { if len(addr) == 0 { return true } var noProxy string for _, env := range []string{teleport.NoProxy, strings.ToLower(teleport.NoProxy)} { noProxy = os.Getenv(env) if noProxy != "" { break } } if noProxy == "" { return true } if noProxy == "*" { return false } addr = strings.ToLower(strings.TrimSpace(addr)) if hasPort(addr) { addr = addr[:strings.LastIndex(addr, ":")] } for _, p := range strings.Split(noProxy, ",") { p = strings.ToLower(strings.TrimSpace(p)) if len(p) == 0 { continue } if hasPort(p) { p = p[:strings.LastIndex(p, ":")] } if addr == p { return false } if len(p) == 0 { // There is no host part, likely the entry is malformed; ignore. continue } if p[0] == '.' && (strings.HasSuffix(addr, p) || addr == p[1:]) { // no_proxy ".foo.com" matches "bar.foo.com" or "foo.com" return false } if p[0] != '.' && strings.HasSuffix(addr, p) && addr[len(addr)-len(p)-1] == '.' { // no_proxy "foo.com" matches "bar.foo.com" return false } } return true }
[ "func", "useProxy", "(", "addr", "string", ")", "bool", "{", "if", "len", "(", "addr", ")", "==", "0", "{", "return", "true", "\n", "}", "\n", "var", "noProxy", "string", "\n", "for", "_", ",", "env", ":=", "range", "[", "]", "string", "{", "teleport", ".", "NoProxy", ",", "strings", ".", "ToLower", "(", "teleport", ".", "NoProxy", ")", "}", "{", "noProxy", "=", "os", ".", "Getenv", "(", "env", ")", "\n", "if", "noProxy", "!=", "\"\"", "{", "break", "\n", "}", "\n", "}", "\n", "if", "noProxy", "==", "\"\"", "{", "return", "true", "\n", "}", "\n", "if", "noProxy", "==", "\"*\"", "{", "return", "false", "\n", "}", "\n", "addr", "=", "strings", ".", "ToLower", "(", "strings", ".", "TrimSpace", "(", "addr", ")", ")", "\n", "if", "hasPort", "(", "addr", ")", "{", "addr", "=", "addr", "[", ":", "strings", ".", "LastIndex", "(", "addr", ",", "\":\"", ")", "]", "\n", "}", "\n", "for", "_", ",", "p", ":=", "range", "strings", ".", "Split", "(", "noProxy", ",", "\",\"", ")", "{", "p", "=", "strings", ".", "ToLower", "(", "strings", ".", "TrimSpace", "(", "p", ")", ")", "\n", "if", "len", "(", "p", ")", "==", "0", "{", "continue", "\n", "}", "\n", "if", "hasPort", "(", "p", ")", "{", "p", "=", "p", "[", ":", "strings", ".", "LastIndex", "(", "p", ",", "\":\"", ")", "]", "\n", "}", "\n", "if", "addr", "==", "p", "{", "return", "false", "\n", "}", "\n", "if", "len", "(", "p", ")", "==", "0", "{", "continue", "\n", "}", "\n", "if", "p", "[", "0", "]", "==", "'.'", "&&", "(", "strings", ".", "HasSuffix", "(", "addr", ",", "p", ")", "||", "addr", "==", "p", "[", "1", ":", "]", ")", "{", "return", "false", "\n", "}", "\n", "if", "p", "[", "0", "]", "!=", "'.'", "&&", "strings", ".", "HasSuffix", "(", "addr", ",", "p", ")", "&&", "addr", "[", "len", "(", "addr", ")", "-", "len", "(", "p", ")", "-", "1", "]", "==", "'.'", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// useProxy reports whether requests to addr should use a proxy, // according to the NO_PROXY or no_proxy environment variable. // addr is always a canonicalAddr with a host and port.
[ "useProxy", "reports", "whether", "requests", "to", "addr", "should", "use", "a", "proxy", "according", "to", "the", "NO_PROXY", "or", "no_proxy", "environment", "variable", ".", "addr", "is", "always", "a", "canonicalAddr", "with", "a", "host", "and", "port", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/proxy/noproxy.go#L22-L70
train
gravitational/teleport
lib/utils/agentconn/agent_windows.go
Dial
func Dial(socket string) (net.Conn, error) { conn, err := winio.DialPipe(defaults.WindowsOpenSSHNamedPipe, nil) if err != nil { return nil, trace.Wrap(err) } return conn, nil }
go
func Dial(socket string) (net.Conn, error) { conn, err := winio.DialPipe(defaults.WindowsOpenSSHNamedPipe, nil) if err != nil { return nil, trace.Wrap(err) } return conn, nil }
[ "func", "Dial", "(", "socket", "string", ")", "(", "net", ".", "Conn", ",", "error", ")", "{", "conn", ",", "err", ":=", "winio", ".", "DialPipe", "(", "defaults", ".", "WindowsOpenSSHNamedPipe", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "conn", ",", "nil", "\n", "}" ]
// Dial creates net.Conn to a SSH agent listening on a Windows named pipe. // This is behind a build flag because winio.DialPipe is only available on // Windows.
[ "Dial", "creates", "net", ".", "Conn", "to", "a", "SSH", "agent", "listening", "on", "a", "Windows", "named", "pipe", ".", "This", "is", "behind", "a", "build", "flag", "because", "winio", ".", "DialPipe", "is", "only", "available", "on", "Windows", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/agentconn/agent_windows.go#L34-L41
train
gravitational/teleport
lib/auth/grpclog.go
Infoln
func (g *GLogger) Infoln(args ...interface{}) { // GRPC is very verbose, so this is intentionally // pushes info level statements as Teleport's debug level ones g.Entry.Debug(fmt.Sprintln(args...)) }
go
func (g *GLogger) Infoln(args ...interface{}) { // GRPC is very verbose, so this is intentionally // pushes info level statements as Teleport's debug level ones g.Entry.Debug(fmt.Sprintln(args...)) }
[ "func", "(", "g", "*", "GLogger", ")", "Infoln", "(", "args", "...", "interface", "{", "}", ")", "{", "g", ".", "Entry", ".", "Debug", "(", "fmt", ".", "Sprintln", "(", "args", "...", ")", ")", "\n", "}" ]
// Infoln logs to INFO log. Arguments are handled in the manner of fmt.Println.
[ "Infoln", "logs", "to", "INFO", "log", ".", "Arguments", "are", "handled", "in", "the", "manner", "of", "fmt", ".", "Println", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/grpclog.go#L54-L58
train
gravitational/teleport
lib/auth/grpclog.go
Infof
func (g *GLogger) Infof(format string, args ...interface{}) { // GRPC is very verbose, so this is intentionally // pushes info level statements as Teleport's debug level ones g.Entry.Debugf(format, args...) }
go
func (g *GLogger) Infof(format string, args ...interface{}) { // GRPC is very verbose, so this is intentionally // pushes info level statements as Teleport's debug level ones g.Entry.Debugf(format, args...) }
[ "func", "(", "g", "*", "GLogger", ")", "Infof", "(", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "g", ".", "Entry", ".", "Debugf", "(", "format", ",", "args", "...", ")", "\n", "}" ]
// Infof logs to INFO log. Arguments are handled in the manner of fmt.Printf.
[ "Infof", "logs", "to", "INFO", "log", ".", "Arguments", "are", "handled", "in", "the", "manner", "of", "fmt", ".", "Printf", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/grpclog.go#L61-L65
train
gravitational/teleport
lib/auth/grpclog.go
Warningln
func (g *GLogger) Warningln(args ...interface{}) { g.Entry.Warning(fmt.Sprintln(args...)) }
go
func (g *GLogger) Warningln(args ...interface{}) { g.Entry.Warning(fmt.Sprintln(args...)) }
[ "func", "(", "g", "*", "GLogger", ")", "Warningln", "(", "args", "...", "interface", "{", "}", ")", "{", "g", ".", "Entry", ".", "Warning", "(", "fmt", ".", "Sprintln", "(", "args", "...", ")", ")", "\n", "}" ]
// Warningln logs to WARNING log. Arguments are handled in the manner of fmt.Println.
[ "Warningln", "logs", "to", "WARNING", "log", ".", "Arguments", "are", "handled", "in", "the", "manner", "of", "fmt", ".", "Println", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/grpclog.go#L73-L75
train
gravitational/teleport
lib/auth/grpclog.go
Warningf
func (g *GLogger) Warningf(format string, args ...interface{}) { g.Entry.Warningf(format, args...) }
go
func (g *GLogger) Warningf(format string, args ...interface{}) { g.Entry.Warningf(format, args...) }
[ "func", "(", "g", "*", "GLogger", ")", "Warningf", "(", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "g", ".", "Entry", ".", "Warningf", "(", "format", ",", "args", "...", ")", "\n", "}" ]
// Warningf logs to WARNING log. Arguments are handled in the manner of fmt.Printf.
[ "Warningf", "logs", "to", "WARNING", "log", ".", "Arguments", "are", "handled", "in", "the", "manner", "of", "fmt", ".", "Printf", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/grpclog.go#L78-L80
train
gravitational/teleport
lib/auth/grpclog.go
Errorln
func (g *GLogger) Errorln(args ...interface{}) { g.Entry.Error(fmt.Sprintln(args...)) }
go
func (g *GLogger) Errorln(args ...interface{}) { g.Entry.Error(fmt.Sprintln(args...)) }
[ "func", "(", "g", "*", "GLogger", ")", "Errorln", "(", "args", "...", "interface", "{", "}", ")", "{", "g", ".", "Entry", ".", "Error", "(", "fmt", ".", "Sprintln", "(", "args", "...", ")", ")", "\n", "}" ]
// Errorln logs to ERROR log. Arguments are handled in the manner of fmt.Println.
[ "Errorln", "logs", "to", "ERROR", "log", ".", "Arguments", "are", "handled", "in", "the", "manner", "of", "fmt", ".", "Println", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/grpclog.go#L88-L90
train
gravitational/teleport
lib/utils/socks/socks.go
Handshake
func Handshake(conn net.Conn) (string, error) { // Read in the version and reject anything other than SOCKS5. version, err := readByte(conn) if err != nil { return "", trace.Wrap(err) } if version != socks5Version { return "", trace.BadParameter("only SOCKS5 is supported") } // Read in the authentication method requested by the client and write back // the method that was selected. At the moment only "no authentication // required" is supported. authMethods, err := readAuthenticationMethod(conn) if err != nil { return "", trace.Wrap(err) } if !byteSliceContains(authMethods, socks5AuthNotRequired) { return "", trace.BadParameter("only 'no authentication required' is supported") } err = writeMethodSelection(conn) if err != nil { return "", trace.Wrap(err) } // Read in the request from the client and make sure the requested command // is supported and extract the remote address. If everything is good, write // out a success response. remoteAddr, err := readRequest(conn) if err != nil { return "", trace.Wrap(err) } err = writeReply(conn) if err != nil { return "", trace.Wrap(err) } return remoteAddr, nil }
go
func Handshake(conn net.Conn) (string, error) { // Read in the version and reject anything other than SOCKS5. version, err := readByte(conn) if err != nil { return "", trace.Wrap(err) } if version != socks5Version { return "", trace.BadParameter("only SOCKS5 is supported") } // Read in the authentication method requested by the client and write back // the method that was selected. At the moment only "no authentication // required" is supported. authMethods, err := readAuthenticationMethod(conn) if err != nil { return "", trace.Wrap(err) } if !byteSliceContains(authMethods, socks5AuthNotRequired) { return "", trace.BadParameter("only 'no authentication required' is supported") } err = writeMethodSelection(conn) if err != nil { return "", trace.Wrap(err) } // Read in the request from the client and make sure the requested command // is supported and extract the remote address. If everything is good, write // out a success response. remoteAddr, err := readRequest(conn) if err != nil { return "", trace.Wrap(err) } err = writeReply(conn) if err != nil { return "", trace.Wrap(err) } return remoteAddr, nil }
[ "func", "Handshake", "(", "conn", "net", ".", "Conn", ")", "(", "string", ",", "error", ")", "{", "version", ",", "err", ":=", "readByte", "(", "conn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "version", "!=", "socks5Version", "{", "return", "\"\"", ",", "trace", ".", "BadParameter", "(", "\"only SOCKS5 is supported\"", ")", "\n", "}", "\n", "authMethods", ",", "err", ":=", "readAuthenticationMethod", "(", "conn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "!", "byteSliceContains", "(", "authMethods", ",", "socks5AuthNotRequired", ")", "{", "return", "\"\"", ",", "trace", ".", "BadParameter", "(", "\"only 'no authentication required' is supported\"", ")", "\n", "}", "\n", "err", "=", "writeMethodSelection", "(", "conn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "remoteAddr", ",", "err", ":=", "readRequest", "(", "conn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "err", "=", "writeReply", "(", "conn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "remoteAddr", ",", "nil", "\n", "}" ]
// Handshake performs a SOCKS5 handshake with the client and returns // the remote address to proxy the connection to.
[ "Handshake", "performs", "a", "SOCKS5", "handshake", "with", "the", "client", "and", "returns", "the", "remote", "address", "to", "proxy", "the", "connection", "to", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/socks/socks.go#L49-L87
train
gravitational/teleport
lib/utils/socks/socks.go
readAuthenticationMethod
func readAuthenticationMethod(conn net.Conn) ([]byte, error) { // Read in the number of authentication methods supported. nmethods, err := readByte(conn) if err != nil { return nil, trace.Wrap(err) } // Read nmethods number of bytes from the connection return the list of // supported authentication methods to the caller. authMethods := make([]byte, nmethods) for i := byte(0); i < nmethods; i++ { method, err := readByte(conn) if err != nil { return nil, trace.Wrap(err) } authMethods = append(authMethods, method) } return authMethods, nil }
go
func readAuthenticationMethod(conn net.Conn) ([]byte, error) { // Read in the number of authentication methods supported. nmethods, err := readByte(conn) if err != nil { return nil, trace.Wrap(err) } // Read nmethods number of bytes from the connection return the list of // supported authentication methods to the caller. authMethods := make([]byte, nmethods) for i := byte(0); i < nmethods; i++ { method, err := readByte(conn) if err != nil { return nil, trace.Wrap(err) } authMethods = append(authMethods, method) } return authMethods, nil }
[ "func", "readAuthenticationMethod", "(", "conn", "net", ".", "Conn", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "nmethods", ",", "err", ":=", "readByte", "(", "conn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "authMethods", ":=", "make", "(", "[", "]", "byte", ",", "nmethods", ")", "\n", "for", "i", ":=", "byte", "(", "0", ")", ";", "i", "<", "nmethods", ";", "i", "++", "{", "method", ",", "err", ":=", "readByte", "(", "conn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "authMethods", "=", "append", "(", "authMethods", ",", "method", ")", "\n", "}", "\n", "return", "authMethods", ",", "nil", "\n", "}" ]
// readAuthenticationMethod reads in the authentication methods the client // supports.
[ "readAuthenticationMethod", "reads", "in", "the", "authentication", "methods", "the", "client", "supports", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/socks/socks.go#L91-L111
train
gravitational/teleport
lib/utils/socks/socks.go
writeMethodSelection
func writeMethodSelection(conn net.Conn) error { message := []byte{socks5Version, socks5AuthNotRequired} n, err := conn.Write(message) if err != nil { return trace.Wrap(err) } if n != len(message) { return trace.BadParameter("wrote: %v wanted to write: %v", n, len(message)) } return nil }
go
func writeMethodSelection(conn net.Conn) error { message := []byte{socks5Version, socks5AuthNotRequired} n, err := conn.Write(message) if err != nil { return trace.Wrap(err) } if n != len(message) { return trace.BadParameter("wrote: %v wanted to write: %v", n, len(message)) } return nil }
[ "func", "writeMethodSelection", "(", "conn", "net", ".", "Conn", ")", "error", "{", "message", ":=", "[", "]", "byte", "{", "socks5Version", ",", "socks5AuthNotRequired", "}", "\n", "n", ",", "err", ":=", "conn", ".", "Write", "(", "message", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "n", "!=", "len", "(", "message", ")", "{", "return", "trace", ".", "BadParameter", "(", "\"wrote: %v wanted to write: %v\"", ",", "n", ",", "len", "(", "message", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// writeMethodSelection writes out the response to the authentication methods. // Right now, only SOCKS5 and "no authentication methods" is supported.
[ "writeMethodSelection", "writes", "out", "the", "response", "to", "the", "authentication", "methods", ".", "Right", "now", "only", "SOCKS5", "and", "no", "authentication", "methods", "is", "supported", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/socks/socks.go#L115-L127
train
gravitational/teleport
lib/utils/socks/socks.go
readAddrType
func readAddrType(conn net.Conn) (int, error) { // Read in the type of the remote host. addrType, err := readByte(conn) if err != nil { return 0, trace.Wrap(err) } // Based off the type, determine how many more bytes to read in for the // remote address. For IPv4 it's 4 bytes, for IPv6 it's 16, and for domain // names read in another byte to determine the length of the field. switch addrType { case socks5AddressTypeIPv4: return net.IPv4len, nil case socks5AddressTypeIPv6: return net.IPv6len, nil case socks5AddressTypeDomainName: len, err := readByte(conn) if err != nil { return 0, trace.Wrap(err) } return int(len), nil default: return 0, trace.BadParameter("unsupported address type: %v", addrType) } }
go
func readAddrType(conn net.Conn) (int, error) { // Read in the type of the remote host. addrType, err := readByte(conn) if err != nil { return 0, trace.Wrap(err) } // Based off the type, determine how many more bytes to read in for the // remote address. For IPv4 it's 4 bytes, for IPv6 it's 16, and for domain // names read in another byte to determine the length of the field. switch addrType { case socks5AddressTypeIPv4: return net.IPv4len, nil case socks5AddressTypeIPv6: return net.IPv6len, nil case socks5AddressTypeDomainName: len, err := readByte(conn) if err != nil { return 0, trace.Wrap(err) } return int(len), nil default: return 0, trace.BadParameter("unsupported address type: %v", addrType) } }
[ "func", "readAddrType", "(", "conn", "net", ".", "Conn", ")", "(", "int", ",", "error", ")", "{", "addrType", ",", "err", ":=", "readByte", "(", "conn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "switch", "addrType", "{", "case", "socks5AddressTypeIPv4", ":", "return", "net", ".", "IPv4len", ",", "nil", "\n", "case", "socks5AddressTypeIPv6", ":", "return", "net", ".", "IPv6len", ",", "nil", "\n", "case", "socks5AddressTypeDomainName", ":", "len", ",", "err", ":=", "readByte", "(", "conn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "int", "(", "len", ")", ",", "nil", "\n", "default", ":", "return", "0", ",", "trace", ".", "BadParameter", "(", "\"unsupported address type: %v\"", ",", "addrType", ")", "\n", "}", "\n", "}" ]
// readAddrType reads in the address type and returns the length of the dest // addr field.
[ "readAddrType", "reads", "in", "the", "address", "type", "and", "returns", "the", "length", "of", "the", "dest", "addr", "field", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/socks/socks.go#L182-L206
train
gravitational/teleport
lib/utils/socks/socks.go
writeReply
func writeReply(conn net.Conn) error { // Write success reply, similar to OpenSSH only success is written. // https://github.com/openssh/openssh-portable/blob/5d14019/channels.c#L1442-L1452 message := []byte{ socks5Version, socks5Succeeded, socks5Reserved, socks5AddressTypeIPv4, } n, err := conn.Write(message) if err != nil { return trace.Wrap(err) } if n != len(message) { return trace.BadParameter("wrote: %v wanted to write: %v", n, len(message)) } // Reply also requires BND.ADDR and BDN.PORT even though they are ignored // because Teleport only supports CONNECT. message = []byte{0, 0, 0, 0, 0, 0} n, err = conn.Write(message) if err != nil { return trace.Wrap(err) } if n != len(message) { return trace.BadParameter("wrote: %v wanted to write: %v", n, len(message)) } return nil }
go
func writeReply(conn net.Conn) error { // Write success reply, similar to OpenSSH only success is written. // https://github.com/openssh/openssh-portable/blob/5d14019/channels.c#L1442-L1452 message := []byte{ socks5Version, socks5Succeeded, socks5Reserved, socks5AddressTypeIPv4, } n, err := conn.Write(message) if err != nil { return trace.Wrap(err) } if n != len(message) { return trace.BadParameter("wrote: %v wanted to write: %v", n, len(message)) } // Reply also requires BND.ADDR and BDN.PORT even though they are ignored // because Teleport only supports CONNECT. message = []byte{0, 0, 0, 0, 0, 0} n, err = conn.Write(message) if err != nil { return trace.Wrap(err) } if n != len(message) { return trace.BadParameter("wrote: %v wanted to write: %v", n, len(message)) } return nil }
[ "func", "writeReply", "(", "conn", "net", ".", "Conn", ")", "error", "{", "message", ":=", "[", "]", "byte", "{", "socks5Version", ",", "socks5Succeeded", ",", "socks5Reserved", ",", "socks5AddressTypeIPv4", ",", "}", "\n", "n", ",", "err", ":=", "conn", ".", "Write", "(", "message", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "n", "!=", "len", "(", "message", ")", "{", "return", "trace", ".", "BadParameter", "(", "\"wrote: %v wanted to write: %v\"", ",", "n", ",", "len", "(", "message", ")", ")", "\n", "}", "\n", "message", "=", "[", "]", "byte", "{", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", "}", "\n", "n", ",", "err", "=", "conn", ".", "Write", "(", "message", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "n", "!=", "len", "(", "message", ")", "{", "return", "trace", ".", "BadParameter", "(", "\"wrote: %v wanted to write: %v\"", ",", "n", ",", "len", "(", "message", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Write the response to the client.
[ "Write", "the", "response", "to", "the", "client", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/socks/socks.go#L209-L238
train
gravitational/teleport
lib/utils/socks/socks.go
readByte
func readByte(conn net.Conn) (byte, error) { b := make([]byte, 1) _, err := io.ReadFull(conn, b) if err != nil { return 0, trace.Wrap(err) } return b[0], nil }
go
func readByte(conn net.Conn) (byte, error) { b := make([]byte, 1) _, err := io.ReadFull(conn, b) if err != nil { return 0, trace.Wrap(err) } return b[0], nil }
[ "func", "readByte", "(", "conn", "net", ".", "Conn", ")", "(", "byte", ",", "error", ")", "{", "b", ":=", "make", "(", "[", "]", "byte", ",", "1", ")", "\n", "_", ",", "err", ":=", "io", ".", "ReadFull", "(", "conn", ",", "b", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "b", "[", "0", "]", ",", "nil", "\n", "}" ]
// readByte a single byte from the passed in net.Conn.
[ "readByte", "a", "single", "byte", "from", "the", "passed", "in", "net", ".", "Conn", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/socks/socks.go#L241-L249
train
gravitational/teleport
lib/utils/socks/socks.go
byteSliceContains
func byteSliceContains(a []byte, b byte) bool { for _, v := range a { if v == b { return true } } return false }
go
func byteSliceContains(a []byte, b byte) bool { for _, v := range a { if v == b { return true } } return false }
[ "func", "byteSliceContains", "(", "a", "[", "]", "byte", ",", "b", "byte", ")", "bool", "{", "for", "_", ",", "v", ":=", "range", "a", "{", "if", "v", "==", "b", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// byteSliceContains checks if the slice a contains the byte b.
[ "byteSliceContains", "checks", "if", "the", "slice", "a", "contains", "the", "byte", "b", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/socks/socks.go#L252-L260
train
gravitational/teleport
lib/shell/shell.go
GetLoginShell
func GetLoginShell(username string) (string, error) { var err error var shellcmd string shellcmd, err = getLoginShell(username) if err != nil { if !trace.IsNotFound(err) { logrus.Warnf("No shell specified for %v, using default %v.", username, DefaultShell) return DefaultShell, nil } return "", trace.Wrap(err) } return shellcmd, nil }
go
func GetLoginShell(username string) (string, error) { var err error var shellcmd string shellcmd, err = getLoginShell(username) if err != nil { if !trace.IsNotFound(err) { logrus.Warnf("No shell specified for %v, using default %v.", username, DefaultShell) return DefaultShell, nil } return "", trace.Wrap(err) } return shellcmd, nil }
[ "func", "GetLoginShell", "(", "username", "string", ")", "(", "string", ",", "error", ")", "{", "var", "err", "error", "\n", "var", "shellcmd", "string", "\n", "shellcmd", ",", "err", "=", "getLoginShell", "(", "username", ")", "\n", "if", "err", "!=", "nil", "{", "if", "!", "trace", ".", "IsNotFound", "(", "err", ")", "{", "logrus", ".", "Warnf", "(", "\"No shell specified for %v, using default %v.\"", ",", "username", ",", "DefaultShell", ")", "\n", "return", "DefaultShell", ",", "nil", "\n", "}", "\n", "return", "\"\"", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "shellcmd", ",", "nil", "\n", "}" ]
// GetLoginShell determines the login shell for a given username.
[ "GetLoginShell", "determines", "the", "login", "shell", "for", "a", "given", "username", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/shell/shell.go#L30-L44
train
gravitational/teleport
integration/helpers.go
GetRoles
func (s *InstanceSecrets) GetRoles() []services.Role { var roles []services.Role for _, ca := range s.GetCAs() { if ca.GetType() != services.UserCA { continue } role := services.RoleForCertAuthority(ca) role.SetLogins(services.Allow, s.AllowedLogins()) roles = append(roles, role) } return roles }
go
func (s *InstanceSecrets) GetRoles() []services.Role { var roles []services.Role for _, ca := range s.GetCAs() { if ca.GetType() != services.UserCA { continue } role := services.RoleForCertAuthority(ca) role.SetLogins(services.Allow, s.AllowedLogins()) roles = append(roles, role) } return roles }
[ "func", "(", "s", "*", "InstanceSecrets", ")", "GetRoles", "(", ")", "[", "]", "services", ".", "Role", "{", "var", "roles", "[", "]", "services", ".", "Role", "\n", "for", "_", ",", "ca", ":=", "range", "s", ".", "GetCAs", "(", ")", "{", "if", "ca", ".", "GetType", "(", ")", "!=", "services", ".", "UserCA", "{", "continue", "\n", "}", "\n", "role", ":=", "services", ".", "RoleForCertAuthority", "(", "ca", ")", "\n", "role", ".", "SetLogins", "(", "services", ".", "Allow", ",", "s", ".", "AllowedLogins", "(", ")", ")", "\n", "roles", "=", "append", "(", "roles", ",", "role", ")", "\n", "}", "\n", "return", "roles", "\n", "}" ]
// GetRoles returns a list of roles to initiate for this secret
[ "GetRoles", "returns", "a", "list", "of", "roles", "to", "initiate", "for", "this", "secret" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L231-L242
train
gravitational/teleport
integration/helpers.go
SetupUserCreds
func SetupUserCreds(tc *client.TeleportClient, proxyHost string, creds UserCreds) error { _, err := tc.AddKey(proxyHost, &creds.Key) if err != nil { return trace.Wrap(err) } err = tc.AddTrustedCA(creds.HostCA) if err != nil { return trace.Wrap(err) } return nil }
go
func SetupUserCreds(tc *client.TeleportClient, proxyHost string, creds UserCreds) error { _, err := tc.AddKey(proxyHost, &creds.Key) if err != nil { return trace.Wrap(err) } err = tc.AddTrustedCA(creds.HostCA) if err != nil { return trace.Wrap(err) } return nil }
[ "func", "SetupUserCreds", "(", "tc", "*", "client", ".", "TeleportClient", ",", "proxyHost", "string", ",", "creds", "UserCreds", ")", "error", "{", "_", ",", "err", ":=", "tc", ".", "AddKey", "(", "proxyHost", ",", "&", "creds", ".", "Key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "err", "=", "tc", ".", "AddTrustedCA", "(", "creds", ".", "HostCA", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SetupUserCreds sets up user credentials for client
[ "SetupUserCreds", "sets", "up", "user", "credentials", "for", "client" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L357-L367
train
gravitational/teleport
integration/helpers.go
SetupUser
func SetupUser(process *service.TeleportProcess, username string, roles []services.Role) error { auth := process.GetAuthServer() teleUser, err := services.NewUser(username) if err != nil { return trace.Wrap(err) } if len(roles) == 0 { role := services.RoleForUser(teleUser) role.SetLogins(services.Allow, []string{username}) // allow tests to forward agent, still needs to be passed in client roleOptions := role.GetOptions() roleOptions.ForwardAgent = services.NewBool(true) role.SetOptions(roleOptions) err = auth.UpsertRole(role) if err != nil { return trace.Wrap(err) } teleUser.AddRole(role.GetMetadata().Name) roles = append(roles, role) } else { for _, role := range roles { err := auth.UpsertRole(role) if err != nil { return trace.Wrap(err) } teleUser.AddRole(role.GetName()) } } err = auth.UpsertUser(teleUser) if err != nil { return trace.Wrap(err) } return nil }
go
func SetupUser(process *service.TeleportProcess, username string, roles []services.Role) error { auth := process.GetAuthServer() teleUser, err := services.NewUser(username) if err != nil { return trace.Wrap(err) } if len(roles) == 0 { role := services.RoleForUser(teleUser) role.SetLogins(services.Allow, []string{username}) // allow tests to forward agent, still needs to be passed in client roleOptions := role.GetOptions() roleOptions.ForwardAgent = services.NewBool(true) role.SetOptions(roleOptions) err = auth.UpsertRole(role) if err != nil { return trace.Wrap(err) } teleUser.AddRole(role.GetMetadata().Name) roles = append(roles, role) } else { for _, role := range roles { err := auth.UpsertRole(role) if err != nil { return trace.Wrap(err) } teleUser.AddRole(role.GetName()) } } err = auth.UpsertUser(teleUser) if err != nil { return trace.Wrap(err) } return nil }
[ "func", "SetupUser", "(", "process", "*", "service", ".", "TeleportProcess", ",", "username", "string", ",", "roles", "[", "]", "services", ".", "Role", ")", "error", "{", "auth", ":=", "process", ".", "GetAuthServer", "(", ")", "\n", "teleUser", ",", "err", ":=", "services", ".", "NewUser", "(", "username", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "len", "(", "roles", ")", "==", "0", "{", "role", ":=", "services", ".", "RoleForUser", "(", "teleUser", ")", "\n", "role", ".", "SetLogins", "(", "services", ".", "Allow", ",", "[", "]", "string", "{", "username", "}", ")", "\n", "roleOptions", ":=", "role", ".", "GetOptions", "(", ")", "\n", "roleOptions", ".", "ForwardAgent", "=", "services", ".", "NewBool", "(", "true", ")", "\n", "role", ".", "SetOptions", "(", "roleOptions", ")", "\n", "err", "=", "auth", ".", "UpsertRole", "(", "role", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "teleUser", ".", "AddRole", "(", "role", ".", "GetMetadata", "(", ")", ".", "Name", ")", "\n", "roles", "=", "append", "(", "roles", ",", "role", ")", "\n", "}", "else", "{", "for", "_", ",", "role", ":=", "range", "roles", "{", "err", ":=", "auth", ".", "UpsertRole", "(", "role", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "teleUser", ".", "AddRole", "(", "role", ".", "GetName", "(", ")", ")", "\n", "}", "\n", "}", "\n", "err", "=", "auth", ".", "UpsertUser", "(", "teleUser", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SetupUser sets up user in the cluster
[ "SetupUser", "sets", "up", "user", "in", "the", "cluster" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L370-L405
train
gravitational/teleport
integration/helpers.go
GenerateUserCreds
func GenerateUserCreds(process *service.TeleportProcess, username string) (*UserCreds, error) { priv, pub, err := testauthority.New().GenerateKeyPair("") if err != nil { return nil, trace.Wrap(err) } a := process.GetAuthServer() sshCert, x509Cert, err := a.GenerateUserCerts(pub, username, time.Hour, teleport.CertificateFormatStandard) if err != nil { return nil, trace.Wrap(err) } clusterName, err := a.GetClusterName() if err != nil { return nil, trace.Wrap(err) } ca, err := a.GetCertAuthority(services.CertAuthID{ Type: services.HostCA, DomainName: clusterName.GetClusterName(), }, false) if err != nil { return nil, trace.Wrap(err) } return &UserCreds{ HostCA: ca, Key: client.Key{ Priv: priv, Pub: pub, Cert: sshCert, TLSCert: x509Cert, }, }, nil }
go
func GenerateUserCreds(process *service.TeleportProcess, username string) (*UserCreds, error) { priv, pub, err := testauthority.New().GenerateKeyPair("") if err != nil { return nil, trace.Wrap(err) } a := process.GetAuthServer() sshCert, x509Cert, err := a.GenerateUserCerts(pub, username, time.Hour, teleport.CertificateFormatStandard) if err != nil { return nil, trace.Wrap(err) } clusterName, err := a.GetClusterName() if err != nil { return nil, trace.Wrap(err) } ca, err := a.GetCertAuthority(services.CertAuthID{ Type: services.HostCA, DomainName: clusterName.GetClusterName(), }, false) if err != nil { return nil, trace.Wrap(err) } return &UserCreds{ HostCA: ca, Key: client.Key{ Priv: priv, Pub: pub, Cert: sshCert, TLSCert: x509Cert, }, }, nil }
[ "func", "GenerateUserCreds", "(", "process", "*", "service", ".", "TeleportProcess", ",", "username", "string", ")", "(", "*", "UserCreds", ",", "error", ")", "{", "priv", ",", "pub", ",", "err", ":=", "testauthority", ".", "New", "(", ")", ".", "GenerateKeyPair", "(", "\"\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "a", ":=", "process", ".", "GetAuthServer", "(", ")", "\n", "sshCert", ",", "x509Cert", ",", "err", ":=", "a", ".", "GenerateUserCerts", "(", "pub", ",", "username", ",", "time", ".", "Hour", ",", "teleport", ".", "CertificateFormatStandard", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "clusterName", ",", "err", ":=", "a", ".", "GetClusterName", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "ca", ",", "err", ":=", "a", ".", "GetCertAuthority", "(", "services", ".", "CertAuthID", "{", "Type", ":", "services", ".", "HostCA", ",", "DomainName", ":", "clusterName", ".", "GetClusterName", "(", ")", ",", "}", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "&", "UserCreds", "{", "HostCA", ":", "ca", ",", "Key", ":", "client", ".", "Key", "{", "Priv", ":", "priv", ",", "Pub", ":", "pub", ",", "Cert", ":", "sshCert", ",", "TLSCert", ":", "x509Cert", ",", "}", ",", "}", ",", "nil", "\n", "}" ]
// GenerateUserCreds generates key to be used by client
[ "GenerateUserCreds", "generates", "key", "to", "be", "used", "by", "client" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L408-L438
train
gravitational/teleport
integration/helpers.go
StartNode
func (i *TeleInstance) StartNode(tconf *service.Config) (*service.TeleportProcess, error) { dataDir, err := ioutil.TempDir("", "cluster-"+i.Secrets.SiteName) if err != nil { return nil, trace.Wrap(err) } tconf.DataDir = dataDir authServer := utils.MustParseAddr(net.JoinHostPort(i.Hostname, i.GetPortAuth())) tconf.AuthServers = append(tconf.AuthServers, *authServer) tconf.Token = "token" tconf.UploadEventsC = i.UploadEventsC var ttl time.Duration tconf.CachePolicy = service.CachePolicy{ Enabled: true, RecentTTL: &ttl, } tconf.SSH.PublicAddrs = []utils.NetAddr{ utils.NetAddr{ AddrNetwork: "tcp", Addr: Loopback, }, utils.NetAddr{ AddrNetwork: "tcp", Addr: Host, }, } tconf.Auth.Enabled = false tconf.Proxy.Enabled = false // Create a new Teleport process and add it to the list of nodes that // compose this "cluster". process, err := service.NewTeleport(tconf) if err != nil { return nil, trace.Wrap(err) } i.Nodes = append(i.Nodes, process) // Build a list of expected events to wait for before unblocking based off // the configuration passed in. expectedEvents := []string{ service.NodeSSHReady, } // Start the process and block until the expected events have arrived. receivedEvents, err := startAndWait(process, expectedEvents) if err != nil { return nil, trace.Wrap(err) } log.Debugf("Teleport node (in instance %v) started: %v/%v events received.", i.Secrets.SiteName, len(expectedEvents), len(receivedEvents)) return process, nil }
go
func (i *TeleInstance) StartNode(tconf *service.Config) (*service.TeleportProcess, error) { dataDir, err := ioutil.TempDir("", "cluster-"+i.Secrets.SiteName) if err != nil { return nil, trace.Wrap(err) } tconf.DataDir = dataDir authServer := utils.MustParseAddr(net.JoinHostPort(i.Hostname, i.GetPortAuth())) tconf.AuthServers = append(tconf.AuthServers, *authServer) tconf.Token = "token" tconf.UploadEventsC = i.UploadEventsC var ttl time.Duration tconf.CachePolicy = service.CachePolicy{ Enabled: true, RecentTTL: &ttl, } tconf.SSH.PublicAddrs = []utils.NetAddr{ utils.NetAddr{ AddrNetwork: "tcp", Addr: Loopback, }, utils.NetAddr{ AddrNetwork: "tcp", Addr: Host, }, } tconf.Auth.Enabled = false tconf.Proxy.Enabled = false // Create a new Teleport process and add it to the list of nodes that // compose this "cluster". process, err := service.NewTeleport(tconf) if err != nil { return nil, trace.Wrap(err) } i.Nodes = append(i.Nodes, process) // Build a list of expected events to wait for before unblocking based off // the configuration passed in. expectedEvents := []string{ service.NodeSSHReady, } // Start the process and block until the expected events have arrived. receivedEvents, err := startAndWait(process, expectedEvents) if err != nil { return nil, trace.Wrap(err) } log.Debugf("Teleport node (in instance %v) started: %v/%v events received.", i.Secrets.SiteName, len(expectedEvents), len(receivedEvents)) return process, nil }
[ "func", "(", "i", "*", "TeleInstance", ")", "StartNode", "(", "tconf", "*", "service", ".", "Config", ")", "(", "*", "service", ".", "TeleportProcess", ",", "error", ")", "{", "dataDir", ",", "err", ":=", "ioutil", ".", "TempDir", "(", "\"\"", ",", "\"cluster-\"", "+", "i", ".", "Secrets", ".", "SiteName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "tconf", ".", "DataDir", "=", "dataDir", "\n", "authServer", ":=", "utils", ".", "MustParseAddr", "(", "net", ".", "JoinHostPort", "(", "i", ".", "Hostname", ",", "i", ".", "GetPortAuth", "(", ")", ")", ")", "\n", "tconf", ".", "AuthServers", "=", "append", "(", "tconf", ".", "AuthServers", ",", "*", "authServer", ")", "\n", "tconf", ".", "Token", "=", "\"token\"", "\n", "tconf", ".", "UploadEventsC", "=", "i", ".", "UploadEventsC", "\n", "var", "ttl", "time", ".", "Duration", "\n", "tconf", ".", "CachePolicy", "=", "service", ".", "CachePolicy", "{", "Enabled", ":", "true", ",", "RecentTTL", ":", "&", "ttl", ",", "}", "\n", "tconf", ".", "SSH", ".", "PublicAddrs", "=", "[", "]", "utils", ".", "NetAddr", "{", "utils", ".", "NetAddr", "{", "AddrNetwork", ":", "\"tcp\"", ",", "Addr", ":", "Loopback", ",", "}", ",", "utils", ".", "NetAddr", "{", "AddrNetwork", ":", "\"tcp\"", ",", "Addr", ":", "Host", ",", "}", ",", "}", "\n", "tconf", ".", "Auth", ".", "Enabled", "=", "false", "\n", "tconf", ".", "Proxy", ".", "Enabled", "=", "false", "\n", "process", ",", "err", ":=", "service", ".", "NewTeleport", "(", "tconf", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "i", ".", "Nodes", "=", "append", "(", "i", ".", "Nodes", ",", "process", ")", "\n", "expectedEvents", ":=", "[", "]", "string", "{", "service", ".", "NodeSSHReady", ",", "}", "\n", "receivedEvents", ",", "err", ":=", "startAndWait", "(", "process", ",", "expectedEvents", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "log", ".", "Debugf", "(", "\"Teleport node (in instance %v) started: %v/%v events received.\"", ",", "i", ".", "Secrets", ".", "SiteName", ",", "len", "(", "expectedEvents", ")", ",", "len", "(", "receivedEvents", ")", ")", "\n", "return", "process", ",", "nil", "\n", "}" ]
// StartNode starts a SSH node and connects it to the cluster.
[ "StartNode", "starts", "a", "SSH", "node", "and", "connects", "it", "to", "the", "cluster", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L603-L655
train
gravitational/teleport
integration/helpers.go
StartNodeAndProxy
func (i *TeleInstance) StartNodeAndProxy(name string, sshPort, proxyWebPort, proxySSHPort int) error { dataDir, err := ioutil.TempDir("", "cluster-"+i.Secrets.SiteName) if err != nil { return trace.Wrap(err) } tconf := service.MakeDefaultConfig() authServer := utils.MustParseAddr(net.JoinHostPort(i.Hostname, i.GetPortAuth())) tconf.AuthServers = append(tconf.AuthServers, *authServer) tconf.Token = "token" tconf.HostUUID = name tconf.Hostname = name tconf.UploadEventsC = i.UploadEventsC tconf.DataDir = dataDir var ttl time.Duration tconf.CachePolicy = service.CachePolicy{ Enabled: true, RecentTTL: &ttl, } tconf.Auth.Enabled = false tconf.Proxy.Enabled = true tconf.Proxy.SSHAddr.Addr = net.JoinHostPort(i.Hostname, fmt.Sprintf("%v", proxySSHPort)) tconf.Proxy.WebAddr.Addr = net.JoinHostPort(i.Hostname, fmt.Sprintf("%v", proxyWebPort)) tconf.Proxy.DisableReverseTunnel = true tconf.Proxy.DisableWebService = true tconf.SSH.Enabled = true tconf.SSH.Addr.Addr = net.JoinHostPort(i.Hostname, fmt.Sprintf("%v", sshPort)) tconf.SSH.PublicAddrs = []utils.NetAddr{ utils.NetAddr{ AddrNetwork: "tcp", Addr: Loopback, }, utils.NetAddr{ AddrNetwork: "tcp", Addr: Host, }, } // Create a new Teleport process and add it to the list of nodes that // compose this "cluster". process, err := service.NewTeleport(tconf) if err != nil { return trace.Wrap(err) } i.Nodes = append(i.Nodes, process) // Build a list of expected events to wait for before unblocking based off // the configuration passed in. expectedEvents := []string{ service.ProxySSHReady, service.NodeSSHReady, } // Start the process and block until the expected events have arrived. receivedEvents, err := startAndWait(process, expectedEvents) if err != nil { return trace.Wrap(err) } log.Debugf("Teleport node and proxy (in instance %v) started: %v/%v events received.", i.Secrets.SiteName, len(expectedEvents), len(receivedEvents)) return nil }
go
func (i *TeleInstance) StartNodeAndProxy(name string, sshPort, proxyWebPort, proxySSHPort int) error { dataDir, err := ioutil.TempDir("", "cluster-"+i.Secrets.SiteName) if err != nil { return trace.Wrap(err) } tconf := service.MakeDefaultConfig() authServer := utils.MustParseAddr(net.JoinHostPort(i.Hostname, i.GetPortAuth())) tconf.AuthServers = append(tconf.AuthServers, *authServer) tconf.Token = "token" tconf.HostUUID = name tconf.Hostname = name tconf.UploadEventsC = i.UploadEventsC tconf.DataDir = dataDir var ttl time.Duration tconf.CachePolicy = service.CachePolicy{ Enabled: true, RecentTTL: &ttl, } tconf.Auth.Enabled = false tconf.Proxy.Enabled = true tconf.Proxy.SSHAddr.Addr = net.JoinHostPort(i.Hostname, fmt.Sprintf("%v", proxySSHPort)) tconf.Proxy.WebAddr.Addr = net.JoinHostPort(i.Hostname, fmt.Sprintf("%v", proxyWebPort)) tconf.Proxy.DisableReverseTunnel = true tconf.Proxy.DisableWebService = true tconf.SSH.Enabled = true tconf.SSH.Addr.Addr = net.JoinHostPort(i.Hostname, fmt.Sprintf("%v", sshPort)) tconf.SSH.PublicAddrs = []utils.NetAddr{ utils.NetAddr{ AddrNetwork: "tcp", Addr: Loopback, }, utils.NetAddr{ AddrNetwork: "tcp", Addr: Host, }, } // Create a new Teleport process and add it to the list of nodes that // compose this "cluster". process, err := service.NewTeleport(tconf) if err != nil { return trace.Wrap(err) } i.Nodes = append(i.Nodes, process) // Build a list of expected events to wait for before unblocking based off // the configuration passed in. expectedEvents := []string{ service.ProxySSHReady, service.NodeSSHReady, } // Start the process and block until the expected events have arrived. receivedEvents, err := startAndWait(process, expectedEvents) if err != nil { return trace.Wrap(err) } log.Debugf("Teleport node and proxy (in instance %v) started: %v/%v events received.", i.Secrets.SiteName, len(expectedEvents), len(receivedEvents)) return nil }
[ "func", "(", "i", "*", "TeleInstance", ")", "StartNodeAndProxy", "(", "name", "string", ",", "sshPort", ",", "proxyWebPort", ",", "proxySSHPort", "int", ")", "error", "{", "dataDir", ",", "err", ":=", "ioutil", ".", "TempDir", "(", "\"\"", ",", "\"cluster-\"", "+", "i", ".", "Secrets", ".", "SiteName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "tconf", ":=", "service", ".", "MakeDefaultConfig", "(", ")", "\n", "authServer", ":=", "utils", ".", "MustParseAddr", "(", "net", ".", "JoinHostPort", "(", "i", ".", "Hostname", ",", "i", ".", "GetPortAuth", "(", ")", ")", ")", "\n", "tconf", ".", "AuthServers", "=", "append", "(", "tconf", ".", "AuthServers", ",", "*", "authServer", ")", "\n", "tconf", ".", "Token", "=", "\"token\"", "\n", "tconf", ".", "HostUUID", "=", "name", "\n", "tconf", ".", "Hostname", "=", "name", "\n", "tconf", ".", "UploadEventsC", "=", "i", ".", "UploadEventsC", "\n", "tconf", ".", "DataDir", "=", "dataDir", "\n", "var", "ttl", "time", ".", "Duration", "\n", "tconf", ".", "CachePolicy", "=", "service", ".", "CachePolicy", "{", "Enabled", ":", "true", ",", "RecentTTL", ":", "&", "ttl", ",", "}", "\n", "tconf", ".", "Auth", ".", "Enabled", "=", "false", "\n", "tconf", ".", "Proxy", ".", "Enabled", "=", "true", "\n", "tconf", ".", "Proxy", ".", "SSHAddr", ".", "Addr", "=", "net", ".", "JoinHostPort", "(", "i", ".", "Hostname", ",", "fmt", ".", "Sprintf", "(", "\"%v\"", ",", "proxySSHPort", ")", ")", "\n", "tconf", ".", "Proxy", ".", "WebAddr", ".", "Addr", "=", "net", ".", "JoinHostPort", "(", "i", ".", "Hostname", ",", "fmt", ".", "Sprintf", "(", "\"%v\"", ",", "proxyWebPort", ")", ")", "\n", "tconf", ".", "Proxy", ".", "DisableReverseTunnel", "=", "true", "\n", "tconf", ".", "Proxy", ".", "DisableWebService", "=", "true", "\n", "tconf", ".", "SSH", ".", "Enabled", "=", "true", "\n", "tconf", ".", "SSH", ".", "Addr", ".", "Addr", "=", "net", ".", "JoinHostPort", "(", "i", ".", "Hostname", ",", "fmt", ".", "Sprintf", "(", "\"%v\"", ",", "sshPort", ")", ")", "\n", "tconf", ".", "SSH", ".", "PublicAddrs", "=", "[", "]", "utils", ".", "NetAddr", "{", "utils", ".", "NetAddr", "{", "AddrNetwork", ":", "\"tcp\"", ",", "Addr", ":", "Loopback", ",", "}", ",", "utils", ".", "NetAddr", "{", "AddrNetwork", ":", "\"tcp\"", ",", "Addr", ":", "Host", ",", "}", ",", "}", "\n", "process", ",", "err", ":=", "service", ".", "NewTeleport", "(", "tconf", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "i", ".", "Nodes", "=", "append", "(", "i", ".", "Nodes", ",", "process", ")", "\n", "expectedEvents", ":=", "[", "]", "string", "{", "service", ".", "ProxySSHReady", ",", "service", ".", "NodeSSHReady", ",", "}", "\n", "receivedEvents", ",", "err", ":=", "startAndWait", "(", "process", ",", "expectedEvents", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "log", ".", "Debugf", "(", "\"Teleport node and proxy (in instance %v) started: %v/%v events received.\"", ",", "i", ".", "Secrets", ".", "SiteName", ",", "len", "(", "expectedEvents", ")", ",", "len", "(", "receivedEvents", ")", ")", "\n", "return", "nil", "\n", "}" ]
// StartNodeAndProxy starts a SSH node and a Proxy Server and connects it to // the cluster.
[ "StartNodeAndProxy", "starts", "a", "SSH", "node", "and", "a", "Proxy", "Server", "and", "connects", "it", "to", "the", "cluster", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L659-L725
train
gravitational/teleport
integration/helpers.go
StartProxy
func (i *TeleInstance) StartProxy(cfg ProxyConfig) error { dataDir, err := ioutil.TempDir("", "cluster-"+i.Secrets.SiteName+"-"+cfg.Name) if err != nil { return trace.Wrap(err) } tconf := service.MakeDefaultConfig() authServer := utils.MustParseAddr(net.JoinHostPort(i.Hostname, i.GetPortAuth())) tconf.AuthServers = append(tconf.AuthServers, *authServer) tconf.CachePolicy = service.CachePolicy{Enabled: true} tconf.DataDir = dataDir tconf.UploadEventsC = i.UploadEventsC tconf.HostUUID = cfg.Name tconf.Hostname = cfg.Name tconf.Token = "token" tconf.Auth.Enabled = false tconf.SSH.Enabled = false tconf.Proxy.Enabled = true tconf.Proxy.SSHAddr.Addr = net.JoinHostPort(i.Hostname, fmt.Sprintf("%v", cfg.SSHPort)) tconf.Proxy.PublicAddrs = []utils.NetAddr{ utils.NetAddr{ AddrNetwork: "tcp", Addr: Loopback, }, utils.NetAddr{ AddrNetwork: "tcp", Addr: Host, }, } tconf.Proxy.ReverseTunnelListenAddr.Addr = net.JoinHostPort(i.Hostname, fmt.Sprintf("%v", cfg.ReverseTunnelPort)) tconf.Proxy.WebAddr.Addr = net.JoinHostPort(i.Hostname, fmt.Sprintf("%v", cfg.WebPort)) tconf.Proxy.DisableReverseTunnel = false tconf.Proxy.DisableWebService = true // Create a new Teleport process and add it to the list of nodes that // compose this "cluster". process, err := service.NewTeleport(tconf) if err != nil { return trace.Wrap(err) } i.Nodes = append(i.Nodes, process) // Build a list of expected events to wait for before unblocking based off // the configuration passed in. expectedEvents := []string{ service.ProxyReverseTunnelReady, service.ProxySSHReady, } // Start the process and block until the expected events have arrived. receivedEvents, err := startAndWait(process, expectedEvents) if err != nil { return trace.Wrap(err) } log.Debugf("Teleport proxy (in instance %v) started: %v/%v events received.", i.Secrets.SiteName, len(expectedEvents), len(receivedEvents)) return nil }
go
func (i *TeleInstance) StartProxy(cfg ProxyConfig) error { dataDir, err := ioutil.TempDir("", "cluster-"+i.Secrets.SiteName+"-"+cfg.Name) if err != nil { return trace.Wrap(err) } tconf := service.MakeDefaultConfig() authServer := utils.MustParseAddr(net.JoinHostPort(i.Hostname, i.GetPortAuth())) tconf.AuthServers = append(tconf.AuthServers, *authServer) tconf.CachePolicy = service.CachePolicy{Enabled: true} tconf.DataDir = dataDir tconf.UploadEventsC = i.UploadEventsC tconf.HostUUID = cfg.Name tconf.Hostname = cfg.Name tconf.Token = "token" tconf.Auth.Enabled = false tconf.SSH.Enabled = false tconf.Proxy.Enabled = true tconf.Proxy.SSHAddr.Addr = net.JoinHostPort(i.Hostname, fmt.Sprintf("%v", cfg.SSHPort)) tconf.Proxy.PublicAddrs = []utils.NetAddr{ utils.NetAddr{ AddrNetwork: "tcp", Addr: Loopback, }, utils.NetAddr{ AddrNetwork: "tcp", Addr: Host, }, } tconf.Proxy.ReverseTunnelListenAddr.Addr = net.JoinHostPort(i.Hostname, fmt.Sprintf("%v", cfg.ReverseTunnelPort)) tconf.Proxy.WebAddr.Addr = net.JoinHostPort(i.Hostname, fmt.Sprintf("%v", cfg.WebPort)) tconf.Proxy.DisableReverseTunnel = false tconf.Proxy.DisableWebService = true // Create a new Teleport process and add it to the list of nodes that // compose this "cluster". process, err := service.NewTeleport(tconf) if err != nil { return trace.Wrap(err) } i.Nodes = append(i.Nodes, process) // Build a list of expected events to wait for before unblocking based off // the configuration passed in. expectedEvents := []string{ service.ProxyReverseTunnelReady, service.ProxySSHReady, } // Start the process and block until the expected events have arrived. receivedEvents, err := startAndWait(process, expectedEvents) if err != nil { return trace.Wrap(err) } log.Debugf("Teleport proxy (in instance %v) started: %v/%v events received.", i.Secrets.SiteName, len(expectedEvents), len(receivedEvents)) return nil }
[ "func", "(", "i", "*", "TeleInstance", ")", "StartProxy", "(", "cfg", "ProxyConfig", ")", "error", "{", "dataDir", ",", "err", ":=", "ioutil", ".", "TempDir", "(", "\"\"", ",", "\"cluster-\"", "+", "i", ".", "Secrets", ".", "SiteName", "+", "\"-\"", "+", "cfg", ".", "Name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "tconf", ":=", "service", ".", "MakeDefaultConfig", "(", ")", "\n", "authServer", ":=", "utils", ".", "MustParseAddr", "(", "net", ".", "JoinHostPort", "(", "i", ".", "Hostname", ",", "i", ".", "GetPortAuth", "(", ")", ")", ")", "\n", "tconf", ".", "AuthServers", "=", "append", "(", "tconf", ".", "AuthServers", ",", "*", "authServer", ")", "\n", "tconf", ".", "CachePolicy", "=", "service", ".", "CachePolicy", "{", "Enabled", ":", "true", "}", "\n", "tconf", ".", "DataDir", "=", "dataDir", "\n", "tconf", ".", "UploadEventsC", "=", "i", ".", "UploadEventsC", "\n", "tconf", ".", "HostUUID", "=", "cfg", ".", "Name", "\n", "tconf", ".", "Hostname", "=", "cfg", ".", "Name", "\n", "tconf", ".", "Token", "=", "\"token\"", "\n", "tconf", ".", "Auth", ".", "Enabled", "=", "false", "\n", "tconf", ".", "SSH", ".", "Enabled", "=", "false", "\n", "tconf", ".", "Proxy", ".", "Enabled", "=", "true", "\n", "tconf", ".", "Proxy", ".", "SSHAddr", ".", "Addr", "=", "net", ".", "JoinHostPort", "(", "i", ".", "Hostname", ",", "fmt", ".", "Sprintf", "(", "\"%v\"", ",", "cfg", ".", "SSHPort", ")", ")", "\n", "tconf", ".", "Proxy", ".", "PublicAddrs", "=", "[", "]", "utils", ".", "NetAddr", "{", "utils", ".", "NetAddr", "{", "AddrNetwork", ":", "\"tcp\"", ",", "Addr", ":", "Loopback", ",", "}", ",", "utils", ".", "NetAddr", "{", "AddrNetwork", ":", "\"tcp\"", ",", "Addr", ":", "Host", ",", "}", ",", "}", "\n", "tconf", ".", "Proxy", ".", "ReverseTunnelListenAddr", ".", "Addr", "=", "net", ".", "JoinHostPort", "(", "i", ".", "Hostname", ",", "fmt", ".", "Sprintf", "(", "\"%v\"", ",", "cfg", ".", "ReverseTunnelPort", ")", ")", "\n", "tconf", ".", "Proxy", ".", "WebAddr", ".", "Addr", "=", "net", ".", "JoinHostPort", "(", "i", ".", "Hostname", ",", "fmt", ".", "Sprintf", "(", "\"%v\"", ",", "cfg", ".", "WebPort", ")", ")", "\n", "tconf", ".", "Proxy", ".", "DisableReverseTunnel", "=", "false", "\n", "tconf", ".", "Proxy", ".", "DisableWebService", "=", "true", "\n", "process", ",", "err", ":=", "service", ".", "NewTeleport", "(", "tconf", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "i", ".", "Nodes", "=", "append", "(", "i", ".", "Nodes", ",", "process", ")", "\n", "expectedEvents", ":=", "[", "]", "string", "{", "service", ".", "ProxyReverseTunnelReady", ",", "service", ".", "ProxySSHReady", ",", "}", "\n", "receivedEvents", ",", "err", ":=", "startAndWait", "(", "process", ",", "expectedEvents", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "log", ".", "Debugf", "(", "\"Teleport proxy (in instance %v) started: %v/%v events received.\"", ",", "i", ".", "Secrets", ".", "SiteName", ",", "len", "(", "expectedEvents", ")", ",", "len", "(", "receivedEvents", ")", ")", "\n", "return", "nil", "\n", "}" ]
// StartProxy starts another Proxy Server and connects it to the cluster.
[ "StartProxy", "starts", "another", "Proxy", "Server", "and", "connects", "it", "to", "the", "cluster", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L740-L802
train
gravitational/teleport
integration/helpers.go
Reset
func (i *TeleInstance) Reset() (err error) { i.Process, err = service.NewTeleport(i.Config) if err != nil { return trace.Wrap(err) } return nil }
go
func (i *TeleInstance) Reset() (err error) { i.Process, err = service.NewTeleport(i.Config) if err != nil { return trace.Wrap(err) } return nil }
[ "func", "(", "i", "*", "TeleInstance", ")", "Reset", "(", ")", "(", "err", "error", ")", "{", "i", ".", "Process", ",", "err", "=", "service", ".", "NewTeleport", "(", "i", ".", "Config", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Reset re-creates the teleport instance based on the same configuration // This is needed if you want to stop the instance, reset it and start again
[ "Reset", "re", "-", "creates", "the", "teleport", "instance", "based", "on", "the", "same", "configuration", "This", "is", "needed", "if", "you", "want", "to", "stop", "the", "instance", "reset", "it", "and", "start", "again" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L806-L812
train
gravitational/teleport
integration/helpers.go
AddUserWithRole
func (i *TeleInstance) AddUserWithRole(username string, role services.Role) *User { user := &User{ Username: username, Roles: []services.Role{role}, } i.Secrets.Users[username] = user return user }
go
func (i *TeleInstance) AddUserWithRole(username string, role services.Role) *User { user := &User{ Username: username, Roles: []services.Role{role}, } i.Secrets.Users[username] = user return user }
[ "func", "(", "i", "*", "TeleInstance", ")", "AddUserWithRole", "(", "username", "string", ",", "role", "services", ".", "Role", ")", "*", "User", "{", "user", ":=", "&", "User", "{", "Username", ":", "username", ",", "Roles", ":", "[", "]", "services", ".", "Role", "{", "role", "}", ",", "}", "\n", "i", ".", "Secrets", ".", "Users", "[", "username", "]", "=", "user", "\n", "return", "user", "\n", "}" ]
// AddUserUserWithRole adds user with assigned role
[ "AddUserUserWithRole", "adds", "user", "with", "assigned", "role" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L815-L822
train
gravitational/teleport
integration/helpers.go
AddUser
func (i *TeleInstance) AddUser(username string, mappings []string) *User { log.Infof("teleInstance.AddUser(%v) mapped to %v", username, mappings) if mappings == nil { mappings = make([]string, 0) } user := &User{ Username: username, AllowedLogins: mappings, } i.Secrets.Users[username] = user return user }
go
func (i *TeleInstance) AddUser(username string, mappings []string) *User { log.Infof("teleInstance.AddUser(%v) mapped to %v", username, mappings) if mappings == nil { mappings = make([]string, 0) } user := &User{ Username: username, AllowedLogins: mappings, } i.Secrets.Users[username] = user return user }
[ "func", "(", "i", "*", "TeleInstance", ")", "AddUser", "(", "username", "string", ",", "mappings", "[", "]", "string", ")", "*", "User", "{", "log", ".", "Infof", "(", "\"teleInstance.AddUser(%v) mapped to %v\"", ",", "username", ",", "mappings", ")", "\n", "if", "mappings", "==", "nil", "{", "mappings", "=", "make", "(", "[", "]", "string", ",", "0", ")", "\n", "}", "\n", "user", ":=", "&", "User", "{", "Username", ":", "username", ",", "AllowedLogins", ":", "mappings", ",", "}", "\n", "i", ".", "Secrets", ".", "Users", "[", "username", "]", "=", "user", "\n", "return", "user", "\n", "}" ]
// Adds a new user into i Teleport instance. 'mappings' is a comma-separated // list of OS users
[ "Adds", "a", "new", "user", "into", "i", "Teleport", "instance", ".", "mappings", "is", "a", "comma", "-", "separated", "list", "of", "OS", "users" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L826-L837
train
gravitational/teleport
integration/helpers.go
Start
func (i *TeleInstance) Start() error { // Build a list of expected events to wait for before unblocking based off // the configuration passed in. expectedEvents := []string{} if i.Config.Auth.Enabled { expectedEvents = append(expectedEvents, service.AuthTLSReady) } if i.Config.Proxy.Enabled { expectedEvents = append(expectedEvents, service.ProxyReverseTunnelReady) expectedEvents = append(expectedEvents, service.ProxySSHReady) expectedEvents = append(expectedEvents, service.ProxyAgentPoolReady) if !i.Config.Proxy.DisableWebService { expectedEvents = append(expectedEvents, service.ProxyWebServerReady) } } if i.Config.SSH.Enabled { expectedEvents = append(expectedEvents, service.NodeSSHReady) } // Start the process and block until the expected events have arrived. receivedEvents, err := startAndWait(i.Process, expectedEvents) if err != nil { return trace.Wrap(err) } // Extract and set reversetunnel.Server and reversetunnel.AgentPool upon // receipt of a ProxyReverseTunnelReady and ProxyAgentPoolReady respectively. for _, re := range receivedEvents { switch re.Name { case service.ProxyReverseTunnelReady: ts, ok := re.Payload.(reversetunnel.Server) if ok { i.Tunnel = ts } case service.ProxyAgentPoolReady: ap, ok := re.Payload.(*reversetunnel.AgentPool) if ok { i.Pool = ap } } } log.Debugf("Teleport instance %v started: %v/%v events received.", i.Secrets.SiteName, len(receivedEvents), len(expectedEvents)) return nil }
go
func (i *TeleInstance) Start() error { // Build a list of expected events to wait for before unblocking based off // the configuration passed in. expectedEvents := []string{} if i.Config.Auth.Enabled { expectedEvents = append(expectedEvents, service.AuthTLSReady) } if i.Config.Proxy.Enabled { expectedEvents = append(expectedEvents, service.ProxyReverseTunnelReady) expectedEvents = append(expectedEvents, service.ProxySSHReady) expectedEvents = append(expectedEvents, service.ProxyAgentPoolReady) if !i.Config.Proxy.DisableWebService { expectedEvents = append(expectedEvents, service.ProxyWebServerReady) } } if i.Config.SSH.Enabled { expectedEvents = append(expectedEvents, service.NodeSSHReady) } // Start the process and block until the expected events have arrived. receivedEvents, err := startAndWait(i.Process, expectedEvents) if err != nil { return trace.Wrap(err) } // Extract and set reversetunnel.Server and reversetunnel.AgentPool upon // receipt of a ProxyReverseTunnelReady and ProxyAgentPoolReady respectively. for _, re := range receivedEvents { switch re.Name { case service.ProxyReverseTunnelReady: ts, ok := re.Payload.(reversetunnel.Server) if ok { i.Tunnel = ts } case service.ProxyAgentPoolReady: ap, ok := re.Payload.(*reversetunnel.AgentPool) if ok { i.Pool = ap } } } log.Debugf("Teleport instance %v started: %v/%v events received.", i.Secrets.SiteName, len(receivedEvents), len(expectedEvents)) return nil }
[ "func", "(", "i", "*", "TeleInstance", ")", "Start", "(", ")", "error", "{", "expectedEvents", ":=", "[", "]", "string", "{", "}", "\n", "if", "i", ".", "Config", ".", "Auth", ".", "Enabled", "{", "expectedEvents", "=", "append", "(", "expectedEvents", ",", "service", ".", "AuthTLSReady", ")", "\n", "}", "\n", "if", "i", ".", "Config", ".", "Proxy", ".", "Enabled", "{", "expectedEvents", "=", "append", "(", "expectedEvents", ",", "service", ".", "ProxyReverseTunnelReady", ")", "\n", "expectedEvents", "=", "append", "(", "expectedEvents", ",", "service", ".", "ProxySSHReady", ")", "\n", "expectedEvents", "=", "append", "(", "expectedEvents", ",", "service", ".", "ProxyAgentPoolReady", ")", "\n", "if", "!", "i", ".", "Config", ".", "Proxy", ".", "DisableWebService", "{", "expectedEvents", "=", "append", "(", "expectedEvents", ",", "service", ".", "ProxyWebServerReady", ")", "\n", "}", "\n", "}", "\n", "if", "i", ".", "Config", ".", "SSH", ".", "Enabled", "{", "expectedEvents", "=", "append", "(", "expectedEvents", ",", "service", ".", "NodeSSHReady", ")", "\n", "}", "\n", "receivedEvents", ",", "err", ":=", "startAndWait", "(", "i", ".", "Process", ",", "expectedEvents", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "for", "_", ",", "re", ":=", "range", "receivedEvents", "{", "switch", "re", ".", "Name", "{", "case", "service", ".", "ProxyReverseTunnelReady", ":", "ts", ",", "ok", ":=", "re", ".", "Payload", ".", "(", "reversetunnel", ".", "Server", ")", "\n", "if", "ok", "{", "i", ".", "Tunnel", "=", "ts", "\n", "}", "\n", "case", "service", ".", "ProxyAgentPoolReady", ":", "ap", ",", "ok", ":=", "re", ".", "Payload", ".", "(", "*", "reversetunnel", ".", "AgentPool", ")", "\n", "if", "ok", "{", "i", ".", "Pool", "=", "ap", "\n", "}", "\n", "}", "\n", "}", "\n", "log", ".", "Debugf", "(", "\"Teleport instance %v started: %v/%v events received.\"", ",", "i", ".", "Secrets", ".", "SiteName", ",", "len", "(", "receivedEvents", ")", ",", "len", "(", "expectedEvents", ")", ")", "\n", "return", "nil", "\n", "}" ]
// Start will start the TeleInstance and then block until it is ready to // process requests based off the passed in configuration.
[ "Start", "will", "start", "the", "TeleInstance", "and", "then", "block", "until", "it", "is", "ready", "to", "process", "requests", "based", "off", "the", "passed", "in", "configuration", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L841-L886
train
gravitational/teleport
integration/helpers.go
NewClientWithCreds
func (i *TeleInstance) NewClientWithCreds(cfg ClientConfig, creds UserCreds) (tc *client.TeleportClient, err error) { clt, err := i.NewUnauthenticatedClient(cfg) if err != nil { return nil, trace.Wrap(err) } err = SetupUserCreds(clt, i.Config.Proxy.SSHAddr.Addr, creds) if err != nil { return nil, trace.Wrap(err) } return clt, nil }
go
func (i *TeleInstance) NewClientWithCreds(cfg ClientConfig, creds UserCreds) (tc *client.TeleportClient, err error) { clt, err := i.NewUnauthenticatedClient(cfg) if err != nil { return nil, trace.Wrap(err) } err = SetupUserCreds(clt, i.Config.Proxy.SSHAddr.Addr, creds) if err != nil { return nil, trace.Wrap(err) } return clt, nil }
[ "func", "(", "i", "*", "TeleInstance", ")", "NewClientWithCreds", "(", "cfg", "ClientConfig", ",", "creds", "UserCreds", ")", "(", "tc", "*", "client", ".", "TeleportClient", ",", "err", "error", ")", "{", "clt", ",", "err", ":=", "i", ".", "NewUnauthenticatedClient", "(", "cfg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "err", "=", "SetupUserCreds", "(", "clt", ",", "i", ".", "Config", ".", "Proxy", ".", "SSHAddr", ".", "Addr", ",", "creds", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "clt", ",", "nil", "\n", "}" ]
// NewClientWithCreds creates client with credentials
[ "NewClientWithCreds", "creates", "client", "with", "credentials" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L906-L916
train
gravitational/teleport
integration/helpers.go
StopProxy
func (i *TeleInstance) StopProxy() error { var errors []error for _, p := range i.Nodes { if p.Config.Proxy.Enabled { if err := p.Close(); err != nil { errors = append(errors, err) log.Errorf("Failed closing extra proxy: %v.", err) } if err := p.Wait(); err != nil { errors = append(errors, err) log.Errorf("Failed to stop extra proxy: %v.", err) } } } return trace.NewAggregate(errors...) }
go
func (i *TeleInstance) StopProxy() error { var errors []error for _, p := range i.Nodes { if p.Config.Proxy.Enabled { if err := p.Close(); err != nil { errors = append(errors, err) log.Errorf("Failed closing extra proxy: %v.", err) } if err := p.Wait(); err != nil { errors = append(errors, err) log.Errorf("Failed to stop extra proxy: %v.", err) } } } return trace.NewAggregate(errors...) }
[ "func", "(", "i", "*", "TeleInstance", ")", "StopProxy", "(", ")", "error", "{", "var", "errors", "[", "]", "error", "\n", "for", "_", ",", "p", ":=", "range", "i", ".", "Nodes", "{", "if", "p", ".", "Config", ".", "Proxy", ".", "Enabled", "{", "if", "err", ":=", "p", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "errors", "=", "append", "(", "errors", ",", "err", ")", "\n", "log", ".", "Errorf", "(", "\"Failed closing extra proxy: %v.\"", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "p", ".", "Wait", "(", ")", ";", "err", "!=", "nil", "{", "errors", "=", "append", "(", "errors", ",", "err", ")", "\n", "log", ".", "Errorf", "(", "\"Failed to stop extra proxy: %v.\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "trace", ".", "NewAggregate", "(", "errors", "...", ")", "\n", "}" ]
// StopProxy loops over the extra nodes in a TeleInstance and stops all // nodes where the proxy server is enabled.
[ "StopProxy", "loops", "over", "the", "extra", "nodes", "in", "a", "TeleInstance", "and", "stops", "all", "nodes", "where", "the", "proxy", "server", "is", "enabled", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L993-L1010
train
gravitational/teleport
integration/helpers.go
StopNodes
func (i *TeleInstance) StopNodes() error { var errors []error for _, node := range i.Nodes { if err := node.Close(); err != nil { errors = append(errors, err) log.Errorf("failed closing extra node %v", err) } if err := node.Wait(); err != nil { errors = append(errors, err) log.Errorf("failed stopping extra node %v", err) } } return trace.NewAggregate(errors...) }
go
func (i *TeleInstance) StopNodes() error { var errors []error for _, node := range i.Nodes { if err := node.Close(); err != nil { errors = append(errors, err) log.Errorf("failed closing extra node %v", err) } if err := node.Wait(); err != nil { errors = append(errors, err) log.Errorf("failed stopping extra node %v", err) } } return trace.NewAggregate(errors...) }
[ "func", "(", "i", "*", "TeleInstance", ")", "StopNodes", "(", ")", "error", "{", "var", "errors", "[", "]", "error", "\n", "for", "_", ",", "node", ":=", "range", "i", ".", "Nodes", "{", "if", "err", ":=", "node", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "errors", "=", "append", "(", "errors", ",", "err", ")", "\n", "log", ".", "Errorf", "(", "\"failed closing extra node %v\"", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "node", ".", "Wait", "(", ")", ";", "err", "!=", "nil", "{", "errors", "=", "append", "(", "errors", ",", "err", ")", "\n", "log", ".", "Errorf", "(", "\"failed stopping extra node %v\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "trace", ".", "NewAggregate", "(", "errors", "...", ")", "\n", "}" ]
// StopNodes stops additional nodes
[ "StopNodes", "stops", "additional", "nodes" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L1013-L1026
train
gravitational/teleport
integration/helpers.go
ServeHTTP
func (p *proxyServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Validate http connect parameters. if r.Method != http.MethodConnect { trace.WriteError(w, trace.BadParameter("%v not supported", r.Method)) return } if r.Host == "" { trace.WriteError(w, trace.BadParameter("host not set")) return } // Dial to the target host, this is done before hijacking the connection to // ensure the target host is accessible. dconn, err := net.Dial("tcp", r.Host) if err != nil { trace.WriteError(w, err) return } defer dconn.Close() // Once the client receives 200 OK, the rest of the data will no longer be // http, but whatever protocol is being tunneled. w.WriteHeader(http.StatusOK) // Hijack request so we can get underlying connection. hj, ok := w.(http.Hijacker) if !ok { trace.WriteError(w, trace.AccessDenied("unable to hijack connection")) return } sconn, _, err := hj.Hijack() if err != nil { trace.WriteError(w, err) return } defer sconn.Close() // Success, we're proxying data now. p.Lock() p.count = p.count + 1 p.Unlock() // Copy from src to dst and dst to src. errc := make(chan error, 2) replicate := func(dst io.Writer, src io.Reader) { _, err := io.Copy(dst, src) errc <- err } go replicate(sconn, dconn) go replicate(dconn, sconn) // Wait until done, error, or 10 second. select { case <-time.After(10 * time.Second): case <-errc: } }
go
func (p *proxyServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Validate http connect parameters. if r.Method != http.MethodConnect { trace.WriteError(w, trace.BadParameter("%v not supported", r.Method)) return } if r.Host == "" { trace.WriteError(w, trace.BadParameter("host not set")) return } // Dial to the target host, this is done before hijacking the connection to // ensure the target host is accessible. dconn, err := net.Dial("tcp", r.Host) if err != nil { trace.WriteError(w, err) return } defer dconn.Close() // Once the client receives 200 OK, the rest of the data will no longer be // http, but whatever protocol is being tunneled. w.WriteHeader(http.StatusOK) // Hijack request so we can get underlying connection. hj, ok := w.(http.Hijacker) if !ok { trace.WriteError(w, trace.AccessDenied("unable to hijack connection")) return } sconn, _, err := hj.Hijack() if err != nil { trace.WriteError(w, err) return } defer sconn.Close() // Success, we're proxying data now. p.Lock() p.count = p.count + 1 p.Unlock() // Copy from src to dst and dst to src. errc := make(chan error, 2) replicate := func(dst io.Writer, src io.Reader) { _, err := io.Copy(dst, src) errc <- err } go replicate(sconn, dconn) go replicate(dconn, sconn) // Wait until done, error, or 10 second. select { case <-time.After(10 * time.Second): case <-errc: } }
[ "func", "(", "p", "*", "proxyServer", ")", "ServeHTTP", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "if", "r", ".", "Method", "!=", "http", ".", "MethodConnect", "{", "trace", ".", "WriteError", "(", "w", ",", "trace", ".", "BadParameter", "(", "\"%v not supported\"", ",", "r", ".", "Method", ")", ")", "\n", "return", "\n", "}", "\n", "if", "r", ".", "Host", "==", "\"\"", "{", "trace", ".", "WriteError", "(", "w", ",", "trace", ".", "BadParameter", "(", "\"host not set\"", ")", ")", "\n", "return", "\n", "}", "\n", "dconn", ",", "err", ":=", "net", ".", "Dial", "(", "\"tcp\"", ",", "r", ".", "Host", ")", "\n", "if", "err", "!=", "nil", "{", "trace", ".", "WriteError", "(", "w", ",", "err", ")", "\n", "return", "\n", "}", "\n", "defer", "dconn", ".", "Close", "(", ")", "\n", "w", ".", "WriteHeader", "(", "http", ".", "StatusOK", ")", "\n", "hj", ",", "ok", ":=", "w", ".", "(", "http", ".", "Hijacker", ")", "\n", "if", "!", "ok", "{", "trace", ".", "WriteError", "(", "w", ",", "trace", ".", "AccessDenied", "(", "\"unable to hijack connection\"", ")", ")", "\n", "return", "\n", "}", "\n", "sconn", ",", "_", ",", "err", ":=", "hj", ".", "Hijack", "(", ")", "\n", "if", "err", "!=", "nil", "{", "trace", ".", "WriteError", "(", "w", ",", "err", ")", "\n", "return", "\n", "}", "\n", "defer", "sconn", ".", "Close", "(", ")", "\n", "p", ".", "Lock", "(", ")", "\n", "p", ".", "count", "=", "p", ".", "count", "+", "1", "\n", "p", ".", "Unlock", "(", ")", "\n", "errc", ":=", "make", "(", "chan", "error", ",", "2", ")", "\n", "replicate", ":=", "func", "(", "dst", "io", ".", "Writer", ",", "src", "io", ".", "Reader", ")", "{", "_", ",", "err", ":=", "io", ".", "Copy", "(", "dst", ",", "src", ")", "\n", "errc", "<-", "err", "\n", "}", "\n", "go", "replicate", "(", "sconn", ",", "dconn", ")", "\n", "go", "replicate", "(", "dconn", ",", "sconn", ")", "\n", "select", "{", "case", "<-", "time", ".", "After", "(", "10", "*", "time", ".", "Second", ")", ":", "case", "<-", "errc", ":", "}", "\n", "}" ]
// ServeHTTP only accepts the CONNECT verb and will tunnel your connection to // the specified host. Also tracks the number of connections that it proxies for // debugging purposes.
[ "ServeHTTP", "only", "accepts", "the", "CONNECT", "verb", "and", "will", "tunnel", "your", "connection", "to", "the", "specified", "host", ".", "Also", "tracks", "the", "number", "of", "connections", "that", "it", "proxies", "for", "debugging", "purposes", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L1093-L1149
train
gravitational/teleport
integration/helpers.go
Count
func (p *proxyServer) Count() int { p.Lock() defer p.Unlock() return p.count }
go
func (p *proxyServer) Count() int { p.Lock() defer p.Unlock() return p.count }
[ "func", "(", "p", "*", "proxyServer", ")", "Count", "(", ")", "int", "{", "p", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "Unlock", "(", ")", "\n", "return", "p", ".", "count", "\n", "}" ]
// Count returns the number of connections that have been proxied.
[ "Count", "returns", "the", "number", "of", "connections", "that", "have", "been", "proxied", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L1152-L1156
train
gravitational/teleport
integration/helpers.go
createAgent
func createAgent(me *user.User, privateKeyByte []byte, certificateBytes []byte) (*teleagent.AgentServer, string, string, error) { // create a path to the unix socket sockDir, err := ioutil.TempDir("", "int-test") if err != nil { return nil, "", "", trace.Wrap(err) } sockPath := filepath.Join(sockDir, "agent.sock") uid, err := strconv.Atoi(me.Uid) if err != nil { return nil, "", "", trace.Wrap(err) } gid, err := strconv.Atoi(me.Gid) if err != nil { return nil, "", "", trace.Wrap(err) } // transform the key and certificate bytes into something the agent can understand publicKey, _, _, _, err := ssh.ParseAuthorizedKey(certificateBytes) if err != nil { return nil, "", "", trace.Wrap(err) } privateKey, err := ssh.ParseRawPrivateKey(privateKeyByte) if err != nil { return nil, "", "", trace.Wrap(err) } agentKey := agent.AddedKey{ PrivateKey: privateKey, Certificate: publicKey.(*ssh.Certificate), Comment: "", LifetimeSecs: 0, ConfirmBeforeUse: false, } // create a (unstarted) agent and add the key to it teleAgent := teleagent.NewServer() teleAgent.Add(agentKey) // start the SSH agent err = teleAgent.ListenUnixSocket(sockPath, uid, gid, 0600) if err != nil { return nil, "", "", trace.Wrap(err) } go teleAgent.Serve() return teleAgent, sockDir, sockPath, nil }
go
func createAgent(me *user.User, privateKeyByte []byte, certificateBytes []byte) (*teleagent.AgentServer, string, string, error) { // create a path to the unix socket sockDir, err := ioutil.TempDir("", "int-test") if err != nil { return nil, "", "", trace.Wrap(err) } sockPath := filepath.Join(sockDir, "agent.sock") uid, err := strconv.Atoi(me.Uid) if err != nil { return nil, "", "", trace.Wrap(err) } gid, err := strconv.Atoi(me.Gid) if err != nil { return nil, "", "", trace.Wrap(err) } // transform the key and certificate bytes into something the agent can understand publicKey, _, _, _, err := ssh.ParseAuthorizedKey(certificateBytes) if err != nil { return nil, "", "", trace.Wrap(err) } privateKey, err := ssh.ParseRawPrivateKey(privateKeyByte) if err != nil { return nil, "", "", trace.Wrap(err) } agentKey := agent.AddedKey{ PrivateKey: privateKey, Certificate: publicKey.(*ssh.Certificate), Comment: "", LifetimeSecs: 0, ConfirmBeforeUse: false, } // create a (unstarted) agent and add the key to it teleAgent := teleagent.NewServer() teleAgent.Add(agentKey) // start the SSH agent err = teleAgent.ListenUnixSocket(sockPath, uid, gid, 0600) if err != nil { return nil, "", "", trace.Wrap(err) } go teleAgent.Serve() return teleAgent, sockDir, sockPath, nil }
[ "func", "createAgent", "(", "me", "*", "user", ".", "User", ",", "privateKeyByte", "[", "]", "byte", ",", "certificateBytes", "[", "]", "byte", ")", "(", "*", "teleagent", ".", "AgentServer", ",", "string", ",", "string", ",", "error", ")", "{", "sockDir", ",", "err", ":=", "ioutil", ".", "TempDir", "(", "\"\"", ",", "\"int-test\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"\"", ",", "\"\"", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "sockPath", ":=", "filepath", ".", "Join", "(", "sockDir", ",", "\"agent.sock\"", ")", "\n", "uid", ",", "err", ":=", "strconv", ".", "Atoi", "(", "me", ".", "Uid", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"\"", ",", "\"\"", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "gid", ",", "err", ":=", "strconv", ".", "Atoi", "(", "me", ".", "Gid", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"\"", ",", "\"\"", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "publicKey", ",", "_", ",", "_", ",", "_", ",", "err", ":=", "ssh", ".", "ParseAuthorizedKey", "(", "certificateBytes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"\"", ",", "\"\"", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "privateKey", ",", "err", ":=", "ssh", ".", "ParseRawPrivateKey", "(", "privateKeyByte", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"\"", ",", "\"\"", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "agentKey", ":=", "agent", ".", "AddedKey", "{", "PrivateKey", ":", "privateKey", ",", "Certificate", ":", "publicKey", ".", "(", "*", "ssh", ".", "Certificate", ")", ",", "Comment", ":", "\"\"", ",", "LifetimeSecs", ":", "0", ",", "ConfirmBeforeUse", ":", "false", ",", "}", "\n", "teleAgent", ":=", "teleagent", ".", "NewServer", "(", ")", "\n", "teleAgent", ".", "Add", "(", "agentKey", ")", "\n", "err", "=", "teleAgent", ".", "ListenUnixSocket", "(", "sockPath", ",", "uid", ",", "gid", ",", "0600", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"\"", ",", "\"\"", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "go", "teleAgent", ".", "Serve", "(", ")", "\n", "return", "teleAgent", ",", "sockDir", ",", "sockPath", ",", "nil", "\n", "}" ]
// createAgent creates a SSH agent with the passed in private key and // certificate that can be used in tests. This is useful so tests don't // clobber your system agent.
[ "createAgent", "creates", "a", "SSH", "agent", "with", "the", "passed", "in", "private", "key", "and", "certificate", "that", "can", "be", "used", "in", "tests", ".", "This", "is", "useful", "so", "tests", "don", "t", "clobber", "your", "system", "agent", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L1307-L1353
train
gravitational/teleport
lib/auth/native/native.go
SetClock
func SetClock(clock clockwork.Clock) KeygenOption { return func(k *Keygen) error { k.clock = clock return nil } }
go
func SetClock(clock clockwork.Clock) KeygenOption { return func(k *Keygen) error { k.clock = clock return nil } }
[ "func", "SetClock", "(", "clock", "clockwork", ".", "Clock", ")", "KeygenOption", "{", "return", "func", "(", "k", "*", "Keygen", ")", "error", "{", "k", ".", "clock", "=", "clock", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// SetClock sets the clock to use for key generation.
[ "SetClock", "sets", "the", "clock", "to", "use", "for", "key", "generation", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/native/native.go#L70-L75
train
gravitational/teleport
lib/auth/native/native.go
PrecomputeKeys
func PrecomputeKeys(count int) KeygenOption { return func(k *Keygen) error { k.precomputeCount = count return nil } }
go
func PrecomputeKeys(count int) KeygenOption { return func(k *Keygen) error { k.precomputeCount = count return nil } }
[ "func", "PrecomputeKeys", "(", "count", "int", ")", "KeygenOption", "{", "return", "func", "(", "k", "*", "Keygen", ")", "error", "{", "k", ".", "precomputeCount", "=", "count", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// PrecomputeKeys sets up a number of private keys to pre-compute // in background, 0 disables the process
[ "PrecomputeKeys", "sets", "up", "a", "number", "of", "private", "keys", "to", "pre", "-", "compute", "in", "background", "0", "disables", "the", "process" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/native/native.go#L79-L84
train
gravitational/teleport
lib/auth/native/native.go
New
func New(ctx context.Context, opts ...KeygenOption) (*Keygen, error) { ctx, cancel := context.WithCancel(ctx) k := &Keygen{ ctx: ctx, cancel: cancel, precomputeCount: PrecomputedNum, clock: clockwork.NewRealClock(), } for _, opt := range opts { if err := opt(k); err != nil { return nil, trace.Wrap(err) } } if k.precomputeCount > 0 { log.Debugf("SSH cert authority is going to pre-compute %v keys.", k.precomputeCount) k.keysCh = make(chan keyPair, k.precomputeCount) go k.precomputeKeys() } else { log.Debugf("SSH cert authority started with no keys pre-compute.") } return k, nil }
go
func New(ctx context.Context, opts ...KeygenOption) (*Keygen, error) { ctx, cancel := context.WithCancel(ctx) k := &Keygen{ ctx: ctx, cancel: cancel, precomputeCount: PrecomputedNum, clock: clockwork.NewRealClock(), } for _, opt := range opts { if err := opt(k); err != nil { return nil, trace.Wrap(err) } } if k.precomputeCount > 0 { log.Debugf("SSH cert authority is going to pre-compute %v keys.", k.precomputeCount) k.keysCh = make(chan keyPair, k.precomputeCount) go k.precomputeKeys() } else { log.Debugf("SSH cert authority started with no keys pre-compute.") } return k, nil }
[ "func", "New", "(", "ctx", "context", ".", "Context", ",", "opts", "...", "KeygenOption", ")", "(", "*", "Keygen", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithCancel", "(", "ctx", ")", "\n", "k", ":=", "&", "Keygen", "{", "ctx", ":", "ctx", ",", "cancel", ":", "cancel", ",", "precomputeCount", ":", "PrecomputedNum", ",", "clock", ":", "clockwork", ".", "NewRealClock", "(", ")", ",", "}", "\n", "for", "_", ",", "opt", ":=", "range", "opts", "{", "if", "err", ":=", "opt", "(", "k", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n", "if", "k", ".", "precomputeCount", ">", "0", "{", "log", ".", "Debugf", "(", "\"SSH cert authority is going to pre-compute %v keys.\"", ",", "k", ".", "precomputeCount", ")", "\n", "k", ".", "keysCh", "=", "make", "(", "chan", "keyPair", ",", "k", ".", "precomputeCount", ")", "\n", "go", "k", ".", "precomputeKeys", "(", ")", "\n", "}", "else", "{", "log", ".", "Debugf", "(", "\"SSH cert authority started with no keys pre-compute.\"", ")", "\n", "}", "\n", "return", "k", ",", "nil", "\n", "}" ]
// New returns a new key generator.
[ "New", "returns", "a", "new", "key", "generator", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/native/native.go#L87-L110
train
gravitational/teleport
lib/auth/native/native.go
GetNewKeyPairFromPool
func (k *Keygen) GetNewKeyPairFromPool() ([]byte, []byte, error) { select { case key := <-k.keysCh: return key.privPem, key.pubBytes, nil default: return GenerateKeyPair("") } }
go
func (k *Keygen) GetNewKeyPairFromPool() ([]byte, []byte, error) { select { case key := <-k.keysCh: return key.privPem, key.pubBytes, nil default: return GenerateKeyPair("") } }
[ "func", "(", "k", "*", "Keygen", ")", "GetNewKeyPairFromPool", "(", ")", "(", "[", "]", "byte", ",", "[", "]", "byte", ",", "error", ")", "{", "select", "{", "case", "key", ":=", "<-", "k", ".", "keysCh", ":", "return", "key", ".", "privPem", ",", "key", ".", "pubBytes", ",", "nil", "\n", "default", ":", "return", "GenerateKeyPair", "(", "\"\"", ")", "\n", "}", "\n", "}" ]
// GetNewKeyPairFromPool returns precomputed key pair from the pool.
[ "GetNewKeyPairFromPool", "returns", "precomputed", "key", "pair", "from", "the", "pool", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/native/native.go#L118-L125
train
gravitational/teleport
lib/auth/native/native.go
precomputeKeys
func (k *Keygen) precomputeKeys() { for { privPem, pubBytes, err := GenerateKeyPair("") if err != nil { log.Errorf("Unable to generate key pair: %v.", err) continue } key := keyPair{ privPem: privPem, pubBytes: pubBytes, } select { case <-k.ctx.Done(): log.Infof("Stopping key precomputation routine.") return case k.keysCh <- key: continue } } }
go
func (k *Keygen) precomputeKeys() { for { privPem, pubBytes, err := GenerateKeyPair("") if err != nil { log.Errorf("Unable to generate key pair: %v.", err) continue } key := keyPair{ privPem: privPem, pubBytes: pubBytes, } select { case <-k.ctx.Done(): log.Infof("Stopping key precomputation routine.") return case k.keysCh <- key: continue } } }
[ "func", "(", "k", "*", "Keygen", ")", "precomputeKeys", "(", ")", "{", "for", "{", "privPem", ",", "pubBytes", ",", "err", ":=", "GenerateKeyPair", "(", "\"\"", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"Unable to generate key pair: %v.\"", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "key", ":=", "keyPair", "{", "privPem", ":", "privPem", ",", "pubBytes", ":", "pubBytes", ",", "}", "\n", "select", "{", "case", "<-", "k", ".", "ctx", ".", "Done", "(", ")", ":", "log", ".", "Infof", "(", "\"Stopping key precomputation routine.\"", ")", "\n", "return", "\n", "case", "k", ".", "keysCh", "<-", "key", ":", "continue", "\n", "}", "\n", "}", "\n", "}" ]
// precomputeKeys continues loops forever trying to compute cache key pairs.
[ "precomputeKeys", "continues", "loops", "forever", "trying", "to", "compute", "cache", "key", "pairs", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/native/native.go#L128-L148
train
gravitational/teleport
lib/auth/native/native.go
GenerateHostCert
func (k *Keygen) GenerateHostCert(c services.HostCertParams) ([]byte, error) { if err := c.Check(); err != nil { return nil, trace.Wrap(err) } pubKey, _, _, _, err := ssh.ParseAuthorizedKey(c.PublicHostKey) if err != nil { return nil, trace.Wrap(err) } signer, err := ssh.ParsePrivateKey(c.PrivateCASigningKey) if err != nil { return nil, trace.Wrap(err) } // Build a valid list of principals from the HostID and NodeName and then // add in any additional principals passed in. principals := BuildPrincipals(c.HostID, c.NodeName, c.ClusterName, c.Roles) principals = append(principals, c.Principals...) if len(principals) == 0 { return nil, trace.BadParameter("no principals provided: %v, %v, %v", c.HostID, c.NodeName, c.Principals) } principals = utils.Deduplicate(principals) // create certificate validBefore := uint64(ssh.CertTimeInfinity) if c.TTL != 0 { b := k.clock.Now().UTC().Add(c.TTL) validBefore = uint64(b.Unix()) } cert := &ssh.Certificate{ ValidPrincipals: principals, Key: pubKey, ValidAfter: uint64(k.clock.Now().UTC().Add(-1 * time.Minute).Unix()), ValidBefore: validBefore, CertType: ssh.HostCert, } cert.Permissions.Extensions = make(map[string]string) cert.Permissions.Extensions[utils.CertExtensionRole] = c.Roles.String() cert.Permissions.Extensions[utils.CertExtensionAuthority] = string(c.ClusterName) // sign host certificate with private signing key of certificate authority if err := cert.SignCert(rand.Reader, signer); err != nil { return nil, trace.Wrap(err) } log.Debugf("Generated SSH host certificate for role %v with principals: %v.", c.Roles, principals) return ssh.MarshalAuthorizedKey(cert), nil }
go
func (k *Keygen) GenerateHostCert(c services.HostCertParams) ([]byte, error) { if err := c.Check(); err != nil { return nil, trace.Wrap(err) } pubKey, _, _, _, err := ssh.ParseAuthorizedKey(c.PublicHostKey) if err != nil { return nil, trace.Wrap(err) } signer, err := ssh.ParsePrivateKey(c.PrivateCASigningKey) if err != nil { return nil, trace.Wrap(err) } // Build a valid list of principals from the HostID and NodeName and then // add in any additional principals passed in. principals := BuildPrincipals(c.HostID, c.NodeName, c.ClusterName, c.Roles) principals = append(principals, c.Principals...) if len(principals) == 0 { return nil, trace.BadParameter("no principals provided: %v, %v, %v", c.HostID, c.NodeName, c.Principals) } principals = utils.Deduplicate(principals) // create certificate validBefore := uint64(ssh.CertTimeInfinity) if c.TTL != 0 { b := k.clock.Now().UTC().Add(c.TTL) validBefore = uint64(b.Unix()) } cert := &ssh.Certificate{ ValidPrincipals: principals, Key: pubKey, ValidAfter: uint64(k.clock.Now().UTC().Add(-1 * time.Minute).Unix()), ValidBefore: validBefore, CertType: ssh.HostCert, } cert.Permissions.Extensions = make(map[string]string) cert.Permissions.Extensions[utils.CertExtensionRole] = c.Roles.String() cert.Permissions.Extensions[utils.CertExtensionAuthority] = string(c.ClusterName) // sign host certificate with private signing key of certificate authority if err := cert.SignCert(rand.Reader, signer); err != nil { return nil, trace.Wrap(err) } log.Debugf("Generated SSH host certificate for role %v with principals: %v.", c.Roles, principals) return ssh.MarshalAuthorizedKey(cert), nil }
[ "func", "(", "k", "*", "Keygen", ")", "GenerateHostCert", "(", "c", "services", ".", "HostCertParams", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "err", ":=", "c", ".", "Check", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "pubKey", ",", "_", ",", "_", ",", "_", ",", "err", ":=", "ssh", ".", "ParseAuthorizedKey", "(", "c", ".", "PublicHostKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "signer", ",", "err", ":=", "ssh", ".", "ParsePrivateKey", "(", "c", ".", "PrivateCASigningKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "principals", ":=", "BuildPrincipals", "(", "c", ".", "HostID", ",", "c", ".", "NodeName", ",", "c", ".", "ClusterName", ",", "c", ".", "Roles", ")", "\n", "principals", "=", "append", "(", "principals", ",", "c", ".", "Principals", "...", ")", "\n", "if", "len", "(", "principals", ")", "==", "0", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"no principals provided: %v, %v, %v\"", ",", "c", ".", "HostID", ",", "c", ".", "NodeName", ",", "c", ".", "Principals", ")", "\n", "}", "\n", "principals", "=", "utils", ".", "Deduplicate", "(", "principals", ")", "\n", "validBefore", ":=", "uint64", "(", "ssh", ".", "CertTimeInfinity", ")", "\n", "if", "c", ".", "TTL", "!=", "0", "{", "b", ":=", "k", ".", "clock", ".", "Now", "(", ")", ".", "UTC", "(", ")", ".", "Add", "(", "c", ".", "TTL", ")", "\n", "validBefore", "=", "uint64", "(", "b", ".", "Unix", "(", ")", ")", "\n", "}", "\n", "cert", ":=", "&", "ssh", ".", "Certificate", "{", "ValidPrincipals", ":", "principals", ",", "Key", ":", "pubKey", ",", "ValidAfter", ":", "uint64", "(", "k", ".", "clock", ".", "Now", "(", ")", ".", "UTC", "(", ")", ".", "Add", "(", "-", "1", "*", "time", ".", "Minute", ")", ".", "Unix", "(", ")", ")", ",", "ValidBefore", ":", "validBefore", ",", "CertType", ":", "ssh", ".", "HostCert", ",", "}", "\n", "cert", ".", "Permissions", ".", "Extensions", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "cert", ".", "Permissions", ".", "Extensions", "[", "utils", ".", "CertExtensionRole", "]", "=", "c", ".", "Roles", ".", "String", "(", ")", "\n", "cert", ".", "Permissions", ".", "Extensions", "[", "utils", ".", "CertExtensionAuthority", "]", "=", "string", "(", "c", ".", "ClusterName", ")", "\n", "if", "err", ":=", "cert", ".", "SignCert", "(", "rand", ".", "Reader", ",", "signer", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "log", ".", "Debugf", "(", "\"Generated SSH host certificate for role %v with principals: %v.\"", ",", "c", ".", "Roles", ",", "principals", ")", "\n", "return", "ssh", ".", "MarshalAuthorizedKey", "(", "cert", ")", ",", "nil", "\n", "}" ]
// GenerateHostCert generates a host certificate with the passed in parameters. // The private key of the CA to sign the certificate must be provided.
[ "GenerateHostCert", "generates", "a", "host", "certificate", "with", "the", "passed", "in", "parameters", ".", "The", "private", "key", "of", "the", "CA", "to", "sign", "the", "certificate", "must", "be", "provided", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/native/native.go#L181-L231
train
gravitational/teleport
lib/auth/native/native.go
GenerateUserCert
func (k *Keygen) GenerateUserCert(c services.UserCertParams) ([]byte, error) { if c.TTL < defaults.MinCertDuration { return nil, trace.BadParameter("wrong certificate TTL") } if len(c.AllowedLogins) == 0 { return nil, trace.BadParameter("allowedLogins: need allowed OS logins") } pubKey, _, _, _, err := ssh.ParseAuthorizedKey(c.PublicUserKey) if err != nil { return nil, trace.Wrap(err) } validBefore := uint64(ssh.CertTimeInfinity) if c.TTL != 0 { b := k.clock.Now().UTC().Add(c.TTL) validBefore = uint64(b.Unix()) log.Debugf("generated user key for %v with expiry on (%v) %v", c.AllowedLogins, validBefore, b) } cert := &ssh.Certificate{ // we have to use key id to identify teleport user KeyId: c.Username, ValidPrincipals: c.AllowedLogins, Key: pubKey, ValidAfter: uint64(k.clock.Now().UTC().Add(-1 * time.Minute).Unix()), ValidBefore: validBefore, CertType: ssh.UserCert, } cert.Permissions.Extensions = map[string]string{ teleport.CertExtensionPermitPTY: "", teleport.CertExtensionPermitPortForwarding: "", } if c.PermitAgentForwarding { cert.Permissions.Extensions[teleport.CertExtensionPermitAgentForwarding] = "" } if !c.PermitPortForwarding { delete(cert.Permissions.Extensions, teleport.CertExtensionPermitPortForwarding) } if len(c.Roles) != 0 { // only add roles to the certificate extensions if the standard format was // requested. we allow the option to omit this to support older versions of // OpenSSH due to a bug in <= OpenSSH 7.1 // https://bugzilla.mindrot.org/show_bug.cgi?id=2387 if c.CertificateFormat == teleport.CertificateFormatStandard { roles, err := services.MarshalCertRoles(c.Roles) if err != nil { return nil, trace.Wrap(err) } cert.Permissions.Extensions[teleport.CertExtensionTeleportRoles] = roles } } signer, err := ssh.ParsePrivateKey(c.PrivateCASigningKey) if err != nil { return nil, trace.Wrap(err) } if err := cert.SignCert(rand.Reader, signer); err != nil { return nil, trace.Wrap(err) } return ssh.MarshalAuthorizedKey(cert), nil }
go
func (k *Keygen) GenerateUserCert(c services.UserCertParams) ([]byte, error) { if c.TTL < defaults.MinCertDuration { return nil, trace.BadParameter("wrong certificate TTL") } if len(c.AllowedLogins) == 0 { return nil, trace.BadParameter("allowedLogins: need allowed OS logins") } pubKey, _, _, _, err := ssh.ParseAuthorizedKey(c.PublicUserKey) if err != nil { return nil, trace.Wrap(err) } validBefore := uint64(ssh.CertTimeInfinity) if c.TTL != 0 { b := k.clock.Now().UTC().Add(c.TTL) validBefore = uint64(b.Unix()) log.Debugf("generated user key for %v with expiry on (%v) %v", c.AllowedLogins, validBefore, b) } cert := &ssh.Certificate{ // we have to use key id to identify teleport user KeyId: c.Username, ValidPrincipals: c.AllowedLogins, Key: pubKey, ValidAfter: uint64(k.clock.Now().UTC().Add(-1 * time.Minute).Unix()), ValidBefore: validBefore, CertType: ssh.UserCert, } cert.Permissions.Extensions = map[string]string{ teleport.CertExtensionPermitPTY: "", teleport.CertExtensionPermitPortForwarding: "", } if c.PermitAgentForwarding { cert.Permissions.Extensions[teleport.CertExtensionPermitAgentForwarding] = "" } if !c.PermitPortForwarding { delete(cert.Permissions.Extensions, teleport.CertExtensionPermitPortForwarding) } if len(c.Roles) != 0 { // only add roles to the certificate extensions if the standard format was // requested. we allow the option to omit this to support older versions of // OpenSSH due to a bug in <= OpenSSH 7.1 // https://bugzilla.mindrot.org/show_bug.cgi?id=2387 if c.CertificateFormat == teleport.CertificateFormatStandard { roles, err := services.MarshalCertRoles(c.Roles) if err != nil { return nil, trace.Wrap(err) } cert.Permissions.Extensions[teleport.CertExtensionTeleportRoles] = roles } } signer, err := ssh.ParsePrivateKey(c.PrivateCASigningKey) if err != nil { return nil, trace.Wrap(err) } if err := cert.SignCert(rand.Reader, signer); err != nil { return nil, trace.Wrap(err) } return ssh.MarshalAuthorizedKey(cert), nil }
[ "func", "(", "k", "*", "Keygen", ")", "GenerateUserCert", "(", "c", "services", ".", "UserCertParams", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "c", ".", "TTL", "<", "defaults", ".", "MinCertDuration", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"wrong certificate TTL\"", ")", "\n", "}", "\n", "if", "len", "(", "c", ".", "AllowedLogins", ")", "==", "0", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"allowedLogins: need allowed OS logins\"", ")", "\n", "}", "\n", "pubKey", ",", "_", ",", "_", ",", "_", ",", "err", ":=", "ssh", ".", "ParseAuthorizedKey", "(", "c", ".", "PublicUserKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "validBefore", ":=", "uint64", "(", "ssh", ".", "CertTimeInfinity", ")", "\n", "if", "c", ".", "TTL", "!=", "0", "{", "b", ":=", "k", ".", "clock", ".", "Now", "(", ")", ".", "UTC", "(", ")", ".", "Add", "(", "c", ".", "TTL", ")", "\n", "validBefore", "=", "uint64", "(", "b", ".", "Unix", "(", ")", ")", "\n", "log", ".", "Debugf", "(", "\"generated user key for %v with expiry on (%v) %v\"", ",", "c", ".", "AllowedLogins", ",", "validBefore", ",", "b", ")", "\n", "}", "\n", "cert", ":=", "&", "ssh", ".", "Certificate", "{", "KeyId", ":", "c", ".", "Username", ",", "ValidPrincipals", ":", "c", ".", "AllowedLogins", ",", "Key", ":", "pubKey", ",", "ValidAfter", ":", "uint64", "(", "k", ".", "clock", ".", "Now", "(", ")", ".", "UTC", "(", ")", ".", "Add", "(", "-", "1", "*", "time", ".", "Minute", ")", ".", "Unix", "(", ")", ")", ",", "ValidBefore", ":", "validBefore", ",", "CertType", ":", "ssh", ".", "UserCert", ",", "}", "\n", "cert", ".", "Permissions", ".", "Extensions", "=", "map", "[", "string", "]", "string", "{", "teleport", ".", "CertExtensionPermitPTY", ":", "\"\"", ",", "teleport", ".", "CertExtensionPermitPortForwarding", ":", "\"\"", ",", "}", "\n", "if", "c", ".", "PermitAgentForwarding", "{", "cert", ".", "Permissions", ".", "Extensions", "[", "teleport", ".", "CertExtensionPermitAgentForwarding", "]", "=", "\"\"", "\n", "}", "\n", "if", "!", "c", ".", "PermitPortForwarding", "{", "delete", "(", "cert", ".", "Permissions", ".", "Extensions", ",", "teleport", ".", "CertExtensionPermitPortForwarding", ")", "\n", "}", "\n", "if", "len", "(", "c", ".", "Roles", ")", "!=", "0", "{", "if", "c", ".", "CertificateFormat", "==", "teleport", ".", "CertificateFormatStandard", "{", "roles", ",", "err", ":=", "services", ".", "MarshalCertRoles", "(", "c", ".", "Roles", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "cert", ".", "Permissions", ".", "Extensions", "[", "teleport", ".", "CertExtensionTeleportRoles", "]", "=", "roles", "\n", "}", "\n", "}", "\n", "signer", ",", "err", ":=", "ssh", ".", "ParsePrivateKey", "(", "c", ".", "PrivateCASigningKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "err", ":=", "cert", ".", "SignCert", "(", "rand", ".", "Reader", ",", "signer", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "ssh", ".", "MarshalAuthorizedKey", "(", "cert", ")", ",", "nil", "\n", "}" ]
// GenerateUserCert generates a host certificate with the passed in parameters. // The private key of the CA to sign the certificate must be provided.
[ "GenerateUserCert", "generates", "a", "host", "certificate", "with", "the", "passed", "in", "parameters", ".", "The", "private", "key", "of", "the", "CA", "to", "sign", "the", "certificate", "must", "be", "provided", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/native/native.go#L235-L292
train
gravitational/teleport
lib/events/s3sessions/s3handler.go
NewHandler
func NewHandler(cfg Config) (*Handler, error) { if err := cfg.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } h := &Handler{ Entry: log.WithFields(log.Fields{ trace.Component: teleport.Component(teleport.SchemeS3), }), Config: cfg, uploader: s3manager.NewUploader(cfg.Session), downloader: s3manager.NewDownloader(cfg.Session), client: s3.New(cfg.Session), } start := time.Now() h.Infof("Setting up bucket %q, sessions path %q in region %q.", h.Bucket, h.Path, h.Region) if err := h.ensureBucket(); err != nil { return nil, trace.Wrap(err) } h.WithFields(log.Fields{"duration": time.Now().Sub(start)}).Infof("Setup bucket %q completed.", h.Bucket) return h, nil }
go
func NewHandler(cfg Config) (*Handler, error) { if err := cfg.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } h := &Handler{ Entry: log.WithFields(log.Fields{ trace.Component: teleport.Component(teleport.SchemeS3), }), Config: cfg, uploader: s3manager.NewUploader(cfg.Session), downloader: s3manager.NewDownloader(cfg.Session), client: s3.New(cfg.Session), } start := time.Now() h.Infof("Setting up bucket %q, sessions path %q in region %q.", h.Bucket, h.Path, h.Region) if err := h.ensureBucket(); err != nil { return nil, trace.Wrap(err) } h.WithFields(log.Fields{"duration": time.Now().Sub(start)}).Infof("Setup bucket %q completed.", h.Bucket) return h, nil }
[ "func", "NewHandler", "(", "cfg", "Config", ")", "(", "*", "Handler", ",", "error", ")", "{", "if", "err", ":=", "cfg", ".", "CheckAndSetDefaults", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "h", ":=", "&", "Handler", "{", "Entry", ":", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "trace", ".", "Component", ":", "teleport", ".", "Component", "(", "teleport", ".", "SchemeS3", ")", ",", "}", ")", ",", "Config", ":", "cfg", ",", "uploader", ":", "s3manager", ".", "NewUploader", "(", "cfg", ".", "Session", ")", ",", "downloader", ":", "s3manager", ".", "NewDownloader", "(", "cfg", ".", "Session", ")", ",", "client", ":", "s3", ".", "New", "(", "cfg", ".", "Session", ")", ",", "}", "\n", "start", ":=", "time", ".", "Now", "(", ")", "\n", "h", ".", "Infof", "(", "\"Setting up bucket %q, sessions path %q in region %q.\"", ",", "h", ".", "Bucket", ",", "h", ".", "Path", ",", "h", ".", "Region", ")", "\n", "if", "err", ":=", "h", ".", "ensureBucket", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "h", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"duration\"", ":", "time", ".", "Now", "(", ")", ".", "Sub", "(", "start", ")", "}", ")", ".", "Infof", "(", "\"Setup bucket %q completed.\"", ",", "h", ".", "Bucket", ")", "\n", "return", "h", ",", "nil", "\n", "}" ]
// NewHandler returns new S3 uploader
[ "NewHandler", "returns", "new", "S3", "uploader" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/s3sessions/s3handler.go#L76-L97
train
gravitational/teleport
lib/events/s3sessions/s3handler.go
Upload
func (l *Handler) Upload(ctx context.Context, sessionID session.ID, reader io.Reader) (string, error) { path := l.path(sessionID) _, err := l.uploader.UploadWithContext(ctx, &s3manager.UploadInput{ Bucket: aws.String(l.Bucket), Key: aws.String(path), Body: reader, ServerSideEncryption: aws.String(s3.ServerSideEncryptionAwsKms), }) if err != nil { return "", ConvertS3Error(err) } return fmt.Sprintf("%v://%v/%v", teleport.SchemeS3, l.Bucket, path), nil }
go
func (l *Handler) Upload(ctx context.Context, sessionID session.ID, reader io.Reader) (string, error) { path := l.path(sessionID) _, err := l.uploader.UploadWithContext(ctx, &s3manager.UploadInput{ Bucket: aws.String(l.Bucket), Key: aws.String(path), Body: reader, ServerSideEncryption: aws.String(s3.ServerSideEncryptionAwsKms), }) if err != nil { return "", ConvertS3Error(err) } return fmt.Sprintf("%v://%v/%v", teleport.SchemeS3, l.Bucket, path), nil }
[ "func", "(", "l", "*", "Handler", ")", "Upload", "(", "ctx", "context", ".", "Context", ",", "sessionID", "session", ".", "ID", ",", "reader", "io", ".", "Reader", ")", "(", "string", ",", "error", ")", "{", "path", ":=", "l", ".", "path", "(", "sessionID", ")", "\n", "_", ",", "err", ":=", "l", ".", "uploader", ".", "UploadWithContext", "(", "ctx", ",", "&", "s3manager", ".", "UploadInput", "{", "Bucket", ":", "aws", ".", "String", "(", "l", ".", "Bucket", ")", ",", "Key", ":", "aws", ".", "String", "(", "path", ")", ",", "Body", ":", "reader", ",", "ServerSideEncryption", ":", "aws", ".", "String", "(", "s3", ".", "ServerSideEncryptionAwsKms", ")", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "ConvertS3Error", "(", "err", ")", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"%v://%v/%v\"", ",", "teleport", ".", "SchemeS3", ",", "l", ".", "Bucket", ",", "path", ")", ",", "nil", "\n", "}" ]
// Upload uploads object to S3 bucket, reads the contents of the object from reader // and returns the target S3 bucket path in case of successful upload.
[ "Upload", "uploads", "object", "to", "S3", "bucket", "reads", "the", "contents", "of", "the", "object", "from", "reader", "and", "returns", "the", "target", "S3", "bucket", "path", "in", "case", "of", "successful", "upload", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/s3sessions/s3handler.go#L117-L129
train
gravitational/teleport
lib/events/s3sessions/s3handler.go
Download
func (l *Handler) Download(ctx context.Context, sessionID session.ID, writer io.WriterAt) error { written, err := l.downloader.DownloadWithContext(ctx, writer, &s3.GetObjectInput{ Bucket: aws.String(l.Bucket), Key: aws.String(l.path(sessionID)), }) if err != nil { return ConvertS3Error(err) } if written == 0 { return trace.NotFound("recording for %v is not found", sessionID) } return nil }
go
func (l *Handler) Download(ctx context.Context, sessionID session.ID, writer io.WriterAt) error { written, err := l.downloader.DownloadWithContext(ctx, writer, &s3.GetObjectInput{ Bucket: aws.String(l.Bucket), Key: aws.String(l.path(sessionID)), }) if err != nil { return ConvertS3Error(err) } if written == 0 { return trace.NotFound("recording for %v is not found", sessionID) } return nil }
[ "func", "(", "l", "*", "Handler", ")", "Download", "(", "ctx", "context", ".", "Context", ",", "sessionID", "session", ".", "ID", ",", "writer", "io", ".", "WriterAt", ")", "error", "{", "written", ",", "err", ":=", "l", ".", "downloader", ".", "DownloadWithContext", "(", "ctx", ",", "writer", ",", "&", "s3", ".", "GetObjectInput", "{", "Bucket", ":", "aws", ".", "String", "(", "l", ".", "Bucket", ")", ",", "Key", ":", "aws", ".", "String", "(", "l", ".", "path", "(", "sessionID", ")", ")", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ConvertS3Error", "(", "err", ")", "\n", "}", "\n", "if", "written", "==", "0", "{", "return", "trace", ".", "NotFound", "(", "\"recording for %v is not found\"", ",", "sessionID", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Download downloads recorded session from S3 bucket and writes the results into writer // return trace.NotFound error is object is not found
[ "Download", "downloads", "recorded", "session", "from", "S3", "bucket", "and", "writes", "the", "results", "into", "writer", "return", "trace", ".", "NotFound", "error", "is", "object", "is", "not", "found" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/s3sessions/s3handler.go#L133-L145
train
gravitational/teleport
lib/events/s3sessions/s3handler.go
deleteBucket
func (h *Handler) deleteBucket() error { // first, list and delete all the objects in the bucket out, err := h.client.ListObjectVersions(&s3.ListObjectVersionsInput{ Bucket: aws.String(h.Bucket), }) if err != nil { return ConvertS3Error(err) } for _, ver := range out.Versions { _, err := h.client.DeleteObject(&s3.DeleteObjectInput{ Bucket: aws.String(h.Bucket), Key: ver.Key, VersionId: ver.VersionId, }) if err != nil { return ConvertS3Error(err) } } _, err = h.client.DeleteBucket(&s3.DeleteBucketInput{ Bucket: aws.String(h.Bucket), }) return ConvertS3Error(err) }
go
func (h *Handler) deleteBucket() error { // first, list and delete all the objects in the bucket out, err := h.client.ListObjectVersions(&s3.ListObjectVersionsInput{ Bucket: aws.String(h.Bucket), }) if err != nil { return ConvertS3Error(err) } for _, ver := range out.Versions { _, err := h.client.DeleteObject(&s3.DeleteObjectInput{ Bucket: aws.String(h.Bucket), Key: ver.Key, VersionId: ver.VersionId, }) if err != nil { return ConvertS3Error(err) } } _, err = h.client.DeleteBucket(&s3.DeleteBucketInput{ Bucket: aws.String(h.Bucket), }) return ConvertS3Error(err) }
[ "func", "(", "h", "*", "Handler", ")", "deleteBucket", "(", ")", "error", "{", "out", ",", "err", ":=", "h", ".", "client", ".", "ListObjectVersions", "(", "&", "s3", ".", "ListObjectVersionsInput", "{", "Bucket", ":", "aws", ".", "String", "(", "h", ".", "Bucket", ")", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ConvertS3Error", "(", "err", ")", "\n", "}", "\n", "for", "_", ",", "ver", ":=", "range", "out", ".", "Versions", "{", "_", ",", "err", ":=", "h", ".", "client", ".", "DeleteObject", "(", "&", "s3", ".", "DeleteObjectInput", "{", "Bucket", ":", "aws", ".", "String", "(", "h", ".", "Bucket", ")", ",", "Key", ":", "ver", ".", "Key", ",", "VersionId", ":", "ver", ".", "VersionId", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ConvertS3Error", "(", "err", ")", "\n", "}", "\n", "}", "\n", "_", ",", "err", "=", "h", ".", "client", ".", "DeleteBucket", "(", "&", "s3", ".", "DeleteBucketInput", "{", "Bucket", ":", "aws", ".", "String", "(", "h", ".", "Bucket", ")", ",", "}", ")", "\n", "return", "ConvertS3Error", "(", "err", ")", "\n", "}" ]
// delete bucket deletes bucket and all it's contents and is used in tests
[ "delete", "bucket", "deletes", "bucket", "and", "all", "it", "s", "contents", "and", "is", "used", "in", "tests" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/s3sessions/s3handler.go#L148-L170
train
gravitational/teleport
lib/events/s3sessions/s3handler.go
ensureBucket
func (h *Handler) ensureBucket() error { _, err := h.client.HeadBucket(&s3.HeadBucketInput{ Bucket: aws.String(h.Bucket), }) err = ConvertS3Error(err) // assumes that bucket is administered by other entity if err == nil { return nil } if !trace.IsNotFound(err) { return trace.Wrap(err) } input := &s3.CreateBucketInput{ Bucket: aws.String(h.Bucket), ACL: aws.String("private"), } _, err = h.client.CreateBucket(input) err = ConvertS3Error(err, "bucket %v already exists", aws.String(h.Bucket)) if err != nil { if !trace.IsAlreadyExists(err) { return trace.Wrap(err) } // if this client has not created the bucket, don't reconfigure it return nil } // turn on versioning ver := &s3.PutBucketVersioningInput{ Bucket: aws.String(h.Bucket), VersioningConfiguration: &s3.VersioningConfiguration{ Status: aws.String("Enabled"), }, } _, err = h.client.PutBucketVersioning(ver) err = ConvertS3Error(err, "failed to set versioning state for bucket %q", h.Bucket) if err != nil { return trace.Wrap(err) } _, err = h.client.PutBucketEncryption(&s3.PutBucketEncryptionInput{ Bucket: aws.String(h.Bucket), ServerSideEncryptionConfiguration: &s3.ServerSideEncryptionConfiguration{ Rules: []*s3.ServerSideEncryptionRule{&s3.ServerSideEncryptionRule{ ApplyServerSideEncryptionByDefault: &s3.ServerSideEncryptionByDefault{ SSEAlgorithm: aws.String(s3.ServerSideEncryptionAwsKms), }, }}, }, }) err = ConvertS3Error(err, "failed to set versioning state for bucket %q", h.Bucket) if err != nil { return trace.Wrap(err) } return nil }
go
func (h *Handler) ensureBucket() error { _, err := h.client.HeadBucket(&s3.HeadBucketInput{ Bucket: aws.String(h.Bucket), }) err = ConvertS3Error(err) // assumes that bucket is administered by other entity if err == nil { return nil } if !trace.IsNotFound(err) { return trace.Wrap(err) } input := &s3.CreateBucketInput{ Bucket: aws.String(h.Bucket), ACL: aws.String("private"), } _, err = h.client.CreateBucket(input) err = ConvertS3Error(err, "bucket %v already exists", aws.String(h.Bucket)) if err != nil { if !trace.IsAlreadyExists(err) { return trace.Wrap(err) } // if this client has not created the bucket, don't reconfigure it return nil } // turn on versioning ver := &s3.PutBucketVersioningInput{ Bucket: aws.String(h.Bucket), VersioningConfiguration: &s3.VersioningConfiguration{ Status: aws.String("Enabled"), }, } _, err = h.client.PutBucketVersioning(ver) err = ConvertS3Error(err, "failed to set versioning state for bucket %q", h.Bucket) if err != nil { return trace.Wrap(err) } _, err = h.client.PutBucketEncryption(&s3.PutBucketEncryptionInput{ Bucket: aws.String(h.Bucket), ServerSideEncryptionConfiguration: &s3.ServerSideEncryptionConfiguration{ Rules: []*s3.ServerSideEncryptionRule{&s3.ServerSideEncryptionRule{ ApplyServerSideEncryptionByDefault: &s3.ServerSideEncryptionByDefault{ SSEAlgorithm: aws.String(s3.ServerSideEncryptionAwsKms), }, }}, }, }) err = ConvertS3Error(err, "failed to set versioning state for bucket %q", h.Bucket) if err != nil { return trace.Wrap(err) } return nil }
[ "func", "(", "h", "*", "Handler", ")", "ensureBucket", "(", ")", "error", "{", "_", ",", "err", ":=", "h", ".", "client", ".", "HeadBucket", "(", "&", "s3", ".", "HeadBucketInput", "{", "Bucket", ":", "aws", ".", "String", "(", "h", ".", "Bucket", ")", ",", "}", ")", "\n", "err", "=", "ConvertS3Error", "(", "err", ")", "\n", "if", "err", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "if", "!", "trace", ".", "IsNotFound", "(", "err", ")", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "input", ":=", "&", "s3", ".", "CreateBucketInput", "{", "Bucket", ":", "aws", ".", "String", "(", "h", ".", "Bucket", ")", ",", "ACL", ":", "aws", ".", "String", "(", "\"private\"", ")", ",", "}", "\n", "_", ",", "err", "=", "h", ".", "client", ".", "CreateBucket", "(", "input", ")", "\n", "err", "=", "ConvertS3Error", "(", "err", ",", "\"bucket %v already exists\"", ",", "aws", ".", "String", "(", "h", ".", "Bucket", ")", ")", "\n", "if", "err", "!=", "nil", "{", "if", "!", "trace", ".", "IsAlreadyExists", "(", "err", ")", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "ver", ":=", "&", "s3", ".", "PutBucketVersioningInput", "{", "Bucket", ":", "aws", ".", "String", "(", "h", ".", "Bucket", ")", ",", "VersioningConfiguration", ":", "&", "s3", ".", "VersioningConfiguration", "{", "Status", ":", "aws", ".", "String", "(", "\"Enabled\"", ")", ",", "}", ",", "}", "\n", "_", ",", "err", "=", "h", ".", "client", ".", "PutBucketVersioning", "(", "ver", ")", "\n", "err", "=", "ConvertS3Error", "(", "err", ",", "\"failed to set versioning state for bucket %q\"", ",", "h", ".", "Bucket", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "_", ",", "err", "=", "h", ".", "client", ".", "PutBucketEncryption", "(", "&", "s3", ".", "PutBucketEncryptionInput", "{", "Bucket", ":", "aws", ".", "String", "(", "h", ".", "Bucket", ")", ",", "ServerSideEncryptionConfiguration", ":", "&", "s3", ".", "ServerSideEncryptionConfiguration", "{", "Rules", ":", "[", "]", "*", "s3", ".", "ServerSideEncryptionRule", "{", "&", "s3", ".", "ServerSideEncryptionRule", "{", "ApplyServerSideEncryptionByDefault", ":", "&", "s3", ".", "ServerSideEncryptionByDefault", "{", "SSEAlgorithm", ":", "aws", ".", "String", "(", "s3", ".", "ServerSideEncryptionAwsKms", ")", ",", "}", ",", "}", "}", ",", "}", ",", "}", ")", "\n", "err", "=", "ConvertS3Error", "(", "err", ",", "\"failed to set versioning state for bucket %q\"", ",", "h", ".", "Bucket", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ensureBucket makes sure bucket exists, and if it does not, creates it
[ "ensureBucket", "makes", "sure", "bucket", "exists", "and", "if", "it", "does", "not", "creates", "it" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/s3sessions/s3handler.go#L180-L233
train
gravitational/teleport
lib/events/s3sessions/s3handler.go
ConvertS3Error
func ConvertS3Error(err error, args ...interface{}) error { if err == nil { return nil } if aerr, ok := err.(awserr.Error); ok { switch aerr.Code() { case s3.ErrCodeNoSuchKey, s3.ErrCodeNoSuchBucket, s3.ErrCodeNoSuchUpload, "NotFound": return trace.NotFound(aerr.Error(), args...) case s3.ErrCodeBucketAlreadyExists, s3.ErrCodeBucketAlreadyOwnedByYou: return trace.AlreadyExists(aerr.Error(), args...) default: return trace.BadParameter(aerr.Error(), args...) } } return err }
go
func ConvertS3Error(err error, args ...interface{}) error { if err == nil { return nil } if aerr, ok := err.(awserr.Error); ok { switch aerr.Code() { case s3.ErrCodeNoSuchKey, s3.ErrCodeNoSuchBucket, s3.ErrCodeNoSuchUpload, "NotFound": return trace.NotFound(aerr.Error(), args...) case s3.ErrCodeBucketAlreadyExists, s3.ErrCodeBucketAlreadyOwnedByYou: return trace.AlreadyExists(aerr.Error(), args...) default: return trace.BadParameter(aerr.Error(), args...) } } return err }
[ "func", "ConvertS3Error", "(", "err", "error", ",", "args", "...", "interface", "{", "}", ")", "error", "{", "if", "err", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "if", "aerr", ",", "ok", ":=", "err", ".", "(", "awserr", ".", "Error", ")", ";", "ok", "{", "switch", "aerr", ".", "Code", "(", ")", "{", "case", "s3", ".", "ErrCodeNoSuchKey", ",", "s3", ".", "ErrCodeNoSuchBucket", ",", "s3", ".", "ErrCodeNoSuchUpload", ",", "\"NotFound\"", ":", "return", "trace", ".", "NotFound", "(", "aerr", ".", "Error", "(", ")", ",", "args", "...", ")", "\n", "case", "s3", ".", "ErrCodeBucketAlreadyExists", ",", "s3", ".", "ErrCodeBucketAlreadyOwnedByYou", ":", "return", "trace", ".", "AlreadyExists", "(", "aerr", ".", "Error", "(", ")", ",", "args", "...", ")", "\n", "default", ":", "return", "trace", ".", "BadParameter", "(", "aerr", ".", "Error", "(", ")", ",", "args", "...", ")", "\n", "}", "\n", "}", "\n", "return", "err", "\n", "}" ]
// ConvertS3Error wraps S3 error and returns trace equivalent
[ "ConvertS3Error", "wraps", "S3", "error", "and", "returns", "trace", "equivalent" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/s3sessions/s3handler.go#L236-L251
train
gravitational/teleport
roles.go
NewRoles
func NewRoles(in []string) (Roles, error) { var roles Roles for _, val := range in { role := Role(val) if err := role.Check(); err != nil { return nil, trace.Wrap(err) } roles = append(roles, role) } return roles, nil }
go
func NewRoles(in []string) (Roles, error) { var roles Roles for _, val := range in { role := Role(val) if err := role.Check(); err != nil { return nil, trace.Wrap(err) } roles = append(roles, role) } return roles, nil }
[ "func", "NewRoles", "(", "in", "[", "]", "string", ")", "(", "Roles", ",", "error", ")", "{", "var", "roles", "Roles", "\n", "for", "_", ",", "val", ":=", "range", "in", "{", "role", ":=", "Role", "(", "val", ")", "\n", "if", "err", ":=", "role", ".", "Check", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "roles", "=", "append", "(", "roles", ",", "role", ")", "\n", "}", "\n", "return", "roles", ",", "nil", "\n", "}" ]
// NewRoles return a list of roles from slice of strings
[ "NewRoles", "return", "a", "list", "of", "roles", "from", "slice", "of", "strings" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/roles.go#L61-L71
train
gravitational/teleport
roles.go
ParseRoles
func ParseRoles(str string) (roles Roles, err error) { for _, s := range strings.Split(str, ",") { r := Role(strings.Title(strings.ToLower(strings.TrimSpace(s)))) if err = r.Check(); err != nil { return nil, trace.Wrap(err) } roles = append(roles, r) } return roles, nil }
go
func ParseRoles(str string) (roles Roles, err error) { for _, s := range strings.Split(str, ",") { r := Role(strings.Title(strings.ToLower(strings.TrimSpace(s)))) if err = r.Check(); err != nil { return nil, trace.Wrap(err) } roles = append(roles, r) } return roles, nil }
[ "func", "ParseRoles", "(", "str", "string", ")", "(", "roles", "Roles", ",", "err", "error", ")", "{", "for", "_", ",", "s", ":=", "range", "strings", ".", "Split", "(", "str", ",", "\",\"", ")", "{", "r", ":=", "Role", "(", "strings", ".", "Title", "(", "strings", ".", "ToLower", "(", "strings", ".", "TrimSpace", "(", "s", ")", ")", ")", ")", "\n", "if", "err", "=", "r", ".", "Check", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "roles", "=", "append", "(", "roles", ",", "r", ")", "\n", "}", "\n", "return", "roles", ",", "nil", "\n", "}" ]
// ParseRoles takes a comma-separated list of roles and returns a slice // of roles, or an error if parsing failed
[ "ParseRoles", "takes", "a", "comma", "-", "separated", "list", "of", "roles", "and", "returns", "a", "slice", "of", "roles", "or", "an", "error", "if", "parsing", "failed" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/roles.go#L75-L84
train
gravitational/teleport
roles.go
Include
func (roles Roles) Include(role Role) bool { for _, r := range roles { if r == role { return true } } return false }
go
func (roles Roles) Include(role Role) bool { for _, r := range roles { if r == role { return true } } return false }
[ "func", "(", "roles", "Roles", ")", "Include", "(", "role", "Role", ")", "bool", "{", "for", "_", ",", "r", ":=", "range", "roles", "{", "if", "r", "==", "role", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Includes returns 'true' if a given list of roles includes a given role
[ "Includes", "returns", "true", "if", "a", "given", "list", "of", "roles", "includes", "a", "given", "role" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/roles.go#L87-L94
train
gravitational/teleport
roles.go
StringSlice
func (roles Roles) StringSlice() []string { s := make([]string, 0) for _, r := range roles { s = append(s, r.String()) } return s }
go
func (roles Roles) StringSlice() []string { s := make([]string, 0) for _, r := range roles { s = append(s, r.String()) } return s }
[ "func", "(", "roles", "Roles", ")", "StringSlice", "(", ")", "[", "]", "string", "{", "s", ":=", "make", "(", "[", "]", "string", ",", "0", ")", "\n", "for", "_", ",", "r", ":=", "range", "roles", "{", "s", "=", "append", "(", "s", ",", "r", ".", "String", "(", ")", ")", "\n", "}", "\n", "return", "s", "\n", "}" ]
// Slice returns roles as string slice
[ "Slice", "returns", "roles", "as", "string", "slice" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/roles.go#L97-L103
train
gravitational/teleport
roles.go
Equals
func (roles Roles) Equals(other Roles) bool { if len(roles) != len(other) { return false } for _, r := range roles { if !other.Include(r) { return false } } return true }
go
func (roles Roles) Equals(other Roles) bool { if len(roles) != len(other) { return false } for _, r := range roles { if !other.Include(r) { return false } } return true }
[ "func", "(", "roles", "Roles", ")", "Equals", "(", "other", "Roles", ")", "bool", "{", "if", "len", "(", "roles", ")", "!=", "len", "(", "other", ")", "{", "return", "false", "\n", "}", "\n", "for", "_", ",", "r", ":=", "range", "roles", "{", "if", "!", "other", ".", "Include", "(", "r", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// Equals compares two sets of roles
[ "Equals", "compares", "two", "sets", "of", "roles" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/roles.go#L106-L116
train
gravitational/teleport
roles.go
Set
func (r *Role) Set(v string) error { val := Role(strings.Title(v)) if err := val.Check(); err != nil { return trace.Wrap(err) } *r = val return nil }
go
func (r *Role) Set(v string) error { val := Role(strings.Title(v)) if err := val.Check(); err != nil { return trace.Wrap(err) } *r = val return nil }
[ "func", "(", "r", "*", "Role", ")", "Set", "(", "v", "string", ")", "error", "{", "val", ":=", "Role", "(", "strings", ".", "Title", "(", "v", ")", ")", "\n", "if", "err", ":=", "val", ".", "Check", "(", ")", ";", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "*", "r", "=", "val", "\n", "return", "nil", "\n", "}" ]
// Set sets the value of the role from string, used to integrate with CLI tools
[ "Set", "sets", "the", "value", "of", "the", "role", "from", "string", "used", "to", "integrate", "with", "CLI", "tools" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/roles.go#L134-L141
train
gravitational/teleport
roles.go
String
func (r *Role) String() string { switch string(*r) { case string(RoleSignup): return "User signup" case string(RoleTrustedCluster), string(LegacyClusterTokenType): return "trusted_cluster" default: return fmt.Sprintf("%v", string(*r)) } }
go
func (r *Role) String() string { switch string(*r) { case string(RoleSignup): return "User signup" case string(RoleTrustedCluster), string(LegacyClusterTokenType): return "trusted_cluster" default: return fmt.Sprintf("%v", string(*r)) } }
[ "func", "(", "r", "*", "Role", ")", "String", "(", ")", "string", "{", "switch", "string", "(", "*", "r", ")", "{", "case", "string", "(", "RoleSignup", ")", ":", "return", "\"User signup\"", "\n", "case", "string", "(", "RoleTrustedCluster", ")", ",", "string", "(", "LegacyClusterTokenType", ")", ":", "return", "\"trusted_cluster\"", "\n", "default", ":", "return", "fmt", ".", "Sprintf", "(", "\"%v\"", ",", "string", "(", "*", "r", ")", ")", "\n", "}", "\n", "}" ]
// String returns debug-friendly representation of this role.
[ "String", "returns", "debug", "-", "friendly", "representation", "of", "this", "role", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/roles.go#L144-L153
train
gravitational/teleport
roles.go
Check
func (r *Role) Check() error { switch *r { case RoleAuth, RoleWeb, RoleNode, RoleAdmin, RoleProvisionToken, RoleTrustedCluster, LegacyClusterTokenType, RoleSignup, RoleProxy, RoleNop: return nil } return trace.BadParameter("role %v is not registered", *r) }
go
func (r *Role) Check() error { switch *r { case RoleAuth, RoleWeb, RoleNode, RoleAdmin, RoleProvisionToken, RoleTrustedCluster, LegacyClusterTokenType, RoleSignup, RoleProxy, RoleNop: return nil } return trace.BadParameter("role %v is not registered", *r) }
[ "func", "(", "r", "*", "Role", ")", "Check", "(", ")", "error", "{", "switch", "*", "r", "{", "case", "RoleAuth", ",", "RoleWeb", ",", "RoleNode", ",", "RoleAdmin", ",", "RoleProvisionToken", ",", "RoleTrustedCluster", ",", "LegacyClusterTokenType", ",", "RoleSignup", ",", "RoleProxy", ",", "RoleNop", ":", "return", "nil", "\n", "}", "\n", "return", "trace", ".", "BadParameter", "(", "\"role %v is not registered\"", ",", "*", "r", ")", "\n", "}" ]
// Check checks if this a a valid role value, returns nil // if it's ok, false otherwise
[ "Check", "checks", "if", "this", "a", "a", "valid", "role", "value", "returns", "nil", "if", "it", "s", "ok", "false", "otherwise" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/roles.go#L157-L166
train
gravitational/teleport
lib/backend/lite/lite.go
CheckAndSetDefaults
func (cfg *Config) CheckAndSetDefaults() error { if cfg.Path == "" && !cfg.Memory { return trace.BadParameter("specify directory path to the database using 'path' parameter") } if cfg.BufferSize == 0 { cfg.BufferSize = backend.DefaultBufferSize } if cfg.PollStreamPeriod == 0 { cfg.PollStreamPeriod = backend.DefaultPollStreamPeriod } if cfg.Clock == nil { cfg.Clock = clockwork.NewRealClock() } if cfg.Sync == "" { cfg.Sync = syncOFF } if cfg.BusyTimeout == 0 { cfg.BusyTimeout = busyTimeout } if cfg.MemoryName == "" { cfg.MemoryName = defaultDBFile } return nil }
go
func (cfg *Config) CheckAndSetDefaults() error { if cfg.Path == "" && !cfg.Memory { return trace.BadParameter("specify directory path to the database using 'path' parameter") } if cfg.BufferSize == 0 { cfg.BufferSize = backend.DefaultBufferSize } if cfg.PollStreamPeriod == 0 { cfg.PollStreamPeriod = backend.DefaultPollStreamPeriod } if cfg.Clock == nil { cfg.Clock = clockwork.NewRealClock() } if cfg.Sync == "" { cfg.Sync = syncOFF } if cfg.BusyTimeout == 0 { cfg.BusyTimeout = busyTimeout } if cfg.MemoryName == "" { cfg.MemoryName = defaultDBFile } return nil }
[ "func", "(", "cfg", "*", "Config", ")", "CheckAndSetDefaults", "(", ")", "error", "{", "if", "cfg", ".", "Path", "==", "\"\"", "&&", "!", "cfg", ".", "Memory", "{", "return", "trace", ".", "BadParameter", "(", "\"specify directory path to the database using 'path' parameter\"", ")", "\n", "}", "\n", "if", "cfg", ".", "BufferSize", "==", "0", "{", "cfg", ".", "BufferSize", "=", "backend", ".", "DefaultBufferSize", "\n", "}", "\n", "if", "cfg", ".", "PollStreamPeriod", "==", "0", "{", "cfg", ".", "PollStreamPeriod", "=", "backend", ".", "DefaultPollStreamPeriod", "\n", "}", "\n", "if", "cfg", ".", "Clock", "==", "nil", "{", "cfg", ".", "Clock", "=", "clockwork", ".", "NewRealClock", "(", ")", "\n", "}", "\n", "if", "cfg", ".", "Sync", "==", "\"\"", "{", "cfg", ".", "Sync", "=", "syncOFF", "\n", "}", "\n", "if", "cfg", ".", "BusyTimeout", "==", "0", "{", "cfg", ".", "BusyTimeout", "=", "busyTimeout", "\n", "}", "\n", "if", "cfg", ".", "MemoryName", "==", "\"\"", "{", "cfg", ".", "MemoryName", "=", "defaultDBFile", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CheckAndSetDefaults is a helper returns an error if the supplied configuration // is not enough to connect to sqlite
[ "CheckAndSetDefaults", "is", "a", "helper", "returns", "an", "error", "if", "the", "supplied", "configuration", "is", "not", "enough", "to", "connect", "to", "sqlite" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/lite/lite.go#L94-L117
train
gravitational/teleport
lib/backend/lite/lite.go
New
func New(ctx context.Context, params backend.Params) (*LiteBackend, error) { var cfg *Config err := utils.ObjectToStruct(params, &cfg) if err != nil { return nil, trace.BadParameter("SQLite configuration is invalid: %v", err) } return NewWithConfig(ctx, *cfg) }
go
func New(ctx context.Context, params backend.Params) (*LiteBackend, error) { var cfg *Config err := utils.ObjectToStruct(params, &cfg) if err != nil { return nil, trace.BadParameter("SQLite configuration is invalid: %v", err) } return NewWithConfig(ctx, *cfg) }
[ "func", "New", "(", "ctx", "context", ".", "Context", ",", "params", "backend", ".", "Params", ")", "(", "*", "LiteBackend", ",", "error", ")", "{", "var", "cfg", "*", "Config", "\n", "err", ":=", "utils", ".", "ObjectToStruct", "(", "params", ",", "&", "cfg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"SQLite configuration is invalid: %v\"", ",", "err", ")", "\n", "}", "\n", "return", "NewWithConfig", "(", "ctx", ",", "*", "cfg", ")", "\n", "}" ]
// New returns a new instance of sqlite backend
[ "New", "returns", "a", "new", "instance", "of", "sqlite", "backend" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/lite/lite.go#L120-L127
train
gravitational/teleport
lib/backend/lite/lite.go
NewWithConfig
func NewWithConfig(ctx context.Context, cfg Config) (*LiteBackend, error) { if err := cfg.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } var connectorURL string if !cfg.Memory { // Ensure that the path to the root directory exists. err := os.MkdirAll(cfg.Path, defaultDirMode) if err != nil { return nil, trace.ConvertSystemError(err) } fullPath := filepath.Join(cfg.Path, defaultDBFile) connectorURL = fmt.Sprintf("file:%v?_busy_timeout=%v&_sync=%v", fullPath, cfg.BusyTimeout, cfg.Sync) } else { connectorURL = fmt.Sprintf("file:%v?mode=memory", cfg.MemoryName) } db, err := sql.Open(BackendName, connectorURL) if err != nil { return nil, trace.Wrap(err, "error opening URI: %v", connectorURL) } // serialize access to sqlite to avoid database is locked errors db.SetMaxOpenConns(1) 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) l := &LiteBackend{ Config: cfg, db: db, Entry: log.WithFields(log.Fields{trace.Component: BackendName}), clock: cfg.Clock, buf: buf, ctx: closeCtx, cancel: cancel, watchStarted: watchStarted, signalWatchStart: signalWatchStart, } l.Debugf("Connected to: %v, poll stream period: %v", connectorURL, cfg.PollStreamPeriod) if err := l.createSchema(); err != nil { return nil, trace.Wrap(err, "error creating schema: %v", connectorURL) } if err := l.showPragmas(); err != nil { l.Warningf("Failed to show pragma settings: %v.", err) } go l.runPeriodicOperations() return l, nil }
go
func NewWithConfig(ctx context.Context, cfg Config) (*LiteBackend, error) { if err := cfg.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } var connectorURL string if !cfg.Memory { // Ensure that the path to the root directory exists. err := os.MkdirAll(cfg.Path, defaultDirMode) if err != nil { return nil, trace.ConvertSystemError(err) } fullPath := filepath.Join(cfg.Path, defaultDBFile) connectorURL = fmt.Sprintf("file:%v?_busy_timeout=%v&_sync=%v", fullPath, cfg.BusyTimeout, cfg.Sync) } else { connectorURL = fmt.Sprintf("file:%v?mode=memory", cfg.MemoryName) } db, err := sql.Open(BackendName, connectorURL) if err != nil { return nil, trace.Wrap(err, "error opening URI: %v", connectorURL) } // serialize access to sqlite to avoid database is locked errors db.SetMaxOpenConns(1) 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) l := &LiteBackend{ Config: cfg, db: db, Entry: log.WithFields(log.Fields{trace.Component: BackendName}), clock: cfg.Clock, buf: buf, ctx: closeCtx, cancel: cancel, watchStarted: watchStarted, signalWatchStart: signalWatchStart, } l.Debugf("Connected to: %v, poll stream period: %v", connectorURL, cfg.PollStreamPeriod) if err := l.createSchema(); err != nil { return nil, trace.Wrap(err, "error creating schema: %v", connectorURL) } if err := l.showPragmas(); err != nil { l.Warningf("Failed to show pragma settings: %v.", err) } go l.runPeriodicOperations() return l, nil }
[ "func", "NewWithConfig", "(", "ctx", "context", ".", "Context", ",", "cfg", "Config", ")", "(", "*", "LiteBackend", ",", "error", ")", "{", "if", "err", ":=", "cfg", ".", "CheckAndSetDefaults", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "var", "connectorURL", "string", "\n", "if", "!", "cfg", ".", "Memory", "{", "err", ":=", "os", ".", "MkdirAll", "(", "cfg", ".", "Path", ",", "defaultDirMode", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "ConvertSystemError", "(", "err", ")", "\n", "}", "\n", "fullPath", ":=", "filepath", ".", "Join", "(", "cfg", ".", "Path", ",", "defaultDBFile", ")", "\n", "connectorURL", "=", "fmt", ".", "Sprintf", "(", "\"file:%v?_busy_timeout=%v&_sync=%v\"", ",", "fullPath", ",", "cfg", ".", "BusyTimeout", ",", "cfg", ".", "Sync", ")", "\n", "}", "else", "{", "connectorURL", "=", "fmt", ".", "Sprintf", "(", "\"file:%v?mode=memory\"", ",", "cfg", ".", "MemoryName", ")", "\n", "}", "\n", "db", ",", "err", ":=", "sql", ".", "Open", "(", "BackendName", ",", "connectorURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ",", "\"error opening URI: %v\"", ",", "connectorURL", ")", "\n", "}", "\n", "db", ".", "SetMaxOpenConns", "(", "1", ")", "\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", "l", ":=", "&", "LiteBackend", "{", "Config", ":", "cfg", ",", "db", ":", "db", ",", "Entry", ":", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "trace", ".", "Component", ":", "BackendName", "}", ")", ",", "clock", ":", "cfg", ".", "Clock", ",", "buf", ":", "buf", ",", "ctx", ":", "closeCtx", ",", "cancel", ":", "cancel", ",", "watchStarted", ":", "watchStarted", ",", "signalWatchStart", ":", "signalWatchStart", ",", "}", "\n", "l", ".", "Debugf", "(", "\"Connected to: %v, poll stream period: %v\"", ",", "connectorURL", ",", "cfg", ".", "PollStreamPeriod", ")", "\n", "if", "err", ":=", "l", ".", "createSchema", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ",", "\"error creating schema: %v\"", ",", "connectorURL", ")", "\n", "}", "\n", "if", "err", ":=", "l", ".", "showPragmas", "(", ")", ";", "err", "!=", "nil", "{", "l", ".", "Warningf", "(", "\"Failed to show pragma settings: %v.\"", ",", "err", ")", "\n", "}", "\n", "go", "l", ".", "runPeriodicOperations", "(", ")", "\n", "return", "l", ",", "nil", "\n", "}" ]
// NewWithConfig returns a new instance of lite backend using // configuration struct as a parameter
[ "NewWithConfig", "returns", "a", "new", "instance", "of", "lite", "backend", "using", "configuration", "struct", "as", "a", "parameter" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/lite/lite.go#L131-L179
train
gravitational/teleport
lib/backend/lite/lite.go
showPragmas
func (l *LiteBackend) showPragmas() error { return l.inTransaction(l.ctx, func(tx *sql.Tx) error { row := tx.QueryRowContext(l.ctx, "PRAGMA synchronous;") var syncValue string if err := row.Scan(&syncValue); err != nil { return trace.Wrap(err) } var timeoutValue string row = tx.QueryRowContext(l.ctx, "PRAGMA busy_timeout;") if err := row.Scan(&timeoutValue); err != nil { return trace.Wrap(err) } l.Debugf("Synchronous: %v, busy timeout: %v", syncValue, timeoutValue) return nil }) }
go
func (l *LiteBackend) showPragmas() error { return l.inTransaction(l.ctx, func(tx *sql.Tx) error { row := tx.QueryRowContext(l.ctx, "PRAGMA synchronous;") var syncValue string if err := row.Scan(&syncValue); err != nil { return trace.Wrap(err) } var timeoutValue string row = tx.QueryRowContext(l.ctx, "PRAGMA busy_timeout;") if err := row.Scan(&timeoutValue); err != nil { return trace.Wrap(err) } l.Debugf("Synchronous: %v, busy timeout: %v", syncValue, timeoutValue) return nil }) }
[ "func", "(", "l", "*", "LiteBackend", ")", "showPragmas", "(", ")", "error", "{", "return", "l", ".", "inTransaction", "(", "l", ".", "ctx", ",", "func", "(", "tx", "*", "sql", ".", "Tx", ")", "error", "{", "row", ":=", "tx", ".", "QueryRowContext", "(", "l", ".", "ctx", ",", "\"PRAGMA synchronous;\"", ")", "\n", "var", "syncValue", "string", "\n", "if", "err", ":=", "row", ".", "Scan", "(", "&", "syncValue", ")", ";", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "var", "timeoutValue", "string", "\n", "row", "=", "tx", ".", "QueryRowContext", "(", "l", ".", "ctx", ",", "\"PRAGMA busy_timeout;\"", ")", "\n", "if", "err", ":=", "row", ".", "Scan", "(", "&", "timeoutValue", ")", ";", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "l", ".", "Debugf", "(", "\"Synchronous: %v, busy timeout: %v\"", ",", "syncValue", ",", "timeoutValue", ")", "\n", "return", "nil", "\n", "}", ")", "\n", "}" ]
// showPragmas is used to debug SQLite database connection // parameters, when called, logs some key PRAGMA values
[ "showPragmas", "is", "used", "to", "debug", "SQLite", "database", "connection", "parameters", "when", "called", "logs", "some", "key", "PRAGMA", "values" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/lite/lite.go#L205-L220
train
gravitational/teleport
lib/backend/lite/lite.go
Imported
func (l *LiteBackend) Imported(ctx context.Context) (imported bool, err error) { err = l.inTransaction(ctx, func(tx *sql.Tx) error { q, err := tx.PrepareContext(ctx, "SELECT imported from meta LIMIT 1") if err != nil { return trace.Wrap(err) } row := q.QueryRowContext(ctx) if err := row.Scan(&imported); err != nil { if err != sql.ErrNoRows { return trace.Wrap(err) } } return nil }) return imported, err }
go
func (l *LiteBackend) Imported(ctx context.Context) (imported bool, err error) { err = l.inTransaction(ctx, func(tx *sql.Tx) error { q, err := tx.PrepareContext(ctx, "SELECT imported from meta LIMIT 1") if err != nil { return trace.Wrap(err) } row := q.QueryRowContext(ctx) if err := row.Scan(&imported); err != nil { if err != sql.ErrNoRows { return trace.Wrap(err) } } return nil }) return imported, err }
[ "func", "(", "l", "*", "LiteBackend", ")", "Imported", "(", "ctx", "context", ".", "Context", ")", "(", "imported", "bool", ",", "err", "error", ")", "{", "err", "=", "l", ".", "inTransaction", "(", "ctx", ",", "func", "(", "tx", "*", "sql", ".", "Tx", ")", "error", "{", "q", ",", "err", ":=", "tx", ".", "PrepareContext", "(", "ctx", ",", "\"SELECT imported from meta LIMIT 1\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "row", ":=", "q", ".", "QueryRowContext", "(", "ctx", ")", "\n", "if", "err", ":=", "row", ".", "Scan", "(", "&", "imported", ")", ";", "err", "!=", "nil", "{", "if", "err", "!=", "sql", ".", "ErrNoRows", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "return", "imported", ",", "err", "\n", "}" ]
// Imported returns true if backend already imported data from another backend
[ "Imported", "returns", "true", "if", "backend", "already", "imported", "data", "from", "another", "backend" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/lite/lite.go#L413-L429
train
gravitational/teleport
lib/backend/lite/lite.go
Import
func (l *LiteBackend) Import(ctx context.Context, items []backend.Item) error { for i := range items { if items[i].Key == nil { return trace.BadParameter("missing parameter key in item %v", i) } } err := l.inTransaction(ctx, func(tx *sql.Tx) error { q, err := tx.PrepareContext(ctx, "SELECT imported from meta LIMIT 1") if err != nil { return trace.Wrap(err) } var imported bool row := q.QueryRowContext(ctx) if err := row.Scan(&imported); err != nil { if err != sql.ErrNoRows { return trace.Wrap(err) } } if imported { return trace.AlreadyExists("database has been already imported") } if err := l.putRangeInTransaction(ctx, tx, items, true); err != nil { return trace.Wrap(err) } stmt, err := tx.PrepareContext(ctx, "INSERT INTO meta(version, imported) values(?, ?)") if err != nil { return trace.Wrap(err) } if _, err := stmt.ExecContext(ctx, schemaVersion, true); err != nil { return trace.Wrap(err) } return nil }) if err != nil { return trace.Wrap(err) } return nil }
go
func (l *LiteBackend) Import(ctx context.Context, items []backend.Item) error { for i := range items { if items[i].Key == nil { return trace.BadParameter("missing parameter key in item %v", i) } } err := l.inTransaction(ctx, func(tx *sql.Tx) error { q, err := tx.PrepareContext(ctx, "SELECT imported from meta LIMIT 1") if err != nil { return trace.Wrap(err) } var imported bool row := q.QueryRowContext(ctx) if err := row.Scan(&imported); err != nil { if err != sql.ErrNoRows { return trace.Wrap(err) } } if imported { return trace.AlreadyExists("database has been already imported") } if err := l.putRangeInTransaction(ctx, tx, items, true); err != nil { return trace.Wrap(err) } stmt, err := tx.PrepareContext(ctx, "INSERT INTO meta(version, imported) values(?, ?)") if err != nil { return trace.Wrap(err) } if _, err := stmt.ExecContext(ctx, schemaVersion, true); err != nil { return trace.Wrap(err) } return nil }) if err != nil { return trace.Wrap(err) } return nil }
[ "func", "(", "l", "*", "LiteBackend", ")", "Import", "(", "ctx", "context", ".", "Context", ",", "items", "[", "]", "backend", ".", "Item", ")", "error", "{", "for", "i", ":=", "range", "items", "{", "if", "items", "[", "i", "]", ".", "Key", "==", "nil", "{", "return", "trace", ".", "BadParameter", "(", "\"missing parameter key in item %v\"", ",", "i", ")", "\n", "}", "\n", "}", "\n", "err", ":=", "l", ".", "inTransaction", "(", "ctx", ",", "func", "(", "tx", "*", "sql", ".", "Tx", ")", "error", "{", "q", ",", "err", ":=", "tx", ".", "PrepareContext", "(", "ctx", ",", "\"SELECT imported from meta LIMIT 1\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "var", "imported", "bool", "\n", "row", ":=", "q", ".", "QueryRowContext", "(", "ctx", ")", "\n", "if", "err", ":=", "row", ".", "Scan", "(", "&", "imported", ")", ";", "err", "!=", "nil", "{", "if", "err", "!=", "sql", ".", "ErrNoRows", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n", "if", "imported", "{", "return", "trace", ".", "AlreadyExists", "(", "\"database has been already imported\"", ")", "\n", "}", "\n", "if", "err", ":=", "l", ".", "putRangeInTransaction", "(", "ctx", ",", "tx", ",", "items", ",", "true", ")", ";", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "stmt", ",", "err", ":=", "tx", ".", "PrepareContext", "(", "ctx", ",", "\"INSERT INTO meta(version, imported) values(?, ?)\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "_", ",", "err", ":=", "stmt", ".", "ExecContext", "(", "ctx", ",", "schemaVersion", ",", "true", ")", ";", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Import imports elements, makes sure elements are imported only once // returns trace.AlreadyExists if elements have been imported
[ "Import", "imports", "elements", "makes", "sure", "elements", "are", "imported", "only", "once", "returns", "trace", ".", "AlreadyExists", "if", "elements", "have", "been", "imported" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/lite/lite.go#L433-L474
train
gravitational/teleport
lib/backend/lite/lite.go
getInTransaction
func (l *LiteBackend) getInTransaction(ctx context.Context, key []byte, tx *sql.Tx, item *backend.Item) error { now := l.clock.Now().UTC() q, err := tx.PrepareContext(ctx, "SELECT key, value, expires, modified FROM kv WHERE key = ? AND (expires IS NULL OR expires > ?) LIMIT 1") if err != nil { return trace.Wrap(err) } row := q.QueryRowContext(ctx, string(key), now) var expires NullTime if err := row.Scan(&item.Key, &item.Value, &expires, &item.ID); err != nil { if err == sql.ErrNoRows { return trace.NotFound("key %v is not found", string(key)) } return trace.Wrap(err) } item.Expires = expires.Time return nil }
go
func (l *LiteBackend) getInTransaction(ctx context.Context, key []byte, tx *sql.Tx, item *backend.Item) error { now := l.clock.Now().UTC() q, err := tx.PrepareContext(ctx, "SELECT key, value, expires, modified FROM kv WHERE key = ? AND (expires IS NULL OR expires > ?) LIMIT 1") if err != nil { return trace.Wrap(err) } row := q.QueryRowContext(ctx, string(key), now) var expires NullTime if err := row.Scan(&item.Key, &item.Value, &expires, &item.ID); err != nil { if err == sql.ErrNoRows { return trace.NotFound("key %v is not found", string(key)) } return trace.Wrap(err) } item.Expires = expires.Time return nil }
[ "func", "(", "l", "*", "LiteBackend", ")", "getInTransaction", "(", "ctx", "context", ".", "Context", ",", "key", "[", "]", "byte", ",", "tx", "*", "sql", ".", "Tx", ",", "item", "*", "backend", ".", "Item", ")", "error", "{", "now", ":=", "l", ".", "clock", ".", "Now", "(", ")", ".", "UTC", "(", ")", "\n", "q", ",", "err", ":=", "tx", ".", "PrepareContext", "(", "ctx", ",", "\"SELECT key, value, expires, modified FROM kv WHERE key = ? AND (expires IS NULL OR expires > ?) LIMIT 1\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "row", ":=", "q", ".", "QueryRowContext", "(", "ctx", ",", "string", "(", "key", ")", ",", "now", ")", "\n", "var", "expires", "NullTime", "\n", "if", "err", ":=", "row", ".", "Scan", "(", "&", "item", ".", "Key", ",", "&", "item", ".", "Value", ",", "&", "expires", ",", "&", "item", ".", "ID", ")", ";", "err", "!=", "nil", "{", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "return", "trace", ".", "NotFound", "(", "\"key %v is not found\"", ",", "string", "(", "key", ")", ")", "\n", "}", "\n", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "item", ".", "Expires", "=", "expires", ".", "Time", "\n", "return", "nil", "\n", "}" ]
// getInTransaction returns an item, works in transaction
[ "getInTransaction", "returns", "an", "item", "works", "in", "transaction" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/lite/lite.go#L579-L596
train
gravitational/teleport
lib/modules/modules.go
PrintVersion
func (p *defaultModules) PrintVersion() { var buf bytes.Buffer buf.WriteString(fmt.Sprintf("Teleport v%s ", teleport.Version)) buf.WriteString(fmt.Sprintf("git:%s ", teleport.Gitref)) buf.WriteString(runtime.Version()) fmt.Println(buf.String()) }
go
func (p *defaultModules) PrintVersion() { var buf bytes.Buffer buf.WriteString(fmt.Sprintf("Teleport v%s ", teleport.Version)) buf.WriteString(fmt.Sprintf("git:%s ", teleport.Gitref)) buf.WriteString(runtime.Version()) fmt.Println(buf.String()) }
[ "func", "(", "p", "*", "defaultModules", ")", "PrintVersion", "(", ")", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "buf", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"Teleport v%s \"", ",", "teleport", ".", "Version", ")", ")", "\n", "buf", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"git:%s \"", ",", "teleport", ".", "Gitref", ")", ")", "\n", "buf", ".", "WriteString", "(", "runtime", ".", "Version", "(", ")", ")", "\n", "fmt", ".", "Println", "(", "buf", ".", "String", "(", ")", ")", "\n", "}" ]
// PrintVersion prints the Teleport version.
[ "PrintVersion", "prints", "the", "Teleport", "version", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/modules/modules.go#L85-L93
train
gravitational/teleport
lib/modules/modules.go
TraitsFromLogins
func (p *defaultModules) TraitsFromLogins(logins []string, kubeGroups []string) map[string][]string { return map[string][]string{ teleport.TraitLogins: logins, teleport.TraitKubeGroups: kubeGroups, } }
go
func (p *defaultModules) TraitsFromLogins(logins []string, kubeGroups []string) map[string][]string { return map[string][]string{ teleport.TraitLogins: logins, teleport.TraitKubeGroups: kubeGroups, } }
[ "func", "(", "p", "*", "defaultModules", ")", "TraitsFromLogins", "(", "logins", "[", "]", "string", ",", "kubeGroups", "[", "]", "string", ")", "map", "[", "string", "]", "[", "]", "string", "{", "return", "map", "[", "string", "]", "[", "]", "string", "{", "teleport", ".", "TraitLogins", ":", "logins", ",", "teleport", ".", "TraitKubeGroups", ":", "kubeGroups", ",", "}", "\n", "}" ]
// TraitsFromLogins returns traits for external user based on the logins // extracted from the connector // // By default logins are treated as allowed logins user traits.
[ "TraitsFromLogins", "returns", "traits", "for", "external", "user", "based", "on", "the", "logins", "extracted", "from", "the", "connector", "By", "default", "logins", "are", "treated", "as", "allowed", "logins", "user", "traits", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/modules/modules.go#L108-L113
train
gravitational/teleport
lib/services/github.go
NewGithubConnector
func NewGithubConnector(name string, spec GithubConnectorSpecV3) GithubConnector { return &GithubConnectorV3{ Kind: KindGithubConnector, Version: V3, Metadata: Metadata{ Name: name, Namespace: defaults.Namespace, }, Spec: spec, } }
go
func NewGithubConnector(name string, spec GithubConnectorSpecV3) GithubConnector { return &GithubConnectorV3{ Kind: KindGithubConnector, Version: V3, Metadata: Metadata{ Name: name, Namespace: defaults.Namespace, }, Spec: spec, } }
[ "func", "NewGithubConnector", "(", "name", "string", ",", "spec", "GithubConnectorSpecV3", ")", "GithubConnector", "{", "return", "&", "GithubConnectorV3", "{", "Kind", ":", "KindGithubConnector", ",", "Version", ":", "V3", ",", "Metadata", ":", "Metadata", "{", "Name", ":", "name", ",", "Namespace", ":", "defaults", ".", "Namespace", ",", "}", ",", "Spec", ":", "spec", ",", "}", "\n", "}" ]
// NewGithubConnector creates a new Github connector from name and spec
[ "NewGithubConnector", "creates", "a", "new", "Github", "connector", "from", "name", "and", "spec" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/github.go#L63-L73
train
gravitational/teleport
lib/services/github.go
SetExpiry
func (c *GithubConnectorV3) SetExpiry(expires time.Time) { c.Metadata.SetExpiry(expires) }
go
func (c *GithubConnectorV3) SetExpiry(expires time.Time) { c.Metadata.SetExpiry(expires) }
[ "func", "(", "c", "*", "GithubConnectorV3", ")", "SetExpiry", "(", "expires", "time", ".", "Time", ")", "{", "c", ".", "Metadata", ".", "SetExpiry", "(", "expires", ")", "\n", "}" ]
// SetExpiry sets the connector expiration time
[ "SetExpiry", "sets", "the", "connector", "expiration", "time" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/github.go#L169-L171
train
gravitational/teleport
lib/services/github.go
SetTTL
func (c *GithubConnectorV3) SetTTL(clock clockwork.Clock, ttl time.Duration) { c.Metadata.SetTTL(clock, ttl) }
go
func (c *GithubConnectorV3) SetTTL(clock clockwork.Clock, ttl time.Duration) { c.Metadata.SetTTL(clock, ttl) }
[ "func", "(", "c", "*", "GithubConnectorV3", ")", "SetTTL", "(", "clock", "clockwork", ".", "Clock", ",", "ttl", "time", ".", "Duration", ")", "{", "c", ".", "Metadata", ".", "SetTTL", "(", "clock", ",", "ttl", ")", "\n", "}" ]
// SetTTL sets the connector TTL
[ "SetTTL", "sets", "the", "connector", "TTL" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/github.go#L174-L176
train
gravitational/teleport
lib/services/github.go
MapClaims
func (c *GithubConnectorV3) MapClaims(claims GithubClaims) ([]string, []string) { var logins, kubeGroups []string for _, mapping := range c.GetTeamsToLogins() { teams, ok := claims.OrganizationToTeams[mapping.Organization] if !ok { // the user does not belong to this organization continue } for _, team := range teams { // see if the user belongs to this team if team == mapping.Team { logins = append(logins, mapping.Logins...) kubeGroups = append(kubeGroups, mapping.KubeGroups...) } } } return utils.Deduplicate(logins), utils.Deduplicate(kubeGroups) }
go
func (c *GithubConnectorV3) MapClaims(claims GithubClaims) ([]string, []string) { var logins, kubeGroups []string for _, mapping := range c.GetTeamsToLogins() { teams, ok := claims.OrganizationToTeams[mapping.Organization] if !ok { // the user does not belong to this organization continue } for _, team := range teams { // see if the user belongs to this team if team == mapping.Team { logins = append(logins, mapping.Logins...) kubeGroups = append(kubeGroups, mapping.KubeGroups...) } } } return utils.Deduplicate(logins), utils.Deduplicate(kubeGroups) }
[ "func", "(", "c", "*", "GithubConnectorV3", ")", "MapClaims", "(", "claims", "GithubClaims", ")", "(", "[", "]", "string", ",", "[", "]", "string", ")", "{", "var", "logins", ",", "kubeGroups", "[", "]", "string", "\n", "for", "_", ",", "mapping", ":=", "range", "c", ".", "GetTeamsToLogins", "(", ")", "{", "teams", ",", "ok", ":=", "claims", ".", "OrganizationToTeams", "[", "mapping", ".", "Organization", "]", "\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n", "for", "_", ",", "team", ":=", "range", "teams", "{", "if", "team", "==", "mapping", ".", "Team", "{", "logins", "=", "append", "(", "logins", ",", "mapping", ".", "Logins", "...", ")", "\n", "kubeGroups", "=", "append", "(", "kubeGroups", ",", "mapping", ".", "KubeGroups", "...", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "utils", ".", "Deduplicate", "(", "logins", ")", ",", "utils", ".", "Deduplicate", "(", "kubeGroups", ")", "\n", "}" ]
// MapClaims returns a list of logins based on the provided claims, // returns a list of logins and list of kubernetes groups
[ "MapClaims", "returns", "a", "list", "of", "logins", "based", "on", "the", "provided", "claims", "returns", "a", "list", "of", "logins", "and", "list", "of", "kubernetes", "groups" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/github.go#L243-L260
train
gravitational/teleport
lib/services/github.go
Unmarshal
func (*TeleportGithubConnectorMarshaler) Unmarshal(bytes []byte) (GithubConnector, error) { var h ResourceHeader if err := json.Unmarshal(bytes, &h); err != nil { return nil, trace.Wrap(err) } switch h.Version { case V3: var c GithubConnectorV3 if err := utils.UnmarshalWithSchema(GetGithubConnectorSchema(), &c, bytes); err != nil { return nil, trace.Wrap(err) } if err := c.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } return &c, nil } return nil, trace.BadParameter( "Github connector resource version %q is not supported", h.Version) }
go
func (*TeleportGithubConnectorMarshaler) Unmarshal(bytes []byte) (GithubConnector, error) { var h ResourceHeader if err := json.Unmarshal(bytes, &h); err != nil { return nil, trace.Wrap(err) } switch h.Version { case V3: var c GithubConnectorV3 if err := utils.UnmarshalWithSchema(GetGithubConnectorSchema(), &c, bytes); err != nil { return nil, trace.Wrap(err) } if err := c.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } return &c, nil } return nil, trace.BadParameter( "Github connector resource version %q is not supported", h.Version) }
[ "func", "(", "*", "TeleportGithubConnectorMarshaler", ")", "Unmarshal", "(", "bytes", "[", "]", "byte", ")", "(", "GithubConnector", ",", "error", ")", "{", "var", "h", "ResourceHeader", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "bytes", ",", "&", "h", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "switch", "h", ".", "Version", "{", "case", "V3", ":", "var", "c", "GithubConnectorV3", "\n", "if", "err", ":=", "utils", ".", "UnmarshalWithSchema", "(", "GetGithubConnectorSchema", "(", ")", ",", "&", "c", ",", "bytes", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "err", ":=", "c", ".", "CheckAndSetDefaults", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "&", "c", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"Github connector resource version %q is not supported\"", ",", "h", ".", "Version", ")", "\n", "}" ]
// UnmarshalGithubConnector unmarshals Github connector from JSON
[ "UnmarshalGithubConnector", "unmarshals", "Github", "connector", "from", "JSON" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/github.go#L295-L313
train
gravitational/teleport
lib/services/github.go
Marshal
func (*TeleportGithubConnectorMarshaler) Marshal(c GithubConnector, opts ...MarshalOption) ([]byte, error) { cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } switch resource := c.(type) { case *GithubConnectorV3: if !cfg.PreserveResourceID { // avoid modifying the original object // to prevent unexpected data races copy := *resource copy.SetResourceID(0) resource = &copy } return utils.FastMarshal(resource) default: return nil, trace.BadParameter("unrecognized resource version %T", c) } }
go
func (*TeleportGithubConnectorMarshaler) Marshal(c GithubConnector, opts ...MarshalOption) ([]byte, error) { cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } switch resource := c.(type) { case *GithubConnectorV3: if !cfg.PreserveResourceID { // avoid modifying the original object // to prevent unexpected data races copy := *resource copy.SetResourceID(0) resource = &copy } return utils.FastMarshal(resource) default: return nil, trace.BadParameter("unrecognized resource version %T", c) } }
[ "func", "(", "*", "TeleportGithubConnectorMarshaler", ")", "Marshal", "(", "c", "GithubConnector", ",", "opts", "...", "MarshalOption", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "cfg", ",", "err", ":=", "collectOptions", "(", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "switch", "resource", ":=", "c", ".", "(", "type", ")", "{", "case", "*", "GithubConnectorV3", ":", "if", "!", "cfg", ".", "PreserveResourceID", "{", "copy", ":=", "*", "resource", "\n", "copy", ".", "SetResourceID", "(", "0", ")", "\n", "resource", "=", "&", "copy", "\n", "}", "\n", "return", "utils", ".", "FastMarshal", "(", "resource", ")", "\n", "default", ":", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"unrecognized resource version %T\"", ",", "c", ")", "\n", "}", "\n", "}" ]
// MarshalGithubConnector marshals Github connector to JSON
[ "MarshalGithubConnector", "marshals", "Github", "connector", "to", "JSON" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/github.go#L316-L334
train
gravitational/teleport
lib/services/local/provisioning.go
DeleteAllTokens
func (s *ProvisioningService) DeleteAllTokens() error { startKey := backend.Key(tokensPrefix) return s.DeleteRange(context.TODO(), startKey, backend.RangeEnd(startKey)) }
go
func (s *ProvisioningService) DeleteAllTokens() error { startKey := backend.Key(tokensPrefix) return s.DeleteRange(context.TODO(), startKey, backend.RangeEnd(startKey)) }
[ "func", "(", "s", "*", "ProvisioningService", ")", "DeleteAllTokens", "(", ")", "error", "{", "startKey", ":=", "backend", ".", "Key", "(", "tokensPrefix", ")", "\n", "return", "s", ".", "DeleteRange", "(", "context", ".", "TODO", "(", ")", ",", "startKey", ",", "backend", ".", "RangeEnd", "(", "startKey", ")", ")", "\n", "}" ]
// DeleteAllTokens deletes all provisioning tokens
[ "DeleteAllTokens", "deletes", "all", "provisioning", "tokens" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/provisioning.go#L66-L69
train
gravitational/teleport
lib/services/clusterconfig.go
NewClusterConfig
func NewClusterConfig(spec ClusterConfigSpecV3) (ClusterConfig, error) { cc := ClusterConfigV3{ Kind: KindClusterConfig, Version: V3, Metadata: Metadata{ Name: MetaNameClusterConfig, Namespace: defaults.Namespace, }, Spec: spec, } if err := cc.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } return &cc, nil }
go
func NewClusterConfig(spec ClusterConfigSpecV3) (ClusterConfig, error) { cc := ClusterConfigV3{ Kind: KindClusterConfig, Version: V3, Metadata: Metadata{ Name: MetaNameClusterConfig, Namespace: defaults.Namespace, }, Spec: spec, } if err := cc.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } return &cc, nil }
[ "func", "NewClusterConfig", "(", "spec", "ClusterConfigSpecV3", ")", "(", "ClusterConfig", ",", "error", ")", "{", "cc", ":=", "ClusterConfigV3", "{", "Kind", ":", "KindClusterConfig", ",", "Version", ":", "V3", ",", "Metadata", ":", "Metadata", "{", "Name", ":", "MetaNameClusterConfig", ",", "Namespace", ":", "defaults", ".", "Namespace", ",", "}", ",", "Spec", ":", "spec", ",", "}", "\n", "if", "err", ":=", "cc", ".", "CheckAndSetDefaults", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "&", "cc", ",", "nil", "\n", "}" ]
// NewClusterConfig is a convenience wrapper to create a ClusterConfig resource.
[ "NewClusterConfig", "is", "a", "convenience", "wrapper", "to", "create", "a", "ClusterConfig", "resource", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/clusterconfig.go#L97-L112
train
gravitational/teleport
lib/services/clusterconfig.go
AuditConfigFromObject
func AuditConfigFromObject(in interface{}) (*AuditConfig, error) { var cfg AuditConfig if in == nil { return &cfg, nil } if err := utils.ObjectToStruct(in, &cfg); err != nil { return nil, trace.Wrap(err) } return &cfg, nil }
go
func AuditConfigFromObject(in interface{}) (*AuditConfig, error) { var cfg AuditConfig if in == nil { return &cfg, nil } if err := utils.ObjectToStruct(in, &cfg); err != nil { return nil, trace.Wrap(err) } return &cfg, nil }
[ "func", "AuditConfigFromObject", "(", "in", "interface", "{", "}", ")", "(", "*", "AuditConfig", ",", "error", ")", "{", "var", "cfg", "AuditConfig", "\n", "if", "in", "==", "nil", "{", "return", "&", "cfg", ",", "nil", "\n", "}", "\n", "if", "err", ":=", "utils", ".", "ObjectToStruct", "(", "in", ",", "&", "cfg", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "&", "cfg", ",", "nil", "\n", "}" ]
// AuditConfigFromObject returns audit config from interface object
[ "AuditConfigFromObject", "returns", "audit", "config", "from", "interface", "object" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/clusterconfig.go#L140-L149
train
gravitational/teleport
lib/services/clusterconfig.go
SetClientIdleTimeout
func (c *ClusterConfigV3) SetClientIdleTimeout(d time.Duration) { c.Spec.ClientIdleTimeout = Duration(d) }
go
func (c *ClusterConfigV3) SetClientIdleTimeout(d time.Duration) { c.Spec.ClientIdleTimeout = Duration(d) }
[ "func", "(", "c", "*", "ClusterConfigV3", ")", "SetClientIdleTimeout", "(", "d", "time", ".", "Duration", ")", "{", "c", ".", "Spec", ".", "ClientIdleTimeout", "=", "Duration", "(", "d", ")", "\n", "}" ]
// SetClientIdleTimeout sets client idle timeout setting
[ "SetClientIdleTimeout", "sets", "client", "idle", "timeout", "setting" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/clusterconfig.go#L279-L281
train
gravitational/teleport
lib/services/clusterconfig.go
SetDisconnectExpiredCert
func (c *ClusterConfigV3) SetDisconnectExpiredCert(b bool) { c.Spec.DisconnectExpiredCert = NewBool(b) }
go
func (c *ClusterConfigV3) SetDisconnectExpiredCert(b bool) { c.Spec.DisconnectExpiredCert = NewBool(b) }
[ "func", "(", "c", "*", "ClusterConfigV3", ")", "SetDisconnectExpiredCert", "(", "b", "bool", ")", "{", "c", ".", "Spec", ".", "DisconnectExpiredCert", "=", "NewBool", "(", "b", ")", "\n", "}" ]
// SetDisconnectExpiredCert sets disconnect client with expired certificate setting
[ "SetDisconnectExpiredCert", "sets", "disconnect", "client", "with", "expired", "certificate", "setting" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/clusterconfig.go#L289-L291
train
gravitational/teleport
lib/services/clusterconfig.go
SetKeepAliveInterval
func (c *ClusterConfigV3) SetKeepAliveInterval(t time.Duration) { c.Spec.KeepAliveInterval = Duration(t) }
go
func (c *ClusterConfigV3) SetKeepAliveInterval(t time.Duration) { c.Spec.KeepAliveInterval = Duration(t) }
[ "func", "(", "c", "*", "ClusterConfigV3", ")", "SetKeepAliveInterval", "(", "t", "time", ".", "Duration", ")", "{", "c", ".", "Spec", ".", "KeepAliveInterval", "=", "Duration", "(", "t", ")", "\n", "}" ]
// SetKeepAliveInterval sets the keep-alive interval.
[ "SetKeepAliveInterval", "sets", "the", "keep", "-", "alive", "interval", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/clusterconfig.go#L299-L301
train
gravitational/teleport
lib/services/clusterconfig.go
String
func (c *ClusterConfigV3) String() string { return fmt.Sprintf("ClusterConfig(SessionRecording=%v, ClusterID=%v, ProxyChecksHostKeys=%v)", c.Spec.SessionRecording, c.Spec.ClusterID, c.Spec.ProxyChecksHostKeys) }
go
func (c *ClusterConfigV3) String() string { return fmt.Sprintf("ClusterConfig(SessionRecording=%v, ClusterID=%v, ProxyChecksHostKeys=%v)", c.Spec.SessionRecording, c.Spec.ClusterID, c.Spec.ProxyChecksHostKeys) }
[ "func", "(", "c", "*", "ClusterConfigV3", ")", "String", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"ClusterConfig(SessionRecording=%v, ClusterID=%v, ProxyChecksHostKeys=%v)\"", ",", "c", ".", "Spec", ".", "SessionRecording", ",", "c", ".", "Spec", ".", "ClusterID", ",", "c", ".", "Spec", ".", "ProxyChecksHostKeys", ")", "\n", "}" ]
// String represents a human readable version of the cluster name.
[ "String", "represents", "a", "human", "readable", "version", "of", "the", "cluster", "name", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/clusterconfig.go#L363-L366
train
gravitational/teleport
lib/services/clusterconfig.go
GetClusterConfigSchema
func GetClusterConfigSchema(extensionSchema string) string { var clusterConfigSchema string if clusterConfigSchema == "" { clusterConfigSchema = fmt.Sprintf(ClusterConfigSpecSchemaTemplate, "") } else { clusterConfigSchema = fmt.Sprintf(ClusterConfigSpecSchemaTemplate, ","+extensionSchema) } return fmt.Sprintf(V2SchemaTemplate, MetadataSchema, clusterConfigSchema, DefaultDefinitions) }
go
func GetClusterConfigSchema(extensionSchema string) string { var clusterConfigSchema string if clusterConfigSchema == "" { clusterConfigSchema = fmt.Sprintf(ClusterConfigSpecSchemaTemplate, "") } else { clusterConfigSchema = fmt.Sprintf(ClusterConfigSpecSchemaTemplate, ","+extensionSchema) } return fmt.Sprintf(V2SchemaTemplate, MetadataSchema, clusterConfigSchema, DefaultDefinitions) }
[ "func", "GetClusterConfigSchema", "(", "extensionSchema", "string", ")", "string", "{", "var", "clusterConfigSchema", "string", "\n", "if", "clusterConfigSchema", "==", "\"\"", "{", "clusterConfigSchema", "=", "fmt", ".", "Sprintf", "(", "ClusterConfigSpecSchemaTemplate", ",", "\"\"", ")", "\n", "}", "else", "{", "clusterConfigSchema", "=", "fmt", ".", "Sprintf", "(", "ClusterConfigSpecSchemaTemplate", ",", "\",\"", "+", "extensionSchema", ")", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "V2SchemaTemplate", ",", "MetadataSchema", ",", "clusterConfigSchema", ",", "DefaultDefinitions", ")", "\n", "}" ]
// GetClusterConfigSchema returns the schema with optionally injected // schema for extensions.
[ "GetClusterConfigSchema", "returns", "the", "schema", "with", "optionally", "injected", "schema", "for", "extensions", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/clusterconfig.go#L427-L435
train
gravitational/teleport
lib/services/clusterconfig.go
Unmarshal
func (t *TeleportClusterConfigMarshaler) Unmarshal(bytes []byte, opts ...MarshalOption) (ClusterConfig, error) { var clusterConfig ClusterConfigV3 if len(bytes) == 0 { return nil, trace.BadParameter("missing resource data") } cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } if cfg.SkipValidation { if err := utils.FastUnmarshal(bytes, &clusterConfig); err != nil { return nil, trace.BadParameter(err.Error()) } } else { err = utils.UnmarshalWithSchema(GetClusterConfigSchema(""), &clusterConfig, bytes) if err != nil { return nil, trace.BadParameter(err.Error()) } } err = clusterConfig.CheckAndSetDefaults() if err != nil { return nil, trace.Wrap(err) } if cfg.ID != 0 { clusterConfig.SetResourceID(cfg.ID) } if !cfg.Expires.IsZero() { clusterConfig.SetExpiry(cfg.Expires) } return &clusterConfig, nil }
go
func (t *TeleportClusterConfigMarshaler) Unmarshal(bytes []byte, opts ...MarshalOption) (ClusterConfig, error) { var clusterConfig ClusterConfigV3 if len(bytes) == 0 { return nil, trace.BadParameter("missing resource data") } cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } if cfg.SkipValidation { if err := utils.FastUnmarshal(bytes, &clusterConfig); err != nil { return nil, trace.BadParameter(err.Error()) } } else { err = utils.UnmarshalWithSchema(GetClusterConfigSchema(""), &clusterConfig, bytes) if err != nil { return nil, trace.BadParameter(err.Error()) } } err = clusterConfig.CheckAndSetDefaults() if err != nil { return nil, trace.Wrap(err) } if cfg.ID != 0 { clusterConfig.SetResourceID(cfg.ID) } if !cfg.Expires.IsZero() { clusterConfig.SetExpiry(cfg.Expires) } return &clusterConfig, nil }
[ "func", "(", "t", "*", "TeleportClusterConfigMarshaler", ")", "Unmarshal", "(", "bytes", "[", "]", "byte", ",", "opts", "...", "MarshalOption", ")", "(", "ClusterConfig", ",", "error", ")", "{", "var", "clusterConfig", "ClusterConfigV3", "\n", "if", "len", "(", "bytes", ")", "==", "0", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"missing resource data\"", ")", "\n", "}", "\n", "cfg", ",", "err", ":=", "collectOptions", "(", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "cfg", ".", "SkipValidation", "{", "if", "err", ":=", "utils", ".", "FastUnmarshal", "(", "bytes", ",", "&", "clusterConfig", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}", "else", "{", "err", "=", "utils", ".", "UnmarshalWithSchema", "(", "GetClusterConfigSchema", "(", "\"\"", ")", ",", "&", "clusterConfig", ",", "bytes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}", "\n", "err", "=", "clusterConfig", ".", "CheckAndSetDefaults", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "cfg", ".", "ID", "!=", "0", "{", "clusterConfig", ".", "SetResourceID", "(", "cfg", ".", "ID", ")", "\n", "}", "\n", "if", "!", "cfg", ".", "Expires", ".", "IsZero", "(", ")", "{", "clusterConfig", ".", "SetExpiry", "(", "cfg", ".", "Expires", ")", "\n", "}", "\n", "return", "&", "clusterConfig", ",", "nil", "\n", "}" ]
// Unmarshal unmarshals ClusterConfig from JSON.
[ "Unmarshal", "unmarshals", "ClusterConfig", "from", "JSON", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/clusterconfig.go#L464-L499
train
gravitational/teleport
lib/services/clusterconfig.go
Marshal
func (t *TeleportClusterConfigMarshaler) Marshal(c ClusterConfig, opts ...MarshalOption) ([]byte, error) { cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } switch resource := c.(type) { case *ClusterConfigV3: if !cfg.PreserveResourceID { // avoid modifying the original object // to prevent unexpected data races copy := *resource copy.SetResourceID(0) resource = &copy } return utils.FastMarshal(resource) default: return nil, trace.BadParameter("unrecognized resource version %T", c) } }
go
func (t *TeleportClusterConfigMarshaler) Marshal(c ClusterConfig, opts ...MarshalOption) ([]byte, error) { cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } switch resource := c.(type) { case *ClusterConfigV3: if !cfg.PreserveResourceID { // avoid modifying the original object // to prevent unexpected data races copy := *resource copy.SetResourceID(0) resource = &copy } return utils.FastMarshal(resource) default: return nil, trace.BadParameter("unrecognized resource version %T", c) } }
[ "func", "(", "t", "*", "TeleportClusterConfigMarshaler", ")", "Marshal", "(", "c", "ClusterConfig", ",", "opts", "...", "MarshalOption", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "cfg", ",", "err", ":=", "collectOptions", "(", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "switch", "resource", ":=", "c", ".", "(", "type", ")", "{", "case", "*", "ClusterConfigV3", ":", "if", "!", "cfg", ".", "PreserveResourceID", "{", "copy", ":=", "*", "resource", "\n", "copy", ".", "SetResourceID", "(", "0", ")", "\n", "resource", "=", "&", "copy", "\n", "}", "\n", "return", "utils", ".", "FastMarshal", "(", "resource", ")", "\n", "default", ":", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"unrecognized resource version %T\"", ",", "c", ")", "\n", "}", "\n", "}" ]
// Marshal marshals ClusterConfig to JSON.
[ "Marshal", "marshals", "ClusterConfig", "to", "JSON", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/clusterconfig.go#L502-L520
train
gravitational/teleport
lib/utils/ver.go
CheckVersions
func CheckVersions(clientVersion string, minClientVersion string) error { clientSemver, err := semver.NewVersion(clientVersion) if err != nil { return trace.Wrap(err, "unsupported version format, need semver format: %q, e.g 1.0.0", clientVersion) } minClientSemver, err := semver.NewVersion(minClientVersion) if err != nil { return trace.Wrap(err, "unsupported version format, need semver format: %q, e.g 1.0.0", minClientVersion) } if clientSemver.Compare(*minClientSemver) < 0 { errorMessage := fmt.Sprintf("minimum client version supported by the server "+ "is %v. Please upgrade the client, downgrade the server, or use the "+ "--skip-version-check flag to by-pass this check.", minClientVersion) return trace.BadParameter(errorMessage) } return nil }
go
func CheckVersions(clientVersion string, minClientVersion string) error { clientSemver, err := semver.NewVersion(clientVersion) if err != nil { return trace.Wrap(err, "unsupported version format, need semver format: %q, e.g 1.0.0", clientVersion) } minClientSemver, err := semver.NewVersion(minClientVersion) if err != nil { return trace.Wrap(err, "unsupported version format, need semver format: %q, e.g 1.0.0", minClientVersion) } if clientSemver.Compare(*minClientSemver) < 0 { errorMessage := fmt.Sprintf("minimum client version supported by the server "+ "is %v. Please upgrade the client, downgrade the server, or use the "+ "--skip-version-check flag to by-pass this check.", minClientVersion) return trace.BadParameter(errorMessage) } return nil }
[ "func", "CheckVersions", "(", "clientVersion", "string", ",", "minClientVersion", "string", ")", "error", "{", "clientSemver", ",", "err", ":=", "semver", ".", "NewVersion", "(", "clientVersion", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ",", "\"unsupported version format, need semver format: %q, e.g 1.0.0\"", ",", "clientVersion", ")", "\n", "}", "\n", "minClientSemver", ",", "err", ":=", "semver", ".", "NewVersion", "(", "minClientVersion", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ",", "\"unsupported version format, need semver format: %q, e.g 1.0.0\"", ",", "minClientVersion", ")", "\n", "}", "\n", "if", "clientSemver", ".", "Compare", "(", "*", "minClientSemver", ")", "<", "0", "{", "errorMessage", ":=", "fmt", ".", "Sprintf", "(", "\"minimum client version supported by the server \"", "+", "\"is %v. Please upgrade the client, downgrade the server, or use the \"", "+", "\"--skip-version-check flag to by-pass this check.\"", ",", "minClientVersion", ")", "\n", "return", "trace", ".", "BadParameter", "(", "errorMessage", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CheckVersions compares client and server versions and makes sure that the // client version is greater than or equal to the minimum version supported // by the server.
[ "CheckVersions", "compares", "client", "and", "server", "versions", "and", "makes", "sure", "that", "the", "client", "version", "is", "greater", "than", "or", "equal", "to", "the", "minimum", "version", "supported", "by", "the", "server", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/ver.go#L30-L51
train
gravitational/teleport
lib/srv/exec.go
NewExecRequest
func NewExecRequest(ctx *ServerContext, command string) (Exec, error) { // It doesn't matter what mode the cluster is in, if this is a Teleport node // return a local *localExec. if ctx.srv.Component() == teleport.ComponentNode { return &localExec{ Ctx: ctx, Command: command, }, nil } // When in recording mode, return an *remoteExec which will execute the // command on a remote host. This is used by in-memory forwarding nodes. if ctx.ClusterConfig.GetSessionRecording() == services.RecordAtProxy { return &remoteExec{ ctx: ctx, command: command, session: ctx.RemoteSession, }, nil } // Otherwise return a *localExec which will execute locally on the server. // used by the regular Teleport nodes. return &localExec{ Ctx: ctx, Command: command, }, nil }
go
func NewExecRequest(ctx *ServerContext, command string) (Exec, error) { // It doesn't matter what mode the cluster is in, if this is a Teleport node // return a local *localExec. if ctx.srv.Component() == teleport.ComponentNode { return &localExec{ Ctx: ctx, Command: command, }, nil } // When in recording mode, return an *remoteExec which will execute the // command on a remote host. This is used by in-memory forwarding nodes. if ctx.ClusterConfig.GetSessionRecording() == services.RecordAtProxy { return &remoteExec{ ctx: ctx, command: command, session: ctx.RemoteSession, }, nil } // Otherwise return a *localExec which will execute locally on the server. // used by the regular Teleport nodes. return &localExec{ Ctx: ctx, Command: command, }, nil }
[ "func", "NewExecRequest", "(", "ctx", "*", "ServerContext", ",", "command", "string", ")", "(", "Exec", ",", "error", ")", "{", "if", "ctx", ".", "srv", ".", "Component", "(", ")", "==", "teleport", ".", "ComponentNode", "{", "return", "&", "localExec", "{", "Ctx", ":", "ctx", ",", "Command", ":", "command", ",", "}", ",", "nil", "\n", "}", "\n", "if", "ctx", ".", "ClusterConfig", ".", "GetSessionRecording", "(", ")", "==", "services", ".", "RecordAtProxy", "{", "return", "&", "remoteExec", "{", "ctx", ":", "ctx", ",", "command", ":", "command", ",", "session", ":", "ctx", ".", "RemoteSession", ",", "}", ",", "nil", "\n", "}", "\n", "return", "&", "localExec", "{", "Ctx", ":", "ctx", ",", "Command", ":", "command", ",", "}", ",", "nil", "\n", "}" ]
// NewExecRequest creates a new local or remote Exec.
[ "NewExecRequest", "creates", "a", "new", "local", "or", "remote", "Exec", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/exec.go#L78-L104
train
gravitational/teleport
lib/srv/exec.go
Wait
func (e *localExec) Wait() (*ExecResult, error) { if e.Cmd.Process == nil { e.Ctx.Errorf("no process") } // wait for the command to complete, then figure out if the command // successfully exited or if it exited in failure execResult, err := collectLocalStatus(e.Cmd, e.Cmd.Wait()) // emit the result of execution to the audit log emitExecAuditEvent(e.Ctx, e.GetCommand(), execResult, err) return execResult, trace.Wrap(err) }
go
func (e *localExec) Wait() (*ExecResult, error) { if e.Cmd.Process == nil { e.Ctx.Errorf("no process") } // wait for the command to complete, then figure out if the command // successfully exited or if it exited in failure execResult, err := collectLocalStatus(e.Cmd, e.Cmd.Wait()) // emit the result of execution to the audit log emitExecAuditEvent(e.Ctx, e.GetCommand(), execResult, err) return execResult, trace.Wrap(err) }
[ "func", "(", "e", "*", "localExec", ")", "Wait", "(", ")", "(", "*", "ExecResult", ",", "error", ")", "{", "if", "e", ".", "Cmd", ".", "Process", "==", "nil", "{", "e", ".", "Ctx", ".", "Errorf", "(", "\"no process\"", ")", "\n", "}", "\n", "execResult", ",", "err", ":=", "collectLocalStatus", "(", "e", ".", "Cmd", ",", "e", ".", "Cmd", ".", "Wait", "(", ")", ")", "\n", "emitExecAuditEvent", "(", "e", ".", "Ctx", ",", "e", ".", "GetCommand", "(", ")", ",", "execResult", ",", "err", ")", "\n", "return", "execResult", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}" ]
// Wait will block while the command executes.
[ "Wait", "will", "block", "while", "the", "command", "executes", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/exec.go#L175-L188
train
gravitational/teleport
lib/srv/exec.go
Wait
func (r *remoteExec) Wait() (*ExecResult, error) { // block until the command is finished and then figure out if the command // successfully exited or if it exited in failure execResult, err := r.collectRemoteStatus(r.session.Wait()) // emit the result of execution to the audit log emitExecAuditEvent(r.ctx, r.command, execResult, err) return execResult, trace.Wrap(err) }
go
func (r *remoteExec) Wait() (*ExecResult, error) { // block until the command is finished and then figure out if the command // successfully exited or if it exited in failure execResult, err := r.collectRemoteStatus(r.session.Wait()) // emit the result of execution to the audit log emitExecAuditEvent(r.ctx, r.command, execResult, err) return execResult, trace.Wrap(err) }
[ "func", "(", "r", "*", "remoteExec", ")", "Wait", "(", ")", "(", "*", "ExecResult", ",", "error", ")", "{", "execResult", ",", "err", ":=", "r", ".", "collectRemoteStatus", "(", "r", ".", "session", ".", "Wait", "(", ")", ")", "\n", "emitExecAuditEvent", "(", "r", ".", "ctx", ",", "r", ".", "command", ",", "execResult", ",", "err", ")", "\n", "return", "execResult", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}" ]
// Wait will block while the command executes then return the result as well // as emit an event to the Audit Log.
[ "Wait", "will", "block", "while", "the", "command", "executes", "then", "return", "the", "result", "as", "well", "as", "emit", "an", "event", "to", "the", "Audit", "Log", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/exec.go#L448-L457
train
gravitational/teleport
lib/srv/exec.go
parseSecureCopy
func parseSecureCopy(path string) (string, string, bool, error) { parts := strings.Fields(path) if len(parts) == 0 { return "", "", false, trace.BadParameter("no executable found") } // Look for the -t flag, it indicates that an upload occurred. The other // flags do no matter for now. action := events.SCPActionDownload if utils.SliceContainsStr(parts, "-t") { action = events.SCPActionUpload } // Exract the name of the Teleport executable on disk. teleportPath, err := os.Executable() if err != nil { return "", "", false, trace.Wrap(err) } _, teleportBinary := filepath.Split(teleportPath) // Extract the name of the executable that was run. The command was secure // copy if the executable was "scp" or "teleport". _, executable := filepath.Split(parts[0]) switch executable { case teleport.SCP, teleportBinary: return parts[len(parts)-1], action, true, nil default: return "", "", false, nil } }
go
func parseSecureCopy(path string) (string, string, bool, error) { parts := strings.Fields(path) if len(parts) == 0 { return "", "", false, trace.BadParameter("no executable found") } // Look for the -t flag, it indicates that an upload occurred. The other // flags do no matter for now. action := events.SCPActionDownload if utils.SliceContainsStr(parts, "-t") { action = events.SCPActionUpload } // Exract the name of the Teleport executable on disk. teleportPath, err := os.Executable() if err != nil { return "", "", false, trace.Wrap(err) } _, teleportBinary := filepath.Split(teleportPath) // Extract the name of the executable that was run. The command was secure // copy if the executable was "scp" or "teleport". _, executable := filepath.Split(parts[0]) switch executable { case teleport.SCP, teleportBinary: return parts[len(parts)-1], action, true, nil default: return "", "", false, nil } }
[ "func", "parseSecureCopy", "(", "path", "string", ")", "(", "string", ",", "string", ",", "bool", ",", "error", ")", "{", "parts", ":=", "strings", ".", "Fields", "(", "path", ")", "\n", "if", "len", "(", "parts", ")", "==", "0", "{", "return", "\"\"", ",", "\"\"", ",", "false", ",", "trace", ".", "BadParameter", "(", "\"no executable found\"", ")", "\n", "}", "\n", "action", ":=", "events", ".", "SCPActionDownload", "\n", "if", "utils", ".", "SliceContainsStr", "(", "parts", ",", "\"-t\"", ")", "{", "action", "=", "events", ".", "SCPActionUpload", "\n", "}", "\n", "teleportPath", ",", "err", ":=", "os", ".", "Executable", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "\"\"", ",", "false", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "_", ",", "teleportBinary", ":=", "filepath", ".", "Split", "(", "teleportPath", ")", "\n", "_", ",", "executable", ":=", "filepath", ".", "Split", "(", "parts", "[", "0", "]", ")", "\n", "switch", "executable", "{", "case", "teleport", ".", "SCP", ",", "teleportBinary", ":", "return", "parts", "[", "len", "(", "parts", ")", "-", "1", "]", ",", "action", ",", "true", ",", "nil", "\n", "default", ":", "return", "\"\"", ",", "\"\"", ",", "false", ",", "nil", "\n", "}", "\n", "}" ]
// parseSecureCopy will parse a command and return if it's secure copy or not.
[ "parseSecureCopy", "will", "parse", "a", "command", "and", "return", "if", "it", "s", "secure", "copy", "or", "not", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/exec.go#L602-L631
train
gravitational/teleport
lib/client/identity.go
MakeIdentityFile
func MakeIdentityFile(filePath string, key *Key, format IdentityFileFormat, certAuthorities []services.CertAuthority) (err error) { const ( // the files and the dir will be created with these permissions: fileMode = 0600 dirMode = 0700 ) if filePath == "" { return trace.BadParameter("identity location is not specified") } var output io.Writer = os.Stdout switch format { // dump user identity into a single file: case IdentityFormatFile: f, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY, fileMode) if err != nil { return trace.Wrap(err) } output = f defer f.Close() // write key: if _, err = output.Write(key.Priv); err != nil { return trace.Wrap(err) } // append cert: if _, err = output.Write(key.Cert); err != nil { return trace.Wrap(err) } // append trusted host certificate authorities for _, ca := range certAuthorities { for _, publicKey := range ca.GetCheckingKeys() { data, err := sshutils.MarshalAuthorizedHostsFormat(ca.GetClusterName(), publicKey, nil) if err != nil { return trace.Wrap(err) } if _, err = output.Write([]byte(data)); err != nil { return trace.Wrap(err) } if _, err = output.Write([]byte("\n")); err != nil { return trace.Wrap(err) } } } // dump user identity into separate files: case IdentityFormatOpenSSH: keyPath := filePath certPath := keyPath + "-cert.pub" err = ioutil.WriteFile(certPath, key.Cert, fileMode) if err != nil { return trace.Wrap(err) } err = ioutil.WriteFile(keyPath, key.Priv, fileMode) if err != nil { return trace.Wrap(err) } default: return trace.BadParameter("unsupported identity format: %q, use either %q or %q", format, IdentityFormatFile, IdentityFormatOpenSSH) } return nil }
go
func MakeIdentityFile(filePath string, key *Key, format IdentityFileFormat, certAuthorities []services.CertAuthority) (err error) { const ( // the files and the dir will be created with these permissions: fileMode = 0600 dirMode = 0700 ) if filePath == "" { return trace.BadParameter("identity location is not specified") } var output io.Writer = os.Stdout switch format { // dump user identity into a single file: case IdentityFormatFile: f, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY, fileMode) if err != nil { return trace.Wrap(err) } output = f defer f.Close() // write key: if _, err = output.Write(key.Priv); err != nil { return trace.Wrap(err) } // append cert: if _, err = output.Write(key.Cert); err != nil { return trace.Wrap(err) } // append trusted host certificate authorities for _, ca := range certAuthorities { for _, publicKey := range ca.GetCheckingKeys() { data, err := sshutils.MarshalAuthorizedHostsFormat(ca.GetClusterName(), publicKey, nil) if err != nil { return trace.Wrap(err) } if _, err = output.Write([]byte(data)); err != nil { return trace.Wrap(err) } if _, err = output.Write([]byte("\n")); err != nil { return trace.Wrap(err) } } } // dump user identity into separate files: case IdentityFormatOpenSSH: keyPath := filePath certPath := keyPath + "-cert.pub" err = ioutil.WriteFile(certPath, key.Cert, fileMode) if err != nil { return trace.Wrap(err) } err = ioutil.WriteFile(keyPath, key.Priv, fileMode) if err != nil { return trace.Wrap(err) } default: return trace.BadParameter("unsupported identity format: %q, use either %q or %q", format, IdentityFormatFile, IdentityFormatOpenSSH) } return nil }
[ "func", "MakeIdentityFile", "(", "filePath", "string", ",", "key", "*", "Key", ",", "format", "IdentityFileFormat", ",", "certAuthorities", "[", "]", "services", ".", "CertAuthority", ")", "(", "err", "error", ")", "{", "const", "(", "fileMode", "=", "0600", "\n", "dirMode", "=", "0700", "\n", ")", "\n", "if", "filePath", "==", "\"\"", "{", "return", "trace", ".", "BadParameter", "(", "\"identity location is not specified\"", ")", "\n", "}", "\n", "var", "output", "io", ".", "Writer", "=", "os", ".", "Stdout", "\n", "switch", "format", "{", "case", "IdentityFormatFile", ":", "f", ",", "err", ":=", "os", ".", "OpenFile", "(", "filePath", ",", "os", ".", "O_CREATE", "|", "os", ".", "O_WRONLY", ",", "fileMode", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "output", "=", "f", "\n", "defer", "f", ".", "Close", "(", ")", "\n", "if", "_", ",", "err", "=", "output", ".", "Write", "(", "key", ".", "Priv", ")", ";", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "_", ",", "err", "=", "output", ".", "Write", "(", "key", ".", "Cert", ")", ";", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "for", "_", ",", "ca", ":=", "range", "certAuthorities", "{", "for", "_", ",", "publicKey", ":=", "range", "ca", ".", "GetCheckingKeys", "(", ")", "{", "data", ",", "err", ":=", "sshutils", ".", "MarshalAuthorizedHostsFormat", "(", "ca", ".", "GetClusterName", "(", ")", ",", "publicKey", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "_", ",", "err", "=", "output", ".", "Write", "(", "[", "]", "byte", "(", "data", ")", ")", ";", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "_", ",", "err", "=", "output", ".", "Write", "(", "[", "]", "byte", "(", "\"\\n\"", ")", ")", ";", "\\n", "err", "!=", "nil", "\n", "}", "\n", "}", "\n", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "case", "IdentityFormatOpenSSH", ":", "keyPath", ":=", "filePath", "\n", "certPath", ":=", "keyPath", "+", "\"-cert.pub\"", "\n", "err", "=", "ioutil", ".", "WriteFile", "(", "certPath", ",", "key", ".", "Cert", ",", "fileMode", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "err", "=", "ioutil", ".", "WriteFile", "(", "keyPath", ",", "key", ".", "Priv", ",", "fileMode", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n", "default", ":", "return", "trace", ".", "BadParameter", "(", "\"unsupported identity format: %q, use either %q or %q\"", ",", "format", ",", "IdentityFormatFile", ",", "IdentityFormatOpenSSH", ")", "\n", "\n", "}" ]
// MakeIdentityFile takes a username + their credentials and saves them to disk // in a specified format
[ "MakeIdentityFile", "takes", "a", "username", "+", "their", "credentials", "and", "saves", "them", "to", "disk", "in", "a", "specified", "format" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/identity.go#L62-L127
train
gravitational/teleport
lib/events/filesessions/fileuploader.go
CheckAndSetDefaults
func (s *Config) CheckAndSetDefaults() error { if s.Directory == "" { return trace.BadParameter("missing parameter Directory") } if !utils.IsDir(s.Directory) { return trace.BadParameter("path %q does not exist or is not a directory", s.Directory) } return nil }
go
func (s *Config) CheckAndSetDefaults() error { if s.Directory == "" { return trace.BadParameter("missing parameter Directory") } if !utils.IsDir(s.Directory) { return trace.BadParameter("path %q does not exist or is not a directory", s.Directory) } return nil }
[ "func", "(", "s", "*", "Config", ")", "CheckAndSetDefaults", "(", ")", "error", "{", "if", "s", ".", "Directory", "==", "\"\"", "{", "return", "trace", ".", "BadParameter", "(", "\"missing parameter Directory\"", ")", "\n", "}", "\n", "if", "!", "utils", ".", "IsDir", "(", "s", ".", "Directory", ")", "{", "return", "trace", ".", "BadParameter", "(", "\"path %q does not exist or is not a directory\"", ",", "s", ".", "Directory", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CheckAndSetDefaults checks and sets default values of file handler config
[ "CheckAndSetDefaults", "checks", "and", "sets", "default", "values", "of", "file", "handler", "config" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/filesessions/fileuploader.go#L41-L49
train
gravitational/teleport
lib/events/filesessions/fileuploader.go
NewHandler
func NewHandler(cfg Config) (*Handler, error) { if err := cfg.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } h := &Handler{ Entry: log.WithFields(log.Fields{ trace.Component: teleport.Component(teleport.SchemeFile), }), Config: cfg, } return h, nil }
go
func NewHandler(cfg Config) (*Handler, error) { if err := cfg.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } h := &Handler{ Entry: log.WithFields(log.Fields{ trace.Component: teleport.Component(teleport.SchemeFile), }), Config: cfg, } return h, nil }
[ "func", "NewHandler", "(", "cfg", "Config", ")", "(", "*", "Handler", ",", "error", ")", "{", "if", "err", ":=", "cfg", ".", "CheckAndSetDefaults", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "h", ":=", "&", "Handler", "{", "Entry", ":", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "trace", ".", "Component", ":", "teleport", ".", "Component", "(", "teleport", ".", "SchemeFile", ")", ",", "}", ")", ",", "Config", ":", "cfg", ",", "}", "\n", "return", "h", ",", "nil", "\n", "}" ]
// NewHandler returns new file sessions handler
[ "NewHandler", "returns", "new", "file", "sessions", "handler" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/filesessions/fileuploader.go#L52-L64
train
gravitational/teleport
lib/events/filesessions/fileuploader.go
Download
func (l *Handler) Download(ctx context.Context, sessionID session.ID, writer io.WriterAt) error { path := l.path(sessionID) _, err := os.Stat(filepath.Dir(path)) f, err := os.Open(path) if err != nil { return trace.ConvertSystemError(err) } defer f.Close() _, err = io.Copy(writer.(io.Writer), f) if err != nil { return trace.Wrap(err) } return nil }
go
func (l *Handler) Download(ctx context.Context, sessionID session.ID, writer io.WriterAt) error { path := l.path(sessionID) _, err := os.Stat(filepath.Dir(path)) f, err := os.Open(path) if err != nil { return trace.ConvertSystemError(err) } defer f.Close() _, err = io.Copy(writer.(io.Writer), f) if err != nil { return trace.Wrap(err) } return nil }
[ "func", "(", "l", "*", "Handler", ")", "Download", "(", "ctx", "context", ".", "Context", ",", "sessionID", "session", ".", "ID", ",", "writer", "io", ".", "WriterAt", ")", "error", "{", "path", ":=", "l", ".", "path", "(", "sessionID", ")", "\n", "_", ",", "err", ":=", "os", ".", "Stat", "(", "filepath", ".", "Dir", "(", "path", ")", ")", "\n", "f", ",", "err", ":=", "os", ".", "Open", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "ConvertSystemError", "(", "err", ")", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n", "_", ",", "err", "=", "io", ".", "Copy", "(", "writer", ".", "(", "io", ".", "Writer", ")", ",", "f", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Download downloads session recording from storage, in case of file handler reads the // file from local directory
[ "Download", "downloads", "session", "recording", "from", "storage", "in", "case", "of", "file", "handler", "reads", "the", "file", "from", "local", "directory" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/filesessions/fileuploader.go#L82-L95
train
gravitational/teleport
lib/events/filesessions/fileuploader.go
Upload
func (l *Handler) Upload(ctx context.Context, sessionID session.ID, reader io.Reader) (string, error) { path := l.path(sessionID) f, err := os.Create(path) if err != nil { return "", trace.ConvertSystemError(err) } defer f.Close() _, err = io.Copy(f, reader) if err != nil { return "", trace.Wrap(err) } return fmt.Sprintf("%v://%v", teleport.SchemeFile, path), nil }
go
func (l *Handler) Upload(ctx context.Context, sessionID session.ID, reader io.Reader) (string, error) { path := l.path(sessionID) f, err := os.Create(path) if err != nil { return "", trace.ConvertSystemError(err) } defer f.Close() _, err = io.Copy(f, reader) if err != nil { return "", trace.Wrap(err) } return fmt.Sprintf("%v://%v", teleport.SchemeFile, path), nil }
[ "func", "(", "l", "*", "Handler", ")", "Upload", "(", "ctx", "context", ".", "Context", ",", "sessionID", "session", ".", "ID", ",", "reader", "io", ".", "Reader", ")", "(", "string", ",", "error", ")", "{", "path", ":=", "l", ".", "path", "(", "sessionID", ")", "\n", "f", ",", "err", ":=", "os", ".", "Create", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "trace", ".", "ConvertSystemError", "(", "err", ")", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n", "_", ",", "err", "=", "io", ".", "Copy", "(", "f", ",", "reader", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"%v://%v\"", ",", "teleport", ".", "SchemeFile", ",", "path", ")", ",", "nil", "\n", "}" ]
// Upload uploads session recording to file storage, in case of file handler, // writes the file to local directory
[ "Upload", "uploads", "session", "recording", "to", "file", "storage", "in", "case", "of", "file", "handler", "writes", "the", "file", "to", "local", "directory" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/filesessions/fileuploader.go#L99-L111
train
gravitational/teleport
tool/tctl/common/token_command.go
List
func (c *TokenCommand) List(client auth.ClientI) error { tokens, err := client.GetTokens() if err != nil { return trace.Wrap(err) } if len(tokens) == 0 { fmt.Println("No active tokens found.") return nil } // Sort by expire time. sort.Slice(tokens, func(i, j int) bool { return tokens[i].Expiry().Unix() < tokens[j].Expiry().Unix() }) if c.format == teleport.Text { tokensView := func() string { table := asciitable.MakeTable([]string{"Token", "Type", "Expiry Time (UTC)"}) for _, t := range tokens { expiry := "never" if t.Expiry().Unix() > 0 { expiry = t.Expiry().Format(time.RFC822) } table.AddRow([]string{t.GetName(), t.GetRoles().String(), expiry}) } return table.AsBuffer().String() } fmt.Printf(tokensView()) } else { data, err := json.MarshalIndent(tokens, "", " ") if err != nil { return trace.Wrap(err, "failed to marshal tokens") } fmt.Printf(string(data)) } return nil }
go
func (c *TokenCommand) List(client auth.ClientI) error { tokens, err := client.GetTokens() if err != nil { return trace.Wrap(err) } if len(tokens) == 0 { fmt.Println("No active tokens found.") return nil } // Sort by expire time. sort.Slice(tokens, func(i, j int) bool { return tokens[i].Expiry().Unix() < tokens[j].Expiry().Unix() }) if c.format == teleport.Text { tokensView := func() string { table := asciitable.MakeTable([]string{"Token", "Type", "Expiry Time (UTC)"}) for _, t := range tokens { expiry := "never" if t.Expiry().Unix() > 0 { expiry = t.Expiry().Format(time.RFC822) } table.AddRow([]string{t.GetName(), t.GetRoles().String(), expiry}) } return table.AsBuffer().String() } fmt.Printf(tokensView()) } else { data, err := json.MarshalIndent(tokens, "", " ") if err != nil { return trace.Wrap(err, "failed to marshal tokens") } fmt.Printf(string(data)) } return nil }
[ "func", "(", "c", "*", "TokenCommand", ")", "List", "(", "client", "auth", ".", "ClientI", ")", "error", "{", "tokens", ",", "err", ":=", "client", ".", "GetTokens", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "len", "(", "tokens", ")", "==", "0", "{", "fmt", ".", "Println", "(", "\"No active tokens found.\"", ")", "\n", "return", "nil", "\n", "}", "\n", "sort", ".", "Slice", "(", "tokens", ",", "func", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "tokens", "[", "i", "]", ".", "Expiry", "(", ")", ".", "Unix", "(", ")", "<", "tokens", "[", "j", "]", ".", "Expiry", "(", ")", ".", "Unix", "(", ")", "}", ")", "\n", "if", "c", ".", "format", "==", "teleport", ".", "Text", "{", "tokensView", ":=", "func", "(", ")", "string", "{", "table", ":=", "asciitable", ".", "MakeTable", "(", "[", "]", "string", "{", "\"Token\"", ",", "\"Type\"", ",", "\"Expiry Time (UTC)\"", "}", ")", "\n", "for", "_", ",", "t", ":=", "range", "tokens", "{", "expiry", ":=", "\"never\"", "\n", "if", "t", ".", "Expiry", "(", ")", ".", "Unix", "(", ")", ">", "0", "{", "expiry", "=", "t", ".", "Expiry", "(", ")", ".", "Format", "(", "time", ".", "RFC822", ")", "\n", "}", "\n", "table", ".", "AddRow", "(", "[", "]", "string", "{", "t", ".", "GetName", "(", ")", ",", "t", ".", "GetRoles", "(", ")", ".", "String", "(", ")", ",", "expiry", "}", ")", "\n", "}", "\n", "return", "table", ".", "AsBuffer", "(", ")", ".", "String", "(", ")", "\n", "}", "\n", "fmt", ".", "Printf", "(", "tokensView", "(", ")", ")", "\n", "}", "else", "{", "data", ",", "err", ":=", "json", ".", "MarshalIndent", "(", "tokens", ",", "\"\"", ",", "\" \"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ",", "\"failed to marshal tokens\"", ")", "\n", "}", "\n", "fmt", ".", "Printf", "(", "string", "(", "data", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// List is called to execute "tokens ls" command.
[ "List", "is", "called", "to", "execute", "tokens", "ls", "command", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/token_command.go#L173-L207
train