repo stringlengths 5 67 | path stringlengths 4 218 | func_name stringlengths 0 151 | original_string stringlengths 52 373k | language stringclasses 6 values | code stringlengths 52 373k | code_tokens listlengths 10 512 | docstring stringlengths 3 47.2k | docstring_tokens listlengths 3 234 | sha stringlengths 40 40 | url stringlengths 85 339 | partition stringclasses 3 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
remind101/empire | scheduler/cloudformation/cloudformation.go | extractProcessData | func extractProcessData(value string) map[string]string {
data := make(map[string]string)
pairs := strings.Split(value, ",")
for _, p := range pairs {
parts := strings.Split(p, "=")
data[parts[0]] = parts[1]
}
return data
} | go | func extractProcessData(value string) map[string]string {
data := make(map[string]string)
pairs := strings.Split(value, ",")
for _, p := range pairs {
parts := strings.Split(p, "=")
data[parts[0]] = parts[1]
}
return data
} | [
"func",
"extractProcessData",
"(",
"value",
"string",
")",
"map",
"[",
"string",
"]",
"string",
"{",
"data",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"pairs",
":=",
"strings",
".",
"Split",
"(",
"value",
",",
"\",\"",
")",
"... | // extractProcessData extracts a map that maps the process name to some
// corresponding value. | [
"extractProcessData",
"extracts",
"a",
"map",
"that",
"maps",
"the",
"process",
"name",
"to",
"some",
"corresponding",
"value",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/cloudformation.go#L1149-L1159 | train |
remind101/empire | scheduler/cloudformation/cloudformation.go | taskDefinitionToProcess | func taskDefinitionToProcess(td *ecs.TaskDefinition) (*twelvefactor.Process, error) {
// If this task definition has no container definitions, then something
// funky is up.
if len(td.ContainerDefinitions) == 0 {
return nil, errors.New("task definition had no container definitions")
}
container := td.ContainerDefinitions[0]
var command []string
for _, s := range container.Command {
command = append(command, *s)
}
env := make(map[string]string)
for _, kvp := range container.Environment {
if kvp != nil {
env[aws.StringValue(kvp.Name)] = aws.StringValue(kvp.Value)
}
}
return &twelvefactor.Process{
Type: aws.StringValue(container.Name),
Command: command,
Env: env,
CPUShares: uint(*container.Cpu),
Memory: uint(*container.Memory) * bytesize.MB,
Nproc: uint(softLimit(container.Ulimits, "nproc")),
}, nil
} | go | func taskDefinitionToProcess(td *ecs.TaskDefinition) (*twelvefactor.Process, error) {
// If this task definition has no container definitions, then something
// funky is up.
if len(td.ContainerDefinitions) == 0 {
return nil, errors.New("task definition had no container definitions")
}
container := td.ContainerDefinitions[0]
var command []string
for _, s := range container.Command {
command = append(command, *s)
}
env := make(map[string]string)
for _, kvp := range container.Environment {
if kvp != nil {
env[aws.StringValue(kvp.Name)] = aws.StringValue(kvp.Value)
}
}
return &twelvefactor.Process{
Type: aws.StringValue(container.Name),
Command: command,
Env: env,
CPUShares: uint(*container.Cpu),
Memory: uint(*container.Memory) * bytesize.MB,
Nproc: uint(softLimit(container.Ulimits, "nproc")),
}, nil
} | [
"func",
"taskDefinitionToProcess",
"(",
"td",
"*",
"ecs",
".",
"TaskDefinition",
")",
"(",
"*",
"twelvefactor",
".",
"Process",
",",
"error",
")",
"{",
"if",
"len",
"(",
"td",
".",
"ContainerDefinitions",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"error... | // taskDefinitionToProcess takes an ECS Task Definition and converts it to a
// Process. | [
"taskDefinitionToProcess",
"takes",
"an",
"ECS",
"Task",
"Definition",
"and",
"converts",
"it",
"to",
"a",
"Process",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/cloudformation.go#L1163-L1192 | train |
remind101/empire | scheduler/cloudformation/cloudformation.go | chunkStrings | func chunkStrings(s []*string, size int) [][]*string {
var chunks [][]*string
for len(s) > 0 {
end := size
if len(s) < size {
end = len(s)
}
chunks = append(chunks, s[0:end])
s = s[end:]
}
return chunks
} | go | func chunkStrings(s []*string, size int) [][]*string {
var chunks [][]*string
for len(s) > 0 {
end := size
if len(s) < size {
end = len(s)
}
chunks = append(chunks, s[0:end])
s = s[end:]
}
return chunks
} | [
"func",
"chunkStrings",
"(",
"s",
"[",
"]",
"*",
"string",
",",
"size",
"int",
")",
"[",
"]",
"[",
"]",
"*",
"string",
"{",
"var",
"chunks",
"[",
"]",
"[",
"]",
"*",
"string",
"\n",
"for",
"len",
"(",
"s",
")",
">",
"0",
"{",
"end",
":=",
"... | // chunkStrings slices a slice of string pointers in equal length chunks, with
// the last slice being the leftovers. | [
"chunkStrings",
"slices",
"a",
"slice",
"of",
"string",
"pointers",
"in",
"equal",
"length",
"chunks",
"with",
"the",
"last",
"slice",
"being",
"the",
"leftovers",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/cloudformation.go#L1210-L1222 | train |
remind101/empire | scheduler/cloudformation/cloudformation.go | updateParameters | func updateParameters(provided []*cloudformation.Parameter, stack *cloudformation.Stack, template *cloudformationTemplate) []*cloudformation.Parameter {
parameters := provided[:]
// This tracks the names of the parameters that have pre-existing values
// on the stack.
existingParams := make(map[string]bool)
for _, p := range stack.Parameters {
existingParams[*p.ParameterKey] = true
}
// These are the parameters that can be set for the stack. If a template
// is provided, then these are the parameters defined in the template.
// If no template is provided, then these are the parameters that the
// stack provides.
settableParams := make(map[string]bool)
if template != nil {
for _, p := range template.Parameters {
settableParams[*p.ParameterKey] = true
}
} else {
settableParams = existingParams
}
// The parameters that are provided in this update.
providedParams := make(map[string]bool)
for _, p := range parameters {
providedParams[*p.ParameterKey] = true
}
// Fill in any parameters that weren't provided with their previous
// value, if available
for k := range settableParams {
notProvided := !providedParams[k]
hasExistingValue := existingParams[k]
// If the parameter hasn't been provided with an explicit value,
// and the stack has this parameter set, we'll use the previous
// value. Not doing this would result in the parameters
// `Default` getting used.
if notProvided && hasExistingValue {
parameters = append(parameters, &cloudformation.Parameter{
ParameterKey: aws.String(k),
UsePreviousValue: aws.Bool(true),
})
}
}
return parameters
} | go | func updateParameters(provided []*cloudformation.Parameter, stack *cloudformation.Stack, template *cloudformationTemplate) []*cloudformation.Parameter {
parameters := provided[:]
// This tracks the names of the parameters that have pre-existing values
// on the stack.
existingParams := make(map[string]bool)
for _, p := range stack.Parameters {
existingParams[*p.ParameterKey] = true
}
// These are the parameters that can be set for the stack. If a template
// is provided, then these are the parameters defined in the template.
// If no template is provided, then these are the parameters that the
// stack provides.
settableParams := make(map[string]bool)
if template != nil {
for _, p := range template.Parameters {
settableParams[*p.ParameterKey] = true
}
} else {
settableParams = existingParams
}
// The parameters that are provided in this update.
providedParams := make(map[string]bool)
for _, p := range parameters {
providedParams[*p.ParameterKey] = true
}
// Fill in any parameters that weren't provided with their previous
// value, if available
for k := range settableParams {
notProvided := !providedParams[k]
hasExistingValue := existingParams[k]
// If the parameter hasn't been provided with an explicit value,
// and the stack has this parameter set, we'll use the previous
// value. Not doing this would result in the parameters
// `Default` getting used.
if notProvided && hasExistingValue {
parameters = append(parameters, &cloudformation.Parameter{
ParameterKey: aws.String(k),
UsePreviousValue: aws.Bool(true),
})
}
}
return parameters
} | [
"func",
"updateParameters",
"(",
"provided",
"[",
"]",
"*",
"cloudformation",
".",
"Parameter",
",",
"stack",
"*",
"cloudformation",
".",
"Stack",
",",
"template",
"*",
"cloudformationTemplate",
")",
"[",
"]",
"*",
"cloudformation",
".",
"Parameter",
"{",
"par... | // updateParameters returns the parameters that should be provided in an
// UpdateStack operation. | [
"updateParameters",
"returns",
"the",
"parameters",
"that",
"should",
"be",
"provided",
"in",
"an",
"UpdateStack",
"operation",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/cloudformation.go#L1226-L1274 | train |
remind101/empire | scheduler/cloudformation/cloudformation.go | stackLockKey | func stackLockKey(stackName string) uint32 {
return crc32.ChecksumIEEE([]byte(fmt.Sprintf("stack_%s", stackName)))
} | go | func stackLockKey(stackName string) uint32 {
return crc32.ChecksumIEEE([]byte(fmt.Sprintf("stack_%s", stackName)))
} | [
"func",
"stackLockKey",
"(",
"stackName",
"string",
")",
"uint32",
"{",
"return",
"crc32",
".",
"ChecksumIEEE",
"(",
"[",
"]",
"byte",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"stack_%s\"",
",",
"stackName",
")",
")",
")",
"\n",
"}"
] | // stackLackKey returns the key to use when obtaining an advisory lock for a
// CloudFormation stack. | [
"stackLackKey",
"returns",
"the",
"key",
"to",
"use",
"when",
"obtaining",
"an",
"advisory",
"lock",
"for",
"a",
"CloudFormation",
"stack",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/cloudformation.go#L1278-L1280 | train |
remind101/empire | scheduler/cloudformation/cloudformation.go | newAdvisoryLock | func newAdvisoryLock(db *sql.DB, stackName string) (*pglock.AdvisoryLock, error) {
l, err := pglock.NewAdvisoryLock(db, stackLockKey(stackName))
if err != nil {
return l, err
}
l.LockTimeout = lockTimeout
l.Context = fmt.Sprintf("stack %s", stackName)
return l, nil
} | go | func newAdvisoryLock(db *sql.DB, stackName string) (*pglock.AdvisoryLock, error) {
l, err := pglock.NewAdvisoryLock(db, stackLockKey(stackName))
if err != nil {
return l, err
}
l.LockTimeout = lockTimeout
l.Context = fmt.Sprintf("stack %s", stackName)
return l, nil
} | [
"func",
"newAdvisoryLock",
"(",
"db",
"*",
"sql",
".",
"DB",
",",
"stackName",
"string",
")",
"(",
"*",
"pglock",
".",
"AdvisoryLock",
",",
"error",
")",
"{",
"l",
",",
"err",
":=",
"pglock",
".",
"NewAdvisoryLock",
"(",
"db",
",",
"stackLockKey",
"(",... | // newAdvsiroyLock returns a new AdvisoryLock suitable for obtaining a lock to
// perform the stack update. | [
"newAdvsiroyLock",
"returns",
"a",
"new",
"AdvisoryLock",
"suitable",
"for",
"obtaining",
"a",
"lock",
"to",
"perform",
"the",
"stack",
"update",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/cloudformation.go#L1284-L1292 | train |
remind101/empire | scheduler/cloudformation/cloudformation.go | output | func output(stack *cloudformation.Stack, key string) (output *cloudformation.Output) {
for _, o := range stack.Outputs {
if *o.OutputKey == key {
output = o
}
}
return
} | go | func output(stack *cloudformation.Stack, key string) (output *cloudformation.Output) {
for _, o := range stack.Outputs {
if *o.OutputKey == key {
output = o
}
}
return
} | [
"func",
"output",
"(",
"stack",
"*",
"cloudformation",
".",
"Stack",
",",
"key",
"string",
")",
"(",
"output",
"*",
"cloudformation",
".",
"Output",
")",
"{",
"for",
"_",
",",
"o",
":=",
"range",
"stack",
".",
"Outputs",
"{",
"if",
"*",
"o",
".",
"... | // output returns the cloudformation.Output that matches the given key. | [
"output",
"returns",
"the",
"cloudformation",
".",
"Output",
"that",
"matches",
"the",
"given",
"key",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/cloudformation.go#L1310-L1317 | train |
remind101/empire | scheduler/cloudformation/cloudformation.go | deploymentsToWatch | func deploymentsToWatch(stack *cloudformation.Stack) (map[string]*ecsDeployment, error) {
deployments := output(stack, deploymentsOutput)
services := output(stack, servicesOutput)
if deployments == nil {
return nil, fmt.Errorf("deployments output missing from stack")
}
if services == nil {
return nil, fmt.Errorf("services output missing from stack")
}
arns := extractProcessData(*services.OutputValue)
deploymentIDs := extractProcessData(*deployments.OutputValue)
if len(arns) == 0 {
return nil, fmt.Errorf("no services found in output")
}
if len(deploymentIDs) == 0 {
return nil, fmt.Errorf("no deploymentIDs found in output")
}
ecsDeployments := make(map[string]*ecsDeployment)
for p, a := range arns {
deploymentID, ok := deploymentIDs[p]
if !ok {
return nil, fmt.Errorf("deployment id not found for process: %v", p)
}
ecsDeployments[a] = &ecsDeployment{
process: p,
ID: deploymentID,
}
}
return ecsDeployments, nil
} | go | func deploymentsToWatch(stack *cloudformation.Stack) (map[string]*ecsDeployment, error) {
deployments := output(stack, deploymentsOutput)
services := output(stack, servicesOutput)
if deployments == nil {
return nil, fmt.Errorf("deployments output missing from stack")
}
if services == nil {
return nil, fmt.Errorf("services output missing from stack")
}
arns := extractProcessData(*services.OutputValue)
deploymentIDs := extractProcessData(*deployments.OutputValue)
if len(arns) == 0 {
return nil, fmt.Errorf("no services found in output")
}
if len(deploymentIDs) == 0 {
return nil, fmt.Errorf("no deploymentIDs found in output")
}
ecsDeployments := make(map[string]*ecsDeployment)
for p, a := range arns {
deploymentID, ok := deploymentIDs[p]
if !ok {
return nil, fmt.Errorf("deployment id not found for process: %v", p)
}
ecsDeployments[a] = &ecsDeployment{
process: p,
ID: deploymentID,
}
}
return ecsDeployments, nil
} | [
"func",
"deploymentsToWatch",
"(",
"stack",
"*",
"cloudformation",
".",
"Stack",
")",
"(",
"map",
"[",
"string",
"]",
"*",
"ecsDeployment",
",",
"error",
")",
"{",
"deployments",
":=",
"output",
"(",
"stack",
",",
"deploymentsOutput",
")",
"\n",
"services",
... | // deploymentsToWatch returns an array of ecsDeployments for the given cloudformation stack | [
"deploymentsToWatch",
"returns",
"an",
"array",
"of",
"ecsDeployments",
"for",
"the",
"given",
"cloudformation",
"stack"
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/cloudformation.go#L1325-L1357 | train |
remind101/empire | server/cloudformation/queue.go | Start | func (q *SQSDispatcher) Start(handle func(context.Context, *sqs.Message) error) {
var wg sync.WaitGroup
for i := 0; i < q.NumWorkers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
q.start(handle)
}()
}
wg.Wait()
} | go | func (q *SQSDispatcher) Start(handle func(context.Context, *sqs.Message) error) {
var wg sync.WaitGroup
for i := 0; i < q.NumWorkers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
q.start(handle)
}()
}
wg.Wait()
} | [
"func",
"(",
"q",
"*",
"SQSDispatcher",
")",
"Start",
"(",
"handle",
"func",
"(",
"context",
".",
"Context",
",",
"*",
"sqs",
".",
"Message",
")",
"error",
")",
"{",
"var",
"wg",
"sync",
".",
"WaitGroup",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<... | // Start starts multiple goroutines pulling messages off of the queue. | [
"Start",
"starts",
"multiple",
"goroutines",
"pulling",
"messages",
"off",
"of",
"the",
"queue",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/server/cloudformation/queue.go#L65-L76 | train |
remind101/empire | server/cloudformation/queue.go | start | func (q *SQSDispatcher) start(handle func(context.Context, *sqs.Message) error) {
var wg sync.WaitGroup
for {
select {
case <-q.stopped:
wg.Wait()
return
default:
ctx := q.Context
resp, err := q.sqs.ReceiveMessage(&sqs.ReceiveMessageInput{
QueueUrl: aws.String(q.QueueURL),
WaitTimeSeconds: aws.Int64(defaultWaitTime),
})
if err != nil {
reporter.Report(ctx, err)
continue
}
for _, m := range resp.Messages {
wg.Add(1)
go func(m *sqs.Message) {
defer wg.Done()
if err := q.handle(ctx, handle, m); err != nil {
reporter.Report(ctx, err)
}
}(m)
}
}
}
} | go | func (q *SQSDispatcher) start(handle func(context.Context, *sqs.Message) error) {
var wg sync.WaitGroup
for {
select {
case <-q.stopped:
wg.Wait()
return
default:
ctx := q.Context
resp, err := q.sqs.ReceiveMessage(&sqs.ReceiveMessageInput{
QueueUrl: aws.String(q.QueueURL),
WaitTimeSeconds: aws.Int64(defaultWaitTime),
})
if err != nil {
reporter.Report(ctx, err)
continue
}
for _, m := range resp.Messages {
wg.Add(1)
go func(m *sqs.Message) {
defer wg.Done()
if err := q.handle(ctx, handle, m); err != nil {
reporter.Report(ctx, err)
}
}(m)
}
}
}
} | [
"func",
"(",
"q",
"*",
"SQSDispatcher",
")",
"start",
"(",
"handle",
"func",
"(",
"context",
".",
"Context",
",",
"*",
"sqs",
".",
"Message",
")",
"error",
")",
"{",
"var",
"wg",
"sync",
".",
"WaitGroup",
"\n",
"for",
"{",
"select",
"{",
"case",
"<... | // start starts a pulling messages off of the queue and passing them to the
// handler. | [
"start",
"starts",
"a",
"pulling",
"messages",
"off",
"of",
"the",
"queue",
"and",
"passing",
"them",
"to",
"the",
"handler",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/server/cloudformation/queue.go#L84-L114 | train |
remind101/empire | server/cloudformation/queue.go | extendMessageVisibilityTimeout | func (q *SQSDispatcher) extendMessageVisibilityTimeout(receiptHandle *string) (<-chan time.Time, error) {
visibilityTimeout := int64(float64(q.VisibilityHeartbeat) / float64(time.Second))
_, err := q.sqs.ChangeMessageVisibility(&sqs.ChangeMessageVisibilityInput{
QueueUrl: aws.String(q.QueueURL),
ReceiptHandle: receiptHandle,
VisibilityTimeout: aws.Int64(visibilityTimeout),
})
if err != nil {
return nil, err
}
return q.after(q.VisibilityHeartbeat / 2), nil
} | go | func (q *SQSDispatcher) extendMessageVisibilityTimeout(receiptHandle *string) (<-chan time.Time, error) {
visibilityTimeout := int64(float64(q.VisibilityHeartbeat) / float64(time.Second))
_, err := q.sqs.ChangeMessageVisibility(&sqs.ChangeMessageVisibilityInput{
QueueUrl: aws.String(q.QueueURL),
ReceiptHandle: receiptHandle,
VisibilityTimeout: aws.Int64(visibilityTimeout),
})
if err != nil {
return nil, err
}
return q.after(q.VisibilityHeartbeat / 2), nil
} | [
"func",
"(",
"q",
"*",
"SQSDispatcher",
")",
"extendMessageVisibilityTimeout",
"(",
"receiptHandle",
"*",
"string",
")",
"(",
"<-",
"chan",
"time",
".",
"Time",
",",
"error",
")",
"{",
"visibilityTimeout",
":=",
"int64",
"(",
"float64",
"(",
"q",
".",
"Vis... | // extendMessageVisibilityTimeout extends the messages visibility timeout by
// VisibilityHeartbeat, and returns a channel that will receive after half of
// VisibilityTimeout has elapsed. | [
"extendMessageVisibilityTimeout",
"extends",
"the",
"messages",
"visibility",
"timeout",
"by",
"VisibilityHeartbeat",
"and",
"returns",
"a",
"channel",
"that",
"will",
"receive",
"after",
"half",
"of",
"VisibilityTimeout",
"has",
"elapsed",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/server/cloudformation/queue.go#L155-L168 | train |
remind101/empire | pkg/heroku/app.go | AppCreate | func (c *Client) AppCreate(options *AppCreateOpts) (*App, error) {
var appRes App
return &appRes, c.Post(&appRes, "/apps", options)
} | go | func (c *Client) AppCreate(options *AppCreateOpts) (*App, error) {
var appRes App
return &appRes, c.Post(&appRes, "/apps", options)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"AppCreate",
"(",
"options",
"*",
"AppCreateOpts",
")",
"(",
"*",
"App",
",",
"error",
")",
"{",
"var",
"appRes",
"App",
"\n",
"return",
"&",
"appRes",
",",
"c",
".",
"Post",
"(",
"&",
"appRes",
",",
"\"/apps\"... | // Create a new app.
//
// options is the struct of optional parameters for this action. | [
"Create",
"a",
"new",
"app",
".",
"options",
"is",
"the",
"struct",
"of",
"optional",
"parameters",
"for",
"this",
"action",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/app.go#L78-L81 | train |
remind101/empire | pkg/heroku/app.go | AppInfo | func (c *Client) AppInfo(appIdentity string) (*App, error) {
var app App
return &app, c.Get(&app, "/apps/"+appIdentity)
} | go | func (c *Client) AppInfo(appIdentity string) (*App, error) {
var app App
return &app, c.Get(&app, "/apps/"+appIdentity)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"AppInfo",
"(",
"appIdentity",
"string",
")",
"(",
"*",
"App",
",",
"error",
")",
"{",
"var",
"app",
"App",
"\n",
"return",
"&",
"app",
",",
"c",
".",
"Get",
"(",
"&",
"app",
",",
"\"/apps/\"",
"+",
"appIdent... | // Info for existing app.
//
// appIdentity is the unique identifier of the App. | [
"Info",
"for",
"existing",
"app",
".",
"appIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"App",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/app.go#L104-L107 | train |
remind101/empire | pkg/heroku/app.go | AppList | func (c *Client) AppList(lr *ListRange) ([]App, error) {
req, err := c.NewRequest("GET", "/apps", nil, nil)
if err != nil {
return nil, err
}
if lr != nil {
lr.SetHeader(req)
}
var appsRes []App
return appsRes, c.DoReq(req, &appsRes)
} | go | func (c *Client) AppList(lr *ListRange) ([]App, error) {
req, err := c.NewRequest("GET", "/apps", nil, nil)
if err != nil {
return nil, err
}
if lr != nil {
lr.SetHeader(req)
}
var appsRes []App
return appsRes, c.DoReq(req, &appsRes)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"AppList",
"(",
"lr",
"*",
"ListRange",
")",
"(",
"[",
"]",
"App",
",",
"error",
")",
"{",
"req",
",",
"err",
":=",
"c",
".",
"NewRequest",
"(",
"\"GET\"",
",",
"\"/apps\"",
",",
"nil",
",",
"nil",
")",
"\n... | // List existing apps.
//
// lr is an optional ListRange that sets the Range options for the paginated
// list of results. | [
"List",
"existing",
"apps",
".",
"lr",
"is",
"an",
"optional",
"ListRange",
"that",
"sets",
"the",
"Range",
"options",
"for",
"the",
"paginated",
"list",
"of",
"results",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/app.go#L113-L125 | train |
remind101/empire | pkg/heroku/app.go | AppUpdate | func (c *Client) AppUpdate(appIdentity string, options *AppUpdateOpts, message string) (*App, error) {
rh := RequestHeaders{CommitMessage: message}
var appRes App
return &appRes, c.PatchWithHeaders(&appRes, "/apps/"+appIdentity, options, rh.Headers())
} | go | func (c *Client) AppUpdate(appIdentity string, options *AppUpdateOpts, message string) (*App, error) {
rh := RequestHeaders{CommitMessage: message}
var appRes App
return &appRes, c.PatchWithHeaders(&appRes, "/apps/"+appIdentity, options, rh.Headers())
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"AppUpdate",
"(",
"appIdentity",
"string",
",",
"options",
"*",
"AppUpdateOpts",
",",
"message",
"string",
")",
"(",
"*",
"App",
",",
"error",
")",
"{",
"rh",
":=",
"RequestHeaders",
"{",
"CommitMessage",
":",
"messa... | // Update an existing app.
//
// appIdentity is the unique identifier of the App. options is the struct of
// optional parameters for this action. | [
"Update",
"an",
"existing",
"app",
".",
"appIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"App",
".",
"options",
"is",
"the",
"struct",
"of",
"optional",
"parameters",
"for",
"this",
"action",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/app.go#L131-L135 | train |
remind101/empire | pkg/image/image.go | Decode | func Decode(in string) (image Image, err error) {
repo, tag := parseRepositoryTag(in)
image.Registry, image.Repository = splitRepository(repo)
if strings.Contains(tag, ":") {
image.Digest = tag
} else {
image.Tag = tag
}
if image.Repository == "" {
err = ErrInvalidImage
return
}
return
} | go | func Decode(in string) (image Image, err error) {
repo, tag := parseRepositoryTag(in)
image.Registry, image.Repository = splitRepository(repo)
if strings.Contains(tag, ":") {
image.Digest = tag
} else {
image.Tag = tag
}
if image.Repository == "" {
err = ErrInvalidImage
return
}
return
} | [
"func",
"Decode",
"(",
"in",
"string",
")",
"(",
"image",
"Image",
",",
"err",
"error",
")",
"{",
"repo",
",",
"tag",
":=",
"parseRepositoryTag",
"(",
"in",
")",
"\n",
"image",
".",
"Registry",
",",
"image",
".",
"Repository",
"=",
"splitRepository",
"... | // Decode decodes the string representation of an image into an Image structure. | [
"Decode",
"decodes",
"the",
"string",
"representation",
"of",
"an",
"image",
"into",
"an",
"Image",
"structure",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/image/image.go#L87-L103 | train |
remind101/empire | pkg/image/image.go | Encode | func Encode(image Image) string {
repo := image.Repository
if image.Registry != "" {
repo = fmt.Sprintf("%s/%s", image.Registry, repo)
}
if image.Digest != "" {
return fmt.Sprintf("%s@%s", repo, image.Digest)
} else if image.Tag != "" {
return fmt.Sprintf("%s:%s", repo, image.Tag)
}
return repo
} | go | func Encode(image Image) string {
repo := image.Repository
if image.Registry != "" {
repo = fmt.Sprintf("%s/%s", image.Registry, repo)
}
if image.Digest != "" {
return fmt.Sprintf("%s@%s", repo, image.Digest)
} else if image.Tag != "" {
return fmt.Sprintf("%s:%s", repo, image.Tag)
}
return repo
} | [
"func",
"Encode",
"(",
"image",
"Image",
")",
"string",
"{",
"repo",
":=",
"image",
".",
"Repository",
"\n",
"if",
"image",
".",
"Registry",
"!=",
"\"\"",
"{",
"repo",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"%s/%s\"",
",",
"image",
".",
"Registry",
",",
... | // Encode encodes an Image to it's string representation. | [
"Encode",
"encodes",
"an",
"Image",
"to",
"it",
"s",
"string",
"representation",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/image/image.go#L106-L119 | train |
remind101/empire | pkg/image/image.go | splitRepository | func splitRepository(fullRepo string) (registry string, path string) {
parts := strings.Split(fullRepo, "/")
if len(parts) < 2 {
return "", parts[0]
}
if len(parts) == 2 {
return "", strings.Join(parts, "/")
}
return parts[0], strings.Join(parts[1:], "/")
} | go | func splitRepository(fullRepo string) (registry string, path string) {
parts := strings.Split(fullRepo, "/")
if len(parts) < 2 {
return "", parts[0]
}
if len(parts) == 2 {
return "", strings.Join(parts, "/")
}
return parts[0], strings.Join(parts[1:], "/")
} | [
"func",
"splitRepository",
"(",
"fullRepo",
"string",
")",
"(",
"registry",
"string",
",",
"path",
"string",
")",
"{",
"parts",
":=",
"strings",
".",
"Split",
"(",
"fullRepo",
",",
"\"/\"",
")",
"\n",
"if",
"len",
"(",
"parts",
")",
"<",
"2",
"{",
"r... | // splitRepository splits a full docker repo into registry and path segments. | [
"splitRepository",
"splits",
"a",
"full",
"docker",
"repo",
"into",
"registry",
"and",
"path",
"segments",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/image/image.go#L122-L134 | train |
remind101/empire | deployments.go | createRelease | func (s *deployerService) createRelease(ctx context.Context, db *gorm.DB, ss twelvefactor.StatusStream, opts DeployOpts) (*Release, error) {
app, img := opts.App, opts.Image
// If no app is specified, attempt to find the app that relates to this
// images repository, or create it if not found.
if app == nil {
var err error
app, err = appsFindOrCreateByRepo(db, img.Repository)
if err != nil {
return nil, err
}
} else {
// If the app doesn't already have a repo attached to it, we'll attach
// this image's repo.
if err := appsEnsureRepo(db, app, img.Repository); err != nil {
return nil, err
}
}
// Grab the latest config.
config, err := s.configs.Config(db, app)
if err != nil {
return nil, err
}
// Create a new slug for the docker image.
slug, err := s.slugs.Create(ctx, db, img, opts.Output)
if err != nil {
return nil, err
}
// Create a new release for the Config
// and Slug.
desc := fmt.Sprintf("Deploy %s", img.String())
desc = appendMessageToDescription(desc, opts.User, opts.Message)
r, err := s.releases.Create(ctx, db, &Release{
App: app,
Config: config,
Slug: slug,
Description: desc,
})
return r, err
} | go | func (s *deployerService) createRelease(ctx context.Context, db *gorm.DB, ss twelvefactor.StatusStream, opts DeployOpts) (*Release, error) {
app, img := opts.App, opts.Image
// If no app is specified, attempt to find the app that relates to this
// images repository, or create it if not found.
if app == nil {
var err error
app, err = appsFindOrCreateByRepo(db, img.Repository)
if err != nil {
return nil, err
}
} else {
// If the app doesn't already have a repo attached to it, we'll attach
// this image's repo.
if err := appsEnsureRepo(db, app, img.Repository); err != nil {
return nil, err
}
}
// Grab the latest config.
config, err := s.configs.Config(db, app)
if err != nil {
return nil, err
}
// Create a new slug for the docker image.
slug, err := s.slugs.Create(ctx, db, img, opts.Output)
if err != nil {
return nil, err
}
// Create a new release for the Config
// and Slug.
desc := fmt.Sprintf("Deploy %s", img.String())
desc = appendMessageToDescription(desc, opts.User, opts.Message)
r, err := s.releases.Create(ctx, db, &Release{
App: app,
Config: config,
Slug: slug,
Description: desc,
})
return r, err
} | [
"func",
"(",
"s",
"*",
"deployerService",
")",
"createRelease",
"(",
"ctx",
"context",
".",
"Context",
",",
"db",
"*",
"gorm",
".",
"DB",
",",
"ss",
"twelvefactor",
".",
"StatusStream",
",",
"opts",
"DeployOpts",
")",
"(",
"*",
"Release",
",",
"error",
... | // createRelease creates a new release that can be deployed | [
"createRelease",
"creates",
"a",
"new",
"release",
"that",
"can",
"be",
"deployed"
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/deployments.go#L20-L63 | train |
remind101/empire | deployments.go | Deploy | func (s *deployerService) Deploy(ctx context.Context, opts DeployOpts) (*Release, error) {
w := opts.Output
var stream twelvefactor.StatusStream
if opts.Stream {
stream = w
}
r, err := s.createInTransaction(ctx, stream, opts)
if err != nil {
return r, w.Error(err)
}
if err := w.Status(fmt.Sprintf("Created new release v%d for %s", r.Version, r.App.Name)); err != nil {
return r, err
}
if err := s.releases.Release(ctx, r, stream); err != nil {
return r, w.Error(err)
}
return r, w.Status(fmt.Sprintf("Finished processing events for release v%d of %s", r.Version, r.App.Name))
} | go | func (s *deployerService) Deploy(ctx context.Context, opts DeployOpts) (*Release, error) {
w := opts.Output
var stream twelvefactor.StatusStream
if opts.Stream {
stream = w
}
r, err := s.createInTransaction(ctx, stream, opts)
if err != nil {
return r, w.Error(err)
}
if err := w.Status(fmt.Sprintf("Created new release v%d for %s", r.Version, r.App.Name)); err != nil {
return r, err
}
if err := s.releases.Release(ctx, r, stream); err != nil {
return r, w.Error(err)
}
return r, w.Status(fmt.Sprintf("Finished processing events for release v%d of %s", r.Version, r.App.Name))
} | [
"func",
"(",
"s",
"*",
"deployerService",
")",
"Deploy",
"(",
"ctx",
"context",
".",
"Context",
",",
"opts",
"DeployOpts",
")",
"(",
"*",
"Release",
",",
"error",
")",
"{",
"w",
":=",
"opts",
".",
"Output",
"\n",
"var",
"stream",
"twelvefactor",
".",
... | // Deploy is a thin wrapper around deploy to that adds the error to the
// jsonmessage stream. | [
"Deploy",
"is",
"a",
"thin",
"wrapper",
"around",
"deploy",
"to",
"that",
"adds",
"the",
"error",
"to",
"the",
"jsonmessage",
"stream",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/deployments.go#L77-L99 | train |
remind101/empire | deployments.go | Publish | func (w *DeploymentStream) Publish(status twelvefactor.Status) error {
return w.Status(status.Message)
} | go | func (w *DeploymentStream) Publish(status twelvefactor.Status) error {
return w.Status(status.Message)
} | [
"func",
"(",
"w",
"*",
"DeploymentStream",
")",
"Publish",
"(",
"status",
"twelvefactor",
".",
"Status",
")",
"error",
"{",
"return",
"w",
".",
"Status",
"(",
"status",
".",
"Message",
")",
"\n",
"}"
] | // Publish implements the scheduler.StatusStream interface. | [
"Publish",
"implements",
"the",
"scheduler",
".",
"StatusStream",
"interface",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/deployments.go#L113-L115 | train |
remind101/empire | deployments.go | Status | func (w *DeploymentStream) Status(message string) error {
m := jsonmessage.JSONMessage{Status: fmt.Sprintf("Status: %s", message)}
return w.Encode(m)
} | go | func (w *DeploymentStream) Status(message string) error {
m := jsonmessage.JSONMessage{Status: fmt.Sprintf("Status: %s", message)}
return w.Encode(m)
} | [
"func",
"(",
"w",
"*",
"DeploymentStream",
")",
"Status",
"(",
"message",
"string",
")",
"error",
"{",
"m",
":=",
"jsonmessage",
".",
"JSONMessage",
"{",
"Status",
":",
"fmt",
".",
"Sprintf",
"(",
"\"Status: %s\"",
",",
"message",
")",
"}",
"\n",
"return... | // Status writes a simple status update to the jsonmessage stream. | [
"Status",
"writes",
"a",
"simple",
"status",
"update",
"to",
"the",
"jsonmessage",
"stream",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/deployments.go#L118-L121 | train |
remind101/empire | pkg/heroku/oauth_authorization.go | OAuthAuthorizationCreate | func (c *Client) OAuthAuthorizationCreate(scope []string, options *OAuthAuthorizationCreateOpts) (*OAuthAuthorization, error) {
params := struct {
Scope []string `json:"scope"`
Client *string `json:"client,omitempty"`
Description *string `json:"description,omitempty"`
ExpiresIn *int `json:"expires_in,omitempty"`
}{
Scope: scope,
}
if options != nil {
params.Client = options.Client
params.Description = options.Description
params.ExpiresIn = options.ExpiresIn
}
var oauthAuthorizationRes OAuthAuthorization
return &oauthAuthorizationRes, c.Post(&oauthAuthorizationRes, "/oauth/authorizations", params)
} | go | func (c *Client) OAuthAuthorizationCreate(scope []string, options *OAuthAuthorizationCreateOpts) (*OAuthAuthorization, error) {
params := struct {
Scope []string `json:"scope"`
Client *string `json:"client,omitempty"`
Description *string `json:"description,omitempty"`
ExpiresIn *int `json:"expires_in,omitempty"`
}{
Scope: scope,
}
if options != nil {
params.Client = options.Client
params.Description = options.Description
params.ExpiresIn = options.ExpiresIn
}
var oauthAuthorizationRes OAuthAuthorization
return &oauthAuthorizationRes, c.Post(&oauthAuthorizationRes, "/oauth/authorizations", params)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"OAuthAuthorizationCreate",
"(",
"scope",
"[",
"]",
"string",
",",
"options",
"*",
"OAuthAuthorizationCreateOpts",
")",
"(",
"*",
"OAuthAuthorization",
",",
"error",
")",
"{",
"params",
":=",
"struct",
"{",
"Scope",
"[",... | // Create a new OAuth authorization.
//
// scope is the The scope of access OAuth authorization allows. options is the
// struct of optional parameters for this action. | [
"Create",
"a",
"new",
"OAuth",
"authorization",
".",
"scope",
"is",
"the",
"The",
"scope",
"of",
"access",
"OAuth",
"authorization",
"allows",
".",
"options",
"is",
"the",
"struct",
"of",
"optional",
"parameters",
"for",
"this",
"action",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/oauth_authorization.go#L60-L76 | train |
remind101/empire | pkg/heroku/oauth_authorization.go | OAuthAuthorizationInfo | func (c *Client) OAuthAuthorizationInfo(oauthAuthorizationIdentity string) (*OAuthAuthorization, error) {
var oauthAuthorization OAuthAuthorization
return &oauthAuthorization, c.Get(&oauthAuthorization, "/oauth/authorizations/"+oauthAuthorizationIdentity)
} | go | func (c *Client) OAuthAuthorizationInfo(oauthAuthorizationIdentity string) (*OAuthAuthorization, error) {
var oauthAuthorization OAuthAuthorization
return &oauthAuthorization, c.Get(&oauthAuthorization, "/oauth/authorizations/"+oauthAuthorizationIdentity)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"OAuthAuthorizationInfo",
"(",
"oauthAuthorizationIdentity",
"string",
")",
"(",
"*",
"OAuthAuthorization",
",",
"error",
")",
"{",
"var",
"oauthAuthorization",
"OAuthAuthorization",
"\n",
"return",
"&",
"oauthAuthorization",
",... | // Info for an OAuth authorization.
//
// oauthAuthorizationIdentity is the unique identifier of the
// OAuthAuthorization. | [
"Info",
"for",
"an",
"OAuth",
"authorization",
".",
"oauthAuthorizationIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"OAuthAuthorization",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/oauth_authorization.go#L100-L103 | train |
remind101/empire | pkg/heroku/oauth_authorization.go | OAuthAuthorizationList | func (c *Client) OAuthAuthorizationList(lr *ListRange) ([]OAuthAuthorization, error) {
req, err := c.NewRequest("GET", "/oauth/authorizations", nil, nil)
if err != nil {
return nil, err
}
if lr != nil {
lr.SetHeader(req)
}
var oauthAuthorizationsRes []OAuthAuthorization
return oauthAuthorizationsRes, c.DoReq(req, &oauthAuthorizationsRes)
} | go | func (c *Client) OAuthAuthorizationList(lr *ListRange) ([]OAuthAuthorization, error) {
req, err := c.NewRequest("GET", "/oauth/authorizations", nil, nil)
if err != nil {
return nil, err
}
if lr != nil {
lr.SetHeader(req)
}
var oauthAuthorizationsRes []OAuthAuthorization
return oauthAuthorizationsRes, c.DoReq(req, &oauthAuthorizationsRes)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"OAuthAuthorizationList",
"(",
"lr",
"*",
"ListRange",
")",
"(",
"[",
"]",
"OAuthAuthorization",
",",
"error",
")",
"{",
"req",
",",
"err",
":=",
"c",
".",
"NewRequest",
"(",
"\"GET\"",
",",
"\"/oauth/authorizations\""... | // List OAuth authorizations.
//
// lr is an optional ListRange that sets the Range options for the paginated
// list of results. | [
"List",
"OAuth",
"authorizations",
".",
"lr",
"is",
"an",
"optional",
"ListRange",
"that",
"sets",
"the",
"Range",
"options",
"for",
"the",
"paginated",
"list",
"of",
"results",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/oauth_authorization.go#L109-L121 | train |
remind101/empire | server/heroku/authentication.go | ExpiresIn | func (t *AccessToken) ExpiresIn() time.Duration {
if t.ExpiresAt == nil {
return 0
}
return t.ExpiresAt.Sub(time.Now())
} | go | func (t *AccessToken) ExpiresIn() time.Duration {
if t.ExpiresAt == nil {
return 0
}
return t.ExpiresAt.Sub(time.Now())
} | [
"func",
"(",
"t",
"*",
"AccessToken",
")",
"ExpiresIn",
"(",
")",
"time",
".",
"Duration",
"{",
"if",
"t",
".",
"ExpiresAt",
"==",
"nil",
"{",
"return",
"0",
"\n",
"}",
"\n",
"return",
"t",
".",
"ExpiresAt",
".",
"Sub",
"(",
"time",
".",
"Now",
"... | // Returns the amount of time before the token expires. | [
"Returns",
"the",
"amount",
"of",
"time",
"before",
"the",
"token",
"expires",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/server/heroku/authentication.go#L32-L38 | train |
remind101/empire | server/heroku/authentication.go | IsValid | func (t *AccessToken) IsValid() error {
if err := t.User.IsValid(); err != nil {
return err
}
return nil
} | go | func (t *AccessToken) IsValid() error {
if err := t.User.IsValid(); err != nil {
return err
}
return nil
} | [
"func",
"(",
"t",
"*",
"AccessToken",
")",
"IsValid",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"t",
".",
"User",
".",
"IsValid",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // IsValid returns nil if the AccessToken is valid. | [
"IsValid",
"returns",
"nil",
"if",
"the",
"AccessToken",
"is",
"valid",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/server/heroku/authentication.go#L41-L47 | train |
remind101/empire | server/heroku/authentication.go | Authenticate | func (a *accessTokenAuthenticator) Authenticate(_ string, token string, _ string) (*auth.Session, error) {
at, err := a.findAccessToken(token)
if err != nil {
return nil, err
}
if at == nil {
return nil, auth.ErrForbidden
}
session := &auth.Session{
User: at.User,
ExpiresAt: at.ExpiresAt,
}
return session, nil
} | go | func (a *accessTokenAuthenticator) Authenticate(_ string, token string, _ string) (*auth.Session, error) {
at, err := a.findAccessToken(token)
if err != nil {
return nil, err
}
if at == nil {
return nil, auth.ErrForbidden
}
session := &auth.Session{
User: at.User,
ExpiresAt: at.ExpiresAt,
}
return session, nil
} | [
"func",
"(",
"a",
"*",
"accessTokenAuthenticator",
")",
"Authenticate",
"(",
"_",
"string",
",",
"token",
"string",
",",
"_",
"string",
")",
"(",
"*",
"auth",
".",
"Session",
",",
"error",
")",
"{",
"at",
",",
"err",
":=",
"a",
".",
"findAccessToken",
... | // Authenticate authenticates the access token, which should be provided as the
// password parameter. Username and otp are ignored. | [
"Authenticate",
"authenticates",
"the",
"access",
"token",
"which",
"should",
"be",
"provided",
"as",
"the",
"password",
"parameter",
".",
"Username",
"and",
"otp",
"are",
"ignored",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/server/heroku/authentication.go#L143-L159 | train |
remind101/empire | server/heroku/authentication.go | AccessTokensCreate | func (s *Server) AccessTokensCreate(token *AccessToken) (*AccessToken, error) {
signed, err := signToken(s.Secret, token)
if err != nil {
return token, err
}
token.Token = signed
return token, token.IsValid()
} | go | func (s *Server) AccessTokensCreate(token *AccessToken) (*AccessToken, error) {
signed, err := signToken(s.Secret, token)
if err != nil {
return token, err
}
token.Token = signed
return token, token.IsValid()
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"AccessTokensCreate",
"(",
"token",
"*",
"AccessToken",
")",
"(",
"*",
"AccessToken",
",",
"error",
")",
"{",
"signed",
",",
"err",
":=",
"signToken",
"(",
"s",
".",
"Secret",
",",
"token",
")",
"\n",
"if",
"err"... | // AccessTokensCreate "creates" the token by jwt signing it and setting the
// Token value. | [
"AccessTokensCreate",
"creates",
"the",
"token",
"by",
"jwt",
"signing",
"it",
"and",
"setting",
"the",
"Token",
"value",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/server/heroku/authentication.go#L163-L172 | train |
remind101/empire | server/heroku/authentication.go | signToken | func signToken(secret []byte, token *AccessToken) (string, error) {
t := accessTokenToJwt(token)
return t.SignedString(secret)
} | go | func signToken(secret []byte, token *AccessToken) (string, error) {
t := accessTokenToJwt(token)
return t.SignedString(secret)
} | [
"func",
"signToken",
"(",
"secret",
"[",
"]",
"byte",
",",
"token",
"*",
"AccessToken",
")",
"(",
"string",
",",
"error",
")",
"{",
"t",
":=",
"accessTokenToJwt",
"(",
"token",
")",
"\n",
"return",
"t",
".",
"SignedString",
"(",
"secret",
")",
"\n",
... | // signToken jwt signs the token and adds the signature to the Token field. | [
"signToken",
"jwt",
"signs",
"the",
"token",
"and",
"adds",
"the",
"signature",
"to",
"the",
"Token",
"field",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/server/heroku/authentication.go#L193-L196 | train |
remind101/empire | server/heroku/authentication.go | parseToken | func parseToken(secret []byte, token string) (*AccessToken, error) {
t, err := jwtParse(secret, token)
if err != nil {
return nil, err
}
if !t.Valid {
return nil, nil
}
return jwtToAccessToken(t)
} | go | func parseToken(secret []byte, token string) (*AccessToken, error) {
t, err := jwtParse(secret, token)
if err != nil {
return nil, err
}
if !t.Valid {
return nil, nil
}
return jwtToAccessToken(t)
} | [
"func",
"parseToken",
"(",
"secret",
"[",
"]",
"byte",
",",
"token",
"string",
")",
"(",
"*",
"AccessToken",
",",
"error",
")",
"{",
"t",
",",
"err",
":=",
"jwtParse",
"(",
"secret",
",",
"token",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",... | // parseToken parses a string token, verifies it, and returns an AccessToken
// instance. | [
"parseToken",
"parses",
"a",
"string",
"token",
"verifies",
"it",
"and",
"returns",
"an",
"AccessToken",
"instance",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/server/heroku/authentication.go#L200-L212 | train |
remind101/empire | server/heroku/authentication.go | jwtToAccessToken | func jwtToAccessToken(t *jwt.Token) (*AccessToken, error) {
var token AccessToken
if t.Claims["exp"] != nil {
exp := time.Unix(int64(t.Claims["exp"].(float64)), 0).UTC()
token.ExpiresAt = &exp
}
if u, ok := t.Claims["User"].(map[string]interface{}); ok {
var user empire.User
if n, ok := u["Name"].(string); ok {
user.Name = n
} else {
return &token, errors.New("missing name")
}
if gt, ok := u["GitHubToken"].(string); ok {
user.GitHubToken = gt
} else {
return &token, errors.New("missing github token")
}
token.User = &user
} else {
return &token, errors.New("missing user")
}
return &token, nil
} | go | func jwtToAccessToken(t *jwt.Token) (*AccessToken, error) {
var token AccessToken
if t.Claims["exp"] != nil {
exp := time.Unix(int64(t.Claims["exp"].(float64)), 0).UTC()
token.ExpiresAt = &exp
}
if u, ok := t.Claims["User"].(map[string]interface{}); ok {
var user empire.User
if n, ok := u["Name"].(string); ok {
user.Name = n
} else {
return &token, errors.New("missing name")
}
if gt, ok := u["GitHubToken"].(string); ok {
user.GitHubToken = gt
} else {
return &token, errors.New("missing github token")
}
token.User = &user
} else {
return &token, errors.New("missing user")
}
return &token, nil
} | [
"func",
"jwtToAccessToken",
"(",
"t",
"*",
"jwt",
".",
"Token",
")",
"(",
"*",
"AccessToken",
",",
"error",
")",
"{",
"var",
"token",
"AccessToken",
"\n",
"if",
"t",
".",
"Claims",
"[",
"\"exp\"",
"]",
"!=",
"nil",
"{",
"exp",
":=",
"time",
".",
"U... | // jwtToAccessTokens maps a jwt.Token to an AccessToken. | [
"jwtToAccessTokens",
"maps",
"a",
"jwt",
".",
"Token",
"to",
"an",
"AccessToken",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/server/heroku/authentication.go#L231-L260 | train |
remind101/empire | pkg/heroku/domain.go | DomainCreate | func (c *Client) DomainCreate(appIdentity string, hostname string) (*Domain, error) {
params := struct {
Hostname string `json:"hostname"`
}{
Hostname: hostname,
}
var domainRes Domain
return &domainRes, c.Post(&domainRes, "/apps/"+appIdentity+"/domains", params)
} | go | func (c *Client) DomainCreate(appIdentity string, hostname string) (*Domain, error) {
params := struct {
Hostname string `json:"hostname"`
}{
Hostname: hostname,
}
var domainRes Domain
return &domainRes, c.Post(&domainRes, "/apps/"+appIdentity+"/domains", params)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"DomainCreate",
"(",
"appIdentity",
"string",
",",
"hostname",
"string",
")",
"(",
"*",
"Domain",
",",
"error",
")",
"{",
"params",
":=",
"struct",
"{",
"Hostname",
"string",
"`json:\"hostname\"`",
"\n",
"}",
"{",
"H... | // Create a new domain.
//
// appIdentity is the unique identifier of the Domain's App. hostname is the
// full hostname. | [
"Create",
"a",
"new",
"domain",
".",
"appIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"Domain",
"s",
"App",
".",
"hostname",
"is",
"the",
"full",
"hostname",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/domain.go#L30-L38 | train |
remind101/empire | pkg/heroku/domain.go | DomainDelete | func (c *Client) DomainDelete(appIdentity string, domainIdentity string) error {
return c.Delete("/apps/" + appIdentity + "/domains/" + domainIdentity)
} | go | func (c *Client) DomainDelete(appIdentity string, domainIdentity string) error {
return c.Delete("/apps/" + appIdentity + "/domains/" + domainIdentity)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"DomainDelete",
"(",
"appIdentity",
"string",
",",
"domainIdentity",
"string",
")",
"error",
"{",
"return",
"c",
".",
"Delete",
"(",
"\"/apps/\"",
"+",
"appIdentity",
"+",
"\"/domains/\"",
"+",
"domainIdentity",
")",
"\n... | // Delete an existing domain
//
// appIdentity is the unique identifier of the Domain's App. domainIdentity is
// the unique identifier of the Domain. | [
"Delete",
"an",
"existing",
"domain",
"appIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"Domain",
"s",
"App",
".",
"domainIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"Domain",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/domain.go#L44-L46 | train |
remind101/empire | pkg/heroku/domain.go | DomainInfo | func (c *Client) DomainInfo(appIdentity string, domainIdentity string) (*Domain, error) {
var domain Domain
return &domain, c.Get(&domain, "/apps/"+appIdentity+"/domains/"+domainIdentity)
} | go | func (c *Client) DomainInfo(appIdentity string, domainIdentity string) (*Domain, error) {
var domain Domain
return &domain, c.Get(&domain, "/apps/"+appIdentity+"/domains/"+domainIdentity)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"DomainInfo",
"(",
"appIdentity",
"string",
",",
"domainIdentity",
"string",
")",
"(",
"*",
"Domain",
",",
"error",
")",
"{",
"var",
"domain",
"Domain",
"\n",
"return",
"&",
"domain",
",",
"c",
".",
"Get",
"(",
"... | // Info for existing domain.
//
// appIdentity is the unique identifier of the Domain's App. domainIdentity is
// the unique identifier of the Domain. | [
"Info",
"for",
"existing",
"domain",
".",
"appIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"Domain",
"s",
"App",
".",
"domainIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"Domain",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/domain.go#L52-L55 | train |
remind101/empire | pkg/heroku/domain.go | DomainList | func (c *Client) DomainList(appIdentity string, lr *ListRange) ([]Domain, error) {
req, err := c.NewRequest("GET", "/apps/"+appIdentity+"/domains", nil, nil)
if err != nil {
return nil, err
}
if lr != nil {
lr.SetHeader(req)
}
var domainsRes []Domain
return domainsRes, c.DoReq(req, &domainsRes)
} | go | func (c *Client) DomainList(appIdentity string, lr *ListRange) ([]Domain, error) {
req, err := c.NewRequest("GET", "/apps/"+appIdentity+"/domains", nil, nil)
if err != nil {
return nil, err
}
if lr != nil {
lr.SetHeader(req)
}
var domainsRes []Domain
return domainsRes, c.DoReq(req, &domainsRes)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"DomainList",
"(",
"appIdentity",
"string",
",",
"lr",
"*",
"ListRange",
")",
"(",
"[",
"]",
"Domain",
",",
"error",
")",
"{",
"req",
",",
"err",
":=",
"c",
".",
"NewRequest",
"(",
"\"GET\"",
",",
"\"/apps/\"",
... | // List existing domains.
//
// appIdentity is the unique identifier of the Domain's App. lr is an optional
// ListRange that sets the Range options for the paginated list of results. | [
"List",
"existing",
"domains",
".",
"appIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"Domain",
"s",
"App",
".",
"lr",
"is",
"an",
"optional",
"ListRange",
"that",
"sets",
"the",
"Range",
"options",
"for",
"the",
"paginated",
"list",
"of",
"... | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/domain.go#L61-L73 | train |
remind101/empire | pkg/stream/http/http.go | StreamingResponseWriter | func StreamingResponseWriter(w http.ResponseWriter) *ResponseWriter {
fw, err := newFlushWriter(w)
if err != nil {
panic(err)
}
return &ResponseWriter{
ResponseWriter: w,
w: fw,
}
} | go | func StreamingResponseWriter(w http.ResponseWriter) *ResponseWriter {
fw, err := newFlushWriter(w)
if err != nil {
panic(err)
}
return &ResponseWriter{
ResponseWriter: w,
w: fw,
}
} | [
"func",
"StreamingResponseWriter",
"(",
"w",
"http",
".",
"ResponseWriter",
")",
"*",
"ResponseWriter",
"{",
"fw",
",",
"err",
":=",
"newFlushWriter",
"(",
"w",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"retur... | // StreamingResponseWriter wraps the http.ResponseWriter with unbuffered
// streaming. If the provided ResponseWriter does not implement http.Flusher,
// this function will panic. | [
"StreamingResponseWriter",
"wraps",
"the",
"http",
".",
"ResponseWriter",
"with",
"unbuffered",
"streaming",
".",
"If",
"the",
"provided",
"ResponseWriter",
"does",
"not",
"implement",
"http",
".",
"Flusher",
"this",
"function",
"will",
"panic",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/stream/http/http.go#L23-L33 | train |
remind101/empire | pkg/stream/http/http.go | Write | func (w *ResponseWriter) Write(p []byte) (int, error) {
return w.w.Write(p)
} | go | func (w *ResponseWriter) Write(p []byte) (int, error) {
return w.w.Write(p)
} | [
"func",
"(",
"w",
"*",
"ResponseWriter",
")",
"Write",
"(",
"p",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"return",
"w",
".",
"w",
".",
"Write",
"(",
"p",
")",
"\n",
"}"
] | // Write delegates to the underlying flushWriter to perform the write and flush
// it to the connection. | [
"Write",
"delegates",
"to",
"the",
"underlying",
"flushWriter",
"to",
"perform",
"the",
"write",
"and",
"flush",
"it",
"to",
"the",
"connection",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/stream/http/http.go#L37-L39 | train |
remind101/empire | pkg/stream/http/http.go | Heartbeat | func Heartbeat(outStream io.Writer, interval time.Duration) chan struct{} {
stop := make(chan struct{})
t := time.NewTicker(interval)
go func() {
for {
select {
case <-t.C:
fmt.Fprintf(outStream, "\x00")
continue
case <-stop:
t.Stop()
return
}
}
}()
return stop
} | go | func Heartbeat(outStream io.Writer, interval time.Duration) chan struct{} {
stop := make(chan struct{})
t := time.NewTicker(interval)
go func() {
for {
select {
case <-t.C:
fmt.Fprintf(outStream, "\x00")
continue
case <-stop:
t.Stop()
return
}
}
}()
return stop
} | [
"func",
"Heartbeat",
"(",
"outStream",
"io",
".",
"Writer",
",",
"interval",
"time",
".",
"Duration",
")",
"chan",
"struct",
"{",
"}",
"{",
"stop",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"t",
":=",
"time",
".",
"NewTicker",
"(",
... | // Heartbeat sends the null character periodically, to keep the connection alive. | [
"Heartbeat",
"sends",
"the",
"null",
"character",
"periodically",
"to",
"keep",
"the",
"connection",
"alive",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/stream/http/http.go#L67-L85 | train |
remind101/empire | scheduler/cloudformation/template.go | taskDefinitionResourceType | func taskDefinitionResourceType(app *twelvefactor.Manifest) string {
check := []string{
"EMPIRE_X_TASK_DEFINITION_TYPE",
"ECS_TASK_DEFINITION", // For backwards compatibility.
}
for _, n := range check {
if v, ok := app.Env[n]; ok {
if v == "custom" {
return "Custom::ECSTaskDefinition"
}
}
}
// Default when not set.
return "AWS::ECS::TaskDefinition"
} | go | func taskDefinitionResourceType(app *twelvefactor.Manifest) string {
check := []string{
"EMPIRE_X_TASK_DEFINITION_TYPE",
"ECS_TASK_DEFINITION", // For backwards compatibility.
}
for _, n := range check {
if v, ok := app.Env[n]; ok {
if v == "custom" {
return "Custom::ECSTaskDefinition"
}
}
}
// Default when not set.
return "AWS::ECS::TaskDefinition"
} | [
"func",
"taskDefinitionResourceType",
"(",
"app",
"*",
"twelvefactor",
".",
"Manifest",
")",
"string",
"{",
"check",
":=",
"[",
"]",
"string",
"{",
"\"EMPIRE_X_TASK_DEFINITION_TYPE\"",
",",
"\"ECS_TASK_DEFINITION\"",
",",
"}",
"\n",
"for",
"_",
",",
"n",
":=",
... | // Returns the name of the CloudFormation resource that should be used to create
// custom task definitions. | [
"Returns",
"the",
"name",
"of",
"the",
"CloudFormation",
"resource",
"that",
"should",
"be",
"used",
"to",
"create",
"custom",
"task",
"definitions",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/template.go#L59-L75 | train |
remind101/empire | scheduler/cloudformation/template.go | Validate | func (t *EmpireTemplate) Validate() error {
r := func(n string) error {
return errors.New(fmt.Sprintf("%s is required", n))
}
if t.VpcId == "" {
return r("VpcId")
}
if t.Cluster == "" {
return r("Cluster")
}
if t.ServiceRole == "" {
return r("ServiceRole")
}
if t.HostedZone == nil {
return r("HostedZone")
}
if t.InternalSecurityGroupID == "" {
return r("InternalSecurityGroupID")
}
if t.ExternalSecurityGroupID == "" {
return r("ExternalSecurityGroupID")
}
if len(t.InternalSubnetIDs) == 0 {
return r("InternalSubnetIDs")
}
if len(t.ExternalSubnetIDs) == 0 {
return r("ExternalSubnetIDs")
}
if t.CustomResourcesTopic == "" {
return r("CustomResourcesTopic")
}
return nil
} | go | func (t *EmpireTemplate) Validate() error {
r := func(n string) error {
return errors.New(fmt.Sprintf("%s is required", n))
}
if t.VpcId == "" {
return r("VpcId")
}
if t.Cluster == "" {
return r("Cluster")
}
if t.ServiceRole == "" {
return r("ServiceRole")
}
if t.HostedZone == nil {
return r("HostedZone")
}
if t.InternalSecurityGroupID == "" {
return r("InternalSecurityGroupID")
}
if t.ExternalSecurityGroupID == "" {
return r("ExternalSecurityGroupID")
}
if len(t.InternalSubnetIDs) == 0 {
return r("InternalSubnetIDs")
}
if len(t.ExternalSubnetIDs) == 0 {
return r("ExternalSubnetIDs")
}
if t.CustomResourcesTopic == "" {
return r("CustomResourcesTopic")
}
return nil
} | [
"func",
"(",
"t",
"*",
"EmpireTemplate",
")",
"Validate",
"(",
")",
"error",
"{",
"r",
":=",
"func",
"(",
"n",
"string",
")",
"error",
"{",
"return",
"errors",
".",
"New",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"%s is required\"",
",",
"n",
")",
")",
"... | // Validate checks that all of the expected values are provided. | [
"Validate",
"checks",
"that",
"all",
"of",
"the",
"expected",
"values",
"are",
"provided",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/template.go#L150-L184 | train |
remind101/empire | scheduler/cloudformation/template.go | Execute | func (t *EmpireTemplate) Execute(w io.Writer, data interface{}) error {
v, err := t.Build(data.(*TemplateData))
if err != nil {
return err
}
if t.NoCompress {
raw, err := json.MarshalIndent(v, "", " ")
if err != nil {
return err
}
_, err = io.Copy(w, bytes.NewReader(raw))
return err
}
return json.NewEncoder(w).Encode(v)
} | go | func (t *EmpireTemplate) Execute(w io.Writer, data interface{}) error {
v, err := t.Build(data.(*TemplateData))
if err != nil {
return err
}
if t.NoCompress {
raw, err := json.MarshalIndent(v, "", " ")
if err != nil {
return err
}
_, err = io.Copy(w, bytes.NewReader(raw))
return err
}
return json.NewEncoder(w).Encode(v)
} | [
"func",
"(",
"t",
"*",
"EmpireTemplate",
")",
"Execute",
"(",
"w",
"io",
".",
"Writer",
",",
"data",
"interface",
"{",
"}",
")",
"error",
"{",
"v",
",",
"err",
":=",
"t",
".",
"Build",
"(",
"data",
".",
"(",
"*",
"TemplateData",
")",
")",
"\n",
... | // Execute builds the template, and writes it to w. | [
"Execute",
"builds",
"the",
"template",
"and",
"writes",
"it",
"to",
"w",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/template.go#L187-L204 | train |
remind101/empire | scheduler/cloudformation/template.go | Build | func (t *EmpireTemplate) Build(data *TemplateData) (*troposphere.Template, error) {
app := data.Manifest
tmpl := troposphere.NewTemplate()
tmpl.Parameters["DNS"] = troposphere.Parameter{
Type: "String",
Description: "When set to `true`, CNAME's will be altered",
Default: "true",
}
tmpl.Parameters[restartParameter] = troposphere.Parameter{
Type: "String",
Description: "Key used to trigger a restart of an app",
Default: "default",
}
tmpl.Conditions["DNSCondition"] = Equals(Ref("DNS"), "true")
for k, v := range t.ExtraOutputs {
tmpl.Outputs[k] = v
}
tmpl.Outputs["Release"] = troposphere.Output{Value: app.Release}
serviceMappings := []interface{}{}
deploymentMappings := []interface{}{}
scheduledProcesses := map[string]string{}
if taskDefinitionResourceType(app) == "Custom::ECSTaskDefinition" {
tmpl.Resources[appEnvironment] = troposphere.Resource{
Type: "Custom::ECSEnvironment",
Properties: map[string]interface{}{
"ServiceToken": t.CustomResourcesTopic,
"Environment": sortedEnvironment(app.Env),
},
}
}
for _, p := range app.Processes {
if p.Env == nil {
p.Env = make(map[string]string)
}
tmpl.Parameters[scaleParameter(p.Type)] = troposphere.Parameter{
Type: "String",
}
switch {
case p.Schedule != nil:
taskDefinition := t.addScheduledTask(tmpl, app, p)
scheduledProcesses[p.Type] = taskDefinition.Name
default:
service, err := t.addService(tmpl, app, p, data.StackTags)
if err != nil {
return tmpl, err
}
serviceMappings = append(serviceMappings, Join("=", p.Type, Ref(service)))
deploymentMappings = append(deploymentMappings, Join("=", p.Type, GetAtt(service, "DeploymentId")))
}
}
if len(scheduledProcesses) > 0 {
// LambdaFunction that will be used to trigger a RunTask.
tmpl.Resources[runTaskFunction] = runTaskResource(t.serviceRoleArn())
}
tmpl.Outputs[servicesOutput] = troposphere.Output{Value: Join(",", serviceMappings...)}
tmpl.Outputs[deploymentsOutput] = troposphere.Output{Value: Join(",", deploymentMappings...)}
return tmpl, nil
} | go | func (t *EmpireTemplate) Build(data *TemplateData) (*troposphere.Template, error) {
app := data.Manifest
tmpl := troposphere.NewTemplate()
tmpl.Parameters["DNS"] = troposphere.Parameter{
Type: "String",
Description: "When set to `true`, CNAME's will be altered",
Default: "true",
}
tmpl.Parameters[restartParameter] = troposphere.Parameter{
Type: "String",
Description: "Key used to trigger a restart of an app",
Default: "default",
}
tmpl.Conditions["DNSCondition"] = Equals(Ref("DNS"), "true")
for k, v := range t.ExtraOutputs {
tmpl.Outputs[k] = v
}
tmpl.Outputs["Release"] = troposphere.Output{Value: app.Release}
serviceMappings := []interface{}{}
deploymentMappings := []interface{}{}
scheduledProcesses := map[string]string{}
if taskDefinitionResourceType(app) == "Custom::ECSTaskDefinition" {
tmpl.Resources[appEnvironment] = troposphere.Resource{
Type: "Custom::ECSEnvironment",
Properties: map[string]interface{}{
"ServiceToken": t.CustomResourcesTopic,
"Environment": sortedEnvironment(app.Env),
},
}
}
for _, p := range app.Processes {
if p.Env == nil {
p.Env = make(map[string]string)
}
tmpl.Parameters[scaleParameter(p.Type)] = troposphere.Parameter{
Type: "String",
}
switch {
case p.Schedule != nil:
taskDefinition := t.addScheduledTask(tmpl, app, p)
scheduledProcesses[p.Type] = taskDefinition.Name
default:
service, err := t.addService(tmpl, app, p, data.StackTags)
if err != nil {
return tmpl, err
}
serviceMappings = append(serviceMappings, Join("=", p.Type, Ref(service)))
deploymentMappings = append(deploymentMappings, Join("=", p.Type, GetAtt(service, "DeploymentId")))
}
}
if len(scheduledProcesses) > 0 {
// LambdaFunction that will be used to trigger a RunTask.
tmpl.Resources[runTaskFunction] = runTaskResource(t.serviceRoleArn())
}
tmpl.Outputs[servicesOutput] = troposphere.Output{Value: Join(",", serviceMappings...)}
tmpl.Outputs[deploymentsOutput] = troposphere.Output{Value: Join(",", deploymentMappings...)}
return tmpl, nil
} | [
"func",
"(",
"t",
"*",
"EmpireTemplate",
")",
"Build",
"(",
"data",
"*",
"TemplateData",
")",
"(",
"*",
"troposphere",
".",
"Template",
",",
"error",
")",
"{",
"app",
":=",
"data",
".",
"Manifest",
"\n",
"tmpl",
":=",
"troposphere",
".",
"NewTemplate",
... | // Build builds a Go representation of a CloudFormation template for the app. | [
"Build",
"builds",
"a",
"Go",
"representation",
"of",
"a",
"CloudFormation",
"template",
"for",
"the",
"app",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/template.go#L207-L276 | train |
remind101/empire | scheduler/cloudformation/template.go | serviceRoleArn | func (t *EmpireTemplate) serviceRoleArn() interface{} {
if _, err := arn.Parse(t.ServiceRole); err == nil {
return t.ServiceRole
}
return Join("", "arn:aws:iam::", Ref("AWS::AccountId"), ":role/", t.ServiceRole)
} | go | func (t *EmpireTemplate) serviceRoleArn() interface{} {
if _, err := arn.Parse(t.ServiceRole); err == nil {
return t.ServiceRole
}
return Join("", "arn:aws:iam::", Ref("AWS::AccountId"), ":role/", t.ServiceRole)
} | [
"func",
"(",
"t",
"*",
"EmpireTemplate",
")",
"serviceRoleArn",
"(",
")",
"interface",
"{",
"}",
"{",
"if",
"_",
",",
"err",
":=",
"arn",
".",
"Parse",
"(",
"t",
".",
"ServiceRole",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"t",
".",
"ServiceRol... | // If the ServiceRole option is not an ARN, it will return a CloudFormation
// expression that expands the ServiceRole to an ARN. | [
"If",
"the",
"ServiceRole",
"option",
"is",
"not",
"an",
"ARN",
"it",
"will",
"return",
"a",
"CloudFormation",
"expression",
"that",
"expands",
"the",
"ServiceRole",
"to",
"an",
"ARN",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/template.go#L738-L743 | train |
remind101/empire | scheduler/cloudformation/template.go | ContainerDefinition | func (t *EmpireTemplate) ContainerDefinition(app *twelvefactor.Manifest, p *twelvefactor.Process) *ecs.ContainerDefinition {
command := []*string{}
for _, s := range p.Command {
ss := s
command = append(command, &ss)
}
labels := make(map[string]*string)
for k, v := range twelvefactor.Labels(app, p) {
labels[k] = aws.String(v)
}
ulimits := []*ecs.Ulimit{}
if p.Nproc != 0 {
ulimits = []*ecs.Ulimit{
&ecs.Ulimit{
Name: aws.String("nproc"),
SoftLimit: aws.Int64(int64(p.Nproc)),
HardLimit: aws.Int64(int64(p.Nproc)),
},
}
}
return &ecs.ContainerDefinition{
Name: aws.String(p.Type),
Cpu: aws.Int64(int64(p.CPUShares)),
Command: command,
Image: aws.String(p.Image.String()),
Essential: aws.Bool(true),
Memory: aws.Int64(int64(p.Memory / bytesize.MB)),
Environment: sortedEnvironment(twelvefactor.Env(app, p)),
LogConfiguration: t.LogConfiguration,
DockerLabels: labels,
Ulimits: ulimits,
}
} | go | func (t *EmpireTemplate) ContainerDefinition(app *twelvefactor.Manifest, p *twelvefactor.Process) *ecs.ContainerDefinition {
command := []*string{}
for _, s := range p.Command {
ss := s
command = append(command, &ss)
}
labels := make(map[string]*string)
for k, v := range twelvefactor.Labels(app, p) {
labels[k] = aws.String(v)
}
ulimits := []*ecs.Ulimit{}
if p.Nproc != 0 {
ulimits = []*ecs.Ulimit{
&ecs.Ulimit{
Name: aws.String("nproc"),
SoftLimit: aws.Int64(int64(p.Nproc)),
HardLimit: aws.Int64(int64(p.Nproc)),
},
}
}
return &ecs.ContainerDefinition{
Name: aws.String(p.Type),
Cpu: aws.Int64(int64(p.CPUShares)),
Command: command,
Image: aws.String(p.Image.String()),
Essential: aws.Bool(true),
Memory: aws.Int64(int64(p.Memory / bytesize.MB)),
Environment: sortedEnvironment(twelvefactor.Env(app, p)),
LogConfiguration: t.LogConfiguration,
DockerLabels: labels,
Ulimits: ulimits,
}
} | [
"func",
"(",
"t",
"*",
"EmpireTemplate",
")",
"ContainerDefinition",
"(",
"app",
"*",
"twelvefactor",
".",
"Manifest",
",",
"p",
"*",
"twelvefactor",
".",
"Process",
")",
"*",
"ecs",
".",
"ContainerDefinition",
"{",
"command",
":=",
"[",
"]",
"*",
"string"... | // ContainerDefinition generates an ECS ContainerDefinition for a process. | [
"ContainerDefinition",
"generates",
"an",
"ECS",
"ContainerDefinition",
"for",
"a",
"process",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/template.go#L754-L789 | train |
remind101/empire | scheduler/cloudformation/template.go | HostedZone | func HostedZone(config client.ConfigProvider, hostedZoneID string) (*route53.HostedZone, error) {
r := route53.New(config)
zid := fixHostedZoneIDPrefix(hostedZoneID)
out, err := r.GetHostedZone(&route53.GetHostedZoneInput{Id: zid})
if err != nil {
return nil, err
}
return out.HostedZone, nil
} | go | func HostedZone(config client.ConfigProvider, hostedZoneID string) (*route53.HostedZone, error) {
r := route53.New(config)
zid := fixHostedZoneIDPrefix(hostedZoneID)
out, err := r.GetHostedZone(&route53.GetHostedZoneInput{Id: zid})
if err != nil {
return nil, err
}
return out.HostedZone, nil
} | [
"func",
"HostedZone",
"(",
"config",
"client",
".",
"ConfigProvider",
",",
"hostedZoneID",
"string",
")",
"(",
"*",
"route53",
".",
"HostedZone",
",",
"error",
")",
"{",
"r",
":=",
"route53",
".",
"New",
"(",
"config",
")",
"\n",
"zid",
":=",
"fixHostedZ... | // HostedZone returns the HostedZone for the ZoneID. | [
"HostedZone",
"returns",
"the",
"HostedZone",
"for",
"the",
"ZoneID",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/template.go#L792-L801 | train |
remind101/empire | scheduler/cloudformation/template.go | cloudformationContainerDefinition | func cloudformationContainerDefinition(cd *ecs.ContainerDefinition) *ContainerDefinitionProperties {
labels := make(map[string]interface{})
for k, v := range cd.DockerLabels {
labels[k] = *v
}
c := &ContainerDefinitionProperties{
Name: *cd.Name,
Command: cd.Command,
Cpu: *cd.Cpu,
Image: *cd.Image,
Essential: *cd.Essential,
Memory: *cd.Memory,
Environment: cd.Environment,
DockerLabels: labels,
Ulimits: cd.Ulimits,
}
if cd.LogConfiguration != nil {
c.LogConfiguration = cd.LogConfiguration
}
return c
} | go | func cloudformationContainerDefinition(cd *ecs.ContainerDefinition) *ContainerDefinitionProperties {
labels := make(map[string]interface{})
for k, v := range cd.DockerLabels {
labels[k] = *v
}
c := &ContainerDefinitionProperties{
Name: *cd.Name,
Command: cd.Command,
Cpu: *cd.Cpu,
Image: *cd.Image,
Essential: *cd.Essential,
Memory: *cd.Memory,
Environment: cd.Environment,
DockerLabels: labels,
Ulimits: cd.Ulimits,
}
if cd.LogConfiguration != nil {
c.LogConfiguration = cd.LogConfiguration
}
return c
} | [
"func",
"cloudformationContainerDefinition",
"(",
"cd",
"*",
"ecs",
".",
"ContainerDefinition",
")",
"*",
"ContainerDefinitionProperties",
"{",
"labels",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"for",
"k",
",",
"v",
":... | // cloudformationContainerDefinition returns the CloudFormation representation
// of a ecs.ContainerDefinition. | [
"cloudformationContainerDefinition",
"returns",
"the",
"CloudFormation",
"representation",
"of",
"a",
"ecs",
".",
"ContainerDefinition",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/template.go#L830-L851 | train |
remind101/empire | scheduler/cloudformation/template.go | runTaskResource | func runTaskResource(role interface{}) troposphere.Resource {
return troposphere.Resource{
Type: "AWS::Lambda::Function",
Properties: map[string]interface{}{
"Description": fmt.Sprintf("Lambda function to run an ECS task"),
"Handler": "index.handler",
"Role": role,
"Runtime": "python2.7",
"Code": map[string]interface{}{
"ZipFile": runTaskCode,
},
},
}
} | go | func runTaskResource(role interface{}) troposphere.Resource {
return troposphere.Resource{
Type: "AWS::Lambda::Function",
Properties: map[string]interface{}{
"Description": fmt.Sprintf("Lambda function to run an ECS task"),
"Handler": "index.handler",
"Role": role,
"Runtime": "python2.7",
"Code": map[string]interface{}{
"ZipFile": runTaskCode,
},
},
}
} | [
"func",
"runTaskResource",
"(",
"role",
"interface",
"{",
"}",
")",
"troposphere",
".",
"Resource",
"{",
"return",
"troposphere",
".",
"Resource",
"{",
"Type",
":",
"\"AWS::Lambda::Function\"",
",",
"Properties",
":",
"map",
"[",
"string",
"]",
"interface",
"{... | // runTaskResource returns a troposphere resource that will create a lambda
// function that can be used to run an ECS task. | [
"runTaskResource",
"returns",
"a",
"troposphere",
"resource",
"that",
"will",
"create",
"a",
"lambda",
"function",
"that",
"can",
"be",
"used",
"to",
"run",
"an",
"ECS",
"task",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/template.go#L885-L898 | train |
remind101/empire | scheduler/cloudformation/template.go | tagsFromLabels | func tagsFromLabels(labels map[string]string) []*cloudformation.Tag {
tags := cloudformationTags{}
for k, v := range labels {
tags = append(tags, &cloudformation.Tag{Key: aws.String(k), Value: aws.String(v)})
}
sort.Sort(tags)
return tags
} | go | func tagsFromLabels(labels map[string]string) []*cloudformation.Tag {
tags := cloudformationTags{}
for k, v := range labels {
tags = append(tags, &cloudformation.Tag{Key: aws.String(k), Value: aws.String(v)})
}
sort.Sort(tags)
return tags
} | [
"func",
"tagsFromLabels",
"(",
"labels",
"map",
"[",
"string",
"]",
"string",
")",
"[",
"]",
"*",
"cloudformation",
".",
"Tag",
"{",
"tags",
":=",
"cloudformationTags",
"{",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"labels",
"{",
"tags",
"=",
... | // tagsFromLabels generates a list of CloudFormation tags from the labels, it
// also sorts the tags by key. | [
"tagsFromLabels",
"generates",
"a",
"list",
"of",
"CloudFormation",
"tags",
"from",
"the",
"labels",
"it",
"also",
"sorts",
"the",
"tags",
"by",
"key",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/template.go#L922-L929 | train |
remind101/empire | events.go | AsyncEvents | func AsyncEvents(e EventStream) EventStream {
s := &asyncEventStream{
e: e,
events: make(chan Event, 100),
}
go s.start()
return s
} | go | func AsyncEvents(e EventStream) EventStream {
s := &asyncEventStream{
e: e,
events: make(chan Event, 100),
}
go s.start()
return s
} | [
"func",
"AsyncEvents",
"(",
"e",
"EventStream",
")",
"EventStream",
"{",
"s",
":=",
"&",
"asyncEventStream",
"{",
"e",
":",
"e",
",",
"events",
":",
"make",
"(",
"chan",
"Event",
",",
"100",
")",
",",
"}",
"\n",
"go",
"s",
".",
"start",
"(",
")",
... | // AsyncEvents returns a new AsyncEventStream that will buffer upto 100 events
// before applying backpressure. | [
"AsyncEvents",
"returns",
"a",
"new",
"AsyncEventStream",
"that",
"will",
"buffer",
"upto",
"100",
"events",
"before",
"applying",
"backpressure",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/events.go#L355-L362 | train |
remind101/empire | server/auth/github/client.go | NewClient | func NewClient(config *oauth2.Config) *Client {
return &Client{
Config: config,
backoff: backoff,
}
} | go | func NewClient(config *oauth2.Config) *Client {
return &Client{
Config: config,
backoff: backoff,
}
} | [
"func",
"NewClient",
"(",
"config",
"*",
"oauth2",
".",
"Config",
")",
"*",
"Client",
"{",
"return",
"&",
"Client",
"{",
"Config",
":",
"config",
",",
"backoff",
":",
"backoff",
",",
"}",
"\n",
"}"
] | // NewClient returns a new Client instance that uses the given oauth2 config. | [
"NewClient",
"returns",
"a",
"new",
"Client",
"instance",
"that",
"uses",
"the",
"given",
"oauth2",
"config",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/server/auth/github/client.go#L80-L85 | train |
remind101/empire | server/auth/github/client.go | IsOrganizationMember | func (c *Client) IsOrganizationMember(organization, token string) (bool, error) {
req, err := c.NewRequest("HEAD", fmt.Sprintf("/user/memberships/orgs/%s", organization), nil)
if err != nil {
return false, err
}
tokenAuth(req, token)
resp, err := c.Do(req, nil)
if err != nil {
if resp != nil && resp.StatusCode == 404 {
return false, nil
}
return false, err
}
return true, nil
} | go | func (c *Client) IsOrganizationMember(organization, token string) (bool, error) {
req, err := c.NewRequest("HEAD", fmt.Sprintf("/user/memberships/orgs/%s", organization), nil)
if err != nil {
return false, err
}
tokenAuth(req, token)
resp, err := c.Do(req, nil)
if err != nil {
if resp != nil && resp.StatusCode == 404 {
return false, nil
}
return false, err
}
return true, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"IsOrganizationMember",
"(",
"organization",
",",
"token",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"req",
",",
"err",
":=",
"c",
".",
"NewRequest",
"(",
"\"HEAD\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\... | // IsOrganizationMember returns true of the authenticated user is a member of the
// organization. | [
"IsOrganizationMember",
"returns",
"true",
"of",
"the",
"authenticated",
"user",
"is",
"a",
"member",
"of",
"the",
"organization",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/server/auth/github/client.go#L172-L189 | train |
remind101/empire | server/auth/github/client.go | IsTeamMember | func (c *Client) IsTeamMember(teamID, token string) (bool, error) {
u, err := c.GetUser(token)
if err != nil {
return false, err
}
req, err := c.NewRequest("GET", fmt.Sprintf("/teams/%s/memberships/%s", teamID, u.Login), nil)
if err != nil {
return false, err
}
tokenAuth(req, token)
var t TeamMembership
resp, err := c.Do(req, &t)
if err != nil {
if resp != nil && resp.StatusCode == 404 {
return false, nil
}
return false, err
}
return t.State == "active", nil
} | go | func (c *Client) IsTeamMember(teamID, token string) (bool, error) {
u, err := c.GetUser(token)
if err != nil {
return false, err
}
req, err := c.NewRequest("GET", fmt.Sprintf("/teams/%s/memberships/%s", teamID, u.Login), nil)
if err != nil {
return false, err
}
tokenAuth(req, token)
var t TeamMembership
resp, err := c.Do(req, &t)
if err != nil {
if resp != nil && resp.StatusCode == 404 {
return false, nil
}
return false, err
}
return t.State == "active", nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"IsTeamMember",
"(",
"teamID",
",",
"token",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"u",
",",
"err",
":=",
"c",
".",
"GetUser",
"(",
"token",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
... | // IsTeamMember returns true if the given user is a member of the team. | [
"IsTeamMember",
"returns",
"true",
"if",
"the",
"given",
"user",
"is",
"a",
"member",
"of",
"the",
"team",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/server/auth/github/client.go#L192-L216 | train |
remind101/empire | pkg/heroku/organization_app.go | OrganizationAppCreate | func (c *Client) OrganizationAppCreate(options *OrganizationAppCreateOpts, message string) (*OrganizationApp, error) {
rh := RequestHeaders{CommitMessage: message}
var organizationAppRes OrganizationApp
return &organizationAppRes, c.PostWithHeaders(&organizationAppRes, "/organizations/apps", options, rh.Headers())
} | go | func (c *Client) OrganizationAppCreate(options *OrganizationAppCreateOpts, message string) (*OrganizationApp, error) {
rh := RequestHeaders{CommitMessage: message}
var organizationAppRes OrganizationApp
return &organizationAppRes, c.PostWithHeaders(&organizationAppRes, "/organizations/apps", options, rh.Headers())
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"OrganizationAppCreate",
"(",
"options",
"*",
"OrganizationAppCreateOpts",
",",
"message",
"string",
")",
"(",
"*",
"OrganizationApp",
",",
"error",
")",
"{",
"rh",
":=",
"RequestHeaders",
"{",
"CommitMessage",
":",
"messa... | // Create a new app in the specified organization, in the default organization
// if unspecified, or in personal account, if default organization is not set.
//
// options is the struct of optional parameters for this action. | [
"Create",
"a",
"new",
"app",
"in",
"the",
"specified",
"organization",
"in",
"the",
"default",
"organization",
"if",
"unspecified",
"or",
"in",
"personal",
"account",
"if",
"default",
"organization",
"is",
"not",
"set",
".",
"options",
"is",
"the",
"struct",
... | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/organization_app.go#L84-L88 | train |
remind101/empire | pkg/heroku/organization_app.go | OrganizationAppList | func (c *Client) OrganizationAppList(lr *ListRange) ([]OrganizationApp, error) {
req, err := c.NewRequest("GET", "/organizations/apps", nil, nil)
if err != nil {
return nil, err
}
if lr != nil {
lr.SetHeader(req)
}
var organizationAppsRes []OrganizationApp
return organizationAppsRes, c.DoReq(req, &organizationAppsRes)
} | go | func (c *Client) OrganizationAppList(lr *ListRange) ([]OrganizationApp, error) {
req, err := c.NewRequest("GET", "/organizations/apps", nil, nil)
if err != nil {
return nil, err
}
if lr != nil {
lr.SetHeader(req)
}
var organizationAppsRes []OrganizationApp
return organizationAppsRes, c.DoReq(req, &organizationAppsRes)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"OrganizationAppList",
"(",
"lr",
"*",
"ListRange",
")",
"(",
"[",
"]",
"OrganizationApp",
",",
"error",
")",
"{",
"req",
",",
"err",
":=",
"c",
".",
"NewRequest",
"(",
"\"GET\"",
",",
"\"/organizations/apps\"",
",",... | // List apps in the default organization, or in personal account, if default
// organization is not set.
//
// lr is an optional ListRange that sets the Range options for the paginated
// list of results. | [
"List",
"apps",
"in",
"the",
"default",
"organization",
"or",
"in",
"personal",
"account",
"if",
"default",
"organization",
"is",
"not",
"set",
".",
"lr",
"is",
"an",
"optional",
"ListRange",
"that",
"sets",
"the",
"Range",
"options",
"for",
"the",
"paginate... | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/organization_app.go#L111-L123 | train |
remind101/empire | pkg/heroku/organization_app.go | OrganizationAppListForOrganization | func (c *Client) OrganizationAppListForOrganization(organizationIdentity string, lr *ListRange) ([]OrganizationApp, error) {
req, err := c.NewRequest("GET", "/organizations/"+organizationIdentity+"/apps", nil, nil)
if err != nil {
return nil, err
}
if lr != nil {
lr.SetHeader(req)
}
var organizationAppsRes []OrganizationApp
return organizationAppsRes, c.DoReq(req, &organizationAppsRes)
} | go | func (c *Client) OrganizationAppListForOrganization(organizationIdentity string, lr *ListRange) ([]OrganizationApp, error) {
req, err := c.NewRequest("GET", "/organizations/"+organizationIdentity+"/apps", nil, nil)
if err != nil {
return nil, err
}
if lr != nil {
lr.SetHeader(req)
}
var organizationAppsRes []OrganizationApp
return organizationAppsRes, c.DoReq(req, &organizationAppsRes)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"OrganizationAppListForOrganization",
"(",
"organizationIdentity",
"string",
",",
"lr",
"*",
"ListRange",
")",
"(",
"[",
"]",
"OrganizationApp",
",",
"error",
")",
"{",
"req",
",",
"err",
":=",
"c",
".",
"NewRequest",
... | // List organization apps.
//
// organizationIdentity is the unique identifier of the OrganizationApp's
// Organization. lr is an optional ListRange that sets the Range options for the
// paginated list of results. | [
"List",
"organization",
"apps",
".",
"organizationIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"OrganizationApp",
"s",
"Organization",
".",
"lr",
"is",
"an",
"optional",
"ListRange",
"that",
"sets",
"the",
"Range",
"options",
"for",
"the",
"pagin... | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/organization_app.go#L130-L142 | train |
remind101/empire | pkg/heroku/organization_app.go | OrganizationAppInfo | func (c *Client) OrganizationAppInfo(appIdentity string) (*OrganizationApp, error) {
var organizationApp OrganizationApp
return &organizationApp, c.Get(&organizationApp, "/organizations/apps/"+appIdentity)
} | go | func (c *Client) OrganizationAppInfo(appIdentity string) (*OrganizationApp, error) {
var organizationApp OrganizationApp
return &organizationApp, c.Get(&organizationApp, "/organizations/apps/"+appIdentity)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"OrganizationAppInfo",
"(",
"appIdentity",
"string",
")",
"(",
"*",
"OrganizationApp",
",",
"error",
")",
"{",
"var",
"organizationApp",
"OrganizationApp",
"\n",
"return",
"&",
"organizationApp",
",",
"c",
".",
"Get",
"(... | // Info for an organization app.
//
// appIdentity is the unique identifier of the OrganizationApp's App. | [
"Info",
"for",
"an",
"organization",
"app",
".",
"appIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"OrganizationApp",
"s",
"App",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/organization_app.go#L147-L150 | train |
remind101/empire | pkg/heroku/organization_app.go | OrganizationAppUpdateLocked | func (c *Client) OrganizationAppUpdateLocked(appIdentity string, locked bool) (*OrganizationApp, error) {
params := struct {
Locked bool `json:"locked"`
}{
Locked: locked,
}
var organizationAppRes OrganizationApp
return &organizationAppRes, c.Patch(&organizationAppRes, "/organizations/apps/"+appIdentity, params)
} | go | func (c *Client) OrganizationAppUpdateLocked(appIdentity string, locked bool) (*OrganizationApp, error) {
params := struct {
Locked bool `json:"locked"`
}{
Locked: locked,
}
var organizationAppRes OrganizationApp
return &organizationAppRes, c.Patch(&organizationAppRes, "/organizations/apps/"+appIdentity, params)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"OrganizationAppUpdateLocked",
"(",
"appIdentity",
"string",
",",
"locked",
"bool",
")",
"(",
"*",
"OrganizationApp",
",",
"error",
")",
"{",
"params",
":=",
"struct",
"{",
"Locked",
"bool",
"`json:\"locked\"`",
"\n",
"}... | // Lock or unlock an organization app.
//
// appIdentity is the unique identifier of the OrganizationApp's App. locked is
// the are other organization members forbidden from joining this app. | [
"Lock",
"or",
"unlock",
"an",
"organization",
"app",
".",
"appIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"OrganizationApp",
"s",
"App",
".",
"locked",
"is",
"the",
"are",
"other",
"organization",
"members",
"forbidden",
"from",
"joining",
"th... | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/organization_app.go#L156-L164 | train |
remind101/empire | pkg/heroku/organization_app.go | OrganizationAppTransferToOrganization | func (c *Client) OrganizationAppTransferToOrganization(appIdentity string, owner string) (*OrganizationApp, error) {
params := struct {
Owner string `json:"owner"`
}{
Owner: owner,
}
var organizationAppRes OrganizationApp
return &organizationAppRes, c.Patch(&organizationAppRes, "/organizations/apps/"+appIdentity, params)
} | go | func (c *Client) OrganizationAppTransferToOrganization(appIdentity string, owner string) (*OrganizationApp, error) {
params := struct {
Owner string `json:"owner"`
}{
Owner: owner,
}
var organizationAppRes OrganizationApp
return &organizationAppRes, c.Patch(&organizationAppRes, "/organizations/apps/"+appIdentity, params)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"OrganizationAppTransferToOrganization",
"(",
"appIdentity",
"string",
",",
"owner",
"string",
")",
"(",
"*",
"OrganizationApp",
",",
"error",
")",
"{",
"params",
":=",
"struct",
"{",
"Owner",
"string",
"`json:\"owner\"`",
... | // Transfer an existing organization app to another organization.
//
// appIdentity is the unique identifier of the OrganizationApp's App. owner is
// the unique name of organization. | [
"Transfer",
"an",
"existing",
"organization",
"app",
"to",
"another",
"organization",
".",
"appIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"OrganizationApp",
"s",
"App",
".",
"owner",
"is",
"the",
"unique",
"name",
"of",
"organization",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/organization_app.go#L184-L192 | train |
remind101/empire | internal/saml/service_provider.go | MakeRedirectAuthenticationRequest | func (sp *ServiceProvider) MakeRedirectAuthenticationRequest(relayState string) (*url.URL, error) {
req, err := sp.MakeAuthenticationRequest(sp.GetSSOBindingLocation(HTTPRedirectBinding))
if err != nil {
return nil, err
}
return req.Redirect(relayState), nil
} | go | func (sp *ServiceProvider) MakeRedirectAuthenticationRequest(relayState string) (*url.URL, error) {
req, err := sp.MakeAuthenticationRequest(sp.GetSSOBindingLocation(HTTPRedirectBinding))
if err != nil {
return nil, err
}
return req.Redirect(relayState), nil
} | [
"func",
"(",
"sp",
"*",
"ServiceProvider",
")",
"MakeRedirectAuthenticationRequest",
"(",
"relayState",
"string",
")",
"(",
"*",
"url",
".",
"URL",
",",
"error",
")",
"{",
"req",
",",
"err",
":=",
"sp",
".",
"MakeAuthenticationRequest",
"(",
"sp",
".",
"Ge... | // MakeRedirectAuthenticationRequest creates a SAML authentication request using
// the HTTP-Redirect binding. It returns a URL that we will redirect the user to
// in order to start the auth process. | [
"MakeRedirectAuthenticationRequest",
"creates",
"a",
"SAML",
"authentication",
"request",
"using",
"the",
"HTTP",
"-",
"Redirect",
"binding",
".",
"It",
"returns",
"a",
"URL",
"that",
"we",
"will",
"redirect",
"the",
"user",
"to",
"in",
"order",
"to",
"start",
... | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/internal/saml/service_provider.go#L104-L110 | train |
remind101/empire | internal/saml/service_provider.go | getIDPSigningCert | func (sp *ServiceProvider) getIDPSigningCert() []byte {
cert := ""
for _, keyDescriptor := range sp.IDPMetadata.IDPSSODescriptor.KeyDescriptor {
if keyDescriptor.Use == "signing" {
cert = keyDescriptor.KeyInfo.Certificate
break
}
}
// If there are no explicitly signing certs, just return the first
// non-empty cert we find.
if cert == "" {
for _, keyDescriptor := range sp.IDPMetadata.IDPSSODescriptor.KeyDescriptor {
if keyDescriptor.Use == "" && keyDescriptor.KeyInfo.Certificate != "" {
cert = keyDescriptor.KeyInfo.Certificate
break
}
}
}
if cert == "" {
return nil
}
// cleanup whitespace and re-encode a PEM
cert = regexp.MustCompile("\\s+").ReplaceAllString(cert, "")
certBytes, _ := base64.StdEncoding.DecodeString(cert)
certBytes = pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: certBytes})
return certBytes
} | go | func (sp *ServiceProvider) getIDPSigningCert() []byte {
cert := ""
for _, keyDescriptor := range sp.IDPMetadata.IDPSSODescriptor.KeyDescriptor {
if keyDescriptor.Use == "signing" {
cert = keyDescriptor.KeyInfo.Certificate
break
}
}
// If there are no explicitly signing certs, just return the first
// non-empty cert we find.
if cert == "" {
for _, keyDescriptor := range sp.IDPMetadata.IDPSSODescriptor.KeyDescriptor {
if keyDescriptor.Use == "" && keyDescriptor.KeyInfo.Certificate != "" {
cert = keyDescriptor.KeyInfo.Certificate
break
}
}
}
if cert == "" {
return nil
}
// cleanup whitespace and re-encode a PEM
cert = regexp.MustCompile("\\s+").ReplaceAllString(cert, "")
certBytes, _ := base64.StdEncoding.DecodeString(cert)
certBytes = pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: certBytes})
return certBytes
} | [
"func",
"(",
"sp",
"*",
"ServiceProvider",
")",
"getIDPSigningCert",
"(",
")",
"[",
"]",
"byte",
"{",
"cert",
":=",
"\"\"",
"\n",
"for",
"_",
",",
"keyDescriptor",
":=",
"range",
"sp",
".",
"IDPMetadata",
".",
"IDPSSODescriptor",
".",
"KeyDescriptor",
"{",... | // getIDPSigningCert returns the certificate which we can use to verify things
// signed by the IDP in PEM format, or nil if no such certificate is found. | [
"getIDPSigningCert",
"returns",
"the",
"certificate",
"which",
"we",
"can",
"use",
"to",
"verify",
"things",
"signed",
"by",
"the",
"IDP",
"in",
"PEM",
"format",
"or",
"nil",
"if",
"no",
"such",
"certificate",
"is",
"found",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/internal/saml/service_provider.go#L148-L180 | train |
remind101/empire | internal/saml/service_provider.go | MakePostAuthenticationRequest | func (sp *ServiceProvider) MakePostAuthenticationRequest(relayState string) ([]byte, error) {
req, err := sp.MakeAuthenticationRequest(sp.GetSSOBindingLocation(HTTPPostBinding))
if err != nil {
return nil, err
}
return req.Post(relayState), nil
} | go | func (sp *ServiceProvider) MakePostAuthenticationRequest(relayState string) ([]byte, error) {
req, err := sp.MakeAuthenticationRequest(sp.GetSSOBindingLocation(HTTPPostBinding))
if err != nil {
return nil, err
}
return req.Post(relayState), nil
} | [
"func",
"(",
"sp",
"*",
"ServiceProvider",
")",
"MakePostAuthenticationRequest",
"(",
"relayState",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"req",
",",
"err",
":=",
"sp",
".",
"MakeAuthenticationRequest",
"(",
"sp",
".",
"GetSSOBindingL... | // MakePostAuthenticationRequest creates a SAML authentication request using
// the HTTP-POST binding. It returns HTML text representing an HTML form that
// can be sent presented to a browser to initiate the login process. | [
"MakePostAuthenticationRequest",
"creates",
"a",
"SAML",
"authentication",
"request",
"using",
"the",
"HTTP",
"-",
"POST",
"binding",
".",
"It",
"returns",
"HTML",
"text",
"representing",
"an",
"HTML",
"form",
"that",
"can",
"be",
"sent",
"presented",
"to",
"a",... | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/internal/saml/service_provider.go#L209-L215 | train |
remind101/empire | internal/saml/service_provider.go | Get | func (aa AssertionAttributes) Get(name string) *AssertionAttribute {
for _, attr := range aa {
if attr.Name == name {
return &attr
}
if attr.FriendlyName == name {
return &attr
}
}
return nil
} | go | func (aa AssertionAttributes) Get(name string) *AssertionAttribute {
for _, attr := range aa {
if attr.Name == name {
return &attr
}
if attr.FriendlyName == name {
return &attr
}
}
return nil
} | [
"func",
"(",
"aa",
"AssertionAttributes",
")",
"Get",
"(",
"name",
"string",
")",
"*",
"AssertionAttribute",
"{",
"for",
"_",
",",
"attr",
":=",
"range",
"aa",
"{",
"if",
"attr",
".",
"Name",
"==",
"name",
"{",
"return",
"&",
"attr",
"\n",
"}",
"\n",... | // Get returns the assertion attribute whose Name or FriendlyName
// matches name, or nil if no matching attribute is found. | [
"Get",
"returns",
"the",
"assertion",
"attribute",
"whose",
"Name",
"or",
"FriendlyName",
"matches",
"name",
"or",
"nil",
"if",
"no",
"matching",
"attribute",
"is",
"found",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/internal/saml/service_provider.go#L255-L265 | train |
remind101/empire | internal/saml/service_provider.go | InitiateLogin | func (sp *ServiceProvider) InitiateLogin(w http.ResponseWriter) error {
acsURL, _ := url.Parse(sp.AcsURL)
binding := HTTPRedirectBinding
bindingLocation := sp.GetSSOBindingLocation(binding)
if bindingLocation == "" {
binding = HTTPPostBinding
bindingLocation = sp.GetSSOBindingLocation(binding)
}
req, err := sp.MakeAuthenticationRequest(bindingLocation)
if err != nil {
return err
}
relayState := base64.URLEncoding.EncodeToString(randomBytes(42))
state := jwt.New(jwt.GetSigningMethod("HS256"))
claims := state.Claims.(jwt.MapClaims)
claims["id"] = req.ID
signedState, err := state.SignedString(sp.cookieSecret())
if err != nil {
return err
}
http.SetCookie(w, &http.Cookie{
Name: fmt.Sprintf("saml_%s", relayState),
Value: signedState,
MaxAge: int(MaxIssueDelay.Seconds()),
HttpOnly: false,
Path: acsURL.Path,
})
if binding == HTTPRedirectBinding {
redirectURL := req.Redirect(relayState)
w.Header().Add("Location", redirectURL.String())
w.WriteHeader(http.StatusFound)
return nil
}
if binding == HTTPPostBinding {
w.Header().Set("Content-Security-Policy", ""+
"default-src; "+
"script-src 'sha256-D8xB+y+rJ90RmLdP72xBqEEc0NUatn7yuCND0orkrgk='; "+
"reflected-xss block; "+
"referrer no-referrer;")
w.Header().Add("Content-type", "text/html")
w.Write([]byte(`<!DOCTYPE html><html><body>`))
w.Write(req.Post(relayState))
w.Write([]byte(`</body></html>`))
return nil
}
panic("not reached")
} | go | func (sp *ServiceProvider) InitiateLogin(w http.ResponseWriter) error {
acsURL, _ := url.Parse(sp.AcsURL)
binding := HTTPRedirectBinding
bindingLocation := sp.GetSSOBindingLocation(binding)
if bindingLocation == "" {
binding = HTTPPostBinding
bindingLocation = sp.GetSSOBindingLocation(binding)
}
req, err := sp.MakeAuthenticationRequest(bindingLocation)
if err != nil {
return err
}
relayState := base64.URLEncoding.EncodeToString(randomBytes(42))
state := jwt.New(jwt.GetSigningMethod("HS256"))
claims := state.Claims.(jwt.MapClaims)
claims["id"] = req.ID
signedState, err := state.SignedString(sp.cookieSecret())
if err != nil {
return err
}
http.SetCookie(w, &http.Cookie{
Name: fmt.Sprintf("saml_%s", relayState),
Value: signedState,
MaxAge: int(MaxIssueDelay.Seconds()),
HttpOnly: false,
Path: acsURL.Path,
})
if binding == HTTPRedirectBinding {
redirectURL := req.Redirect(relayState)
w.Header().Add("Location", redirectURL.String())
w.WriteHeader(http.StatusFound)
return nil
}
if binding == HTTPPostBinding {
w.Header().Set("Content-Security-Policy", ""+
"default-src; "+
"script-src 'sha256-D8xB+y+rJ90RmLdP72xBqEEc0NUatn7yuCND0orkrgk='; "+
"reflected-xss block; "+
"referrer no-referrer;")
w.Header().Add("Content-type", "text/html")
w.Write([]byte(`<!DOCTYPE html><html><body>`))
w.Write(req.Post(relayState))
w.Write([]byte(`</body></html>`))
return nil
}
panic("not reached")
} | [
"func",
"(",
"sp",
"*",
"ServiceProvider",
")",
"InitiateLogin",
"(",
"w",
"http",
".",
"ResponseWriter",
")",
"error",
"{",
"acsURL",
",",
"_",
":=",
"url",
".",
"Parse",
"(",
"sp",
".",
"AcsURL",
")",
"\n",
"binding",
":=",
"HTTPRedirectBinding",
"\n",... | // Login performs the necessary actions to start an SP initiated login. | [
"Login",
"performs",
"the",
"necessary",
"actions",
"to",
"start",
"an",
"SP",
"initiated",
"login",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/internal/saml/service_provider.go#L443-L494 | train |
remind101/empire | internal/saml/service_provider.go | Parse | func (sp *ServiceProvider) Parse(w http.ResponseWriter, r *http.Request) (*Assertion, error) {
allowIdPInitiated := ""
possibleRequestIDs := []string{allowIdPInitiated}
// Find the request id that relates to this RelayState.
relayState := r.PostFormValue("RelayState")
if sp.cookieSecret() != nil && relayState != "" {
cookieName := fmt.Sprintf("saml_%s", relayState)
cookie, err := r.Cookie(cookieName)
if err != nil {
return nil, fmt.Errorf("cannot find %s cookie", cookieName)
}
// Verify the integrity of the cookie.
state, err := jwt.Parse(cookie.Value, func(t *jwt.Token) (interface{}, error) {
return sp.cookieSecret(), nil
})
if err != nil || !state.Valid {
return nil, fmt.Errorf("could not decode state JWT: %v", err)
}
claims := state.Claims.(jwt.MapClaims)
id := claims["id"].(string)
possibleRequestIDs = append(possibleRequestIDs, id)
// delete the cookie
cookie.Value = ""
cookie.Expires = time.Time{}
http.SetCookie(w, cookie)
}
samlResponse := r.PostFormValue("SAMLResponse")
return sp.ParseSAMLResponse(samlResponse, possibleRequestIDs)
} | go | func (sp *ServiceProvider) Parse(w http.ResponseWriter, r *http.Request) (*Assertion, error) {
allowIdPInitiated := ""
possibleRequestIDs := []string{allowIdPInitiated}
// Find the request id that relates to this RelayState.
relayState := r.PostFormValue("RelayState")
if sp.cookieSecret() != nil && relayState != "" {
cookieName := fmt.Sprintf("saml_%s", relayState)
cookie, err := r.Cookie(cookieName)
if err != nil {
return nil, fmt.Errorf("cannot find %s cookie", cookieName)
}
// Verify the integrity of the cookie.
state, err := jwt.Parse(cookie.Value, func(t *jwt.Token) (interface{}, error) {
return sp.cookieSecret(), nil
})
if err != nil || !state.Valid {
return nil, fmt.Errorf("could not decode state JWT: %v", err)
}
claims := state.Claims.(jwt.MapClaims)
id := claims["id"].(string)
possibleRequestIDs = append(possibleRequestIDs, id)
// delete the cookie
cookie.Value = ""
cookie.Expires = time.Time{}
http.SetCookie(w, cookie)
}
samlResponse := r.PostFormValue("SAMLResponse")
return sp.ParseSAMLResponse(samlResponse, possibleRequestIDs)
} | [
"func",
"(",
"sp",
"*",
"ServiceProvider",
")",
"Parse",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"Assertion",
",",
"error",
")",
"{",
"allowIdPInitiated",
":=",
"\"\"",
"\n",
"possibleRequestIDs",
":... | // Parse parses the SAMLResponse | [
"Parse",
"parses",
"the",
"SAMLResponse"
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/internal/saml/service_provider.go#L497-L531 | train |
remind101/empire | internal/realip/realip.go | RealIP | func (r *Resolver) RealIP(req *http.Request) string {
var hdrRealIP string
if r.XRealIp {
hdrRealIP = req.Header.Get("X-Real-Ip")
}
var hdrForwardedFor string
if r.XForwardedFor {
hdrForwardedFor = req.Header.Get("X-Forwarded-For")
}
if len(hdrForwardedFor) == 0 && len(hdrRealIP) == 0 {
return ipAddrFromRemoteAddr(req.RemoteAddr)
}
// X-Forwarded-For is potentially a list of addresses separated with ","
forwarded := sort.StringSlice(strings.Split(hdrForwardedFor, ","))
// This will ignore the X-Forwarded-For entries matching a load balancer
// and use the first (from right to left) untrused address as the real
// ip. This is done to prevent spoofing X-Forwarded-For.
//
// For example, let's say you wanted try to spoof your ip to make it
// look like a request came from an office ip (204.28.121.211). You
// would make a request like this:
//
// curl https://www.example.com/debug -H "X-Forwarded-For: 204.28.121.211"
//
// The load balancer would then tag on the connecting ip, as well as the
// ip address of the load balancer itself. The application would receive
// an X-Forwarded-For header like the following:
//
// "X-Forwarded-For": [
// "204.28.121.211, 49.228.250.246, 10.128.21.180"
// ]
//
// This will look at each ip from right to left, and use the first
// "untrusted" address as the real ip.
//
// 1. The first ip, 10.128.21.180, is the loadbalancer ip address and is
// considered trusted because it's a LAN cidr.
// 2. The second ip, 49.228.250.246, is untrusted, so this is determined to
// be the real ip address.
//
// By doing this, the spoofed ip (204.28.121.211) is ignored.
reverse(forwarded)
for _, addr := range forwarded {
// return first non-local address
addr = strings.TrimSpace(addr)
if len(addr) > 0 && !isLocalAddress(addr) {
return addr
}
}
return hdrRealIP
} | go | func (r *Resolver) RealIP(req *http.Request) string {
var hdrRealIP string
if r.XRealIp {
hdrRealIP = req.Header.Get("X-Real-Ip")
}
var hdrForwardedFor string
if r.XForwardedFor {
hdrForwardedFor = req.Header.Get("X-Forwarded-For")
}
if len(hdrForwardedFor) == 0 && len(hdrRealIP) == 0 {
return ipAddrFromRemoteAddr(req.RemoteAddr)
}
// X-Forwarded-For is potentially a list of addresses separated with ","
forwarded := sort.StringSlice(strings.Split(hdrForwardedFor, ","))
// This will ignore the X-Forwarded-For entries matching a load balancer
// and use the first (from right to left) untrused address as the real
// ip. This is done to prevent spoofing X-Forwarded-For.
//
// For example, let's say you wanted try to spoof your ip to make it
// look like a request came from an office ip (204.28.121.211). You
// would make a request like this:
//
// curl https://www.example.com/debug -H "X-Forwarded-For: 204.28.121.211"
//
// The load balancer would then tag on the connecting ip, as well as the
// ip address of the load balancer itself. The application would receive
// an X-Forwarded-For header like the following:
//
// "X-Forwarded-For": [
// "204.28.121.211, 49.228.250.246, 10.128.21.180"
// ]
//
// This will look at each ip from right to left, and use the first
// "untrusted" address as the real ip.
//
// 1. The first ip, 10.128.21.180, is the loadbalancer ip address and is
// considered trusted because it's a LAN cidr.
// 2. The second ip, 49.228.250.246, is untrusted, so this is determined to
// be the real ip address.
//
// By doing this, the spoofed ip (204.28.121.211) is ignored.
reverse(forwarded)
for _, addr := range forwarded {
// return first non-local address
addr = strings.TrimSpace(addr)
if len(addr) > 0 && !isLocalAddress(addr) {
return addr
}
}
return hdrRealIP
} | [
"func",
"(",
"r",
"*",
"Resolver",
")",
"RealIP",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"string",
"{",
"var",
"hdrRealIP",
"string",
"\n",
"if",
"r",
".",
"XRealIp",
"{",
"hdrRealIP",
"=",
"req",
".",
"Header",
".",
"Get",
"(",
"\"X-Real-Ip\"... | // RealIP return client's real public IP address
// from http request headers. | [
"RealIP",
"return",
"client",
"s",
"real",
"public",
"IP",
"address",
"from",
"http",
"request",
"headers",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/internal/realip/realip.go#L67-L123 | train |
remind101/empire | internal/realip/realip.go | Middleware | func Middleware(h http.Handler, r *Resolver) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
ip := r.RealIP(req)
h.ServeHTTP(w, req.WithContext(context.WithValue(req.Context(), realIPKey, ip)))
})
} | go | func Middleware(h http.Handler, r *Resolver) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
ip := r.RealIP(req)
h.ServeHTTP(w, req.WithContext(context.WithValue(req.Context(), realIPKey, ip)))
})
} | [
"func",
"Middleware",
"(",
"h",
"http",
".",
"Handler",
",",
"r",
"*",
"Resolver",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
... | // Middleware is a simple http.Handler middleware that extracts the RealIP from
// the request and set it on the request context. Anything downstream can then
// simply call realip.RealIP to extract the real ip from the request. | [
"Middleware",
"is",
"a",
"simple",
"http",
".",
"Handler",
"middleware",
"that",
"extracts",
"the",
"RealIP",
"from",
"the",
"request",
"and",
"set",
"it",
"on",
"the",
"request",
"context",
".",
"Anything",
"downstream",
"can",
"then",
"simply",
"call",
"re... | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/internal/realip/realip.go#L128-L133 | train |
remind101/empire | internal/realip/realip.go | RealIP | func RealIP(req *http.Request) string {
ip, ok := req.Context().Value(realIPKey).(string)
if !ok {
// Fallback to a secure resolver.
return DefaultResolver.RealIP(req)
}
return ip
} | go | func RealIP(req *http.Request) string {
ip, ok := req.Context().Value(realIPKey).(string)
if !ok {
// Fallback to a secure resolver.
return DefaultResolver.RealIP(req)
}
return ip
} | [
"func",
"RealIP",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"string",
"{",
"ip",
",",
"ok",
":=",
"req",
".",
"Context",
"(",
")",
".",
"Value",
"(",
"realIPKey",
")",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"DefaultRes... | // Extracts the real ip from the request context. | [
"Extracts",
"the",
"real",
"ip",
"from",
"the",
"request",
"context",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/internal/realip/realip.go#L136-L143 | train |
remind101/empire | internal/realip/realip.go | reverse | func reverse(ss []string) {
last := len(ss) - 1
for i := 0; i < len(ss)/2; i++ {
ss[i], ss[last-i] = ss[last-i], ss[i]
}
} | go | func reverse(ss []string) {
last := len(ss) - 1
for i := 0; i < len(ss)/2; i++ {
ss[i], ss[last-i] = ss[last-i], ss[i]
}
} | [
"func",
"reverse",
"(",
"ss",
"[",
"]",
"string",
")",
"{",
"last",
":=",
"len",
"(",
"ss",
")",
"-",
"1",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"ss",
")",
"/",
"2",
";",
"i",
"++",
"{",
"ss",
"[",
"i",
"]",
",",
"ss",... | // reverse reverses a slice of strings. | [
"reverse",
"reverses",
"a",
"slice",
"of",
"strings",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/internal/realip/realip.go#L146-L151 | train |
remind101/empire | stats/statsd.go | NewStatsd | func NewStatsd(addr, prefix string) (*Statsd, error) {
c, err := statsd.NewClient(addr, prefix)
if err != nil {
return nil, err
}
return &Statsd{
client: c,
}, nil
} | go | func NewStatsd(addr, prefix string) (*Statsd, error) {
c, err := statsd.NewClient(addr, prefix)
if err != nil {
return nil, err
}
return &Statsd{
client: c,
}, nil
} | [
"func",
"NewStatsd",
"(",
"addr",
",",
"prefix",
"string",
")",
"(",
"*",
"Statsd",
",",
"error",
")",
"{",
"c",
",",
"err",
":=",
"statsd",
".",
"NewClient",
"(",
"addr",
",",
"prefix",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
... | // NewStatsd returns a new Statsd implementation that sends stats to addr. | [
"NewStatsd",
"returns",
"a",
"new",
"Statsd",
"implementation",
"that",
"sends",
"stats",
"to",
"addr",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/stats/statsd.go#L15-L23 | train |
remind101/empire | scheduler/docker/docker.go | RunAttachedWithDocker | func RunAttachedWithDocker(s twelvefactor.Scheduler, client *dockerutil.Client) *AttachedScheduler {
return &AttachedScheduler{
Scheduler: s,
dockerScheduler: NewScheduler(client),
}
} | go | func RunAttachedWithDocker(s twelvefactor.Scheduler, client *dockerutil.Client) *AttachedScheduler {
return &AttachedScheduler{
Scheduler: s,
dockerScheduler: NewScheduler(client),
}
} | [
"func",
"RunAttachedWithDocker",
"(",
"s",
"twelvefactor",
".",
"Scheduler",
",",
"client",
"*",
"dockerutil",
".",
"Client",
")",
"*",
"AttachedScheduler",
"{",
"return",
"&",
"AttachedScheduler",
"{",
"Scheduler",
":",
"s",
",",
"dockerScheduler",
":",
"NewSch... | // RunAttachedWithDocker wraps a Scheduler to run attached Run's using a Docker
// client. | [
"RunAttachedWithDocker",
"wraps",
"a",
"Scheduler",
"to",
"run",
"attached",
"Run",
"s",
"using",
"a",
"Docker",
"client",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/docker/docker.go#L66-L71 | train |
remind101/empire | scheduler/docker/docker.go | Run | func (s *AttachedScheduler) Run(ctx context.Context, app *twelvefactor.Manifest) error {
if len(app.Processes) != 1 {
return fmt.Errorf("docker: cannot run mutliple processes with attached scheduler")
}
p := app.Processes[0]
// Attached means stdout, stdin is attached.
attached := p.Stdin != nil || p.Stdout != nil || p.Stderr != nil
if attached {
return s.dockerScheduler.Run(ctx, app)
} else {
return s.Scheduler.Run(ctx, app)
}
} | go | func (s *AttachedScheduler) Run(ctx context.Context, app *twelvefactor.Manifest) error {
if len(app.Processes) != 1 {
return fmt.Errorf("docker: cannot run mutliple processes with attached scheduler")
}
p := app.Processes[0]
// Attached means stdout, stdin is attached.
attached := p.Stdin != nil || p.Stdout != nil || p.Stderr != nil
if attached {
return s.dockerScheduler.Run(ctx, app)
} else {
return s.Scheduler.Run(ctx, app)
}
} | [
"func",
"(",
"s",
"*",
"AttachedScheduler",
")",
"Run",
"(",
"ctx",
"context",
".",
"Context",
",",
"app",
"*",
"twelvefactor",
".",
"Manifest",
")",
"error",
"{",
"if",
"len",
"(",
"app",
".",
"Processes",
")",
"!=",
"1",
"{",
"return",
"fmt",
".",
... | // Run runs attached processes using the docker scheduler, and detached
// processes using the wrapped scheduler. | [
"Run",
"runs",
"attached",
"processes",
"using",
"the",
"docker",
"scheduler",
"and",
"detached",
"processes",
"using",
"the",
"wrapped",
"scheduler",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/docker/docker.go#L75-L89 | train |
remind101/empire | scheduler/docker/docker.go | Tasks | func (s *AttachedScheduler) Tasks(ctx context.Context, app string) ([]*twelvefactor.Task, error) {
if !s.ShowAttached {
return s.Scheduler.Tasks(ctx, app)
}
type instancesResult struct {
instances []*twelvefactor.Task
err error
}
ch := make(chan instancesResult, 1)
go func() {
attachedInstances, err := s.dockerScheduler.InstancesFromAttachedRuns(ctx, app)
ch <- instancesResult{attachedInstances, err}
}()
instances, err := s.Scheduler.Tasks(ctx, app)
if err != nil {
return instances, err
}
result := <-ch
if err := result.err; err != nil {
return instances, err
}
return append(instances, result.instances...), nil
} | go | func (s *AttachedScheduler) Tasks(ctx context.Context, app string) ([]*twelvefactor.Task, error) {
if !s.ShowAttached {
return s.Scheduler.Tasks(ctx, app)
}
type instancesResult struct {
instances []*twelvefactor.Task
err error
}
ch := make(chan instancesResult, 1)
go func() {
attachedInstances, err := s.dockerScheduler.InstancesFromAttachedRuns(ctx, app)
ch <- instancesResult{attachedInstances, err}
}()
instances, err := s.Scheduler.Tasks(ctx, app)
if err != nil {
return instances, err
}
result := <-ch
if err := result.err; err != nil {
return instances, err
}
return append(instances, result.instances...), nil
} | [
"func",
"(",
"s",
"*",
"AttachedScheduler",
")",
"Tasks",
"(",
"ctx",
"context",
".",
"Context",
",",
"app",
"string",
")",
"(",
"[",
"]",
"*",
"twelvefactor",
".",
"Task",
",",
"error",
")",
"{",
"if",
"!",
"s",
".",
"ShowAttached",
"{",
"return",
... | // Tasks returns a combination of instances from the wrapped scheduler, as
// well as instances from attached runs. | [
"Tasks",
"returns",
"a",
"combination",
"of",
"instances",
"from",
"the",
"wrapped",
"scheduler",
"as",
"well",
"as",
"instances",
"from",
"attached",
"runs",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/docker/docker.go#L93-L120 | train |
remind101/empire | scheduler/docker/docker.go | Stop | func (s *AttachedScheduler) Stop(ctx context.Context, maybeContainerID string) error {
if !s.ShowAttached {
return s.Scheduler.Stop(ctx, maybeContainerID)
}
err := s.dockerScheduler.Stop(ctx, maybeContainerID)
// If there's no container with this ID, delegate to the wrapped
// scheduler.
if _, ok := err.(*docker.NoSuchContainer); ok {
return s.Scheduler.Stop(ctx, maybeContainerID)
}
return err
} | go | func (s *AttachedScheduler) Stop(ctx context.Context, maybeContainerID string) error {
if !s.ShowAttached {
return s.Scheduler.Stop(ctx, maybeContainerID)
}
err := s.dockerScheduler.Stop(ctx, maybeContainerID)
// If there's no container with this ID, delegate to the wrapped
// scheduler.
if _, ok := err.(*docker.NoSuchContainer); ok {
return s.Scheduler.Stop(ctx, maybeContainerID)
}
return err
} | [
"func",
"(",
"s",
"*",
"AttachedScheduler",
")",
"Stop",
"(",
"ctx",
"context",
".",
"Context",
",",
"maybeContainerID",
"string",
")",
"error",
"{",
"if",
"!",
"s",
".",
"ShowAttached",
"{",
"return",
"s",
".",
"Scheduler",
".",
"Stop",
"(",
"ctx",
",... | // Stop checks if there's an attached run matching the given id, and stops that
// container if there is. Otherwise, it delegates to the wrapped Scheduler. | [
"Stop",
"checks",
"if",
"there",
"s",
"an",
"attached",
"run",
"matching",
"the",
"given",
"id",
"and",
"stops",
"that",
"container",
"if",
"there",
"is",
".",
"Otherwise",
"it",
"delegates",
"to",
"the",
"wrapped",
"Scheduler",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/docker/docker.go#L124-L138 | train |
remind101/empire | scheduler/docker/docker.go | InstancesFromAttachedRuns | func (s *Scheduler) InstancesFromAttachedRuns(ctx context.Context, app string) ([]*twelvefactor.Task, error) {
// Filter only docker containers that were started as an attached run.
attached := fmt.Sprintf("%s=%s", runLabel, Attached)
return s.instances(ctx, app, attached)
} | go | func (s *Scheduler) InstancesFromAttachedRuns(ctx context.Context, app string) ([]*twelvefactor.Task, error) {
// Filter only docker containers that were started as an attached run.
attached := fmt.Sprintf("%s=%s", runLabel, Attached)
return s.instances(ctx, app, attached)
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"InstancesFromAttachedRuns",
"(",
"ctx",
"context",
".",
"Context",
",",
"app",
"string",
")",
"(",
"[",
"]",
"*",
"twelvefactor",
".",
"Task",
",",
"error",
")",
"{",
"attached",
":=",
"fmt",
".",
"Sprintf",
"(... | // InstancesFromAttachedRuns returns Instances that were started from attached
// runs. | [
"InstancesFromAttachedRuns",
"returns",
"Instances",
"that",
"were",
"started",
"from",
"attached",
"runs",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/docker/docker.go#L234-L238 | train |
remind101/empire | scheduler/docker/docker.go | instances | func (s *Scheduler) instances(ctx context.Context, app string, labels ...string) ([]*twelvefactor.Task, error) {
var instances []*twelvefactor.Task
containers, err := s.docker.ListContainers(docker.ListContainersOptions{
Filters: map[string][]string{
"label": append([]string{
fmt.Sprintf("%s=%s", appLabel, app),
}, labels...),
},
})
if err != nil {
return nil, fmt.Errorf("error listing containers from attached runs: %v", err)
}
for _, apiContainer := range containers {
container, err := s.docker.InspectContainer(apiContainer.ID)
if err != nil {
return instances, fmt.Errorf("error inspecting container %s: %v", apiContainer.ID, err)
}
state := strings.ToUpper(container.State.StateString())
instances = append(instances, &twelvefactor.Task{
ID: container.ID[0:12],
State: state,
UpdatedAt: container.State.StartedAt,
Process: &twelvefactor.Process{
Type: container.Config.Labels[processLabel],
Command: container.Config.Cmd,
Env: parseEnv(container.Config.Env),
Memory: uint(container.HostConfig.Memory),
CPUShares: uint(container.HostConfig.CPUShares),
},
})
}
return instances, nil
} | go | func (s *Scheduler) instances(ctx context.Context, app string, labels ...string) ([]*twelvefactor.Task, error) {
var instances []*twelvefactor.Task
containers, err := s.docker.ListContainers(docker.ListContainersOptions{
Filters: map[string][]string{
"label": append([]string{
fmt.Sprintf("%s=%s", appLabel, app),
}, labels...),
},
})
if err != nil {
return nil, fmt.Errorf("error listing containers from attached runs: %v", err)
}
for _, apiContainer := range containers {
container, err := s.docker.InspectContainer(apiContainer.ID)
if err != nil {
return instances, fmt.Errorf("error inspecting container %s: %v", apiContainer.ID, err)
}
state := strings.ToUpper(container.State.StateString())
instances = append(instances, &twelvefactor.Task{
ID: container.ID[0:12],
State: state,
UpdatedAt: container.State.StartedAt,
Process: &twelvefactor.Process{
Type: container.Config.Labels[processLabel],
Command: container.Config.Cmd,
Env: parseEnv(container.Config.Env),
Memory: uint(container.HostConfig.Memory),
CPUShares: uint(container.HostConfig.CPUShares),
},
})
}
return instances, nil
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"instances",
"(",
"ctx",
"context",
".",
"Context",
",",
"app",
"string",
",",
"labels",
"...",
"string",
")",
"(",
"[",
"]",
"*",
"twelvefactor",
".",
"Task",
",",
"error",
")",
"{",
"var",
"instances",
"[",
... | // instances returns docker container instances for this app, optionally
// filtered with labels. | [
"instances",
"returns",
"docker",
"container",
"instances",
"for",
"this",
"app",
"optionally",
"filtered",
"with",
"labels",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/docker/docker.go#L242-L279 | train |
remind101/empire | scheduler/docker/docker.go | Stop | func (s *Scheduler) Stop(ctx context.Context, containerID string) error {
container, err := s.docker.InspectContainer(containerID)
if err != nil {
return err
}
// Some extra protection around stopping containers. We don't want to
// allow users to stop containers that may have been started outside of
// Empire.
if _, ok := container.Config.Labels[runLabel]; !ok {
return &docker.NoSuchContainer{
ID: containerID,
}
}
if err := s.docker.StopContainer(ctx, containerID, stopContainerTimeout); err != nil {
return err
}
return nil
} | go | func (s *Scheduler) Stop(ctx context.Context, containerID string) error {
container, err := s.docker.InspectContainer(containerID)
if err != nil {
return err
}
// Some extra protection around stopping containers. We don't want to
// allow users to stop containers that may have been started outside of
// Empire.
if _, ok := container.Config.Labels[runLabel]; !ok {
return &docker.NoSuchContainer{
ID: containerID,
}
}
if err := s.docker.StopContainer(ctx, containerID, stopContainerTimeout); err != nil {
return err
}
return nil
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"Stop",
"(",
"ctx",
"context",
".",
"Context",
",",
"containerID",
"string",
")",
"error",
"{",
"container",
",",
"err",
":=",
"s",
".",
"docker",
".",
"InspectContainer",
"(",
"containerID",
")",
"\n",
"if",
"e... | // Stop stops the given container. | [
"Stop",
"stops",
"the",
"given",
"container",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/docker/docker.go#L282-L302 | train |
ory/ladon | condition_cidr.go | Fulfills | func (c *CIDRCondition) Fulfills(value interface{}, _ *Request) bool {
ips, ok := value.(string)
if !ok {
return false
}
_, cidrnet, err := net.ParseCIDR(c.CIDR)
if err != nil {
return false
}
ip := net.ParseIP(ips)
if ip == nil {
return false
}
return cidrnet.Contains(ip)
} | go | func (c *CIDRCondition) Fulfills(value interface{}, _ *Request) bool {
ips, ok := value.(string)
if !ok {
return false
}
_, cidrnet, err := net.ParseCIDR(c.CIDR)
if err != nil {
return false
}
ip := net.ParseIP(ips)
if ip == nil {
return false
}
return cidrnet.Contains(ip)
} | [
"func",
"(",
"c",
"*",
"CIDRCondition",
")",
"Fulfills",
"(",
"value",
"interface",
"{",
"}",
",",
"_",
"*",
"Request",
")",
"bool",
"{",
"ips",
",",
"ok",
":=",
"value",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"false",
"\n... | // Fulfills returns true if the the request is fulfilled by the condition. | [
"Fulfills",
"returns",
"true",
"if",
"the",
"the",
"request",
"is",
"fulfilled",
"by",
"the",
"condition",
"."
] | 7f1c376a9a46cd4e09f90d3940e81cd963b0d87d | https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/condition_cidr.go#L33-L50 | train |
ory/ladon | condition_boolean.go | Fulfills | func (c *BooleanCondition) Fulfills(value interface{}, _ *Request) bool {
val, ok := value.(bool)
return ok && val == c.BooleanValue
} | go | func (c *BooleanCondition) Fulfills(value interface{}, _ *Request) bool {
val, ok := value.(bool)
return ok && val == c.BooleanValue
} | [
"func",
"(",
"c",
"*",
"BooleanCondition",
")",
"Fulfills",
"(",
"value",
"interface",
"{",
"}",
",",
"_",
"*",
"Request",
")",
"bool",
"{",
"val",
",",
"ok",
":=",
"value",
".",
"(",
"bool",
")",
"\n",
"return",
"ok",
"&&",
"val",
"==",
"c",
"."... | // Fulfills determines if the BooleanCondition is fulfilled.
// The BooleanCondition is fulfilled if the provided boolean value matches the conditions boolean value. | [
"Fulfills",
"determines",
"if",
"the",
"BooleanCondition",
"is",
"fulfilled",
".",
"The",
"BooleanCondition",
"is",
"fulfilled",
"if",
"the",
"provided",
"boolean",
"value",
"matches",
"the",
"conditions",
"boolean",
"value",
"."
] | 7f1c376a9a46cd4e09f90d3940e81cd963b0d87d | https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/condition_boolean.go#L21-L25 | train |
ory/ladon | condition_subject_equal.go | Fulfills | func (c *EqualsSubjectCondition) Fulfills(value interface{}, r *Request) bool {
s, ok := value.(string)
return ok && s == r.Subject
} | go | func (c *EqualsSubjectCondition) Fulfills(value interface{}, r *Request) bool {
s, ok := value.(string)
return ok && s == r.Subject
} | [
"func",
"(",
"c",
"*",
"EqualsSubjectCondition",
")",
"Fulfills",
"(",
"value",
"interface",
"{",
"}",
",",
"r",
"*",
"Request",
")",
"bool",
"{",
"s",
",",
"ok",
":=",
"value",
".",
"(",
"string",
")",
"\n",
"return",
"ok",
"&&",
"s",
"==",
"r",
... | // Fulfills returns true if the request's subject is equal to the given value string | [
"Fulfills",
"returns",
"true",
"if",
"the",
"request",
"s",
"subject",
"is",
"equal",
"to",
"the",
"given",
"value",
"string"
] | 7f1c376a9a46cd4e09f90d3940e81cd963b0d87d | https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/condition_subject_equal.go#L27-L31 | train |
ory/ladon | manager/memory/manager_memory.go | Update | func (m *MemoryManager) Update(policy Policy) error {
m.Lock()
defer m.Unlock()
m.Policies[policy.GetID()] = policy
return nil
} | go | func (m *MemoryManager) Update(policy Policy) error {
m.Lock()
defer m.Unlock()
m.Policies[policy.GetID()] = policy
return nil
} | [
"func",
"(",
"m",
"*",
"MemoryManager",
")",
"Update",
"(",
"policy",
"Policy",
")",
"error",
"{",
"m",
".",
"Lock",
"(",
")",
"\n",
"defer",
"m",
".",
"Unlock",
"(",
")",
"\n",
"m",
".",
"Policies",
"[",
"policy",
".",
"GetID",
"(",
")",
"]",
... | // Update updates an existing policy. | [
"Update",
"updates",
"an",
"existing",
"policy",
"."
] | 7f1c376a9a46cd4e09f90d3940e81cd963b0d87d | https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/manager/memory/manager_memory.go#L47-L52 | train |
ory/ladon | manager/memory/manager_memory.go | GetAll | func (m *MemoryManager) GetAll(limit, offset int64) (Policies, error) {
keys := make([]string, len(m.Policies))
i := 0
m.RLock()
for key := range m.Policies {
keys[i] = key
i++
}
start, end := pagination.Index(int(limit), int(offset), len(m.Policies))
sort.Strings(keys)
ps := make(Policies, len(keys[start:end]))
i = 0
for _, key := range keys[start:end] {
ps[i] = m.Policies[key]
i++
}
m.RUnlock()
return ps, nil
} | go | func (m *MemoryManager) GetAll(limit, offset int64) (Policies, error) {
keys := make([]string, len(m.Policies))
i := 0
m.RLock()
for key := range m.Policies {
keys[i] = key
i++
}
start, end := pagination.Index(int(limit), int(offset), len(m.Policies))
sort.Strings(keys)
ps := make(Policies, len(keys[start:end]))
i = 0
for _, key := range keys[start:end] {
ps[i] = m.Policies[key]
i++
}
m.RUnlock()
return ps, nil
} | [
"func",
"(",
"m",
"*",
"MemoryManager",
")",
"GetAll",
"(",
"limit",
",",
"offset",
"int64",
")",
"(",
"Policies",
",",
"error",
")",
"{",
"keys",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"m",
".",
"Policies",
")",
")",
"\n",
"i",
... | // GetAll returns all policies. | [
"GetAll",
"returns",
"all",
"policies",
"."
] | 7f1c376a9a46cd4e09f90d3940e81cd963b0d87d | https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/manager/memory/manager_memory.go#L55-L74 | train |
ory/ladon | manager/memory/manager_memory.go | Create | func (m *MemoryManager) Create(policy Policy) error {
m.Lock()
defer m.Unlock()
if _, found := m.Policies[policy.GetID()]; found {
return errors.New("Policy exists")
}
m.Policies[policy.GetID()] = policy
return nil
} | go | func (m *MemoryManager) Create(policy Policy) error {
m.Lock()
defer m.Unlock()
if _, found := m.Policies[policy.GetID()]; found {
return errors.New("Policy exists")
}
m.Policies[policy.GetID()] = policy
return nil
} | [
"func",
"(",
"m",
"*",
"MemoryManager",
")",
"Create",
"(",
"policy",
"Policy",
")",
"error",
"{",
"m",
".",
"Lock",
"(",
")",
"\n",
"defer",
"m",
".",
"Unlock",
"(",
")",
"\n",
"if",
"_",
",",
"found",
":=",
"m",
".",
"Policies",
"[",
"policy",
... | // Create a new pollicy to MemoryManager. | [
"Create",
"a",
"new",
"pollicy",
"to",
"MemoryManager",
"."
] | 7f1c376a9a46cd4e09f90d3940e81cd963b0d87d | https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/manager/memory/manager_memory.go#L77-L87 | train |
ory/ladon | manager/memory/manager_memory.go | Get | func (m *MemoryManager) Get(id string) (Policy, error) {
m.RLock()
defer m.RUnlock()
p, ok := m.Policies[id]
if !ok {
return nil, errors.New("Not found")
}
return p, nil
} | go | func (m *MemoryManager) Get(id string) (Policy, error) {
m.RLock()
defer m.RUnlock()
p, ok := m.Policies[id]
if !ok {
return nil, errors.New("Not found")
}
return p, nil
} | [
"func",
"(",
"m",
"*",
"MemoryManager",
")",
"Get",
"(",
"id",
"string",
")",
"(",
"Policy",
",",
"error",
")",
"{",
"m",
".",
"RLock",
"(",
")",
"\n",
"defer",
"m",
".",
"RUnlock",
"(",
")",
"\n",
"p",
",",
"ok",
":=",
"m",
".",
"Policies",
... | // Get retrieves a policy. | [
"Get",
"retrieves",
"a",
"policy",
"."
] | 7f1c376a9a46cd4e09f90d3940e81cd963b0d87d | https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/manager/memory/manager_memory.go#L90-L99 | train |
ory/ladon | manager/memory/manager_memory.go | Delete | func (m *MemoryManager) Delete(id string) error {
m.Lock()
defer m.Unlock()
delete(m.Policies, id)
return nil
} | go | func (m *MemoryManager) Delete(id string) error {
m.Lock()
defer m.Unlock()
delete(m.Policies, id)
return nil
} | [
"func",
"(",
"m",
"*",
"MemoryManager",
")",
"Delete",
"(",
"id",
"string",
")",
"error",
"{",
"m",
".",
"Lock",
"(",
")",
"\n",
"defer",
"m",
".",
"Unlock",
"(",
")",
"\n",
"delete",
"(",
"m",
".",
"Policies",
",",
"id",
")",
"\n",
"return",
"... | // Delete removes a policy. | [
"Delete",
"removes",
"a",
"policy",
"."
] | 7f1c376a9a46cd4e09f90d3940e81cd963b0d87d | https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/manager/memory/manager_memory.go#L102-L107 | train |
ory/ladon | condition_string_pairs_equal.go | Fulfills | func (c *StringPairsEqualCondition) Fulfills(value interface{}, _ *Request) bool {
pairs, PairsOk := value.([]interface{})
if !PairsOk {
return false
}
for _, v := range pairs {
pair, PairOk := v.([]interface{})
if !PairOk || (len(pair) != 2) {
return false
}
a, AOk := pair[0].(string)
b, BOk := pair[1].(string)
if !AOk || !BOk || (a != b) {
return false
}
}
return true
} | go | func (c *StringPairsEqualCondition) Fulfills(value interface{}, _ *Request) bool {
pairs, PairsOk := value.([]interface{})
if !PairsOk {
return false
}
for _, v := range pairs {
pair, PairOk := v.([]interface{})
if !PairOk || (len(pair) != 2) {
return false
}
a, AOk := pair[0].(string)
b, BOk := pair[1].(string)
if !AOk || !BOk || (a != b) {
return false
}
}
return true
} | [
"func",
"(",
"c",
"*",
"StringPairsEqualCondition",
")",
"Fulfills",
"(",
"value",
"interface",
"{",
"}",
",",
"_",
"*",
"Request",
")",
"bool",
"{",
"pairs",
",",
"PairsOk",
":=",
"value",
".",
"(",
"[",
"]",
"interface",
"{",
"}",
")",
"\n",
"if",
... | // Fulfills returns true if the given value is an array of string arrays and
// each string array has exactly two values which are equal | [
"Fulfills",
"returns",
"true",
"if",
"the",
"given",
"value",
"is",
"an",
"array",
"of",
"string",
"arrays",
"and",
"each",
"string",
"array",
"has",
"exactly",
"two",
"values",
"which",
"are",
"equal"
] | 7f1c376a9a46cd4e09f90d3940e81cd963b0d87d | https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/condition_string_pairs_equal.go#L30-L51 | train |
ory/ladon | condition_string_match.go | Fulfills | func (c *StringMatchCondition) Fulfills(value interface{}, _ *Request) bool {
s, ok := value.(string)
matches, _ := regexp.MatchString(c.Matches, s)
return ok && matches
} | go | func (c *StringMatchCondition) Fulfills(value interface{}, _ *Request) bool {
s, ok := value.(string)
matches, _ := regexp.MatchString(c.Matches, s)
return ok && matches
} | [
"func",
"(",
"c",
"*",
"StringMatchCondition",
")",
"Fulfills",
"(",
"value",
"interface",
"{",
"}",
",",
"_",
"*",
"Request",
")",
"bool",
"{",
"s",
",",
"ok",
":=",
"value",
".",
"(",
"string",
")",
"\n",
"matches",
",",
"_",
":=",
"regexp",
".",... | // Fulfills returns true if the given value is a string and matches the regex
// pattern in StringMatchCondition.Matches | [
"Fulfills",
"returns",
"true",
"if",
"the",
"given",
"value",
"is",
"a",
"string",
"and",
"matches",
"the",
"regex",
"pattern",
"in",
"StringMatchCondition",
".",
"Matches"
] | 7f1c376a9a46cd4e09f90d3940e81cd963b0d87d | https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/condition_string_match.go#L35-L41 | train |
ory/ladon | ladon.go | IsAllowed | func (l *Ladon) IsAllowed(r *Request) (err error) {
policies, err := l.Manager.FindRequestCandidates(r)
if err != nil {
return err
}
// Although the manager is responsible of matching the policies, it might decide to just scan for
// subjects, it might return all policies, or it might have a different pattern matching than Golang.
// Thus, we need to make sure that we actually matched the right policies.
return l.DoPoliciesAllow(r, policies)
} | go | func (l *Ladon) IsAllowed(r *Request) (err error) {
policies, err := l.Manager.FindRequestCandidates(r)
if err != nil {
return err
}
// Although the manager is responsible of matching the policies, it might decide to just scan for
// subjects, it might return all policies, or it might have a different pattern matching than Golang.
// Thus, we need to make sure that we actually matched the right policies.
return l.DoPoliciesAllow(r, policies)
} | [
"func",
"(",
"l",
"*",
"Ladon",
")",
"IsAllowed",
"(",
"r",
"*",
"Request",
")",
"(",
"err",
"error",
")",
"{",
"policies",
",",
"err",
":=",
"l",
".",
"Manager",
".",
"FindRequestCandidates",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"... | // IsAllowed returns nil if subject s has permission p on resource r with context c or an error otherwise. | [
"IsAllowed",
"returns",
"nil",
"if",
"subject",
"s",
"has",
"permission",
"p",
"on",
"resource",
"r",
"with",
"context",
"c",
"or",
"an",
"error",
"otherwise",
"."
] | 7f1c376a9a46cd4e09f90d3940e81cd963b0d87d | https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/ladon.go#L49-L59 | train |
ory/ladon | ladon.go | DoPoliciesAllow | func (l *Ladon) DoPoliciesAllow(r *Request, policies []Policy) (err error) {
var allowed = false
var deciders = Policies{}
// Iterate through all policies
for _, p := range policies {
// Does the action match with one of the policies?
// This is the first check because usually actions are a superset of get|update|delete|set
// and thus match faster.
if pm, err := l.matcher().Matches(p, p.GetActions(), r.Action); err != nil {
return errors.WithStack(err)
} else if !pm {
// no, continue to next policy
continue
}
// Does the subject match with one of the policies?
// There are usually less subjects than resources which is why this is checked
// before checking for resources.
if sm, err := l.matcher().Matches(p, p.GetSubjects(), r.Subject); err != nil {
return err
} else if !sm {
// no, continue to next policy
continue
}
// Does the resource match with one of the policies?
if rm, err := l.matcher().Matches(p, p.GetResources(), r.Resource); err != nil {
return errors.WithStack(err)
} else if !rm {
// no, continue to next policy
continue
}
// Are the policies conditions met?
// This is checked first because it usually has a small complexity.
if !l.passesConditions(p, r) {
// no, continue to next policy
continue
}
// Is the policies effect deny? If yes, this overrides all allow policies -> access denied.
if !p.AllowAccess() {
deciders = append(deciders, p)
l.auditLogger().LogRejectedAccessRequest(r, policies, deciders)
return errors.WithStack(ErrRequestForcefullyDenied)
}
allowed = true
deciders = append(deciders, p)
}
if !allowed {
l.auditLogger().LogRejectedAccessRequest(r, policies, deciders)
return errors.WithStack(ErrRequestDenied)
}
l.auditLogger().LogGrantedAccessRequest(r, policies, deciders)
return nil
} | go | func (l *Ladon) DoPoliciesAllow(r *Request, policies []Policy) (err error) {
var allowed = false
var deciders = Policies{}
// Iterate through all policies
for _, p := range policies {
// Does the action match with one of the policies?
// This is the first check because usually actions are a superset of get|update|delete|set
// and thus match faster.
if pm, err := l.matcher().Matches(p, p.GetActions(), r.Action); err != nil {
return errors.WithStack(err)
} else if !pm {
// no, continue to next policy
continue
}
// Does the subject match with one of the policies?
// There are usually less subjects than resources which is why this is checked
// before checking for resources.
if sm, err := l.matcher().Matches(p, p.GetSubjects(), r.Subject); err != nil {
return err
} else if !sm {
// no, continue to next policy
continue
}
// Does the resource match with one of the policies?
if rm, err := l.matcher().Matches(p, p.GetResources(), r.Resource); err != nil {
return errors.WithStack(err)
} else if !rm {
// no, continue to next policy
continue
}
// Are the policies conditions met?
// This is checked first because it usually has a small complexity.
if !l.passesConditions(p, r) {
// no, continue to next policy
continue
}
// Is the policies effect deny? If yes, this overrides all allow policies -> access denied.
if !p.AllowAccess() {
deciders = append(deciders, p)
l.auditLogger().LogRejectedAccessRequest(r, policies, deciders)
return errors.WithStack(ErrRequestForcefullyDenied)
}
allowed = true
deciders = append(deciders, p)
}
if !allowed {
l.auditLogger().LogRejectedAccessRequest(r, policies, deciders)
return errors.WithStack(ErrRequestDenied)
}
l.auditLogger().LogGrantedAccessRequest(r, policies, deciders)
return nil
} | [
"func",
"(",
"l",
"*",
"Ladon",
")",
"DoPoliciesAllow",
"(",
"r",
"*",
"Request",
",",
"policies",
"[",
"]",
"Policy",
")",
"(",
"err",
"error",
")",
"{",
"var",
"allowed",
"=",
"false",
"\n",
"var",
"deciders",
"=",
"Policies",
"{",
"}",
"\n",
"fo... | // DoPoliciesAllow returns nil if subject s has permission p on resource r with context c for a given policy list or an error otherwise.
// The IsAllowed interface should be preferred since it uses the manager directly. This is a lower level interface for when you don't want to use the ladon manager. | [
"DoPoliciesAllow",
"returns",
"nil",
"if",
"subject",
"s",
"has",
"permission",
"p",
"on",
"resource",
"r",
"with",
"context",
"c",
"for",
"a",
"given",
"policy",
"list",
"or",
"an",
"error",
"otherwise",
".",
"The",
"IsAllowed",
"interface",
"should",
"be",... | 7f1c376a9a46cd4e09f90d3940e81cd963b0d87d | https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/ladon.go#L63-L122 | train |
ory/ladon | condition_resource_contains.go | Fulfills | func (c *ResourceContainsCondition) Fulfills(value interface{}, r *Request) bool {
filter, ok := value.(map[string]interface{})
if !ok {
return false
}
valueString, ok := filter["value"].(string)
if !ok || len(valueString) < 1 {
return false
}
//If no delimiter provided default to "equals" check
delimiterString, ok := filter["delimiter"].(string)
if !ok || len(delimiterString) < 1 {
delimiterString = ""
}
// Append delimiter to strings to prevent delim+1 being interpreted as delim+10 being present
filterValue := delimiterString + valueString + delimiterString
resourceString := delimiterString + r.Resource + delimiterString
matches := strings.Contains(resourceString, filterValue)
return matches
} | go | func (c *ResourceContainsCondition) Fulfills(value interface{}, r *Request) bool {
filter, ok := value.(map[string]interface{})
if !ok {
return false
}
valueString, ok := filter["value"].(string)
if !ok || len(valueString) < 1 {
return false
}
//If no delimiter provided default to "equals" check
delimiterString, ok := filter["delimiter"].(string)
if !ok || len(delimiterString) < 1 {
delimiterString = ""
}
// Append delimiter to strings to prevent delim+1 being interpreted as delim+10 being present
filterValue := delimiterString + valueString + delimiterString
resourceString := delimiterString + r.Resource + delimiterString
matches := strings.Contains(resourceString, filterValue)
return matches
} | [
"func",
"(",
"c",
"*",
"ResourceContainsCondition",
")",
"Fulfills",
"(",
"value",
"interface",
"{",
"}",
",",
"r",
"*",
"Request",
")",
"bool",
"{",
"filter",
",",
"ok",
":=",
"value",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",... | // Fulfills returns true if the request's resouce contains the given value string | [
"Fulfills",
"returns",
"true",
"if",
"the",
"request",
"s",
"resouce",
"contains",
"the",
"given",
"value",
"string"
] | 7f1c376a9a46cd4e09f90d3940e81cd963b0d87d | https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/condition_resource_contains.go#L29-L54 | train |
ory/ladon | matcher_regexp.go | Matches | func (m *RegexpMatcher) Matches(p Policy, haystack []string, needle string) (bool, error) {
var reg *regexp.Regexp
var err error
for _, h := range haystack {
// This means that the current haystack item does not contain a regular expression
if strings.Count(h, string(p.GetStartDelimiter())) == 0 {
// If we have a simple string match, we've got a match!
if h == needle {
return true, nil
}
// Not string match, but also no regexp, continue with next haystack item
continue
}
if reg = m.get(h); reg != nil {
if reg.MatchString(needle) {
return true, nil
}
continue
}
reg, err = compiler.CompileRegex(h, p.GetStartDelimiter(), p.GetEndDelimiter())
if err != nil {
return false, errors.WithStack(err)
}
m.set(h, reg)
if reg.MatchString(needle) {
return true, nil
}
}
return false, nil
} | go | func (m *RegexpMatcher) Matches(p Policy, haystack []string, needle string) (bool, error) {
var reg *regexp.Regexp
var err error
for _, h := range haystack {
// This means that the current haystack item does not contain a regular expression
if strings.Count(h, string(p.GetStartDelimiter())) == 0 {
// If we have a simple string match, we've got a match!
if h == needle {
return true, nil
}
// Not string match, but also no regexp, continue with next haystack item
continue
}
if reg = m.get(h); reg != nil {
if reg.MatchString(needle) {
return true, nil
}
continue
}
reg, err = compiler.CompileRegex(h, p.GetStartDelimiter(), p.GetEndDelimiter())
if err != nil {
return false, errors.WithStack(err)
}
m.set(h, reg)
if reg.MatchString(needle) {
return true, nil
}
}
return false, nil
} | [
"func",
"(",
"m",
"*",
"RegexpMatcher",
")",
"Matches",
"(",
"p",
"Policy",
",",
"haystack",
"[",
"]",
"string",
",",
"needle",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"var",
"reg",
"*",
"regexp",
".",
"Regexp",
"\n",
"var",
"err",
"err... | // Matches a needle with an array of regular expressions and returns true if a match was found. | [
"Matches",
"a",
"needle",
"with",
"an",
"array",
"of",
"regular",
"expressions",
"and",
"returns",
"true",
"if",
"a",
"match",
"was",
"found",
"."
] | 7f1c376a9a46cd4e09f90d3940e81cd963b0d87d | https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/matcher_regexp.go#L66-L100 | train |
ory/ladon | condition.go | AddCondition | func (cs Conditions) AddCondition(key string, c Condition) {
cs[key] = c
} | go | func (cs Conditions) AddCondition(key string, c Condition) {
cs[key] = c
} | [
"func",
"(",
"cs",
"Conditions",
")",
"AddCondition",
"(",
"key",
"string",
",",
"c",
"Condition",
")",
"{",
"cs",
"[",
"key",
"]",
"=",
"c",
"\n",
"}"
] | // AddCondition adds a condition to the collection. | [
"AddCondition",
"adds",
"a",
"condition",
"to",
"the",
"collection",
"."
] | 7f1c376a9a46cd4e09f90d3940e81cd963b0d87d | https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/condition.go#L42-L44 | train |
ory/ladon | condition.go | MarshalJSON | func (cs Conditions) MarshalJSON() ([]byte, error) {
out := make(map[string]*jsonCondition, len(cs))
for k, c := range cs {
raw, err := json.Marshal(c)
if err != nil {
return []byte{}, errors.WithStack(err)
}
out[k] = &jsonCondition{
Type: c.GetName(),
Options: json.RawMessage(raw),
}
}
return json.Marshal(out)
} | go | func (cs Conditions) MarshalJSON() ([]byte, error) {
out := make(map[string]*jsonCondition, len(cs))
for k, c := range cs {
raw, err := json.Marshal(c)
if err != nil {
return []byte{}, errors.WithStack(err)
}
out[k] = &jsonCondition{
Type: c.GetName(),
Options: json.RawMessage(raw),
}
}
return json.Marshal(out)
} | [
"func",
"(",
"cs",
"Conditions",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"out",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"jsonCondition",
",",
"len",
"(",
"cs",
")",
")",
"\n",
"for",
"k",
",",
"c"... | // MarshalJSON marshals a list of conditions to json. | [
"MarshalJSON",
"marshals",
"a",
"list",
"of",
"conditions",
"to",
"json",
"."
] | 7f1c376a9a46cd4e09f90d3940e81cd963b0d87d | https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/condition.go#L47-L62 | train |
ory/ladon | condition.go | UnmarshalJSON | func (cs Conditions) UnmarshalJSON(data []byte) error {
if cs == nil {
return errors.New("Can not be nil")
}
var jcs map[string]jsonCondition
var dc Condition
if err := json.Unmarshal(data, &jcs); err != nil {
return errors.WithStack(err)
}
for k, jc := range jcs {
var found bool
for name, c := range ConditionFactories {
if name == jc.Type {
found = true
dc = c()
if len(jc.Options) == 0 {
cs[k] = dc
break
}
if err := json.Unmarshal(jc.Options, dc); err != nil {
return errors.WithStack(err)
}
cs[k] = dc
break
}
}
if !found {
return errors.Errorf("Could not find condition type %s", jc.Type)
}
}
return nil
} | go | func (cs Conditions) UnmarshalJSON(data []byte) error {
if cs == nil {
return errors.New("Can not be nil")
}
var jcs map[string]jsonCondition
var dc Condition
if err := json.Unmarshal(data, &jcs); err != nil {
return errors.WithStack(err)
}
for k, jc := range jcs {
var found bool
for name, c := range ConditionFactories {
if name == jc.Type {
found = true
dc = c()
if len(jc.Options) == 0 {
cs[k] = dc
break
}
if err := json.Unmarshal(jc.Options, dc); err != nil {
return errors.WithStack(err)
}
cs[k] = dc
break
}
}
if !found {
return errors.Errorf("Could not find condition type %s", jc.Type)
}
}
return nil
} | [
"func",
"(",
"cs",
"Conditions",
")",
"UnmarshalJSON",
"(",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"if",
"cs",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"Can not be nil\"",
")",
"\n",
"}",
"\n",
"var",
"jcs",
"map",
"[",
"string"... | // UnmarshalJSON unmarshals a list of conditions from json. | [
"UnmarshalJSON",
"unmarshals",
"a",
"list",
"of",
"conditions",
"from",
"json",
"."
] | 7f1c376a9a46cd4e09f90d3940e81cd963b0d87d | https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/condition.go#L65-L104 | train |
ory/ladon | condition_string_equal.go | Fulfills | func (c *StringEqualCondition) Fulfills(value interface{}, _ *Request) bool {
s, ok := value.(string)
return ok && s == c.Equals
} | go | func (c *StringEqualCondition) Fulfills(value interface{}, _ *Request) bool {
s, ok := value.(string)
return ok && s == c.Equals
} | [
"func",
"(",
"c",
"*",
"StringEqualCondition",
")",
"Fulfills",
"(",
"value",
"interface",
"{",
"}",
",",
"_",
"*",
"Request",
")",
"bool",
"{",
"s",
",",
"ok",
":=",
"value",
".",
"(",
"string",
")",
"\n",
"return",
"ok",
"&&",
"s",
"==",
"c",
"... | // Fulfills returns true if the given value is a string and is the
// same as in StringEqualCondition.Equals | [
"Fulfills",
"returns",
"true",
"if",
"the",
"given",
"value",
"is",
"a",
"string",
"and",
"is",
"the",
"same",
"as",
"in",
"StringEqualCondition",
".",
"Equals"
] | 7f1c376a9a46cd4e09f90d3940e81cd963b0d87d | https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/condition_string_equal.go#L31-L35 | train |
ory/ladon | compiler/regex.go | delimiterIndices | func delimiterIndices(s string, delimiterStart, delimiterEnd byte) ([]int, error) {
var level, idx int
idxs := make([]int, 0)
for i := 0; i < len(s); i++ {
switch s[i] {
case delimiterStart:
if level++; level == 1 {
idx = i
}
case delimiterEnd:
if level--; level == 0 {
idxs = append(idxs, idx, i+1)
} else if level < 0 {
return nil, fmt.Errorf(`Unbalanced braces in "%q"`, s)
}
}
}
if level != 0 {
return nil, fmt.Errorf(`Unbalanced braces in "%q"`, s)
}
return idxs, nil
} | go | func delimiterIndices(s string, delimiterStart, delimiterEnd byte) ([]int, error) {
var level, idx int
idxs := make([]int, 0)
for i := 0; i < len(s); i++ {
switch s[i] {
case delimiterStart:
if level++; level == 1 {
idx = i
}
case delimiterEnd:
if level--; level == 0 {
idxs = append(idxs, idx, i+1)
} else if level < 0 {
return nil, fmt.Errorf(`Unbalanced braces in "%q"`, s)
}
}
}
if level != 0 {
return nil, fmt.Errorf(`Unbalanced braces in "%q"`, s)
}
return idxs, nil
} | [
"func",
"delimiterIndices",
"(",
"s",
"string",
",",
"delimiterStart",
",",
"delimiterEnd",
"byte",
")",
"(",
"[",
"]",
"int",
",",
"error",
")",
"{",
"var",
"level",
",",
"idx",
"int",
"\n",
"idxs",
":=",
"make",
"(",
"[",
"]",
"int",
",",
"0",
")... | // delimiterIndices returns the first level delimiter indices from a string.
// It returns an error in case of unbalanced delimiters. | [
"delimiterIndices",
"returns",
"the",
"first",
"level",
"delimiter",
"indices",
"from",
"a",
"string",
".",
"It",
"returns",
"an",
"error",
"in",
"case",
"of",
"unbalanced",
"delimiters",
"."
] | 7f1c376a9a46cd4e09f90d3940e81cd963b0d87d | https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/compiler/regex.go#L75-L98 | train |
ory/ladon | policy.go | UnmarshalJSON | func (p *DefaultPolicy) UnmarshalJSON(data []byte) error {
var pol = struct {
ID string `json:"id" gorethink:"id"`
Description string `json:"description" gorethink:"description"`
Subjects []string `json:"subjects" gorethink:"subjects"`
Effect string `json:"effect" gorethink:"effect"`
Resources []string `json:"resources" gorethink:"resources"`
Actions []string `json:"actions" gorethink:"actions"`
Conditions Conditions `json:"conditions" gorethink:"conditions"`
Meta []byte `json:"meta" gorethink:"meta"`
}{
Conditions: Conditions{},
}
if err := json.Unmarshal(data, &pol); err != nil {
return errors.WithStack(err)
}
*p = *&DefaultPolicy{
ID: pol.ID,
Description: pol.Description,
Subjects: pol.Subjects,
Effect: pol.Effect,
Resources: pol.Resources,
Actions: pol.Actions,
Conditions: pol.Conditions,
Meta: pol.Meta,
}
return nil
} | go | func (p *DefaultPolicy) UnmarshalJSON(data []byte) error {
var pol = struct {
ID string `json:"id" gorethink:"id"`
Description string `json:"description" gorethink:"description"`
Subjects []string `json:"subjects" gorethink:"subjects"`
Effect string `json:"effect" gorethink:"effect"`
Resources []string `json:"resources" gorethink:"resources"`
Actions []string `json:"actions" gorethink:"actions"`
Conditions Conditions `json:"conditions" gorethink:"conditions"`
Meta []byte `json:"meta" gorethink:"meta"`
}{
Conditions: Conditions{},
}
if err := json.Unmarshal(data, &pol); err != nil {
return errors.WithStack(err)
}
*p = *&DefaultPolicy{
ID: pol.ID,
Description: pol.Description,
Subjects: pol.Subjects,
Effect: pol.Effect,
Resources: pol.Resources,
Actions: pol.Actions,
Conditions: pol.Conditions,
Meta: pol.Meta,
}
return nil
} | [
"func",
"(",
"p",
"*",
"DefaultPolicy",
")",
"UnmarshalJSON",
"(",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"var",
"pol",
"=",
"struct",
"{",
"ID",
"string",
"`json:\"id\" gorethink:\"id\"`",
"\n",
"Description",
"string",
"`json:\"description\" gorethink:\"de... | // UnmarshalJSON overwrite own policy with values of the given in policy in JSON format | [
"UnmarshalJSON",
"overwrite",
"own",
"policy",
"with",
"values",
"of",
"the",
"given",
"in",
"policy",
"in",
"JSON",
"format"
] | 7f1c376a9a46cd4e09f90d3940e81cd963b0d87d | https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/policy.go#L81-L110 | train |
sajari/docconv | tidy.go | Tidy | func Tidy(r io.Reader, xmlIn bool) ([]byte, error) {
f, err := ioutil.TempFile("/tmp", "sajari-convert-")
if err != nil {
return nil, err
}
defer os.Remove(f.Name())
io.Copy(f, r)
var output []byte
if xmlIn {
output, err = exec.Command("tidy", "-xml", "-numeric", "-asxml", "-quiet", "-utf8", f.Name()).Output()
} else {
output, err = exec.Command("tidy", "-numeric", "-asxml", "-quiet", "-utf8", f.Name()).Output()
}
if err != nil && err.Error() != "exit status 1" {
return nil, err
}
return output, nil
} | go | func Tidy(r io.Reader, xmlIn bool) ([]byte, error) {
f, err := ioutil.TempFile("/tmp", "sajari-convert-")
if err != nil {
return nil, err
}
defer os.Remove(f.Name())
io.Copy(f, r)
var output []byte
if xmlIn {
output, err = exec.Command("tidy", "-xml", "-numeric", "-asxml", "-quiet", "-utf8", f.Name()).Output()
} else {
output, err = exec.Command("tidy", "-numeric", "-asxml", "-quiet", "-utf8", f.Name()).Output()
}
if err != nil && err.Error() != "exit status 1" {
return nil, err
}
return output, nil
} | [
"func",
"Tidy",
"(",
"r",
"io",
".",
"Reader",
",",
"xmlIn",
"bool",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"ioutil",
".",
"TempFile",
"(",
"\"/tmp\"",
",",
"\"sajari-convert-\"",
")",
"\n",
"if",
"err",
"!=",
... | // Tidy attempts to tidy up XML.
// Errors & warnings are deliberately suppressed as underlying tools
// throw warnings very easily. | [
"Tidy",
"attempts",
"to",
"tidy",
"up",
"XML",
".",
"Errors",
"&",
"warnings",
"are",
"deliberately",
"suppressed",
"as",
"underlying",
"tools",
"throw",
"warnings",
"very",
"easily",
"."
] | eedabc494f8e97c31f94c70453273f16dbecbc6f | https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/tidy.go#L13-L32 | train |
sajari/docconv | local.go | Done | func (l *LocalFile) Done() {
l.Close()
if l.unlink {
os.Remove(l.Name())
}
} | go | func (l *LocalFile) Done() {
l.Close()
if l.unlink {
os.Remove(l.Name())
}
} | [
"func",
"(",
"l",
"*",
"LocalFile",
")",
"Done",
"(",
")",
"{",
"l",
".",
"Close",
"(",
")",
"\n",
"if",
"l",
".",
"unlink",
"{",
"os",
".",
"Remove",
"(",
"l",
".",
"Name",
"(",
")",
")",
"\n",
"}",
"\n",
"}"
] | // Done cleans up all resources. | [
"Done",
"cleans",
"up",
"all",
"resources",
"."
] | eedabc494f8e97c31f94c70453273f16dbecbc6f | https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/local.go#L46-L51 | train |
sajari/docconv | odt.go | ConvertODT | func ConvertODT(r io.Reader) (string, map[string]string, error) {
meta := make(map[string]string)
var textBody string
b, err := ioutil.ReadAll(r)
if err != nil {
return "", nil, err
}
zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b)))
if err != nil {
return "", nil, fmt.Errorf("error unzipping data: %v", err)
}
for _, f := range zr.File {
switch f.Name {
case "meta.xml":
rc, err := f.Open()
if err != nil {
return "", nil, fmt.Errorf("error extracting '%v' from archive: %v", f.Name, err)
}
defer rc.Close()
info, err := XMLToMap(rc)
if err != nil {
return "", nil, fmt.Errorf("error parsing '%v': %v", f.Name, err)
}
if tmp, ok := info["creator"]; ok {
meta["Author"] = tmp
}
if tmp, ok := info["date"]; ok {
if t, err := time.Parse("2006-01-02T15:04:05", tmp); err == nil {
meta["ModifiedDate"] = fmt.Sprintf("%d", t.Unix())
}
}
if tmp, ok := info["creation-date"]; ok {
if t, err := time.Parse("2006-01-02T15:04:05", tmp); err == nil {
meta["CreatedDate"] = fmt.Sprintf("%d", t.Unix())
}
}
case "content.xml":
rc, err := f.Open()
if err != nil {
return "", nil, fmt.Errorf("error extracting '%v' from archive: %v", f.Name, err)
}
defer rc.Close()
textBody, err = XMLToText(rc, []string{"br", "p", "tab"}, []string{}, true)
if err != nil {
return "", nil, fmt.Errorf("error parsing '%v': %v", f.Name, err)
}
}
}
return textBody, meta, nil
} | go | func ConvertODT(r io.Reader) (string, map[string]string, error) {
meta := make(map[string]string)
var textBody string
b, err := ioutil.ReadAll(r)
if err != nil {
return "", nil, err
}
zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b)))
if err != nil {
return "", nil, fmt.Errorf("error unzipping data: %v", err)
}
for _, f := range zr.File {
switch f.Name {
case "meta.xml":
rc, err := f.Open()
if err != nil {
return "", nil, fmt.Errorf("error extracting '%v' from archive: %v", f.Name, err)
}
defer rc.Close()
info, err := XMLToMap(rc)
if err != nil {
return "", nil, fmt.Errorf("error parsing '%v': %v", f.Name, err)
}
if tmp, ok := info["creator"]; ok {
meta["Author"] = tmp
}
if tmp, ok := info["date"]; ok {
if t, err := time.Parse("2006-01-02T15:04:05", tmp); err == nil {
meta["ModifiedDate"] = fmt.Sprintf("%d", t.Unix())
}
}
if tmp, ok := info["creation-date"]; ok {
if t, err := time.Parse("2006-01-02T15:04:05", tmp); err == nil {
meta["CreatedDate"] = fmt.Sprintf("%d", t.Unix())
}
}
case "content.xml":
rc, err := f.Open()
if err != nil {
return "", nil, fmt.Errorf("error extracting '%v' from archive: %v", f.Name, err)
}
defer rc.Close()
textBody, err = XMLToText(rc, []string{"br", "p", "tab"}, []string{}, true)
if err != nil {
return "", nil, fmt.Errorf("error parsing '%v': %v", f.Name, err)
}
}
}
return textBody, meta, nil
} | [
"func",
"ConvertODT",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"string",
",",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"meta",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"var",
"textBody",
"string",
"\n",... | // ConvertODT converts a ODT file to text | [
"ConvertODT",
"converts",
"a",
"ODT",
"file",
"to",
"text"
] | eedabc494f8e97c31f94c70453273f16dbecbc6f | https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/odt.go#L13-L69 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.