repo
stringlengths
5
67
sha
stringlengths
40
40
path
stringlengths
4
234
url
stringlengths
85
339
language
stringclasses
6 values
split
stringclasses
3 values
doc
stringlengths
3
51.2k
sign
stringlengths
5
8.01k
problem
stringlengths
13
51.2k
output
stringlengths
0
3.87M
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/kube/client/kubeclient.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/client/kubeclient.go#L142-L163
go
train
// kubeconfigFromEnv extracts location of kubeconfig from the environment.
func kubeconfigFromEnv() string
// kubeconfigFromEnv extracts location of kubeconfig from the environment. func kubeconfigFromEnv() string
{ kubeconfig := os.Getenv(teleport.EnvKubeConfig) // The KUBECONFIG environment variable is a list. On Windows it's // semicolon-delimited. On Linux and macOS it's colon-delimited. var parts []string switch runtime.GOOS { case teleport.WindowsOS: parts = strings.Split(kubeconfig, ";") default: parts = stri...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/filelog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/filelog.go#L60-L86
go
train
// CheckAndSetDefaults checks and sets config defaults
func (cfg *FileLogConfig) CheckAndSetDefaults() error
// CheckAndSetDefaults checks and sets config defaults func (cfg *FileLogConfig) CheckAndSetDefaults() error
{ if cfg.Dir == "" { return trace.BadParameter("missing parameter Dir") } if !utils.IsDir(cfg.Dir) { return trace.BadParameter("path %q does not exist or is not a directory", cfg.Dir) } if cfg.SymlinkDir == "" { cfg.SymlinkDir = cfg.Dir } if !utils.IsDir(cfg.SymlinkDir) { return trace.BadParameter("path...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/filelog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/filelog.go#L89-L100
go
train
// NewFileLog returns a new instance of a file log
func NewFileLog(cfg FileLogConfig) (*FileLog, error)
// NewFileLog returns a new instance of a file log func NewFileLog(cfg FileLogConfig) (*FileLog, error)
{ if err := cfg.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } f := &FileLog{ FileLogConfig: cfg, Entry: log.WithFields(log.Fields{ trace.Component: teleport.ComponentAuditLog, }), } return f, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/filelog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/filelog.go#L117-L137
go
train
// EmitAuditEvent adds a new event to the log. Part of auth.IFileLog interface.
func (l *FileLog) EmitAuditEvent(event Event, fields EventFields) error
// EmitAuditEvent adds a new event to the log. Part of auth.IFileLog interface. func (l *FileLog) EmitAuditEvent(event Event, fields EventFields) error
{ // see if the log needs to be rotated err := l.rotateLog() if err != nil { log.Error(err) } err = UpdateEventFields(event, fields, l.Clock, l.UIDGenerator) if err != nil { log.Error(err) } // line is the text to be logged line, err := json.Marshal(fields) if err != nil { return trace.Wrap(err) } //...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/filelog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/filelog.go#L141-L181
go
train
// SearchEvents finds events. Results show up sorted by date (newest first), // limit is used when set to value > 0
func (l *FileLog) SearchEvents(fromUTC, toUTC time.Time, query string, limit int) ([]EventFields, error)
// SearchEvents finds events. Results show up sorted by date (newest first), // limit is used when set to value > 0 func (l *FileLog) SearchEvents(fromUTC, toUTC time.Time, query string, limit int) ([]EventFields, error)
{ l.Debugf("SearchEvents(%v, %v, query=%v, limit=%v)", fromUTC, toUTC, query, limit) if limit <= 0 { limit = defaults.EventsIterationLimit } if limit > defaults.EventsMaxIterationLimit { return nil, trace.BadParameter("limit %v exceeds max iteration limit %v", limit, defaults.MaxIterationLimit) } // how many...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/filelog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/filelog.go#L184-L226
go
train
// SearchSessionEvents searches for session related events. Used to find completed sessions.
func (l *FileLog) SearchSessionEvents(fromUTC, toUTC time.Time, limit int) ([]EventFields, error)
// SearchSessionEvents searches for session related events. Used to find completed sessions. func (l *FileLog) SearchSessionEvents(fromUTC, toUTC time.Time, limit int) ([]EventFields, error)
{ l.Debugf("SearchSessionEvents(%v, %v, %v)", fromUTC, toUTC, limit) // only search for specific event types query := url.Values{} query[EventType] = []string{ SessionStartEvent, SessionEndEvent, } // because of the limit and distributed nature of auth server event // logs, some events can be fetched with...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/filelog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/filelog.go#L230-L240
go
train
// Close closes the audit log, which inluces closing all file handles and releasing // all session loggers
func (l *FileLog) Close() error
// Close closes the audit log, which inluces closing all file handles and releasing // all session loggers func (l *FileLog) Close() error
{ l.Lock() defer l.Unlock() var err error if l.file != nil { err = l.file.Close() l.file = nil } return err }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/filelog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/filelog.go#L292-L342
go
train
// rotateLog checks if the current log file is older than a given duration, // and if it is, closes it and opens a new one.
func (l *FileLog) rotateLog() (err error)
// rotateLog checks if the current log file is older than a given duration, // and if it is, closes it and opens a new one. func (l *FileLog) rotateLog() (err error)
{ l.Lock() defer l.Unlock() // determine the timestamp for the current log file fileTime := l.Clock.Now().In(time.UTC) // truncate time to the resolution of one day, cutting at the day end boundary fileTime = time.Date(fileTime.Year(), fileTime.Month(), fileTime.Day(), 0, 0, 0, 0, time.UTC) logFilename := fi...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/filelog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/filelog.go#L346-L398
go
train
// matchingFiles returns files matching the time restrictions of the query // across multiple auth servers, returns a list of file names
func (l *FileLog) matchingFiles(fromUTC, toUTC time.Time) ([]eventFile, error)
// matchingFiles returns files matching the time restrictions of the query // across multiple auth servers, returns a list of file names func (l *FileLog) matchingFiles(fromUTC, toUTC time.Time) ([]eventFile, error)
{ var dirs []string var err error if l.SearchDirs != nil { dirs, err = l.SearchDirs() if err != nil { return nil, trace.Wrap(err) } } else { dirs = []string{l.Dir} } var filtered []eventFile for _, dir := range dirs { // scan the log directory: df, err := os.Open(dir) if err != nil { return...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/filelog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/filelog.go#L401-L404
go
train
// parseFileTime parses file's timestamp encoded into filename
func parseFileTime(filename string) (time.Time, error)
// parseFileTime parses file's timestamp encoded into filename func parseFileTime(filename string) (time.Time, error)
{ base := strings.TrimSuffix(filename, filepath.Ext(filename)) return time.Parse(defaults.AuditLogTimeFormat, base) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/filelog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/filelog.go#L410-L464
go
train
// findInFile scans a given log file and returns events that fit the criteria // This simplistic implementation ONLY SEARCHES FOR EVENT TYPE(s) // // You can pass multiple types like "event=session.start&event=session.end"
func (l *FileLog) findInFile(fn string, query url.Values, total *int, limit int) ([]EventFields, error)
// findInFile scans a given log file and returns events that fit the criteria // This simplistic implementation ONLY SEARCHES FOR EVENT TYPE(s) // // You can pass multiple types like "event=session.start&event=session.end" func (l *FileLog) findInFile(fn string, query url.Values, total *int, limit int) ([]EventFields, ...
{ l.Debugf("Called findInFile(%s, %v).", fn, query) retval := make([]EventFields, 0) eventFilter, ok := query[EventType] if !ok && len(query) > 0 { return nil, nil } doFilter := len(eventFilter) > 0 // open the log file: lf, err := os.OpenFile(fn, os.O_RDONLY, 0) if err != nil { return nil, trace.Wrap(e...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/filelog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/filelog.go#L501-L511
go
train
// getTime converts json time to string
func getTime(v interface{}) time.Time
// getTime converts json time to string func getTime(v interface{}) time.Time
{ sval, ok := v.(string) if !ok { return time.Time{} } t, err := time.Parse(time.RFC3339, sval) if err != nil { return time.Time{} } return t }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/equals.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/equals.go#L33-L43
go
train
// StringMapsEqual returns true if two strings maps are equal
func StringMapsEqual(a, b map[string]string) bool
// StringMapsEqual returns true if two strings maps are equal func StringMapsEqual(a, b map[string]string) bool
{ if len(a) != len(b) { return false } for key := range a { if a[key] != b[key] { return false } } return true }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/equals.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/equals.go#L59-L69
go
train
// StringMapSlicesEqual returns true if two maps of string slices are equal
func StringMapSlicesEqual(a, b map[string][]string) bool
// StringMapSlicesEqual returns true if two maps of string slices are equal func StringMapSlicesEqual(a, b map[string][]string) bool
{ if len(a) != len(b) { return false } for key := range a { if !StringSlicesEqual(a[key], b[key]) { return false } } return true }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/saml.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/saml.go#L110-L120
go
train
// NewSAMLConnector returns a new SAMLConnector based off a name and SAMLConnectorSpecV2.
func NewSAMLConnector(name string, spec SAMLConnectorSpecV2) SAMLConnector
// NewSAMLConnector returns a new SAMLConnector based off a name and SAMLConnectorSpecV2. func NewSAMLConnector(name string, spec SAMLConnectorSpecV2) SAMLConnector
{ return &SAMLConnectorV2{ Kind: KindSAMLConnector, Version: V2, Metadata: Metadata{ Name: name, Namespace: defaults.Namespace, }, Spec: spec, } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/saml.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/saml.go#L155-L193
go
train
// UnmarshalSAMLConnector unmarshals connector from
func (*TeleportSAMLConnectorMarshaler) UnmarshalSAMLConnector(bytes []byte, opts ...MarshalOption) (SAMLConnector, error)
// UnmarshalSAMLConnector unmarshals connector from func (*TeleportSAMLConnectorMarshaler) UnmarshalSAMLConnector(bytes []byte, opts ...MarshalOption) (SAMLConnector, error)
{ cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } var h ResourceHeader err = utils.FastUnmarshal(bytes, &h) if err != nil { return nil, trace.Wrap(err) } switch h.Version { case V2: var c SAMLConnectorV2 if cfg.SkipValidation { if err := utils.FastUnmarshal(bytes, &c)...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/saml.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/saml.go#L196-L223
go
train
// MarshalUser marshals SAML connector into JSON
func (*TeleportSAMLConnectorMarshaler) MarshalSAMLConnector(c SAMLConnector, opts ...MarshalOption) ([]byte, error)
// MarshalUser marshals SAML connector into JSON func (*TeleportSAMLConnectorMarshaler) MarshalSAMLConnector(c SAMLConnector, opts ...MarshalOption) ([]byte, error)
{ cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } type connv2 interface { V2() *SAMLConnectorV2 } version := cfg.GetVersion() switch version { case V2: v, ok := c.(connv2) if !ok { return nil, trace.BadParameter("don't know how to marshal %v", V2) } v2 := v.V2() ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/saml.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/saml.go#L340-L389
go
train
// Equals returns true if the connectors are identical
func (o *SAMLConnectorV2) Equals(other SAMLConnector) bool
// Equals returns true if the connectors are identical func (o *SAMLConnectorV2) Equals(other SAMLConnector) bool
{ if o.GetName() != other.GetName() { return false } if o.GetCert() != other.GetCert() { return false } if o.GetAudience() != other.GetAudience() { return false } if o.GetEntityDescriptor() != other.GetEntityDescriptor() { return false } if o.Expiry() != other.Expiry() { return false } if o.GetIss...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/saml.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/saml.go#L407-L409
go
train
// SetExpiry sets expiry time for the object
func (o *SAMLConnectorV2) SetExpiry(expires time.Time)
// SetExpiry sets expiry time for the object func (o *SAMLConnectorV2) SetExpiry(expires time.Time)
{ o.Metadata.SetExpiry(expires) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/saml.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/saml.go#L442-L447
go
train
// Display - Friendly name for this provider.
func (o *SAMLConnectorV2) GetDisplay() string
// Display - Friendly name for this provider. func (o *SAMLConnectorV2) GetDisplay() string
{ if o.Spec.Display != "" { return o.Spec.Display } return o.GetName() }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/saml.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/saml.go#L470-L476
go
train
// GetAttributes returns list of attributes expected by mappings
func (o *SAMLConnectorV2) GetAttributes() []string
// GetAttributes returns list of attributes expected by mappings func (o *SAMLConnectorV2) GetAttributes() []string
{ var out []string for _, mapping := range o.Spec.AttributesToRoles { out = append(out, mapping.Name) } return utils.Deduplicate(out) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/saml.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/saml.go#L479-L508
go
train
// MapClaims maps SAML attributes to roles
func (o *SAMLConnectorV2) MapAttributes(assertionInfo saml2.AssertionInfo) []string
// MapClaims maps SAML attributes to roles func (o *SAMLConnectorV2) MapAttributes(assertionInfo saml2.AssertionInfo) []string
{ var roles []string for _, mapping := range o.Spec.AttributesToRoles { for _, attr := range assertionInfo.Values { if attr.Name != mapping.Name { continue } mappingLoop: for _, value := range attr.Values { for _, role := range mapping.Roles { outRole, err := utils.ReplaceRegexp(mapping.Val...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/saml.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/saml.go#L515-L527
go
train
// executeSAMLStringTemplate takes a raw template string and a map of // assertions to execute a template and generate output. Because the data // structure used to execute the template is a map, the format of the raw // string is expected to be {{index . "key"}}. See // https://golang.org/pkg/text/template/ for more d...
func executeSAMLStringTemplate(raw string, assertion map[string]string) (string, error)
// executeSAMLStringTemplate takes a raw template string and a map of // assertions to execute a template and generate output. Because the data // structure used to execute the template is a map, the format of the raw // string is expected to be {{index . "key"}}. See // https://golang.org/pkg/text/template/ for more d...
{ tmpl, err := template.New("dynamic-roles").Parse(raw) if err != nil { return "", trace.Wrap(err) } var buf bytes.Buffer err = tmpl.Execute(&buf, assertion) if err != nil { return "", trace.Wrap(err) } return buf.String(), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/saml.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/saml.go#L534-L552
go
train
// executeSAMLStringTemplate takes raw template strings and a map of // assertions to execute templates and generate a slice of output. Because the // data structure used to execute the template is a map, the format of each raw // string is expected to be {{index . "key"}}. See // https://golang.org/pkg/text/template/ ...
func executeSAMLSliceTemplate(raw []string, assertion map[string]string) ([]string, error)
// executeSAMLStringTemplate takes raw template strings and a map of // assertions to execute templates and generate a slice of output. Because the // data structure used to execute the template is a map, the format of each raw // string is expected to be {{index . "key"}}. See // https://golang.org/pkg/text/template/ ...
{ var sl []string for _, v := range raw { tmpl, err := template.New("dynamic-roles").Parse(v) if err != nil { return nil, trace.Wrap(err) } var buf bytes.Buffer err = tmpl.Execute(&buf, assertion) if err != nil { return nil, trace.Wrap(err) } sl = append(sl, buf.String()) } return sl, nil ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/saml.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/saml.go#L555-L696
go
train
// GetServiceProvider initialises service provider spec from settings
func (o *SAMLConnectorV2) GetServiceProvider(clock clockwork.Clock) (*saml2.SAMLServiceProvider, error)
// GetServiceProvider initialises service provider spec from settings func (o *SAMLConnectorV2) GetServiceProvider(clock clockwork.Clock) (*saml2.SAMLServiceProvider, error)
{ if o.Metadata.Name == "" { return nil, trace.BadParameter("ID: missing connector name, name your connector to refer to internally e.g. okta1") } if o.Metadata.Name == teleport.Local { return nil, trace.BadParameter("ID: invalid connector name %v is a reserved name", teleport.Local) } if o.Spec.AssertionCons...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/saml.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/saml.go#L792-L798
go
train
// GetAttributeNames returns a list of claim names from the claim values
func GetAttributeNames(attributes map[string]types.Attribute) []string
// GetAttributeNames returns a list of claim names from the claim values func GetAttributeNames(attributes map[string]types.Attribute) []string
{ var out []string for _, attr := range attributes { out = append(out, attr.Name) } return out }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/saml.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/saml.go#L853-L865
go
train
// buildAssertionMap takes an saml2.AssertionInfo and builds a friendly map // that can be used to access assertion/value pairs. If multiple values are // returned for an assertion, they are joined into a string by ",".
func buildAssertionMap(assertionInfo saml2.AssertionInfo) map[string]string
// buildAssertionMap takes an saml2.AssertionInfo and builds a friendly map // that can be used to access assertion/value pairs. If multiple values are // returned for an assertion, they are joined into a string by ",". func buildAssertionMap(assertionInfo saml2.AssertionInfo) map[string]string
{ assertionMap := make(map[string]string) for _, assr := range assertionInfo.Values { var vals []string for _, v := range assr.Values { vals = append(vals, v.Value) } assertionMap[assr.Name] = strings.Join(vals, ",") } return assertionMap }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/presence.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/presence.go#L159-L167
go
train
// NewNamespace returns new namespace
func NewNamespace(name string) Namespace
// NewNamespace returns new namespace func NewNamespace(name string) Namespace
{ return Namespace{ Kind: KindNamespace, Version: V2, Metadata: Metadata{ Name: name, }, } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/resource.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/resource.go#L254-L258
go
train
// AddOptions adds marshal options and returns a new copy
func AddOptions(opts []MarshalOption, add ...MarshalOption) []MarshalOption
// AddOptions adds marshal options and returns a new copy func AddOptions(opts []MarshalOption, add ...MarshalOption) []MarshalOption
{ out := make([]MarshalOption, len(opts), len(opts)+len(add)) copy(out, opts) return append(opts, add...) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/resource.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/resource.go#L261-L266
go
train
// WithResourceID assigns ID to the resource
func WithResourceID(id int64) MarshalOption
// WithResourceID assigns ID to the resource func WithResourceID(id int64) MarshalOption
{ return func(c *MarshalConfig) error { c.ID = id return nil } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/resource.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/resource.go#L269-L274
go
train
// WithExpires assigns expiry value
func WithExpires(expires time.Time) MarshalOption
// WithExpires assigns expiry value func WithExpires(expires time.Time) MarshalOption
{ return func(c *MarshalConfig) error { c.Expires = expires return nil } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/resource.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/resource.go#L280-L290
go
train
// WithVersion sets marshal version
func WithVersion(v string) MarshalOption
// WithVersion sets marshal version func WithVersion(v string) MarshalOption
{ return func(c *MarshalConfig) error { switch v { case V1, V2: c.Version = v return nil default: return trace.BadParameter("version '%v' is not supported", v) } } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/resource.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/resource.go#L389-L391
go
train
// SetExpiry sets object expiry
func (h *ResourceHeader) SetExpiry(t time.Time)
// SetExpiry sets object expiry func (h *ResourceHeader) SetExpiry(t time.Time)
{ h.Metadata.SetExpiry(t) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/resource.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/resource.go#L394-L396
go
train
// SetTTL sets Expires header using current clock
func (h *ResourceHeader) SetTTL(clock clockwork.Clock, ttl time.Duration)
// SetTTL sets Expires header using current clock func (h *ResourceHeader) SetTTL(clock clockwork.Clock, ttl time.Duration)
{ h.Metadata.SetTTL(clock, ttl) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/resource.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/resource.go#L419-L428
go
train
// UnmarshalJSON unmarshals header and captures raw state
func (u *UnknownResource) UnmarshalJSON(raw []byte) error
// UnmarshalJSON unmarshals header and captures raw state func (u *UnknownResource) UnmarshalJSON(raw []byte) error
{ var h ResourceHeader if err := json.Unmarshal(raw, &h); err != nil { return trace.Wrap(err) } u.Raw = make([]byte, len(raw)) u.ResourceHeader = h copy(u.Raw, raw) return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/resource.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/resource.go#L489-L494
go
train
// Expires returns object expiry setting.
func (m *Metadata) Expiry() time.Time
// Expires returns object expiry setting. func (m *Metadata) Expiry() time.Time
{ if m.Expires == nil { return time.Time{} } return *m.Expires }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/resource.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/resource.go#L497-L500
go
train
// SetTTL sets Expires header using realtime clock
func (m *Metadata) SetTTL(clock clockwork.Clock, ttl time.Duration)
// SetTTL sets Expires header using realtime clock func (m *Metadata) SetTTL(clock clockwork.Clock, ttl time.Duration)
{ expireTime := clock.Now().UTC().Add(ttl) m.Expires = &expireTime }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/resource.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/resource.go#L503-L517
go
train
// CheckAndSetDefaults checks validity of all parameters and sets defaults
func (m *Metadata) CheckAndSetDefaults() error
// CheckAndSetDefaults checks validity of all parameters and sets defaults func (m *Metadata) CheckAndSetDefaults() error
{ if m.Name == "" { return trace.BadParameter("missing parameter Name") } if m.Namespace == "" { m.Namespace = defaults.Namespace } // adjust expires time to utc if it's set if m.Expires != nil { utils.UTC(m.Expires) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/resource.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/resource.go#L520-L557
go
train
// ParseShortcut parses resource shortcut
func ParseShortcut(in string) (string, error)
// ParseShortcut parses resource shortcut func ParseShortcut(in string) (string, error)
{ if in == "" { return "", trace.BadParameter("missing resource name") } switch strings.ToLower(in) { case "role", "roles": return KindRole, nil case "namespaces", "ns": return KindNamespace, nil case "auth_servers", "auth": return KindAuthServer, nil case "proxies": return KindProxy, nil case "nodes...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/resource.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/resource.go#L560-L580
go
train
// ParseRef parses resource reference eg daemonsets/ds1
func ParseRef(ref string) (*Ref, error)
// ParseRef parses resource reference eg daemonsets/ds1 func ParseRef(ref string) (*Ref, error)
{ if ref == "" { return nil, trace.BadParameter("missing value") } parts := strings.FieldsFunc(ref, isDelimiter) switch len(parts) { case 1: shortcut, err := ParseShortcut(parts[0]) if err != nil { return nil, trace.Wrap(err) } return &Ref{Kind: shortcut}, nil case 2: shortcut, err := ParseShortcu...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/parse/parse.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/parse/parse.go#L33-L61
go
train
// IsRoleVariable checks if the passed in string matches the variable pattern // {{external.foo}} or {{internal.bar}}. If it does, it returns the variable // prefix and the variable name. In the previous example this would be // "external" or "internal" for the variable prefix and "foo" or "bar" for the // variable nam...
func IsRoleVariable(variable string) (string, string, error)
// IsRoleVariable checks if the passed in string matches the variable pattern // {{external.foo}} or {{internal.bar}}. If it does, it returns the variable // prefix and the variable name. In the previous example this would be // "external" or "internal" for the variable prefix and "foo" or "bar" for the // variable nam...
{ // time whitespace around string if it exists variable = strings.TrimSpace(variable) // strip {{ and }} from the start and end of the variable if !strings.HasPrefix(variable, "{{") || !strings.HasSuffix(variable, "}}") { return "", "", trace.NotFound("no variable found: %v", variable) } variable = variable[...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/parse/parse.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/parse/parse.go#L64-L105
go
train
// walk will walk the ast tree and gather all the variable parts into a slice and return it.
func walk(node ast.Node) ([]string, error)
// walk will walk the ast tree and gather all the variable parts into a slice and return it. func walk(node ast.Node) ([]string, error)
{ var l []string switch n := node.(type) { case *ast.IndexExpr: ret, err := walk(n.X) if err != nil { return nil, err } l = append(l, ret...) ret, err = walk(n.Index) if err != nil { return nil, err } l = append(l, ret...) case *ast.SelectorExpr: ret, err := walk(n.X) if err != nil { ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/linking.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/linking.go#L79-L121
go
train
// ParseWebLinks partially implements RFC 8288 parsing, enough to support // GitHub pagination links. See https://tools.ietf.org/html/rfc8288 for more // details on Web Linking and https://github.com/google/go-github for the API // client that this function was original extracted from. // // Link headers typically look...
func ParseWebLinks(response *http.Response) WebLinks
// ParseWebLinks partially implements RFC 8288 parsing, enough to support // GitHub pagination links. See https://tools.ietf.org/html/rfc8288 for more // details on Web Linking and https://github.com/google/go-github for the API // client that this function was original extracted from. // // Link headers typically look...
{ wls := WebLinks{} if links, ok := response.Header["Link"]; ok && len(links) > 0 { for _, lnk := range links { for _, link := range strings.Split(lnk, ",") { segments := strings.Split(strings.TrimSpace(link), ";") // link must at least have href and rel if len(segments) < 2 { continue } ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/auditlog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/auditlog.go#L197-L230
go
train
// CheckAndSetDefaults checks and sets defaults
func (a *AuditLogConfig) CheckAndSetDefaults() error
// CheckAndSetDefaults checks and sets defaults func (a *AuditLogConfig) CheckAndSetDefaults() error
{ if a.DataDir == "" { return trace.BadParameter("missing parameter DataDir") } if a.ServerID == "" { return trace.BadParameter("missing parameter ServerID") } if a.Clock == nil { a.Clock = clockwork.NewRealClock() } if a.UIDGenerator == nil { a.UIDGenerator = utils.NewRealUID() } if a.RotationPeriod ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/auditlog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/auditlog.go#L235-L300
go
train
// Creates and returns a new Audit Log object whish will store its logfiles in // a given directory. Session recording can be disabled by setting // recordSessions to false.
func NewAuditLog(cfg AuditLogConfig) (*AuditLog, error)
// Creates and returns a new Audit Log object whish will store its logfiles in // a given directory. Session recording can be disabled by setting // recordSessions to false. func NewAuditLog(cfg AuditLogConfig) (*AuditLog, error)
{ if err := cfg.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } ctx, cancel := context.WithCancel(cfg.Context) al := &AuditLog{ playbackDir: filepath.Join(cfg.DataDir, PlaybackDir, SessionLogsDir, defaults.Namespace), AuditLogConfig: cfg, Entry: log.WithFields(log.Fields{ trace.Comp...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/auditlog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/auditlog.go#L317-L328
go
train
// CheckAndSetDefaults checks and sets default parameters
func (l *SessionRecording) CheckAndSetDefaults() error
// CheckAndSetDefaults checks and sets default parameters func (l *SessionRecording) CheckAndSetDefaults() error
{ if l.Recording == nil { return trace.BadParameter("missing parameter Recording") } if l.SessionID.IsZero() { return trace.BadParameter("missing parameter session ID") } if l.Namespace == "" { l.Namespace = defaults.Namespace } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/auditlog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/auditlog.go#L332-L354
go
train
// UploadSessionRecording uploads session recording to the audit server // TODO(klizhentas) add protection against overwrites from different nodes
func (l *AuditLog) UploadSessionRecording(r SessionRecording) error
// UploadSessionRecording uploads session recording to the audit server // TODO(klizhentas) add protection against overwrites from different nodes func (l *AuditLog) UploadSessionRecording(r SessionRecording) error
{ if err := r.CheckAndSetDefaults(); err != nil { return trace.Wrap(err) } if l.UploadHandler == nil { // unpack the tarball locally to sessions directory err := utils.Extract(r.Recording, filepath.Join(l.DataDir, l.ServerID, SessionLogsDir, r.Namespace)) return trace.Wrap(err) } // use upload handler st...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/auditlog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/auditlog.go#L469-L475
go
train
// chunkFileNames returns file names of all session chunk files
func (idx *sessionIndex) chunkFileNames() []string
// chunkFileNames returns file names of all session chunk files func (idx *sessionIndex) chunkFileNames() []string
{ fileNames := make([]string, len(idx.chunks)) for i := 0; i < len(idx.chunks); i++ { fileNames[i] = idx.chunksFileName(i) } return fileNames }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/auditlog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/auditlog.go#L560-L575
go
train
// createOrGetDownload creates a new download sync entry for a given session, // if there is no active download in progress, or returns an existing one. // if the new context has been created, cancel function is returned as a // second argument. Caller should call this function to signal that download has been // compl...
func (l *AuditLog) createOrGetDownload(path string) (context.Context, context.CancelFunc)
// createOrGetDownload creates a new download sync entry for a given session, // if there is no active download in progress, or returns an existing one. // if the new context has been created, cancel function is returned as a // second argument. Caller should call this function to signal that download has been // compl...
{ l.Lock() defer l.Unlock() ctx, ok := l.activeDownloads[path] if ok { return ctx, nil } ctx, cancel := context.WithCancel(context.TODO()) l.activeDownloads[path] = ctx return ctx, func() { cancel() l.Lock() defer l.Unlock() delete(l.activeDownloads, path) } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/auditlog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/auditlog.go#L646-L668
go
train
// GetSessionChunk returns a reader which console and web clients request // to receive a live stream of a given session. The reader allows access to a // session stream range from offsetBytes to offsetBytes+maxBytes
func (l *AuditLog) GetSessionChunk(namespace string, sid session.ID, offsetBytes, maxBytes int) ([]byte, error)
// GetSessionChunk returns a reader which console and web clients request // to receive a live stream of a given session. The reader allows access to a // session stream range from offsetBytes to offsetBytes+maxBytes func (l *AuditLog) GetSessionChunk(namespace string, sid session.ID, offsetBytes, maxBytes int) ([]byte...
{ if l.UploadHandler != nil { if err := l.downloadSession(namespace, sid); err != nil { return nil, trace.Wrap(err) } } var data []byte for { out, err := l.getSessionChunk(namespace, sid, offsetBytes, maxBytes) if err != nil { if err == io.EOF { return data, nil } return nil, trace.Wrap(err...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/auditlog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/auditlog.go#L797-L841
go
train
// Returns all events that happen during a session sorted by time // (oldest first). // // Can be filtered by 'after' (cursor value to return events newer than) // // This function is usually used in conjunction with GetSessionReader to // replay recorded session streams.
func (l *AuditLog) GetSessionEvents(namespace string, sid session.ID, afterN int, includePrintEvents bool) ([]EventFields, error)
// Returns all events that happen during a session sorted by time // (oldest first). // // Can be filtered by 'after' (cursor value to return events newer than) // // This function is usually used in conjunction with GetSessionReader to // replay recorded session streams. func (l *AuditLog) GetSessionEvents(namespace s...
{ l.WithFields(log.Fields{"sid": string(sid), "afterN": afterN, "printEvents": includePrintEvents}).Debugf("GetSessionEvents.") if namespace == "" { return nil, trace.BadParameter("missing parameter namespace") } // Print events are stored in the context of the downloaded session // so pull them if !includePri...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/auditlog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/auditlog.go#L879-L898
go
train
// EmitAuditEvent adds a new event to the log. If emitting fails, a Prometheus // counter is incremented.
func (l *AuditLog) EmitAuditEvent(event Event, fields EventFields) error
// EmitAuditEvent adds a new event to the log. If emitting fails, a Prometheus // counter is incremented. func (l *AuditLog) EmitAuditEvent(event Event, fields EventFields) error
{ // If an external logger has been set, use it as the emitter, otherwise // fallback to the local disk based emitter. var emitAuditEvent func(event Event, fields EventFields) error if l.ExternalLog != nil { emitAuditEvent = l.ExternalLog.EmitAuditEvent } else { emitAuditEvent = l.localLog.EmitAuditEvent } ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/auditlog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/auditlog.go#L901-L911
go
train
// emitEvent emits event for test purposes
func (l *AuditLog) emitEvent(e AuditLogEvent)
// emitEvent emits event for test purposes func (l *AuditLog) emitEvent(e AuditLogEvent)
{ if l.EventsC == nil { return } select { case l.EventsC <- &e: return default: l.Warningf("Blocked on the events channel.") } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/auditlog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/auditlog.go#L914-L925
go
train
// auditDirs returns directories used for audit log storage
func (l *AuditLog) auditDirs() ([]string, error)
// auditDirs returns directories used for audit log storage func (l *AuditLog) auditDirs() ([]string, error)
{ authServers, err := l.getAuthServers() if err != nil { return nil, trace.Wrap(err) } var out []string for _, serverID := range authServers { out = append(out, filepath.Join(l.DataDir, serverID)) } return out, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/auditlog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/auditlog.go#L929-L941
go
train
// SearchEvents finds events. Results show up sorted by date (newest first), // limit is used when set to value > 0
func (l *AuditLog) SearchEvents(fromUTC, toUTC time.Time, query string, limit int) ([]EventFields, error)
// SearchEvents finds events. Results show up sorted by date (newest first), // limit is used when set to value > 0 func (l *AuditLog) SearchEvents(fromUTC, toUTC time.Time, query string, limit int) ([]EventFields, error)
{ l.Debugf("SearchEvents(%v, %v, query=%v, limit=%v)", fromUTC, toUTC, query, limit) if limit <= 0 { limit = defaults.EventsIterationLimit } if limit > defaults.EventsMaxIterationLimit { return nil, trace.BadParameter("limit %v exceeds max iteration limit %v", limit, defaults.MaxIterationLimit) } if l.Extern...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/auditlog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/auditlog.go#L944-L951
go
train
// SearchSessionEvents searches for session related events. Used to find completed sessions.
func (l *AuditLog) SearchSessionEvents(fromUTC, toUTC time.Time, limit int) ([]EventFields, error)
// SearchSessionEvents searches for session related events. Used to find completed sessions. func (l *AuditLog) SearchSessionEvents(fromUTC, toUTC time.Time, limit int) ([]EventFields, error)
{ l.Debugf("SearchSessionEvents(%v, %v, %v)", fromUTC, toUTC, limit) if l.ExternalLog != nil { return l.ExternalLog.SearchSessionEvents(fromUTC, toUTC, limit) } return l.localLog.SearchSessionEvents(fromUTC, toUTC, limit) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/auditlog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/auditlog.go#L955-L972
go
train
// Closes the audit log, which inluces closing all file handles and releasing // all session loggers
func (l *AuditLog) Close() error
// Closes the audit log, which inluces closing all file handles and releasing // all session loggers func (l *AuditLog) Close() error
{ if l.ExternalLog != nil { if err := l.ExternalLog.Close(); err != nil { log.Warningf("Close failure: %v", err) } } l.cancel() l.Lock() defer l.Unlock() if l.localLog != nil { if err := l.localLog.Close(); err != nil { log.Warningf("Close failure: %v", err) } l.localLog = nil } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/auditlog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/auditlog.go#L992-L1019
go
train
// periodicSpaceMonitor run forever monitoring how much disk space has been // used on disk. Values are emitted to a Prometheus gauge.
func (l *AuditLog) periodicSpaceMonitor()
// periodicSpaceMonitor run forever monitoring how much disk space has been // used on disk. Values are emitted to a Prometheus gauge. func (l *AuditLog) periodicSpaceMonitor()
{ ticker := time.NewTicker(defaults.DiskAlertInterval) defer ticker.Stop() for { select { case <-ticker.C: // Find out what percentage of disk space is used. If the syscall fails, // emit that to prometheus as well. usedPercent, err := percentUsed(l.DataDir) if err != nil { auditFailedDisk.Inc(...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/auditlog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/auditlog.go#L1024-L1032
go
train
// percentUsed returns percentage of disk space used. The percentage of disk // space used is calculated from (total blocks - free blocks)/total blocks. // The value is rounded to the nearest whole integer.
func percentUsed(path string) (float64, error)
// percentUsed returns percentage of disk space used. The percentage of disk // space used is calculated from (total blocks - free blocks)/total blocks. // The value is rounded to the nearest whole integer. func percentUsed(path string) (float64, error)
{ var stat syscall.Statfs_t err := syscall.Statfs(path, &stat) if err != nil { return 0, trace.Wrap(err) } ratio := float64(stat.Blocks-stat.Bfree) / float64(stat.Blocks) return math.Round(ratio * 100), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/legacy/dir/impl.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L77-L111
go
train
// New creates a new instance of a directory based backend that implements // backend.Backend.
func New(params legacy.Params) (*Backend, error)
// New creates a new instance of a directory based backend that implements // backend.Backend. func New(params legacy.Params) (*Backend, error)
{ rootDir := params.GetString("path") if rootDir == "" { rootDir = params.GetString("data_dir") } if rootDir == "" { return nil, trace.BadParameter("filesystem backend: 'path' is not set") } // Ensure that the path to the root directory exists. err := os.MkdirAll(rootDir, defaultDirMode) if err != nil { ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/legacy/dir/impl.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L119-L133
go
train
// GetKeys returns a list of keys for a given bucket.
func (bk *Backend) GetKeys(bucket []string) ([]string, error)
// GetKeys returns a list of keys for a given bucket. func (bk *Backend) GetKeys(bucket []string) ([]string, error)
{ // Get all the key/value pairs for this bucket. items, err := bk.GetItems(bucket) if err != nil { return nil, trace.Wrap(err) } // Return only the keys, the keys are already sorted by GetItems. keys := make([]string, len(items)) for i, e := range items { keys[i] = e.Key } return keys, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/legacy/dir/impl.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L136-L195
go
train
// Export exports all items from the backend in new backend Items
func (bk *Backend) Export() ([]backend.Item, error)
// Export exports all items from the backend in new backend Items func (bk *Backend) Export() ([]backend.Item, error)
{ var out []backend.Item // Get a list of all buckets in the backend. files, err := ioutil.ReadDir(path.Join(bk.rootDir)) if err != nil { return nil, trace.ConvertSystemError(err) } // Loop over all buckets in the backend. for _, fi := range files { // skip sqlite database file - (in general sense, // d...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/legacy/dir/impl.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L198-L268
go
train
// GetItems returns all items (key/value pairs) in a given bucket.
func (bk *Backend) GetItems(bucket []string, opts ...legacy.OpOption) ([]legacy.Item, error)
// GetItems returns all items (key/value pairs) in a given bucket. func (bk *Backend) GetItems(bucket []string, opts ...legacy.OpOption) ([]legacy.Item, error)
{ var out []legacy.Item // Get a list of all buckets in the backend. files, err := ioutil.ReadDir(path.Join(bk.rootDir)) if err != nil { return nil, trace.ConvertSystemError(err) } // Loop over all buckets in the backend. for _, fi := range files { pathToBucket := bk.pathToBucket(fi.Name()) bucketPrefix...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/legacy/dir/impl.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L272-L290
go
train
// CreateVal creates a key/value pair with the given TTL in the bucket. If // the key already exists in the bucket, trace.AlreadyExists is returned.
func (bk *Backend) CreateVal(bucket []string, key string, val []byte, ttl time.Duration) error
// CreateVal creates a key/value pair with the given TTL in the bucket. If // the key already exists in the bucket, trace.AlreadyExists is returned. func (bk *Backend) CreateVal(bucket []string, key string, val []byte, ttl time.Duration) error
{ // Open the bucket to work on the items. b, err := bk.openBucket(bk.flatten(bucket), os.O_CREATE|os.O_RDWR) if err != nil { return trace.Wrap(err) } defer b.Close() // If the key exists and is not expired, return trace.AlreadyExists. item, ok := b.getItem(key) if ok && !bk.isExpired(item) { return trace...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/legacy/dir/impl.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L294-L306
go
train
// UpsertVal inserts (or updates if it already exists) the value for a key // with the given TTL.
func (bk *Backend) UpsertVal(bucket []string, key string, val []byte, ttl time.Duration) error
// UpsertVal inserts (or updates if it already exists) the value for a key // with the given TTL. func (bk *Backend) UpsertVal(bucket []string, key string, val []byte, ttl time.Duration) error
{ // Open the bucket to work on the items. b, err := bk.openBucket(bk.flatten(bucket), os.O_CREATE|os.O_RDWR) if err != nil { return trace.Wrap(err) } defer b.Close() // Update the item in the bucket. b.updateItem(key, val, ttl) return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/legacy/dir/impl.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L310-L324
go
train
// UpsertItems inserts (or updates if it already exists) all passed in // legacy.Items with the given TTL.
func (bk *Backend) UpsertItems(bucket []string, newItems []legacy.Item) error
// UpsertItems inserts (or updates if it already exists) all passed in // legacy.Items with the given TTL. func (bk *Backend) UpsertItems(bucket []string, newItems []legacy.Item) error
{ // Open the bucket to work on the items. b, err := bk.openBucket(bk.flatten(bucket), os.O_CREATE|os.O_RDWR) if err != nil { return trace.Wrap(err) } defer b.Close() // Update items in bucket. for _, e := range newItems { b.updateItem(e.Key, e.Value, e.TTL) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/legacy/dir/impl.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L327-L374
go
train
// GetVal return a value for a given key in the bucket
func (bk *Backend) GetVal(bucket []string, key string) ([]byte, error)
// GetVal return a value for a given key in the bucket func (bk *Backend) GetVal(bucket []string, key string) ([]byte, error)
{ // Open the bucket to work on the items. b, err := bk.openBucket(bk.flatten(bucket), os.O_RDWR) if err != nil { // GetVal on a bucket needs to return trace.BadParameter. If opening the // bucket failed a partial match up to a bucket may still exist. To support // returning trace.BadParameter in this situati...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/legacy/dir/impl.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L377-L406
go
train
// CompareAndSwapVal compares and swap values in atomic operation
func (bk *Backend) CompareAndSwapVal(bucket []string, key string, val []byte, prevVal []byte, ttl time.Duration) error
// CompareAndSwapVal compares and swap values in atomic operation func (bk *Backend) CompareAndSwapVal(bucket []string, key string, val []byte, prevVal []byte, ttl time.Duration) error
{ // Open the bucket to work on the items. b, err := bk.openBucket(bk.flatten(bucket), os.O_CREATE|os.O_RDWR) if err != nil { er := trace.ConvertSystemError(err) if trace.IsNotFound(er) { return trace.CompareFailed("%v/%v did not match expected value", bucket, key) } return trace.Wrap(er) } defer b.Clo...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/legacy/dir/impl.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L409-L427
go
train
// DeleteKey deletes a key in a bucket.
func (bk *Backend) DeleteKey(bucket []string, key string) error
// DeleteKey deletes a key in a bucket. func (bk *Backend) DeleteKey(bucket []string, key string) error
{ // Open the bucket to work on the items. b, err := bk.openBucket(bk.flatten(bucket), os.O_RDWR) if err != nil { return trace.Wrap(err) } defer b.Close() // If the key doesn't exist, return trace.NotFound. _, ok := b.getItem(key) if !ok { return trace.NotFound("key %v not found", key) } // Otherwise, ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/legacy/dir/impl.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L430-L439
go
train
// DeleteBucket deletes the bucket by a given path.
func (bk *Backend) DeleteBucket(parent []string, bucket string) error
// DeleteBucket deletes the bucket by a given path. func (bk *Backend) DeleteBucket(parent []string, bucket string) error
{ fullBucket := append(parent, bucket) err := os.Remove(bk.flatten(fullBucket)) if err != nil { return trace.ConvertSystemError(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/legacy/dir/impl.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L442-L467
go
train
// AcquireLock grabs a lock that will be released automatically in TTL.
func (bk *Backend) AcquireLock(token string, ttl time.Duration) (err error)
// AcquireLock grabs a lock that will be released automatically in TTL. func (bk *Backend) AcquireLock(token string, ttl time.Duration) (err error)
{ bk.log.Debugf("AcquireLock(%s)", token) if err = legacy.ValidateLockTTL(ttl); err != nil { return trace.Wrap(err) } bucket := []string{locksBucket} for { // GetVal will clear TTL on a lock bk.GetVal(bucket, token) // CreateVal is atomic: err = bk.CreateVal(bucket, token, []byte{1}, ttl) if err ==...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/legacy/dir/impl.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L470-L479
go
train
// ReleaseLock forces lock release before TTL.
func (bk *Backend) ReleaseLock(token string) (err error)
// ReleaseLock forces lock release before TTL. func (bk *Backend) ReleaseLock(token string) (err error)
{ bk.log.Debugf("ReleaseLock(%s)", token) if err = bk.DeleteKey([]string{locksBucket}, token); err != nil { if !os.IsNotExist(err) { return trace.ConvertSystemError(err) } } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/legacy/dir/impl.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L483-L485
go
train
// pathToBucket prepends the root directory to the bucket returning the full // path to the bucket on the filesystem.
func (bk *Backend) pathToBucket(bucket string) string
// pathToBucket prepends the root directory to the bucket returning the full // path to the bucket on the filesystem. func (bk *Backend) pathToBucket(bucket string) string
{ return filepath.Join(bk.rootDir, bucket) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/legacy/dir/impl.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L488-L494
go
train
// decodeBucket decodes bucket into parts of path
func decodeBucket(bucket string) ([]string, error)
// decodeBucket decodes bucket into parts of path func decodeBucket(bucket string) ([]string, error)
{ decoded, err := url.QueryUnescape(bucket) if err != nil { return nil, trace.Wrap(err) } return filepath.SplitList(decoded), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/legacy/dir/impl.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L498-L506
go
train
// flatten takes a bucket and flattens it (URL encodes) and prepends the root // directory returning the full path to the bucket on the filesystem.
func (bk *Backend) flatten(bucket []string) string
// flatten takes a bucket and flattens it (URL encodes) and prepends the root // directory returning the full path to the bucket on the filesystem. func (bk *Backend) flatten(bucket []string) string
{ // Convert ["foo", "bar"] to "foo/bar" raw := filepath.Join(bucket...) // URL encode bucket from "foo/bar" to "foo%2Fbar". flat := url.QueryEscape(raw) return filepath.Join(bk.rootDir, flat) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/legacy/dir/impl.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L509-L514
go
train
// isExpired checks if the bucket item is expired or not.
func (bk *Backend) isExpired(bv bucketItem) bool
// isExpired checks if the bucket item is expired or not. func (bk *Backend) isExpired(bv bucketItem) bool
{ if bv.ExpiryTime.IsZero() { return false } return bk.Clock().Now().After(bv.ExpiryTime) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/legacy/dir/impl.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L543-L566
go
train
// openBucket will open a file, lock it, and then read in all the items in // the bucket.
func (bk *Backend) openBucket(prefix string, openFlag int) (*bucket, error)
// openBucket will open a file, lock it, and then read in all the items in // the bucket. func (bk *Backend) openBucket(prefix string, openFlag int) (*bucket, error)
{ // Open bucket with requested flags. file, err := os.OpenFile(prefix, openFlag, defaultFileMode) if err != nil { return nil, trace.ConvertSystemError(err) } // Lock the bucket so no one else can access it. if err := utils.FSWriteLock(file); err != nil { return nil, trace.Wrap(err) } // Read in all item...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/legacy/dir/impl.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L591-L613
go
train
// Close will write out items (if requested), unlock file, and close it.
func (b *bucket) Close() error
// Close will write out items (if requested), unlock file, and close it. func (b *bucket) Close() error
{ var err error // If the items were updated, write them out to disk. if b.itemsUpdated { err = writeBucket(b.file, b.items) if err != nil { b.backend.log.Warnf("Unable to update keys in %v: %v.", b.file.Name(), err) } } err = utils.FSUnlock(b.file) if err != nil { b.backend.log.Warnf("Unable to unl...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/legacy/dir/impl.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L617-L639
go
train
// readBucket will read in the bucket and return a map of keys. The second return // value returns true to false to indicate if the file was empty or not.
func readBucket(f *os.File) (map[string]bucketItem, error)
// readBucket will read in the bucket and return a map of keys. The second return // value returns true to false to indicate if the file was empty or not. func readBucket(f *os.File) (map[string]bucketItem, error)
{ // If the file is empty, return an empty bucket. ok, err := isEmpty(f) if err != nil { return nil, trace.Wrap(err) } if ok { return map[string]bucketItem{}, nil } // The file is not empty, read it into a map. var items map[string]bucketItem bytes, err := ioutil.ReadAll(f) if err != nil { return nil,...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/legacy/dir/impl.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L642-L664
go
train
// writeBucket will truncate the file and write out the items to the file f.
func writeBucket(f *os.File, items map[string]bucketItem) error
// writeBucket will truncate the file and write out the items to the file f. func writeBucket(f *os.File, items map[string]bucketItem) error
{ // Marshal items to disk format. bytes, err := json.Marshal(items) if err != nil { return trace.Wrap(err) } // Truncate the file. if _, err := f.Seek(0, 0); err != nil { return trace.ConvertSystemError(err) } if err := f.Truncate(0); err != nil { return trace.ConvertSystemError(err) } // Write out ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/legacy/dir/impl.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L667-L678
go
train
// isEmpty checks if the file is empty or not.
func isEmpty(f *os.File) (bool, error)
// isEmpty checks if the file is empty or not. func isEmpty(f *os.File) (bool, error)
{ fi, err := f.Stat() if err != nil { return false, trace.Wrap(err) } if fi.Size() > 0 { return false, nil } return true, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/legacy/dir/impl.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L683-L704
go
train
// suffix returns the first bucket after where pathToBucket and bucketPrefix // differ. For example, if pathToBucket is "/roles/admin/params" and // bucketPrefix is "/roles", then "admin" is returned.
func suffix(pathToBucket string, bucketPrefix string) (string, error)
// suffix returns the first bucket after where pathToBucket and bucketPrefix // differ. For example, if pathToBucket is "/roles/admin/params" and // bucketPrefix is "/roles", then "admin" is returned. func suffix(pathToBucket string, bucketPrefix string) (string, error)
{ full, err := url.QueryUnescape(pathToBucket) if err != nil { return "", trace.Wrap(err) } prefix, err := url.QueryUnescape(bucketPrefix) if err != nil { return "", trace.Wrap(err) } remain := full[len(prefix)+1:] if remain == "" { return "", trace.BadParameter("unable to split %v", remain) } vals :...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/legacy/dir/impl.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L709-L727
go
train
// removeDuplicates removes any duplicate items from the passed in slice. This // is to ensure that partial matches don't result in multiple values returned. // This is consistent with our DynamoDB implementation.
func removeDuplicates(items []legacy.Item) []legacy.Item
// removeDuplicates removes any duplicate items from the passed in slice. This // is to ensure that partial matches don't result in multiple values returned. // This is consistent with our DynamoDB implementation. func removeDuplicates(items []legacy.Item) []legacy.Item
{ // Use map to record duplicates as we find them. encountered := map[string]bool{} result := make([]legacy.Item, 0, len(items)) // Loop over all items, if it has not been seen before, append to result. for _, e := range items { _, ok := encountered[e.FullPath] if !ok { // Record this element as an encoun...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/legacy/dir/impl.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L732-L750
go
train
// removeDuplicates removes any duplicate items from the passed in slice. This // is to ensure that partial matches don't result in multiple values returned. // This is consistent with our DynamoDB implementation.
func removeBackendDuplicates(items []backend.Item) []backend.Item
// removeDuplicates removes any duplicate items from the passed in slice. This // is to ensure that partial matches don't result in multiple values returned. // This is consistent with our DynamoDB implementation. func removeBackendDuplicates(items []backend.Item) []backend.Item
{ // Use map to record duplicates as we find them. encountered := map[string]bool{} result := make([]backend.Item, 0, len(items)) // Loop over all items, if it has not been seen before, append to result. for _, e := range items { _, ok := encountered[string(e.Key)] if !ok { // Record this element as an en...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/memory/item.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/memory/item.go#L37-L46
go
train
// Less is used for Btree operations, // returns true if item is less than the other one
func (i *btreeItem) Less(iother btree.Item) bool
// Less is used for Btree operations, // returns true if item is less than the other one func (i *btreeItem) Less(iother btree.Item) bool
{ switch other := iother.(type) { case *btreeItem: return bytes.Compare(i.Key, other.Key) < 0 case *prefixItem: return !iother.Less(i) default: return false } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/memory/item.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/memory/item.go#L55-L61
go
train
// Less is used for Btree operations
func (p *prefixItem) Less(iother btree.Item) bool
// Less is used for Btree operations func (p *prefixItem) Less(iother btree.Item) bool
{ other := iother.(*btreeItem) if bytes.HasPrefix(other.Key, p.prefix) { return false } return true }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/remotecluster.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/remotecluster.go#L50-L59
go
train
// NewRemoteCluster is a convenience wa to create a RemoteCluster resource.
func NewRemoteCluster(name string) (RemoteCluster, error)
// NewRemoteCluster is a convenience wa to create a RemoteCluster resource. func NewRemoteCluster(name string) (RemoteCluster, error)
{ return &RemoteClusterV3{ Kind: KindRemoteCluster, Version: V3, Metadata: Metadata{ Name: name, Namespace: defaults.Namespace, }, }, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/remotecluster.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/remotecluster.go#L128-L130
go
train
// SetLastHeartbeat sets last heartbeat of the cluster
func (c *RemoteClusterV3) SetLastHeartbeat(t time.Time)
// SetLastHeartbeat sets last heartbeat of the cluster func (c *RemoteClusterV3) SetLastHeartbeat(t time.Time)
{ c.Status.LastHeartbeat = t }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/remotecluster.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/remotecluster.go#L148-L150
go
train
// SetExpiry sets expiry time for the object
func (c *RemoteClusterV3) SetExpiry(expires time.Time)
// SetExpiry sets expiry time for the object func (c *RemoteClusterV3) SetExpiry(expires time.Time)
{ c.Metadata.SetExpiry(expires) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/remotecluster.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/remotecluster.go#L173-L175
go
train
// String represents a human readable version of remote cluster settings.
func (r *RemoteClusterV3) String() string
// String represents a human readable version of remote cluster settings. func (r *RemoteClusterV3) String() string
{ return fmt.Sprintf("RemoteCluster(%v, %v)", r.Metadata.Name, r.Status.Connection) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/remotecluster.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/remotecluster.go#L207-L237
go
train
// UnmarshalRemoteCluster unmarshals remote cluster from JSON or YAML.
func UnmarshalRemoteCluster(bytes []byte, opts ...MarshalOption) (RemoteCluster, error)
// UnmarshalRemoteCluster unmarshals remote cluster from JSON or YAML. func UnmarshalRemoteCluster(bytes []byte, opts ...MarshalOption) (RemoteCluster, error)
{ cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } var cluster RemoteClusterV3 if len(bytes) == 0 { return nil, trace.BadParameter("missing resource data") } if cfg.SkipValidation { err := utils.FastUnmarshal(bytes, &cluster) if err != nil { return nil, trace.Wrap(err...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/remotecluster.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/remotecluster.go#L240-L258
go
train
// MarshalRemoteCluster marshals remote cluster to JSON.
func MarshalRemoteCluster(c RemoteCluster, opts ...MarshalOption) ([]byte, error)
// MarshalRemoteCluster marshals remote cluster to JSON. func MarshalRemoteCluster(c RemoteCluster, opts ...MarshalOption) ([]byte, error)
{ cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } switch resource := c.(type) { case *RemoteClusterV3: if !cfg.PreserveResourceID { // avoid modifying the original object // to prevent unexpected data races copy := *resource copy.SetResourceID(0) resource = &copy ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/tlsca/ca.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/tlsca/ca.go#L43-L57
go
train
// New returns new CA from PEM encoded certificate and private // key. Private Key is optional, if omitted CA won't be able to // issue new certificates, only verify them
func New(certPEM, keyPEM []byte) (*CertAuthority, error)
// New returns new CA from PEM encoded certificate and private // key. Private Key is optional, if omitted CA won't be able to // issue new certificates, only verify them func New(certPEM, keyPEM []byte) (*CertAuthority, error)
{ ca := &CertAuthority{} var err error ca.Cert, err = ParseCertificatePEM(certPEM) if err != nil { return nil, trace.Wrap(err) } if len(keyPEM) != 0 { ca.Signer, err = ParsePrivateKeyPEM(keyPEM) if err != nil { return nil, trace.Wrap(err) } } return ca, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/tlsca/ca.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/tlsca/ca.go#L82-L90
go
train
// CheckAndSetDefaults checks and sets default values
func (i *Identity) CheckAndSetDefaults() error
// CheckAndSetDefaults checks and sets default values func (i *Identity) CheckAndSetDefaults() error
{ if i.Username == "" { return trace.BadParameter("missing identity username") } if len(i.Groups) == 0 { return trace.BadParameter("missing identity groups") } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/tlsca/ca.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/tlsca/ca.go#L93-L102
go
train
// Subject converts identity to X.509 subject name
func (id *Identity) Subject() pkix.Name
// Subject converts identity to X.509 subject name func (id *Identity) Subject() pkix.Name
{ subject := pkix.Name{ CommonName: id.Username, } subject.Organization = append([]string{}, id.Groups...) subject.OrganizationalUnit = append([]string{}, id.Usage...) subject.Locality = append([]string{}, id.Principals...) subject.Province = append([]string{}, id.KubernetesGroups...) return subject }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/tlsca/ca.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/tlsca/ca.go#L105-L117
go
train
// FromSubject returns identity from subject name
func FromSubject(subject pkix.Name) (*Identity, error)
// FromSubject returns identity from subject name func FromSubject(subject pkix.Name) (*Identity, error)
{ i := &Identity{ Username: subject.CommonName, Groups: subject.Organization, Usage: subject.OrganizationalUnit, Principals: subject.Locality, KubernetesGroups: subject.Province, } if err := i.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } return i...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/tlsca/ca.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/tlsca/ca.go#L135-L149
go
train
// CheckAndSetDefaults checks and sets default values
func (c *CertificateRequest) CheckAndSetDefaults() error
// CheckAndSetDefaults checks and sets default values func (c *CertificateRequest) CheckAndSetDefaults() error
{ if c.Clock == nil { return trace.BadParameter("missing parameter Clock") } if c.PublicKey == nil { return trace.BadParameter("missing parameter PublicKey") } if c.Subject.CommonName == "" { return trace.BadParameter("missing parameter Subject.Common name") } if c.NotAfter.IsZero() { return trace.BadPa...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/tlsca/ca.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/tlsca/ca.go#L152-L200
go
train
// GenerateCertificate generates certificate from request
func (ca *CertAuthority) GenerateCertificate(req CertificateRequest) ([]byte, error)
// GenerateCertificate generates certificate from request func (ca *CertAuthority) GenerateCertificate(req CertificateRequest) ([]byte, error)
{ if err := req.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) if err != nil { return nil, trace.Wrap(err) } log.WithFields(logrus.Fields{ "not_after": req.NotAfter...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/termhandlers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/termhandlers.go#L39-L119
go
train
// HandleExec handles requests of type "exec" which can execute with or // without a TTY. Result of execution is propagated back on the ExecResult // channel of the context.
func (t *TermHandlers) HandleExec(ch ssh.Channel, req *ssh.Request, ctx *ServerContext) error
// HandleExec handles requests of type "exec" which can execute with or // without a TTY. Result of execution is propagated back on the ExecResult // channel of the context. func (t *TermHandlers) HandleExec(ch ssh.Channel, req *ssh.Request, ctx *ServerContext) error
{ execRequest, err := parseExecRequest(req, ctx) if err != nil { return trace.Wrap(err) } // a terminal has been previously allocate for this command. // run this inside an interactive session if ctx.GetTerm() != nil { return t.SessionRegistry.OpenSession(ch, req, ctx) } // If this code is running on a T...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/termhandlers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/termhandlers.go#L124-L162
go
train
// HandlePTYReq handles requests of type "pty-req" which allocate a TTY for // "exec" or "shell" requests. The "pty-req" includes the size of the TTY as // well as the terminal type requested.
func (t *TermHandlers) HandlePTYReq(ch ssh.Channel, req *ssh.Request, ctx *ServerContext) error
// HandlePTYReq handles requests of type "pty-req" which allocate a TTY for // "exec" or "shell" requests. The "pty-req" includes the size of the TTY as // well as the terminal type requested. func (t *TermHandlers) HandlePTYReq(ch ssh.Channel, req *ssh.Request, ctx *ServerContext) error
{ // parse and extract the requested window size of the pty ptyRequest, err := parsePTYReq(req) if err != nil { return trace.Wrap(err) } termModes, err := ptyRequest.TerminalModes() if err != nil { return trace.Wrap(err) } params, err := rsession.NewTerminalParamsFromUint32(ptyRequest.W, ptyRequest.H) i...