repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
apex/apex
utils/utils.go
AssumeRole
func AssumeRole(role string, config *aws.Config) (*aws.Config, error) { stscreds := sts.New(session.New(config)) params := &sts.AssumeRoleInput{ RoleArn: &role, RoleSessionName: aws.String("apex"), DurationSeconds: aws.Int64(1800), } res, err := stscreds.AssumeRole(params) if err != nil { return nil, err } id := *res.Credentials.AccessKeyId secret := *res.Credentials.SecretAccessKey token := *res.Credentials.SessionToken return &aws.Config{ Region: config.Region, Credentials: credentials.NewStaticCredentials(id, secret, token), }, nil }
go
func AssumeRole(role string, config *aws.Config) (*aws.Config, error) { stscreds := sts.New(session.New(config)) params := &sts.AssumeRoleInput{ RoleArn: &role, RoleSessionName: aws.String("apex"), DurationSeconds: aws.Int64(1800), } res, err := stscreds.AssumeRole(params) if err != nil { return nil, err } id := *res.Credentials.AccessKeyId secret := *res.Credentials.SecretAccessKey token := *res.Credentials.SessionToken return &aws.Config{ Region: config.Region, Credentials: credentials.NewStaticCredentials(id, secret, token), }, nil }
[ "func", "AssumeRole", "(", "role", "string", ",", "config", "*", "aws", ".", "Config", ")", "(", "*", "aws", ".", "Config", ",", "error", ")", "{", "stscreds", ":=", "sts", ".", "New", "(", "session", ".", "New", "(", "config", ")", ")", "\n\n", "params", ":=", "&", "sts", ".", "AssumeRoleInput", "{", "RoleArn", ":", "&", "role", ",", "RoleSessionName", ":", "aws", ".", "String", "(", "\"", "\"", ")", ",", "DurationSeconds", ":", "aws", ".", "Int64", "(", "1800", ")", ",", "}", "\n\n", "res", ",", "err", ":=", "stscreds", ".", "AssumeRole", "(", "params", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "id", ":=", "*", "res", ".", "Credentials", ".", "AccessKeyId", "\n", "secret", ":=", "*", "res", ".", "Credentials", ".", "SecretAccessKey", "\n", "token", ":=", "*", "res", ".", "Credentials", ".", "SessionToken", "\n\n", "return", "&", "aws", ".", "Config", "{", "Region", ":", "config", ".", "Region", ",", "Credentials", ":", "credentials", ".", "NewStaticCredentials", "(", "id", ",", "secret", ",", "token", ")", ",", "}", ",", "nil", "\n", "}" ]
// AssumeRole uses STS to assume the given `role`.
[ "AssumeRole", "uses", "STS", "to", "assume", "the", "given", "role", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/utils/utils.go#L163-L185
train
apex/apex
project/project.go
Open
func (p *Project) Open() error { p.defaults() configFile := "project.json" if p.Environment != "" { configFile = fmt.Sprintf("project.%s.json", p.Environment) } f, err := os.Open(filepath.Join(p.Path, configFile)) if err != nil { return err } if err := json.NewDecoder(f).Decode(&p.Config); err != nil { return err } if p.InfraEnvironment == "" { p.InfraEnvironment = p.Config.DefaultEnvironment } if p.Role == "" { p.Role = p.readInfraRole() } if err := validator.Validate(&p.Config); err != nil { return err } t, err := template.New("nameTemplate").Parse(p.NameTemplate) if err != nil { return err } p.nameTemplate = t ignoreFile, err := utils.ReadIgnoreFile(p.Path) if err != nil { return err } p.IgnoreFile = append(p.IgnoreFile, ignoreFile...) return nil }
go
func (p *Project) Open() error { p.defaults() configFile := "project.json" if p.Environment != "" { configFile = fmt.Sprintf("project.%s.json", p.Environment) } f, err := os.Open(filepath.Join(p.Path, configFile)) if err != nil { return err } if err := json.NewDecoder(f).Decode(&p.Config); err != nil { return err } if p.InfraEnvironment == "" { p.InfraEnvironment = p.Config.DefaultEnvironment } if p.Role == "" { p.Role = p.readInfraRole() } if err := validator.Validate(&p.Config); err != nil { return err } t, err := template.New("nameTemplate").Parse(p.NameTemplate) if err != nil { return err } p.nameTemplate = t ignoreFile, err := utils.ReadIgnoreFile(p.Path) if err != nil { return err } p.IgnoreFile = append(p.IgnoreFile, ignoreFile...) return nil }
[ "func", "(", "p", "*", "Project", ")", "Open", "(", ")", "error", "{", "p", ".", "defaults", "(", ")", "\n\n", "configFile", ":=", "\"", "\"", "\n", "if", "p", ".", "Environment", "!=", "\"", "\"", "{", "configFile", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "p", ".", "Environment", ")", "\n", "}", "\n\n", "f", ",", "err", ":=", "os", ".", "Open", "(", "filepath", ".", "Join", "(", "p", ".", "Path", ",", "configFile", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "json", ".", "NewDecoder", "(", "f", ")", ".", "Decode", "(", "&", "p", ".", "Config", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "p", ".", "InfraEnvironment", "==", "\"", "\"", "{", "p", ".", "InfraEnvironment", "=", "p", ".", "Config", ".", "DefaultEnvironment", "\n", "}", "\n\n", "if", "p", ".", "Role", "==", "\"", "\"", "{", "p", ".", "Role", "=", "p", ".", "readInfraRole", "(", ")", "\n", "}", "\n\n", "if", "err", ":=", "validator", ".", "Validate", "(", "&", "p", ".", "Config", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "t", ",", "err", ":=", "template", ".", "New", "(", "\"", "\"", ")", ".", "Parse", "(", "p", ".", "NameTemplate", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "p", ".", "nameTemplate", "=", "t", "\n\n", "ignoreFile", ",", "err", ":=", "utils", ".", "ReadIgnoreFile", "(", "p", ".", "Path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "p", ".", "IgnoreFile", "=", "append", "(", "p", ".", "IgnoreFile", ",", "ignoreFile", "...", ")", "\n\n", "return", "nil", "\n", "}" ]
// Open the project.json file and prime the config.
[ "Open", "the", "project", ".", "json", "file", "and", "prime", "the", "config", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/project/project.go#L100-L142
train
apex/apex
project/project.go
DeployAndClean
func (p *Project) DeployAndClean() error { if err := p.Deploy(); err != nil { return err } return p.Clean() }
go
func (p *Project) DeployAndClean() error { if err := p.Deploy(); err != nil { return err } return p.Clean() }
[ "func", "(", "p", "*", "Project", ")", "DeployAndClean", "(", ")", "error", "{", "if", "err", ":=", "p", ".", "Deploy", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "p", ".", "Clean", "(", ")", "\n", "}" ]
// DeployAndClean deploys functions and then cleans up their build artifacts.
[ "DeployAndClean", "deploys", "functions", "and", "then", "cleans", "up", "their", "build", "artifacts", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/project/project.go#L181-L187
train
apex/apex
project/project.go
Deploy
func (p *Project) Deploy() error { p.Log.Debugf("deploying %d functions", len(p.Functions)) sem := make(semaphore.Semaphore, p.Concurrency) errs := make(chan error) go func() { for _, fn := range p.Functions { fn := fn sem.Acquire() go func() { defer sem.Release() err := fn.Deploy() if err != nil { err = fmt.Errorf("function %s: %s", fn.Name, err) } errs <- err }() } sem.Wait() close(errs) }() for err := range errs { if err != nil { return err } } return nil }
go
func (p *Project) Deploy() error { p.Log.Debugf("deploying %d functions", len(p.Functions)) sem := make(semaphore.Semaphore, p.Concurrency) errs := make(chan error) go func() { for _, fn := range p.Functions { fn := fn sem.Acquire() go func() { defer sem.Release() err := fn.Deploy() if err != nil { err = fmt.Errorf("function %s: %s", fn.Name, err) } errs <- err }() } sem.Wait() close(errs) }() for err := range errs { if err != nil { return err } } return nil }
[ "func", "(", "p", "*", "Project", ")", "Deploy", "(", ")", "error", "{", "p", ".", "Log", ".", "Debugf", "(", "\"", "\"", ",", "len", "(", "p", ".", "Functions", ")", ")", "\n\n", "sem", ":=", "make", "(", "semaphore", ".", "Semaphore", ",", "p", ".", "Concurrency", ")", "\n", "errs", ":=", "make", "(", "chan", "error", ")", "\n\n", "go", "func", "(", ")", "{", "for", "_", ",", "fn", ":=", "range", "p", ".", "Functions", "{", "fn", ":=", "fn", "\n", "sem", ".", "Acquire", "(", ")", "\n\n", "go", "func", "(", ")", "{", "defer", "sem", ".", "Release", "(", ")", "\n\n", "err", ":=", "fn", ".", "Deploy", "(", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "fn", ".", "Name", ",", "err", ")", "\n", "}", "\n\n", "errs", "<-", "err", "\n", "}", "(", ")", "\n", "}", "\n\n", "sem", ".", "Wait", "(", ")", "\n", "close", "(", "errs", ")", "\n", "}", "(", ")", "\n\n", "for", "err", ":=", "range", "errs", "{", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Deploy functions and their configurations.
[ "Deploy", "functions", "and", "their", "configurations", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/project/project.go#L190-L224
train
apex/apex
project/project.go
Clean
func (p *Project) Clean() error { p.Log.Debugf("cleaning %d functions", len(p.Functions)) for _, fn := range p.Functions { if err := fn.Clean(); err != nil { return fmt.Errorf("function %s: %s", fn.Name, err) } } return nil }
go
func (p *Project) Clean() error { p.Log.Debugf("cleaning %d functions", len(p.Functions)) for _, fn := range p.Functions { if err := fn.Clean(); err != nil { return fmt.Errorf("function %s: %s", fn.Name, err) } } return nil }
[ "func", "(", "p", "*", "Project", ")", "Clean", "(", ")", "error", "{", "p", ".", "Log", ".", "Debugf", "(", "\"", "\"", ",", "len", "(", "p", ".", "Functions", ")", ")", "\n\n", "for", "_", ",", "fn", ":=", "range", "p", ".", "Functions", "{", "if", "err", ":=", "fn", ".", "Clean", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "fn", ".", "Name", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Clean up function build artifacts.
[ "Clean", "up", "function", "build", "artifacts", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/project/project.go#L227-L237
train
apex/apex
project/project.go
Delete
func (p *Project) Delete() error { p.Log.Debugf("deleting %d functions", len(p.Functions)) for _, fn := range p.Functions { if _, err := fn.GetConfig(); err != nil { if awserr, ok := err.(awserr.Error); ok && awserr.Code() == "ResourceNotFoundException" { p.Log.Infof("function %q hasn't been deployed yet or has been deleted manually on AWS Lambda", fn.Name) continue } return fmt.Errorf("function %s: %s", fn.Name, err) } if err := fn.Delete(); err != nil { return fmt.Errorf("function %s: %s", fn.Name, err) } } return nil }
go
func (p *Project) Delete() error { p.Log.Debugf("deleting %d functions", len(p.Functions)) for _, fn := range p.Functions { if _, err := fn.GetConfig(); err != nil { if awserr, ok := err.(awserr.Error); ok && awserr.Code() == "ResourceNotFoundException" { p.Log.Infof("function %q hasn't been deployed yet or has been deleted manually on AWS Lambda", fn.Name) continue } return fmt.Errorf("function %s: %s", fn.Name, err) } if err := fn.Delete(); err != nil { return fmt.Errorf("function %s: %s", fn.Name, err) } } return nil }
[ "func", "(", "p", "*", "Project", ")", "Delete", "(", ")", "error", "{", "p", ".", "Log", ".", "Debugf", "(", "\"", "\"", ",", "len", "(", "p", ".", "Functions", ")", ")", "\n\n", "for", "_", ",", "fn", ":=", "range", "p", ".", "Functions", "{", "if", "_", ",", "err", ":=", "fn", ".", "GetConfig", "(", ")", ";", "err", "!=", "nil", "{", "if", "awserr", ",", "ok", ":=", "err", ".", "(", "awserr", ".", "Error", ")", ";", "ok", "&&", "awserr", ".", "Code", "(", ")", "==", "\"", "\"", "{", "p", ".", "Log", ".", "Infof", "(", "\"", "\"", ",", "fn", ".", "Name", ")", "\n", "continue", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "fn", ".", "Name", ",", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "fn", ".", "Delete", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "fn", ".", "Name", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Delete functions.
[ "Delete", "functions", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/project/project.go#L240-L258
train
apex/apex
project/project.go
RollbackVersion
func (p *Project) RollbackVersion(version string) error { p.Log.Debugf("rolling back %d functions to version %s", len(p.Functions), version) for _, fn := range p.Functions { if err := fn.RollbackVersion(version); err != nil { return fmt.Errorf("function %s: %s", fn.Name, err) } } return nil }
go
func (p *Project) RollbackVersion(version string) error { p.Log.Debugf("rolling back %d functions to version %s", len(p.Functions), version) for _, fn := range p.Functions { if err := fn.RollbackVersion(version); err != nil { return fmt.Errorf("function %s: %s", fn.Name, err) } } return nil }
[ "func", "(", "p", "*", "Project", ")", "RollbackVersion", "(", "version", "string", ")", "error", "{", "p", ".", "Log", ".", "Debugf", "(", "\"", "\"", ",", "len", "(", "p", ".", "Functions", ")", ",", "version", ")", "\n\n", "for", "_", ",", "fn", ":=", "range", "p", ".", "Functions", "{", "if", "err", ":=", "fn", ".", "RollbackVersion", "(", "version", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "fn", ".", "Name", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// RollbackVersion project functions to the specified version.
[ "RollbackVersion", "project", "functions", "to", "the", "specified", "version", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/project/project.go#L274-L284
train
apex/apex
project/project.go
FunctionDirNames
func (p *Project) FunctionDirNames() (list []string, err error) { dir := filepath.Join(p.Path, functionsDir) files, err := ioutil.ReadDir(dir) if err != nil { return nil, err } for _, file := range files { if file.IsDir() { list = append(list, file.Name()) } } return list, nil }
go
func (p *Project) FunctionDirNames() (list []string, err error) { dir := filepath.Join(p.Path, functionsDir) files, err := ioutil.ReadDir(dir) if err != nil { return nil, err } for _, file := range files { if file.IsDir() { list = append(list, file.Name()) } } return list, nil }
[ "func", "(", "p", "*", "Project", ")", "FunctionDirNames", "(", ")", "(", "list", "[", "]", "string", ",", "err", "error", ")", "{", "dir", ":=", "filepath", ".", "Join", "(", "p", ".", "Path", ",", "functionsDir", ")", "\n\n", "files", ",", "err", ":=", "ioutil", ".", "ReadDir", "(", "dir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "for", "_", ",", "file", ":=", "range", "files", "{", "if", "file", ".", "IsDir", "(", ")", "{", "list", "=", "append", "(", "list", ",", "file", ".", "Name", "(", ")", ")", "\n", "}", "\n", "}", "\n\n", "return", "list", ",", "nil", "\n", "}" ]
// FunctionDirNames returns a list of function directory names.
[ "FunctionDirNames", "returns", "a", "list", "of", "function", "directory", "names", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/project/project.go#L287-L302
train
apex/apex
project/project.go
LoadEnvFromFile
func (p *Project) LoadEnvFromFile(path string) error { p.Log.Debugf("load env from file %q", path) var env map[string]string f, err := os.Open(path) if err != nil { return err } defer f.Close() if err := json.NewDecoder(f).Decode(&env); err != nil { return err } for k, v := range env { p.Setenv(k, v) } return nil }
go
func (p *Project) LoadEnvFromFile(path string) error { p.Log.Debugf("load env from file %q", path) var env map[string]string f, err := os.Open(path) if err != nil { return err } defer f.Close() if err := json.NewDecoder(f).Decode(&env); err != nil { return err } for k, v := range env { p.Setenv(k, v) } return nil }
[ "func", "(", "p", "*", "Project", ")", "LoadEnvFromFile", "(", "path", "string", ")", "error", "{", "p", ".", "Log", ".", "Debugf", "(", "\"", "\"", ",", "path", ")", "\n", "var", "env", "map", "[", "string", "]", "string", "\n\n", "f", ",", "err", ":=", "os", ".", "Open", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "if", "err", ":=", "json", ".", "NewDecoder", "(", "f", ")", ".", "Decode", "(", "&", "env", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "for", "k", ",", "v", ":=", "range", "env", "{", "p", ".", "Setenv", "(", "k", ",", "v", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// LoadEnvFromFile reads `path` JSON and applies it to the environment.
[ "LoadEnvFromFile", "reads", "path", "JSON", "and", "applies", "it", "to", "the", "environment", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/project/project.go#L305-L324
train
apex/apex
project/project.go
Setenv
func (p *Project) Setenv(name, value string) { for _, fn := range p.Functions { fn.Setenv(name, value) } }
go
func (p *Project) Setenv(name, value string) { for _, fn := range p.Functions { fn.Setenv(name, value) } }
[ "func", "(", "p", "*", "Project", ")", "Setenv", "(", "name", ",", "value", "string", ")", "{", "for", "_", ",", "fn", ":=", "range", "p", ".", "Functions", "{", "fn", ".", "Setenv", "(", "name", ",", "value", ")", "\n", "}", "\n", "}" ]
// Setenv sets environment variable `name` to `value` on every function in project.
[ "Setenv", "sets", "environment", "variable", "name", "to", "value", "on", "every", "function", "in", "project", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/project/project.go#L327-L331
train
apex/apex
project/project.go
LoadFunctionByPath
func (p *Project) LoadFunctionByPath(name, path string) (*function.Function, error) { fn := &function.Function{ Config: function.Config{ Runtime: p.Runtime, Memory: p.Memory, Timeout: p.Timeout, Role: p.Role, Handler: p.Handler, Shim: p.Shim, Hooks: p.Hooks, Environment: copyStringMap(p.Config.Environment), RetainedVersions: p.RetainedVersions, VPC: copyVPC(p.VPC), Zip: p.Zip, }, Name: name, Path: path, Log: p.Log, IgnoreFile: p.IgnoreFile, Alias: p.Alias, } if name, err := p.name(fn); err == nil { fn.FunctionName = name } else { return nil, err } if err := fn.Open(p.Environment); err != nil { return nil, err } fn.Service = p.ServiceProvider.NewService(fn.AWSConfig()) return fn, nil }
go
func (p *Project) LoadFunctionByPath(name, path string) (*function.Function, error) { fn := &function.Function{ Config: function.Config{ Runtime: p.Runtime, Memory: p.Memory, Timeout: p.Timeout, Role: p.Role, Handler: p.Handler, Shim: p.Shim, Hooks: p.Hooks, Environment: copyStringMap(p.Config.Environment), RetainedVersions: p.RetainedVersions, VPC: copyVPC(p.VPC), Zip: p.Zip, }, Name: name, Path: path, Log: p.Log, IgnoreFile: p.IgnoreFile, Alias: p.Alias, } if name, err := p.name(fn); err == nil { fn.FunctionName = name } else { return nil, err } if err := fn.Open(p.Environment); err != nil { return nil, err } fn.Service = p.ServiceProvider.NewService(fn.AWSConfig()) return fn, nil }
[ "func", "(", "p", "*", "Project", ")", "LoadFunctionByPath", "(", "name", ",", "path", "string", ")", "(", "*", "function", ".", "Function", ",", "error", ")", "{", "fn", ":=", "&", "function", ".", "Function", "{", "Config", ":", "function", ".", "Config", "{", "Runtime", ":", "p", ".", "Runtime", ",", "Memory", ":", "p", ".", "Memory", ",", "Timeout", ":", "p", ".", "Timeout", ",", "Role", ":", "p", ".", "Role", ",", "Handler", ":", "p", ".", "Handler", ",", "Shim", ":", "p", ".", "Shim", ",", "Hooks", ":", "p", ".", "Hooks", ",", "Environment", ":", "copyStringMap", "(", "p", ".", "Config", ".", "Environment", ")", ",", "RetainedVersions", ":", "p", ".", "RetainedVersions", ",", "VPC", ":", "copyVPC", "(", "p", ".", "VPC", ")", ",", "Zip", ":", "p", ".", "Zip", ",", "}", ",", "Name", ":", "name", ",", "Path", ":", "path", ",", "Log", ":", "p", ".", "Log", ",", "IgnoreFile", ":", "p", ".", "IgnoreFile", ",", "Alias", ":", "p", ".", "Alias", ",", "}", "\n\n", "if", "name", ",", "err", ":=", "p", ".", "name", "(", "fn", ")", ";", "err", "==", "nil", "{", "fn", ".", "FunctionName", "=", "name", "\n", "}", "else", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "err", ":=", "fn", ".", "Open", "(", "p", ".", "Environment", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "fn", ".", "Service", "=", "p", ".", "ServiceProvider", ".", "NewService", "(", "fn", ".", "AWSConfig", "(", ")", ")", "\n\n", "return", "fn", ",", "nil", "\n", "}" ]
// LoadFunctionByPath returns the function in the given directory.
[ "LoadFunctionByPath", "returns", "the", "function", "in", "the", "given", "directory", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/project/project.go#L339-L374
train
apex/apex
project/project.go
CreateOrUpdateAlias
func (p *Project) CreateOrUpdateAlias(alias, version string) error { p.Log.Debugf("updating %d functions", len(p.Functions)) sem := make(semaphore.Semaphore, p.Concurrency) errs := make(chan error) go func() { for _, fn := range p.Functions { fn := fn sem.Acquire() go func() { defer sem.Release() version, err := fn.GetVersionFromAlias(version) if err != nil { err = fmt.Errorf("function %s: %s", fn.Name, err) } err = fn.CreateOrUpdateAlias(alias, version) if err != nil { err = fmt.Errorf("function %s: %s", fn.Name, err) } errs <- err }() } sem.Wait() close(errs) }() for err := range errs { if err != nil { return err } } return nil }
go
func (p *Project) CreateOrUpdateAlias(alias, version string) error { p.Log.Debugf("updating %d functions", len(p.Functions)) sem := make(semaphore.Semaphore, p.Concurrency) errs := make(chan error) go func() { for _, fn := range p.Functions { fn := fn sem.Acquire() go func() { defer sem.Release() version, err := fn.GetVersionFromAlias(version) if err != nil { err = fmt.Errorf("function %s: %s", fn.Name, err) } err = fn.CreateOrUpdateAlias(alias, version) if err != nil { err = fmt.Errorf("function %s: %s", fn.Name, err) } errs <- err }() } sem.Wait() close(errs) }() for err := range errs { if err != nil { return err } } return nil }
[ "func", "(", "p", "*", "Project", ")", "CreateOrUpdateAlias", "(", "alias", ",", "version", "string", ")", "error", "{", "p", ".", "Log", ".", "Debugf", "(", "\"", "\"", ",", "len", "(", "p", ".", "Functions", ")", ")", "\n\n", "sem", ":=", "make", "(", "semaphore", ".", "Semaphore", ",", "p", ".", "Concurrency", ")", "\n", "errs", ":=", "make", "(", "chan", "error", ")", "\n\n", "go", "func", "(", ")", "{", "for", "_", ",", "fn", ":=", "range", "p", ".", "Functions", "{", "fn", ":=", "fn", "\n", "sem", ".", "Acquire", "(", ")", "\n\n", "go", "func", "(", ")", "{", "defer", "sem", ".", "Release", "(", ")", "\n\n", "version", ",", "err", ":=", "fn", ".", "GetVersionFromAlias", "(", "version", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "fn", ".", "Name", ",", "err", ")", "\n", "}", "\n\n", "err", "=", "fn", ".", "CreateOrUpdateAlias", "(", "alias", ",", "version", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "fn", ".", "Name", ",", "err", ")", "\n", "}", "\n\n", "errs", "<-", "err", "\n", "}", "(", ")", "\n", "}", "\n\n", "sem", ".", "Wait", "(", ")", "\n", "close", "(", "errs", ")", "\n", "}", "(", ")", "\n\n", "for", "err", ":=", "range", "errs", "{", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// CreateOrUpdateAlias ensures the given `alias` is available for `version`.
[ "CreateOrUpdateAlias", "ensures", "the", "given", "alias", "is", "available", "for", "version", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/project/project.go#L377-L416
train
apex/apex
project/project.go
name
func (p *Project) name(fn *function.Function) (string, error) { data := struct { Project *Project Function *function.Function }{ Project: p, Function: fn, } name, err := render(p.nameTemplate, data) if err != nil { return "", err } return name, nil }
go
func (p *Project) name(fn *function.Function) (string, error) { data := struct { Project *Project Function *function.Function }{ Project: p, Function: fn, } name, err := render(p.nameTemplate, data) if err != nil { return "", err } return name, nil }
[ "func", "(", "p", "*", "Project", ")", "name", "(", "fn", "*", "function", ".", "Function", ")", "(", "string", ",", "error", ")", "{", "data", ":=", "struct", "{", "Project", "*", "Project", "\n", "Function", "*", "function", ".", "Function", "\n", "}", "{", "Project", ":", "p", ",", "Function", ":", "fn", ",", "}", "\n\n", "name", ",", "err", ":=", "render", "(", "p", ".", "nameTemplate", ",", "data", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "name", ",", "nil", "\n", "}" ]
// name returns the computed name for `fn`, using the nameTemplate.
[ "name", "returns", "the", "computed", "name", "for", "fn", "using", "the", "nameTemplate", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/project/project.go#L419-L434
train
apex/apex
project/project.go
readInfraRole
func (p *Project) readInfraRole() string { role, err := infra.Output(p.InfraEnvironment, "lambda_function_role_id") if err != nil { p.Log.Debugf("couldn't read role from infrastructure: %s", err) return "" } return role }
go
func (p *Project) readInfraRole() string { role, err := infra.Output(p.InfraEnvironment, "lambda_function_role_id") if err != nil { p.Log.Debugf("couldn't read role from infrastructure: %s", err) return "" } return role }
[ "func", "(", "p", "*", "Project", ")", "readInfraRole", "(", ")", "string", "{", "role", ",", "err", ":=", "infra", ".", "Output", "(", "p", ".", "InfraEnvironment", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "p", ".", "Log", ".", "Debugf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\"", "\"", "\n", "}", "\n\n", "return", "role", "\n", "}" ]
// readInfraRole reads lambda function IAM role from infrastructure
[ "readInfraRole", "reads", "lambda", "function", "IAM", "role", "from", "infrastructure" ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/project/project.go#L437-L445
train
apex/apex
project/project.go
render
func render(t *template.Template, v interface{}) (string, error) { buf := new(bytes.Buffer) if err := t.Execute(buf, v); err != nil { return "", err } return buf.String(), nil }
go
func render(t *template.Template, v interface{}) (string, error) { buf := new(bytes.Buffer) if err := t.Execute(buf, v); err != nil { return "", err } return buf.String(), nil }
[ "func", "render", "(", "t", "*", "template", ".", "Template", ",", "v", "interface", "{", "}", ")", "(", "string", ",", "error", ")", "{", "buf", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n\n", "if", "err", ":=", "t", ".", "Execute", "(", "buf", ",", "v", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "buf", ".", "String", "(", ")", ",", "nil", "\n", "}" ]
// render returns a string by executing template `t` against the given value `v`.
[ "render", "returns", "a", "string", "by", "executing", "template", "t", "against", "the", "given", "value", "v", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/project/project.go#L448-L456
train
apex/apex
project/project.go
copyVPC
func copyVPC(in vpc.VPC) vpc.VPC { securityGroups := make([]string, len(in.SecurityGroups)) copy(securityGroups, in.SecurityGroups) subnets := make([]string, len(in.Subnets)) copy(subnets, in.Subnets) return vpc.VPC{ SecurityGroups: securityGroups, Subnets: subnets, } }
go
func copyVPC(in vpc.VPC) vpc.VPC { securityGroups := make([]string, len(in.SecurityGroups)) copy(securityGroups, in.SecurityGroups) subnets := make([]string, len(in.Subnets)) copy(subnets, in.Subnets) return vpc.VPC{ SecurityGroups: securityGroups, Subnets: subnets, } }
[ "func", "copyVPC", "(", "in", "vpc", ".", "VPC", ")", "vpc", ".", "VPC", "{", "securityGroups", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "in", ".", "SecurityGroups", ")", ")", "\n", "copy", "(", "securityGroups", ",", "in", ".", "SecurityGroups", ")", "\n", "subnets", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "in", ".", "Subnets", ")", ")", "\n", "copy", "(", "subnets", ",", "in", ".", "Subnets", ")", "\n\n", "return", "vpc", ".", "VPC", "{", "SecurityGroups", ":", "securityGroups", ",", "Subnets", ":", "subnets", ",", "}", "\n", "}" ]
// copyVPC returns a copy of `in`.
[ "copyVPC", "returns", "a", "copy", "of", "in", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/project/project.go#L468-L478
train
apex/apex
project/project.go
matches
func matches(name string, patterns []string) (bool, error) { if len(patterns) == 0 { return true, nil } for _, pattern := range patterns { match, err := filepath.Match(pattern, name) if err != nil { return false, err } if match { return true, nil } } return false, nil }
go
func matches(name string, patterns []string) (bool, error) { if len(patterns) == 0 { return true, nil } for _, pattern := range patterns { match, err := filepath.Match(pattern, name) if err != nil { return false, err } if match { return true, nil } } return false, nil }
[ "func", "matches", "(", "name", "string", ",", "patterns", "[", "]", "string", ")", "(", "bool", ",", "error", ")", "{", "if", "len", "(", "patterns", ")", "==", "0", "{", "return", "true", ",", "nil", "\n", "}", "\n\n", "for", "_", ",", "pattern", ":=", "range", "patterns", "{", "match", ",", "err", ":=", "filepath", ".", "Match", "(", "pattern", ",", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n\n", "if", "match", "{", "return", "true", ",", "nil", "\n", "}", "\n", "}", "\n\n", "return", "false", ",", "nil", "\n", "}" ]
// matches returns true if `name` is matched by any of the given `patterns`, // or if zero `patterns` are provided.
[ "matches", "returns", "true", "if", "name", "is", "matched", "by", "any", "of", "the", "given", "patterns", "or", "if", "zero", "patterns", "are", "provided", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/project/project.go#L482-L499
train
apex/apex
internal/progressreader/progressreader.go
Read
func (r *reader) Read(b []byte) (int, error) { r.Do(term.ClearAll) n, err := r.ReadCloser.Read(b) r.written += n r.p.ValueInt(r.written) r.render(term.CenterLine(r.p.String())) return n, err }
go
func (r *reader) Read(b []byte) (int, error) { r.Do(term.ClearAll) n, err := r.ReadCloser.Read(b) r.written += n r.p.ValueInt(r.written) r.render(term.CenterLine(r.p.String())) return n, err }
[ "func", "(", "r", "*", "reader", ")", "Read", "(", "b", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "r", ".", "Do", "(", "term", ".", "ClearAll", ")", "\n", "n", ",", "err", ":=", "r", ".", "ReadCloser", ".", "Read", "(", "b", ")", "\n", "r", ".", "written", "+=", "n", "\n", "r", ".", "p", ".", "ValueInt", "(", "r", ".", "written", ")", "\n", "r", ".", "render", "(", "term", ".", "CenterLine", "(", "r", ".", "p", ".", "String", "(", ")", ")", ")", "\n", "return", "n", ",", "err", "\n", "}" ]
// Read implementation.
[ "Read", "implementation", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/progressreader/progressreader.go#L24-L31
train
apex/apex
internal/progressreader/progressreader.go
New
func New(size int, r io.ReadCloser) io.ReadCloser { return &reader{ ReadCloser: r, p: util.NewProgressInt(size), render: term.Renderer(), } }
go
func New(size int, r io.ReadCloser) io.ReadCloser { return &reader{ ReadCloser: r, p: util.NewProgressInt(size), render: term.Renderer(), } }
[ "func", "New", "(", "size", "int", ",", "r", "io", ".", "ReadCloser", ")", "io", ".", "ReadCloser", "{", "return", "&", "reader", "{", "ReadCloser", ":", "r", ",", "p", ":", "util", ".", "NewProgressInt", "(", "size", ")", ",", "render", ":", "term", ".", "Renderer", "(", ")", ",", "}", "\n", "}" ]
// New returns a progress bar reader.
[ "New", "returns", "a", "progress", "bar", "reader", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/progressreader/progressreader.go#L34-L40
train
apex/apex
metrics/metric.go
Collect
func (m *Metric) Collect() (a AggregatedMetrics) { for n := range m.collect(m.gen()) { value := aggregate(n.Value) switch n.Name { case "Duration": a.Duration = value case "Errors": a.Errors = value case "Invocations": a.Invocations = value case "Throttles": a.Throttles = value } } return }
go
func (m *Metric) Collect() (a AggregatedMetrics) { for n := range m.collect(m.gen()) { value := aggregate(n.Value) switch n.Name { case "Duration": a.Duration = value case "Errors": a.Errors = value case "Invocations": a.Invocations = value case "Throttles": a.Throttles = value } } return }
[ "func", "(", "m", "*", "Metric", ")", "Collect", "(", ")", "(", "a", "AggregatedMetrics", ")", "{", "for", "n", ":=", "range", "m", ".", "collect", "(", "m", ".", "gen", "(", ")", ")", "{", "value", ":=", "aggregate", "(", "n", ".", "Value", ")", "\n\n", "switch", "n", ".", "Name", "{", "case", "\"", "\"", ":", "a", ".", "Duration", "=", "value", "\n", "case", "\"", "\"", ":", "a", ".", "Errors", "=", "value", "\n", "case", "\"", "\"", ":", "a", ".", "Invocations", "=", "value", "\n", "case", "\"", "\"", ":", "a", ".", "Throttles", "=", "value", "\n", "}", "\n", "}", "\n\n", "return", "\n", "}" ]
// Collect and aggregate metrics for on function.
[ "Collect", "and", "aggregate", "metrics", "for", "on", "function", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/metrics/metric.go#L21-L38
train
apex/apex
metrics/metric.go
stats
func (m *Metric) stats(name string) (*cloudwatch.GetMetricStatisticsOutput, error) { return m.Service.GetMetricStatistics(&cloudwatch.GetMetricStatisticsInput{ StartTime: &m.StartDate, EndTime: &m.EndDate, MetricName: &name, Namespace: aws.String("AWS/Lambda"), Period: aws.Int64(int64(period(m.StartDate, m.EndDate).Seconds())), Statistics: []*string{ aws.String("Sum"), }, Dimensions: []*cloudwatch.Dimension{ { Name: aws.String("FunctionName"), Value: &m.FunctionName, }, }, Unit: aws.String(unit(name)), }) }
go
func (m *Metric) stats(name string) (*cloudwatch.GetMetricStatisticsOutput, error) { return m.Service.GetMetricStatistics(&cloudwatch.GetMetricStatisticsInput{ StartTime: &m.StartDate, EndTime: &m.EndDate, MetricName: &name, Namespace: aws.String("AWS/Lambda"), Period: aws.Int64(int64(period(m.StartDate, m.EndDate).Seconds())), Statistics: []*string{ aws.String("Sum"), }, Dimensions: []*cloudwatch.Dimension{ { Name: aws.String("FunctionName"), Value: &m.FunctionName, }, }, Unit: aws.String(unit(name)), }) }
[ "func", "(", "m", "*", "Metric", ")", "stats", "(", "name", "string", ")", "(", "*", "cloudwatch", ".", "GetMetricStatisticsOutput", ",", "error", ")", "{", "return", "m", ".", "Service", ".", "GetMetricStatistics", "(", "&", "cloudwatch", ".", "GetMetricStatisticsInput", "{", "StartTime", ":", "&", "m", ".", "StartDate", ",", "EndTime", ":", "&", "m", ".", "EndDate", ",", "MetricName", ":", "&", "name", ",", "Namespace", ":", "aws", ".", "String", "(", "\"", "\"", ")", ",", "Period", ":", "aws", ".", "Int64", "(", "int64", "(", "period", "(", "m", ".", "StartDate", ",", "m", ".", "EndDate", ")", ".", "Seconds", "(", ")", ")", ")", ",", "Statistics", ":", "[", "]", "*", "string", "{", "aws", ".", "String", "(", "\"", "\"", ")", ",", "}", ",", "Dimensions", ":", "[", "]", "*", "cloudwatch", ".", "Dimension", "{", "{", "Name", ":", "aws", ".", "String", "(", "\"", "\"", ")", ",", "Value", ":", "&", "m", ".", "FunctionName", ",", "}", ",", "}", ",", "Unit", ":", "aws", ".", "String", "(", "unit", "(", "name", ")", ")", ",", "}", ")", "\n", "}" ]
// stats for function `name`.
[ "stats", "for", "function", "name", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/metrics/metric.go#L47-L65
train
apex/apex
metrics/metric.go
collect
func (m *Metric) collect(in <-chan string) <-chan cloudWatchMetric { var wg sync.WaitGroup out := make(chan cloudWatchMetric) for name := range in { wg.Add(1) name := name go func() { defer wg.Done() res, err := m.stats(name) if err != nil { // TODO: refactor so that errors are reported in cmd fmt.Println(err.Error()) return } out <- cloudWatchMetric{ Name: name, Value: res.Datapoints, } }() } go func() { wg.Wait() close(out) }() return out }
go
func (m *Metric) collect(in <-chan string) <-chan cloudWatchMetric { var wg sync.WaitGroup out := make(chan cloudWatchMetric) for name := range in { wg.Add(1) name := name go func() { defer wg.Done() res, err := m.stats(name) if err != nil { // TODO: refactor so that errors are reported in cmd fmt.Println(err.Error()) return } out <- cloudWatchMetric{ Name: name, Value: res.Datapoints, } }() } go func() { wg.Wait() close(out) }() return out }
[ "func", "(", "m", "*", "Metric", ")", "collect", "(", "in", "<-", "chan", "string", ")", "<-", "chan", "cloudWatchMetric", "{", "var", "wg", "sync", ".", "WaitGroup", "\n", "out", ":=", "make", "(", "chan", "cloudWatchMetric", ")", "\n\n", "for", "name", ":=", "range", "in", "{", "wg", ".", "Add", "(", "1", ")", "\n", "name", ":=", "name", "\n\n", "go", "func", "(", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n\n", "res", ",", "err", ":=", "m", ".", "stats", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "// TODO: refactor so that errors are reported in cmd", "fmt", ".", "Println", "(", "err", ".", "Error", "(", ")", ")", "\n", "return", "\n", "}", "\n\n", "out", "<-", "cloudWatchMetric", "{", "Name", ":", "name", ",", "Value", ":", "res", ".", "Datapoints", ",", "}", "\n", "}", "(", ")", "\n", "}", "\n\n", "go", "func", "(", ")", "{", "wg", ".", "Wait", "(", ")", "\n", "close", "(", "out", ")", "\n", "}", "(", ")", "\n\n", "return", "out", "\n", "}" ]
// collect starts a new cloudwatch session and requests the key metrics.
[ "collect", "starts", "a", "new", "cloudwatch", "session", "and", "requests", "the", "key", "metrics", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/metrics/metric.go#L68-L99
train
apex/apex
metrics/metric.go
gen
func (m *Metric) gen() <-chan string { out := make(chan string, len(metricsNames)) for _, n := range metricsNames { out <- n } close(out) return out }
go
func (m *Metric) gen() <-chan string { out := make(chan string, len(metricsNames)) for _, n := range metricsNames { out <- n } close(out) return out }
[ "func", "(", "m", "*", "Metric", ")", "gen", "(", ")", "<-", "chan", "string", "{", "out", ":=", "make", "(", "chan", "string", ",", "len", "(", "metricsNames", ")", ")", "\n", "for", "_", ",", "n", ":=", "range", "metricsNames", "{", "out", "<-", "n", "\n", "}", "\n", "close", "(", "out", ")", "\n", "return", "out", "\n", "}" ]
// gen generates the key metric structs and returns a channel pipeline.
[ "gen", "generates", "the", "key", "metric", "structs", "and", "returns", "a", "channel", "pipeline", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/metrics/metric.go#L102-L109
train
apex/apex
metrics/metric.go
period
func period(start, end time.Time) time.Duration { switch n := end.Sub(start).Hours(); { case n > 24: return time.Hour * 24 default: return time.Hour } }
go
func period(start, end time.Time) time.Duration { switch n := end.Sub(start).Hours(); { case n > 24: return time.Hour * 24 default: return time.Hour } }
[ "func", "period", "(", "start", ",", "end", "time", ".", "Time", ")", "time", ".", "Duration", "{", "switch", "n", ":=", "end", ".", "Sub", "(", "start", ")", ".", "Hours", "(", ")", ";", "{", "case", "n", ">", "24", ":", "return", "time", ".", "Hour", "*", "24", "\n", "default", ":", "return", "time", ".", "Hour", "\n", "}", "\n", "}" ]
// period returns the resolution of metrics.
[ "period", "returns", "the", "resolution", "of", "metrics", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/metrics/metric.go#L112-L119
train
apex/apex
metrics/metric.go
aggregate
func aggregate(datapoints []*cloudwatch.Datapoint) int { sum := 0.0 for _, datapoint := range datapoints { sum += *datapoint.Sum } return int(sum) }
go
func aggregate(datapoints []*cloudwatch.Datapoint) int { sum := 0.0 for _, datapoint := range datapoints { sum += *datapoint.Sum } return int(sum) }
[ "func", "aggregate", "(", "datapoints", "[", "]", "*", "cloudwatch", ".", "Datapoint", ")", "int", "{", "sum", ":=", "0.0", "\n\n", "for", "_", ",", "datapoint", ":=", "range", "datapoints", "{", "sum", "+=", "*", "datapoint", ".", "Sum", "\n", "}", "\n\n", "return", "int", "(", "sum", ")", "\n", "}" ]
// aggregate accumulates the datapoints.
[ "aggregate", "accumulates", "the", "datapoints", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/metrics/metric.go#L132-L140
train
apex/apex
plugins/hooks/hooks.go
Error
func (e *HookError) Error() string { return fmt.Sprintf("%s hook: %s", e.Hook, e.Output) }
go
func (e *HookError) Error() string { return fmt.Sprintf("%s hook: %s", e.Hook, e.Output) }
[ "func", "(", "e", "*", "HookError", ")", "Error", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "e", ".", "Hook", ",", "e", ".", "Output", ")", "\n", "}" ]
// Error string.
[ "Error", "string", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/plugins/hooks/hooks.go#L28-L30
train
apex/apex
plugins/hooks/hooks.go
Build
func (p *Plugin) Build(fn *function.Function, zip *archive.Zip) error { return p.run("build", fn.Hooks.Build, fn) }
go
func (p *Plugin) Build(fn *function.Function, zip *archive.Zip) error { return p.run("build", fn.Hooks.Build, fn) }
[ "func", "(", "p", "*", "Plugin", ")", "Build", "(", "fn", "*", "function", ".", "Function", ",", "zip", "*", "archive", ".", "Zip", ")", "error", "{", "return", "p", ".", "run", "(", "\"", "\"", ",", "fn", ".", "Hooks", ".", "Build", ",", "fn", ")", "\n", "}" ]
// Build runs the "build" hook commands.
[ "Build", "runs", "the", "build", "hook", "commands", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/plugins/hooks/hooks.go#L36-L38
train
apex/apex
plugins/hooks/hooks.go
Deploy
func (p *Plugin) Deploy(fn *function.Function) error { return p.run("deploy", fn.Hooks.Deploy, fn) }
go
func (p *Plugin) Deploy(fn *function.Function) error { return p.run("deploy", fn.Hooks.Deploy, fn) }
[ "func", "(", "p", "*", "Plugin", ")", "Deploy", "(", "fn", "*", "function", ".", "Function", ")", "error", "{", "return", "p", ".", "run", "(", "\"", "\"", ",", "fn", ".", "Hooks", ".", "Deploy", ",", "fn", ")", "\n", "}" ]
// Deploy runs the "deploy" hook commands.
[ "Deploy", "runs", "the", "deploy", "hook", "commands", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/plugins/hooks/hooks.go#L46-L48
train
apex/apex
plugins/hooks/hooks.go
run
func (p *Plugin) run(hook, command string, fn *function.Function) error { if command == "" { return nil } fn.Log.WithFields(log.Fields{ "hook": hook, "command": command, }).Debug("hook") var cmd *exec.Cmd if runtime.GOOS == "windows" { cmd = exec.Command("cmd", "/c", command) } else { cmd = exec.Command("sh", "-c", command) } cmd.Env = os.Environ() cmd.Dir = fn.Path b, err := cmd.CombinedOutput() if err != nil { return &HookError{ Hook: hook, Command: command, Output: string(b), } } return nil }
go
func (p *Plugin) run(hook, command string, fn *function.Function) error { if command == "" { return nil } fn.Log.WithFields(log.Fields{ "hook": hook, "command": command, }).Debug("hook") var cmd *exec.Cmd if runtime.GOOS == "windows" { cmd = exec.Command("cmd", "/c", command) } else { cmd = exec.Command("sh", "-c", command) } cmd.Env = os.Environ() cmd.Dir = fn.Path b, err := cmd.CombinedOutput() if err != nil { return &HookError{ Hook: hook, Command: command, Output: string(b), } } return nil }
[ "func", "(", "p", "*", "Plugin", ")", "run", "(", "hook", ",", "command", "string", ",", "fn", "*", "function", ".", "Function", ")", "error", "{", "if", "command", "==", "\"", "\"", "{", "return", "nil", "\n", "}", "\n\n", "fn", ".", "Log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "hook", ",", "\"", "\"", ":", "command", ",", "}", ")", ".", "Debug", "(", "\"", "\"", ")", "\n\n", "var", "cmd", "*", "exec", ".", "Cmd", "\n", "if", "runtime", ".", "GOOS", "==", "\"", "\"", "{", "cmd", "=", "exec", ".", "Command", "(", "\"", "\"", ",", "\"", "\"", ",", "command", ")", "\n", "}", "else", "{", "cmd", "=", "exec", ".", "Command", "(", "\"", "\"", ",", "\"", "\"", ",", "command", ")", "\n", "}", "\n", "cmd", ".", "Env", "=", "os", ".", "Environ", "(", ")", "\n", "cmd", ".", "Dir", "=", "fn", ".", "Path", "\n\n", "b", ",", "err", ":=", "cmd", ".", "CombinedOutput", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "HookError", "{", "Hook", ":", "hook", ",", "Command", ":", "command", ",", "Output", ":", "string", "(", "b", ")", ",", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// run a hook command.
[ "run", "a", "hook", "command", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/plugins/hooks/hooks.go#L51-L80
train
apex/apex
internal/util/util.go
ClearHeader
func ClearHeader(h http.Header) { for k := range h { if keepFields[k] { continue } h.Del(k) } }
go
func ClearHeader(h http.Header) { for k := range h { if keepFields[k] { continue } h.Del(k) } }
[ "func", "ClearHeader", "(", "h", "http", ".", "Header", ")", "{", "for", "k", ":=", "range", "h", "{", "if", "keepFields", "[", "k", "]", "{", "continue", "\n", "}", "\n\n", "h", ".", "Del", "(", "k", ")", "\n", "}", "\n", "}" ]
// ClearHeader removes all header fields.
[ "ClearHeader", "removes", "all", "header", "fields", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L38-L46
train
apex/apex
internal/util/util.go
ReadFileJSON
func ReadFileJSON(path string, v interface{}) error { b, err := ioutil.ReadFile(path) if err != nil { return errors.Wrap(err, "reading") } if err := json.Unmarshal(b, &v); err != nil { return errors.Wrap(err, "unmarshaling") } return nil }
go
func ReadFileJSON(path string, v interface{}) error { b, err := ioutil.ReadFile(path) if err != nil { return errors.Wrap(err, "reading") } if err := json.Unmarshal(b, &v); err != nil { return errors.Wrap(err, "unmarshaling") } return nil }
[ "func", "ReadFileJSON", "(", "path", "string", ",", "v", "interface", "{", "}", ")", "error", "{", "b", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "b", ",", "&", "v", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// ReadFileJSON reads json from the given path.
[ "ReadFileJSON", "reads", "json", "from", "the", "given", "path", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L64-L75
train
apex/apex
internal/util/util.go
Camelcase
func Camelcase(s string, v ...interface{}) string { return name.CamelCase(fmt.Sprintf(s, v...), true) }
go
func Camelcase(s string, v ...interface{}) string { return name.CamelCase(fmt.Sprintf(s, v...), true) }
[ "func", "Camelcase", "(", "s", "string", ",", "v", "...", "interface", "{", "}", ")", "string", "{", "return", "name", ".", "CamelCase", "(", "fmt", ".", "Sprintf", "(", "s", ",", "v", "...", ")", ",", "true", ")", "\n", "}" ]
// Camelcase string with optional args.
[ "Camelcase", "string", "with", "optional", "args", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L78-L80
train
apex/apex
internal/util/util.go
NewInlineProgressInt
func NewInlineProgressInt(total int) *progress.Bar { b := progress.NewInt(total) b.Template(`{{.Bar}} {{.Percent | printf "%0.0f"}}% {{.Text}}`) b.Width = 20 b.StartDelimiter = colors.Gray("|") b.EndDelimiter = colors.Gray("|") b.Filled = colors.Purple("█") b.Empty = colors.Gray(" ") return b }
go
func NewInlineProgressInt(total int) *progress.Bar { b := progress.NewInt(total) b.Template(`{{.Bar}} {{.Percent | printf "%0.0f"}}% {{.Text}}`) b.Width = 20 b.StartDelimiter = colors.Gray("|") b.EndDelimiter = colors.Gray("|") b.Filled = colors.Purple("█") b.Empty = colors.Gray(" ") return b }
[ "func", "NewInlineProgressInt", "(", "total", "int", ")", "*", "progress", ".", "Bar", "{", "b", ":=", "progress", ".", "NewInt", "(", "total", ")", "\n", "b", ".", "Template", "(", "`{{.Bar}} {{.Percent | printf \"%0.0f\"}}% {{.Text}}`", ")", "\n", "b", ".", "Width", "=", "20", "\n", "b", ".", "StartDelimiter", "=", "colors", ".", "Gray", "(", "\"", "\"", ")", "\n", "b", ".", "EndDelimiter", "=", "colors", ".", "Gray", "(", "\"", "\"", ")", "\n", "b", ".", "Filled", "=", "colors", ".", "Purple", "(", "\"", "", "", "\n", "b", ".", "Empty", "=", "colors", ".", "Gray", "(", "\"", "\"", ")", "\n", "return", "b", "\n", "}" ]
// NewInlineProgressInt with the given total.
[ "NewInlineProgressInt", "with", "the", "given", "total", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L95-L104
train
apex/apex
internal/util/util.go
Fatal
func Fatal(err error) { fmt.Fprintf(os.Stderr, "\n %s %s\n\n", colors.Red("Error:"), err) os.Exit(1) }
go
func Fatal(err error) { fmt.Fprintf(os.Stderr, "\n %s %s\n\n", colors.Red("Error:"), err) os.Exit(1) }
[ "func", "Fatal", "(", "err", "error", ")", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\\n", "\\n", "\\n", "\"", ",", "colors", ".", "Red", "(", "\"", "\"", ")", ",", "err", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}" ]
// Fatal error.
[ "Fatal", "error", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L115-L118
train
apex/apex
internal/util/util.go
IsJSON
func IsJSON(s string) bool { return len(s) > 1 && s[0] == '{' && s[len(s)-1] == '}' }
go
func IsJSON(s string) bool { return len(s) > 1 && s[0] == '{' && s[len(s)-1] == '}' }
[ "func", "IsJSON", "(", "s", "string", ")", "bool", "{", "return", "len", "(", "s", ")", ">", "1", "&&", "s", "[", "0", "]", "==", "'{'", "&&", "s", "[", "len", "(", "s", ")", "-", "1", "]", "==", "'}'", "\n", "}" ]
// IsJSON returns true if the string looks like json.
[ "IsJSON", "returns", "true", "if", "the", "string", "looks", "like", "json", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L121-L123
train
apex/apex
internal/util/util.go
IsNotFound
func IsNotFound(err error) bool { switch { case err == nil: return false case strings.Contains(err.Error(), "does not exist"): return true case strings.Contains(err.Error(), "not found"): return true default: return false } }
go
func IsNotFound(err error) bool { switch { case err == nil: return false case strings.Contains(err.Error(), "does not exist"): return true case strings.Contains(err.Error(), "not found"): return true default: return false } }
[ "func", "IsNotFound", "(", "err", "error", ")", "bool", "{", "switch", "{", "case", "err", "==", "nil", ":", "return", "false", "\n", "case", "strings", ".", "Contains", "(", "err", ".", "Error", "(", ")", ",", "\"", "\"", ")", ":", "return", "true", "\n", "case", "strings", ".", "Contains", "(", "err", ".", "Error", "(", ")", ",", "\"", "\"", ")", ":", "return", "true", "\n", "default", ":", "return", "false", "\n", "}", "\n", "}" ]
// IsNotFound returns true if err is not nil and represents a missing resource.
[ "IsNotFound", "returns", "true", "if", "err", "is", "not", "nil", "and", "represents", "a", "missing", "resource", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L131-L142
train
apex/apex
internal/util/util.go
Env
func Env(m map[string]string) (env []string) { for k, v := range m { env = append(env, fmt.Sprintf("%s=%s", k, v)) } return }
go
func Env(m map[string]string) (env []string) { for k, v := range m { env = append(env, fmt.Sprintf("%s=%s", k, v)) } return }
[ "func", "Env", "(", "m", "map", "[", "string", "]", "string", ")", "(", "env", "[", "]", "string", ")", "{", "for", "k", ",", "v", ":=", "range", "m", "{", "env", "=", "append", "(", "env", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "k", ",", "v", ")", ")", "\n", "}", "\n", "return", "\n", "}" ]
// Env returns a slice from environment variable map.
[ "Env", "returns", "a", "slice", "from", "environment", "variable", "map", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L157-L162
train
apex/apex
internal/util/util.go
PrefixLines
func PrefixLines(s string, prefix string) string { lines := strings.Split(s, "\n") for i, l := range lines { lines[i] = prefix + l } return strings.Join(lines, "\n") }
go
func PrefixLines(s string, prefix string) string { lines := strings.Split(s, "\n") for i, l := range lines { lines[i] = prefix + l } return strings.Join(lines, "\n") }
[ "func", "PrefixLines", "(", "s", "string", ",", "prefix", "string", ")", "string", "{", "lines", ":=", "strings", ".", "Split", "(", "s", ",", "\"", "\\n", "\"", ")", "\n", "for", "i", ",", "l", ":=", "range", "lines", "{", "lines", "[", "i", "]", "=", "prefix", "+", "l", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "lines", ",", "\"", "\\n", "\"", ")", "\n", "}" ]
// PrefixLines prefixes the lines in s with prefix.
[ "PrefixLines", "prefixes", "the", "lines", "in", "s", "with", "prefix", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L165-L171
train
apex/apex
internal/util/util.go
WaitForListen
func WaitForListen(u *url.URL, timeout time.Duration) error { timedout := time.After(timeout) b := backoff.Backoff{ Min: 100 * time.Millisecond, Max: time.Second, Factor: 1.5, } for { select { case <-timedout: return errors.Errorf("timed out after %s", timeout) case <-time.After(b.Duration()): if IsListening(u) { return nil } } } }
go
func WaitForListen(u *url.URL, timeout time.Duration) error { timedout := time.After(timeout) b := backoff.Backoff{ Min: 100 * time.Millisecond, Max: time.Second, Factor: 1.5, } for { select { case <-timedout: return errors.Errorf("timed out after %s", timeout) case <-time.After(b.Duration()): if IsListening(u) { return nil } } } }
[ "func", "WaitForListen", "(", "u", "*", "url", ".", "URL", ",", "timeout", "time", ".", "Duration", ")", "error", "{", "timedout", ":=", "time", ".", "After", "(", "timeout", ")", "\n\n", "b", ":=", "backoff", ".", "Backoff", "{", "Min", ":", "100", "*", "time", ".", "Millisecond", ",", "Max", ":", "time", ".", "Second", ",", "Factor", ":", "1.5", ",", "}", "\n\n", "for", "{", "select", "{", "case", "<-", "timedout", ":", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "timeout", ")", "\n", "case", "<-", "time", ".", "After", "(", "b", ".", "Duration", "(", ")", ")", ":", "if", "IsListening", "(", "u", ")", "{", "return", "nil", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// WaitForListen blocks until `u` is listening with timeout.
[ "WaitForListen", "blocks", "until", "u", "is", "listening", "with", "timeout", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L179-L198
train
apex/apex
internal/util/util.go
IsListening
func IsListening(u *url.URL) bool { conn, err := net.Dial("tcp", u.Host) if err != nil { return false } conn.Close() return true }
go
func IsListening(u *url.URL) bool { conn, err := net.Dial("tcp", u.Host) if err != nil { return false } conn.Close() return true }
[ "func", "IsListening", "(", "u", "*", "url", ".", "URL", ")", "bool", "{", "conn", ",", "err", ":=", "net", ".", "Dial", "(", "\"", "\"", ",", "u", ".", "Host", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n\n", "conn", ".", "Close", "(", ")", "\n", "return", "true", "\n", "}" ]
// IsListening returns true if there's a server listening on `u`.
[ "IsListening", "returns", "true", "if", "there", "s", "a", "server", "listening", "on", "u", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L201-L209
train
apex/apex
internal/util/util.go
ExitStatus
func ExitStatus(cmd *exec.Cmd, err error) string { ps := cmd.ProcessState if e, ok := err.(*exec.ExitError); ok { ps = e.ProcessState } if ps != nil { s, ok := ps.Sys().(syscall.WaitStatus) if ok { return fmt.Sprintf("%d", s.ExitStatus()) } } return "?" }
go
func ExitStatus(cmd *exec.Cmd, err error) string { ps := cmd.ProcessState if e, ok := err.(*exec.ExitError); ok { ps = e.ProcessState } if ps != nil { s, ok := ps.Sys().(syscall.WaitStatus) if ok { return fmt.Sprintf("%d", s.ExitStatus()) } } return "?" }
[ "func", "ExitStatus", "(", "cmd", "*", "exec", ".", "Cmd", ",", "err", "error", ")", "string", "{", "ps", ":=", "cmd", ".", "ProcessState", "\n\n", "if", "e", ",", "ok", ":=", "err", ".", "(", "*", "exec", ".", "ExitError", ")", ";", "ok", "{", "ps", "=", "e", ".", "ProcessState", "\n", "}", "\n\n", "if", "ps", "!=", "nil", "{", "s", ",", "ok", ":=", "ps", ".", "Sys", "(", ")", ".", "(", "syscall", ".", "WaitStatus", ")", "\n", "if", "ok", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "s", ".", "ExitStatus", "(", ")", ")", "\n", "}", "\n", "}", "\n\n", "return", "\"", "\"", "\n", "}" ]
// ExitStatus returns the exit status of cmd.
[ "ExitStatus", "returns", "the", "exit", "status", "of", "cmd", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L212-L227
train
apex/apex
internal/util/util.go
Log
func Log(msg string, v ...interface{}) { fmt.Printf(" %s\n", colors.Purple(fmt.Sprintf(msg, v...))) }
go
func Log(msg string, v ...interface{}) { fmt.Printf(" %s\n", colors.Purple(fmt.Sprintf(msg, v...))) }
[ "func", "Log", "(", "msg", "string", ",", "v", "...", "interface", "{", "}", ")", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "colors", ".", "Purple", "(", "fmt", ".", "Sprintf", "(", "msg", ",", "v", "...", ")", ")", ")", "\n", "}" ]
// Log outputs a log message.
[ "Log", "outputs", "a", "log", "message", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L252-L254
train
apex/apex
internal/util/util.go
LogClear
func LogClear(msg string, v ...interface{}) { term.MoveUp(1) term.ClearLine() fmt.Printf("\r %s\n", colors.Purple(fmt.Sprintf(msg, v...))) }
go
func LogClear(msg string, v ...interface{}) { term.MoveUp(1) term.ClearLine() fmt.Printf("\r %s\n", colors.Purple(fmt.Sprintf(msg, v...))) }
[ "func", "LogClear", "(", "msg", "string", ",", "v", "...", "interface", "{", "}", ")", "{", "term", ".", "MoveUp", "(", "1", ")", "\n", "term", ".", "ClearLine", "(", ")", "\n", "fmt", ".", "Printf", "(", "\"", "\\r", "\\n", "\"", ",", "colors", ".", "Purple", "(", "fmt", ".", "Sprintf", "(", "msg", ",", "v", "...", ")", ")", ")", "\n", "}" ]
// LogClear clears the line and outputs a log message.
[ "LogClear", "clears", "the", "line", "and", "outputs", "a", "log", "message", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L257-L261
train
apex/apex
internal/util/util.go
LogTitle
func LogTitle(msg string, v ...interface{}) { fmt.Printf("\n \x1b[1m%s\x1b[m\n\n", fmt.Sprintf(msg, v...)) }
go
func LogTitle(msg string, v ...interface{}) { fmt.Printf("\n \x1b[1m%s\x1b[m\n\n", fmt.Sprintf(msg, v...)) }
[ "func", "LogTitle", "(", "msg", "string", ",", "v", "...", "interface", "{", "}", ")", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\\x1b", "\\x1b", "\\n", "\\n", "\"", ",", "fmt", ".", "Sprintf", "(", "msg", ",", "v", "...", ")", ")", "\n", "}" ]
// LogTitle outputs a log title.
[ "LogTitle", "outputs", "a", "log", "title", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L264-L266
train
apex/apex
internal/util/util.go
LogName
func LogName(name, msg string, v ...interface{}) { fmt.Printf(" %s %s\n", colors.Purple(name+":"), fmt.Sprintf(msg, v...)) }
go
func LogName(name, msg string, v ...interface{}) { fmt.Printf(" %s %s\n", colors.Purple(name+":"), fmt.Sprintf(msg, v...)) }
[ "func", "LogName", "(", "name", ",", "msg", "string", ",", "v", "...", "interface", "{", "}", ")", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "colors", ".", "Purple", "(", "name", "+", "\"", "\"", ")", ",", "fmt", ".", "Sprintf", "(", "msg", ",", "v", "...", ")", ")", "\n", "}" ]
// LogName outputs a log message with name.
[ "LogName", "outputs", "a", "log", "message", "with", "name", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L269-L271
train
apex/apex
internal/util/util.go
LogListItem
func LogListItem(msg string, v ...interface{}) { fmt.Printf(" • %s\n", fmt.Sprintf(msg, v...)) }
go
func LogListItem(msg string, v ...interface{}) { fmt.Printf(" • %s\n", fmt.Sprintf(msg, v...)) }
[ "func", "LogListItem", "(", "msg", "string", ",", "v", "...", "interface", "{", "}", ")", "{", "fmt", ".", "Printf", "(", "\"", "\",", " ", "f", "t.S", "p", "rintf(m", "s", "g, ", "v", ".", ".))", "", "", "\n", "}" ]
// LogListItem outputs a list item.
[ "LogListItem", "outputs", "a", "list", "item", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L274-L276
train
apex/apex
internal/util/util.go
ToFloat
func ToFloat(v interface{}) float64 { switch n := v.(type) { case int: return float64(n) case int8: return float64(n) case int16: return float64(n) case int32: return float64(n) case int64: return float64(n) case uint: return float64(n) case uint8: return float64(n) case uint16: return float64(n) case uint32: return float64(n) case uint64: return float64(n) case float32: return float64(n) case float64: return n default: return math.NaN() } }
go
func ToFloat(v interface{}) float64 { switch n := v.(type) { case int: return float64(n) case int8: return float64(n) case int16: return float64(n) case int32: return float64(n) case int64: return float64(n) case uint: return float64(n) case uint8: return float64(n) case uint16: return float64(n) case uint32: return float64(n) case uint64: return float64(n) case float32: return float64(n) case float64: return n default: return math.NaN() } }
[ "func", "ToFloat", "(", "v", "interface", "{", "}", ")", "float64", "{", "switch", "n", ":=", "v", ".", "(", "type", ")", "{", "case", "int", ":", "return", "float64", "(", "n", ")", "\n", "case", "int8", ":", "return", "float64", "(", "n", ")", "\n", "case", "int16", ":", "return", "float64", "(", "n", ")", "\n", "case", "int32", ":", "return", "float64", "(", "n", ")", "\n", "case", "int64", ":", "return", "float64", "(", "n", ")", "\n", "case", "uint", ":", "return", "float64", "(", "n", ")", "\n", "case", "uint8", ":", "return", "float64", "(", "n", ")", "\n", "case", "uint16", ":", "return", "float64", "(", "n", ")", "\n", "case", "uint32", ":", "return", "float64", "(", "n", ")", "\n", "case", "uint64", ":", "return", "float64", "(", "n", ")", "\n", "case", "float32", ":", "return", "float64", "(", "n", ")", "\n", "case", "float64", ":", "return", "n", "\n", "default", ":", "return", "math", ".", "NaN", "(", ")", "\n", "}", "\n", "}" ]
// ToFloat returns a float or NaN.
[ "ToFloat", "returns", "a", "float", "or", "NaN", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L279-L308
train
apex/apex
internal/util/util.go
MillisecondsSince
func MillisecondsSince(t time.Time) int { return int(time.Since(t) / time.Millisecond) }
go
func MillisecondsSince(t time.Time) int { return int(time.Since(t) / time.Millisecond) }
[ "func", "MillisecondsSince", "(", "t", "time", ".", "Time", ")", "int", "{", "return", "int", "(", "time", ".", "Since", "(", "t", ")", "/", "time", ".", "Millisecond", ")", "\n", "}" ]
// MillisecondsSince returns the duration as milliseconds relative to time t.
[ "MillisecondsSince", "returns", "the", "duration", "as", "milliseconds", "relative", "to", "time", "t", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L316-L318
train
apex/apex
internal/util/util.go
ParseDuration
func ParseDuration(s string) (d time.Duration, err error) { r := strings.NewReader(s) switch { case strings.HasSuffix(s, "d"): var v float64 _, err = fmt.Fscanf(r, "%fd", &v) d = time.Duration(v * float64(24*time.Hour)) case strings.HasSuffix(s, "w"): var v float64 _, err = fmt.Fscanf(r, "%fw", &v) d = time.Duration(v * float64(24*time.Hour*7)) case strings.HasSuffix(s, "mo"): var v float64 _, err = fmt.Fscanf(r, "%fmo", &v) d = time.Duration(v * float64(30*24*time.Hour)) case strings.HasSuffix(s, "M"): var v float64 _, err = fmt.Fscanf(r, "%fM", &v) d = time.Duration(v * float64(30*24*time.Hour)) default: d, err = time.ParseDuration(s) } return }
go
func ParseDuration(s string) (d time.Duration, err error) { r := strings.NewReader(s) switch { case strings.HasSuffix(s, "d"): var v float64 _, err = fmt.Fscanf(r, "%fd", &v) d = time.Duration(v * float64(24*time.Hour)) case strings.HasSuffix(s, "w"): var v float64 _, err = fmt.Fscanf(r, "%fw", &v) d = time.Duration(v * float64(24*time.Hour*7)) case strings.HasSuffix(s, "mo"): var v float64 _, err = fmt.Fscanf(r, "%fmo", &v) d = time.Duration(v * float64(30*24*time.Hour)) case strings.HasSuffix(s, "M"): var v float64 _, err = fmt.Fscanf(r, "%fM", &v) d = time.Duration(v * float64(30*24*time.Hour)) default: d, err = time.ParseDuration(s) } return }
[ "func", "ParseDuration", "(", "s", "string", ")", "(", "d", "time", ".", "Duration", ",", "err", "error", ")", "{", "r", ":=", "strings", ".", "NewReader", "(", "s", ")", "\n\n", "switch", "{", "case", "strings", ".", "HasSuffix", "(", "s", ",", "\"", "\"", ")", ":", "var", "v", "float64", "\n", "_", ",", "err", "=", "fmt", ".", "Fscanf", "(", "r", ",", "\"", "\"", ",", "&", "v", ")", "\n", "d", "=", "time", ".", "Duration", "(", "v", "*", "float64", "(", "24", "*", "time", ".", "Hour", ")", ")", "\n", "case", "strings", ".", "HasSuffix", "(", "s", ",", "\"", "\"", ")", ":", "var", "v", "float64", "\n", "_", ",", "err", "=", "fmt", ".", "Fscanf", "(", "r", ",", "\"", "\"", ",", "&", "v", ")", "\n", "d", "=", "time", ".", "Duration", "(", "v", "*", "float64", "(", "24", "*", "time", ".", "Hour", "*", "7", ")", ")", "\n", "case", "strings", ".", "HasSuffix", "(", "s", ",", "\"", "\"", ")", ":", "var", "v", "float64", "\n", "_", ",", "err", "=", "fmt", ".", "Fscanf", "(", "r", ",", "\"", "\"", ",", "&", "v", ")", "\n", "d", "=", "time", ".", "Duration", "(", "v", "*", "float64", "(", "30", "*", "24", "*", "time", ".", "Hour", ")", ")", "\n", "case", "strings", ".", "HasSuffix", "(", "s", ",", "\"", "\"", ")", ":", "var", "v", "float64", "\n", "_", ",", "err", "=", "fmt", ".", "Fscanf", "(", "r", ",", "\"", "\"", ",", "&", "v", ")", "\n", "d", "=", "time", ".", "Duration", "(", "v", "*", "float64", "(", "30", "*", "24", "*", "time", ".", "Hour", ")", ")", "\n", "default", ":", "d", ",", "err", "=", "time", ".", "ParseDuration", "(", "s", ")", "\n", "}", "\n\n", "return", "\n", "}" ]
// ParseDuration string with day and month approximation support.
[ "ParseDuration", "string", "with", "day", "and", "month", "approximation", "support", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L321-L346
train
apex/apex
internal/util/util.go
ParseSections
func ParseSections(r io.Reader) (sections []string, err error) { s := bufio.NewScanner(r) for s.Scan() { t := s.Text() if strings.HasPrefix(t, "[") { sections = append(sections, strings.Trim(t, "[]")) } } err = s.Err() return }
go
func ParseSections(r io.Reader) (sections []string, err error) { s := bufio.NewScanner(r) for s.Scan() { t := s.Text() if strings.HasPrefix(t, "[") { sections = append(sections, strings.Trim(t, "[]")) } } err = s.Err() return }
[ "func", "ParseSections", "(", "r", "io", ".", "Reader", ")", "(", "sections", "[", "]", "string", ",", "err", "error", ")", "{", "s", ":=", "bufio", ".", "NewScanner", "(", "r", ")", "\n\n", "for", "s", ".", "Scan", "(", ")", "{", "t", ":=", "s", ".", "Text", "(", ")", "\n", "if", "strings", ".", "HasPrefix", "(", "t", ",", "\"", "\"", ")", "{", "sections", "=", "append", "(", "sections", ",", "strings", ".", "Trim", "(", "t", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "}", "\n\n", "err", "=", "s", ".", "Err", "(", ")", "\n\n", "return", "\n", "}" ]
// ParseSections returns INI style sections from r.
[ "ParseSections", "returns", "INI", "style", "sections", "from", "r", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/internal/util/util.go#L368-L381
train
apex/apex
cost/cost.go
Cost
func Cost(requests, ms, memory int) float64 { return RequestCost(requests) + DurationCost(ms, memory) }
go
func Cost(requests, ms, memory int) float64 { return RequestCost(requests) + DurationCost(ms, memory) }
[ "func", "Cost", "(", "requests", ",", "ms", ",", "memory", "int", ")", "float64", "{", "return", "RequestCost", "(", "requests", ")", "+", "DurationCost", "(", "ms", ",", "memory", ")", "\n", "}" ]
// Cost returns the total cost.
[ "Cost", "returns", "the", "total", "cost", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cost/cost.go#L50-L52
train
apex/apex
infra/tfvars.go
functionVars
func (p *Proxy) functionVars() (args []string) { args = append(args, "-var") args = append(args, fmt.Sprintf("aws_region=%s", p.Region)) args = append(args, "-var") args = append(args, fmt.Sprintf("apex_environment=%s", p.Environment)) if p.Role != "" { args = append(args, "-var") args = append(args, fmt.Sprintf("apex_function_role=%s", p.Role)) } // GetConfig is slow, so store the results and then use the configurations as needed var relations []ConfigRelation for _, fn := range p.Functions { config, err := fn.GetConfig() if err != nil { log.Debugf("can't fetch function config: %s", err.Error()) continue } var relation ConfigRelation relation.Function = fn relation.Configuration = config.Configuration relations = append(relations, relation) } args = append(args, getFunctionArnVars(relations)...) args = append(args, getFunctionNameVars(relations)...) args = append(args, getFunctionArns(relations)...) args = append(args, getFunctionNames(relations)...) return args }
go
func (p *Proxy) functionVars() (args []string) { args = append(args, "-var") args = append(args, fmt.Sprintf("aws_region=%s", p.Region)) args = append(args, "-var") args = append(args, fmt.Sprintf("apex_environment=%s", p.Environment)) if p.Role != "" { args = append(args, "-var") args = append(args, fmt.Sprintf("apex_function_role=%s", p.Role)) } // GetConfig is slow, so store the results and then use the configurations as needed var relations []ConfigRelation for _, fn := range p.Functions { config, err := fn.GetConfig() if err != nil { log.Debugf("can't fetch function config: %s", err.Error()) continue } var relation ConfigRelation relation.Function = fn relation.Configuration = config.Configuration relations = append(relations, relation) } args = append(args, getFunctionArnVars(relations)...) args = append(args, getFunctionNameVars(relations)...) args = append(args, getFunctionArns(relations)...) args = append(args, getFunctionNames(relations)...) return args }
[ "func", "(", "p", "*", "Proxy", ")", "functionVars", "(", ")", "(", "args", "[", "]", "string", ")", "{", "args", "=", "append", "(", "args", ",", "\"", "\"", ")", "\n", "args", "=", "append", "(", "args", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "p", ".", "Region", ")", ")", "\n\n", "args", "=", "append", "(", "args", ",", "\"", "\"", ")", "\n", "args", "=", "append", "(", "args", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "p", ".", "Environment", ")", ")", "\n\n", "if", "p", ".", "Role", "!=", "\"", "\"", "{", "args", "=", "append", "(", "args", ",", "\"", "\"", ")", "\n", "args", "=", "append", "(", "args", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "p", ".", "Role", ")", ")", "\n", "}", "\n\n", "// GetConfig is slow, so store the results and then use the configurations as needed", "var", "relations", "[", "]", "ConfigRelation", "\n", "for", "_", ",", "fn", ":=", "range", "p", ".", "Functions", "{", "config", ",", "err", ":=", "fn", ".", "GetConfig", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Debugf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "continue", "\n", "}", "\n\n", "var", "relation", "ConfigRelation", "\n", "relation", ".", "Function", "=", "fn", "\n", "relation", ".", "Configuration", "=", "config", ".", "Configuration", "\n", "relations", "=", "append", "(", "relations", ",", "relation", ")", "\n", "}", "\n\n", "args", "=", "append", "(", "args", ",", "getFunctionArnVars", "(", "relations", ")", "...", ")", "\n", "args", "=", "append", "(", "args", ",", "getFunctionNameVars", "(", "relations", ")", "...", ")", "\n", "args", "=", "append", "(", "args", ",", "getFunctionArns", "(", "relations", ")", "...", ")", "\n", "args", "=", "append", "(", "args", ",", "getFunctionNames", "(", "relations", ")", "...", ")", "\n\n", "return", "args", "\n", "}" ]
// functionVars returns the function variables as terraform -var arguments.
[ "functionVars", "returns", "the", "function", "variables", "as", "terraform", "-", "var", "arguments", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/infra/tfvars.go#L19-L53
train
apex/apex
infra/tfvars.go
getFunctionArnVars
func getFunctionArnVars(relations []ConfigRelation) (args []string) { log.Debugf("Generating the tfvar apex_function_FUNCTION") for _, rel := range relations { args = append(args, "-var") args = append(args, fmt.Sprintf("apex_function_%s=%s", rel.Function.Name, *rel.Configuration.FunctionArn)) } return args }
go
func getFunctionArnVars(relations []ConfigRelation) (args []string) { log.Debugf("Generating the tfvar apex_function_FUNCTION") for _, rel := range relations { args = append(args, "-var") args = append(args, fmt.Sprintf("apex_function_%s=%s", rel.Function.Name, *rel.Configuration.FunctionArn)) } return args }
[ "func", "getFunctionArnVars", "(", "relations", "[", "]", "ConfigRelation", ")", "(", "args", "[", "]", "string", ")", "{", "log", ".", "Debugf", "(", "\"", "\"", ")", "\n", "for", "_", ",", "rel", ":=", "range", "relations", "{", "args", "=", "append", "(", "args", ",", "\"", "\"", ")", "\n", "args", "=", "append", "(", "args", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "rel", ".", "Function", ".", "Name", ",", "*", "rel", ".", "Configuration", ".", "FunctionArn", ")", ")", "\n", "}", "\n", "return", "args", "\n", "}" ]
// Generate a series of variables apex_function_FUNCTION that contains the arn of the functions // This function is being phased out in favour of apex_function_arns
[ "Generate", "a", "series", "of", "variables", "apex_function_FUNCTION", "that", "contains", "the", "arn", "of", "the", "functions", "This", "function", "is", "being", "phased", "out", "in", "favour", "of", "apex_function_arns" ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/infra/tfvars.go#L57-L64
train
apex/apex
infra/tfvars.go
getFunctionArns
func getFunctionArns(relations []ConfigRelation) (args []string) { log.Debugf("Generating the tfvar apex_function_arns") var arns []string for _, rel := range relations { arns = append(arns, fmt.Sprintf("%s = %q", rel.Function.Name, *rel.Configuration.FunctionArn)) } args = append(args, "-var") args = append(args, fmt.Sprintf("apex_function_arns={ %s }", strings.Join(arns, ", "))) return args }
go
func getFunctionArns(relations []ConfigRelation) (args []string) { log.Debugf("Generating the tfvar apex_function_arns") var arns []string for _, rel := range relations { arns = append(arns, fmt.Sprintf("%s = %q", rel.Function.Name, *rel.Configuration.FunctionArn)) } args = append(args, "-var") args = append(args, fmt.Sprintf("apex_function_arns={ %s }", strings.Join(arns, ", "))) return args }
[ "func", "getFunctionArns", "(", "relations", "[", "]", "ConfigRelation", ")", "(", "args", "[", "]", "string", ")", "{", "log", ".", "Debugf", "(", "\"", "\"", ")", "\n", "var", "arns", "[", "]", "string", "\n", "for", "_", ",", "rel", ":=", "range", "relations", "{", "arns", "=", "append", "(", "arns", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "rel", ".", "Function", ".", "Name", ",", "*", "rel", ".", "Configuration", ".", "FunctionArn", ")", ")", "\n", "}", "\n", "args", "=", "append", "(", "args", ",", "\"", "\"", ")", "\n", "args", "=", "append", "(", "args", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "strings", ".", "Join", "(", "arns", ",", "\"", "\"", ")", ")", ")", "\n", "return", "args", "\n", "}" ]
// Generates a map that has the function's name as a key and the arn of the function as a value
[ "Generates", "a", "map", "that", "has", "the", "function", "s", "name", "as", "a", "key", "and", "the", "arn", "of", "the", "function", "as", "a", "value" ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/infra/tfvars.go#L78-L87
train
apex/apex
infra/tfvars.go
getFunctionNames
func getFunctionNames(relations []ConfigRelation) (args []string) { log.Debugf("Generating the tfvar apex_function_names") var names []string for _, rel := range relations { names = append(names, fmt.Sprintf("%s = %q", rel.Function.Name, rel.Function.FunctionName)) } args = append(args, "-var") args = append(args, fmt.Sprintf("apex_function_names={ %s }", strings.Join(names, ", "))) return args }
go
func getFunctionNames(relations []ConfigRelation) (args []string) { log.Debugf("Generating the tfvar apex_function_names") var names []string for _, rel := range relations { names = append(names, fmt.Sprintf("%s = %q", rel.Function.Name, rel.Function.FunctionName)) } args = append(args, "-var") args = append(args, fmt.Sprintf("apex_function_names={ %s }", strings.Join(names, ", "))) return args }
[ "func", "getFunctionNames", "(", "relations", "[", "]", "ConfigRelation", ")", "(", "args", "[", "]", "string", ")", "{", "log", ".", "Debugf", "(", "\"", "\"", ")", "\n", "var", "names", "[", "]", "string", "\n", "for", "_", ",", "rel", ":=", "range", "relations", "{", "names", "=", "append", "(", "names", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "rel", ".", "Function", ".", "Name", ",", "rel", ".", "Function", ".", "FunctionName", ")", ")", "\n", "}", "\n", "args", "=", "append", "(", "args", ",", "\"", "\"", ")", "\n", "args", "=", "append", "(", "args", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "strings", ".", "Join", "(", "names", ",", "\"", "\"", ")", ")", ")", "\n", "return", "args", "\n", "}" ]
// Generates a map that has the function's name as a key and the full name of the function as a value
[ "Generates", "a", "map", "that", "has", "the", "function", "s", "name", "as", "a", "key", "and", "the", "full", "name", "of", "the", "function", "as", "a", "value" ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/infra/tfvars.go#L90-L99
train
apex/apex
exec/exec.go
Run
func (p *Proxy) Run(command string, args ...string) error { log.WithFields(log.Fields{ "command": command, "args": args, }).Debug("exec") cmd := exec.Command(command, args...) cmd.Env = append(os.Environ(), p.functionEnvVars()...) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr cmd.Dir = p.Dir return cmd.Run() }
go
func (p *Proxy) Run(command string, args ...string) error { log.WithFields(log.Fields{ "command": command, "args": args, }).Debug("exec") cmd := exec.Command(command, args...) cmd.Env = append(os.Environ(), p.functionEnvVars()...) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr cmd.Dir = p.Dir return cmd.Run() }
[ "func", "(", "p", "*", "Proxy", ")", "Run", "(", "command", "string", ",", "args", "...", "string", ")", "error", "{", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "command", ",", "\"", "\"", ":", "args", ",", "}", ")", ".", "Debug", "(", "\"", "\"", ")", "\n\n", "cmd", ":=", "exec", ".", "Command", "(", "command", ",", "args", "...", ")", "\n", "cmd", ".", "Env", "=", "append", "(", "os", ".", "Environ", "(", ")", ",", "p", ".", "functionEnvVars", "(", ")", "...", ")", "\n", "cmd", ".", "Stdin", "=", "os", ".", "Stdin", "\n", "cmd", ".", "Stdout", "=", "os", ".", "Stdout", "\n", "cmd", ".", "Stderr", "=", "os", ".", "Stderr", "\n", "cmd", ".", "Dir", "=", "p", ".", "Dir", "\n\n", "return", "cmd", ".", "Run", "(", ")", "\n", "}" ]
// Run command in specified directory.
[ "Run", "command", "in", "specified", "directory", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/exec/exec.go#L23-L37
train
apex/apex
metrics/metrics.go
Collect
func (m *Metrics) Collect() (a map[string]AggregatedMetrics) { a = make(map[string]AggregatedMetrics) for _, fnName := range m.FunctionNames { metric := Metric{ Config: m.Config, FunctionName: fnName, } a[fnName] = metric.Collect() } return }
go
func (m *Metrics) Collect() (a map[string]AggregatedMetrics) { a = make(map[string]AggregatedMetrics) for _, fnName := range m.FunctionNames { metric := Metric{ Config: m.Config, FunctionName: fnName, } a[fnName] = metric.Collect() } return }
[ "func", "(", "m", "*", "Metrics", ")", "Collect", "(", ")", "(", "a", "map", "[", "string", "]", "AggregatedMetrics", ")", "{", "a", "=", "make", "(", "map", "[", "string", "]", "AggregatedMetrics", ")", "\n\n", "for", "_", ",", "fnName", ":=", "range", "m", ".", "FunctionNames", "{", "metric", ":=", "Metric", "{", "Config", ":", "m", ".", "Config", ",", "FunctionName", ":", "fnName", ",", "}", "\n\n", "a", "[", "fnName", "]", "=", "metric", ".", "Collect", "(", ")", "\n", "}", "\n\n", "return", "\n", "}" ]
// Collect and aggregate metrics for multiple functions.
[ "Collect", "and", "aggregate", "metrics", "for", "multiple", "functions", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/metrics/metrics.go#L33-L46
train
apex/apex
cmd/apex/autocomplete/autocomplete.go
find
func find(name string) *cobra.Command { for _, cmd := range root.Command.Commands() { if cmd.Name() == name { return cmd } } return nil }
go
func find(name string) *cobra.Command { for _, cmd := range root.Command.Commands() { if cmd.Name() == name { return cmd } } return nil }
[ "func", "find", "(", "name", "string", ")", "*", "cobra", ".", "Command", "{", "for", "_", ",", "cmd", ":=", "range", "root", ".", "Command", ".", "Commands", "(", ")", "{", "if", "cmd", ".", "Name", "(", ")", "==", "name", "{", "return", "cmd", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// find command by `name`.
[ "find", "command", "by", "name", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cmd/apex/autocomplete/autocomplete.go#L73-L80
train
apex/apex
cmd/apex/autocomplete/autocomplete.go
rootCommands
func rootCommands() { for _, cmd := range root.Command.Commands() { if !cmd.Hidden { fmt.Printf("%s ", cmd.Name()) } } }
go
func rootCommands() { for _, cmd := range root.Command.Commands() { if !cmd.Hidden { fmt.Printf("%s ", cmd.Name()) } } }
[ "func", "rootCommands", "(", ")", "{", "for", "_", ",", "cmd", ":=", "range", "root", ".", "Command", ".", "Commands", "(", ")", "{", "if", "!", "cmd", ".", "Hidden", "{", "fmt", ".", "Printf", "(", "\"", "\"", ",", "cmd", ".", "Name", "(", ")", ")", "\n", "}", "\n", "}", "\n", "}" ]
// output root commands.
[ "output", "root", "commands", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cmd/apex/autocomplete/autocomplete.go#L83-L89
train
apex/apex
cmd/apex/autocomplete/autocomplete.go
flags
func flags(cmd *cobra.Command) { cmd.Flags().VisitAll(func(f *flag.Flag) { if !f.Hidden { fmt.Printf("--%s ", f.Name) } }) }
go
func flags(cmd *cobra.Command) { cmd.Flags().VisitAll(func(f *flag.Flag) { if !f.Hidden { fmt.Printf("--%s ", f.Name) } }) }
[ "func", "flags", "(", "cmd", "*", "cobra", ".", "Command", ")", "{", "cmd", ".", "Flags", "(", ")", ".", "VisitAll", "(", "func", "(", "f", "*", "flag", ".", "Flag", ")", "{", "if", "!", "f", ".", "Hidden", "{", "fmt", ".", "Printf", "(", "\"", "\"", ",", "f", ".", "Name", ")", "\n", "}", "\n", "}", ")", "\n", "}" ]
// output flags.
[ "output", "flags", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cmd/apex/autocomplete/autocomplete.go#L92-L98
train
apex/apex
plugins/inference/inference.go
Open
func (p *Plugin) Open(fn *function.Function) error { if fn.Runtime != "" { return nil } fn.Log.Debug("inferring runtime") for name, runtime := range p.Files { if _, err := os.Stat(filepath.Join(fn.Path, name)); err == nil { fn.Log.WithField("runtime", runtime).Debug("inferred runtime") fn.Runtime = runtime return nil } } return nil }
go
func (p *Plugin) Open(fn *function.Function) error { if fn.Runtime != "" { return nil } fn.Log.Debug("inferring runtime") for name, runtime := range p.Files { if _, err := os.Stat(filepath.Join(fn.Path, name)); err == nil { fn.Log.WithField("runtime", runtime).Debug("inferred runtime") fn.Runtime = runtime return nil } } return nil }
[ "func", "(", "p", "*", "Plugin", ")", "Open", "(", "fn", "*", "function", ".", "Function", ")", "error", "{", "if", "fn", ".", "Runtime", "!=", "\"", "\"", "{", "return", "nil", "\n", "}", "\n\n", "fn", ".", "Log", ".", "Debug", "(", "\"", "\"", ")", "\n\n", "for", "name", ",", "runtime", ":=", "range", "p", ".", "Files", "{", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "filepath", ".", "Join", "(", "fn", ".", "Path", ",", "name", ")", ")", ";", "err", "==", "nil", "{", "fn", ".", "Log", ".", "WithField", "(", "\"", "\"", ",", "runtime", ")", ".", "Debug", "(", "\"", "\"", ")", "\n", "fn", ".", "Runtime", "=", "runtime", "\n", "return", "nil", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Open checks for files in the function directory to infer its runtime.
[ "Open", "checks", "for", "files", "in", "the", "function", "directory", "to", "infer", "its", "runtime", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/plugins/inference/inference.go#L35-L51
train
apex/apex
service/provider.go
NewProvider
func NewProvider(session *session.Session, dryRun bool) Provideriface { return &Provider{ Session: session, DryRun: dryRun, } }
go
func NewProvider(session *session.Session, dryRun bool) Provideriface { return &Provider{ Session: session, DryRun: dryRun, } }
[ "func", "NewProvider", "(", "session", "*", "session", ".", "Session", ",", "dryRun", "bool", ")", "Provideriface", "{", "return", "&", "Provider", "{", "Session", ":", "session", ",", "DryRun", ":", "dryRun", ",", "}", "\n", "}" ]
// NewProvider with session and dry run
[ "NewProvider", "with", "session", "and", "dry", "run" ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/service/provider.go#L24-L29
train
apex/apex
service/provider.go
NewService
func (p *Provider) NewService(cfg *aws.Config) lambdaiface.LambdaAPI { if p.DryRun { return dryrun.New(p.Session) } else if cfg != nil { return lambda.New(p.Session, cfg) } else { return lambda.New(p.Session) } }
go
func (p *Provider) NewService(cfg *aws.Config) lambdaiface.LambdaAPI { if p.DryRun { return dryrun.New(p.Session) } else if cfg != nil { return lambda.New(p.Session, cfg) } else { return lambda.New(p.Session) } }
[ "func", "(", "p", "*", "Provider", ")", "NewService", "(", "cfg", "*", "aws", ".", "Config", ")", "lambdaiface", ".", "LambdaAPI", "{", "if", "p", ".", "DryRun", "{", "return", "dryrun", ".", "New", "(", "p", ".", "Session", ")", "\n", "}", "else", "if", "cfg", "!=", "nil", "{", "return", "lambda", ".", "New", "(", "p", ".", "Session", ",", "cfg", ")", "\n", "}", "else", "{", "return", "lambda", ".", "New", "(", "p", ".", "Session", ")", "\n", "}", "\n", "}" ]
// NewService returns Lambda service with AWS config
[ "NewService", "returns", "Lambda", "service", "with", "AWS", "config" ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/service/provider.go#L32-L40
train
apex/apex
plugins/shim/shim.go
Build
func (p *Plugin) Build(fn *function.Function, zip *archive.Zip) error { if fn.Shim { fn.Log.Debug("add shim") if err := zip.AddBytes("index.js", shim.MustAsset("index.js")); err != nil { return err } if err := zip.AddBytes("byline.js", shim.MustAsset("byline.js")); err != nil { return err } } return nil }
go
func (p *Plugin) Build(fn *function.Function, zip *archive.Zip) error { if fn.Shim { fn.Log.Debug("add shim") if err := zip.AddBytes("index.js", shim.MustAsset("index.js")); err != nil { return err } if err := zip.AddBytes("byline.js", shim.MustAsset("byline.js")); err != nil { return err } } return nil }
[ "func", "(", "p", "*", "Plugin", ")", "Build", "(", "fn", "*", "function", ".", "Function", ",", "zip", "*", "archive", ".", "Zip", ")", "error", "{", "if", "fn", ".", "Shim", "{", "fn", ".", "Log", ".", "Debug", "(", "\"", "\"", ")", "\n\n", "if", "err", ":=", "zip", ".", "AddBytes", "(", "\"", "\"", ",", "shim", ".", "MustAsset", "(", "\"", "\"", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "zip", ".", "AddBytes", "(", "\"", "\"", ",", "shim", ".", "MustAsset", "(", "\"", "\"", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Build adds the nodejs shim files.
[ "Build", "adds", "the", "nodejs", "shim", "files", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/plugins/shim/shim.go#L19-L33
train
apex/apex
cmd/apex/list/list.go
outputTFvars
func outputTFvars() { for _, fn := range root.Project.Functions { config, err := fn.GetConfig() if err != nil { log.Debugf("can't fetch function config: %s", err.Error()) continue } fmt.Printf("apex_function_%s=%q\n", fn.Name, *config.Configuration.FunctionArn) } }
go
func outputTFvars() { for _, fn := range root.Project.Functions { config, err := fn.GetConfig() if err != nil { log.Debugf("can't fetch function config: %s", err.Error()) continue } fmt.Printf("apex_function_%s=%q\n", fn.Name, *config.Configuration.FunctionArn) } }
[ "func", "outputTFvars", "(", ")", "{", "for", "_", ",", "fn", ":=", "range", "root", ".", "Project", ".", "Functions", "{", "config", ",", "err", ":=", "fn", ".", "GetConfig", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Debugf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "continue", "\n", "}", "\n\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "fn", ".", "Name", ",", "*", "config", ".", "Configuration", ".", "FunctionArn", ")", "\n", "}", "\n", "}" ]
// outputTFvars format.
[ "outputTFvars", "format", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cmd/apex/list/list.go#L61-L71
train
apex/apex
cmd/apex/list/list.go
outputList
func outputList() { fmt.Println() for _, fn := range root.Project.Functions { awsFn, err := fn.GetConfigCurrent() if awserr, ok := err.(awserr.Error); ok && awserr.Code() == "ResourceNotFoundException" { fmt.Printf(" \033[%dm%s\033[0m (not deployed) \n", colors.Blue, fn.Name) } else { fmt.Printf(" \033[%dm%s\033[0m\n", colors.Blue, fn.Name) } if fn.Description != "" { fmt.Printf(" description: %v\n", fn.Description) } fmt.Printf(" runtime: %v\n", fn.Runtime) fmt.Printf(" memory: %vmb\n", fn.Memory) fmt.Printf(" timeout: %vs\n", fn.Timeout) fmt.Printf(" role: %v\n", fn.Role) fmt.Printf(" handler: %v\n", fn.Handler) if awsFn != nil && awsFn.Configuration != nil && awsFn.Configuration.FunctionArn != nil { fmt.Printf(" arn: %v\n", *awsFn.Configuration.FunctionArn) } if err != nil { fmt.Println() continue // ignore } aliaslist, err := fn.GetAliases() if err != nil { continue } var aliases string for index, alias := range aliaslist.Aliases { if index > 0 { aliases += ", " } aliases += fmt.Sprintf("%s@v%s", *alias.Name, *alias.FunctionVersion) } if aliases == "" { aliases = "<none>" } fmt.Printf(" aliases: %s\n", aliases) fmt.Println() } }
go
func outputList() { fmt.Println() for _, fn := range root.Project.Functions { awsFn, err := fn.GetConfigCurrent() if awserr, ok := err.(awserr.Error); ok && awserr.Code() == "ResourceNotFoundException" { fmt.Printf(" \033[%dm%s\033[0m (not deployed) \n", colors.Blue, fn.Name) } else { fmt.Printf(" \033[%dm%s\033[0m\n", colors.Blue, fn.Name) } if fn.Description != "" { fmt.Printf(" description: %v\n", fn.Description) } fmt.Printf(" runtime: %v\n", fn.Runtime) fmt.Printf(" memory: %vmb\n", fn.Memory) fmt.Printf(" timeout: %vs\n", fn.Timeout) fmt.Printf(" role: %v\n", fn.Role) fmt.Printf(" handler: %v\n", fn.Handler) if awsFn != nil && awsFn.Configuration != nil && awsFn.Configuration.FunctionArn != nil { fmt.Printf(" arn: %v\n", *awsFn.Configuration.FunctionArn) } if err != nil { fmt.Println() continue // ignore } aliaslist, err := fn.GetAliases() if err != nil { continue } var aliases string for index, alias := range aliaslist.Aliases { if index > 0 { aliases += ", " } aliases += fmt.Sprintf("%s@v%s", *alias.Name, *alias.FunctionVersion) } if aliases == "" { aliases = "<none>" } fmt.Printf(" aliases: %s\n", aliases) fmt.Println() } }
[ "func", "outputList", "(", ")", "{", "fmt", ".", "Println", "(", ")", "\n", "for", "_", ",", "fn", ":=", "range", "root", ".", "Project", ".", "Functions", "{", "awsFn", ",", "err", ":=", "fn", ".", "GetConfigCurrent", "(", ")", "\n\n", "if", "awserr", ",", "ok", ":=", "err", ".", "(", "awserr", ".", "Error", ")", ";", "ok", "&&", "awserr", ".", "Code", "(", ")", "==", "\"", "\"", "{", "fmt", ".", "Printf", "(", "\"", "\\033", "\\033", "\\n", "\"", ",", "colors", ".", "Blue", ",", "fn", ".", "Name", ")", "\n", "}", "else", "{", "fmt", ".", "Printf", "(", "\"", "\\033", "\\033", "\\n", "\"", ",", "colors", ".", "Blue", ",", "fn", ".", "Name", ")", "\n", "}", "\n\n", "if", "fn", ".", "Description", "!=", "\"", "\"", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "fn", ".", "Description", ")", "\n", "}", "\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "fn", ".", "Runtime", ")", "\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "fn", ".", "Memory", ")", "\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "fn", ".", "Timeout", ")", "\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "fn", ".", "Role", ")", "\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "fn", ".", "Handler", ")", "\n", "if", "awsFn", "!=", "nil", "&&", "awsFn", ".", "Configuration", "!=", "nil", "&&", "awsFn", ".", "Configuration", ".", "FunctionArn", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "*", "awsFn", ".", "Configuration", ".", "FunctionArn", ")", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Println", "(", ")", "\n", "continue", "// ignore", "\n", "}", "\n\n", "aliaslist", ",", "err", ":=", "fn", ".", "GetAliases", "(", ")", "\n", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "\n\n", "var", "aliases", "string", "\n", "for", "index", ",", "alias", ":=", "range", "aliaslist", ".", "Aliases", "{", "if", "index", ">", "0", "{", "aliases", "+=", "\"", "\"", "\n", "}", "\n", "aliases", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "*", "alias", ".", "Name", ",", "*", "alias", ".", "FunctionVersion", ")", "\n", "}", "\n", "if", "aliases", "==", "\"", "\"", "{", "aliases", "=", "\"", "\"", "\n", "}", "\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "aliases", ")", "\n", "fmt", ".", "Println", "(", ")", "\n", "}", "\n", "}" ]
// outputList format.
[ "outputList", "format", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cmd/apex/list/list.go#L74-L120
train
xtaci/kcp-go
fec.go
freeRange
func (dec *fecDecoder) freeRange(first, n int, q []fecPacket) []fecPacket { for i := first; i < first+n; i++ { // recycle buffer xmitBuf.Put([]byte(q[i])) } if first == 0 && n < len(q)/2 { return q[n:] } copy(q[first:], q[first+n:]) return q[:len(q)-n] }
go
func (dec *fecDecoder) freeRange(first, n int, q []fecPacket) []fecPacket { for i := first; i < first+n; i++ { // recycle buffer xmitBuf.Put([]byte(q[i])) } if first == 0 && n < len(q)/2 { return q[n:] } copy(q[first:], q[first+n:]) return q[:len(q)-n] }
[ "func", "(", "dec", "*", "fecDecoder", ")", "freeRange", "(", "first", ",", "n", "int", ",", "q", "[", "]", "fecPacket", ")", "[", "]", "fecPacket", "{", "for", "i", ":=", "first", ";", "i", "<", "first", "+", "n", ";", "i", "++", "{", "// recycle buffer", "xmitBuf", ".", "Put", "(", "[", "]", "byte", "(", "q", "[", "i", "]", ")", ")", "\n", "}", "\n\n", "if", "first", "==", "0", "&&", "n", "<", "len", "(", "q", ")", "/", "2", "{", "return", "q", "[", "n", ":", "]", "\n", "}", "\n", "copy", "(", "q", "[", "first", ":", "]", ",", "q", "[", "first", "+", "n", ":", "]", ")", "\n", "return", "q", "[", ":", "len", "(", "q", ")", "-", "n", "]", "\n", "}" ]
// free a range of fecPacket
[ "free", "a", "range", "of", "fecPacket" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/fec.go#L178-L188
train
xtaci/kcp-go
readloop_linux.go
readLoop
func (s *UDPSession) readLoop() { addr, _ := net.ResolveUDPAddr("udp", s.conn.LocalAddr().String()) if addr.IP.To4() != nil { s.readLoopIPv4() } else { s.readLoopIPv6() } }
go
func (s *UDPSession) readLoop() { addr, _ := net.ResolveUDPAddr("udp", s.conn.LocalAddr().String()) if addr.IP.To4() != nil { s.readLoopIPv4() } else { s.readLoopIPv6() } }
[ "func", "(", "s", "*", "UDPSession", ")", "readLoop", "(", ")", "{", "addr", ",", "_", ":=", "net", ".", "ResolveUDPAddr", "(", "\"", "\"", ",", "s", ".", "conn", ".", "LocalAddr", "(", ")", ".", "String", "(", ")", ")", "\n", "if", "addr", ".", "IP", ".", "To4", "(", ")", "!=", "nil", "{", "s", ".", "readLoopIPv4", "(", ")", "\n", "}", "else", "{", "s", ".", "readLoopIPv6", "(", ")", "\n", "}", "\n", "}" ]
// the read loop for a client session
[ "the", "read", "loop", "for", "a", "client", "session" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/readloop_linux.go#L19-L26
train
xtaci/kcp-go
readloop_linux.go
monitor
func (l *Listener) monitor() { addr, _ := net.ResolveUDPAddr("udp", l.conn.LocalAddr().String()) if addr.IP.To4() != nil { l.monitorIPv4() } else { l.monitorIPv6() } }
go
func (l *Listener) monitor() { addr, _ := net.ResolveUDPAddr("udp", l.conn.LocalAddr().String()) if addr.IP.To4() != nil { l.monitorIPv4() } else { l.monitorIPv6() } }
[ "func", "(", "l", "*", "Listener", ")", "monitor", "(", ")", "{", "addr", ",", "_", ":=", "net", ".", "ResolveUDPAddr", "(", "\"", "\"", ",", "l", ".", "conn", ".", "LocalAddr", "(", ")", ".", "String", "(", ")", ")", "\n", "if", "addr", ".", "IP", ".", "To4", "(", ")", "!=", "nil", "{", "l", ".", "monitorIPv4", "(", ")", "\n", "}", "else", "{", "l", ".", "monitorIPv6", "(", ")", "\n", "}", "\n", "}" ]
// monitor incoming data for all connections of server
[ "monitor", "incoming", "data", "for", "all", "connections", "of", "server" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/readloop_linux.go#L100-L107
train
xtaci/kcp-go
kcp.go
encode
func (seg *segment) encode(ptr []byte) []byte { ptr = ikcp_encode32u(ptr, seg.conv) ptr = ikcp_encode8u(ptr, seg.cmd) ptr = ikcp_encode8u(ptr, seg.frg) ptr = ikcp_encode16u(ptr, seg.wnd) ptr = ikcp_encode32u(ptr, seg.ts) ptr = ikcp_encode32u(ptr, seg.sn) ptr = ikcp_encode32u(ptr, seg.una) ptr = ikcp_encode32u(ptr, uint32(len(seg.data))) atomic.AddUint64(&DefaultSnmp.OutSegs, 1) return ptr }
go
func (seg *segment) encode(ptr []byte) []byte { ptr = ikcp_encode32u(ptr, seg.conv) ptr = ikcp_encode8u(ptr, seg.cmd) ptr = ikcp_encode8u(ptr, seg.frg) ptr = ikcp_encode16u(ptr, seg.wnd) ptr = ikcp_encode32u(ptr, seg.ts) ptr = ikcp_encode32u(ptr, seg.sn) ptr = ikcp_encode32u(ptr, seg.una) ptr = ikcp_encode32u(ptr, uint32(len(seg.data))) atomic.AddUint64(&DefaultSnmp.OutSegs, 1) return ptr }
[ "func", "(", "seg", "*", "segment", ")", "encode", "(", "ptr", "[", "]", "byte", ")", "[", "]", "byte", "{", "ptr", "=", "ikcp_encode32u", "(", "ptr", ",", "seg", ".", "conv", ")", "\n", "ptr", "=", "ikcp_encode8u", "(", "ptr", ",", "seg", ".", "cmd", ")", "\n", "ptr", "=", "ikcp_encode8u", "(", "ptr", ",", "seg", ".", "frg", ")", "\n", "ptr", "=", "ikcp_encode16u", "(", "ptr", ",", "seg", ".", "wnd", ")", "\n", "ptr", "=", "ikcp_encode32u", "(", "ptr", ",", "seg", ".", "ts", ")", "\n", "ptr", "=", "ikcp_encode32u", "(", "ptr", ",", "seg", ".", "sn", ")", "\n", "ptr", "=", "ikcp_encode32u", "(", "ptr", ",", "seg", ".", "una", ")", "\n", "ptr", "=", "ikcp_encode32u", "(", "ptr", ",", "uint32", "(", "len", "(", "seg", ".", "data", ")", ")", ")", "\n", "atomic", ".", "AddUint64", "(", "&", "DefaultSnmp", ".", "OutSegs", ",", "1", ")", "\n", "return", "ptr", "\n", "}" ]
// encode a segment into buffer
[ "encode", "a", "segment", "into", "buffer" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L112-L123
train
xtaci/kcp-go
kcp.go
NewKCP
func NewKCP(conv uint32, output output_callback) *KCP { kcp := new(KCP) kcp.conv = conv kcp.snd_wnd = IKCP_WND_SND kcp.rcv_wnd = IKCP_WND_RCV kcp.rmt_wnd = IKCP_WND_RCV kcp.mtu = IKCP_MTU_DEF kcp.mss = kcp.mtu - IKCP_OVERHEAD kcp.buffer = make([]byte, kcp.mtu) kcp.rx_rto = IKCP_RTO_DEF kcp.rx_minrto = IKCP_RTO_MIN kcp.interval = IKCP_INTERVAL kcp.ts_flush = IKCP_INTERVAL kcp.ssthresh = IKCP_THRESH_INIT kcp.dead_link = IKCP_DEADLINK kcp.output = output return kcp }
go
func NewKCP(conv uint32, output output_callback) *KCP { kcp := new(KCP) kcp.conv = conv kcp.snd_wnd = IKCP_WND_SND kcp.rcv_wnd = IKCP_WND_RCV kcp.rmt_wnd = IKCP_WND_RCV kcp.mtu = IKCP_MTU_DEF kcp.mss = kcp.mtu - IKCP_OVERHEAD kcp.buffer = make([]byte, kcp.mtu) kcp.rx_rto = IKCP_RTO_DEF kcp.rx_minrto = IKCP_RTO_MIN kcp.interval = IKCP_INTERVAL kcp.ts_flush = IKCP_INTERVAL kcp.ssthresh = IKCP_THRESH_INIT kcp.dead_link = IKCP_DEADLINK kcp.output = output return kcp }
[ "func", "NewKCP", "(", "conv", "uint32", ",", "output", "output_callback", ")", "*", "KCP", "{", "kcp", ":=", "new", "(", "KCP", ")", "\n", "kcp", ".", "conv", "=", "conv", "\n", "kcp", ".", "snd_wnd", "=", "IKCP_WND_SND", "\n", "kcp", ".", "rcv_wnd", "=", "IKCP_WND_RCV", "\n", "kcp", ".", "rmt_wnd", "=", "IKCP_WND_RCV", "\n", "kcp", ".", "mtu", "=", "IKCP_MTU_DEF", "\n", "kcp", ".", "mss", "=", "kcp", ".", "mtu", "-", "IKCP_OVERHEAD", "\n", "kcp", ".", "buffer", "=", "make", "(", "[", "]", "byte", ",", "kcp", ".", "mtu", ")", "\n", "kcp", ".", "rx_rto", "=", "IKCP_RTO_DEF", "\n", "kcp", ".", "rx_minrto", "=", "IKCP_RTO_MIN", "\n", "kcp", ".", "interval", "=", "IKCP_INTERVAL", "\n", "kcp", ".", "ts_flush", "=", "IKCP_INTERVAL", "\n", "kcp", ".", "ssthresh", "=", "IKCP_THRESH_INIT", "\n", "kcp", ".", "dead_link", "=", "IKCP_DEADLINK", "\n", "kcp", ".", "output", "=", "output", "\n", "return", "kcp", "\n", "}" ]
// NewKCP create a new kcp control object, 'conv' must equal in two endpoint // from the same connection.
[ "NewKCP", "create", "a", "new", "kcp", "control", "object", "conv", "must", "equal", "in", "two", "endpoint", "from", "the", "same", "connection", "." ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L160-L177
train
xtaci/kcp-go
kcp.go
newSegment
func (kcp *KCP) newSegment(size int) (seg segment) { seg.data = xmitBuf.Get().([]byte)[:size] return }
go
func (kcp *KCP) newSegment(size int) (seg segment) { seg.data = xmitBuf.Get().([]byte)[:size] return }
[ "func", "(", "kcp", "*", "KCP", ")", "newSegment", "(", "size", "int", ")", "(", "seg", "segment", ")", "{", "seg", ".", "data", "=", "xmitBuf", ".", "Get", "(", ")", ".", "(", "[", "]", "byte", ")", "[", ":", "size", "]", "\n", "return", "\n", "}" ]
// newSegment creates a KCP segment
[ "newSegment", "creates", "a", "KCP", "segment" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L180-L183
train
xtaci/kcp-go
kcp.go
delSegment
func (kcp *KCP) delSegment(seg *segment) { if seg.data != nil { xmitBuf.Put(seg.data) seg.data = nil } }
go
func (kcp *KCP) delSegment(seg *segment) { if seg.data != nil { xmitBuf.Put(seg.data) seg.data = nil } }
[ "func", "(", "kcp", "*", "KCP", ")", "delSegment", "(", "seg", "*", "segment", ")", "{", "if", "seg", ".", "data", "!=", "nil", "{", "xmitBuf", ".", "Put", "(", "seg", ".", "data", ")", "\n", "seg", ".", "data", "=", "nil", "\n", "}", "\n", "}" ]
// delSegment recycles a KCP segment
[ "delSegment", "recycles", "a", "KCP", "segment" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L186-L191
train
xtaci/kcp-go
kcp.go
ReserveBytes
func (kcp *KCP) ReserveBytes(n int) bool { if n >= int(kcp.mtu-IKCP_OVERHEAD) || n < 0 { return false } kcp.reserved = n kcp.mss = kcp.mtu - IKCP_OVERHEAD - uint32(n) return true }
go
func (kcp *KCP) ReserveBytes(n int) bool { if n >= int(kcp.mtu-IKCP_OVERHEAD) || n < 0 { return false } kcp.reserved = n kcp.mss = kcp.mtu - IKCP_OVERHEAD - uint32(n) return true }
[ "func", "(", "kcp", "*", "KCP", ")", "ReserveBytes", "(", "n", "int", ")", "bool", "{", "if", "n", ">=", "int", "(", "kcp", ".", "mtu", "-", "IKCP_OVERHEAD", ")", "||", "n", "<", "0", "{", "return", "false", "\n", "}", "\n", "kcp", ".", "reserved", "=", "n", "\n", "kcp", ".", "mss", "=", "kcp", ".", "mtu", "-", "IKCP_OVERHEAD", "-", "uint32", "(", "n", ")", "\n", "return", "true", "\n", "}" ]
// ReserveBytes keeps n bytes untouched from the beginning of the buffer // the output_callback function should be aware of this // return false if n >= mss
[ "ReserveBytes", "keeps", "n", "bytes", "untouched", "from", "the", "beginning", "of", "the", "buffer", "the", "output_callback", "function", "should", "be", "aware", "of", "this", "return", "false", "if", "n", ">", "=", "mss" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L196-L203
train
xtaci/kcp-go
kcp.go
PeekSize
func (kcp *KCP) PeekSize() (length int) { if len(kcp.rcv_queue) == 0 { return -1 } seg := &kcp.rcv_queue[0] if seg.frg == 0 { return len(seg.data) } if len(kcp.rcv_queue) < int(seg.frg+1) { return -1 } for k := range kcp.rcv_queue { seg := &kcp.rcv_queue[k] length += len(seg.data) if seg.frg == 0 { break } } return }
go
func (kcp *KCP) PeekSize() (length int) { if len(kcp.rcv_queue) == 0 { return -1 } seg := &kcp.rcv_queue[0] if seg.frg == 0 { return len(seg.data) } if len(kcp.rcv_queue) < int(seg.frg+1) { return -1 } for k := range kcp.rcv_queue { seg := &kcp.rcv_queue[k] length += len(seg.data) if seg.frg == 0 { break } } return }
[ "func", "(", "kcp", "*", "KCP", ")", "PeekSize", "(", ")", "(", "length", "int", ")", "{", "if", "len", "(", "kcp", ".", "rcv_queue", ")", "==", "0", "{", "return", "-", "1", "\n", "}", "\n\n", "seg", ":=", "&", "kcp", ".", "rcv_queue", "[", "0", "]", "\n", "if", "seg", ".", "frg", "==", "0", "{", "return", "len", "(", "seg", ".", "data", ")", "\n", "}", "\n\n", "if", "len", "(", "kcp", ".", "rcv_queue", ")", "<", "int", "(", "seg", ".", "frg", "+", "1", ")", "{", "return", "-", "1", "\n", "}", "\n\n", "for", "k", ":=", "range", "kcp", ".", "rcv_queue", "{", "seg", ":=", "&", "kcp", ".", "rcv_queue", "[", "k", "]", "\n", "length", "+=", "len", "(", "seg", ".", "data", ")", "\n", "if", "seg", ".", "frg", "==", "0", "{", "break", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// PeekSize checks the size of next message in the recv queue
[ "PeekSize", "checks", "the", "size", "of", "next", "message", "in", "the", "recv", "queue" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L206-L228
train
xtaci/kcp-go
kcp.go
parse_data
func (kcp *KCP) parse_data(newseg segment) bool { sn := newseg.sn if _itimediff(sn, kcp.rcv_nxt+kcp.rcv_wnd) >= 0 || _itimediff(sn, kcp.rcv_nxt) < 0 { return true } n := len(kcp.rcv_buf) - 1 insert_idx := 0 repeat := false for i := n; i >= 0; i-- { seg := &kcp.rcv_buf[i] if seg.sn == sn { repeat = true break } if _itimediff(sn, seg.sn) > 0 { insert_idx = i + 1 break } } if !repeat { // replicate the content if it's new dataCopy := xmitBuf.Get().([]byte)[:len(newseg.data)] copy(dataCopy, newseg.data) newseg.data = dataCopy if insert_idx == n+1 { kcp.rcv_buf = append(kcp.rcv_buf, newseg) } else { kcp.rcv_buf = append(kcp.rcv_buf, segment{}) copy(kcp.rcv_buf[insert_idx+1:], kcp.rcv_buf[insert_idx:]) kcp.rcv_buf[insert_idx] = newseg } } // move available data from rcv_buf -> rcv_queue count := 0 for k := range kcp.rcv_buf { seg := &kcp.rcv_buf[k] if seg.sn == kcp.rcv_nxt && len(kcp.rcv_queue) < int(kcp.rcv_wnd) { kcp.rcv_nxt++ count++ } else { break } } if count > 0 { kcp.rcv_queue = append(kcp.rcv_queue, kcp.rcv_buf[:count]...) kcp.rcv_buf = kcp.remove_front(kcp.rcv_buf, count) } return repeat }
go
func (kcp *KCP) parse_data(newseg segment) bool { sn := newseg.sn if _itimediff(sn, kcp.rcv_nxt+kcp.rcv_wnd) >= 0 || _itimediff(sn, kcp.rcv_nxt) < 0 { return true } n := len(kcp.rcv_buf) - 1 insert_idx := 0 repeat := false for i := n; i >= 0; i-- { seg := &kcp.rcv_buf[i] if seg.sn == sn { repeat = true break } if _itimediff(sn, seg.sn) > 0 { insert_idx = i + 1 break } } if !repeat { // replicate the content if it's new dataCopy := xmitBuf.Get().([]byte)[:len(newseg.data)] copy(dataCopy, newseg.data) newseg.data = dataCopy if insert_idx == n+1 { kcp.rcv_buf = append(kcp.rcv_buf, newseg) } else { kcp.rcv_buf = append(kcp.rcv_buf, segment{}) copy(kcp.rcv_buf[insert_idx+1:], kcp.rcv_buf[insert_idx:]) kcp.rcv_buf[insert_idx] = newseg } } // move available data from rcv_buf -> rcv_queue count := 0 for k := range kcp.rcv_buf { seg := &kcp.rcv_buf[k] if seg.sn == kcp.rcv_nxt && len(kcp.rcv_queue) < int(kcp.rcv_wnd) { kcp.rcv_nxt++ count++ } else { break } } if count > 0 { kcp.rcv_queue = append(kcp.rcv_queue, kcp.rcv_buf[:count]...) kcp.rcv_buf = kcp.remove_front(kcp.rcv_buf, count) } return repeat }
[ "func", "(", "kcp", "*", "KCP", ")", "parse_data", "(", "newseg", "segment", ")", "bool", "{", "sn", ":=", "newseg", ".", "sn", "\n", "if", "_itimediff", "(", "sn", ",", "kcp", ".", "rcv_nxt", "+", "kcp", ".", "rcv_wnd", ")", ">=", "0", "||", "_itimediff", "(", "sn", ",", "kcp", ".", "rcv_nxt", ")", "<", "0", "{", "return", "true", "\n", "}", "\n\n", "n", ":=", "len", "(", "kcp", ".", "rcv_buf", ")", "-", "1", "\n", "insert_idx", ":=", "0", "\n", "repeat", ":=", "false", "\n", "for", "i", ":=", "n", ";", "i", ">=", "0", ";", "i", "--", "{", "seg", ":=", "&", "kcp", ".", "rcv_buf", "[", "i", "]", "\n", "if", "seg", ".", "sn", "==", "sn", "{", "repeat", "=", "true", "\n", "break", "\n", "}", "\n", "if", "_itimediff", "(", "sn", ",", "seg", ".", "sn", ")", ">", "0", "{", "insert_idx", "=", "i", "+", "1", "\n", "break", "\n", "}", "\n", "}", "\n\n", "if", "!", "repeat", "{", "// replicate the content if it's new", "dataCopy", ":=", "xmitBuf", ".", "Get", "(", ")", ".", "(", "[", "]", "byte", ")", "[", ":", "len", "(", "newseg", ".", "data", ")", "]", "\n", "copy", "(", "dataCopy", ",", "newseg", ".", "data", ")", "\n", "newseg", ".", "data", "=", "dataCopy", "\n\n", "if", "insert_idx", "==", "n", "+", "1", "{", "kcp", ".", "rcv_buf", "=", "append", "(", "kcp", ".", "rcv_buf", ",", "newseg", ")", "\n", "}", "else", "{", "kcp", ".", "rcv_buf", "=", "append", "(", "kcp", ".", "rcv_buf", ",", "segment", "{", "}", ")", "\n", "copy", "(", "kcp", ".", "rcv_buf", "[", "insert_idx", "+", "1", ":", "]", ",", "kcp", ".", "rcv_buf", "[", "insert_idx", ":", "]", ")", "\n", "kcp", ".", "rcv_buf", "[", "insert_idx", "]", "=", "newseg", "\n", "}", "\n", "}", "\n\n", "// move available data from rcv_buf -> rcv_queue", "count", ":=", "0", "\n", "for", "k", ":=", "range", "kcp", ".", "rcv_buf", "{", "seg", ":=", "&", "kcp", ".", "rcv_buf", "[", "k", "]", "\n", "if", "seg", ".", "sn", "==", "kcp", ".", "rcv_nxt", "&&", "len", "(", "kcp", ".", "rcv_queue", ")", "<", "int", "(", "kcp", ".", "rcv_wnd", ")", "{", "kcp", ".", "rcv_nxt", "++", "\n", "count", "++", "\n", "}", "else", "{", "break", "\n", "}", "\n", "}", "\n", "if", "count", ">", "0", "{", "kcp", ".", "rcv_queue", "=", "append", "(", "kcp", ".", "rcv_queue", ",", "kcp", ".", "rcv_buf", "[", ":", "count", "]", "...", ")", "\n", "kcp", ".", "rcv_buf", "=", "kcp", ".", "remove_front", "(", "kcp", ".", "rcv_buf", ",", "count", ")", "\n", "}", "\n\n", "return", "repeat", "\n", "}" ]
// returns true if data has repeated
[ "returns", "true", "if", "data", "has", "repeated" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L453-L507
train
xtaci/kcp-go
kcp.go
SetMtu
func (kcp *KCP) SetMtu(mtu int) int { if mtu < 50 || mtu < IKCP_OVERHEAD { return -1 } if kcp.reserved >= int(kcp.mtu-IKCP_OVERHEAD) || kcp.reserved < 0 { return -1 } buffer := make([]byte, mtu) if buffer == nil { return -2 } kcp.mtu = uint32(mtu) kcp.mss = kcp.mtu - IKCP_OVERHEAD - uint32(kcp.reserved) kcp.buffer = buffer return 0 }
go
func (kcp *KCP) SetMtu(mtu int) int { if mtu < 50 || mtu < IKCP_OVERHEAD { return -1 } if kcp.reserved >= int(kcp.mtu-IKCP_OVERHEAD) || kcp.reserved < 0 { return -1 } buffer := make([]byte, mtu) if buffer == nil { return -2 } kcp.mtu = uint32(mtu) kcp.mss = kcp.mtu - IKCP_OVERHEAD - uint32(kcp.reserved) kcp.buffer = buffer return 0 }
[ "func", "(", "kcp", "*", "KCP", ")", "SetMtu", "(", "mtu", "int", ")", "int", "{", "if", "mtu", "<", "50", "||", "mtu", "<", "IKCP_OVERHEAD", "{", "return", "-", "1", "\n", "}", "\n", "if", "kcp", ".", "reserved", ">=", "int", "(", "kcp", ".", "mtu", "-", "IKCP_OVERHEAD", ")", "||", "kcp", ".", "reserved", "<", "0", "{", "return", "-", "1", "\n", "}", "\n\n", "buffer", ":=", "make", "(", "[", "]", "byte", ",", "mtu", ")", "\n", "if", "buffer", "==", "nil", "{", "return", "-", "2", "\n", "}", "\n", "kcp", ".", "mtu", "=", "uint32", "(", "mtu", ")", "\n", "kcp", ".", "mss", "=", "kcp", ".", "mtu", "-", "IKCP_OVERHEAD", "-", "uint32", "(", "kcp", ".", "reserved", ")", "\n", "kcp", ".", "buffer", "=", "buffer", "\n", "return", "0", "\n", "}" ]
// SetMtu changes MTU size, default is 1400
[ "SetMtu", "changes", "MTU", "size", "default", "is", "1400" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L957-L973
train
xtaci/kcp-go
kcp.go
WaitSnd
func (kcp *KCP) WaitSnd() int { return len(kcp.snd_buf) + len(kcp.snd_queue) }
go
func (kcp *KCP) WaitSnd() int { return len(kcp.snd_buf) + len(kcp.snd_queue) }
[ "func", "(", "kcp", "*", "KCP", ")", "WaitSnd", "(", ")", "int", "{", "return", "len", "(", "kcp", ".", "snd_buf", ")", "+", "len", "(", "kcp", ".", "snd_queue", ")", "\n", "}" ]
// WaitSnd gets how many packet is waiting to be sent
[ "WaitSnd", "gets", "how", "many", "packet", "is", "waiting", "to", "be", "sent" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/kcp.go#L1019-L1021
train
xtaci/kcp-go
sess.go
newUDPSession
func newUDPSession(conv uint32, dataShards, parityShards int, l *Listener, conn net.PacketConn, remote net.Addr, block BlockCrypt) *UDPSession { sess := new(UDPSession) sess.die = make(chan struct{}) sess.nonce = new(nonceAES128) sess.nonce.Init() sess.chReadEvent = make(chan struct{}, 1) sess.chWriteEvent = make(chan struct{}, 1) sess.chReadError = make(chan error, 1) sess.chWriteError = make(chan error, 1) sess.remote = remote sess.conn = conn sess.l = l sess.block = block sess.recvbuf = make([]byte, mtuLimit) // FEC codec initialization sess.fecDecoder = newFECDecoder(rxFECMulti*(dataShards+parityShards), dataShards, parityShards) if sess.block != nil { sess.fecEncoder = newFECEncoder(dataShards, parityShards, cryptHeaderSize) } else { sess.fecEncoder = newFECEncoder(dataShards, parityShards, 0) } // calculate additional header size introduced by FEC and encryption if sess.block != nil { sess.headerSize += cryptHeaderSize } if sess.fecEncoder != nil { sess.headerSize += fecHeaderSizePlus2 } sess.kcp = NewKCP(conv, func(buf []byte, size int) { if size >= IKCP_OVERHEAD+sess.headerSize { sess.output(buf[:size]) } }) sess.kcp.ReserveBytes(sess.headerSize) // register current session to the global updater, // which call sess.update() periodically. updater.addSession(sess) if sess.l == nil { // it's a client connection go sess.readLoop() atomic.AddUint64(&DefaultSnmp.ActiveOpens, 1) } else { atomic.AddUint64(&DefaultSnmp.PassiveOpens, 1) } currestab := atomic.AddUint64(&DefaultSnmp.CurrEstab, 1) maxconn := atomic.LoadUint64(&DefaultSnmp.MaxConn) if currestab > maxconn { atomic.CompareAndSwapUint64(&DefaultSnmp.MaxConn, maxconn, currestab) } return sess }
go
func newUDPSession(conv uint32, dataShards, parityShards int, l *Listener, conn net.PacketConn, remote net.Addr, block BlockCrypt) *UDPSession { sess := new(UDPSession) sess.die = make(chan struct{}) sess.nonce = new(nonceAES128) sess.nonce.Init() sess.chReadEvent = make(chan struct{}, 1) sess.chWriteEvent = make(chan struct{}, 1) sess.chReadError = make(chan error, 1) sess.chWriteError = make(chan error, 1) sess.remote = remote sess.conn = conn sess.l = l sess.block = block sess.recvbuf = make([]byte, mtuLimit) // FEC codec initialization sess.fecDecoder = newFECDecoder(rxFECMulti*(dataShards+parityShards), dataShards, parityShards) if sess.block != nil { sess.fecEncoder = newFECEncoder(dataShards, parityShards, cryptHeaderSize) } else { sess.fecEncoder = newFECEncoder(dataShards, parityShards, 0) } // calculate additional header size introduced by FEC and encryption if sess.block != nil { sess.headerSize += cryptHeaderSize } if sess.fecEncoder != nil { sess.headerSize += fecHeaderSizePlus2 } sess.kcp = NewKCP(conv, func(buf []byte, size int) { if size >= IKCP_OVERHEAD+sess.headerSize { sess.output(buf[:size]) } }) sess.kcp.ReserveBytes(sess.headerSize) // register current session to the global updater, // which call sess.update() periodically. updater.addSession(sess) if sess.l == nil { // it's a client connection go sess.readLoop() atomic.AddUint64(&DefaultSnmp.ActiveOpens, 1) } else { atomic.AddUint64(&DefaultSnmp.PassiveOpens, 1) } currestab := atomic.AddUint64(&DefaultSnmp.CurrEstab, 1) maxconn := atomic.LoadUint64(&DefaultSnmp.MaxConn) if currestab > maxconn { atomic.CompareAndSwapUint64(&DefaultSnmp.MaxConn, maxconn, currestab) } return sess }
[ "func", "newUDPSession", "(", "conv", "uint32", ",", "dataShards", ",", "parityShards", "int", ",", "l", "*", "Listener", ",", "conn", "net", ".", "PacketConn", ",", "remote", "net", ".", "Addr", ",", "block", "BlockCrypt", ")", "*", "UDPSession", "{", "sess", ":=", "new", "(", "UDPSession", ")", "\n", "sess", ".", "die", "=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "sess", ".", "nonce", "=", "new", "(", "nonceAES128", ")", "\n", "sess", ".", "nonce", ".", "Init", "(", ")", "\n", "sess", ".", "chReadEvent", "=", "make", "(", "chan", "struct", "{", "}", ",", "1", ")", "\n", "sess", ".", "chWriteEvent", "=", "make", "(", "chan", "struct", "{", "}", ",", "1", ")", "\n", "sess", ".", "chReadError", "=", "make", "(", "chan", "error", ",", "1", ")", "\n", "sess", ".", "chWriteError", "=", "make", "(", "chan", "error", ",", "1", ")", "\n", "sess", ".", "remote", "=", "remote", "\n", "sess", ".", "conn", "=", "conn", "\n", "sess", ".", "l", "=", "l", "\n", "sess", ".", "block", "=", "block", "\n", "sess", ".", "recvbuf", "=", "make", "(", "[", "]", "byte", ",", "mtuLimit", ")", "\n\n", "// FEC codec initialization", "sess", ".", "fecDecoder", "=", "newFECDecoder", "(", "rxFECMulti", "*", "(", "dataShards", "+", "parityShards", ")", ",", "dataShards", ",", "parityShards", ")", "\n", "if", "sess", ".", "block", "!=", "nil", "{", "sess", ".", "fecEncoder", "=", "newFECEncoder", "(", "dataShards", ",", "parityShards", ",", "cryptHeaderSize", ")", "\n", "}", "else", "{", "sess", ".", "fecEncoder", "=", "newFECEncoder", "(", "dataShards", ",", "parityShards", ",", "0", ")", "\n", "}", "\n\n", "// calculate additional header size introduced by FEC and encryption", "if", "sess", ".", "block", "!=", "nil", "{", "sess", ".", "headerSize", "+=", "cryptHeaderSize", "\n", "}", "\n", "if", "sess", ".", "fecEncoder", "!=", "nil", "{", "sess", ".", "headerSize", "+=", "fecHeaderSizePlus2", "\n", "}", "\n\n", "sess", ".", "kcp", "=", "NewKCP", "(", "conv", ",", "func", "(", "buf", "[", "]", "byte", ",", "size", "int", ")", "{", "if", "size", ">=", "IKCP_OVERHEAD", "+", "sess", ".", "headerSize", "{", "sess", ".", "output", "(", "buf", "[", ":", "size", "]", ")", "\n", "}", "\n", "}", ")", "\n", "sess", ".", "kcp", ".", "ReserveBytes", "(", "sess", ".", "headerSize", ")", "\n\n", "// register current session to the global updater,", "// which call sess.update() periodically.", "updater", ".", "addSession", "(", "sess", ")", "\n\n", "if", "sess", ".", "l", "==", "nil", "{", "// it's a client connection", "go", "sess", ".", "readLoop", "(", ")", "\n", "atomic", ".", "AddUint64", "(", "&", "DefaultSnmp", ".", "ActiveOpens", ",", "1", ")", "\n", "}", "else", "{", "atomic", ".", "AddUint64", "(", "&", "DefaultSnmp", ".", "PassiveOpens", ",", "1", ")", "\n", "}", "\n", "currestab", ":=", "atomic", ".", "AddUint64", "(", "&", "DefaultSnmp", ".", "CurrEstab", ",", "1", ")", "\n", "maxconn", ":=", "atomic", ".", "LoadUint64", "(", "&", "DefaultSnmp", ".", "MaxConn", ")", "\n", "if", "currestab", ">", "maxconn", "{", "atomic", ".", "CompareAndSwapUint64", "(", "&", "DefaultSnmp", ".", "MaxConn", ",", "maxconn", ",", "currestab", ")", "\n", "}", "\n\n", "return", "sess", "\n", "}" ]
// newUDPSession create a new udp session for client or server
[ "newUDPSession", "create", "a", "new", "udp", "session", "for", "client", "or", "server" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L113-L168
train
xtaci/kcp-go
sess.go
WriteBuffers
func (s *UDPSession) WriteBuffers(v [][]byte) (n int, err error) { for { s.mu.Lock() if s.isClosed { s.mu.Unlock() return 0, errors.New(errBrokenPipe) } if s.kcp.WaitSnd() < int(s.kcp.snd_wnd) { for _, b := range v { n += len(b) for { if len(b) <= int(s.kcp.mss) { s.kcp.Send(b) break } else { s.kcp.Send(b[:s.kcp.mss]) b = b[s.kcp.mss:] } } } if s.kcp.WaitSnd() >= int(s.kcp.snd_wnd) || !s.writeDelay { s.kcp.flush(false) } s.mu.Unlock() atomic.AddUint64(&DefaultSnmp.BytesSent, uint64(n)) return n, nil } var timeout *time.Timer var c <-chan time.Time if !s.wd.IsZero() { if time.Now().After(s.wd) { s.mu.Unlock() return 0, errTimeout{} } delay := s.wd.Sub(time.Now()) timeout = time.NewTimer(delay) c = timeout.C } s.mu.Unlock() select { case <-s.chWriteEvent: case <-c: case <-s.die: case err = <-s.chWriteError: if timeout != nil { timeout.Stop() } return n, err } if timeout != nil { timeout.Stop() } } }
go
func (s *UDPSession) WriteBuffers(v [][]byte) (n int, err error) { for { s.mu.Lock() if s.isClosed { s.mu.Unlock() return 0, errors.New(errBrokenPipe) } if s.kcp.WaitSnd() < int(s.kcp.snd_wnd) { for _, b := range v { n += len(b) for { if len(b) <= int(s.kcp.mss) { s.kcp.Send(b) break } else { s.kcp.Send(b[:s.kcp.mss]) b = b[s.kcp.mss:] } } } if s.kcp.WaitSnd() >= int(s.kcp.snd_wnd) || !s.writeDelay { s.kcp.flush(false) } s.mu.Unlock() atomic.AddUint64(&DefaultSnmp.BytesSent, uint64(n)) return n, nil } var timeout *time.Timer var c <-chan time.Time if !s.wd.IsZero() { if time.Now().After(s.wd) { s.mu.Unlock() return 0, errTimeout{} } delay := s.wd.Sub(time.Now()) timeout = time.NewTimer(delay) c = timeout.C } s.mu.Unlock() select { case <-s.chWriteEvent: case <-c: case <-s.die: case err = <-s.chWriteError: if timeout != nil { timeout.Stop() } return n, err } if timeout != nil { timeout.Stop() } } }
[ "func", "(", "s", "*", "UDPSession", ")", "WriteBuffers", "(", "v", "[", "]", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "for", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "if", "s", ".", "isClosed", "{", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "0", ",", "errors", ".", "New", "(", "errBrokenPipe", ")", "\n", "}", "\n\n", "if", "s", ".", "kcp", ".", "WaitSnd", "(", ")", "<", "int", "(", "s", ".", "kcp", ".", "snd_wnd", ")", "{", "for", "_", ",", "b", ":=", "range", "v", "{", "n", "+=", "len", "(", "b", ")", "\n", "for", "{", "if", "len", "(", "b", ")", "<=", "int", "(", "s", ".", "kcp", ".", "mss", ")", "{", "s", ".", "kcp", ".", "Send", "(", "b", ")", "\n", "break", "\n", "}", "else", "{", "s", ".", "kcp", ".", "Send", "(", "b", "[", ":", "s", ".", "kcp", ".", "mss", "]", ")", "\n", "b", "=", "b", "[", "s", ".", "kcp", ".", "mss", ":", "]", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "s", ".", "kcp", ".", "WaitSnd", "(", ")", ">=", "int", "(", "s", ".", "kcp", ".", "snd_wnd", ")", "||", "!", "s", ".", "writeDelay", "{", "s", ".", "kcp", ".", "flush", "(", "false", ")", "\n", "}", "\n", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "atomic", ".", "AddUint64", "(", "&", "DefaultSnmp", ".", "BytesSent", ",", "uint64", "(", "n", ")", ")", "\n", "return", "n", ",", "nil", "\n", "}", "\n\n", "var", "timeout", "*", "time", ".", "Timer", "\n", "var", "c", "<-", "chan", "time", ".", "Time", "\n", "if", "!", "s", ".", "wd", ".", "IsZero", "(", ")", "{", "if", "time", ".", "Now", "(", ")", ".", "After", "(", "s", ".", "wd", ")", "{", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "0", ",", "errTimeout", "{", "}", "\n", "}", "\n", "delay", ":=", "s", ".", "wd", ".", "Sub", "(", "time", ".", "Now", "(", ")", ")", "\n", "timeout", "=", "time", ".", "NewTimer", "(", "delay", ")", "\n", "c", "=", "timeout", ".", "C", "\n", "}", "\n", "s", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "select", "{", "case", "<-", "s", ".", "chWriteEvent", ":", "case", "<-", "c", ":", "case", "<-", "s", ".", "die", ":", "case", "err", "=", "<-", "s", ".", "chWriteError", ":", "if", "timeout", "!=", "nil", "{", "timeout", ".", "Stop", "(", ")", "\n", "}", "\n", "return", "n", ",", "err", "\n", "}", "\n\n", "if", "timeout", "!=", "nil", "{", "timeout", ".", "Stop", "(", ")", "\n", "}", "\n", "}", "\n", "}" ]
// WriteBuffers write a vector of byte slices to the underlying connection
[ "WriteBuffers", "write", "a", "vector", "of", "byte", "slices", "to", "the", "underlying", "connection" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L247-L305
train
xtaci/kcp-go
sess.go
SetWriteDelay
func (s *UDPSession) SetWriteDelay(delay bool) { s.mu.Lock() defer s.mu.Unlock() s.writeDelay = delay }
go
func (s *UDPSession) SetWriteDelay(delay bool) { s.mu.Lock() defer s.mu.Unlock() s.writeDelay = delay }
[ "func", "(", "s", "*", "UDPSession", ")", "SetWriteDelay", "(", "delay", "bool", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "s", ".", "writeDelay", "=", "delay", "\n", "}" ]
// SetWriteDelay delays write for bulk transfer until the next update interval
[ "SetWriteDelay", "delays", "write", "for", "bulk", "transfer", "until", "the", "next", "update", "interval" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L365-L369
train
xtaci/kcp-go
sess.go
SetWindowSize
func (s *UDPSession) SetWindowSize(sndwnd, rcvwnd int) { s.mu.Lock() defer s.mu.Unlock() s.kcp.WndSize(sndwnd, rcvwnd) }
go
func (s *UDPSession) SetWindowSize(sndwnd, rcvwnd int) { s.mu.Lock() defer s.mu.Unlock() s.kcp.WndSize(sndwnd, rcvwnd) }
[ "func", "(", "s", "*", "UDPSession", ")", "SetWindowSize", "(", "sndwnd", ",", "rcvwnd", "int", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "s", ".", "kcp", ".", "WndSize", "(", "sndwnd", ",", "rcvwnd", ")", "\n", "}" ]
// SetWindowSize set maximum window size
[ "SetWindowSize", "set", "maximum", "window", "size" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L372-L376
train
xtaci/kcp-go
sess.go
SetACKNoDelay
func (s *UDPSession) SetACKNoDelay(nodelay bool) { s.mu.Lock() defer s.mu.Unlock() s.ackNoDelay = nodelay }
go
func (s *UDPSession) SetACKNoDelay(nodelay bool) { s.mu.Lock() defer s.mu.Unlock() s.ackNoDelay = nodelay }
[ "func", "(", "s", "*", "UDPSession", ")", "SetACKNoDelay", "(", "nodelay", "bool", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "s", ".", "ackNoDelay", "=", "nodelay", "\n", "}" ]
// SetACKNoDelay changes ack flush option, set true to flush ack immediately,
[ "SetACKNoDelay", "changes", "ack", "flush", "option", "set", "true", "to", "flush", "ack", "immediately" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L402-L406
train
xtaci/kcp-go
sess.go
SetDUP
func (s *UDPSession) SetDUP(dup int) { s.mu.Lock() defer s.mu.Unlock() s.dup = dup }
go
func (s *UDPSession) SetDUP(dup int) { s.mu.Lock() defer s.mu.Unlock() s.dup = dup }
[ "func", "(", "s", "*", "UDPSession", ")", "SetDUP", "(", "dup", "int", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "s", ".", "dup", "=", "dup", "\n", "}" ]
// SetDUP duplicates udp packets for kcp output, for testing purpose only
[ "SetDUP", "duplicates", "udp", "packets", "for", "kcp", "output", "for", "testing", "purpose", "only" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L409-L413
train
xtaci/kcp-go
sess.go
SetReadBuffer
func (s *UDPSession) SetReadBuffer(bytes int) error { s.mu.Lock() defer s.mu.Unlock() if s.l == nil { if nc, ok := s.conn.(setReadBuffer); ok { return nc.SetReadBuffer(bytes) } } return errors.New(errInvalidOperation) }
go
func (s *UDPSession) SetReadBuffer(bytes int) error { s.mu.Lock() defer s.mu.Unlock() if s.l == nil { if nc, ok := s.conn.(setReadBuffer); ok { return nc.SetReadBuffer(bytes) } } return errors.New(errInvalidOperation) }
[ "func", "(", "s", "*", "UDPSession", ")", "SetReadBuffer", "(", "bytes", "int", ")", "error", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "s", ".", "l", "==", "nil", "{", "if", "nc", ",", "ok", ":=", "s", ".", "conn", ".", "(", "setReadBuffer", ")", ";", "ok", "{", "return", "nc", ".", "SetReadBuffer", "(", "bytes", ")", "\n", "}", "\n", "}", "\n", "return", "errors", ".", "New", "(", "errInvalidOperation", ")", "\n", "}" ]
// SetReadBuffer sets the socket read buffer, no effect if it's accepted from Listener
[ "SetReadBuffer", "sets", "the", "socket", "read", "buffer", "no", "effect", "if", "it", "s", "accepted", "from", "Listener" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L441-L450
train
xtaci/kcp-go
sess.go
update
func (s *UDPSession) update() (interval time.Duration) { s.mu.Lock() waitsnd := s.kcp.WaitSnd() interval = time.Duration(s.kcp.flush(false)) * time.Millisecond if s.kcp.WaitSnd() < waitsnd { s.notifyWriteEvent() } s.mu.Unlock() return }
go
func (s *UDPSession) update() (interval time.Duration) { s.mu.Lock() waitsnd := s.kcp.WaitSnd() interval = time.Duration(s.kcp.flush(false)) * time.Millisecond if s.kcp.WaitSnd() < waitsnd { s.notifyWriteEvent() } s.mu.Unlock() return }
[ "func", "(", "s", "*", "UDPSession", ")", "update", "(", ")", "(", "interval", "time", ".", "Duration", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "waitsnd", ":=", "s", ".", "kcp", ".", "WaitSnd", "(", ")", "\n", "interval", "=", "time", ".", "Duration", "(", "s", ".", "kcp", ".", "flush", "(", "false", ")", ")", "*", "time", ".", "Millisecond", "\n", "if", "s", ".", "kcp", ".", "WaitSnd", "(", ")", "<", "waitsnd", "{", "s", ".", "notifyWriteEvent", "(", ")", "\n", "}", "\n", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "\n", "}" ]
// kcp update, returns interval for next calling
[ "kcp", "update", "returns", "interval", "for", "next", "calling" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L518-L527
train
xtaci/kcp-go
sess.go
SetReadBuffer
func (l *Listener) SetReadBuffer(bytes int) error { if nc, ok := l.conn.(setReadBuffer); ok { return nc.SetReadBuffer(bytes) } return errors.New(errInvalidOperation) }
go
func (l *Listener) SetReadBuffer(bytes int) error { if nc, ok := l.conn.(setReadBuffer); ok { return nc.SetReadBuffer(bytes) } return errors.New(errInvalidOperation) }
[ "func", "(", "l", "*", "Listener", ")", "SetReadBuffer", "(", "bytes", "int", ")", "error", "{", "if", "nc", ",", "ok", ":=", "l", ".", "conn", ".", "(", "setReadBuffer", ")", ";", "ok", "{", "return", "nc", ".", "SetReadBuffer", "(", "bytes", ")", "\n", "}", "\n", "return", "errors", ".", "New", "(", "errInvalidOperation", ")", "\n", "}" ]
// SetReadBuffer sets the socket read buffer for the Listener
[ "SetReadBuffer", "sets", "the", "socket", "read", "buffer", "for", "the", "Listener" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L733-L738
train
xtaci/kcp-go
sess.go
SetWriteBuffer
func (l *Listener) SetWriteBuffer(bytes int) error { if nc, ok := l.conn.(setWriteBuffer); ok { return nc.SetWriteBuffer(bytes) } return errors.New(errInvalidOperation) }
go
func (l *Listener) SetWriteBuffer(bytes int) error { if nc, ok := l.conn.(setWriteBuffer); ok { return nc.SetWriteBuffer(bytes) } return errors.New(errInvalidOperation) }
[ "func", "(", "l", "*", "Listener", ")", "SetWriteBuffer", "(", "bytes", "int", ")", "error", "{", "if", "nc", ",", "ok", ":=", "l", ".", "conn", ".", "(", "setWriteBuffer", ")", ";", "ok", "{", "return", "nc", ".", "SetWriteBuffer", "(", "bytes", ")", "\n", "}", "\n", "return", "errors", ".", "New", "(", "errInvalidOperation", ")", "\n", "}" ]
// SetWriteBuffer sets the socket write buffer for the Listener
[ "SetWriteBuffer", "sets", "the", "socket", "write", "buffer", "for", "the", "Listener" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L741-L746
train
xtaci/kcp-go
sess.go
SetDSCP
func (l *Listener) SetDSCP(dscp int) error { if nc, ok := l.conn.(net.Conn); ok { addr, _ := net.ResolveUDPAddr("udp", nc.LocalAddr().String()) if addr.IP.To4() != nil { return ipv4.NewConn(nc).SetTOS(dscp << 2) } else { return ipv6.NewConn(nc).SetTrafficClass(dscp) } } return errors.New(errInvalidOperation) }
go
func (l *Listener) SetDSCP(dscp int) error { if nc, ok := l.conn.(net.Conn); ok { addr, _ := net.ResolveUDPAddr("udp", nc.LocalAddr().String()) if addr.IP.To4() != nil { return ipv4.NewConn(nc).SetTOS(dscp << 2) } else { return ipv6.NewConn(nc).SetTrafficClass(dscp) } } return errors.New(errInvalidOperation) }
[ "func", "(", "l", "*", "Listener", ")", "SetDSCP", "(", "dscp", "int", ")", "error", "{", "if", "nc", ",", "ok", ":=", "l", ".", "conn", ".", "(", "net", ".", "Conn", ")", ";", "ok", "{", "addr", ",", "_", ":=", "net", ".", "ResolveUDPAddr", "(", "\"", "\"", ",", "nc", ".", "LocalAddr", "(", ")", ".", "String", "(", ")", ")", "\n", "if", "addr", ".", "IP", ".", "To4", "(", ")", "!=", "nil", "{", "return", "ipv4", ".", "NewConn", "(", "nc", ")", ".", "SetTOS", "(", "dscp", "<<", "2", ")", "\n", "}", "else", "{", "return", "ipv6", ".", "NewConn", "(", "nc", ")", ".", "SetTrafficClass", "(", "dscp", ")", "\n", "}", "\n", "}", "\n", "return", "errors", ".", "New", "(", "errInvalidOperation", ")", "\n", "}" ]
// SetDSCP sets the 6bit DSCP field of IP header
[ "SetDSCP", "sets", "the", "6bit", "DSCP", "field", "of", "IP", "header" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L749-L759
train
xtaci/kcp-go
sess.go
AcceptKCP
func (l *Listener) AcceptKCP() (*UDPSession, error) { var timeout <-chan time.Time if tdeadline, ok := l.rd.Load().(time.Time); ok && !tdeadline.IsZero() { timeout = time.After(tdeadline.Sub(time.Now())) } select { case <-timeout: return nil, &errTimeout{} case c := <-l.chAccepts: return c, nil case <-l.die: return nil, errors.New(errBrokenPipe) } }
go
func (l *Listener) AcceptKCP() (*UDPSession, error) { var timeout <-chan time.Time if tdeadline, ok := l.rd.Load().(time.Time); ok && !tdeadline.IsZero() { timeout = time.After(tdeadline.Sub(time.Now())) } select { case <-timeout: return nil, &errTimeout{} case c := <-l.chAccepts: return c, nil case <-l.die: return nil, errors.New(errBrokenPipe) } }
[ "func", "(", "l", "*", "Listener", ")", "AcceptKCP", "(", ")", "(", "*", "UDPSession", ",", "error", ")", "{", "var", "timeout", "<-", "chan", "time", ".", "Time", "\n", "if", "tdeadline", ",", "ok", ":=", "l", ".", "rd", ".", "Load", "(", ")", ".", "(", "time", ".", "Time", ")", ";", "ok", "&&", "!", "tdeadline", ".", "IsZero", "(", ")", "{", "timeout", "=", "time", ".", "After", "(", "tdeadline", ".", "Sub", "(", "time", ".", "Now", "(", ")", ")", ")", "\n", "}", "\n\n", "select", "{", "case", "<-", "timeout", ":", "return", "nil", ",", "&", "errTimeout", "{", "}", "\n", "case", "c", ":=", "<-", "l", ".", "chAccepts", ":", "return", "c", ",", "nil", "\n", "case", "<-", "l", ".", "die", ":", "return", "nil", ",", "errors", ".", "New", "(", "errBrokenPipe", ")", "\n", "}", "\n", "}" ]
// AcceptKCP accepts a KCP connection
[ "AcceptKCP", "accepts", "a", "KCP", "connection" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L767-L781
train
xtaci/kcp-go
sess.go
Close
func (l *Listener) Close() error { close(l.die) return l.conn.Close() }
go
func (l *Listener) Close() error { close(l.die) return l.conn.Close() }
[ "func", "(", "l", "*", "Listener", ")", "Close", "(", ")", "error", "{", "close", "(", "l", ".", "die", ")", "\n", "return", "l", ".", "conn", ".", "Close", "(", ")", "\n", "}" ]
// Close stops listening on the UDP address. Already Accepted connections are not closed.
[ "Close", "stops", "listening", "on", "the", "UDP", "address", ".", "Already", "Accepted", "connections", "are", "not", "closed", "." ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L803-L806
train
xtaci/kcp-go
sess.go
closeSession
func (l *Listener) closeSession(remote net.Addr) (ret bool) { l.sessionLock.Lock() defer l.sessionLock.Unlock() if _, ok := l.sessions[remote.String()]; ok { delete(l.sessions, remote.String()) return true } return false }
go
func (l *Listener) closeSession(remote net.Addr) (ret bool) { l.sessionLock.Lock() defer l.sessionLock.Unlock() if _, ok := l.sessions[remote.String()]; ok { delete(l.sessions, remote.String()) return true } return false }
[ "func", "(", "l", "*", "Listener", ")", "closeSession", "(", "remote", "net", ".", "Addr", ")", "(", "ret", "bool", ")", "{", "l", ".", "sessionLock", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "sessionLock", ".", "Unlock", "(", ")", "\n", "if", "_", ",", "ok", ":=", "l", ".", "sessions", "[", "remote", ".", "String", "(", ")", "]", ";", "ok", "{", "delete", "(", "l", ".", "sessions", ",", "remote", ".", "String", "(", ")", ")", "\n", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// closeSession notify the listener that a session has closed
[ "closeSession", "notify", "the", "listener", "that", "a", "session", "has", "closed" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L809-L817
train
xtaci/kcp-go
sess.go
ListenWithOptions
func ListenWithOptions(laddr string, block BlockCrypt, dataShards, parityShards int) (*Listener, error) { udpaddr, err := net.ResolveUDPAddr("udp", laddr) if err != nil { return nil, errors.Wrap(err, "net.ResolveUDPAddr") } conn, err := net.ListenUDP("udp", udpaddr) if err != nil { return nil, errors.Wrap(err, "net.ListenUDP") } return ServeConn(block, dataShards, parityShards, conn) }
go
func ListenWithOptions(laddr string, block BlockCrypt, dataShards, parityShards int) (*Listener, error) { udpaddr, err := net.ResolveUDPAddr("udp", laddr) if err != nil { return nil, errors.Wrap(err, "net.ResolveUDPAddr") } conn, err := net.ListenUDP("udp", udpaddr) if err != nil { return nil, errors.Wrap(err, "net.ListenUDP") } return ServeConn(block, dataShards, parityShards, conn) }
[ "func", "ListenWithOptions", "(", "laddr", "string", ",", "block", "BlockCrypt", ",", "dataShards", ",", "parityShards", "int", ")", "(", "*", "Listener", ",", "error", ")", "{", "udpaddr", ",", "err", ":=", "net", ".", "ResolveUDPAddr", "(", "\"", "\"", ",", "laddr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "conn", ",", "err", ":=", "net", ".", "ListenUDP", "(", "\"", "\"", ",", "udpaddr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "ServeConn", "(", "block", ",", "dataShards", ",", "parityShards", ",", "conn", ")", "\n", "}" ]
// ListenWithOptions listens for incoming KCP packets addressed to the local address laddr on the network "udp" with packet encryption, // dataShards, parityShards defines Reed-Solomon Erasure Coding parameters
[ "ListenWithOptions", "listens", "for", "incoming", "KCP", "packets", "addressed", "to", "the", "local", "address", "laddr", "on", "the", "network", "udp", "with", "packet", "encryption", "dataShards", "parityShards", "defines", "Reed", "-", "Solomon", "Erasure", "Coding", "parameters" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L827-L838
train
xtaci/kcp-go
sess.go
ServeConn
func ServeConn(block BlockCrypt, dataShards, parityShards int, conn net.PacketConn) (*Listener, error) { l := new(Listener) l.conn = conn l.sessions = make(map[string]*UDPSession) l.chAccepts = make(chan *UDPSession, acceptBacklog) l.chSessionClosed = make(chan net.Addr) l.die = make(chan struct{}) l.dataShards = dataShards l.parityShards = parityShards l.block = block l.fecDecoder = newFECDecoder(rxFECMulti*(dataShards+parityShards), dataShards, parityShards) // calculate header size if l.block != nil { l.headerSize += cryptHeaderSize } if l.fecDecoder != nil { l.headerSize += fecHeaderSizePlus2 } go l.monitor() return l, nil }
go
func ServeConn(block BlockCrypt, dataShards, parityShards int, conn net.PacketConn) (*Listener, error) { l := new(Listener) l.conn = conn l.sessions = make(map[string]*UDPSession) l.chAccepts = make(chan *UDPSession, acceptBacklog) l.chSessionClosed = make(chan net.Addr) l.die = make(chan struct{}) l.dataShards = dataShards l.parityShards = parityShards l.block = block l.fecDecoder = newFECDecoder(rxFECMulti*(dataShards+parityShards), dataShards, parityShards) // calculate header size if l.block != nil { l.headerSize += cryptHeaderSize } if l.fecDecoder != nil { l.headerSize += fecHeaderSizePlus2 } go l.monitor() return l, nil }
[ "func", "ServeConn", "(", "block", "BlockCrypt", ",", "dataShards", ",", "parityShards", "int", ",", "conn", "net", ".", "PacketConn", ")", "(", "*", "Listener", ",", "error", ")", "{", "l", ":=", "new", "(", "Listener", ")", "\n", "l", ".", "conn", "=", "conn", "\n", "l", ".", "sessions", "=", "make", "(", "map", "[", "string", "]", "*", "UDPSession", ")", "\n", "l", ".", "chAccepts", "=", "make", "(", "chan", "*", "UDPSession", ",", "acceptBacklog", ")", "\n", "l", ".", "chSessionClosed", "=", "make", "(", "chan", "net", ".", "Addr", ")", "\n", "l", ".", "die", "=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "l", ".", "dataShards", "=", "dataShards", "\n", "l", ".", "parityShards", "=", "parityShards", "\n", "l", ".", "block", "=", "block", "\n", "l", ".", "fecDecoder", "=", "newFECDecoder", "(", "rxFECMulti", "*", "(", "dataShards", "+", "parityShards", ")", ",", "dataShards", ",", "parityShards", ")", "\n\n", "// calculate header size", "if", "l", ".", "block", "!=", "nil", "{", "l", ".", "headerSize", "+=", "cryptHeaderSize", "\n", "}", "\n", "if", "l", ".", "fecDecoder", "!=", "nil", "{", "l", ".", "headerSize", "+=", "fecHeaderSizePlus2", "\n", "}", "\n\n", "go", "l", ".", "monitor", "(", ")", "\n", "return", "l", ",", "nil", "\n", "}" ]
// ServeConn serves KCP protocol for a single packet connection.
[ "ServeConn", "serves", "KCP", "protocol", "for", "a", "single", "packet", "connection", "." ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L841-L863
train
xtaci/kcp-go
sess.go
DialWithOptions
func DialWithOptions(raddr string, block BlockCrypt, dataShards, parityShards int) (*UDPSession, error) { // network type detection udpaddr, err := net.ResolveUDPAddr("udp", raddr) if err != nil { return nil, errors.Wrap(err, "net.ResolveUDPAddr") } network := "udp4" if udpaddr.IP.To4() == nil { network = "udp" } conn, err := net.ListenUDP(network, nil) if err != nil { return nil, errors.Wrap(err, "net.DialUDP") } return NewConn(raddr, block, dataShards, parityShards, conn) }
go
func DialWithOptions(raddr string, block BlockCrypt, dataShards, parityShards int) (*UDPSession, error) { // network type detection udpaddr, err := net.ResolveUDPAddr("udp", raddr) if err != nil { return nil, errors.Wrap(err, "net.ResolveUDPAddr") } network := "udp4" if udpaddr.IP.To4() == nil { network = "udp" } conn, err := net.ListenUDP(network, nil) if err != nil { return nil, errors.Wrap(err, "net.DialUDP") } return NewConn(raddr, block, dataShards, parityShards, conn) }
[ "func", "DialWithOptions", "(", "raddr", "string", ",", "block", "BlockCrypt", ",", "dataShards", ",", "parityShards", "int", ")", "(", "*", "UDPSession", ",", "error", ")", "{", "// network type detection", "udpaddr", ",", "err", ":=", "net", ".", "ResolveUDPAddr", "(", "\"", "\"", ",", "raddr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "network", ":=", "\"", "\"", "\n", "if", "udpaddr", ".", "IP", ".", "To4", "(", ")", "==", "nil", "{", "network", "=", "\"", "\"", "\n", "}", "\n\n", "conn", ",", "err", ":=", "net", ".", "ListenUDP", "(", "network", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "NewConn", "(", "raddr", ",", "block", ",", "dataShards", ",", "parityShards", ",", "conn", ")", "\n", "}" ]
// DialWithOptions connects to the remote address "raddr" on the network "udp" with packet encryption
[ "DialWithOptions", "connects", "to", "the", "remote", "address", "raddr", "on", "the", "network", "udp", "with", "packet", "encryption" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L869-L886
train
xtaci/kcp-go
sess.go
NewConn
func NewConn(raddr string, block BlockCrypt, dataShards, parityShards int, conn net.PacketConn) (*UDPSession, error) { udpaddr, err := net.ResolveUDPAddr("udp", raddr) if err != nil { return nil, errors.Wrap(err, "net.ResolveUDPAddr") } var convid uint32 binary.Read(rand.Reader, binary.LittleEndian, &convid) return newUDPSession(convid, dataShards, parityShards, nil, conn, udpaddr, block), nil }
go
func NewConn(raddr string, block BlockCrypt, dataShards, parityShards int, conn net.PacketConn) (*UDPSession, error) { udpaddr, err := net.ResolveUDPAddr("udp", raddr) if err != nil { return nil, errors.Wrap(err, "net.ResolveUDPAddr") } var convid uint32 binary.Read(rand.Reader, binary.LittleEndian, &convid) return newUDPSession(convid, dataShards, parityShards, nil, conn, udpaddr, block), nil }
[ "func", "NewConn", "(", "raddr", "string", ",", "block", "BlockCrypt", ",", "dataShards", ",", "parityShards", "int", ",", "conn", "net", ".", "PacketConn", ")", "(", "*", "UDPSession", ",", "error", ")", "{", "udpaddr", ",", "err", ":=", "net", ".", "ResolveUDPAddr", "(", "\"", "\"", ",", "raddr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "var", "convid", "uint32", "\n", "binary", ".", "Read", "(", "rand", ".", "Reader", ",", "binary", ".", "LittleEndian", ",", "&", "convid", ")", "\n", "return", "newUDPSession", "(", "convid", ",", "dataShards", ",", "parityShards", ",", "nil", ",", "conn", ",", "udpaddr", ",", "block", ")", ",", "nil", "\n", "}" ]
// NewConn establishes a session and talks KCP protocol over a packet connection.
[ "NewConn", "establishes", "a", "session", "and", "talks", "KCP", "protocol", "over", "a", "packet", "connection", "." ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/sess.go#L889-L898
train
xtaci/kcp-go
snmp.go
ToSlice
func (s *Snmp) ToSlice() []string { snmp := s.Copy() return []string{ fmt.Sprint(snmp.BytesSent), fmt.Sprint(snmp.BytesReceived), fmt.Sprint(snmp.MaxConn), fmt.Sprint(snmp.ActiveOpens), fmt.Sprint(snmp.PassiveOpens), fmt.Sprint(snmp.CurrEstab), fmt.Sprint(snmp.InErrs), fmt.Sprint(snmp.InCsumErrors), fmt.Sprint(snmp.KCPInErrors), fmt.Sprint(snmp.InPkts), fmt.Sprint(snmp.OutPkts), fmt.Sprint(snmp.InSegs), fmt.Sprint(snmp.OutSegs), fmt.Sprint(snmp.InBytes), fmt.Sprint(snmp.OutBytes), fmt.Sprint(snmp.RetransSegs), fmt.Sprint(snmp.FastRetransSegs), fmt.Sprint(snmp.EarlyRetransSegs), fmt.Sprint(snmp.LostSegs), fmt.Sprint(snmp.RepeatSegs), fmt.Sprint(snmp.FECParityShards), fmt.Sprint(snmp.FECErrs), fmt.Sprint(snmp.FECRecovered), fmt.Sprint(snmp.FECShortShards), } }
go
func (s *Snmp) ToSlice() []string { snmp := s.Copy() return []string{ fmt.Sprint(snmp.BytesSent), fmt.Sprint(snmp.BytesReceived), fmt.Sprint(snmp.MaxConn), fmt.Sprint(snmp.ActiveOpens), fmt.Sprint(snmp.PassiveOpens), fmt.Sprint(snmp.CurrEstab), fmt.Sprint(snmp.InErrs), fmt.Sprint(snmp.InCsumErrors), fmt.Sprint(snmp.KCPInErrors), fmt.Sprint(snmp.InPkts), fmt.Sprint(snmp.OutPkts), fmt.Sprint(snmp.InSegs), fmt.Sprint(snmp.OutSegs), fmt.Sprint(snmp.InBytes), fmt.Sprint(snmp.OutBytes), fmt.Sprint(snmp.RetransSegs), fmt.Sprint(snmp.FastRetransSegs), fmt.Sprint(snmp.EarlyRetransSegs), fmt.Sprint(snmp.LostSegs), fmt.Sprint(snmp.RepeatSegs), fmt.Sprint(snmp.FECParityShards), fmt.Sprint(snmp.FECErrs), fmt.Sprint(snmp.FECRecovered), fmt.Sprint(snmp.FECShortShards), } }
[ "func", "(", "s", "*", "Snmp", ")", "ToSlice", "(", ")", "[", "]", "string", "{", "snmp", ":=", "s", ".", "Copy", "(", ")", "\n", "return", "[", "]", "string", "{", "fmt", ".", "Sprint", "(", "snmp", ".", "BytesSent", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "BytesReceived", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "MaxConn", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "ActiveOpens", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "PassiveOpens", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "CurrEstab", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "InErrs", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "InCsumErrors", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "KCPInErrors", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "InPkts", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "OutPkts", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "InSegs", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "OutSegs", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "InBytes", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "OutBytes", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "RetransSegs", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "FastRetransSegs", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "EarlyRetransSegs", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "LostSegs", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "RepeatSegs", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "FECParityShards", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "FECErrs", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "FECRecovered", ")", ",", "fmt", ".", "Sprint", "(", "snmp", ".", "FECShortShards", ")", ",", "}", "\n", "}" ]
// ToSlice returns current snmp info as slice
[ "ToSlice", "returns", "current", "snmp", "info", "as", "slice" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/snmp.go#L71-L99
train
xtaci/kcp-go
snmp.go
Copy
func (s *Snmp) Copy() *Snmp { d := newSnmp() d.BytesSent = atomic.LoadUint64(&s.BytesSent) d.BytesReceived = atomic.LoadUint64(&s.BytesReceived) d.MaxConn = atomic.LoadUint64(&s.MaxConn) d.ActiveOpens = atomic.LoadUint64(&s.ActiveOpens) d.PassiveOpens = atomic.LoadUint64(&s.PassiveOpens) d.CurrEstab = atomic.LoadUint64(&s.CurrEstab) d.InErrs = atomic.LoadUint64(&s.InErrs) d.InCsumErrors = atomic.LoadUint64(&s.InCsumErrors) d.KCPInErrors = atomic.LoadUint64(&s.KCPInErrors) d.InPkts = atomic.LoadUint64(&s.InPkts) d.OutPkts = atomic.LoadUint64(&s.OutPkts) d.InSegs = atomic.LoadUint64(&s.InSegs) d.OutSegs = atomic.LoadUint64(&s.OutSegs) d.InBytes = atomic.LoadUint64(&s.InBytes) d.OutBytes = atomic.LoadUint64(&s.OutBytes) d.RetransSegs = atomic.LoadUint64(&s.RetransSegs) d.FastRetransSegs = atomic.LoadUint64(&s.FastRetransSegs) d.EarlyRetransSegs = atomic.LoadUint64(&s.EarlyRetransSegs) d.LostSegs = atomic.LoadUint64(&s.LostSegs) d.RepeatSegs = atomic.LoadUint64(&s.RepeatSegs) d.FECParityShards = atomic.LoadUint64(&s.FECParityShards) d.FECErrs = atomic.LoadUint64(&s.FECErrs) d.FECRecovered = atomic.LoadUint64(&s.FECRecovered) d.FECShortShards = atomic.LoadUint64(&s.FECShortShards) return d }
go
func (s *Snmp) Copy() *Snmp { d := newSnmp() d.BytesSent = atomic.LoadUint64(&s.BytesSent) d.BytesReceived = atomic.LoadUint64(&s.BytesReceived) d.MaxConn = atomic.LoadUint64(&s.MaxConn) d.ActiveOpens = atomic.LoadUint64(&s.ActiveOpens) d.PassiveOpens = atomic.LoadUint64(&s.PassiveOpens) d.CurrEstab = atomic.LoadUint64(&s.CurrEstab) d.InErrs = atomic.LoadUint64(&s.InErrs) d.InCsumErrors = atomic.LoadUint64(&s.InCsumErrors) d.KCPInErrors = atomic.LoadUint64(&s.KCPInErrors) d.InPkts = atomic.LoadUint64(&s.InPkts) d.OutPkts = atomic.LoadUint64(&s.OutPkts) d.InSegs = atomic.LoadUint64(&s.InSegs) d.OutSegs = atomic.LoadUint64(&s.OutSegs) d.InBytes = atomic.LoadUint64(&s.InBytes) d.OutBytes = atomic.LoadUint64(&s.OutBytes) d.RetransSegs = atomic.LoadUint64(&s.RetransSegs) d.FastRetransSegs = atomic.LoadUint64(&s.FastRetransSegs) d.EarlyRetransSegs = atomic.LoadUint64(&s.EarlyRetransSegs) d.LostSegs = atomic.LoadUint64(&s.LostSegs) d.RepeatSegs = atomic.LoadUint64(&s.RepeatSegs) d.FECParityShards = atomic.LoadUint64(&s.FECParityShards) d.FECErrs = atomic.LoadUint64(&s.FECErrs) d.FECRecovered = atomic.LoadUint64(&s.FECRecovered) d.FECShortShards = atomic.LoadUint64(&s.FECShortShards) return d }
[ "func", "(", "s", "*", "Snmp", ")", "Copy", "(", ")", "*", "Snmp", "{", "d", ":=", "newSnmp", "(", ")", "\n", "d", ".", "BytesSent", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "BytesSent", ")", "\n", "d", ".", "BytesReceived", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "BytesReceived", ")", "\n", "d", ".", "MaxConn", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "MaxConn", ")", "\n", "d", ".", "ActiveOpens", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "ActiveOpens", ")", "\n", "d", ".", "PassiveOpens", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "PassiveOpens", ")", "\n", "d", ".", "CurrEstab", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "CurrEstab", ")", "\n", "d", ".", "InErrs", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "InErrs", ")", "\n", "d", ".", "InCsumErrors", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "InCsumErrors", ")", "\n", "d", ".", "KCPInErrors", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "KCPInErrors", ")", "\n", "d", ".", "InPkts", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "InPkts", ")", "\n", "d", ".", "OutPkts", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "OutPkts", ")", "\n", "d", ".", "InSegs", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "InSegs", ")", "\n", "d", ".", "OutSegs", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "OutSegs", ")", "\n", "d", ".", "InBytes", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "InBytes", ")", "\n", "d", ".", "OutBytes", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "OutBytes", ")", "\n", "d", ".", "RetransSegs", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "RetransSegs", ")", "\n", "d", ".", "FastRetransSegs", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "FastRetransSegs", ")", "\n", "d", ".", "EarlyRetransSegs", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "EarlyRetransSegs", ")", "\n", "d", ".", "LostSegs", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "LostSegs", ")", "\n", "d", ".", "RepeatSegs", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "RepeatSegs", ")", "\n", "d", ".", "FECParityShards", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "FECParityShards", ")", "\n", "d", ".", "FECErrs", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "FECErrs", ")", "\n", "d", ".", "FECRecovered", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "FECRecovered", ")", "\n", "d", ".", "FECShortShards", "=", "atomic", ".", "LoadUint64", "(", "&", "s", ".", "FECShortShards", ")", "\n", "return", "d", "\n", "}" ]
// Copy make a copy of current snmp snapshot
[ "Copy", "make", "a", "copy", "of", "current", "snmp", "snapshot" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/snmp.go#L102-L129
train
xtaci/kcp-go
snmp.go
Reset
func (s *Snmp) Reset() { atomic.StoreUint64(&s.BytesSent, 0) atomic.StoreUint64(&s.BytesReceived, 0) atomic.StoreUint64(&s.MaxConn, 0) atomic.StoreUint64(&s.ActiveOpens, 0) atomic.StoreUint64(&s.PassiveOpens, 0) atomic.StoreUint64(&s.CurrEstab, 0) atomic.StoreUint64(&s.InErrs, 0) atomic.StoreUint64(&s.InCsumErrors, 0) atomic.StoreUint64(&s.KCPInErrors, 0) atomic.StoreUint64(&s.InPkts, 0) atomic.StoreUint64(&s.OutPkts, 0) atomic.StoreUint64(&s.InSegs, 0) atomic.StoreUint64(&s.OutSegs, 0) atomic.StoreUint64(&s.InBytes, 0) atomic.StoreUint64(&s.OutBytes, 0) atomic.StoreUint64(&s.RetransSegs, 0) atomic.StoreUint64(&s.FastRetransSegs, 0) atomic.StoreUint64(&s.EarlyRetransSegs, 0) atomic.StoreUint64(&s.LostSegs, 0) atomic.StoreUint64(&s.RepeatSegs, 0) atomic.StoreUint64(&s.FECParityShards, 0) atomic.StoreUint64(&s.FECErrs, 0) atomic.StoreUint64(&s.FECRecovered, 0) atomic.StoreUint64(&s.FECShortShards, 0) }
go
func (s *Snmp) Reset() { atomic.StoreUint64(&s.BytesSent, 0) atomic.StoreUint64(&s.BytesReceived, 0) atomic.StoreUint64(&s.MaxConn, 0) atomic.StoreUint64(&s.ActiveOpens, 0) atomic.StoreUint64(&s.PassiveOpens, 0) atomic.StoreUint64(&s.CurrEstab, 0) atomic.StoreUint64(&s.InErrs, 0) atomic.StoreUint64(&s.InCsumErrors, 0) atomic.StoreUint64(&s.KCPInErrors, 0) atomic.StoreUint64(&s.InPkts, 0) atomic.StoreUint64(&s.OutPkts, 0) atomic.StoreUint64(&s.InSegs, 0) atomic.StoreUint64(&s.OutSegs, 0) atomic.StoreUint64(&s.InBytes, 0) atomic.StoreUint64(&s.OutBytes, 0) atomic.StoreUint64(&s.RetransSegs, 0) atomic.StoreUint64(&s.FastRetransSegs, 0) atomic.StoreUint64(&s.EarlyRetransSegs, 0) atomic.StoreUint64(&s.LostSegs, 0) atomic.StoreUint64(&s.RepeatSegs, 0) atomic.StoreUint64(&s.FECParityShards, 0) atomic.StoreUint64(&s.FECErrs, 0) atomic.StoreUint64(&s.FECRecovered, 0) atomic.StoreUint64(&s.FECShortShards, 0) }
[ "func", "(", "s", "*", "Snmp", ")", "Reset", "(", ")", "{", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "BytesSent", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "BytesReceived", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "MaxConn", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "ActiveOpens", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "PassiveOpens", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "CurrEstab", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "InErrs", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "InCsumErrors", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "KCPInErrors", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "InPkts", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "OutPkts", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "InSegs", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "OutSegs", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "InBytes", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "OutBytes", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "RetransSegs", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "FastRetransSegs", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "EarlyRetransSegs", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "LostSegs", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "RepeatSegs", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "FECParityShards", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "FECErrs", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "FECRecovered", ",", "0", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "s", ".", "FECShortShards", ",", "0", ")", "\n", "}" ]
// Reset values to zero
[ "Reset", "values", "to", "zero" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/snmp.go#L132-L157
train
xtaci/kcp-go
crypt.go
NewSimpleXORBlockCrypt
func NewSimpleXORBlockCrypt(key []byte) (BlockCrypt, error) { c := new(simpleXORBlockCrypt) c.xortbl = pbkdf2.Key(key, []byte(saltxor), 32, mtuLimit, sha1.New) return c, nil }
go
func NewSimpleXORBlockCrypt(key []byte) (BlockCrypt, error) { c := new(simpleXORBlockCrypt) c.xortbl = pbkdf2.Key(key, []byte(saltxor), 32, mtuLimit, sha1.New) return c, nil }
[ "func", "NewSimpleXORBlockCrypt", "(", "key", "[", "]", "byte", ")", "(", "BlockCrypt", ",", "error", ")", "{", "c", ":=", "new", "(", "simpleXORBlockCrypt", ")", "\n", "c", ".", "xortbl", "=", "pbkdf2", ".", "Key", "(", "key", ",", "[", "]", "byte", "(", "saltxor", ")", ",", "32", ",", "mtuLimit", ",", "sha1", ".", "New", ")", "\n", "return", "c", ",", "nil", "\n", "}" ]
// NewSimpleXORBlockCrypt simple xor with key expanding
[ "NewSimpleXORBlockCrypt", "simple", "xor", "with", "key", "expanding" ]
88b8a1475ba14b58f41457c9c89b5ccd919f1c24
https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/crypt.go#L224-L228
train