id
int32 0
167k
| repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
sequence | docstring
stringlengths 6
2.61k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
1,200 | mweagle/Sparta | aws/step/step.go | WithRetriers | func (ps *ParallelState) WithRetriers(retries ...*TaskRetry) *ParallelState {
if ps.Retriers == nil {
ps.Retriers = make([]*TaskRetry, 0)
}
ps.Retriers = append(ps.Retriers, retries...)
return ps
} | go | func (ps *ParallelState) WithRetriers(retries ...*TaskRetry) *ParallelState {
if ps.Retriers == nil {
ps.Retriers = make([]*TaskRetry, 0)
}
ps.Retriers = append(ps.Retriers, retries...)
return ps
} | [
"func",
"(",
"ps",
"*",
"ParallelState",
")",
"WithRetriers",
"(",
"retries",
"...",
"*",
"TaskRetry",
")",
"*",
"ParallelState",
"{",
"if",
"ps",
".",
"Retriers",
"==",
"nil",
"{",
"ps",
".",
"Retriers",
"=",
"make",
"(",
"[",
"]",
"*",
"TaskRetry",
",",
"0",
")",
"\n",
"}",
"\n",
"ps",
".",
"Retriers",
"=",
"append",
"(",
"ps",
".",
"Retriers",
",",
"retries",
"...",
")",
"\n",
"return",
"ps",
"\n",
"}"
] | // WithRetriers is the fluent builder for TaskState | [
"WithRetriers",
"is",
"the",
"fluent",
"builder",
"for",
"TaskState"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/step.go#L1360-L1366 |
1,201 | mweagle/Sparta | aws/step/step.go | WithCatchers | func (ps *ParallelState) WithCatchers(catch ...*TaskCatch) *ParallelState {
if ps.Catchers == nil {
ps.Catchers = make([]*TaskCatch, 0)
}
ps.Catchers = append(ps.Catchers, catch...)
return ps
} | go | func (ps *ParallelState) WithCatchers(catch ...*TaskCatch) *ParallelState {
if ps.Catchers == nil {
ps.Catchers = make([]*TaskCatch, 0)
}
ps.Catchers = append(ps.Catchers, catch...)
return ps
} | [
"func",
"(",
"ps",
"*",
"ParallelState",
")",
"WithCatchers",
"(",
"catch",
"...",
"*",
"TaskCatch",
")",
"*",
"ParallelState",
"{",
"if",
"ps",
".",
"Catchers",
"==",
"nil",
"{",
"ps",
".",
"Catchers",
"=",
"make",
"(",
"[",
"]",
"*",
"TaskCatch",
",",
"0",
")",
"\n",
"}",
"\n",
"ps",
".",
"Catchers",
"=",
"append",
"(",
"ps",
".",
"Catchers",
",",
"catch",
"...",
")",
"\n",
"return",
"ps",
"\n",
"}"
] | // WithCatchers is the fluent builder for TaskState | [
"WithCatchers",
"is",
"the",
"fluent",
"builder",
"for",
"TaskState"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/step.go#L1369-L1375 |
1,202 | mweagle/Sparta | aws/step/step.go | NewParallelState | func NewParallelState(parallelStateName string, states StateMachine) *ParallelState {
return &ParallelState{
baseInnerState: baseInnerState{
name: parallelStateName,
id: rand.Int63(),
},
States: states,
}
} | go | func NewParallelState(parallelStateName string, states StateMachine) *ParallelState {
return &ParallelState{
baseInnerState: baseInnerState{
name: parallelStateName,
id: rand.Int63(),
},
States: states,
}
} | [
"func",
"NewParallelState",
"(",
"parallelStateName",
"string",
",",
"states",
"StateMachine",
")",
"*",
"ParallelState",
"{",
"return",
"&",
"ParallelState",
"{",
"baseInnerState",
":",
"baseInnerState",
"{",
"name",
":",
"parallelStateName",
",",
"id",
":",
"rand",
".",
"Int63",
"(",
")",
",",
"}",
",",
"States",
":",
"states",
",",
"}",
"\n",
"}"
] | // NewParallelState returns a "ParallelState" with the supplied
// information | [
"NewParallelState",
"returns",
"a",
"ParallelState",
"with",
"the",
"supplied",
"information"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/step.go#L1436-L1444 |
1,203 | mweagle/Sparta | aws/step/step.go | Comment | func (sm *StateMachine) Comment(comment string) *StateMachine {
sm.comment = comment
return sm
} | go | func (sm *StateMachine) Comment(comment string) *StateMachine {
sm.comment = comment
return sm
} | [
"func",
"(",
"sm",
"*",
"StateMachine",
")",
"Comment",
"(",
"comment",
"string",
")",
"*",
"StateMachine",
"{",
"sm",
".",
"comment",
"=",
"comment",
"\n",
"return",
"sm",
"\n",
"}"
] | //Comment sets the StateMachine comment | [
"Comment",
"sets",
"the",
"StateMachine",
"comment"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/step.go#L1461-L1464 |
1,204 | mweagle/Sparta | aws/step/step.go | WithRoleArn | func (sm *StateMachine) WithRoleArn(roleArn gocf.Stringable) *StateMachine {
sm.roleArn = roleArn
return sm
} | go | func (sm *StateMachine) WithRoleArn(roleArn gocf.Stringable) *StateMachine {
sm.roleArn = roleArn
return sm
} | [
"func",
"(",
"sm",
"*",
"StateMachine",
")",
"WithRoleArn",
"(",
"roleArn",
"gocf",
".",
"Stringable",
")",
"*",
"StateMachine",
"{",
"sm",
".",
"roleArn",
"=",
"roleArn",
"\n",
"return",
"sm",
"\n",
"}"
] | //WithRoleArn sets the state machine roleArn | [
"WithRoleArn",
"sets",
"the",
"state",
"machine",
"roleArn"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/step.go#L1467-L1470 |
1,205 | mweagle/Sparta | aws/step/step.go | validate | func (sm *StateMachine) validate() []error {
validationErrors := make([]error, 0)
if sm.stateDefinitionError != nil {
validationErrors = append(validationErrors, sm.stateDefinitionError)
}
// TODO - add Catcher validator
/*
Each Catcher MUST contain a field named “ErrorEquals”, specified exactly as with the Retrier “ErrorEquals” field, and a field named “Next” whose value MUST be a string exactly matching a State Name.
When a state reports an error and either there is no Retry field, or retries have failed to resolve the error, the interpreter scans through the Catchers in array order, and when the Error Name appears in the value of a Catcher’s “ErrorEquals” field, transitions the machine to the state named in the value of the “Next” field.
The reserved name “States.ALL” appearing in a Retrier’s “ErrorEquals” field is a wild-card and matches any Error Name. Such a value MUST appear alone in the “ErrorEquals” array and MUST appear in the last Catcher in the “Catch” array.
*/
return validationErrors
} | go | func (sm *StateMachine) validate() []error {
validationErrors := make([]error, 0)
if sm.stateDefinitionError != nil {
validationErrors = append(validationErrors, sm.stateDefinitionError)
}
// TODO - add Catcher validator
/*
Each Catcher MUST contain a field named “ErrorEquals”, specified exactly as with the Retrier “ErrorEquals” field, and a field named “Next” whose value MUST be a string exactly matching a State Name.
When a state reports an error and either there is no Retry field, or retries have failed to resolve the error, the interpreter scans through the Catchers in array order, and when the Error Name appears in the value of a Catcher’s “ErrorEquals” field, transitions the machine to the state named in the value of the “Next” field.
The reserved name “States.ALL” appearing in a Retrier’s “ErrorEquals” field is a wild-card and matches any Error Name. Such a value MUST appear alone in the “ErrorEquals” array and MUST appear in the last Catcher in the “Catch” array.
*/
return validationErrors
} | [
"func",
"(",
"sm",
"*",
"StateMachine",
")",
"validate",
"(",
")",
"[",
"]",
"error",
"{",
"validationErrors",
":=",
"make",
"(",
"[",
"]",
"error",
",",
"0",
")",
"\n",
"if",
"sm",
".",
"stateDefinitionError",
"!=",
"nil",
"{",
"validationErrors",
"=",
"append",
"(",
"validationErrors",
",",
"sm",
".",
"stateDefinitionError",
")",
"\n",
"}",
"\n\n",
"// TODO - add Catcher validator",
"/*\n\t\tEach Catcher MUST contain a field named “ErrorEquals”, specified exactly as with the Retrier “ErrorEquals” field, and a field named “Next” whose value MUST be a string exactly matching a State Name.\n\n\t\tWhen a state reports an error and either there is no Retry field, or retries have failed to resolve the error, the interpreter scans through the Catchers in array order, and when the Error Name appears in the value of a Catcher’s “ErrorEquals” field, transitions the machine to the state named in the value of the “Next” field.\n\n\t\tThe reserved name “States.ALL” appearing in a Retrier’s “ErrorEquals” field is a wild-card and matches any Error Name. Such a value MUST appear alone in the “ErrorEquals” array and MUST appear in the last Catcher in the “Catch” array.\n\t*/",
"return",
"validationErrors",
"\n",
"}"
] | // validate performs any validation against the state machine
// prior to marshaling | [
"validate",
"performs",
"any",
"validation",
"against",
"the",
"state",
"machine",
"prior",
"to",
"marshaling"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/step.go#L1474-L1489 |
1,206 | mweagle/Sparta | aws/step/step.go | StateMachineDecorator | func (sm *StateMachine) StateMachineDecorator() sparta.ServiceDecoratorHookFunc {
cfName := sparta.CloudFormationResourceName("StateMachine", "StateMachine")
return sm.StateMachineNamedDecorator(cfName)
} | go | func (sm *StateMachine) StateMachineDecorator() sparta.ServiceDecoratorHookFunc {
cfName := sparta.CloudFormationResourceName("StateMachine", "StateMachine")
return sm.StateMachineNamedDecorator(cfName)
} | [
"func",
"(",
"sm",
"*",
"StateMachine",
")",
"StateMachineDecorator",
"(",
")",
"sparta",
".",
"ServiceDecoratorHookFunc",
"{",
"cfName",
":=",
"sparta",
".",
"CloudFormationResourceName",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"sm",
".",
"StateMachineNamedDecorator",
"(",
"cfName",
")",
"\n",
"}"
] | // StateMachineDecorator is a decorator that returns a default
// CloudFormationResource named decorator | [
"StateMachineDecorator",
"is",
"a",
"decorator",
"that",
"returns",
"a",
"default",
"CloudFormationResource",
"named",
"decorator"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/step.go#L1493-L1496 |
1,207 | mweagle/Sparta | aws/step/step.go | NewStateMachine | func NewStateMachine(stateMachineName string,
startState TransitionState) *StateMachine {
uniqueStates := make(map[string]MachineState)
pendingStates := []MachineState{startState}
duplicateStateNames := make(map[string]bool)
nodeVisited := func(node MachineState) bool {
if node == nil {
return true
}
_, visited := uniqueStates[node.Name()]
return visited
}
for len(pendingStates) != 0 {
headState, tailStates := pendingStates[0], pendingStates[1:]
uniqueStates[headState.Name()] = headState
switch stateNode := headState.(type) {
case *ChoiceState:
for _, eachChoice := range stateNode.Choices {
if !nodeVisited(eachChoice.nextState()) {
tailStates = append(tailStates, eachChoice.nextState())
}
}
if !nodeVisited(stateNode.Default) {
tailStates = append(tailStates, stateNode.Default)
}
case TransitionState:
for _, eachAdjacentState := range stateNode.AdjacentStates() {
if !nodeVisited(eachAdjacentState) {
tailStates = append(tailStates, eachAdjacentState)
}
}
// Are there any Catchers in here?
}
pendingStates = tailStates
}
// Walk all the states and assemble them into the states slice
sm := &StateMachine{
name: stateMachineName,
startAt: startState,
uniqueStates: uniqueStates,
}
// Store duplicate state names
if len(duplicateStateNames) != 0 {
sm.stateDefinitionError = fmt.Errorf("duplicate state names: %#v", duplicateStateNames)
}
return sm
} | go | func NewStateMachine(stateMachineName string,
startState TransitionState) *StateMachine {
uniqueStates := make(map[string]MachineState)
pendingStates := []MachineState{startState}
duplicateStateNames := make(map[string]bool)
nodeVisited := func(node MachineState) bool {
if node == nil {
return true
}
_, visited := uniqueStates[node.Name()]
return visited
}
for len(pendingStates) != 0 {
headState, tailStates := pendingStates[0], pendingStates[1:]
uniqueStates[headState.Name()] = headState
switch stateNode := headState.(type) {
case *ChoiceState:
for _, eachChoice := range stateNode.Choices {
if !nodeVisited(eachChoice.nextState()) {
tailStates = append(tailStates, eachChoice.nextState())
}
}
if !nodeVisited(stateNode.Default) {
tailStates = append(tailStates, stateNode.Default)
}
case TransitionState:
for _, eachAdjacentState := range stateNode.AdjacentStates() {
if !nodeVisited(eachAdjacentState) {
tailStates = append(tailStates, eachAdjacentState)
}
}
// Are there any Catchers in here?
}
pendingStates = tailStates
}
// Walk all the states and assemble them into the states slice
sm := &StateMachine{
name: stateMachineName,
startAt: startState,
uniqueStates: uniqueStates,
}
// Store duplicate state names
if len(duplicateStateNames) != 0 {
sm.stateDefinitionError = fmt.Errorf("duplicate state names: %#v", duplicateStateNames)
}
return sm
} | [
"func",
"NewStateMachine",
"(",
"stateMachineName",
"string",
",",
"startState",
"TransitionState",
")",
"*",
"StateMachine",
"{",
"uniqueStates",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"MachineState",
")",
"\n",
"pendingStates",
":=",
"[",
"]",
"MachineState",
"{",
"startState",
"}",
"\n",
"duplicateStateNames",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"bool",
")",
"\n\n",
"nodeVisited",
":=",
"func",
"(",
"node",
"MachineState",
")",
"bool",
"{",
"if",
"node",
"==",
"nil",
"{",
"return",
"true",
"\n",
"}",
"\n",
"_",
",",
"visited",
":=",
"uniqueStates",
"[",
"node",
".",
"Name",
"(",
")",
"]",
"\n",
"return",
"visited",
"\n",
"}",
"\n\n",
"for",
"len",
"(",
"pendingStates",
")",
"!=",
"0",
"{",
"headState",
",",
"tailStates",
":=",
"pendingStates",
"[",
"0",
"]",
",",
"pendingStates",
"[",
"1",
":",
"]",
"\n",
"uniqueStates",
"[",
"headState",
".",
"Name",
"(",
")",
"]",
"=",
"headState",
"\n\n",
"switch",
"stateNode",
":=",
"headState",
".",
"(",
"type",
")",
"{",
"case",
"*",
"ChoiceState",
":",
"for",
"_",
",",
"eachChoice",
":=",
"range",
"stateNode",
".",
"Choices",
"{",
"if",
"!",
"nodeVisited",
"(",
"eachChoice",
".",
"nextState",
"(",
")",
")",
"{",
"tailStates",
"=",
"append",
"(",
"tailStates",
",",
"eachChoice",
".",
"nextState",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"nodeVisited",
"(",
"stateNode",
".",
"Default",
")",
"{",
"tailStates",
"=",
"append",
"(",
"tailStates",
",",
"stateNode",
".",
"Default",
")",
"\n",
"}",
"\n\n",
"case",
"TransitionState",
":",
"for",
"_",
",",
"eachAdjacentState",
":=",
"range",
"stateNode",
".",
"AdjacentStates",
"(",
")",
"{",
"if",
"!",
"nodeVisited",
"(",
"eachAdjacentState",
")",
"{",
"tailStates",
"=",
"append",
"(",
"tailStates",
",",
"eachAdjacentState",
")",
"\n",
"}",
"\n",
"}",
"\n",
"// Are there any Catchers in here?",
"}",
"\n",
"pendingStates",
"=",
"tailStates",
"\n",
"}",
"\n\n",
"// Walk all the states and assemble them into the states slice",
"sm",
":=",
"&",
"StateMachine",
"{",
"name",
":",
"stateMachineName",
",",
"startAt",
":",
"startState",
",",
"uniqueStates",
":",
"uniqueStates",
",",
"}",
"\n",
"// Store duplicate state names",
"if",
"len",
"(",
"duplicateStateNames",
")",
"!=",
"0",
"{",
"sm",
".",
"stateDefinitionError",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"duplicateStateNames",
")",
"\n",
"}",
"\n",
"return",
"sm",
"\n",
"}"
] | // NewStateMachine returns a new StateMachine instance | [
"NewStateMachine",
"returns",
"a",
"new",
"StateMachine",
"instance"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/step.go#L1629-L1680 |
1,208 | mweagle/Sparta | magefile/actions.go | Log | func Log(formatSpecifier string, args ...interface{}) {
if mg.Verbose() {
if len(args) != 0 {
log.Printf(formatSpecifier, args...)
} else {
log.Print(formatSpecifier)
}
}
} | go | func Log(formatSpecifier string, args ...interface{}) {
if mg.Verbose() {
if len(args) != 0 {
log.Printf(formatSpecifier, args...)
} else {
log.Print(formatSpecifier)
}
}
} | [
"func",
"Log",
"(",
"formatSpecifier",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"if",
"mg",
".",
"Verbose",
"(",
")",
"{",
"if",
"len",
"(",
"args",
")",
"!=",
"0",
"{",
"log",
".",
"Printf",
"(",
"formatSpecifier",
",",
"args",
"...",
")",
"\n",
"}",
"else",
"{",
"log",
".",
"Print",
"(",
"formatSpecifier",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Log is a mage verbose aware log function | [
"Log",
"is",
"a",
"mage",
"verbose",
"aware",
"log",
"function"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/magefile/actions.go#L14-L22 |
1,209 | mweagle/Sparta | magefile/actions.go | Script | func Script(commands [][]string) error {
for _, eachCommand := range commands {
var commandErr error
if len(eachCommand) <= 1 {
commandErr = sh.Run(eachCommand[0])
} else {
commandErr = sh.Run(eachCommand[0], eachCommand[1:]...)
}
if commandErr != nil {
return commandErr
}
}
return nil
} | go | func Script(commands [][]string) error {
for _, eachCommand := range commands {
var commandErr error
if len(eachCommand) <= 1 {
commandErr = sh.Run(eachCommand[0])
} else {
commandErr = sh.Run(eachCommand[0], eachCommand[1:]...)
}
if commandErr != nil {
return commandErr
}
}
return nil
} | [
"func",
"Script",
"(",
"commands",
"[",
"]",
"[",
"]",
"string",
")",
"error",
"{",
"for",
"_",
",",
"eachCommand",
":=",
"range",
"commands",
"{",
"var",
"commandErr",
"error",
"\n",
"if",
"len",
"(",
"eachCommand",
")",
"<=",
"1",
"{",
"commandErr",
"=",
"sh",
".",
"Run",
"(",
"eachCommand",
"[",
"0",
"]",
")",
"\n",
"}",
"else",
"{",
"commandErr",
"=",
"sh",
".",
"Run",
"(",
"eachCommand",
"[",
"0",
"]",
",",
"eachCommand",
"[",
"1",
":",
"]",
"...",
")",
"\n",
"}",
"\n",
"if",
"commandErr",
"!=",
"nil",
"{",
"return",
"commandErr",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Script is a 2d array of commands to run as a script | [
"Script",
"is",
"a",
"2d",
"array",
"of",
"commands",
"to",
"run",
"as",
"a",
"script"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/magefile/actions.go#L25-L38 |
1,210 | mweagle/Sparta | magefile/actions.go | ApplyToSource | func ApplyToSource(fileExtension string,
ignoredSubdirectories []string,
commandParts ...string) error {
if len(commandParts) <= 0 {
return errors.New("applyToSource requires a command to apply to source files")
}
eligibleSourceFiles, eligibleSourceFilesErr := sourceFilesOfType(fileExtension, ignoredSubdirectories)
if eligibleSourceFilesErr != nil {
return eligibleSourceFilesErr
}
Log(header)
Log("Applying `%s` to %d `*.%s` source files", commandParts[0], len(eligibleSourceFiles), fileExtension)
Log(header)
commandArgs := []string{}
if len(commandParts) > 1 {
commandArgs = append(commandArgs, commandParts[1:]...)
}
for _, eachFile := range eligibleSourceFiles {
applyArgs := append(commandArgs, eachFile)
applyErr := sh.Run(commandParts[0], applyArgs...)
if applyErr != nil {
return applyErr
}
}
return nil
} | go | func ApplyToSource(fileExtension string,
ignoredSubdirectories []string,
commandParts ...string) error {
if len(commandParts) <= 0 {
return errors.New("applyToSource requires a command to apply to source files")
}
eligibleSourceFiles, eligibleSourceFilesErr := sourceFilesOfType(fileExtension, ignoredSubdirectories)
if eligibleSourceFilesErr != nil {
return eligibleSourceFilesErr
}
Log(header)
Log("Applying `%s` to %d `*.%s` source files", commandParts[0], len(eligibleSourceFiles), fileExtension)
Log(header)
commandArgs := []string{}
if len(commandParts) > 1 {
commandArgs = append(commandArgs, commandParts[1:]...)
}
for _, eachFile := range eligibleSourceFiles {
applyArgs := append(commandArgs, eachFile)
applyErr := sh.Run(commandParts[0], applyArgs...)
if applyErr != nil {
return applyErr
}
}
return nil
} | [
"func",
"ApplyToSource",
"(",
"fileExtension",
"string",
",",
"ignoredSubdirectories",
"[",
"]",
"string",
",",
"commandParts",
"...",
"string",
")",
"error",
"{",
"if",
"len",
"(",
"commandParts",
")",
"<=",
"0",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"eligibleSourceFiles",
",",
"eligibleSourceFilesErr",
":=",
"sourceFilesOfType",
"(",
"fileExtension",
",",
"ignoredSubdirectories",
")",
"\n",
"if",
"eligibleSourceFilesErr",
"!=",
"nil",
"{",
"return",
"eligibleSourceFilesErr",
"\n",
"}",
"\n\n",
"Log",
"(",
"header",
")",
"\n",
"Log",
"(",
"\"",
"\"",
",",
"commandParts",
"[",
"0",
"]",
",",
"len",
"(",
"eligibleSourceFiles",
")",
",",
"fileExtension",
")",
"\n",
"Log",
"(",
"header",
")",
"\n\n",
"commandArgs",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"if",
"len",
"(",
"commandParts",
")",
">",
"1",
"{",
"commandArgs",
"=",
"append",
"(",
"commandArgs",
",",
"commandParts",
"[",
"1",
":",
"]",
"...",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"eachFile",
":=",
"range",
"eligibleSourceFiles",
"{",
"applyArgs",
":=",
"append",
"(",
"commandArgs",
",",
"eachFile",
")",
"\n",
"applyErr",
":=",
"sh",
".",
"Run",
"(",
"commandParts",
"[",
"0",
"]",
",",
"applyArgs",
"...",
")",
"\n",
"if",
"applyErr",
"!=",
"nil",
"{",
"return",
"applyErr",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // ApplyToSource is a mage compatible function that applies a
// command to your source tree | [
"ApplyToSource",
"is",
"a",
"mage",
"compatible",
"function",
"that",
"applies",
"a",
"command",
"to",
"your",
"source",
"tree"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/magefile/actions.go#L42-L69 |
1,211 | mweagle/Sparta | magefile/actions.go | SpartaCommand | func SpartaCommand(commandParts ...string) error {
noopValue := ""
parsedBool, parsedBoolErr := strconv.ParseBool(os.Getenv("NOOP"))
if parsedBoolErr == nil && parsedBool {
noopValue = "--noop"
}
curDir, curDirErr := os.Getwd()
if curDirErr != nil {
return errors.New("Failed to get current directory. Error: " + curDirErr.Error())
}
setenvErr := os.Setenv(mg.VerboseEnv, "1")
if setenvErr != nil {
return setenvErr
}
commandArgs := []string{
"run",
curDir,
}
commandArgs = append(commandArgs, commandParts...)
if noopValue != "" {
commandArgs = append(commandArgs, "--noop")
}
return sh.Run("go",
commandArgs...)
} | go | func SpartaCommand(commandParts ...string) error {
noopValue := ""
parsedBool, parsedBoolErr := strconv.ParseBool(os.Getenv("NOOP"))
if parsedBoolErr == nil && parsedBool {
noopValue = "--noop"
}
curDir, curDirErr := os.Getwd()
if curDirErr != nil {
return errors.New("Failed to get current directory. Error: " + curDirErr.Error())
}
setenvErr := os.Setenv(mg.VerboseEnv, "1")
if setenvErr != nil {
return setenvErr
}
commandArgs := []string{
"run",
curDir,
}
commandArgs = append(commandArgs, commandParts...)
if noopValue != "" {
commandArgs = append(commandArgs, "--noop")
}
return sh.Run("go",
commandArgs...)
} | [
"func",
"SpartaCommand",
"(",
"commandParts",
"...",
"string",
")",
"error",
"{",
"noopValue",
":=",
"\"",
"\"",
"\n",
"parsedBool",
",",
"parsedBoolErr",
":=",
"strconv",
".",
"ParseBool",
"(",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
")",
"\n",
"if",
"parsedBoolErr",
"==",
"nil",
"&&",
"parsedBool",
"{",
"noopValue",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"curDir",
",",
"curDirErr",
":=",
"os",
".",
"Getwd",
"(",
")",
"\n",
"if",
"curDirErr",
"!=",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
"+",
"curDirErr",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"setenvErr",
":=",
"os",
".",
"Setenv",
"(",
"mg",
".",
"VerboseEnv",
",",
"\"",
"\"",
")",
"\n",
"if",
"setenvErr",
"!=",
"nil",
"{",
"return",
"setenvErr",
"\n",
"}",
"\n",
"commandArgs",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"curDir",
",",
"}",
"\n",
"commandArgs",
"=",
"append",
"(",
"commandArgs",
",",
"commandParts",
"...",
")",
"\n",
"if",
"noopValue",
"!=",
"\"",
"\"",
"{",
"commandArgs",
"=",
"append",
"(",
"commandArgs",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"sh",
".",
"Run",
"(",
"\"",
"\"",
",",
"commandArgs",
"...",
")",
"\n",
"}"
] | // SpartaCommand issues a go run command that encapsulates resolving
// global env vars that can be translated into Sparta command line options | [
"SpartaCommand",
"issues",
"a",
"go",
"run",
"command",
"that",
"encapsulates",
"resolving",
"global",
"env",
"vars",
"that",
"can",
"be",
"translated",
"into",
"Sparta",
"command",
"line",
"options"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/magefile/actions.go#L73-L97 |
1,212 | mweagle/Sparta | magefile/actions.go | Provision | func Provision() error {
// Get the bucketName
bucketName := os.Getenv("S3_BUCKET")
if bucketName == "" {
return errors.New("Provision requires env.S3_BUCKET to be defined")
}
return SpartaCommand("provision", "--s3Bucket", bucketName)
} | go | func Provision() error {
// Get the bucketName
bucketName := os.Getenv("S3_BUCKET")
if bucketName == "" {
return errors.New("Provision requires env.S3_BUCKET to be defined")
}
return SpartaCommand("provision", "--s3Bucket", bucketName)
} | [
"func",
"Provision",
"(",
")",
"error",
"{",
"// Get the bucketName",
"bucketName",
":=",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"\n",
"if",
"bucketName",
"==",
"\"",
"\"",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"SpartaCommand",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"bucketName",
")",
"\n",
"}"
] | // Provision deploys the given service | [
"Provision",
"deploys",
"the",
"given",
"service"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/magefile/actions.go#L100-L107 |
1,213 | mweagle/Sparta | magefile/actions.go | Describe | func Describe() error {
// Get the bucketName
bucketName := os.Getenv("S3_BUCKET")
if bucketName == "" {
return errors.New("Describe requires env.S3_BUCKET to be defined")
}
return SpartaCommand("describe", "--s3Bucket", bucketName, "--out", "graph.html")
} | go | func Describe() error {
// Get the bucketName
bucketName := os.Getenv("S3_BUCKET")
if bucketName == "" {
return errors.New("Describe requires env.S3_BUCKET to be defined")
}
return SpartaCommand("describe", "--s3Bucket", bucketName, "--out", "graph.html")
} | [
"func",
"Describe",
"(",
")",
"error",
"{",
"// Get the bucketName",
"bucketName",
":=",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"\n",
"if",
"bucketName",
"==",
"\"",
"\"",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"SpartaCommand",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"bucketName",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // Describe deploys the given service | [
"Describe",
"deploys",
"the",
"given",
"service"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/magefile/actions.go#L110-L117 |
1,214 | mweagle/Sparta | util.go | describeInfoValue | func describeInfoValue(dynamicValue interface{}) string {
switch typedArn := dynamicValue.(type) {
case string:
return typedArn
case gocf.Stringable:
data, dataErr := json.Marshal(typedArn)
if dataErr != nil {
data = []byte(fmt.Sprintf("%v", typedArn))
}
return string(data)
default:
panic(fmt.Sprintf("Unsupported dynamic value type for `describe`: %+v", typedArn))
}
} | go | func describeInfoValue(dynamicValue interface{}) string {
switch typedArn := dynamicValue.(type) {
case string:
return typedArn
case gocf.Stringable:
data, dataErr := json.Marshal(typedArn)
if dataErr != nil {
data = []byte(fmt.Sprintf("%v", typedArn))
}
return string(data)
default:
panic(fmt.Sprintf("Unsupported dynamic value type for `describe`: %+v", typedArn))
}
} | [
"func",
"describeInfoValue",
"(",
"dynamicValue",
"interface",
"{",
"}",
")",
"string",
"{",
"switch",
"typedArn",
":=",
"dynamicValue",
".",
"(",
"type",
")",
"{",
"case",
"string",
":",
"return",
"typedArn",
"\n",
"case",
"gocf",
".",
"Stringable",
":",
"data",
",",
"dataErr",
":=",
"json",
".",
"Marshal",
"(",
"typedArn",
")",
"\n",
"if",
"dataErr",
"!=",
"nil",
"{",
"data",
"=",
"[",
"]",
"byte",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"typedArn",
")",
")",
"\n",
"}",
"\n",
"return",
"string",
"(",
"data",
")",
"\n",
"default",
":",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"typedArn",
")",
")",
"\n",
"}",
"\n",
"}"
] | // describeInfoValue is a utility function that accepts
// some type of dynamic gocf value and transforms it into
// something that is `describe` output compatible | [
"describeInfoValue",
"is",
"a",
"utility",
"function",
"that",
"accepts",
"some",
"type",
"of",
"dynamic",
"gocf",
"value",
"and",
"transforms",
"it",
"into",
"something",
"that",
"is",
"describe",
"output",
"compatible"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/util.go#L38-L51 |
1,215 | mweagle/Sparta | util.go | relativePath | func relativePath(logPath string) string {
cwd, cwdErr := os.Getwd()
if cwdErr == nil {
relPath := strings.TrimPrefix(logPath, cwd)
if relPath != logPath {
logPath = fmt.Sprintf(".%s", relPath)
}
}
return logPath
} | go | func relativePath(logPath string) string {
cwd, cwdErr := os.Getwd()
if cwdErr == nil {
relPath := strings.TrimPrefix(logPath, cwd)
if relPath != logPath {
logPath = fmt.Sprintf(".%s", relPath)
}
}
return logPath
} | [
"func",
"relativePath",
"(",
"logPath",
"string",
")",
"string",
"{",
"cwd",
",",
"cwdErr",
":=",
"os",
".",
"Getwd",
"(",
")",
"\n",
"if",
"cwdErr",
"==",
"nil",
"{",
"relPath",
":=",
"strings",
".",
"TrimPrefix",
"(",
"logPath",
",",
"cwd",
")",
"\n",
"if",
"relPath",
"!=",
"logPath",
"{",
"logPath",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"relPath",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"logPath",
"\n",
"}"
] | // relativePath returns the relative path of logPath if it's relative to the current
// workint directory | [
"relativePath",
"returns",
"the",
"relative",
"path",
"of",
"logPath",
"if",
"it",
"s",
"relative",
"to",
"the",
"current",
"workint",
"directory"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/util.go#L55-L64 |
1,216 | mweagle/Sparta | util.go | Run | func (t *workTask) Run(wg *sync.WaitGroup) {
t.Result = t.task()
wg.Done()
} | go | func (t *workTask) Run(wg *sync.WaitGroup) {
t.Result = t.task()
wg.Done()
} | [
"func",
"(",
"t",
"*",
"workTask",
")",
"Run",
"(",
"wg",
"*",
"sync",
".",
"WaitGroup",
")",
"{",
"t",
".",
"Result",
"=",
"t",
".",
"task",
"(",
")",
"\n",
"wg",
".",
"Done",
"(",
")",
"\n",
"}"
] | // Run runs a Task and does appropriate accounting via a given sync.WorkGroup. | [
"Run",
"runs",
"a",
"Task",
"and",
"does",
"appropriate",
"accounting",
"via",
"a",
"given",
"sync",
".",
"WorkGroup",
"."
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/util.go#L144-L147 |
1,217 | mweagle/Sparta | util.go | newWorkerPool | func newWorkerPool(tasks []*workTask, concurrency int) *workerPool {
return &workerPool{
Tasks: tasks,
concurrency: concurrency,
tasksChan: make(chan *workTask),
}
} | go | func newWorkerPool(tasks []*workTask, concurrency int) *workerPool {
return &workerPool{
Tasks: tasks,
concurrency: concurrency,
tasksChan: make(chan *workTask),
}
} | [
"func",
"newWorkerPool",
"(",
"tasks",
"[",
"]",
"*",
"workTask",
",",
"concurrency",
"int",
")",
"*",
"workerPool",
"{",
"return",
"&",
"workerPool",
"{",
"Tasks",
":",
"tasks",
",",
"concurrency",
":",
"concurrency",
",",
"tasksChan",
":",
"make",
"(",
"chan",
"*",
"workTask",
")",
",",
"}",
"\n",
"}"
] | // newWorkerPool initializes a new pool with the given tasks and at the given
// concurrency. | [
"newWorkerPool",
"initializes",
"a",
"new",
"pool",
"with",
"the",
"given",
"tasks",
"and",
"at",
"the",
"given",
"concurrency",
"."
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/util.go#L166-L172 |
1,218 | mweagle/Sparta | util.go | workResults | func (p *workerPool) workResults() ([]interface{}, []error) {
result := []interface{}{}
errors := []error{}
for _, eachResult := range p.Tasks {
if eachResult.Result.Error() != nil {
errors = append(errors, eachResult.Result.Error())
} else {
result = append(result, eachResult.Result.Result())
}
}
return result, errors
} | go | func (p *workerPool) workResults() ([]interface{}, []error) {
result := []interface{}{}
errors := []error{}
for _, eachResult := range p.Tasks {
if eachResult.Result.Error() != nil {
errors = append(errors, eachResult.Result.Error())
} else {
result = append(result, eachResult.Result.Result())
}
}
return result, errors
} | [
"func",
"(",
"p",
"*",
"workerPool",
")",
"workResults",
"(",
")",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"[",
"]",
"error",
")",
"{",
"result",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"}",
"\n",
"errors",
":=",
"[",
"]",
"error",
"{",
"}",
"\n\n",
"for",
"_",
",",
"eachResult",
":=",
"range",
"p",
".",
"Tasks",
"{",
"if",
"eachResult",
".",
"Result",
".",
"Error",
"(",
")",
"!=",
"nil",
"{",
"errors",
"=",
"append",
"(",
"errors",
",",
"eachResult",
".",
"Result",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"else",
"{",
"result",
"=",
"append",
"(",
"result",
",",
"eachResult",
".",
"Result",
".",
"Result",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"result",
",",
"errors",
"\n",
"}"
] | // HasErrors indicates whether there were any errors from tasks run. Its result
// is only meaningful after Run has been called. | [
"HasErrors",
"indicates",
"whether",
"there",
"were",
"any",
"errors",
"from",
"tasks",
"run",
".",
"Its",
"result",
"is",
"only",
"meaningful",
"after",
"Run",
"has",
"been",
"called",
"."
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/util.go#L176-L188 |
1,219 | mweagle/Sparta | util.go | Run | func (p *workerPool) Run() ([]interface{}, []error) {
for i := 0; i < p.concurrency; i++ {
go p.work()
}
p.wg.Add(len(p.Tasks))
for _, task := range p.Tasks {
p.tasksChan <- task
}
// all workers return
close(p.tasksChan)
p.wg.Wait()
return p.workResults()
} | go | func (p *workerPool) Run() ([]interface{}, []error) {
for i := 0; i < p.concurrency; i++ {
go p.work()
}
p.wg.Add(len(p.Tasks))
for _, task := range p.Tasks {
p.tasksChan <- task
}
// all workers return
close(p.tasksChan)
p.wg.Wait()
return p.workResults()
} | [
"func",
"(",
"p",
"*",
"workerPool",
")",
"Run",
"(",
")",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"[",
"]",
"error",
")",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"p",
".",
"concurrency",
";",
"i",
"++",
"{",
"go",
"p",
".",
"work",
"(",
")",
"\n",
"}",
"\n\n",
"p",
".",
"wg",
".",
"Add",
"(",
"len",
"(",
"p",
".",
"Tasks",
")",
")",
"\n",
"for",
"_",
",",
"task",
":=",
"range",
"p",
".",
"Tasks",
"{",
"p",
".",
"tasksChan",
"<-",
"task",
"\n",
"}",
"\n\n",
"// all workers return",
"close",
"(",
"p",
".",
"tasksChan",
")",
"\n\n",
"p",
".",
"wg",
".",
"Wait",
"(",
")",
"\n",
"return",
"p",
".",
"workResults",
"(",
")",
"\n",
"}"
] | // Run runs all work within the pool and blocks until it's finished. | [
"Run",
"runs",
"all",
"work",
"within",
"the",
"pool",
"and",
"blocks",
"until",
"it",
"s",
"finished",
"."
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/util.go#L191-L206 |
1,220 | mweagle/Sparta | util.go | work | func (p *workerPool) work() {
for task := range p.tasksChan {
task.Run(&p.wg)
}
} | go | func (p *workerPool) work() {
for task := range p.tasksChan {
task.Run(&p.wg)
}
} | [
"func",
"(",
"p",
"*",
"workerPool",
")",
"work",
"(",
")",
"{",
"for",
"task",
":=",
"range",
"p",
".",
"tasksChan",
"{",
"task",
".",
"Run",
"(",
"&",
"p",
".",
"wg",
")",
"\n",
"}",
"\n",
"}"
] | // The work loop for any single goroutine. | [
"The",
"work",
"loop",
"for",
"any",
"single",
"goroutine",
"."
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/util.go#L209-L213 |
1,221 | mweagle/Sparta | archetype/cloudwatch.go | OnCloudWatchMessage | func (reactorFunc CloudWatchReactorFunc) OnCloudWatchMessage(ctx context.Context,
cwLogs awsLambdaEvents.CloudwatchLogsEvent) (interface{}, error) {
return reactorFunc(ctx, cwLogs)
} | go | func (reactorFunc CloudWatchReactorFunc) OnCloudWatchMessage(ctx context.Context,
cwLogs awsLambdaEvents.CloudwatchLogsEvent) (interface{}, error) {
return reactorFunc(ctx, cwLogs)
} | [
"func",
"(",
"reactorFunc",
"CloudWatchReactorFunc",
")",
"OnCloudWatchMessage",
"(",
"ctx",
"context",
".",
"Context",
",",
"cwLogs",
"awsLambdaEvents",
".",
"CloudwatchLogsEvent",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"return",
"reactorFunc",
"(",
"ctx",
",",
"cwLogs",
")",
"\n",
"}"
] | // OnCloudWatchMessage satisfies the CloudWatchReactor interface | [
"OnCloudWatchMessage",
"satisfies",
"the",
"CloudWatchReactor",
"interface"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/archetype/cloudwatch.go#L28-L31 |
1,222 | mweagle/Sparta | archetype/cloudwatch.go | NewCloudWatchReactor | func NewCloudWatchReactor(reactor CloudWatchReactor,
subscriptions map[string]sparta.CloudWatchEventsRule,
additionalLambdaPermissions []sparta.IAMRolePrivilege) (*sparta.LambdaAWSInfo, error) {
if len(subscriptions) <= 0 {
return nil, errors.Errorf("CloudWatchLogs subscription map must not be empty")
}
reactorLambda := func(ctx context.Context, cwLogs awsLambdaEvents.CloudwatchLogsEvent) (interface{}, error) {
return reactor.OnCloudWatchMessage(ctx, cwLogs)
}
lambdaFn, lambdaFnErr := sparta.NewAWSLambda(reactorName(reactor),
reactorLambda,
sparta.IAMRoleDefinition{})
if lambdaFnErr != nil {
return nil, errors.Wrapf(lambdaFnErr, "attempting to create reactor")
}
cloudWatchEventsPermission := sparta.CloudWatchEventsPermission{}
cloudWatchEventsPermission.Rules = make(map[string]sparta.CloudWatchEventsRule)
for eachRuleName, eachRule := range subscriptions {
cloudWatchEventsPermission.Rules[eachRuleName] = eachRule
}
lambdaFn.Permissions = append(lambdaFn.Permissions, cloudWatchEventsPermission)
if len(additionalLambdaPermissions) != 0 {
lambdaFn.RoleDefinition.Privileges = additionalLambdaPermissions
}
return lambdaFn, nil
} | go | func NewCloudWatchReactor(reactor CloudWatchReactor,
subscriptions map[string]sparta.CloudWatchEventsRule,
additionalLambdaPermissions []sparta.IAMRolePrivilege) (*sparta.LambdaAWSInfo, error) {
if len(subscriptions) <= 0 {
return nil, errors.Errorf("CloudWatchLogs subscription map must not be empty")
}
reactorLambda := func(ctx context.Context, cwLogs awsLambdaEvents.CloudwatchLogsEvent) (interface{}, error) {
return reactor.OnCloudWatchMessage(ctx, cwLogs)
}
lambdaFn, lambdaFnErr := sparta.NewAWSLambda(reactorName(reactor),
reactorLambda,
sparta.IAMRoleDefinition{})
if lambdaFnErr != nil {
return nil, errors.Wrapf(lambdaFnErr, "attempting to create reactor")
}
cloudWatchEventsPermission := sparta.CloudWatchEventsPermission{}
cloudWatchEventsPermission.Rules = make(map[string]sparta.CloudWatchEventsRule)
for eachRuleName, eachRule := range subscriptions {
cloudWatchEventsPermission.Rules[eachRuleName] = eachRule
}
lambdaFn.Permissions = append(lambdaFn.Permissions, cloudWatchEventsPermission)
if len(additionalLambdaPermissions) != 0 {
lambdaFn.RoleDefinition.Privileges = additionalLambdaPermissions
}
return lambdaFn, nil
} | [
"func",
"NewCloudWatchReactor",
"(",
"reactor",
"CloudWatchReactor",
",",
"subscriptions",
"map",
"[",
"string",
"]",
"sparta",
".",
"CloudWatchEventsRule",
",",
"additionalLambdaPermissions",
"[",
"]",
"sparta",
".",
"IAMRolePrivilege",
")",
"(",
"*",
"sparta",
".",
"LambdaAWSInfo",
",",
"error",
")",
"{",
"if",
"len",
"(",
"subscriptions",
")",
"<=",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"reactorLambda",
":=",
"func",
"(",
"ctx",
"context",
".",
"Context",
",",
"cwLogs",
"awsLambdaEvents",
".",
"CloudwatchLogsEvent",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"return",
"reactor",
".",
"OnCloudWatchMessage",
"(",
"ctx",
",",
"cwLogs",
")",
"\n",
"}",
"\n",
"lambdaFn",
",",
"lambdaFnErr",
":=",
"sparta",
".",
"NewAWSLambda",
"(",
"reactorName",
"(",
"reactor",
")",
",",
"reactorLambda",
",",
"sparta",
".",
"IAMRoleDefinition",
"{",
"}",
")",
"\n",
"if",
"lambdaFnErr",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrapf",
"(",
"lambdaFnErr",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"cloudWatchEventsPermission",
":=",
"sparta",
".",
"CloudWatchEventsPermission",
"{",
"}",
"\n",
"cloudWatchEventsPermission",
".",
"Rules",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"sparta",
".",
"CloudWatchEventsRule",
")",
"\n",
"for",
"eachRuleName",
",",
"eachRule",
":=",
"range",
"subscriptions",
"{",
"cloudWatchEventsPermission",
".",
"Rules",
"[",
"eachRuleName",
"]",
"=",
"eachRule",
"\n",
"}",
"\n",
"lambdaFn",
".",
"Permissions",
"=",
"append",
"(",
"lambdaFn",
".",
"Permissions",
",",
"cloudWatchEventsPermission",
")",
"\n\n",
"if",
"len",
"(",
"additionalLambdaPermissions",
")",
"!=",
"0",
"{",
"lambdaFn",
".",
"RoleDefinition",
".",
"Privileges",
"=",
"additionalLambdaPermissions",
"\n",
"}",
"\n",
"return",
"lambdaFn",
",",
"nil",
"\n",
"}"
] | // NewCloudWatchReactor returns a CloudWatch logs reactor lambda function | [
"NewCloudWatchReactor",
"returns",
"a",
"CloudWatch",
"logs",
"reactor",
"lambda",
"function"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/archetype/cloudwatch.go#L81-L108 |
1,223 | mweagle/Sparta | sparta.go | Register | func (lei *LambdaEventInterceptors) Register(provider LambdaInterceptorProvider) *LambdaEventInterceptors {
namedInterceptor := func(interceptor Interceptor) *NamedInterceptor {
return &NamedInterceptor{
Name: fmt.Sprintf("%T", provider),
Interceptor: interceptor,
}
}
if lei.Begin == nil {
lei.Begin = make(InterceptorList, 0)
}
lei.Begin = append(lei.Begin, namedInterceptor(provider.Begin))
if lei.BeforeSetup == nil {
lei.BeforeSetup = make(InterceptorList, 0)
}
lei.BeforeSetup = append(lei.BeforeSetup, namedInterceptor(provider.BeforeSetup))
if lei.AfterSetup == nil {
lei.AfterSetup = make(InterceptorList, 0)
}
lei.AfterSetup = append(lei.AfterSetup, namedInterceptor(provider.AfterSetup))
if lei.BeforeDispatch == nil {
lei.BeforeDispatch = make(InterceptorList, 0)
}
lei.BeforeDispatch = append(lei.BeforeDispatch, namedInterceptor(provider.BeforeDispatch))
if lei.AfterDispatch == nil {
lei.AfterDispatch = make(InterceptorList, 0)
}
lei.AfterDispatch = append(lei.AfterDispatch, namedInterceptor(provider.AfterDispatch))
if lei.Complete == nil {
lei.Complete = make(InterceptorList, 0)
}
lei.Complete = append(lei.Complete, namedInterceptor(provider.Complete))
return lei
} | go | func (lei *LambdaEventInterceptors) Register(provider LambdaInterceptorProvider) *LambdaEventInterceptors {
namedInterceptor := func(interceptor Interceptor) *NamedInterceptor {
return &NamedInterceptor{
Name: fmt.Sprintf("%T", provider),
Interceptor: interceptor,
}
}
if lei.Begin == nil {
lei.Begin = make(InterceptorList, 0)
}
lei.Begin = append(lei.Begin, namedInterceptor(provider.Begin))
if lei.BeforeSetup == nil {
lei.BeforeSetup = make(InterceptorList, 0)
}
lei.BeforeSetup = append(lei.BeforeSetup, namedInterceptor(provider.BeforeSetup))
if lei.AfterSetup == nil {
lei.AfterSetup = make(InterceptorList, 0)
}
lei.AfterSetup = append(lei.AfterSetup, namedInterceptor(provider.AfterSetup))
if lei.BeforeDispatch == nil {
lei.BeforeDispatch = make(InterceptorList, 0)
}
lei.BeforeDispatch = append(lei.BeforeDispatch, namedInterceptor(provider.BeforeDispatch))
if lei.AfterDispatch == nil {
lei.AfterDispatch = make(InterceptorList, 0)
}
lei.AfterDispatch = append(lei.AfterDispatch, namedInterceptor(provider.AfterDispatch))
if lei.Complete == nil {
lei.Complete = make(InterceptorList, 0)
}
lei.Complete = append(lei.Complete, namedInterceptor(provider.Complete))
return lei
} | [
"func",
"(",
"lei",
"*",
"LambdaEventInterceptors",
")",
"Register",
"(",
"provider",
"LambdaInterceptorProvider",
")",
"*",
"LambdaEventInterceptors",
"{",
"namedInterceptor",
":=",
"func",
"(",
"interceptor",
"Interceptor",
")",
"*",
"NamedInterceptor",
"{",
"return",
"&",
"NamedInterceptor",
"{",
"Name",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"provider",
")",
",",
"Interceptor",
":",
"interceptor",
",",
"}",
"\n",
"}",
"\n",
"if",
"lei",
".",
"Begin",
"==",
"nil",
"{",
"lei",
".",
"Begin",
"=",
"make",
"(",
"InterceptorList",
",",
"0",
")",
"\n",
"}",
"\n",
"lei",
".",
"Begin",
"=",
"append",
"(",
"lei",
".",
"Begin",
",",
"namedInterceptor",
"(",
"provider",
".",
"Begin",
")",
")",
"\n\n",
"if",
"lei",
".",
"BeforeSetup",
"==",
"nil",
"{",
"lei",
".",
"BeforeSetup",
"=",
"make",
"(",
"InterceptorList",
",",
"0",
")",
"\n",
"}",
"\n",
"lei",
".",
"BeforeSetup",
"=",
"append",
"(",
"lei",
".",
"BeforeSetup",
",",
"namedInterceptor",
"(",
"provider",
".",
"BeforeSetup",
")",
")",
"\n\n",
"if",
"lei",
".",
"AfterSetup",
"==",
"nil",
"{",
"lei",
".",
"AfterSetup",
"=",
"make",
"(",
"InterceptorList",
",",
"0",
")",
"\n",
"}",
"\n",
"lei",
".",
"AfterSetup",
"=",
"append",
"(",
"lei",
".",
"AfterSetup",
",",
"namedInterceptor",
"(",
"provider",
".",
"AfterSetup",
")",
")",
"\n\n",
"if",
"lei",
".",
"BeforeDispatch",
"==",
"nil",
"{",
"lei",
".",
"BeforeDispatch",
"=",
"make",
"(",
"InterceptorList",
",",
"0",
")",
"\n",
"}",
"\n",
"lei",
".",
"BeforeDispatch",
"=",
"append",
"(",
"lei",
".",
"BeforeDispatch",
",",
"namedInterceptor",
"(",
"provider",
".",
"BeforeDispatch",
")",
")",
"\n\n",
"if",
"lei",
".",
"AfterDispatch",
"==",
"nil",
"{",
"lei",
".",
"AfterDispatch",
"=",
"make",
"(",
"InterceptorList",
",",
"0",
")",
"\n",
"}",
"\n",
"lei",
".",
"AfterDispatch",
"=",
"append",
"(",
"lei",
".",
"AfterDispatch",
",",
"namedInterceptor",
"(",
"provider",
".",
"AfterDispatch",
")",
")",
"\n\n",
"if",
"lei",
".",
"Complete",
"==",
"nil",
"{",
"lei",
".",
"Complete",
"=",
"make",
"(",
"InterceptorList",
",",
"0",
")",
"\n",
"}",
"\n",
"lei",
".",
"Complete",
"=",
"append",
"(",
"lei",
".",
"Complete",
",",
"namedInterceptor",
"(",
"provider",
".",
"Complete",
")",
")",
"\n",
"return",
"lei",
"\n",
"}"
] | // Register is a convenience function to register a struct that
// implements the LambdaInterceptorProvider interface | [
"Register",
"is",
"a",
"convenience",
"function",
"to",
"register",
"a",
"struct",
"that",
"implements",
"the",
"LambdaInterceptorProvider",
"interface"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/sparta.go#L621-L658 |
1,224 | mweagle/Sparta | sparta.go | lambdaFunctionName | func (info *LambdaAWSInfo) lambdaFunctionName() string {
if info.cachedLambdaFunctionName != "" {
return info.cachedLambdaFunctionName
}
var lambdaFuncName string
if info.Options != nil &&
info.Options.SpartaOptions != nil &&
info.Options.SpartaOptions.Name != "" {
lambdaFuncName = info.Options.SpartaOptions.Name
} else if info.userSuppliedFunctionName != "" {
lambdaFuncName = info.userSuppliedFunctionName
} else {
// Using the default name, let's at least remove the
// first prefix, since that's the SCM provider and
// doesn't provide a lot of value...
if info.handlerSymbol != nil {
lambdaPtr := runtime.FuncForPC(reflect.ValueOf(info.handlerSymbol).Pointer())
lambdaFuncName = lambdaPtr.Name()
}
// Split
// cwd: /Users/mweagle/Documents/gopath/src/github.com/mweagle/SpartaHelloWorld
// anonymous: github.com/mweagle/Sparta.(*StructHandler1).(github.com/mweagle/Sparta.handler)-fm
// RE==> var reSplit = regexp.MustCompile("[\\(\\)\\.\\*]+")
// RESULT ==> Hello,[github com/mweagle/Sparta StructHandler1 github com/mweagle/Sparta handler -fm]
// Same package: main.helloWorld
// Other package, free function: github.com/mweagle/SpartaPython.HelloWorld
// Grab the name of the function...
structDefined := strings.Contains(lambdaFuncName, "(") || strings.Contains(lambdaFuncName, ")")
otherPackage := strings.Contains(lambdaFuncName, "/")
canonicalName := lambdaFuncName
if structDefined {
var reSplit = regexp.MustCompile(`[*\(\)\[\]]+`)
// Function name:
// github.com/mweagle/Sparta.(*StructHandler1).handler-fm
parts := reSplit.Split(lambdaFuncName, -1)
lastPart := parts[len(parts)-1]
penultimatePart := lastPart
if len(parts) > 1 {
penultimatePart = parts[len(parts)-2]
}
intermediateName := fmt.Sprintf("%s-%s", penultimatePart, lastPart)
reClean := regexp.MustCompile(`[\*\(\)]+`)
canonicalName = reClean.ReplaceAllString(intermediateName, "")
} else if otherPackage {
parts := strings.Split(lambdaFuncName, "/")
canonicalName = parts[len(parts)-1]
}
// Final sanitization
// Issue: https://github.com/mweagle/Sparta/issues/63
lambdaFuncName = sanitizedName(canonicalName)
}
// Cache it so we only do this once
info.cachedLambdaFunctionName = lambdaFuncName
return info.cachedLambdaFunctionName
} | go | func (info *LambdaAWSInfo) lambdaFunctionName() string {
if info.cachedLambdaFunctionName != "" {
return info.cachedLambdaFunctionName
}
var lambdaFuncName string
if info.Options != nil &&
info.Options.SpartaOptions != nil &&
info.Options.SpartaOptions.Name != "" {
lambdaFuncName = info.Options.SpartaOptions.Name
} else if info.userSuppliedFunctionName != "" {
lambdaFuncName = info.userSuppliedFunctionName
} else {
// Using the default name, let's at least remove the
// first prefix, since that's the SCM provider and
// doesn't provide a lot of value...
if info.handlerSymbol != nil {
lambdaPtr := runtime.FuncForPC(reflect.ValueOf(info.handlerSymbol).Pointer())
lambdaFuncName = lambdaPtr.Name()
}
// Split
// cwd: /Users/mweagle/Documents/gopath/src/github.com/mweagle/SpartaHelloWorld
// anonymous: github.com/mweagle/Sparta.(*StructHandler1).(github.com/mweagle/Sparta.handler)-fm
// RE==> var reSplit = regexp.MustCompile("[\\(\\)\\.\\*]+")
// RESULT ==> Hello,[github com/mweagle/Sparta StructHandler1 github com/mweagle/Sparta handler -fm]
// Same package: main.helloWorld
// Other package, free function: github.com/mweagle/SpartaPython.HelloWorld
// Grab the name of the function...
structDefined := strings.Contains(lambdaFuncName, "(") || strings.Contains(lambdaFuncName, ")")
otherPackage := strings.Contains(lambdaFuncName, "/")
canonicalName := lambdaFuncName
if structDefined {
var reSplit = regexp.MustCompile(`[*\(\)\[\]]+`)
// Function name:
// github.com/mweagle/Sparta.(*StructHandler1).handler-fm
parts := reSplit.Split(lambdaFuncName, -1)
lastPart := parts[len(parts)-1]
penultimatePart := lastPart
if len(parts) > 1 {
penultimatePart = parts[len(parts)-2]
}
intermediateName := fmt.Sprintf("%s-%s", penultimatePart, lastPart)
reClean := regexp.MustCompile(`[\*\(\)]+`)
canonicalName = reClean.ReplaceAllString(intermediateName, "")
} else if otherPackage {
parts := strings.Split(lambdaFuncName, "/")
canonicalName = parts[len(parts)-1]
}
// Final sanitization
// Issue: https://github.com/mweagle/Sparta/issues/63
lambdaFuncName = sanitizedName(canonicalName)
}
// Cache it so we only do this once
info.cachedLambdaFunctionName = lambdaFuncName
return info.cachedLambdaFunctionName
} | [
"func",
"(",
"info",
"*",
"LambdaAWSInfo",
")",
"lambdaFunctionName",
"(",
")",
"string",
"{",
"if",
"info",
".",
"cachedLambdaFunctionName",
"!=",
"\"",
"\"",
"{",
"return",
"info",
".",
"cachedLambdaFunctionName",
"\n",
"}",
"\n",
"var",
"lambdaFuncName",
"string",
"\n\n",
"if",
"info",
".",
"Options",
"!=",
"nil",
"&&",
"info",
".",
"Options",
".",
"SpartaOptions",
"!=",
"nil",
"&&",
"info",
".",
"Options",
".",
"SpartaOptions",
".",
"Name",
"!=",
"\"",
"\"",
"{",
"lambdaFuncName",
"=",
"info",
".",
"Options",
".",
"SpartaOptions",
".",
"Name",
"\n",
"}",
"else",
"if",
"info",
".",
"userSuppliedFunctionName",
"!=",
"\"",
"\"",
"{",
"lambdaFuncName",
"=",
"info",
".",
"userSuppliedFunctionName",
"\n",
"}",
"else",
"{",
"// Using the default name, let's at least remove the",
"// first prefix, since that's the SCM provider and",
"// doesn't provide a lot of value...",
"if",
"info",
".",
"handlerSymbol",
"!=",
"nil",
"{",
"lambdaPtr",
":=",
"runtime",
".",
"FuncForPC",
"(",
"reflect",
".",
"ValueOf",
"(",
"info",
".",
"handlerSymbol",
")",
".",
"Pointer",
"(",
")",
")",
"\n",
"lambdaFuncName",
"=",
"lambdaPtr",
".",
"Name",
"(",
")",
"\n",
"}",
"\n\n",
"// Split",
"// cwd: /Users/mweagle/Documents/gopath/src/github.com/mweagle/SpartaHelloWorld",
"// anonymous: github.com/mweagle/Sparta.(*StructHandler1).(github.com/mweagle/Sparta.handler)-fm",
"//\tRE==> var reSplit = regexp.MustCompile(\"[\\\\(\\\\)\\\\.\\\\*]+\")",
"// \tRESULT ==> Hello,[github com/mweagle/Sparta StructHandler1 github com/mweagle/Sparta handler -fm]",
"// Same package: main.helloWorld",
"// Other package, free function: github.com/mweagle/SpartaPython.HelloWorld",
"// Grab the name of the function...",
"structDefined",
":=",
"strings",
".",
"Contains",
"(",
"lambdaFuncName",
",",
"\"",
"\"",
")",
"||",
"strings",
".",
"Contains",
"(",
"lambdaFuncName",
",",
"\"",
"\"",
")",
"\n",
"otherPackage",
":=",
"strings",
".",
"Contains",
"(",
"lambdaFuncName",
",",
"\"",
"\"",
")",
"\n",
"canonicalName",
":=",
"lambdaFuncName",
"\n",
"if",
"structDefined",
"{",
"var",
"reSplit",
"=",
"regexp",
".",
"MustCompile",
"(",
"`[*\\(\\)\\[\\]]+`",
")",
"\n",
"// Function name:",
"// github.com/mweagle/Sparta.(*StructHandler1).handler-fm",
"parts",
":=",
"reSplit",
".",
"Split",
"(",
"lambdaFuncName",
",",
"-",
"1",
")",
"\n",
"lastPart",
":=",
"parts",
"[",
"len",
"(",
"parts",
")",
"-",
"1",
"]",
"\n",
"penultimatePart",
":=",
"lastPart",
"\n",
"if",
"len",
"(",
"parts",
")",
">",
"1",
"{",
"penultimatePart",
"=",
"parts",
"[",
"len",
"(",
"parts",
")",
"-",
"2",
"]",
"\n",
"}",
"\n",
"intermediateName",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"penultimatePart",
",",
"lastPart",
")",
"\n",
"reClean",
":=",
"regexp",
".",
"MustCompile",
"(",
"`[\\*\\(\\)]+`",
")",
"\n",
"canonicalName",
"=",
"reClean",
".",
"ReplaceAllString",
"(",
"intermediateName",
",",
"\"",
"\"",
")",
"\n",
"}",
"else",
"if",
"otherPackage",
"{",
"parts",
":=",
"strings",
".",
"Split",
"(",
"lambdaFuncName",
",",
"\"",
"\"",
")",
"\n",
"canonicalName",
"=",
"parts",
"[",
"len",
"(",
"parts",
")",
"-",
"1",
"]",
"\n",
"}",
"\n",
"// Final sanitization",
"// Issue: https://github.com/mweagle/Sparta/issues/63",
"lambdaFuncName",
"=",
"sanitizedName",
"(",
"canonicalName",
")",
"\n",
"}",
"\n",
"// Cache it so we only do this once",
"info",
".",
"cachedLambdaFunctionName",
"=",
"lambdaFuncName",
"\n",
"return",
"info",
".",
"cachedLambdaFunctionName",
"\n",
"}"
] | // lambdaFunctionName returns the internal
// function name for lambda export binding | [
"lambdaFunctionName",
"returns",
"the",
"internal",
"function",
"name",
"for",
"lambda",
"export",
"binding"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/sparta.go#L729-L787 |
1,225 | mweagle/Sparta | sparta.go | LogicalResourceName | func (info *LambdaAWSInfo) LogicalResourceName() string {
// Per http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resources-section-structure.html,
// we can only use alphanumeric, so we'll take the sanitized name and
// remove all underscores
// Prefer the user-supplied stable name to the internal one.
baseName := info.lambdaFunctionName()
resourceName := strings.Replace(sanitizedName(baseName), "_", "", -1)
prefix := fmt.Sprintf("%sLambda", resourceName)
return CloudFormationResourceName(prefix, info.lambdaFunctionName())
} | go | func (info *LambdaAWSInfo) LogicalResourceName() string {
// Per http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resources-section-structure.html,
// we can only use alphanumeric, so we'll take the sanitized name and
// remove all underscores
// Prefer the user-supplied stable name to the internal one.
baseName := info.lambdaFunctionName()
resourceName := strings.Replace(sanitizedName(baseName), "_", "", -1)
prefix := fmt.Sprintf("%sLambda", resourceName)
return CloudFormationResourceName(prefix, info.lambdaFunctionName())
} | [
"func",
"(",
"info",
"*",
"LambdaAWSInfo",
")",
"LogicalResourceName",
"(",
")",
"string",
"{",
"// Per http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resources-section-structure.html,",
"// we can only use alphanumeric, so we'll take the sanitized name and",
"// remove all underscores",
"// Prefer the user-supplied stable name to the internal one.",
"baseName",
":=",
"info",
".",
"lambdaFunctionName",
"(",
")",
"\n",
"resourceName",
":=",
"strings",
".",
"Replace",
"(",
"sanitizedName",
"(",
"baseName",
")",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n",
"prefix",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"resourceName",
")",
"\n",
"return",
"CloudFormationResourceName",
"(",
"prefix",
",",
"info",
".",
"lambdaFunctionName",
"(",
")",
")",
"\n",
"}"
] | // LogicalResourceName returns the stable, content-addressable logical
// name for this LambdaAWSInfo value. This is the CloudFormation
// resource name | [
"LogicalResourceName",
"returns",
"the",
"stable",
"content",
"-",
"addressable",
"logical",
"name",
"for",
"this",
"LambdaAWSInfo",
"value",
".",
"This",
"is",
"the",
"CloudFormation",
"resource",
"name"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/sparta.go#L837-L846 |
1,226 | mweagle/Sparta | sparta.go | LambdaName | func LambdaName(handlerSymbol interface{}) string {
funcPtr := runtime.FuncForPC(reflect.ValueOf(handlerSymbol).Pointer())
return funcPtr.Name()
} | go | func LambdaName(handlerSymbol interface{}) string {
funcPtr := runtime.FuncForPC(reflect.ValueOf(handlerSymbol).Pointer())
return funcPtr.Name()
} | [
"func",
"LambdaName",
"(",
"handlerSymbol",
"interface",
"{",
"}",
")",
"string",
"{",
"funcPtr",
":=",
"runtime",
".",
"FuncForPC",
"(",
"reflect",
".",
"ValueOf",
"(",
"handlerSymbol",
")",
".",
"Pointer",
"(",
")",
")",
"\n",
"return",
"funcPtr",
".",
"Name",
"(",
")",
"\n",
"}"
] | // LambdaName returns the Go-reflection discovered name for a given
// function | [
"LambdaName",
"returns",
"the",
"Go",
"-",
"reflection",
"discovered",
"name",
"for",
"a",
"given",
"function"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/sparta.go#L1193-L1196 |
1,227 | mweagle/Sparta | lambda_permissions.go | BucketArn | func (storage *MessageBodyStorage) BucketArn() *gocf.StringExpr {
return gocf.Join("",
gocf.String("arn:aws:s3:::"),
storage.bucketNameExpr)
} | go | func (storage *MessageBodyStorage) BucketArn() *gocf.StringExpr {
return gocf.Join("",
gocf.String("arn:aws:s3:::"),
storage.bucketNameExpr)
} | [
"func",
"(",
"storage",
"*",
"MessageBodyStorage",
")",
"BucketArn",
"(",
")",
"*",
"gocf",
".",
"StringExpr",
"{",
"return",
"gocf",
".",
"Join",
"(",
"\"",
"\"",
",",
"gocf",
".",
"String",
"(",
"\"",
"\"",
")",
",",
"storage",
".",
"bucketNameExpr",
")",
"\n",
"}"
] | // BucketArn returns an Arn value that can be used as an
// lambdaFn.RoleDefinition.Privileges `Resource` value. | [
"BucketArn",
"returns",
"an",
"Arn",
"value",
"that",
"can",
"be",
"used",
"as",
"an",
"lambdaFn",
".",
"RoleDefinition",
".",
"Privileges",
"Resource",
"value",
"."
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/lambda_permissions.go#L385-L389 |
1,228 | mweagle/Sparta | lambda_permissions.go | NewMessageBodyStorageResource | func (perm *SESPermission) NewMessageBodyStorageResource(bucketLogicalName string) (*MessageBodyStorage, error) {
if len(bucketLogicalName) <= 0 {
return nil, errors.New("NewMessageBodyStorageResource requires a unique, non-empty `bucketLogicalName` parameter ")
}
store := &MessageBodyStorage{
logicalBucketName: bucketLogicalName,
}
store.cloudFormationS3BucketResourceName = CloudFormationResourceName("SESMessageStoreBucket", bucketLogicalName)
store.bucketNameExpr = gocf.Ref(store.cloudFormationS3BucketResourceName).String()
return store, nil
} | go | func (perm *SESPermission) NewMessageBodyStorageResource(bucketLogicalName string) (*MessageBodyStorage, error) {
if len(bucketLogicalName) <= 0 {
return nil, errors.New("NewMessageBodyStorageResource requires a unique, non-empty `bucketLogicalName` parameter ")
}
store := &MessageBodyStorage{
logicalBucketName: bucketLogicalName,
}
store.cloudFormationS3BucketResourceName = CloudFormationResourceName("SESMessageStoreBucket", bucketLogicalName)
store.bucketNameExpr = gocf.Ref(store.cloudFormationS3BucketResourceName).String()
return store, nil
} | [
"func",
"(",
"perm",
"*",
"SESPermission",
")",
"NewMessageBodyStorageResource",
"(",
"bucketLogicalName",
"string",
")",
"(",
"*",
"MessageBodyStorage",
",",
"error",
")",
"{",
"if",
"len",
"(",
"bucketLogicalName",
")",
"<=",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"store",
":=",
"&",
"MessageBodyStorage",
"{",
"logicalBucketName",
":",
"bucketLogicalName",
",",
"}",
"\n",
"store",
".",
"cloudFormationS3BucketResourceName",
"=",
"CloudFormationResourceName",
"(",
"\"",
"\"",
",",
"bucketLogicalName",
")",
"\n",
"store",
".",
"bucketNameExpr",
"=",
"gocf",
".",
"Ref",
"(",
"store",
".",
"cloudFormationS3BucketResourceName",
")",
".",
"String",
"(",
")",
"\n",
"return",
"store",
",",
"nil",
"\n",
"}"
] | // NewMessageBodyStorageResource provisions a new S3 bucket to store message body
// content. | [
"NewMessageBodyStorageResource",
"provisions",
"a",
"new",
"S3",
"bucket",
"to",
"store",
"message",
"body",
"content",
"."
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/lambda_permissions.go#L578-L588 |
1,229 | mweagle/Sparta | lambda_permissions.go | MarshalJSON | func (rule CloudWatchEventsRule) MarshalJSON() ([]byte, error) {
ruleJSON := map[string]interface{}{}
if rule.Description != "" {
ruleJSON["Description"] = rule.Description
}
if nil != rule.EventPattern {
eventPatternString, err := json.Marshal(rule.EventPattern)
if nil != err {
return nil, err
}
ruleJSON["EventPattern"] = string(eventPatternString)
}
if rule.ScheduleExpression != "" {
ruleJSON["ScheduleExpression"] = rule.ScheduleExpression
}
if nil != rule.RuleTarget {
ruleJSON["RuleTarget"] = rule.RuleTarget
}
return json.Marshal(ruleJSON)
} | go | func (rule CloudWatchEventsRule) MarshalJSON() ([]byte, error) {
ruleJSON := map[string]interface{}{}
if rule.Description != "" {
ruleJSON["Description"] = rule.Description
}
if nil != rule.EventPattern {
eventPatternString, err := json.Marshal(rule.EventPattern)
if nil != err {
return nil, err
}
ruleJSON["EventPattern"] = string(eventPatternString)
}
if rule.ScheduleExpression != "" {
ruleJSON["ScheduleExpression"] = rule.ScheduleExpression
}
if nil != rule.RuleTarget {
ruleJSON["RuleTarget"] = rule.RuleTarget
}
return json.Marshal(ruleJSON)
} | [
"func",
"(",
"rule",
"CloudWatchEventsRule",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"ruleJSON",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"}",
"\n\n",
"if",
"rule",
".",
"Description",
"!=",
"\"",
"\"",
"{",
"ruleJSON",
"[",
"\"",
"\"",
"]",
"=",
"rule",
".",
"Description",
"\n",
"}",
"\n",
"if",
"nil",
"!=",
"rule",
".",
"EventPattern",
"{",
"eventPatternString",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"rule",
".",
"EventPattern",
")",
"\n",
"if",
"nil",
"!=",
"err",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"ruleJSON",
"[",
"\"",
"\"",
"]",
"=",
"string",
"(",
"eventPatternString",
")",
"\n",
"}",
"\n",
"if",
"rule",
".",
"ScheduleExpression",
"!=",
"\"",
"\"",
"{",
"ruleJSON",
"[",
"\"",
"\"",
"]",
"=",
"rule",
".",
"ScheduleExpression",
"\n",
"}",
"\n",
"if",
"nil",
"!=",
"rule",
".",
"RuleTarget",
"{",
"ruleJSON",
"[",
"\"",
"\"",
"]",
"=",
"rule",
".",
"RuleTarget",
"\n",
"}",
"\n",
"return",
"json",
".",
"Marshal",
"(",
"ruleJSON",
")",
"\n",
"}"
] | // MarshalJSON customizes the JSON representation used when serializing to the
// CloudFormation template representation. | [
"MarshalJSON",
"customizes",
"the",
"JSON",
"representation",
"used",
"when",
"serializing",
"to",
"the",
"CloudFormation",
"template",
"representation",
"."
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/lambda_permissions.go#L757-L777 |
1,230 | mweagle/Sparta | aws/apigateway/response.go | Error | func (apigError *Error) Error() string {
bytes, bytesErr := json.Marshal(apigError)
if bytesErr != nil {
bytes = []byte(http.StatusText(http.StatusInternalServerError))
}
return string(bytes)
} | go | func (apigError *Error) Error() string {
bytes, bytesErr := json.Marshal(apigError)
if bytesErr != nil {
bytes = []byte(http.StatusText(http.StatusInternalServerError))
}
return string(bytes)
} | [
"func",
"(",
"apigError",
"*",
"Error",
")",
"Error",
"(",
")",
"string",
"{",
"bytes",
",",
"bytesErr",
":=",
"json",
".",
"Marshal",
"(",
"apigError",
")",
"\n",
"if",
"bytesErr",
"!=",
"nil",
"{",
"bytes",
"=",
"[",
"]",
"byte",
"(",
"http",
".",
"StatusText",
"(",
"http",
".",
"StatusInternalServerError",
")",
")",
"\n",
"}",
"\n",
"return",
"string",
"(",
"bytes",
")",
"\n",
"}"
] | // Error returns the JSONified version of this error which will
// trigger the appropriate integration mapping. | [
"Error",
"returns",
"the",
"JSONified",
"version",
"of",
"this",
"error",
"which",
"will",
"trigger",
"the",
"appropriate",
"integration",
"mapping",
"."
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/apigateway/response.go#L21-L27 |
1,231 | mweagle/Sparta | aws/apigateway/response.go | NewErrorResponse | func NewErrorResponse(statusCode int, messages ...interface{}) *Error {
additionalMessages := make([]string, len(messages))
for eachIndex, eachMessage := range messages {
switch typedValue := eachMessage.(type) {
case error:
additionalMessages[eachIndex] = typedValue.Error()
default:
additionalMessages[eachIndex] = fmt.Sprintf("%v", typedValue)
}
}
err := &Error{
Code: statusCode,
Err: http.StatusText(statusCode),
Message: strings.Join(additionalMessages, " "),
Context: make(map[string]interface{}),
}
if len(err.Err) <= 0 {
err.Code = http.StatusInternalServerError
err.Err = http.StatusText(http.StatusInternalServerError)
}
return err
} | go | func NewErrorResponse(statusCode int, messages ...interface{}) *Error {
additionalMessages := make([]string, len(messages))
for eachIndex, eachMessage := range messages {
switch typedValue := eachMessage.(type) {
case error:
additionalMessages[eachIndex] = typedValue.Error()
default:
additionalMessages[eachIndex] = fmt.Sprintf("%v", typedValue)
}
}
err := &Error{
Code: statusCode,
Err: http.StatusText(statusCode),
Message: strings.Join(additionalMessages, " "),
Context: make(map[string]interface{}),
}
if len(err.Err) <= 0 {
err.Code = http.StatusInternalServerError
err.Err = http.StatusText(http.StatusInternalServerError)
}
return err
} | [
"func",
"NewErrorResponse",
"(",
"statusCode",
"int",
",",
"messages",
"...",
"interface",
"{",
"}",
")",
"*",
"Error",
"{",
"additionalMessages",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"messages",
")",
")",
"\n",
"for",
"eachIndex",
",",
"eachMessage",
":=",
"range",
"messages",
"{",
"switch",
"typedValue",
":=",
"eachMessage",
".",
"(",
"type",
")",
"{",
"case",
"error",
":",
"additionalMessages",
"[",
"eachIndex",
"]",
"=",
"typedValue",
".",
"Error",
"(",
")",
"\n",
"default",
":",
"additionalMessages",
"[",
"eachIndex",
"]",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"typedValue",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"err",
":=",
"&",
"Error",
"{",
"Code",
":",
"statusCode",
",",
"Err",
":",
"http",
".",
"StatusText",
"(",
"statusCode",
")",
",",
"Message",
":",
"strings",
".",
"Join",
"(",
"additionalMessages",
",",
"\"",
"\"",
")",
",",
"Context",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
",",
"}",
"\n",
"if",
"len",
"(",
"err",
".",
"Err",
")",
"<=",
"0",
"{",
"err",
".",
"Code",
"=",
"http",
".",
"StatusInternalServerError",
"\n",
"err",
".",
"Err",
"=",
"http",
".",
"StatusText",
"(",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // NewErrorResponse returns a response that satisfies
// the regular expression used to determine integration mappings
// via the API Gateway. messages is a stringable type. Error interface
// instances will be properly typecast. | [
"NewErrorResponse",
"returns",
"a",
"response",
"that",
"satisfies",
"the",
"regular",
"expression",
"used",
"to",
"determine",
"integration",
"mappings",
"via",
"the",
"API",
"Gateway",
".",
"messages",
"is",
"a",
"stringable",
"type",
".",
"Error",
"interface",
"instances",
"will",
"be",
"properly",
"typecast",
"."
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/apigateway/response.go#L33-L56 |
1,232 | mweagle/Sparta | aws/apigateway/response.go | MarshalJSON | func (resp *Response) MarshalJSON() ([]byte, error) {
canonicalResponse := canonicalResponse{
Code: resp.Code,
Body: resp.Body,
}
if len(resp.Headers) != 0 {
canonicalResponse.Headers = make(map[string]string)
for eachKey, eachValue := range resp.Headers {
canonicalResponse.Headers[strings.ToLower(eachKey)] = eachValue
}
}
return json.Marshal(&canonicalResponse)
} | go | func (resp *Response) MarshalJSON() ([]byte, error) {
canonicalResponse := canonicalResponse{
Code: resp.Code,
Body: resp.Body,
}
if len(resp.Headers) != 0 {
canonicalResponse.Headers = make(map[string]string)
for eachKey, eachValue := range resp.Headers {
canonicalResponse.Headers[strings.ToLower(eachKey)] = eachValue
}
}
return json.Marshal(&canonicalResponse)
} | [
"func",
"(",
"resp",
"*",
"Response",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"canonicalResponse",
":=",
"canonicalResponse",
"{",
"Code",
":",
"resp",
".",
"Code",
",",
"Body",
":",
"resp",
".",
"Body",
",",
"}",
"\n",
"if",
"len",
"(",
"resp",
".",
"Headers",
")",
"!=",
"0",
"{",
"canonicalResponse",
".",
"Headers",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"for",
"eachKey",
",",
"eachValue",
":=",
"range",
"resp",
".",
"Headers",
"{",
"canonicalResponse",
".",
"Headers",
"[",
"strings",
".",
"ToLower",
"(",
"eachKey",
")",
"]",
"=",
"eachValue",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"json",
".",
"Marshal",
"(",
"&",
"canonicalResponse",
")",
"\n",
"}"
] | // MarshalJSON is a custom marshaller to ensure that the marshalled
// headers are always lowercase | [
"MarshalJSON",
"is",
"a",
"custom",
"marshaller",
"to",
"ensure",
"that",
"the",
"marshalled",
"headers",
"are",
"always",
"lowercase"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/apigateway/response.go#L79-L91 |
1,233 | mweagle/Sparta | aws/apigateway/response.go | NewResponse | func NewResponse(code int, body interface{}, headers ...map[string]string) *Response {
response := &Response{
Code: code,
Body: body,
}
if len(headers) != 0 {
response.Headers = make(map[string]string)
for _, eachHeaderMap := range headers {
for eachKey, eachValue := range eachHeaderMap {
response.Headers[eachKey] = eachValue
}
}
}
return response
} | go | func NewResponse(code int, body interface{}, headers ...map[string]string) *Response {
response := &Response{
Code: code,
Body: body,
}
if len(headers) != 0 {
response.Headers = make(map[string]string)
for _, eachHeaderMap := range headers {
for eachKey, eachValue := range eachHeaderMap {
response.Headers[eachKey] = eachValue
}
}
}
return response
} | [
"func",
"NewResponse",
"(",
"code",
"int",
",",
"body",
"interface",
"{",
"}",
",",
"headers",
"...",
"map",
"[",
"string",
"]",
"string",
")",
"*",
"Response",
"{",
"response",
":=",
"&",
"Response",
"{",
"Code",
":",
"code",
",",
"Body",
":",
"body",
",",
"}",
"\n",
"if",
"len",
"(",
"headers",
")",
"!=",
"0",
"{",
"response",
".",
"Headers",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"for",
"_",
",",
"eachHeaderMap",
":=",
"range",
"headers",
"{",
"for",
"eachKey",
",",
"eachValue",
":=",
"range",
"eachHeaderMap",
"{",
"response",
".",
"Headers",
"[",
"eachKey",
"]",
"=",
"eachValue",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"response",
"\n",
"}"
] | // NewResponse returns an API Gateway response object | [
"NewResponse",
"returns",
"an",
"API",
"Gateway",
"response",
"object"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/apigateway/response.go#L94-L108 |
1,234 | mweagle/Sparta | aws/step/dynamodb.go | NewDynamoDBGetItemState | func NewDynamoDBGetItemState(stateName string,
parameters DynamoDBGetItemParameters) *DynamoDBGetItemState {
dgis := &DynamoDBGetItemState{
BaseTask: BaseTask{
baseInnerState: baseInnerState{
name: stateName,
id: rand.Int63(),
},
},
parameters: parameters,
}
return dgis
} | go | func NewDynamoDBGetItemState(stateName string,
parameters DynamoDBGetItemParameters) *DynamoDBGetItemState {
dgis := &DynamoDBGetItemState{
BaseTask: BaseTask{
baseInnerState: baseInnerState{
name: stateName,
id: rand.Int63(),
},
},
parameters: parameters,
}
return dgis
} | [
"func",
"NewDynamoDBGetItemState",
"(",
"stateName",
"string",
",",
"parameters",
"DynamoDBGetItemParameters",
")",
"*",
"DynamoDBGetItemState",
"{",
"dgis",
":=",
"&",
"DynamoDBGetItemState",
"{",
"BaseTask",
":",
"BaseTask",
"{",
"baseInnerState",
":",
"baseInnerState",
"{",
"name",
":",
"stateName",
",",
"id",
":",
"rand",
".",
"Int63",
"(",
")",
",",
"}",
",",
"}",
",",
"parameters",
":",
"parameters",
",",
"}",
"\n",
"return",
"dgis",
"\n",
"}"
] | // NewDynamoDBGetItemState returns an initialized DynamoDB GetItem state | [
"NewDynamoDBGetItemState",
"returns",
"an",
"initialized",
"DynamoDB",
"GetItem",
"state"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/dynamodb.go#L47-L60 |
1,235 | mweagle/Sparta | aws/step/dynamodb.go | NewDynamoDBPutItemState | func NewDynamoDBPutItemState(stateName string,
parameters DynamoDBPutItemParameters) *DynamoDBPutItemState {
dpis := &DynamoDBPutItemState{
BaseTask: BaseTask{
baseInnerState: baseInnerState{
name: stateName,
id: rand.Int63(),
},
},
parameters: parameters,
}
return dpis
} | go | func NewDynamoDBPutItemState(stateName string,
parameters DynamoDBPutItemParameters) *DynamoDBPutItemState {
dpis := &DynamoDBPutItemState{
BaseTask: BaseTask{
baseInnerState: baseInnerState{
name: stateName,
id: rand.Int63(),
},
},
parameters: parameters,
}
return dpis
} | [
"func",
"NewDynamoDBPutItemState",
"(",
"stateName",
"string",
",",
"parameters",
"DynamoDBPutItemParameters",
")",
"*",
"DynamoDBPutItemState",
"{",
"dpis",
":=",
"&",
"DynamoDBPutItemState",
"{",
"BaseTask",
":",
"BaseTask",
"{",
"baseInnerState",
":",
"baseInnerState",
"{",
"name",
":",
"stateName",
",",
"id",
":",
"rand",
".",
"Int63",
"(",
")",
",",
"}",
",",
"}",
",",
"parameters",
":",
"parameters",
",",
"}",
"\n",
"return",
"dpis",
"\n",
"}"
] | // NewDynamoDBPutItemState returns an initialized DynamoDB PutItem state | [
"NewDynamoDBPutItemState",
"returns",
"an",
"initialized",
"DynamoDB",
"PutItem",
"state"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/dynamodb.go#L102-L115 |
1,236 | mweagle/Sparta | aws/accessor/interface.go | xrayInit | func xrayInit(awsClient *client.Client) {
if os.Getenv("AWS_XRAY_DAEMON_ADDRESS") != "" &&
os.Getenv("AWS_EXECUTION_ENV") != "" {
xray.AWS(awsClient)
}
} | go | func xrayInit(awsClient *client.Client) {
if os.Getenv("AWS_XRAY_DAEMON_ADDRESS") != "" &&
os.Getenv("AWS_EXECUTION_ENV") != "" {
xray.AWS(awsClient)
}
} | [
"func",
"xrayInit",
"(",
"awsClient",
"*",
"client",
".",
"Client",
")",
"{",
"if",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"&&",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"xray",
".",
"AWS",
"(",
"awsClient",
")",
"\n",
"}",
"\n",
"}"
] | // Conditionally attach XRay if it seems like the right thing to do | [
"Conditionally",
"attach",
"XRay",
"if",
"it",
"seems",
"like",
"the",
"right",
"thing",
"to",
"do"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/accessor/interface.go#L12-L17 |
1,237 | mweagle/Sparta | archetype/codecommit.go | OnCodeCommitEvent | func (reactorFunc CodeCommitReactorFunc) OnCodeCommitEvent(ctx context.Context,
codeCommitEvent awsLambdaEvents.CodeCommitEvent) (interface{}, error) {
return reactorFunc(ctx, codeCommitEvent)
} | go | func (reactorFunc CodeCommitReactorFunc) OnCodeCommitEvent(ctx context.Context,
codeCommitEvent awsLambdaEvents.CodeCommitEvent) (interface{}, error) {
return reactorFunc(ctx, codeCommitEvent)
} | [
"func",
"(",
"reactorFunc",
"CodeCommitReactorFunc",
")",
"OnCodeCommitEvent",
"(",
"ctx",
"context",
".",
"Context",
",",
"codeCommitEvent",
"awsLambdaEvents",
".",
"CodeCommitEvent",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"return",
"reactorFunc",
"(",
"ctx",
",",
"codeCommitEvent",
")",
"\n",
"}"
] | // OnCodeCommitEvent satisfies the CodeCommitReactor interface | [
"OnCodeCommitEvent",
"satisfies",
"the",
"CodeCommitReactor",
"interface"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/archetype/codecommit.go#L28-L31 |
1,238 | mweagle/Sparta | archetype/codecommit.go | NewCodeCommitReactor | func NewCodeCommitReactor(reactor CodeCommitReactor,
repositoryName gocf.Stringable,
branches []string,
events []string,
additionalLambdaPermissions []sparta.IAMRolePrivilege) (*sparta.LambdaAWSInfo, error) {
reactorLambda := func(ctx context.Context, codeCommitEvent awsLambdaEvents.CodeCommitEvent) (interface{}, error) {
return reactor.OnCodeCommitEvent(ctx, codeCommitEvent)
}
lambdaFn, lambdaFnErr := sparta.NewAWSLambda(reactorName(reactor),
reactorLambda,
sparta.IAMRoleDefinition{})
if lambdaFnErr != nil {
return nil, errors.Wrapf(lambdaFnErr, "attempting to create reactor")
}
lambdaFn.Permissions = append(lambdaFn.Permissions, sparta.CodeCommitPermission{
BasePermission: sparta.BasePermission{
SourceArn: repositoryName,
},
RepositoryName: repositoryName.String(),
Branches: branches,
Events: events,
})
if len(additionalLambdaPermissions) != 0 {
lambdaFn.RoleDefinition.Privileges = additionalLambdaPermissions
}
return lambdaFn, nil
} | go | func NewCodeCommitReactor(reactor CodeCommitReactor,
repositoryName gocf.Stringable,
branches []string,
events []string,
additionalLambdaPermissions []sparta.IAMRolePrivilege) (*sparta.LambdaAWSInfo, error) {
reactorLambda := func(ctx context.Context, codeCommitEvent awsLambdaEvents.CodeCommitEvent) (interface{}, error) {
return reactor.OnCodeCommitEvent(ctx, codeCommitEvent)
}
lambdaFn, lambdaFnErr := sparta.NewAWSLambda(reactorName(reactor),
reactorLambda,
sparta.IAMRoleDefinition{})
if lambdaFnErr != nil {
return nil, errors.Wrapf(lambdaFnErr, "attempting to create reactor")
}
lambdaFn.Permissions = append(lambdaFn.Permissions, sparta.CodeCommitPermission{
BasePermission: sparta.BasePermission{
SourceArn: repositoryName,
},
RepositoryName: repositoryName.String(),
Branches: branches,
Events: events,
})
if len(additionalLambdaPermissions) != 0 {
lambdaFn.RoleDefinition.Privileges = additionalLambdaPermissions
}
return lambdaFn, nil
} | [
"func",
"NewCodeCommitReactor",
"(",
"reactor",
"CodeCommitReactor",
",",
"repositoryName",
"gocf",
".",
"Stringable",
",",
"branches",
"[",
"]",
"string",
",",
"events",
"[",
"]",
"string",
",",
"additionalLambdaPermissions",
"[",
"]",
"sparta",
".",
"IAMRolePrivilege",
")",
"(",
"*",
"sparta",
".",
"LambdaAWSInfo",
",",
"error",
")",
"{",
"reactorLambda",
":=",
"func",
"(",
"ctx",
"context",
".",
"Context",
",",
"codeCommitEvent",
"awsLambdaEvents",
".",
"CodeCommitEvent",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"return",
"reactor",
".",
"OnCodeCommitEvent",
"(",
"ctx",
",",
"codeCommitEvent",
")",
"\n",
"}",
"\n\n",
"lambdaFn",
",",
"lambdaFnErr",
":=",
"sparta",
".",
"NewAWSLambda",
"(",
"reactorName",
"(",
"reactor",
")",
",",
"reactorLambda",
",",
"sparta",
".",
"IAMRoleDefinition",
"{",
"}",
")",
"\n",
"if",
"lambdaFnErr",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrapf",
"(",
"lambdaFnErr",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"lambdaFn",
".",
"Permissions",
"=",
"append",
"(",
"lambdaFn",
".",
"Permissions",
",",
"sparta",
".",
"CodeCommitPermission",
"{",
"BasePermission",
":",
"sparta",
".",
"BasePermission",
"{",
"SourceArn",
":",
"repositoryName",
",",
"}",
",",
"RepositoryName",
":",
"repositoryName",
".",
"String",
"(",
")",
",",
"Branches",
":",
"branches",
",",
"Events",
":",
"events",
",",
"}",
")",
"\n",
"if",
"len",
"(",
"additionalLambdaPermissions",
")",
"!=",
"0",
"{",
"lambdaFn",
".",
"RoleDefinition",
".",
"Privileges",
"=",
"additionalLambdaPermissions",
"\n",
"}",
"\n",
"return",
"lambdaFn",
",",
"nil",
"\n",
"}"
] | // NewCodeCommitReactor returns an SNS reactor lambda function | [
"NewCodeCommitReactor",
"returns",
"an",
"SNS",
"reactor",
"lambda",
"function"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/archetype/codecommit.go#L39-L68 |
1,239 | mweagle/Sparta | aws/accessor/s3.go | BucketPrivilege | func (svc *S3Accessor) BucketPrivilege(bucketPrivs ...string) sparta.IAMRolePrivilege {
return sparta.IAMRolePrivilege{
Actions: bucketPrivs,
Resource: spartaCF.S3ArnForBucket(gocf.Ref(svc.S3BucketResourceName)),
}
} | go | func (svc *S3Accessor) BucketPrivilege(bucketPrivs ...string) sparta.IAMRolePrivilege {
return sparta.IAMRolePrivilege{
Actions: bucketPrivs,
Resource: spartaCF.S3ArnForBucket(gocf.Ref(svc.S3BucketResourceName)),
}
} | [
"func",
"(",
"svc",
"*",
"S3Accessor",
")",
"BucketPrivilege",
"(",
"bucketPrivs",
"...",
"string",
")",
"sparta",
".",
"IAMRolePrivilege",
"{",
"return",
"sparta",
".",
"IAMRolePrivilege",
"{",
"Actions",
":",
"bucketPrivs",
",",
"Resource",
":",
"spartaCF",
".",
"S3ArnForBucket",
"(",
"gocf",
".",
"Ref",
"(",
"svc",
".",
"S3BucketResourceName",
")",
")",
",",
"}",
"\n",
"}"
] | // BucketPrivilege returns a privilege that targets the Bucket | [
"BucketPrivilege",
"returns",
"a",
"privilege",
"that",
"targets",
"the",
"Bucket"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/accessor/s3.go#L26-L31 |
1,240 | mweagle/Sparta | aws/accessor/s3.go | KeysPrivilege | func (svc *S3Accessor) KeysPrivilege(keyPrivileges ...string) sparta.IAMRolePrivilege {
return sparta.IAMRolePrivilege{
Actions: keyPrivileges,
Resource: spartaCF.S3AllKeysArnForBucket(gocf.Ref(svc.S3BucketResourceName)),
}
} | go | func (svc *S3Accessor) KeysPrivilege(keyPrivileges ...string) sparta.IAMRolePrivilege {
return sparta.IAMRolePrivilege{
Actions: keyPrivileges,
Resource: spartaCF.S3AllKeysArnForBucket(gocf.Ref(svc.S3BucketResourceName)),
}
} | [
"func",
"(",
"svc",
"*",
"S3Accessor",
")",
"KeysPrivilege",
"(",
"keyPrivileges",
"...",
"string",
")",
"sparta",
".",
"IAMRolePrivilege",
"{",
"return",
"sparta",
".",
"IAMRolePrivilege",
"{",
"Actions",
":",
"keyPrivileges",
",",
"Resource",
":",
"spartaCF",
".",
"S3AllKeysArnForBucket",
"(",
"gocf",
".",
"Ref",
"(",
"svc",
".",
"S3BucketResourceName",
")",
")",
",",
"}",
"\n",
"}"
] | // KeysPrivilege returns a privilege that targets the Bucket objects | [
"KeysPrivilege",
"returns",
"a",
"privilege",
"that",
"targets",
"the",
"Bucket",
"objects"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/accessor/s3.go#L34-L39 |
1,241 | mweagle/Sparta | execute_build.go | awsLambdaFunctionName | func awsLambdaFunctionName(internalFunctionName string) gocf.Stringable {
sanitizedName := awsLambdaInternalName(internalFunctionName)
// When we build, we return a gocf.Join that
// will use the stack name and the internal name. When we run, we're going
// to use the name discovered from the environment.
return gocf.Join("",
gocf.Ref("AWS::StackName"),
gocf.String(functionNameDelimiter),
gocf.String(sanitizedName))
} | go | func awsLambdaFunctionName(internalFunctionName string) gocf.Stringable {
sanitizedName := awsLambdaInternalName(internalFunctionName)
// When we build, we return a gocf.Join that
// will use the stack name and the internal name. When we run, we're going
// to use the name discovered from the environment.
return gocf.Join("",
gocf.Ref("AWS::StackName"),
gocf.String(functionNameDelimiter),
gocf.String(sanitizedName))
} | [
"func",
"awsLambdaFunctionName",
"(",
"internalFunctionName",
"string",
")",
"gocf",
".",
"Stringable",
"{",
"sanitizedName",
":=",
"awsLambdaInternalName",
"(",
"internalFunctionName",
")",
"\n",
"// When we build, we return a gocf.Join that",
"// will use the stack name and the internal name. When we run, we're going",
"// to use the name discovered from the environment.",
"return",
"gocf",
".",
"Join",
"(",
"\"",
"\"",
",",
"gocf",
".",
"Ref",
"(",
"\"",
"\"",
")",
",",
"gocf",
".",
"String",
"(",
"functionNameDelimiter",
")",
",",
"gocf",
".",
"String",
"(",
"sanitizedName",
")",
")",
"\n",
"}"
] | // awsLambdaFunctionName returns the name of the function, which
// is set in the CloudFormation template that is published
// into the container as `AWS_LAMBDA_FUNCTION_NAME`. The function name
// is dependent on the CloudFormation stack name so that
// CodePipeline based builds can properly create unique FunctionNAmes
// within an account | [
"awsLambdaFunctionName",
"returns",
"the",
"name",
"of",
"the",
"function",
"which",
"is",
"set",
"in",
"the",
"CloudFormation",
"template",
"that",
"is",
"published",
"into",
"the",
"container",
"as",
"AWS_LAMBDA_FUNCTION_NAME",
".",
"The",
"function",
"name",
"is",
"dependent",
"on",
"the",
"CloudFormation",
"stack",
"name",
"so",
"that",
"CodePipeline",
"based",
"builds",
"can",
"properly",
"create",
"unique",
"FunctionNAmes",
"within",
"an",
"account"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/execute_build.go#L31-L40 |
1,242 | mweagle/Sparta | archetype/dynamodb.go | OnDynamoEvent | func (reactorFunc DynamoDBReactorFunc) OnDynamoEvent(ctx context.Context,
dynamoEvent awsLambdaEvents.DynamoDBEvent) (interface{}, error) {
return reactorFunc(ctx, dynamoEvent)
} | go | func (reactorFunc DynamoDBReactorFunc) OnDynamoEvent(ctx context.Context,
dynamoEvent awsLambdaEvents.DynamoDBEvent) (interface{}, error) {
return reactorFunc(ctx, dynamoEvent)
} | [
"func",
"(",
"reactorFunc",
"DynamoDBReactorFunc",
")",
"OnDynamoEvent",
"(",
"ctx",
"context",
".",
"Context",
",",
"dynamoEvent",
"awsLambdaEvents",
".",
"DynamoDBEvent",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"return",
"reactorFunc",
"(",
"ctx",
",",
"dynamoEvent",
")",
"\n",
"}"
] | // OnDynamoEvent satisfies the DynamoDBReactor interface | [
"OnDynamoEvent",
"satisfies",
"the",
"DynamoDBReactor",
"interface"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/archetype/dynamodb.go#L29-L32 |
1,243 | mweagle/Sparta | archetype/dynamodb.go | ReactorName | func (reactorFunc DynamoDBReactorFunc) ReactorName() string {
return runtime.FuncForPC(reflect.ValueOf(reactorFunc).Pointer()).Name()
} | go | func (reactorFunc DynamoDBReactorFunc) ReactorName() string {
return runtime.FuncForPC(reflect.ValueOf(reactorFunc).Pointer()).Name()
} | [
"func",
"(",
"reactorFunc",
"DynamoDBReactorFunc",
")",
"ReactorName",
"(",
")",
"string",
"{",
"return",
"runtime",
".",
"FuncForPC",
"(",
"reflect",
".",
"ValueOf",
"(",
"reactorFunc",
")",
".",
"Pointer",
"(",
")",
")",
".",
"Name",
"(",
")",
"\n",
"}"
] | // ReactorName provides the name of the reactor func | [
"ReactorName",
"provides",
"the",
"name",
"of",
"the",
"reactor",
"func"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/archetype/dynamodb.go#L35-L37 |
1,244 | mweagle/Sparta | archetype/dynamodb.go | NewDynamoDBReactor | func NewDynamoDBReactor(reactor DynamoDBReactor,
dynamoDBARN gocf.Stringable,
startingPosition string,
batchSize int64,
additionalLambdaPermissions []sparta.IAMRolePrivilege) (*sparta.LambdaAWSInfo, error) {
reactorLambda := func(ctx context.Context, dynamoEvent awsLambdaEvents.DynamoDBEvent) (interface{}, error) {
return reactor.OnDynamoEvent(ctx, dynamoEvent)
}
lambdaFn, lambdaFnErr := sparta.NewAWSLambda(reactorName(reactor),
reactorLambda,
sparta.IAMRoleDefinition{})
if lambdaFnErr != nil {
return nil, errors.Wrapf(lambdaFnErr, "attempting to create reactor")
}
lambdaFn.EventSourceMappings = append(lambdaFn.EventSourceMappings,
&sparta.EventSourceMapping{
EventSourceArn: dynamoDBARN,
StartingPosition: startingPosition,
BatchSize: batchSize,
})
if len(additionalLambdaPermissions) != 0 {
lambdaFn.RoleDefinition.Privileges = additionalLambdaPermissions
}
return lambdaFn, nil
} | go | func NewDynamoDBReactor(reactor DynamoDBReactor,
dynamoDBARN gocf.Stringable,
startingPosition string,
batchSize int64,
additionalLambdaPermissions []sparta.IAMRolePrivilege) (*sparta.LambdaAWSInfo, error) {
reactorLambda := func(ctx context.Context, dynamoEvent awsLambdaEvents.DynamoDBEvent) (interface{}, error) {
return reactor.OnDynamoEvent(ctx, dynamoEvent)
}
lambdaFn, lambdaFnErr := sparta.NewAWSLambda(reactorName(reactor),
reactorLambda,
sparta.IAMRoleDefinition{})
if lambdaFnErr != nil {
return nil, errors.Wrapf(lambdaFnErr, "attempting to create reactor")
}
lambdaFn.EventSourceMappings = append(lambdaFn.EventSourceMappings,
&sparta.EventSourceMapping{
EventSourceArn: dynamoDBARN,
StartingPosition: startingPosition,
BatchSize: batchSize,
})
if len(additionalLambdaPermissions) != 0 {
lambdaFn.RoleDefinition.Privileges = additionalLambdaPermissions
}
return lambdaFn, nil
} | [
"func",
"NewDynamoDBReactor",
"(",
"reactor",
"DynamoDBReactor",
",",
"dynamoDBARN",
"gocf",
".",
"Stringable",
",",
"startingPosition",
"string",
",",
"batchSize",
"int64",
",",
"additionalLambdaPermissions",
"[",
"]",
"sparta",
".",
"IAMRolePrivilege",
")",
"(",
"*",
"sparta",
".",
"LambdaAWSInfo",
",",
"error",
")",
"{",
"reactorLambda",
":=",
"func",
"(",
"ctx",
"context",
".",
"Context",
",",
"dynamoEvent",
"awsLambdaEvents",
".",
"DynamoDBEvent",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"return",
"reactor",
".",
"OnDynamoEvent",
"(",
"ctx",
",",
"dynamoEvent",
")",
"\n",
"}",
"\n\n",
"lambdaFn",
",",
"lambdaFnErr",
":=",
"sparta",
".",
"NewAWSLambda",
"(",
"reactorName",
"(",
"reactor",
")",
",",
"reactorLambda",
",",
"sparta",
".",
"IAMRoleDefinition",
"{",
"}",
")",
"\n",
"if",
"lambdaFnErr",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrapf",
"(",
"lambdaFnErr",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"lambdaFn",
".",
"EventSourceMappings",
"=",
"append",
"(",
"lambdaFn",
".",
"EventSourceMappings",
",",
"&",
"sparta",
".",
"EventSourceMapping",
"{",
"EventSourceArn",
":",
"dynamoDBARN",
",",
"StartingPosition",
":",
"startingPosition",
",",
"BatchSize",
":",
"batchSize",
",",
"}",
")",
"\n",
"if",
"len",
"(",
"additionalLambdaPermissions",
")",
"!=",
"0",
"{",
"lambdaFn",
".",
"RoleDefinition",
".",
"Privileges",
"=",
"additionalLambdaPermissions",
"\n",
"}",
"\n",
"return",
"lambdaFn",
",",
"nil",
"\n",
"}"
] | // NewDynamoDBReactor returns an Kinesis reactor lambda function | [
"NewDynamoDBReactor",
"returns",
"an",
"Kinesis",
"reactor",
"lambda",
"function"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/archetype/dynamodb.go#L40-L67 |
1,245 | mweagle/Sparta | aws/step/batch.go | NewBatchTaskState | func NewBatchTaskState(stateName string,
parameters BatchTaskParameters) *BatchTaskState {
sns := &BatchTaskState{
BaseTask: BaseTask{
baseInnerState: baseInnerState{
name: stateName,
id: rand.Int63(),
},
},
parameters: parameters,
}
return sns
} | go | func NewBatchTaskState(stateName string,
parameters BatchTaskParameters) *BatchTaskState {
sns := &BatchTaskState{
BaseTask: BaseTask{
baseInnerState: baseInnerState{
name: stateName,
id: rand.Int63(),
},
},
parameters: parameters,
}
return sns
} | [
"func",
"NewBatchTaskState",
"(",
"stateName",
"string",
",",
"parameters",
"BatchTaskParameters",
")",
"*",
"BatchTaskState",
"{",
"sns",
":=",
"&",
"BatchTaskState",
"{",
"BaseTask",
":",
"BaseTask",
"{",
"baseInnerState",
":",
"baseInnerState",
"{",
"name",
":",
"stateName",
",",
"id",
":",
"rand",
".",
"Int63",
"(",
")",
",",
"}",
",",
"}",
",",
"parameters",
":",
"parameters",
",",
"}",
"\n",
"return",
"sns",
"\n",
"}"
] | // NewBatchTaskState returns an initialized BatchTaskState | [
"NewBatchTaskState",
"returns",
"an",
"initialized",
"BatchTaskState"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/batch.go#L39-L52 |
1,246 | mweagle/Sparta | resource_references.go | resolveResourceRef | func resolveResourceRef(expr interface{}) (*resourceRef, error) {
// Is there any chance it's just a string?
typedString, typedStringOk := expr.(string)
if typedStringOk {
return &resourceRef{
RefType: resourceLiteral,
ResourceName: typedString,
}, nil
}
// Some type of intrinsic function?
marshalled, marshalledErr := json.Marshal(expr)
if marshalledErr != nil {
return nil, errors.Errorf("Failed to unmarshal dynamic resource ref %v", expr)
}
var refFunc gocf.RefFunc
if json.Unmarshal(marshalled, &refFunc) == nil &&
len(refFunc.Name) != 0 {
return &resourceRef{
RefType: resourceRefFunc,
ResourceName: refFunc.Name,
}, nil
}
var getAttFunc gocf.GetAttFunc
if json.Unmarshal(marshalled, &getAttFunc) == nil && len(getAttFunc.Resource) != 0 {
return &resourceRef{
RefType: resourceGetAttrFunc,
ResourceName: getAttFunc.Resource,
}, nil
}
// Any chance it's a string?
var stringExprFunc gocf.StringExpr
if json.Unmarshal(marshalled, &stringExprFunc) == nil && len(stringExprFunc.Literal) != 0 {
return &resourceRef{
RefType: resourceStringFunc,
ResourceName: stringExprFunc.Literal,
}, nil
}
// Nope
return nil, nil
} | go | func resolveResourceRef(expr interface{}) (*resourceRef, error) {
// Is there any chance it's just a string?
typedString, typedStringOk := expr.(string)
if typedStringOk {
return &resourceRef{
RefType: resourceLiteral,
ResourceName: typedString,
}, nil
}
// Some type of intrinsic function?
marshalled, marshalledErr := json.Marshal(expr)
if marshalledErr != nil {
return nil, errors.Errorf("Failed to unmarshal dynamic resource ref %v", expr)
}
var refFunc gocf.RefFunc
if json.Unmarshal(marshalled, &refFunc) == nil &&
len(refFunc.Name) != 0 {
return &resourceRef{
RefType: resourceRefFunc,
ResourceName: refFunc.Name,
}, nil
}
var getAttFunc gocf.GetAttFunc
if json.Unmarshal(marshalled, &getAttFunc) == nil && len(getAttFunc.Resource) != 0 {
return &resourceRef{
RefType: resourceGetAttrFunc,
ResourceName: getAttFunc.Resource,
}, nil
}
// Any chance it's a string?
var stringExprFunc gocf.StringExpr
if json.Unmarshal(marshalled, &stringExprFunc) == nil && len(stringExprFunc.Literal) != 0 {
return &resourceRef{
RefType: resourceStringFunc,
ResourceName: stringExprFunc.Literal,
}, nil
}
// Nope
return nil, nil
} | [
"func",
"resolveResourceRef",
"(",
"expr",
"interface",
"{",
"}",
")",
"(",
"*",
"resourceRef",
",",
"error",
")",
"{",
"// Is there any chance it's just a string?",
"typedString",
",",
"typedStringOk",
":=",
"expr",
".",
"(",
"string",
")",
"\n",
"if",
"typedStringOk",
"{",
"return",
"&",
"resourceRef",
"{",
"RefType",
":",
"resourceLiteral",
",",
"ResourceName",
":",
"typedString",
",",
"}",
",",
"nil",
"\n",
"}",
"\n",
"// Some type of intrinsic function?",
"marshalled",
",",
"marshalledErr",
":=",
"json",
".",
"Marshal",
"(",
"expr",
")",
"\n",
"if",
"marshalledErr",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"expr",
")",
"\n",
"}",
"\n",
"var",
"refFunc",
"gocf",
".",
"RefFunc",
"\n",
"if",
"json",
".",
"Unmarshal",
"(",
"marshalled",
",",
"&",
"refFunc",
")",
"==",
"nil",
"&&",
"len",
"(",
"refFunc",
".",
"Name",
")",
"!=",
"0",
"{",
"return",
"&",
"resourceRef",
"{",
"RefType",
":",
"resourceRefFunc",
",",
"ResourceName",
":",
"refFunc",
".",
"Name",
",",
"}",
",",
"nil",
"\n",
"}",
"\n\n",
"var",
"getAttFunc",
"gocf",
".",
"GetAttFunc",
"\n",
"if",
"json",
".",
"Unmarshal",
"(",
"marshalled",
",",
"&",
"getAttFunc",
")",
"==",
"nil",
"&&",
"len",
"(",
"getAttFunc",
".",
"Resource",
")",
"!=",
"0",
"{",
"return",
"&",
"resourceRef",
"{",
"RefType",
":",
"resourceGetAttrFunc",
",",
"ResourceName",
":",
"getAttFunc",
".",
"Resource",
",",
"}",
",",
"nil",
"\n",
"}",
"\n",
"// Any chance it's a string?",
"var",
"stringExprFunc",
"gocf",
".",
"StringExpr",
"\n",
"if",
"json",
".",
"Unmarshal",
"(",
"marshalled",
",",
"&",
"stringExprFunc",
")",
"==",
"nil",
"&&",
"len",
"(",
"stringExprFunc",
".",
"Literal",
")",
"!=",
"0",
"{",
"return",
"&",
"resourceRef",
"{",
"RefType",
":",
"resourceStringFunc",
",",
"ResourceName",
":",
"stringExprFunc",
".",
"Literal",
",",
"}",
",",
"nil",
"\n",
"}",
"\n\n",
"// Nope",
"return",
"nil",
",",
"nil",
"\n",
"}"
] | // resolveResourceRef takes an interface representing a dynamic ARN
// and tries to determine the CloudFormation resource name it resolves to | [
"resolveResourceRef",
"takes",
"an",
"interface",
"representing",
"a",
"dynamic",
"ARN",
"and",
"tries",
"to",
"determine",
"the",
"CloudFormation",
"resource",
"name",
"it",
"resolves",
"to"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/resource_references.go#L38-L80 |
1,247 | mweagle/Sparta | resource_references.go | visitResolvedEventSourceMapping | func visitResolvedEventSourceMapping(visitor resolvedResourceVisitor,
lambdaAWSInfos []*LambdaAWSInfo,
template *gocf.Template,
logger *logrus.Logger) error {
//
// BEGIN
// Inline closure to wrap the visitor function so that we can provide
// specific error messages
visitEventSourceMappingRef := func(lambdaAWSInfo *LambdaAWSInfo,
eventSourceMapping *EventSourceMapping,
mappingIndex int,
resource *resourceRef) error {
annotateStatementsErr := visitor(lambdaAWSInfo,
eventSourceMapping,
mappingIndex,
resource)
// Early exit?
if annotateStatementsErr != nil {
return errors.Wrapf(annotateStatementsErr,
"Visiting event source mapping: %#v",
eventSourceMapping)
}
return nil
}
//
// END
// Iterate through every lambda function. If there is an EventSourceMapping
// that points to a piece of infastructure provisioned by this stack,
// find the referred resource and supply it to the visitor
for _, eachLambda := range lambdaAWSInfos {
for eachIndex, eachEventSource := range eachLambda.EventSourceMappings {
resourceRef, resourceRefErr := resolveResourceRef(eachEventSource.EventSourceArn)
if resourceRefErr != nil {
return errors.Wrapf(resourceRefErr,
"Failed to resolve EventSourceArn: %#v", eachEventSource)
}
// At this point everything is a string, so we need to unmarshall
// and see if the Arn is supplied by either a Ref or a GetAttr
// function. In those cases, we need to look around in the template
// to go from: EventMapping -> Type -> Lambda -> LambdaIAMRole
// so that we can add the permissions
if resourceRef != nil {
annotationErr := visitEventSourceMappingRef(eachLambda,
eachEventSource,
eachIndex,
resourceRef)
// Anything go wrong?
if annotationErr != nil {
return errors.Wrapf(annotationErr,
"Failed to annotate template for EventSourceMapping: %#v",
eachEventSource)
}
}
}
}
return nil
} | go | func visitResolvedEventSourceMapping(visitor resolvedResourceVisitor,
lambdaAWSInfos []*LambdaAWSInfo,
template *gocf.Template,
logger *logrus.Logger) error {
//
// BEGIN
// Inline closure to wrap the visitor function so that we can provide
// specific error messages
visitEventSourceMappingRef := func(lambdaAWSInfo *LambdaAWSInfo,
eventSourceMapping *EventSourceMapping,
mappingIndex int,
resource *resourceRef) error {
annotateStatementsErr := visitor(lambdaAWSInfo,
eventSourceMapping,
mappingIndex,
resource)
// Early exit?
if annotateStatementsErr != nil {
return errors.Wrapf(annotateStatementsErr,
"Visiting event source mapping: %#v",
eventSourceMapping)
}
return nil
}
//
// END
// Iterate through every lambda function. If there is an EventSourceMapping
// that points to a piece of infastructure provisioned by this stack,
// find the referred resource and supply it to the visitor
for _, eachLambda := range lambdaAWSInfos {
for eachIndex, eachEventSource := range eachLambda.EventSourceMappings {
resourceRef, resourceRefErr := resolveResourceRef(eachEventSource.EventSourceArn)
if resourceRefErr != nil {
return errors.Wrapf(resourceRefErr,
"Failed to resolve EventSourceArn: %#v", eachEventSource)
}
// At this point everything is a string, so we need to unmarshall
// and see if the Arn is supplied by either a Ref or a GetAttr
// function. In those cases, we need to look around in the template
// to go from: EventMapping -> Type -> Lambda -> LambdaIAMRole
// so that we can add the permissions
if resourceRef != nil {
annotationErr := visitEventSourceMappingRef(eachLambda,
eachEventSource,
eachIndex,
resourceRef)
// Anything go wrong?
if annotationErr != nil {
return errors.Wrapf(annotationErr,
"Failed to annotate template for EventSourceMapping: %#v",
eachEventSource)
}
}
}
}
return nil
} | [
"func",
"visitResolvedEventSourceMapping",
"(",
"visitor",
"resolvedResourceVisitor",
",",
"lambdaAWSInfos",
"[",
"]",
"*",
"LambdaAWSInfo",
",",
"template",
"*",
"gocf",
".",
"Template",
",",
"logger",
"*",
"logrus",
".",
"Logger",
")",
"error",
"{",
"//",
"// BEGIN",
"// Inline closure to wrap the visitor function so that we can provide",
"// specific error messages",
"visitEventSourceMappingRef",
":=",
"func",
"(",
"lambdaAWSInfo",
"*",
"LambdaAWSInfo",
",",
"eventSourceMapping",
"*",
"EventSourceMapping",
",",
"mappingIndex",
"int",
",",
"resource",
"*",
"resourceRef",
")",
"error",
"{",
"annotateStatementsErr",
":=",
"visitor",
"(",
"lambdaAWSInfo",
",",
"eventSourceMapping",
",",
"mappingIndex",
",",
"resource",
")",
"\n\n",
"// Early exit?",
"if",
"annotateStatementsErr",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"annotateStatementsErr",
",",
"\"",
"\"",
",",
"eventSourceMapping",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"//",
"// END",
"// Iterate through every lambda function. If there is an EventSourceMapping",
"// that points to a piece of infastructure provisioned by this stack,",
"// find the referred resource and supply it to the visitor",
"for",
"_",
",",
"eachLambda",
":=",
"range",
"lambdaAWSInfos",
"{",
"for",
"eachIndex",
",",
"eachEventSource",
":=",
"range",
"eachLambda",
".",
"EventSourceMappings",
"{",
"resourceRef",
",",
"resourceRefErr",
":=",
"resolveResourceRef",
"(",
"eachEventSource",
".",
"EventSourceArn",
")",
"\n",
"if",
"resourceRefErr",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"resourceRefErr",
",",
"\"",
"\"",
",",
"eachEventSource",
")",
"\n",
"}",
"\n\n",
"// At this point everything is a string, so we need to unmarshall",
"// and see if the Arn is supplied by either a Ref or a GetAttr",
"// function. In those cases, we need to look around in the template",
"// to go from: EventMapping -> Type -> Lambda -> LambdaIAMRole",
"// so that we can add the permissions",
"if",
"resourceRef",
"!=",
"nil",
"{",
"annotationErr",
":=",
"visitEventSourceMappingRef",
"(",
"eachLambda",
",",
"eachEventSource",
",",
"eachIndex",
",",
"resourceRef",
")",
"\n",
"// Anything go wrong?",
"if",
"annotationErr",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"annotationErr",
",",
"\"",
"\"",
",",
"eachEventSource",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // visitResolvedEventSourceMapping is a utility function that visits all the EventSourceMapping
// entries for the given lambdaAWSInfo struct | [
"visitResolvedEventSourceMapping",
"is",
"a",
"utility",
"function",
"that",
"visits",
"all",
"the",
"EventSourceMapping",
"entries",
"for",
"the",
"given",
"lambdaAWSInfo",
"struct"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/resource_references.go#L110-L171 |
1,248 | mweagle/Sparta | provision_annotations.go | eventSourceMappingPoliciesForResource | func eventSourceMappingPoliciesForResource(resource *resourceRef,
template *gocf.Template,
logger *logrus.Logger) ([]spartaIAM.PolicyStatement, error) {
policyStatements := []spartaIAM.PolicyStatement{}
if isResolvedResourceType(resource, template, ":dynamodb:", &gocf.DynamoDBTable{}) {
policyStatements = append(policyStatements, CommonIAMStatements.DynamoDB...)
} else if isResolvedResourceType(resource, template, ":kinesis:", &gocf.KinesisStream{}) {
policyStatements = append(policyStatements, CommonIAMStatements.Kinesis...)
} else if isResolvedResourceType(resource, template, ":sqs:", &gocf.SQSQueue{}) {
policyStatements = append(policyStatements, CommonIAMStatements.SQS...)
} else {
logger.WithFields(logrus.Fields{
"Resource": resource,
}).Debug("No additional EventSource IAM permissions found for event type")
}
return policyStatements, nil
} | go | func eventSourceMappingPoliciesForResource(resource *resourceRef,
template *gocf.Template,
logger *logrus.Logger) ([]spartaIAM.PolicyStatement, error) {
policyStatements := []spartaIAM.PolicyStatement{}
if isResolvedResourceType(resource, template, ":dynamodb:", &gocf.DynamoDBTable{}) {
policyStatements = append(policyStatements, CommonIAMStatements.DynamoDB...)
} else if isResolvedResourceType(resource, template, ":kinesis:", &gocf.KinesisStream{}) {
policyStatements = append(policyStatements, CommonIAMStatements.Kinesis...)
} else if isResolvedResourceType(resource, template, ":sqs:", &gocf.SQSQueue{}) {
policyStatements = append(policyStatements, CommonIAMStatements.SQS...)
} else {
logger.WithFields(logrus.Fields{
"Resource": resource,
}).Debug("No additional EventSource IAM permissions found for event type")
}
return policyStatements, nil
} | [
"func",
"eventSourceMappingPoliciesForResource",
"(",
"resource",
"*",
"resourceRef",
",",
"template",
"*",
"gocf",
".",
"Template",
",",
"logger",
"*",
"logrus",
".",
"Logger",
")",
"(",
"[",
"]",
"spartaIAM",
".",
"PolicyStatement",
",",
"error",
")",
"{",
"policyStatements",
":=",
"[",
"]",
"spartaIAM",
".",
"PolicyStatement",
"{",
"}",
"\n\n",
"if",
"isResolvedResourceType",
"(",
"resource",
",",
"template",
",",
"\"",
"\"",
",",
"&",
"gocf",
".",
"DynamoDBTable",
"{",
"}",
")",
"{",
"policyStatements",
"=",
"append",
"(",
"policyStatements",
",",
"CommonIAMStatements",
".",
"DynamoDB",
"...",
")",
"\n",
"}",
"else",
"if",
"isResolvedResourceType",
"(",
"resource",
",",
"template",
",",
"\"",
"\"",
",",
"&",
"gocf",
".",
"KinesisStream",
"{",
"}",
")",
"{",
"policyStatements",
"=",
"append",
"(",
"policyStatements",
",",
"CommonIAMStatements",
".",
"Kinesis",
"...",
")",
"\n",
"}",
"else",
"if",
"isResolvedResourceType",
"(",
"resource",
",",
"template",
",",
"\"",
"\"",
",",
"&",
"gocf",
".",
"SQSQueue",
"{",
"}",
")",
"{",
"policyStatements",
"=",
"append",
"(",
"policyStatements",
",",
"CommonIAMStatements",
".",
"SQS",
"...",
")",
"\n",
"}",
"else",
"{",
"logger",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"resource",
",",
"}",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"policyStatements",
",",
"nil",
"\n",
"}"
] | // eventSourceMappingPoliciesForResource returns the IAM specific privileges for each
// type of supported AWS Lambda EventSourceMapping | [
"eventSourceMappingPoliciesForResource",
"returns",
"the",
"IAM",
"specific",
"privileges",
"for",
"each",
"type",
"of",
"supported",
"AWS",
"Lambda",
"EventSourceMapping"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/provision_annotations.go#L18-L36 |
1,249 | mweagle/Sparta | aws/step/sns.go | NewSNSTaskState | func NewSNSTaskState(stateName string,
parameters SNSTaskParameters) *SNSTaskState {
sns := &SNSTaskState{
BaseTask: BaseTask{
baseInnerState: baseInnerState{
name: stateName,
id: rand.Int63(),
},
},
parameters: parameters,
}
return sns
} | go | func NewSNSTaskState(stateName string,
parameters SNSTaskParameters) *SNSTaskState {
sns := &SNSTaskState{
BaseTask: BaseTask{
baseInnerState: baseInnerState{
name: stateName,
id: rand.Int63(),
},
},
parameters: parameters,
}
return sns
} | [
"func",
"NewSNSTaskState",
"(",
"stateName",
"string",
",",
"parameters",
"SNSTaskParameters",
")",
"*",
"SNSTaskState",
"{",
"sns",
":=",
"&",
"SNSTaskState",
"{",
"BaseTask",
":",
"BaseTask",
"{",
"baseInnerState",
":",
"baseInnerState",
"{",
"name",
":",
"stateName",
",",
"id",
":",
"rand",
".",
"Int63",
"(",
")",
",",
"}",
",",
"}",
",",
"parameters",
":",
"parameters",
",",
"}",
"\n",
"return",
"sns",
"\n",
"}"
] | // NewSNSTaskState returns an initialized SNSTaskState | [
"NewSNSTaskState",
"returns",
"an",
"initialized",
"SNSTaskState"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/sns.go#L37-L50 |
1,250 | mweagle/Sparta | decorator/outputs.go | PublishRefOutputDecorator | func PublishRefOutputDecorator(keyName string, description string) sparta.TemplateDecoratorHookFunc {
attrDecorator := func(serviceName string,
lambdaResourceName string,
lambdaResource gocf.LambdaFunction,
resourceMetadata map[string]interface{},
S3Bucket string,
S3Key string,
buildID string,
template *gocf.Template,
context map[string]interface{},
logger *logrus.Logger) error {
// Add the function ARN as a stack output
template.Outputs[sanitizedKeyName(keyName)] = &gocf.Output{
Description: description,
Value: gocf.Ref(lambdaResourceName),
}
return nil
}
return sparta.TemplateDecoratorHookFunc(attrDecorator)
} | go | func PublishRefOutputDecorator(keyName string, description string) sparta.TemplateDecoratorHookFunc {
attrDecorator := func(serviceName string,
lambdaResourceName string,
lambdaResource gocf.LambdaFunction,
resourceMetadata map[string]interface{},
S3Bucket string,
S3Key string,
buildID string,
template *gocf.Template,
context map[string]interface{},
logger *logrus.Logger) error {
// Add the function ARN as a stack output
template.Outputs[sanitizedKeyName(keyName)] = &gocf.Output{
Description: description,
Value: gocf.Ref(lambdaResourceName),
}
return nil
}
return sparta.TemplateDecoratorHookFunc(attrDecorator)
} | [
"func",
"PublishRefOutputDecorator",
"(",
"keyName",
"string",
",",
"description",
"string",
")",
"sparta",
".",
"TemplateDecoratorHookFunc",
"{",
"attrDecorator",
":=",
"func",
"(",
"serviceName",
"string",
",",
"lambdaResourceName",
"string",
",",
"lambdaResource",
"gocf",
".",
"LambdaFunction",
",",
"resourceMetadata",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"S3Bucket",
"string",
",",
"S3Key",
"string",
",",
"buildID",
"string",
",",
"template",
"*",
"gocf",
".",
"Template",
",",
"context",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"logger",
"*",
"logrus",
".",
"Logger",
")",
"error",
"{",
"// Add the function ARN as a stack output",
"template",
".",
"Outputs",
"[",
"sanitizedKeyName",
"(",
"keyName",
")",
"]",
"=",
"&",
"gocf",
".",
"Output",
"{",
"Description",
":",
"description",
",",
"Value",
":",
"gocf",
".",
"Ref",
"(",
"lambdaResourceName",
")",
",",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"sparta",
".",
"TemplateDecoratorHookFunc",
"(",
"attrDecorator",
")",
"\n",
"}"
] | // PublishRefOutputDecorator returns an TemplateDecoratorHookFunc
// that publishes the Ref value for a given lambda | [
"PublishRefOutputDecorator",
"returns",
"an",
"TemplateDecoratorHookFunc",
"that",
"publishes",
"the",
"Ref",
"value",
"for",
"a",
"given",
"lambda"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/decorator/outputs.go#L81-L102 |
1,251 | mweagle/Sparta | aws/session.go | NewSessionWithConfig | func NewSessionWithConfig(awsConfig *aws.Config, logger *logrus.Logger) *session.Session {
return NewSessionWithConfigLevel(awsConfig, aws.LogDebugWithRequestErrors, logger)
} | go | func NewSessionWithConfig(awsConfig *aws.Config, logger *logrus.Logger) *session.Session {
return NewSessionWithConfigLevel(awsConfig, aws.LogDebugWithRequestErrors, logger)
} | [
"func",
"NewSessionWithConfig",
"(",
"awsConfig",
"*",
"aws",
".",
"Config",
",",
"logger",
"*",
"logrus",
".",
"Logger",
")",
"*",
"session",
".",
"Session",
"{",
"return",
"NewSessionWithConfigLevel",
"(",
"awsConfig",
",",
"aws",
".",
"LogDebugWithRequestErrors",
",",
"logger",
")",
"\n",
"}"
] | // NewSessionWithConfig returns an awsSession that includes the user supplied
// configuration information | [
"NewSessionWithConfig",
"returns",
"an",
"awsSession",
"that",
"includes",
"the",
"user",
"supplied",
"configuration",
"information"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/session.go#L21-L23 |
1,252 | mweagle/Sparta | aws/session.go | NewSession | func NewSession(logger *logrus.Logger) *session.Session {
return NewSessionWithLevel(aws.LogDebugWithRequestErrors, logger)
} | go | func NewSession(logger *logrus.Logger) *session.Session {
return NewSessionWithLevel(aws.LogDebugWithRequestErrors, logger)
} | [
"func",
"NewSession",
"(",
"logger",
"*",
"logrus",
".",
"Logger",
")",
"*",
"session",
".",
"Session",
"{",
"return",
"NewSessionWithLevel",
"(",
"aws",
".",
"LogDebugWithRequestErrors",
",",
"logger",
")",
"\n",
"}"
] | // NewSession that attaches a debug level handler to all AWS requests from services
// sharing the session value. | [
"NewSession",
"that",
"attaches",
"a",
"debug",
"level",
"handler",
"to",
"all",
"AWS",
"requests",
"from",
"services",
"sharing",
"the",
"session",
"value",
"."
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/session.go#L27-L29 |
1,253 | mweagle/Sparta | decorator/s3_artifact_publisher.go | S3ArtifactPublisherDecorator | func S3ArtifactPublisherDecorator(bucket gocf.Stringable,
key gocf.Stringable,
data map[string]interface{}) sparta.ServiceDecoratorHookHandler {
// Setup the CF distro
artifactDecorator := func(context map[string]interface{},
serviceName string,
template *gocf.Template,
S3Bucket string,
S3Key string,
buildID string,
awsSession *session.Session,
noop bool,
logger *logrus.Logger) error {
// Ensure the custom action handler...
sourceArnExpr := gocf.Join("",
gocf.String("arn:aws:s3:::"),
bucket.String(),
gocf.String("/*"))
configuratorResName, err := sparta.EnsureCustomResourceHandler(serviceName,
cfCustomResources.S3ArtifactPublisher,
sourceArnExpr,
[]string{},
template,
S3Bucket,
S3Key,
logger)
if err != nil {
return err
}
// Create the invocation of the custom action...
s3PublishResource := &cfCustomResources.S3ArtifactPublisherResource{}
s3PublishResource.ServiceToken = gocf.GetAtt(configuratorResName, "Arn")
s3PublishResource.Bucket = bucket.String()
s3PublishResource.Key = key.String()
s3PublishResource.Body = data
// Name?
resourceInvokerName := sparta.CloudFormationResourceName("ArtifactS3",
fmt.Sprintf("%v", bucket.String()),
fmt.Sprintf("%v", key.String()))
// Add it
template.AddResource(resourceInvokerName, s3PublishResource)
return nil
}
return sparta.ServiceDecoratorHookFunc(artifactDecorator)
} | go | func S3ArtifactPublisherDecorator(bucket gocf.Stringable,
key gocf.Stringable,
data map[string]interface{}) sparta.ServiceDecoratorHookHandler {
// Setup the CF distro
artifactDecorator := func(context map[string]interface{},
serviceName string,
template *gocf.Template,
S3Bucket string,
S3Key string,
buildID string,
awsSession *session.Session,
noop bool,
logger *logrus.Logger) error {
// Ensure the custom action handler...
sourceArnExpr := gocf.Join("",
gocf.String("arn:aws:s3:::"),
bucket.String(),
gocf.String("/*"))
configuratorResName, err := sparta.EnsureCustomResourceHandler(serviceName,
cfCustomResources.S3ArtifactPublisher,
sourceArnExpr,
[]string{},
template,
S3Bucket,
S3Key,
logger)
if err != nil {
return err
}
// Create the invocation of the custom action...
s3PublishResource := &cfCustomResources.S3ArtifactPublisherResource{}
s3PublishResource.ServiceToken = gocf.GetAtt(configuratorResName, "Arn")
s3PublishResource.Bucket = bucket.String()
s3PublishResource.Key = key.String()
s3PublishResource.Body = data
// Name?
resourceInvokerName := sparta.CloudFormationResourceName("ArtifactS3",
fmt.Sprintf("%v", bucket.String()),
fmt.Sprintf("%v", key.String()))
// Add it
template.AddResource(resourceInvokerName, s3PublishResource)
return nil
}
return sparta.ServiceDecoratorHookFunc(artifactDecorator)
} | [
"func",
"S3ArtifactPublisherDecorator",
"(",
"bucket",
"gocf",
".",
"Stringable",
",",
"key",
"gocf",
".",
"Stringable",
",",
"data",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"sparta",
".",
"ServiceDecoratorHookHandler",
"{",
"// Setup the CF distro",
"artifactDecorator",
":=",
"func",
"(",
"context",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"serviceName",
"string",
",",
"template",
"*",
"gocf",
".",
"Template",
",",
"S3Bucket",
"string",
",",
"S3Key",
"string",
",",
"buildID",
"string",
",",
"awsSession",
"*",
"session",
".",
"Session",
",",
"noop",
"bool",
",",
"logger",
"*",
"logrus",
".",
"Logger",
")",
"error",
"{",
"// Ensure the custom action handler...",
"sourceArnExpr",
":=",
"gocf",
".",
"Join",
"(",
"\"",
"\"",
",",
"gocf",
".",
"String",
"(",
"\"",
"\"",
")",
",",
"bucket",
".",
"String",
"(",
")",
",",
"gocf",
".",
"String",
"(",
"\"",
"\"",
")",
")",
"\n\n",
"configuratorResName",
",",
"err",
":=",
"sparta",
".",
"EnsureCustomResourceHandler",
"(",
"serviceName",
",",
"cfCustomResources",
".",
"S3ArtifactPublisher",
",",
"sourceArnExpr",
",",
"[",
"]",
"string",
"{",
"}",
",",
"template",
",",
"S3Bucket",
",",
"S3Key",
",",
"logger",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Create the invocation of the custom action...",
"s3PublishResource",
":=",
"&",
"cfCustomResources",
".",
"S3ArtifactPublisherResource",
"{",
"}",
"\n",
"s3PublishResource",
".",
"ServiceToken",
"=",
"gocf",
".",
"GetAtt",
"(",
"configuratorResName",
",",
"\"",
"\"",
")",
"\n",
"s3PublishResource",
".",
"Bucket",
"=",
"bucket",
".",
"String",
"(",
")",
"\n",
"s3PublishResource",
".",
"Key",
"=",
"key",
".",
"String",
"(",
")",
"\n",
"s3PublishResource",
".",
"Body",
"=",
"data",
"\n\n",
"// Name?",
"resourceInvokerName",
":=",
"sparta",
".",
"CloudFormationResourceName",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"bucket",
".",
"String",
"(",
")",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"key",
".",
"String",
"(",
")",
")",
")",
"\n\n",
"// Add it",
"template",
".",
"AddResource",
"(",
"resourceInvokerName",
",",
"s3PublishResource",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"sparta",
".",
"ServiceDecoratorHookFunc",
"(",
"artifactDecorator",
")",
"\n",
"}"
] | // S3ArtifactPublisherDecorator returns a ServiceDecoratorHookHandler
// function that publishes the given data to an S3 Bucket
// using the given bucket and key. | [
"S3ArtifactPublisherDecorator",
"returns",
"a",
"ServiceDecoratorHookHandler",
"function",
"that",
"publishes",
"the",
"given",
"data",
"to",
"an",
"S3",
"Bucket",
"using",
"the",
"given",
"bucket",
"and",
"key",
"."
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/decorator/s3_artifact_publisher.go#L16-L67 |
1,254 | mweagle/Sparta | sparta_main_build.go | NewLoggerWithFormatter | func NewLoggerWithFormatter(level string, formatter logrus.Formatter) (*logrus.Logger, error) {
logger := logrus.New()
// If there is an environment override, use that
envLogLevel := os.Getenv(envVarLogLevel)
if envLogLevel != "" {
level = envLogLevel
}
logLevel, err := logrus.ParseLevel(level)
if err != nil {
return nil, err
}
logger.Level = logLevel
if nil != formatter {
logger.Formatter = formatter
}
logger.Out = os.Stdout
return logger, nil
} | go | func NewLoggerWithFormatter(level string, formatter logrus.Formatter) (*logrus.Logger, error) {
logger := logrus.New()
// If there is an environment override, use that
envLogLevel := os.Getenv(envVarLogLevel)
if envLogLevel != "" {
level = envLogLevel
}
logLevel, err := logrus.ParseLevel(level)
if err != nil {
return nil, err
}
logger.Level = logLevel
if nil != formatter {
logger.Formatter = formatter
}
logger.Out = os.Stdout
return logger, nil
} | [
"func",
"NewLoggerWithFormatter",
"(",
"level",
"string",
",",
"formatter",
"logrus",
".",
"Formatter",
")",
"(",
"*",
"logrus",
".",
"Logger",
",",
"error",
")",
"{",
"logger",
":=",
"logrus",
".",
"New",
"(",
")",
"\n",
"// If there is an environment override, use that",
"envLogLevel",
":=",
"os",
".",
"Getenv",
"(",
"envVarLogLevel",
")",
"\n",
"if",
"envLogLevel",
"!=",
"\"",
"\"",
"{",
"level",
"=",
"envLogLevel",
"\n",
"}",
"\n\n",
"logLevel",
",",
"err",
":=",
"logrus",
".",
"ParseLevel",
"(",
"level",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"logger",
".",
"Level",
"=",
"logLevel",
"\n",
"if",
"nil",
"!=",
"formatter",
"{",
"logger",
".",
"Formatter",
"=",
"formatter",
"\n",
"}",
"\n",
"logger",
".",
"Out",
"=",
"os",
".",
"Stdout",
"\n",
"return",
"logger",
",",
"nil",
"\n",
"}"
] | // NewLoggerWithFormatter returns a logger with the given formatter. If formatter
// is nil, a TTY-aware formatter is used | [
"NewLoggerWithFormatter",
"returns",
"a",
"logger",
"with",
"the",
"given",
"formatter",
".",
"If",
"formatter",
"is",
"nil",
"a",
"TTY",
"-",
"aware",
"formatter",
"is",
"used"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/sparta_main_build.go#L40-L59 |
1,255 | mweagle/Sparta | delete.go | Delete | func Delete(serviceName string, logger *logrus.Logger) error {
session := spartaAWS.NewSession(logger)
awsCloudFormation := cloudformation.New(session)
exists, err := spartaCF.StackExists(serviceName, session, logger)
if nil != err {
return err
}
logger.WithFields(logrus.Fields{
"Exists": exists,
"Name": serviceName,
}).Info("Stack existence check")
if exists {
params := &cloudformation.DeleteStackInput{
StackName: aws.String(serviceName),
}
resp, err := awsCloudFormation.DeleteStack(params)
if nil != resp {
logger.WithFields(logrus.Fields{
"Response": resp,
}).Info("Delete request submitted")
}
return err
}
logger.Info("Stack does not exist")
return nil
} | go | func Delete(serviceName string, logger *logrus.Logger) error {
session := spartaAWS.NewSession(logger)
awsCloudFormation := cloudformation.New(session)
exists, err := spartaCF.StackExists(serviceName, session, logger)
if nil != err {
return err
}
logger.WithFields(logrus.Fields{
"Exists": exists,
"Name": serviceName,
}).Info("Stack existence check")
if exists {
params := &cloudformation.DeleteStackInput{
StackName: aws.String(serviceName),
}
resp, err := awsCloudFormation.DeleteStack(params)
if nil != resp {
logger.WithFields(logrus.Fields{
"Response": resp,
}).Info("Delete request submitted")
}
return err
}
logger.Info("Stack does not exist")
return nil
} | [
"func",
"Delete",
"(",
"serviceName",
"string",
",",
"logger",
"*",
"logrus",
".",
"Logger",
")",
"error",
"{",
"session",
":=",
"spartaAWS",
".",
"NewSession",
"(",
"logger",
")",
"\n",
"awsCloudFormation",
":=",
"cloudformation",
".",
"New",
"(",
"session",
")",
"\n\n",
"exists",
",",
"err",
":=",
"spartaCF",
".",
"StackExists",
"(",
"serviceName",
",",
"session",
",",
"logger",
")",
"\n",
"if",
"nil",
"!=",
"err",
"{",
"return",
"err",
"\n",
"}",
"\n",
"logger",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"exists",
",",
"\"",
"\"",
":",
"serviceName",
",",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"if",
"exists",
"{",
"params",
":=",
"&",
"cloudformation",
".",
"DeleteStackInput",
"{",
"StackName",
":",
"aws",
".",
"String",
"(",
"serviceName",
")",
",",
"}",
"\n",
"resp",
",",
"err",
":=",
"awsCloudFormation",
".",
"DeleteStack",
"(",
"params",
")",
"\n",
"if",
"nil",
"!=",
"resp",
"{",
"logger",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"resp",
",",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"logger",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Delete ensures that the provided serviceName is deleted.
// Failing to delete a non-existent service is considered a success. | [
"Delete",
"ensures",
"that",
"the",
"provided",
"serviceName",
"is",
"deleted",
".",
"Failing",
"to",
"delete",
"a",
"non",
"-",
"existent",
"service",
"is",
"considered",
"a",
"success",
"."
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/delete.go#L15-L43 |
1,256 | mweagle/Sparta | archetype/kinesis.go | OnKinesisMessage | func (reactorFunc KinesisReactorFunc) OnKinesisMessage(ctx context.Context,
kinesisEvent awsLambdaEvents.KinesisEvent) (interface{}, error) {
return reactorFunc(ctx, kinesisEvent)
} | go | func (reactorFunc KinesisReactorFunc) OnKinesisMessage(ctx context.Context,
kinesisEvent awsLambdaEvents.KinesisEvent) (interface{}, error) {
return reactorFunc(ctx, kinesisEvent)
} | [
"func",
"(",
"reactorFunc",
"KinesisReactorFunc",
")",
"OnKinesisMessage",
"(",
"ctx",
"context",
".",
"Context",
",",
"kinesisEvent",
"awsLambdaEvents",
".",
"KinesisEvent",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"return",
"reactorFunc",
"(",
"ctx",
",",
"kinesisEvent",
")",
"\n",
"}"
] | // OnKinesisMessage satisfies the KinesisReactor interface | [
"OnKinesisMessage",
"satisfies",
"the",
"KinesisReactor",
"interface"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/archetype/kinesis.go#L29-L32 |
1,257 | mweagle/Sparta | archetype/kinesis.go | NewKinesisReactor | func NewKinesisReactor(reactor KinesisReactor,
kinesisStream gocf.Stringable,
startingPosition string,
batchSize int64,
additionalLambdaPermissions []sparta.IAMRolePrivilege) (*sparta.LambdaAWSInfo, error) {
reactorLambda := func(ctx context.Context, kinesisEvent awsLambdaEvents.KinesisEvent) (interface{}, error) {
return reactor.OnKinesisMessage(ctx, kinesisEvent)
}
lambdaFn, lambdaFnErr := sparta.NewAWSLambda(reactorName(reactor),
reactorLambda,
sparta.IAMRoleDefinition{})
if lambdaFnErr != nil {
return nil, errors.Wrapf(lambdaFnErr, "attempting to create reactor")
}
lambdaFn.EventSourceMappings = append(lambdaFn.EventSourceMappings,
&sparta.EventSourceMapping{
EventSourceArn: kinesisStream,
StartingPosition: startingPosition,
BatchSize: batchSize,
})
if len(additionalLambdaPermissions) != 0 {
lambdaFn.RoleDefinition.Privileges = additionalLambdaPermissions
}
return lambdaFn, nil
} | go | func NewKinesisReactor(reactor KinesisReactor,
kinesisStream gocf.Stringable,
startingPosition string,
batchSize int64,
additionalLambdaPermissions []sparta.IAMRolePrivilege) (*sparta.LambdaAWSInfo, error) {
reactorLambda := func(ctx context.Context, kinesisEvent awsLambdaEvents.KinesisEvent) (interface{}, error) {
return reactor.OnKinesisMessage(ctx, kinesisEvent)
}
lambdaFn, lambdaFnErr := sparta.NewAWSLambda(reactorName(reactor),
reactorLambda,
sparta.IAMRoleDefinition{})
if lambdaFnErr != nil {
return nil, errors.Wrapf(lambdaFnErr, "attempting to create reactor")
}
lambdaFn.EventSourceMappings = append(lambdaFn.EventSourceMappings,
&sparta.EventSourceMapping{
EventSourceArn: kinesisStream,
StartingPosition: startingPosition,
BatchSize: batchSize,
})
if len(additionalLambdaPermissions) != 0 {
lambdaFn.RoleDefinition.Privileges = additionalLambdaPermissions
}
return lambdaFn, nil
} | [
"func",
"NewKinesisReactor",
"(",
"reactor",
"KinesisReactor",
",",
"kinesisStream",
"gocf",
".",
"Stringable",
",",
"startingPosition",
"string",
",",
"batchSize",
"int64",
",",
"additionalLambdaPermissions",
"[",
"]",
"sparta",
".",
"IAMRolePrivilege",
")",
"(",
"*",
"sparta",
".",
"LambdaAWSInfo",
",",
"error",
")",
"{",
"reactorLambda",
":=",
"func",
"(",
"ctx",
"context",
".",
"Context",
",",
"kinesisEvent",
"awsLambdaEvents",
".",
"KinesisEvent",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"return",
"reactor",
".",
"OnKinesisMessage",
"(",
"ctx",
",",
"kinesisEvent",
")",
"\n",
"}",
"\n\n",
"lambdaFn",
",",
"lambdaFnErr",
":=",
"sparta",
".",
"NewAWSLambda",
"(",
"reactorName",
"(",
"reactor",
")",
",",
"reactorLambda",
",",
"sparta",
".",
"IAMRoleDefinition",
"{",
"}",
")",
"\n",
"if",
"lambdaFnErr",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrapf",
"(",
"lambdaFnErr",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"lambdaFn",
".",
"EventSourceMappings",
"=",
"append",
"(",
"lambdaFn",
".",
"EventSourceMappings",
",",
"&",
"sparta",
".",
"EventSourceMapping",
"{",
"EventSourceArn",
":",
"kinesisStream",
",",
"StartingPosition",
":",
"startingPosition",
",",
"BatchSize",
":",
"batchSize",
",",
"}",
")",
"\n",
"if",
"len",
"(",
"additionalLambdaPermissions",
")",
"!=",
"0",
"{",
"lambdaFn",
".",
"RoleDefinition",
".",
"Privileges",
"=",
"additionalLambdaPermissions",
"\n",
"}",
"\n",
"return",
"lambdaFn",
",",
"nil",
"\n",
"}"
] | // NewKinesisReactor returns an Kinesis reactor lambda function | [
"NewKinesisReactor",
"returns",
"an",
"Kinesis",
"reactor",
"lambda",
"function"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/archetype/kinesis.go#L40-L67 |
1,258 | mweagle/Sparta | archetype/s3.go | OnS3Event | func (reactorFunc S3ReactorFunc) OnS3Event(ctx context.Context, event awsLambdaEvents.S3Event) (interface{}, error) {
return reactorFunc(ctx, event)
} | go | func (reactorFunc S3ReactorFunc) OnS3Event(ctx context.Context, event awsLambdaEvents.S3Event) (interface{}, error) {
return reactorFunc(ctx, event)
} | [
"func",
"(",
"reactorFunc",
"S3ReactorFunc",
")",
"OnS3Event",
"(",
"ctx",
"context",
".",
"Context",
",",
"event",
"awsLambdaEvents",
".",
"S3Event",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"return",
"reactorFunc",
"(",
"ctx",
",",
"event",
")",
"\n",
"}"
] | // OnS3Event satisfies the S3Reactor interface | [
"OnS3Event",
"satisfies",
"the",
"S3Reactor",
"interface"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/archetype/s3.go#L36-L38 |
1,259 | mweagle/Sparta | archetype/s3.go | s3NotificationPrefixBasedPermission | func s3NotificationPrefixBasedPermission(bucketName gocf.Stringable, keyPathPrefix string) sparta.S3Permission {
permission := sparta.S3Permission{
BasePermission: sparta.BasePermission{
SourceArn: bucketName.String(),
},
Events: []string{"s3:ObjectCreated:*",
"s3:ObjectRemoved:*"},
}
if keyPathPrefix != "" {
permission.Filter = s3.NotificationConfigurationFilter{
Key: &s3.KeyFilter{
FilterRules: []*s3.FilterRule{{
Name: aws.String("prefix"),
Value: aws.String(keyPathPrefix),
}},
},
}
}
return permission
} | go | func s3NotificationPrefixBasedPermission(bucketName gocf.Stringable, keyPathPrefix string) sparta.S3Permission {
permission := sparta.S3Permission{
BasePermission: sparta.BasePermission{
SourceArn: bucketName.String(),
},
Events: []string{"s3:ObjectCreated:*",
"s3:ObjectRemoved:*"},
}
if keyPathPrefix != "" {
permission.Filter = s3.NotificationConfigurationFilter{
Key: &s3.KeyFilter{
FilterRules: []*s3.FilterRule{{
Name: aws.String("prefix"),
Value: aws.String(keyPathPrefix),
}},
},
}
}
return permission
} | [
"func",
"s3NotificationPrefixBasedPermission",
"(",
"bucketName",
"gocf",
".",
"Stringable",
",",
"keyPathPrefix",
"string",
")",
"sparta",
".",
"S3Permission",
"{",
"permission",
":=",
"sparta",
".",
"S3Permission",
"{",
"BasePermission",
":",
"sparta",
".",
"BasePermission",
"{",
"SourceArn",
":",
"bucketName",
".",
"String",
"(",
")",
",",
"}",
",",
"Events",
":",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"}",
"\n\n",
"if",
"keyPathPrefix",
"!=",
"\"",
"\"",
"{",
"permission",
".",
"Filter",
"=",
"s3",
".",
"NotificationConfigurationFilter",
"{",
"Key",
":",
"&",
"s3",
".",
"KeyFilter",
"{",
"FilterRules",
":",
"[",
"]",
"*",
"s3",
".",
"FilterRule",
"{",
"{",
"Name",
":",
"aws",
".",
"String",
"(",
"\"",
"\"",
")",
",",
"Value",
":",
"aws",
".",
"String",
"(",
"keyPathPrefix",
")",
",",
"}",
"}",
",",
"}",
",",
"}",
"\n",
"}",
"\n",
"return",
"permission",
"\n",
"}"
] | // s3NotificationPrefixFilter is a DRY spec for setting up a notification configuration
// filter | [
"s3NotificationPrefixFilter",
"is",
"a",
"DRY",
"spec",
"for",
"setting",
"up",
"a",
"notification",
"configuration",
"filter"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/archetype/s3.go#L47-L68 |
1,260 | mweagle/Sparta | archetype/s3.go | NewS3Reactor | func NewS3Reactor(reactor S3Reactor, s3Bucket gocf.Stringable, additionalLambdaPermissions []sparta.IAMRolePrivilege) (*sparta.LambdaAWSInfo, error) {
return NewS3ScopedReactor(reactor, s3Bucket, "", additionalLambdaPermissions)
} | go | func NewS3Reactor(reactor S3Reactor, s3Bucket gocf.Stringable, additionalLambdaPermissions []sparta.IAMRolePrivilege) (*sparta.LambdaAWSInfo, error) {
return NewS3ScopedReactor(reactor, s3Bucket, "", additionalLambdaPermissions)
} | [
"func",
"NewS3Reactor",
"(",
"reactor",
"S3Reactor",
",",
"s3Bucket",
"gocf",
".",
"Stringable",
",",
"additionalLambdaPermissions",
"[",
"]",
"sparta",
".",
"IAMRolePrivilege",
")",
"(",
"*",
"sparta",
".",
"LambdaAWSInfo",
",",
"error",
")",
"{",
"return",
"NewS3ScopedReactor",
"(",
"reactor",
",",
"s3Bucket",
",",
"\"",
"\"",
",",
"additionalLambdaPermissions",
")",
"\n",
"}"
] | // NewS3Reactor returns an S3 reactor lambda function | [
"NewS3Reactor",
"returns",
"an",
"S3",
"reactor",
"lambda",
"function"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/archetype/s3.go#L71-L73 |
1,261 | mweagle/Sparta | archetype/s3.go | NewS3ScopedReactor | func NewS3ScopedReactor(reactor S3Reactor,
s3Bucket gocf.Stringable,
keyPathPrefix string,
additionalLambdaPermissions []sparta.IAMRolePrivilege) (*sparta.LambdaAWSInfo, error) {
reactorLambda := func(ctx context.Context, event awsLambdaEvents.S3Event) (interface{}, error) {
return reactor.OnS3Event(ctx, event)
}
// Privilege must include access to the S3 bucket for GetObjectRequest
lambdaFn, lambdaFnErr := sparta.NewAWSLambda(reactorName(reactor),
reactorLambda,
sparta.IAMRoleDefinition{})
if lambdaFnErr != nil {
return nil, errors.Wrapf(lambdaFnErr, "attempting to create reactor")
}
privileges := []sparta.IAMRolePrivilege{{
Actions: []string{"s3:GetObject"},
Resource: spartaCF.S3AllKeysArnForBucket(s3Bucket),
}}
if len(additionalLambdaPermissions) != 0 {
privileges = append(privileges, additionalLambdaPermissions...)
}
// IAM Role privileges
lambdaFn.RoleDefinition.Privileges = privileges
// Event Triggers
lambdaFn.Permissions = append(lambdaFn.Permissions,
s3NotificationPrefixBasedPermission(s3Bucket, keyPathPrefix))
return lambdaFn, nil
} | go | func NewS3ScopedReactor(reactor S3Reactor,
s3Bucket gocf.Stringable,
keyPathPrefix string,
additionalLambdaPermissions []sparta.IAMRolePrivilege) (*sparta.LambdaAWSInfo, error) {
reactorLambda := func(ctx context.Context, event awsLambdaEvents.S3Event) (interface{}, error) {
return reactor.OnS3Event(ctx, event)
}
// Privilege must include access to the S3 bucket for GetObjectRequest
lambdaFn, lambdaFnErr := sparta.NewAWSLambda(reactorName(reactor),
reactorLambda,
sparta.IAMRoleDefinition{})
if lambdaFnErr != nil {
return nil, errors.Wrapf(lambdaFnErr, "attempting to create reactor")
}
privileges := []sparta.IAMRolePrivilege{{
Actions: []string{"s3:GetObject"},
Resource: spartaCF.S3AllKeysArnForBucket(s3Bucket),
}}
if len(additionalLambdaPermissions) != 0 {
privileges = append(privileges, additionalLambdaPermissions...)
}
// IAM Role privileges
lambdaFn.RoleDefinition.Privileges = privileges
// Event Triggers
lambdaFn.Permissions = append(lambdaFn.Permissions,
s3NotificationPrefixBasedPermission(s3Bucket, keyPathPrefix))
return lambdaFn, nil
} | [
"func",
"NewS3ScopedReactor",
"(",
"reactor",
"S3Reactor",
",",
"s3Bucket",
"gocf",
".",
"Stringable",
",",
"keyPathPrefix",
"string",
",",
"additionalLambdaPermissions",
"[",
"]",
"sparta",
".",
"IAMRolePrivilege",
")",
"(",
"*",
"sparta",
".",
"LambdaAWSInfo",
",",
"error",
")",
"{",
"reactorLambda",
":=",
"func",
"(",
"ctx",
"context",
".",
"Context",
",",
"event",
"awsLambdaEvents",
".",
"S3Event",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"return",
"reactor",
".",
"OnS3Event",
"(",
"ctx",
",",
"event",
")",
"\n",
"}",
"\n\n",
"// Privilege must include access to the S3 bucket for GetObjectRequest",
"lambdaFn",
",",
"lambdaFnErr",
":=",
"sparta",
".",
"NewAWSLambda",
"(",
"reactorName",
"(",
"reactor",
")",
",",
"reactorLambda",
",",
"sparta",
".",
"IAMRoleDefinition",
"{",
"}",
")",
"\n",
"if",
"lambdaFnErr",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrapf",
"(",
"lambdaFnErr",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"privileges",
":=",
"[",
"]",
"sparta",
".",
"IAMRolePrivilege",
"{",
"{",
"Actions",
":",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
",",
"Resource",
":",
"spartaCF",
".",
"S3AllKeysArnForBucket",
"(",
"s3Bucket",
")",
",",
"}",
"}",
"\n",
"if",
"len",
"(",
"additionalLambdaPermissions",
")",
"!=",
"0",
"{",
"privileges",
"=",
"append",
"(",
"privileges",
",",
"additionalLambdaPermissions",
"...",
")",
"\n",
"}",
"\n\n",
"// IAM Role privileges",
"lambdaFn",
".",
"RoleDefinition",
".",
"Privileges",
"=",
"privileges",
"\n\n",
"// Event Triggers",
"lambdaFn",
".",
"Permissions",
"=",
"append",
"(",
"lambdaFn",
".",
"Permissions",
",",
"s3NotificationPrefixBasedPermission",
"(",
"s3Bucket",
",",
"keyPathPrefix",
")",
")",
"\n\n",
"return",
"lambdaFn",
",",
"nil",
"\n",
"}"
] | // NewS3ScopedReactor returns an S3 reactor lambda function scoped to the given S3 key prefix | [
"NewS3ScopedReactor",
"returns",
"an",
"S3",
"reactor",
"lambda",
"function",
"scoped",
"to",
"the",
"given",
"S3",
"key",
"prefix"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/archetype/s3.go#L76-L109 |
1,262 | mweagle/Sparta | aws/cloudformation/util.go | init | func init() {
cloudFormationStackTemplateMap = make(map[string]*gocf.Template)
rand.Seed(time.Now().Unix())
} | go | func init() {
cloudFormationStackTemplateMap = make(map[string]*gocf.Template)
rand.Seed(time.Now().Unix())
} | [
"func",
"init",
"(",
")",
"{",
"cloudFormationStackTemplateMap",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"gocf",
".",
"Template",
")",
"\n",
"rand",
".",
"Seed",
"(",
"time",
".",
"Now",
"(",
")",
".",
"Unix",
"(",
")",
")",
"\n",
"}"
] | //var cacheLock sync.Mutex | [
"var",
"cacheLock",
"sync",
".",
"Mutex"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/cloudformation/util.go#L35-L38 |
1,263 | mweagle/Sparta | aws/cloudformation/util.go | StackEvents | func StackEvents(stackID string,
eventFilterLowerBoundInclusive time.Time,
awsSession *session.Session) ([]*cloudformation.StackEvent, error) {
cfService := cloudformation.New(awsSession)
var events []*cloudformation.StackEvent
nextToken := ""
for {
params := &cloudformation.DescribeStackEventsInput{
StackName: aws.String(stackID),
}
if len(nextToken) > 0 {
params.NextToken = aws.String(nextToken)
}
resp, err := cfService.DescribeStackEvents(params)
if nil != err {
return nil, err
}
for _, eachEvent := range resp.StackEvents {
if eachEvent.Timestamp.Equal(eventFilterLowerBoundInclusive) ||
eachEvent.Timestamp.After(eventFilterLowerBoundInclusive) {
events = append(events, eachEvent)
}
}
if nil == resp.NextToken {
break
} else {
nextToken = *resp.NextToken
}
}
return events, nil
} | go | func StackEvents(stackID string,
eventFilterLowerBoundInclusive time.Time,
awsSession *session.Session) ([]*cloudformation.StackEvent, error) {
cfService := cloudformation.New(awsSession)
var events []*cloudformation.StackEvent
nextToken := ""
for {
params := &cloudformation.DescribeStackEventsInput{
StackName: aws.String(stackID),
}
if len(nextToken) > 0 {
params.NextToken = aws.String(nextToken)
}
resp, err := cfService.DescribeStackEvents(params)
if nil != err {
return nil, err
}
for _, eachEvent := range resp.StackEvents {
if eachEvent.Timestamp.Equal(eventFilterLowerBoundInclusive) ||
eachEvent.Timestamp.After(eventFilterLowerBoundInclusive) {
events = append(events, eachEvent)
}
}
if nil == resp.NextToken {
break
} else {
nextToken = *resp.NextToken
}
}
return events, nil
} | [
"func",
"StackEvents",
"(",
"stackID",
"string",
",",
"eventFilterLowerBoundInclusive",
"time",
".",
"Time",
",",
"awsSession",
"*",
"session",
".",
"Session",
")",
"(",
"[",
"]",
"*",
"cloudformation",
".",
"StackEvent",
",",
"error",
")",
"{",
"cfService",
":=",
"cloudformation",
".",
"New",
"(",
"awsSession",
")",
"\n",
"var",
"events",
"[",
"]",
"*",
"cloudformation",
".",
"StackEvent",
"\n\n",
"nextToken",
":=",
"\"",
"\"",
"\n",
"for",
"{",
"params",
":=",
"&",
"cloudformation",
".",
"DescribeStackEventsInput",
"{",
"StackName",
":",
"aws",
".",
"String",
"(",
"stackID",
")",
",",
"}",
"\n",
"if",
"len",
"(",
"nextToken",
")",
">",
"0",
"{",
"params",
".",
"NextToken",
"=",
"aws",
".",
"String",
"(",
"nextToken",
")",
"\n",
"}",
"\n\n",
"resp",
",",
"err",
":=",
"cfService",
".",
"DescribeStackEvents",
"(",
"params",
")",
"\n",
"if",
"nil",
"!=",
"err",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"eachEvent",
":=",
"range",
"resp",
".",
"StackEvents",
"{",
"if",
"eachEvent",
".",
"Timestamp",
".",
"Equal",
"(",
"eventFilterLowerBoundInclusive",
")",
"||",
"eachEvent",
".",
"Timestamp",
".",
"After",
"(",
"eventFilterLowerBoundInclusive",
")",
"{",
"events",
"=",
"append",
"(",
"events",
",",
"eachEvent",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"nil",
"==",
"resp",
".",
"NextToken",
"{",
"break",
"\n",
"}",
"else",
"{",
"nextToken",
"=",
"*",
"resp",
".",
"NextToken",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"events",
",",
"nil",
"\n",
"}"
] | // StackEvents returns the slice of cloudformation.StackEvents for the given stackID or stackName | [
"StackEvents",
"returns",
"the",
"slice",
"of",
"cloudformation",
".",
"StackEvents",
"for",
"the",
"given",
"stackID",
"or",
"stackName"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/cloudformation/util.go#L484-L517 |
1,264 | mweagle/Sparta | aws/cloudformation/util.go | WaitForStackOperationComplete | func WaitForStackOperationComplete(stackID string,
pollingMessage string,
awsCloudFormation *cloudformation.CloudFormation,
logger *logrus.Logger) (*WaitForStackOperationCompleteResult, error) {
result := &WaitForStackOperationCompleteResult{}
startTime := time.Now()
// Startup a spinner...
charSetIndex := 7
cliSpinner := spinner.New(spinner.CharSets[charSetIndex],
333*time.Millisecond)
cliSpinnerStarted := false
// Poll for the current stackID state, and
describeStacksInput := &cloudformation.DescribeStacksInput{
StackName: aws.String(stackID),
}
for waitComplete := false; !waitComplete; {
// Startup the spinner if needed...
switch logger.Formatter.(type) {
case *logrus.JSONFormatter:
{
logger.Info(pollingMessage)
}
default:
if !cliSpinnerStarted {
cliSpinner.Start()
defer cliSpinner.Stop()
cliSpinnerStarted = true
}
spinnerText := fmt.Sprintf(" %s (requested: %s)",
pollingMessage,
humanize.Time(startTime))
cliSpinner.Suffix = spinnerText
}
// Then sleep and figure out if things are done...
sleepDuration := time.Duration(11+rand.Int31n(13)) * time.Second
time.Sleep(sleepDuration)
describeStacksOutput, err := awsCloudFormation.DescribeStacks(describeStacksInput)
if nil != err {
// TODO - add retry iff we're RateExceeded due to collective access
return nil, err
}
if len(describeStacksOutput.Stacks) <= 0 {
return nil, fmt.Errorf("failed to enumerate stack info: %v", *describeStacksInput.StackName)
}
result.stackInfo = describeStacksOutput.Stacks[0]
switch *(result.stackInfo).StackStatus {
case cloudformation.StackStatusCreateComplete,
cloudformation.StackStatusUpdateComplete:
result.operationSuccessful = true
waitComplete = true
case
// Include DeleteComplete as new provisions will automatically rollback
cloudformation.StackStatusDeleteComplete,
cloudformation.StackStatusCreateFailed,
cloudformation.StackStatusDeleteFailed,
cloudformation.StackStatusRollbackFailed,
cloudformation.StackStatusRollbackComplete,
cloudformation.StackStatusUpdateRollbackComplete:
result.operationSuccessful = false
waitComplete = true
default:
// If this is JSON output, just do the normal thing
// NOP
}
}
return result, nil
} | go | func WaitForStackOperationComplete(stackID string,
pollingMessage string,
awsCloudFormation *cloudformation.CloudFormation,
logger *logrus.Logger) (*WaitForStackOperationCompleteResult, error) {
result := &WaitForStackOperationCompleteResult{}
startTime := time.Now()
// Startup a spinner...
charSetIndex := 7
cliSpinner := spinner.New(spinner.CharSets[charSetIndex],
333*time.Millisecond)
cliSpinnerStarted := false
// Poll for the current stackID state, and
describeStacksInput := &cloudformation.DescribeStacksInput{
StackName: aws.String(stackID),
}
for waitComplete := false; !waitComplete; {
// Startup the spinner if needed...
switch logger.Formatter.(type) {
case *logrus.JSONFormatter:
{
logger.Info(pollingMessage)
}
default:
if !cliSpinnerStarted {
cliSpinner.Start()
defer cliSpinner.Stop()
cliSpinnerStarted = true
}
spinnerText := fmt.Sprintf(" %s (requested: %s)",
pollingMessage,
humanize.Time(startTime))
cliSpinner.Suffix = spinnerText
}
// Then sleep and figure out if things are done...
sleepDuration := time.Duration(11+rand.Int31n(13)) * time.Second
time.Sleep(sleepDuration)
describeStacksOutput, err := awsCloudFormation.DescribeStacks(describeStacksInput)
if nil != err {
// TODO - add retry iff we're RateExceeded due to collective access
return nil, err
}
if len(describeStacksOutput.Stacks) <= 0 {
return nil, fmt.Errorf("failed to enumerate stack info: %v", *describeStacksInput.StackName)
}
result.stackInfo = describeStacksOutput.Stacks[0]
switch *(result.stackInfo).StackStatus {
case cloudformation.StackStatusCreateComplete,
cloudformation.StackStatusUpdateComplete:
result.operationSuccessful = true
waitComplete = true
case
// Include DeleteComplete as new provisions will automatically rollback
cloudformation.StackStatusDeleteComplete,
cloudformation.StackStatusCreateFailed,
cloudformation.StackStatusDeleteFailed,
cloudformation.StackStatusRollbackFailed,
cloudformation.StackStatusRollbackComplete,
cloudformation.StackStatusUpdateRollbackComplete:
result.operationSuccessful = false
waitComplete = true
default:
// If this is JSON output, just do the normal thing
// NOP
}
}
return result, nil
} | [
"func",
"WaitForStackOperationComplete",
"(",
"stackID",
"string",
",",
"pollingMessage",
"string",
",",
"awsCloudFormation",
"*",
"cloudformation",
".",
"CloudFormation",
",",
"logger",
"*",
"logrus",
".",
"Logger",
")",
"(",
"*",
"WaitForStackOperationCompleteResult",
",",
"error",
")",
"{",
"result",
":=",
"&",
"WaitForStackOperationCompleteResult",
"{",
"}",
"\n\n",
"startTime",
":=",
"time",
".",
"Now",
"(",
")",
"\n\n",
"// Startup a spinner...",
"charSetIndex",
":=",
"7",
"\n",
"cliSpinner",
":=",
"spinner",
".",
"New",
"(",
"spinner",
".",
"CharSets",
"[",
"charSetIndex",
"]",
",",
"333",
"*",
"time",
".",
"Millisecond",
")",
"\n",
"cliSpinnerStarted",
":=",
"false",
"\n\n",
"// Poll for the current stackID state, and",
"describeStacksInput",
":=",
"&",
"cloudformation",
".",
"DescribeStacksInput",
"{",
"StackName",
":",
"aws",
".",
"String",
"(",
"stackID",
")",
",",
"}",
"\n",
"for",
"waitComplete",
":=",
"false",
";",
"!",
"waitComplete",
";",
"{",
"// Startup the spinner if needed...",
"switch",
"logger",
".",
"Formatter",
".",
"(",
"type",
")",
"{",
"case",
"*",
"logrus",
".",
"JSONFormatter",
":",
"{",
"logger",
".",
"Info",
"(",
"pollingMessage",
")",
"\n",
"}",
"\n",
"default",
":",
"if",
"!",
"cliSpinnerStarted",
"{",
"cliSpinner",
".",
"Start",
"(",
")",
"\n",
"defer",
"cliSpinner",
".",
"Stop",
"(",
")",
"\n",
"cliSpinnerStarted",
"=",
"true",
"\n",
"}",
"\n",
"spinnerText",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"pollingMessage",
",",
"humanize",
".",
"Time",
"(",
"startTime",
")",
")",
"\n",
"cliSpinner",
".",
"Suffix",
"=",
"spinnerText",
"\n",
"}",
"\n\n",
"// Then sleep and figure out if things are done...",
"sleepDuration",
":=",
"time",
".",
"Duration",
"(",
"11",
"+",
"rand",
".",
"Int31n",
"(",
"13",
")",
")",
"*",
"time",
".",
"Second",
"\n",
"time",
".",
"Sleep",
"(",
"sleepDuration",
")",
"\n\n",
"describeStacksOutput",
",",
"err",
":=",
"awsCloudFormation",
".",
"DescribeStacks",
"(",
"describeStacksInput",
")",
"\n",
"if",
"nil",
"!=",
"err",
"{",
"// TODO - add retry iff we're RateExceeded due to collective access",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"describeStacksOutput",
".",
"Stacks",
")",
"<=",
"0",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"*",
"describeStacksInput",
".",
"StackName",
")",
"\n",
"}",
"\n",
"result",
".",
"stackInfo",
"=",
"describeStacksOutput",
".",
"Stacks",
"[",
"0",
"]",
"\n",
"switch",
"*",
"(",
"result",
".",
"stackInfo",
")",
".",
"StackStatus",
"{",
"case",
"cloudformation",
".",
"StackStatusCreateComplete",
",",
"cloudformation",
".",
"StackStatusUpdateComplete",
":",
"result",
".",
"operationSuccessful",
"=",
"true",
"\n",
"waitComplete",
"=",
"true",
"\n",
"case",
"// Include DeleteComplete as new provisions will automatically rollback",
"cloudformation",
".",
"StackStatusDeleteComplete",
",",
"cloudformation",
".",
"StackStatusCreateFailed",
",",
"cloudformation",
".",
"StackStatusDeleteFailed",
",",
"cloudformation",
".",
"StackStatusRollbackFailed",
",",
"cloudformation",
".",
"StackStatusRollbackComplete",
",",
"cloudformation",
".",
"StackStatusUpdateRollbackComplete",
":",
"result",
".",
"operationSuccessful",
"=",
"false",
"\n",
"waitComplete",
"=",
"true",
"\n",
"default",
":",
"// If this is JSON output, just do the normal thing",
"// NOP",
"}",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // WaitForStackOperationComplete is a blocking, polling based call that
// periodically fetches the stackID set of events and uses the state value
// to determine if an operation is complete | [
"WaitForStackOperationComplete",
"is",
"a",
"blocking",
"polling",
"based",
"call",
"that",
"periodically",
"fetches",
"the",
"stackID",
"set",
"of",
"events",
"and",
"uses",
"the",
"state",
"value",
"to",
"determine",
"if",
"an",
"operation",
"is",
"complete"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/cloudformation/util.go#L529-L601 |
1,265 | mweagle/Sparta | aws/cloudformation/util.go | UploadTemplate | func UploadTemplate(serviceName string,
cfTemplate *gocf.Template,
s3Bucket string,
s3KeyName string,
awsSession *session.Session,
logger *logrus.Logger) (string, error) {
logger.WithFields(logrus.Fields{
"Key": s3KeyName,
"Bucket": s3Bucket,
}).Info("Uploading CloudFormation template")
s3Uploader := s3manager.NewUploader(awsSession)
// Serialize the template and upload it
cfTemplateJSON, err := json.Marshal(cfTemplate)
if err != nil {
return "", errors.Wrap(err, "Failed to Marshal CloudFormation template")
}
// Upload the actual CloudFormation template to S3 to maximize the template
// size limit
// Ref: http://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_CreateStack.html
contentBody := string(cfTemplateJSON)
uploadInput := &s3manager.UploadInput{
Bucket: &s3Bucket,
Key: &s3KeyName,
ContentType: aws.String("application/json"),
Body: strings.NewReader(contentBody),
}
templateUploadResult, templateUploadResultErr := s3Uploader.Upload(uploadInput)
if nil != templateUploadResultErr {
return "", templateUploadResultErr
}
// Be transparent
logger.WithFields(logrus.Fields{
"URL": templateUploadResult.Location,
}).Info("Template uploaded")
return templateUploadResult.Location, nil
} | go | func UploadTemplate(serviceName string,
cfTemplate *gocf.Template,
s3Bucket string,
s3KeyName string,
awsSession *session.Session,
logger *logrus.Logger) (string, error) {
logger.WithFields(logrus.Fields{
"Key": s3KeyName,
"Bucket": s3Bucket,
}).Info("Uploading CloudFormation template")
s3Uploader := s3manager.NewUploader(awsSession)
// Serialize the template and upload it
cfTemplateJSON, err := json.Marshal(cfTemplate)
if err != nil {
return "", errors.Wrap(err, "Failed to Marshal CloudFormation template")
}
// Upload the actual CloudFormation template to S3 to maximize the template
// size limit
// Ref: http://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_CreateStack.html
contentBody := string(cfTemplateJSON)
uploadInput := &s3manager.UploadInput{
Bucket: &s3Bucket,
Key: &s3KeyName,
ContentType: aws.String("application/json"),
Body: strings.NewReader(contentBody),
}
templateUploadResult, templateUploadResultErr := s3Uploader.Upload(uploadInput)
if nil != templateUploadResultErr {
return "", templateUploadResultErr
}
// Be transparent
logger.WithFields(logrus.Fields{
"URL": templateUploadResult.Location,
}).Info("Template uploaded")
return templateUploadResult.Location, nil
} | [
"func",
"UploadTemplate",
"(",
"serviceName",
"string",
",",
"cfTemplate",
"*",
"gocf",
".",
"Template",
",",
"s3Bucket",
"string",
",",
"s3KeyName",
"string",
",",
"awsSession",
"*",
"session",
".",
"Session",
",",
"logger",
"*",
"logrus",
".",
"Logger",
")",
"(",
"string",
",",
"error",
")",
"{",
"logger",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"s3KeyName",
",",
"\"",
"\"",
":",
"s3Bucket",
",",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"s3Uploader",
":=",
"s3manager",
".",
"NewUploader",
"(",
"awsSession",
")",
"\n\n",
"// Serialize the template and upload it",
"cfTemplateJSON",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"cfTemplate",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Upload the actual CloudFormation template to S3 to maximize the template",
"// size limit",
"// Ref: http://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_CreateStack.html",
"contentBody",
":=",
"string",
"(",
"cfTemplateJSON",
")",
"\n",
"uploadInput",
":=",
"&",
"s3manager",
".",
"UploadInput",
"{",
"Bucket",
":",
"&",
"s3Bucket",
",",
"Key",
":",
"&",
"s3KeyName",
",",
"ContentType",
":",
"aws",
".",
"String",
"(",
"\"",
"\"",
")",
",",
"Body",
":",
"strings",
".",
"NewReader",
"(",
"contentBody",
")",
",",
"}",
"\n",
"templateUploadResult",
",",
"templateUploadResultErr",
":=",
"s3Uploader",
".",
"Upload",
"(",
"uploadInput",
")",
"\n",
"if",
"nil",
"!=",
"templateUploadResultErr",
"{",
"return",
"\"",
"\"",
",",
"templateUploadResultErr",
"\n",
"}",
"\n\n",
"// Be transparent",
"logger",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"templateUploadResult",
".",
"Location",
",",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"return",
"templateUploadResult",
".",
"Location",
",",
"nil",
"\n",
"}"
] | // UploadTemplate marshals the given cfTemplate and uploads it to the
// supplied bucket using the given KeyName | [
"UploadTemplate",
"marshals",
"the",
"given",
"cfTemplate",
"and",
"uploads",
"it",
"to",
"the",
"supplied",
"bucket",
"using",
"the",
"given",
"KeyName"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/cloudformation/util.go#L636-L676 |
1,266 | mweagle/Sparta | aws/cloudformation/util.go | StackExists | func StackExists(stackNameOrID string, awsSession *session.Session, logger *logrus.Logger) (bool, error) {
cf := cloudformation.New(awsSession)
describeStacksInput := &cloudformation.DescribeStacksInput{
StackName: aws.String(stackNameOrID),
}
describeStacksOutput, err := cf.DescribeStacks(describeStacksInput)
logger.WithFields(logrus.Fields{
"DescribeStackOutput": describeStacksOutput,
}).Debug("DescribeStackOutput results")
exists := false
if err != nil {
logger.WithFields(logrus.Fields{
"DescribeStackOutputError": err,
}).Debug("DescribeStackOutput")
// If the stack doesn't exist, then no worries
if strings.Contains(err.Error(), "does not exist") {
exists = false
} else {
return false, err
}
} else {
exists = true
}
return exists, nil
} | go | func StackExists(stackNameOrID string, awsSession *session.Session, logger *logrus.Logger) (bool, error) {
cf := cloudformation.New(awsSession)
describeStacksInput := &cloudformation.DescribeStacksInput{
StackName: aws.String(stackNameOrID),
}
describeStacksOutput, err := cf.DescribeStacks(describeStacksInput)
logger.WithFields(logrus.Fields{
"DescribeStackOutput": describeStacksOutput,
}).Debug("DescribeStackOutput results")
exists := false
if err != nil {
logger.WithFields(logrus.Fields{
"DescribeStackOutputError": err,
}).Debug("DescribeStackOutput")
// If the stack doesn't exist, then no worries
if strings.Contains(err.Error(), "does not exist") {
exists = false
} else {
return false, err
}
} else {
exists = true
}
return exists, nil
} | [
"func",
"StackExists",
"(",
"stackNameOrID",
"string",
",",
"awsSession",
"*",
"session",
".",
"Session",
",",
"logger",
"*",
"logrus",
".",
"Logger",
")",
"(",
"bool",
",",
"error",
")",
"{",
"cf",
":=",
"cloudformation",
".",
"New",
"(",
"awsSession",
")",
"\n\n",
"describeStacksInput",
":=",
"&",
"cloudformation",
".",
"DescribeStacksInput",
"{",
"StackName",
":",
"aws",
".",
"String",
"(",
"stackNameOrID",
")",
",",
"}",
"\n",
"describeStacksOutput",
",",
"err",
":=",
"cf",
".",
"DescribeStacks",
"(",
"describeStacksInput",
")",
"\n",
"logger",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"describeStacksOutput",
",",
"}",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n\n",
"exists",
":=",
"false",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"err",
",",
"}",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n\n",
"// If the stack doesn't exist, then no worries",
"if",
"strings",
".",
"Contains",
"(",
"err",
".",
"Error",
"(",
")",
",",
"\"",
"\"",
")",
"{",
"exists",
"=",
"false",
"\n",
"}",
"else",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"}",
"else",
"{",
"exists",
"=",
"true",
"\n",
"}",
"\n",
"return",
"exists",
",",
"nil",
"\n",
"}"
] | // StackExists returns whether the given stackName or stackID currently exists | [
"StackExists",
"returns",
"whether",
"the",
"given",
"stackName",
"or",
"stackID",
"currently",
"exists"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/cloudformation/util.go#L679-L706 |
1,267 | mweagle/Sparta | aws/cloudformation/util.go | CreateStackChangeSet | func CreateStackChangeSet(changeSetRequestName string,
serviceName string,
cfTemplate *gocf.Template,
templateURL string,
awsTags []*cloudformation.Tag,
awsCloudFormation *cloudformation.CloudFormation,
logger *logrus.Logger) (*cloudformation.DescribeChangeSetOutput, error) {
capabilities := stackCapabilities(cfTemplate)
changeSetInput := &cloudformation.CreateChangeSetInput{
Capabilities: capabilities,
ChangeSetName: aws.String(changeSetRequestName),
ClientToken: aws.String(changeSetRequestName),
Description: aws.String(fmt.Sprintf("Change set for service: %s", serviceName)),
StackName: aws.String(serviceName),
TemplateURL: aws.String(templateURL),
}
if len(awsTags) != 0 {
changeSetInput.Tags = awsTags
}
_, changeSetError := awsCloudFormation.CreateChangeSet(changeSetInput)
if nil != changeSetError {
return nil, changeSetError
}
logger.WithFields(logrus.Fields{
"StackName": serviceName,
}).Info("Issued CreateChangeSet request")
describeChangeSetInput := cloudformation.DescribeChangeSetInput{
ChangeSetName: aws.String(changeSetRequestName),
StackName: aws.String(serviceName),
}
var describeChangeSetOutput *cloudformation.DescribeChangeSetOutput
// Loop, with a total timeout of 3 minutes
startTime := time.Now()
changeSetStabilized := false
for !changeSetStabilized {
sleepDuration := cloudformationPollingDelay()
time.Sleep(sleepDuration)
changeSetOutput, describeChangeSetError := awsCloudFormation.DescribeChangeSet(&describeChangeSetInput)
if nil != describeChangeSetError {
return nil, describeChangeSetError
}
describeChangeSetOutput = changeSetOutput
// The current status of the change set, such as CREATE_IN_PROGRESS, CREATE_COMPLETE,
// or FAILED.
if nil != describeChangeSetOutput {
switch *describeChangeSetOutput.Status {
case "CREATE_IN_PROGRESS":
// If this has taken more than 3 minutes, then that's an error
elapsedTime := time.Since(startTime)
if elapsedTime > cloudformationPollingTimeout {
return nil, fmt.Errorf("failed to finalize ChangeSet within window: %s", elapsedTime.String())
}
case "CREATE_COMPLETE":
changeSetStabilized = true
case "FAILED":
return nil, fmt.Errorf("failed to create ChangeSet: %#v", *describeChangeSetOutput)
}
}
}
logger.WithFields(logrus.Fields{
"DescribeChangeSetOutput": describeChangeSetOutput,
}).Debug("DescribeChangeSet result")
//////////////////////////////////////////////////////////////////////////////
// If there aren't any changes, then skip it...
if len(describeChangeSetOutput.Changes) <= 0 {
logger.WithFields(logrus.Fields{
"StackName": serviceName,
}).Info("No changes detected for service")
// Delete it...
_, deleteChangeSetResultErr := DeleteChangeSet(serviceName,
changeSetRequestName,
awsCloudFormation)
return nil, deleteChangeSetResultErr
}
return describeChangeSetOutput, nil
} | go | func CreateStackChangeSet(changeSetRequestName string,
serviceName string,
cfTemplate *gocf.Template,
templateURL string,
awsTags []*cloudformation.Tag,
awsCloudFormation *cloudformation.CloudFormation,
logger *logrus.Logger) (*cloudformation.DescribeChangeSetOutput, error) {
capabilities := stackCapabilities(cfTemplate)
changeSetInput := &cloudformation.CreateChangeSetInput{
Capabilities: capabilities,
ChangeSetName: aws.String(changeSetRequestName),
ClientToken: aws.String(changeSetRequestName),
Description: aws.String(fmt.Sprintf("Change set for service: %s", serviceName)),
StackName: aws.String(serviceName),
TemplateURL: aws.String(templateURL),
}
if len(awsTags) != 0 {
changeSetInput.Tags = awsTags
}
_, changeSetError := awsCloudFormation.CreateChangeSet(changeSetInput)
if nil != changeSetError {
return nil, changeSetError
}
logger.WithFields(logrus.Fields{
"StackName": serviceName,
}).Info("Issued CreateChangeSet request")
describeChangeSetInput := cloudformation.DescribeChangeSetInput{
ChangeSetName: aws.String(changeSetRequestName),
StackName: aws.String(serviceName),
}
var describeChangeSetOutput *cloudformation.DescribeChangeSetOutput
// Loop, with a total timeout of 3 minutes
startTime := time.Now()
changeSetStabilized := false
for !changeSetStabilized {
sleepDuration := cloudformationPollingDelay()
time.Sleep(sleepDuration)
changeSetOutput, describeChangeSetError := awsCloudFormation.DescribeChangeSet(&describeChangeSetInput)
if nil != describeChangeSetError {
return nil, describeChangeSetError
}
describeChangeSetOutput = changeSetOutput
// The current status of the change set, such as CREATE_IN_PROGRESS, CREATE_COMPLETE,
// or FAILED.
if nil != describeChangeSetOutput {
switch *describeChangeSetOutput.Status {
case "CREATE_IN_PROGRESS":
// If this has taken more than 3 minutes, then that's an error
elapsedTime := time.Since(startTime)
if elapsedTime > cloudformationPollingTimeout {
return nil, fmt.Errorf("failed to finalize ChangeSet within window: %s", elapsedTime.String())
}
case "CREATE_COMPLETE":
changeSetStabilized = true
case "FAILED":
return nil, fmt.Errorf("failed to create ChangeSet: %#v", *describeChangeSetOutput)
}
}
}
logger.WithFields(logrus.Fields{
"DescribeChangeSetOutput": describeChangeSetOutput,
}).Debug("DescribeChangeSet result")
//////////////////////////////////////////////////////////////////////////////
// If there aren't any changes, then skip it...
if len(describeChangeSetOutput.Changes) <= 0 {
logger.WithFields(logrus.Fields{
"StackName": serviceName,
}).Info("No changes detected for service")
// Delete it...
_, deleteChangeSetResultErr := DeleteChangeSet(serviceName,
changeSetRequestName,
awsCloudFormation)
return nil, deleteChangeSetResultErr
}
return describeChangeSetOutput, nil
} | [
"func",
"CreateStackChangeSet",
"(",
"changeSetRequestName",
"string",
",",
"serviceName",
"string",
",",
"cfTemplate",
"*",
"gocf",
".",
"Template",
",",
"templateURL",
"string",
",",
"awsTags",
"[",
"]",
"*",
"cloudformation",
".",
"Tag",
",",
"awsCloudFormation",
"*",
"cloudformation",
".",
"CloudFormation",
",",
"logger",
"*",
"logrus",
".",
"Logger",
")",
"(",
"*",
"cloudformation",
".",
"DescribeChangeSetOutput",
",",
"error",
")",
"{",
"capabilities",
":=",
"stackCapabilities",
"(",
"cfTemplate",
")",
"\n",
"changeSetInput",
":=",
"&",
"cloudformation",
".",
"CreateChangeSetInput",
"{",
"Capabilities",
":",
"capabilities",
",",
"ChangeSetName",
":",
"aws",
".",
"String",
"(",
"changeSetRequestName",
")",
",",
"ClientToken",
":",
"aws",
".",
"String",
"(",
"changeSetRequestName",
")",
",",
"Description",
":",
"aws",
".",
"String",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"serviceName",
")",
")",
",",
"StackName",
":",
"aws",
".",
"String",
"(",
"serviceName",
")",
",",
"TemplateURL",
":",
"aws",
".",
"String",
"(",
"templateURL",
")",
",",
"}",
"\n",
"if",
"len",
"(",
"awsTags",
")",
"!=",
"0",
"{",
"changeSetInput",
".",
"Tags",
"=",
"awsTags",
"\n",
"}",
"\n",
"_",
",",
"changeSetError",
":=",
"awsCloudFormation",
".",
"CreateChangeSet",
"(",
"changeSetInput",
")",
"\n",
"if",
"nil",
"!=",
"changeSetError",
"{",
"return",
"nil",
",",
"changeSetError",
"\n",
"}",
"\n\n",
"logger",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"serviceName",
",",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"describeChangeSetInput",
":=",
"cloudformation",
".",
"DescribeChangeSetInput",
"{",
"ChangeSetName",
":",
"aws",
".",
"String",
"(",
"changeSetRequestName",
")",
",",
"StackName",
":",
"aws",
".",
"String",
"(",
"serviceName",
")",
",",
"}",
"\n\n",
"var",
"describeChangeSetOutput",
"*",
"cloudformation",
".",
"DescribeChangeSetOutput",
"\n\n",
"// Loop, with a total timeout of 3 minutes",
"startTime",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"changeSetStabilized",
":=",
"false",
"\n",
"for",
"!",
"changeSetStabilized",
"{",
"sleepDuration",
":=",
"cloudformationPollingDelay",
"(",
")",
"\n",
"time",
".",
"Sleep",
"(",
"sleepDuration",
")",
"\n\n",
"changeSetOutput",
",",
"describeChangeSetError",
":=",
"awsCloudFormation",
".",
"DescribeChangeSet",
"(",
"&",
"describeChangeSetInput",
")",
"\n\n",
"if",
"nil",
"!=",
"describeChangeSetError",
"{",
"return",
"nil",
",",
"describeChangeSetError",
"\n",
"}",
"\n",
"describeChangeSetOutput",
"=",
"changeSetOutput",
"\n",
"// The current status of the change set, such as CREATE_IN_PROGRESS, CREATE_COMPLETE,",
"// or FAILED.",
"if",
"nil",
"!=",
"describeChangeSetOutput",
"{",
"switch",
"*",
"describeChangeSetOutput",
".",
"Status",
"{",
"case",
"\"",
"\"",
":",
"// If this has taken more than 3 minutes, then that's an error",
"elapsedTime",
":=",
"time",
".",
"Since",
"(",
"startTime",
")",
"\n",
"if",
"elapsedTime",
">",
"cloudformationPollingTimeout",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"elapsedTime",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n",
"case",
"\"",
"\"",
":",
"changeSetStabilized",
"=",
"true",
"\n",
"case",
"\"",
"\"",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"*",
"describeChangeSetOutput",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"logger",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"describeChangeSetOutput",
",",
"}",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n\n",
"//////////////////////////////////////////////////////////////////////////////",
"// If there aren't any changes, then skip it...",
"if",
"len",
"(",
"describeChangeSetOutput",
".",
"Changes",
")",
"<=",
"0",
"{",
"logger",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"serviceName",
",",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"// Delete it...",
"_",
",",
"deleteChangeSetResultErr",
":=",
"DeleteChangeSet",
"(",
"serviceName",
",",
"changeSetRequestName",
",",
"awsCloudFormation",
")",
"\n",
"return",
"nil",
",",
"deleteChangeSetResultErr",
"\n",
"}",
"\n",
"return",
"describeChangeSetOutput",
",",
"nil",
"\n",
"}"
] | // CreateStackChangeSet returns the DescribeChangeSetOutput
// for a given stack transformation | [
"CreateStackChangeSet",
"returns",
"the",
"DescribeChangeSetOutput",
"for",
"a",
"given",
"stack",
"transformation"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/cloudformation/util.go#L710-L795 |
1,268 | mweagle/Sparta | aws/cloudformation/util.go | DeleteChangeSet | func DeleteChangeSet(stackName string,
changeSetRequestName string,
awsCloudFormation *cloudformation.CloudFormation) (*cloudformation.DeleteChangeSetOutput, error) {
// Delete request...
deleteChangeSetInput := cloudformation.DeleteChangeSetInput{
ChangeSetName: aws.String(changeSetRequestName),
StackName: aws.String(stackName),
}
startTime := time.Now()
for {
elapsedTime := time.Since(startTime)
deleteChangeSetResults, deleteChangeSetResultErr := awsCloudFormation.DeleteChangeSet(&deleteChangeSetInput)
if nil == deleteChangeSetResultErr {
return deleteChangeSetResults, nil
} else if strings.Contains(deleteChangeSetResultErr.Error(), "CREATE_IN_PROGRESS") {
if elapsedTime > cloudformationPollingTimeout {
return nil, fmt.Errorf("failed to delete ChangeSet within timeout window: %s", elapsedTime.String())
}
sleepDuration := cloudformationPollingDelay()
time.Sleep(sleepDuration)
} else {
return nil, deleteChangeSetResultErr
}
}
} | go | func DeleteChangeSet(stackName string,
changeSetRequestName string,
awsCloudFormation *cloudformation.CloudFormation) (*cloudformation.DeleteChangeSetOutput, error) {
// Delete request...
deleteChangeSetInput := cloudformation.DeleteChangeSetInput{
ChangeSetName: aws.String(changeSetRequestName),
StackName: aws.String(stackName),
}
startTime := time.Now()
for {
elapsedTime := time.Since(startTime)
deleteChangeSetResults, deleteChangeSetResultErr := awsCloudFormation.DeleteChangeSet(&deleteChangeSetInput)
if nil == deleteChangeSetResultErr {
return deleteChangeSetResults, nil
} else if strings.Contains(deleteChangeSetResultErr.Error(), "CREATE_IN_PROGRESS") {
if elapsedTime > cloudformationPollingTimeout {
return nil, fmt.Errorf("failed to delete ChangeSet within timeout window: %s", elapsedTime.String())
}
sleepDuration := cloudformationPollingDelay()
time.Sleep(sleepDuration)
} else {
return nil, deleteChangeSetResultErr
}
}
} | [
"func",
"DeleteChangeSet",
"(",
"stackName",
"string",
",",
"changeSetRequestName",
"string",
",",
"awsCloudFormation",
"*",
"cloudformation",
".",
"CloudFormation",
")",
"(",
"*",
"cloudformation",
".",
"DeleteChangeSetOutput",
",",
"error",
")",
"{",
"// Delete request...",
"deleteChangeSetInput",
":=",
"cloudformation",
".",
"DeleteChangeSetInput",
"{",
"ChangeSetName",
":",
"aws",
".",
"String",
"(",
"changeSetRequestName",
")",
",",
"StackName",
":",
"aws",
".",
"String",
"(",
"stackName",
")",
",",
"}",
"\n\n",
"startTime",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"for",
"{",
"elapsedTime",
":=",
"time",
".",
"Since",
"(",
"startTime",
")",
"\n\n",
"deleteChangeSetResults",
",",
"deleteChangeSetResultErr",
":=",
"awsCloudFormation",
".",
"DeleteChangeSet",
"(",
"&",
"deleteChangeSetInput",
")",
"\n",
"if",
"nil",
"==",
"deleteChangeSetResultErr",
"{",
"return",
"deleteChangeSetResults",
",",
"nil",
"\n",
"}",
"else",
"if",
"strings",
".",
"Contains",
"(",
"deleteChangeSetResultErr",
".",
"Error",
"(",
")",
",",
"\"",
"\"",
")",
"{",
"if",
"elapsedTime",
">",
"cloudformationPollingTimeout",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"elapsedTime",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n",
"sleepDuration",
":=",
"cloudformationPollingDelay",
"(",
")",
"\n",
"time",
".",
"Sleep",
"(",
"sleepDuration",
")",
"\n",
"}",
"else",
"{",
"return",
"nil",
",",
"deleteChangeSetResultErr",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // DeleteChangeSet is a utility function that attempts to delete
// an existing CloudFormation change set, with a bit of retry
// logic in case of EC | [
"DeleteChangeSet",
"is",
"a",
"utility",
"function",
"that",
"attempts",
"to",
"delete",
"an",
"existing",
"CloudFormation",
"change",
"set",
"with",
"a",
"bit",
"of",
"retry",
"logic",
"in",
"case",
"of",
"EC"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/cloudformation/util.go#L800-L827 |
1,269 | mweagle/Sparta | aws/cloudformation/util.go | ListStacks | func ListStacks(session *session.Session,
maxReturned int,
stackFilters ...string) ([]*cloudformation.StackSummary, error) {
listStackInput := &cloudformation.ListStacksInput{
StackStatusFilter: []*string{},
}
for _, eachFilter := range stackFilters {
listStackInput.StackStatusFilter = append(listStackInput.StackStatusFilter, aws.String(eachFilter))
}
cloudformationSvc := cloudformation.New(session)
accumulator := []*cloudformation.StackSummary{}
for {
listResult, listResultErr := cloudformationSvc.ListStacks(listStackInput)
if listResultErr != nil {
return nil, listResultErr
}
accumulator = append(accumulator, listResult.StackSummaries...)
if len(accumulator) >= maxReturned || listResult.NextToken == nil {
return accumulator, nil
}
listStackInput.NextToken = listResult.NextToken
}
} | go | func ListStacks(session *session.Session,
maxReturned int,
stackFilters ...string) ([]*cloudformation.StackSummary, error) {
listStackInput := &cloudformation.ListStacksInput{
StackStatusFilter: []*string{},
}
for _, eachFilter := range stackFilters {
listStackInput.StackStatusFilter = append(listStackInput.StackStatusFilter, aws.String(eachFilter))
}
cloudformationSvc := cloudformation.New(session)
accumulator := []*cloudformation.StackSummary{}
for {
listResult, listResultErr := cloudformationSvc.ListStacks(listStackInput)
if listResultErr != nil {
return nil, listResultErr
}
accumulator = append(accumulator, listResult.StackSummaries...)
if len(accumulator) >= maxReturned || listResult.NextToken == nil {
return accumulator, nil
}
listStackInput.NextToken = listResult.NextToken
}
} | [
"func",
"ListStacks",
"(",
"session",
"*",
"session",
".",
"Session",
",",
"maxReturned",
"int",
",",
"stackFilters",
"...",
"string",
")",
"(",
"[",
"]",
"*",
"cloudformation",
".",
"StackSummary",
",",
"error",
")",
"{",
"listStackInput",
":=",
"&",
"cloudformation",
".",
"ListStacksInput",
"{",
"StackStatusFilter",
":",
"[",
"]",
"*",
"string",
"{",
"}",
",",
"}",
"\n",
"for",
"_",
",",
"eachFilter",
":=",
"range",
"stackFilters",
"{",
"listStackInput",
".",
"StackStatusFilter",
"=",
"append",
"(",
"listStackInput",
".",
"StackStatusFilter",
",",
"aws",
".",
"String",
"(",
"eachFilter",
")",
")",
"\n",
"}",
"\n",
"cloudformationSvc",
":=",
"cloudformation",
".",
"New",
"(",
"session",
")",
"\n",
"accumulator",
":=",
"[",
"]",
"*",
"cloudformation",
".",
"StackSummary",
"{",
"}",
"\n",
"for",
"{",
"listResult",
",",
"listResultErr",
":=",
"cloudformationSvc",
".",
"ListStacks",
"(",
"listStackInput",
")",
"\n",
"if",
"listResultErr",
"!=",
"nil",
"{",
"return",
"nil",
",",
"listResultErr",
"\n",
"}",
"\n",
"accumulator",
"=",
"append",
"(",
"accumulator",
",",
"listResult",
".",
"StackSummaries",
"...",
")",
"\n",
"if",
"len",
"(",
"accumulator",
")",
">=",
"maxReturned",
"||",
"listResult",
".",
"NextToken",
"==",
"nil",
"{",
"return",
"accumulator",
",",
"nil",
"\n",
"}",
"\n",
"listStackInput",
".",
"NextToken",
"=",
"listResult",
".",
"NextToken",
"\n",
"}",
"\n",
"}"
] | // ListStacks returns a slice of stacks that meet the given filter. | [
"ListStacks",
"returns",
"a",
"slice",
"of",
"stacks",
"that",
"meet",
"the",
"given",
"filter",
"."
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/cloudformation/util.go#L830-L853 |
1,270 | mweagle/Sparta | provision.go | EnsureCustomResourceHandler | func EnsureCustomResourceHandler(serviceName string,
customResourceCloudFormationTypeName string,
sourceArn *gocf.StringExpr,
dependsOn []string,
template *gocf.Template,
S3Bucket string,
S3Key string,
logger *logrus.Logger) (string, error) {
// Ok, we need a way to round trip this type as the AWS lambda function name.
// The problem with this is that the full CustomResource::Type value isn't an
// AWS Lambda friendly name. We want to do this so that in the AWS lambda handler
// we can attempt to instantiate a new CustomAction resource, typecast it to a
// CustomResourceCommand type and then apply the workflow. Doing this means
// we can decouple the lookup logic for custom resource...
resource := gocf.NewResourceByType(customResourceCloudFormationTypeName)
if resource == nil {
return "", errors.Errorf("Unable to create custom resource handler of type: %v", customResourceCloudFormationTypeName)
}
command, commandOk := resource.(cfCustomResources.CustomResourceCommand)
if !commandOk {
return "", errors.Errorf("Cannot type assert resource type %s to CustomResourceCommand", customResourceCloudFormationTypeName)
}
// Prefix
commandType := reflect.TypeOf(command)
customResourceTypeName := fmt.Sprintf("%T", command)
prefixName := fmt.Sprintf("%s-CFRes", serviceName)
subscriberHandlerName := CloudFormationResourceName(prefixName, customResourceTypeName)
//////////////////////////////////////////////////////////////////////////////
// IAM Role definition
iamResourceName, err := ensureIAMRoleForCustomResource(command,
sourceArn,
template,
logger)
if nil != err {
return "", errors.Wrapf(err,
"Failed to ensure IAM Role for custom resource: %T",
command)
}
iamRoleRef := gocf.GetAtt(iamResourceName, "Arn")
_, exists := template.Resources[subscriberHandlerName]
if exists {
return subscriberHandlerName, nil
}
// Encode the resourceType...
configuratorDescription := customResourceDescription(serviceName, customResourceTypeName)
//////////////////////////////////////////////////////////////////////////////
// Custom Resource Lambda Handler
// Insert it into the template resources...
logger.WithFields(logrus.Fields{
"CloudFormationResourceType": customResourceCloudFormationTypeName,
"Resource": customResourceTypeName,
"TypeOf": commandType.String(),
}).Info("Including Lambda CustomResource")
// Don't forget the discovery info...
userDispatchMap := map[string]*gocf.StringExpr{
EnvVarCustomResourceTypeName: gocf.String(customResourceCloudFormationTypeName),
}
lambdaEnv, lambdaEnvErr := lambdaFunctionEnvironment(userDispatchMap,
customResourceTypeName,
nil,
logger)
if lambdaEnvErr != nil {
return "", errors.Wrapf(lambdaEnvErr, "Failed to create environment for required custom resource")
}
// Add the special key that's the custom resource type name
customResourceHandlerDef := gocf.LambdaFunction{
Code: &gocf.LambdaFunctionCode{
S3Bucket: gocf.String(S3Bucket),
S3Key: gocf.String(S3Key),
},
Runtime: gocf.String(GoLambdaVersion),
Description: gocf.String(configuratorDescription),
Handler: gocf.String(SpartaBinaryName),
Role: iamRoleRef,
Timeout: gocf.Integer(30),
// Let AWS assign a name here...
// FunctionName: lambdaFunctionName.String(),
// DISPATCH INFORMATION
Environment: lambdaEnv,
}
cfResource := template.AddResource(subscriberHandlerName, customResourceHandlerDef)
if nil != dependsOn && (len(dependsOn) > 0) {
cfResource.DependsOn = append(cfResource.DependsOn, dependsOn...)
}
return subscriberHandlerName, nil
} | go | func EnsureCustomResourceHandler(serviceName string,
customResourceCloudFormationTypeName string,
sourceArn *gocf.StringExpr,
dependsOn []string,
template *gocf.Template,
S3Bucket string,
S3Key string,
logger *logrus.Logger) (string, error) {
// Ok, we need a way to round trip this type as the AWS lambda function name.
// The problem with this is that the full CustomResource::Type value isn't an
// AWS Lambda friendly name. We want to do this so that in the AWS lambda handler
// we can attempt to instantiate a new CustomAction resource, typecast it to a
// CustomResourceCommand type and then apply the workflow. Doing this means
// we can decouple the lookup logic for custom resource...
resource := gocf.NewResourceByType(customResourceCloudFormationTypeName)
if resource == nil {
return "", errors.Errorf("Unable to create custom resource handler of type: %v", customResourceCloudFormationTypeName)
}
command, commandOk := resource.(cfCustomResources.CustomResourceCommand)
if !commandOk {
return "", errors.Errorf("Cannot type assert resource type %s to CustomResourceCommand", customResourceCloudFormationTypeName)
}
// Prefix
commandType := reflect.TypeOf(command)
customResourceTypeName := fmt.Sprintf("%T", command)
prefixName := fmt.Sprintf("%s-CFRes", serviceName)
subscriberHandlerName := CloudFormationResourceName(prefixName, customResourceTypeName)
//////////////////////////////////////////////////////////////////////////////
// IAM Role definition
iamResourceName, err := ensureIAMRoleForCustomResource(command,
sourceArn,
template,
logger)
if nil != err {
return "", errors.Wrapf(err,
"Failed to ensure IAM Role for custom resource: %T",
command)
}
iamRoleRef := gocf.GetAtt(iamResourceName, "Arn")
_, exists := template.Resources[subscriberHandlerName]
if exists {
return subscriberHandlerName, nil
}
// Encode the resourceType...
configuratorDescription := customResourceDescription(serviceName, customResourceTypeName)
//////////////////////////////////////////////////////////////////////////////
// Custom Resource Lambda Handler
// Insert it into the template resources...
logger.WithFields(logrus.Fields{
"CloudFormationResourceType": customResourceCloudFormationTypeName,
"Resource": customResourceTypeName,
"TypeOf": commandType.String(),
}).Info("Including Lambda CustomResource")
// Don't forget the discovery info...
userDispatchMap := map[string]*gocf.StringExpr{
EnvVarCustomResourceTypeName: gocf.String(customResourceCloudFormationTypeName),
}
lambdaEnv, lambdaEnvErr := lambdaFunctionEnvironment(userDispatchMap,
customResourceTypeName,
nil,
logger)
if lambdaEnvErr != nil {
return "", errors.Wrapf(lambdaEnvErr, "Failed to create environment for required custom resource")
}
// Add the special key that's the custom resource type name
customResourceHandlerDef := gocf.LambdaFunction{
Code: &gocf.LambdaFunctionCode{
S3Bucket: gocf.String(S3Bucket),
S3Key: gocf.String(S3Key),
},
Runtime: gocf.String(GoLambdaVersion),
Description: gocf.String(configuratorDescription),
Handler: gocf.String(SpartaBinaryName),
Role: iamRoleRef,
Timeout: gocf.Integer(30),
// Let AWS assign a name here...
// FunctionName: lambdaFunctionName.String(),
// DISPATCH INFORMATION
Environment: lambdaEnv,
}
cfResource := template.AddResource(subscriberHandlerName, customResourceHandlerDef)
if nil != dependsOn && (len(dependsOn) > 0) {
cfResource.DependsOn = append(cfResource.DependsOn, dependsOn...)
}
return subscriberHandlerName, nil
} | [
"func",
"EnsureCustomResourceHandler",
"(",
"serviceName",
"string",
",",
"customResourceCloudFormationTypeName",
"string",
",",
"sourceArn",
"*",
"gocf",
".",
"StringExpr",
",",
"dependsOn",
"[",
"]",
"string",
",",
"template",
"*",
"gocf",
".",
"Template",
",",
"S3Bucket",
"string",
",",
"S3Key",
"string",
",",
"logger",
"*",
"logrus",
".",
"Logger",
")",
"(",
"string",
",",
"error",
")",
"{",
"// Ok, we need a way to round trip this type as the AWS lambda function name.",
"// The problem with this is that the full CustomResource::Type value isn't an",
"// AWS Lambda friendly name. We want to do this so that in the AWS lambda handler",
"// we can attempt to instantiate a new CustomAction resource, typecast it to a",
"// CustomResourceCommand type and then apply the workflow. Doing this means",
"// we can decouple the lookup logic for custom resource...",
"resource",
":=",
"gocf",
".",
"NewResourceByType",
"(",
"customResourceCloudFormationTypeName",
")",
"\n",
"if",
"resource",
"==",
"nil",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"customResourceCloudFormationTypeName",
")",
"\n",
"}",
"\n",
"command",
",",
"commandOk",
":=",
"resource",
".",
"(",
"cfCustomResources",
".",
"CustomResourceCommand",
")",
"\n",
"if",
"!",
"commandOk",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"customResourceCloudFormationTypeName",
")",
"\n",
"}",
"\n\n",
"// Prefix",
"commandType",
":=",
"reflect",
".",
"TypeOf",
"(",
"command",
")",
"\n",
"customResourceTypeName",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"command",
")",
"\n",
"prefixName",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"serviceName",
")",
"\n",
"subscriberHandlerName",
":=",
"CloudFormationResourceName",
"(",
"prefixName",
",",
"customResourceTypeName",
")",
"\n\n",
"//////////////////////////////////////////////////////////////////////////////",
"// IAM Role definition",
"iamResourceName",
",",
"err",
":=",
"ensureIAMRoleForCustomResource",
"(",
"command",
",",
"sourceArn",
",",
"template",
",",
"logger",
")",
"\n",
"if",
"nil",
"!=",
"err",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"command",
")",
"\n",
"}",
"\n",
"iamRoleRef",
":=",
"gocf",
".",
"GetAtt",
"(",
"iamResourceName",
",",
"\"",
"\"",
")",
"\n",
"_",
",",
"exists",
":=",
"template",
".",
"Resources",
"[",
"subscriberHandlerName",
"]",
"\n",
"if",
"exists",
"{",
"return",
"subscriberHandlerName",
",",
"nil",
"\n",
"}",
"\n\n",
"// Encode the resourceType...",
"configuratorDescription",
":=",
"customResourceDescription",
"(",
"serviceName",
",",
"customResourceTypeName",
")",
"\n\n",
"//////////////////////////////////////////////////////////////////////////////",
"// Custom Resource Lambda Handler",
"// Insert it into the template resources...",
"logger",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"customResourceCloudFormationTypeName",
",",
"\"",
"\"",
":",
"customResourceTypeName",
",",
"\"",
"\"",
":",
"commandType",
".",
"String",
"(",
")",
",",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"// Don't forget the discovery info...",
"userDispatchMap",
":=",
"map",
"[",
"string",
"]",
"*",
"gocf",
".",
"StringExpr",
"{",
"EnvVarCustomResourceTypeName",
":",
"gocf",
".",
"String",
"(",
"customResourceCloudFormationTypeName",
")",
",",
"}",
"\n",
"lambdaEnv",
",",
"lambdaEnvErr",
":=",
"lambdaFunctionEnvironment",
"(",
"userDispatchMap",
",",
"customResourceTypeName",
",",
"nil",
",",
"logger",
")",
"\n",
"if",
"lambdaEnvErr",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Wrapf",
"(",
"lambdaEnvErr",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// Add the special key that's the custom resource type name",
"customResourceHandlerDef",
":=",
"gocf",
".",
"LambdaFunction",
"{",
"Code",
":",
"&",
"gocf",
".",
"LambdaFunctionCode",
"{",
"S3Bucket",
":",
"gocf",
".",
"String",
"(",
"S3Bucket",
")",
",",
"S3Key",
":",
"gocf",
".",
"String",
"(",
"S3Key",
")",
",",
"}",
",",
"Runtime",
":",
"gocf",
".",
"String",
"(",
"GoLambdaVersion",
")",
",",
"Description",
":",
"gocf",
".",
"String",
"(",
"configuratorDescription",
")",
",",
"Handler",
":",
"gocf",
".",
"String",
"(",
"SpartaBinaryName",
")",
",",
"Role",
":",
"iamRoleRef",
",",
"Timeout",
":",
"gocf",
".",
"Integer",
"(",
"30",
")",
",",
"// Let AWS assign a name here...",
"//\t\tFunctionName: lambdaFunctionName.String(),",
"// DISPATCH INFORMATION",
"Environment",
":",
"lambdaEnv",
",",
"}",
"\n\n",
"cfResource",
":=",
"template",
".",
"AddResource",
"(",
"subscriberHandlerName",
",",
"customResourceHandlerDef",
")",
"\n",
"if",
"nil",
"!=",
"dependsOn",
"&&",
"(",
"len",
"(",
"dependsOn",
")",
">",
"0",
")",
"{",
"cfResource",
".",
"DependsOn",
"=",
"append",
"(",
"cfResource",
".",
"DependsOn",
",",
"dependsOn",
"...",
")",
"\n",
"}",
"\n",
"return",
"subscriberHandlerName",
",",
"nil",
"\n",
"}"
] | // EnsureCustomResourceHandler handles ensuring that the custom resource responsible
// for supporting the operation is actually part of this stack. The returned
// string value is the CloudFormation resource name that implements this
// resource. The customResourceCloudFormationTypeName must have already
// been registered with gocf and implement the resources.CustomResourceCommand
// interface | [
"EnsureCustomResourceHandler",
"handles",
"ensuring",
"that",
"the",
"custom",
"resource",
"responsible",
"for",
"supporting",
"the",
"operation",
"is",
"actually",
"part",
"of",
"this",
"stack",
".",
"The",
"returned",
"string",
"value",
"is",
"the",
"CloudFormation",
"resource",
"name",
"that",
"implements",
"this",
"resource",
".",
"The",
"customResourceCloudFormationTypeName",
"must",
"have",
"already",
"been",
"registered",
"with",
"gocf",
"and",
"implement",
"the",
"resources",
".",
"CustomResourceCommand",
"interface"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/provision.go#L109-L202 |
1,271 | mweagle/Sparta | system/exec.go | RunOSCommand | func RunOSCommand(cmd *exec.Cmd, logger *logrus.Logger) error {
logger.WithFields(logrus.Fields{
"Arguments": cmd.Args,
"Dir": cmd.Dir,
"Path": cmd.Path,
"Env": cmd.Env,
}).Debug("Running Command")
outputWriter := logger.Writer()
cmdErr := RunAndCaptureOSCommand(cmd,
outputWriter,
outputWriter,
logger)
closeErr := outputWriter.Close()
if closeErr != nil {
logger.WithField("closeError", closeErr).Warn("Failed to close OS command writer")
}
return cmdErr
} | go | func RunOSCommand(cmd *exec.Cmd, logger *logrus.Logger) error {
logger.WithFields(logrus.Fields{
"Arguments": cmd.Args,
"Dir": cmd.Dir,
"Path": cmd.Path,
"Env": cmd.Env,
}).Debug("Running Command")
outputWriter := logger.Writer()
cmdErr := RunAndCaptureOSCommand(cmd,
outputWriter,
outputWriter,
logger)
closeErr := outputWriter.Close()
if closeErr != nil {
logger.WithField("closeError", closeErr).Warn("Failed to close OS command writer")
}
return cmdErr
} | [
"func",
"RunOSCommand",
"(",
"cmd",
"*",
"exec",
".",
"Cmd",
",",
"logger",
"*",
"logrus",
".",
"Logger",
")",
"error",
"{",
"logger",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"cmd",
".",
"Args",
",",
"\"",
"\"",
":",
"cmd",
".",
"Dir",
",",
"\"",
"\"",
":",
"cmd",
".",
"Path",
",",
"\"",
"\"",
":",
"cmd",
".",
"Env",
",",
"}",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"outputWriter",
":=",
"logger",
".",
"Writer",
"(",
")",
"\n",
"cmdErr",
":=",
"RunAndCaptureOSCommand",
"(",
"cmd",
",",
"outputWriter",
",",
"outputWriter",
",",
"logger",
")",
"\n",
"closeErr",
":=",
"outputWriter",
".",
"Close",
"(",
")",
"\n",
"if",
"closeErr",
"!=",
"nil",
"{",
"logger",
".",
"WithField",
"(",
"\"",
"\"",
",",
"closeErr",
")",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"cmdErr",
"\n",
"}"
] | // RunOSCommand properly executes a system command
// and writes the output to the provided logger | [
"RunOSCommand",
"properly",
"executes",
"a",
"system",
"command",
"and",
"writes",
"the",
"output",
"to",
"the",
"provided",
"logger"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/system/exec.go#L12-L29 |
1,272 | mweagle/Sparta | system/exec.go | RunAndCaptureOSCommand | func RunAndCaptureOSCommand(cmd *exec.Cmd,
stdoutWriter io.Writer,
stderrWriter io.Writer,
logger *logrus.Logger) error {
logger.WithFields(logrus.Fields{
"Arguments": cmd.Args,
"Dir": cmd.Dir,
"Path": cmd.Path,
"Env": cmd.Env,
}).Debug("Running Command")
cmd.Stdout = stdoutWriter
cmd.Stderr = stderrWriter
return cmd.Run()
} | go | func RunAndCaptureOSCommand(cmd *exec.Cmd,
stdoutWriter io.Writer,
stderrWriter io.Writer,
logger *logrus.Logger) error {
logger.WithFields(logrus.Fields{
"Arguments": cmd.Args,
"Dir": cmd.Dir,
"Path": cmd.Path,
"Env": cmd.Env,
}).Debug("Running Command")
cmd.Stdout = stdoutWriter
cmd.Stderr = stderrWriter
return cmd.Run()
} | [
"func",
"RunAndCaptureOSCommand",
"(",
"cmd",
"*",
"exec",
".",
"Cmd",
",",
"stdoutWriter",
"io",
".",
"Writer",
",",
"stderrWriter",
"io",
".",
"Writer",
",",
"logger",
"*",
"logrus",
".",
"Logger",
")",
"error",
"{",
"logger",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"cmd",
".",
"Args",
",",
"\"",
"\"",
":",
"cmd",
".",
"Dir",
",",
"\"",
"\"",
":",
"cmd",
".",
"Path",
",",
"\"",
"\"",
":",
"cmd",
".",
"Env",
",",
"}",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"cmd",
".",
"Stdout",
"=",
"stdoutWriter",
"\n",
"cmd",
".",
"Stderr",
"=",
"stderrWriter",
"\n",
"return",
"cmd",
".",
"Run",
"(",
")",
"\n\n",
"}"
] | // RunAndCaptureOSCommand runs the given command and
// captures the stdout and stderr | [
"RunAndCaptureOSCommand",
"runs",
"the",
"given",
"command",
"and",
"captures",
"the",
"stdout",
"and",
"stderr"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/system/exec.go#L33-L47 |
1,273 | mweagle/Sparta | decorator/dashboard.go | DashboardDecorator | func DashboardDecorator(lambdaAWSInfo []*sparta.LambdaAWSInfo,
timeSeriesPeriod int) sparta.ServiceDecoratorHookFunc {
return func(context map[string]interface{},
serviceName string,
cfTemplate *gocf.Template,
S3Bucket string,
S3Key string,
buildID string,
awsSession *session.Session,
noop bool,
logger *logrus.Logger) error {
lambdaFunctions := make([]*LambdaTemplateData, len(lambdaAWSInfo))
for index, eachLambda := range lambdaAWSInfo {
lambdaFunctions[index] = &LambdaTemplateData{
LambdaAWSInfo: eachLambda,
ResourceName: eachLambda.LogicalResourceName(),
}
}
dashboardTemplateData := &DashboardTemplateData{
SpartaVersion: sparta.SpartaVersion,
SpartaGitHash: sparta.SpartaGitHash,
LambdaFunctions: lambdaFunctions,
TimeSeriesPeriod: timeSeriesPeriod,
Extents: widgetExtents{
HeaderWidthUnits: headerWidthUnits,
HeaderHeightUnits: headerHeightUnits,
MetricWidthUnits: metricWidthUnits,
MetricHeightUnits: metricHeightUnits,
MetricsPerRow: metricsPerRow,
},
}
dashboardTmpl, dashboardTmplErr := template.New("dashboard").
Delims("<<", ">>").
Funcs(templateFuncMap).
Parse(dashboardTemplate)
if nil != dashboardTmplErr {
return dashboardTmplErr
}
var templateResults bytes.Buffer
evalResultErr := dashboardTmpl.Execute(&templateResults, dashboardTemplateData)
if nil != evalResultErr {
return evalResultErr
}
// Raw template output
logger.WithFields(logrus.Fields{
"Dashboard": templateResults.String(),
}).Debug("CloudWatch Dashboard template result")
// Replace any multiline backtick newlines with nothing, since otherwise
// the Fn::Joined JSON will be malformed
reReplace, reReplaceErr := regexp.Compile("\n")
if nil != reReplaceErr {
return reReplaceErr
}
escapedBytes := reReplace.ReplaceAll(templateResults.Bytes(), []byte(""))
logger.WithFields(logrus.Fields{
"Dashboard": string(escapedBytes),
}).Debug("CloudWatch Dashboard post cleanup")
// Super, now parse this into an Fn::Join representation
// so that we can get inline expansion of the AWS pseudo params
templateReader := bytes.NewReader(escapedBytes)
templateExpr, templateExprErr := spartaCF.ConvertToTemplateExpression(templateReader, nil)
if nil != templateExprErr {
return templateExprErr
}
dashboardResource := gocf.CloudWatchDashboard{}
dashboardResource.DashboardBody = templateExpr
dashboardResource.DashboardName = gocf.String(serviceName)
dashboardName := sparta.CloudFormationResourceName("Dashboard", "Dashboard")
cfTemplate.AddResource(dashboardName, &dashboardResource)
// Add the output
cfTemplate.Outputs[OutputDashboardURL] = &gocf.Output{
Description: "CloudWatch Dashboard URL",
Value: gocf.Join("",
gocf.String("https://"),
gocf.Ref("AWS::Region"),
gocf.String(".console.aws.amazon.com/cloudwatch/home?region="),
gocf.Ref("AWS::Region"),
gocf.String("#dashboards:name="),
gocf.Ref(dashboardName)),
}
return nil
}
} | go | func DashboardDecorator(lambdaAWSInfo []*sparta.LambdaAWSInfo,
timeSeriesPeriod int) sparta.ServiceDecoratorHookFunc {
return func(context map[string]interface{},
serviceName string,
cfTemplate *gocf.Template,
S3Bucket string,
S3Key string,
buildID string,
awsSession *session.Session,
noop bool,
logger *logrus.Logger) error {
lambdaFunctions := make([]*LambdaTemplateData, len(lambdaAWSInfo))
for index, eachLambda := range lambdaAWSInfo {
lambdaFunctions[index] = &LambdaTemplateData{
LambdaAWSInfo: eachLambda,
ResourceName: eachLambda.LogicalResourceName(),
}
}
dashboardTemplateData := &DashboardTemplateData{
SpartaVersion: sparta.SpartaVersion,
SpartaGitHash: sparta.SpartaGitHash,
LambdaFunctions: lambdaFunctions,
TimeSeriesPeriod: timeSeriesPeriod,
Extents: widgetExtents{
HeaderWidthUnits: headerWidthUnits,
HeaderHeightUnits: headerHeightUnits,
MetricWidthUnits: metricWidthUnits,
MetricHeightUnits: metricHeightUnits,
MetricsPerRow: metricsPerRow,
},
}
dashboardTmpl, dashboardTmplErr := template.New("dashboard").
Delims("<<", ">>").
Funcs(templateFuncMap).
Parse(dashboardTemplate)
if nil != dashboardTmplErr {
return dashboardTmplErr
}
var templateResults bytes.Buffer
evalResultErr := dashboardTmpl.Execute(&templateResults, dashboardTemplateData)
if nil != evalResultErr {
return evalResultErr
}
// Raw template output
logger.WithFields(logrus.Fields{
"Dashboard": templateResults.String(),
}).Debug("CloudWatch Dashboard template result")
// Replace any multiline backtick newlines with nothing, since otherwise
// the Fn::Joined JSON will be malformed
reReplace, reReplaceErr := regexp.Compile("\n")
if nil != reReplaceErr {
return reReplaceErr
}
escapedBytes := reReplace.ReplaceAll(templateResults.Bytes(), []byte(""))
logger.WithFields(logrus.Fields{
"Dashboard": string(escapedBytes),
}).Debug("CloudWatch Dashboard post cleanup")
// Super, now parse this into an Fn::Join representation
// so that we can get inline expansion of the AWS pseudo params
templateReader := bytes.NewReader(escapedBytes)
templateExpr, templateExprErr := spartaCF.ConvertToTemplateExpression(templateReader, nil)
if nil != templateExprErr {
return templateExprErr
}
dashboardResource := gocf.CloudWatchDashboard{}
dashboardResource.DashboardBody = templateExpr
dashboardResource.DashboardName = gocf.String(serviceName)
dashboardName := sparta.CloudFormationResourceName("Dashboard", "Dashboard")
cfTemplate.AddResource(dashboardName, &dashboardResource)
// Add the output
cfTemplate.Outputs[OutputDashboardURL] = &gocf.Output{
Description: "CloudWatch Dashboard URL",
Value: gocf.Join("",
gocf.String("https://"),
gocf.Ref("AWS::Region"),
gocf.String(".console.aws.amazon.com/cloudwatch/home?region="),
gocf.Ref("AWS::Region"),
gocf.String("#dashboards:name="),
gocf.Ref(dashboardName)),
}
return nil
}
} | [
"func",
"DashboardDecorator",
"(",
"lambdaAWSInfo",
"[",
"]",
"*",
"sparta",
".",
"LambdaAWSInfo",
",",
"timeSeriesPeriod",
"int",
")",
"sparta",
".",
"ServiceDecoratorHookFunc",
"{",
"return",
"func",
"(",
"context",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"serviceName",
"string",
",",
"cfTemplate",
"*",
"gocf",
".",
"Template",
",",
"S3Bucket",
"string",
",",
"S3Key",
"string",
",",
"buildID",
"string",
",",
"awsSession",
"*",
"session",
".",
"Session",
",",
"noop",
"bool",
",",
"logger",
"*",
"logrus",
".",
"Logger",
")",
"error",
"{",
"lambdaFunctions",
":=",
"make",
"(",
"[",
"]",
"*",
"LambdaTemplateData",
",",
"len",
"(",
"lambdaAWSInfo",
")",
")",
"\n",
"for",
"index",
",",
"eachLambda",
":=",
"range",
"lambdaAWSInfo",
"{",
"lambdaFunctions",
"[",
"index",
"]",
"=",
"&",
"LambdaTemplateData",
"{",
"LambdaAWSInfo",
":",
"eachLambda",
",",
"ResourceName",
":",
"eachLambda",
".",
"LogicalResourceName",
"(",
")",
",",
"}",
"\n",
"}",
"\n",
"dashboardTemplateData",
":=",
"&",
"DashboardTemplateData",
"{",
"SpartaVersion",
":",
"sparta",
".",
"SpartaVersion",
",",
"SpartaGitHash",
":",
"sparta",
".",
"SpartaGitHash",
",",
"LambdaFunctions",
":",
"lambdaFunctions",
",",
"TimeSeriesPeriod",
":",
"timeSeriesPeriod",
",",
"Extents",
":",
"widgetExtents",
"{",
"HeaderWidthUnits",
":",
"headerWidthUnits",
",",
"HeaderHeightUnits",
":",
"headerHeightUnits",
",",
"MetricWidthUnits",
":",
"metricWidthUnits",
",",
"MetricHeightUnits",
":",
"metricHeightUnits",
",",
"MetricsPerRow",
":",
"metricsPerRow",
",",
"}",
",",
"}",
"\n\n",
"dashboardTmpl",
",",
"dashboardTmplErr",
":=",
"template",
".",
"New",
"(",
"\"",
"\"",
")",
".",
"Delims",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
".",
"Funcs",
"(",
"templateFuncMap",
")",
".",
"Parse",
"(",
"dashboardTemplate",
")",
"\n",
"if",
"nil",
"!=",
"dashboardTmplErr",
"{",
"return",
"dashboardTmplErr",
"\n",
"}",
"\n",
"var",
"templateResults",
"bytes",
".",
"Buffer",
"\n",
"evalResultErr",
":=",
"dashboardTmpl",
".",
"Execute",
"(",
"&",
"templateResults",
",",
"dashboardTemplateData",
")",
"\n",
"if",
"nil",
"!=",
"evalResultErr",
"{",
"return",
"evalResultErr",
"\n",
"}",
"\n\n",
"// Raw template output",
"logger",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"templateResults",
".",
"String",
"(",
")",
",",
"}",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n\n",
"// Replace any multiline backtick newlines with nothing, since otherwise",
"// the Fn::Joined JSON will be malformed",
"reReplace",
",",
"reReplaceErr",
":=",
"regexp",
".",
"Compile",
"(",
"\"",
"\\n",
"\"",
")",
"\n",
"if",
"nil",
"!=",
"reReplaceErr",
"{",
"return",
"reReplaceErr",
"\n",
"}",
"\n",
"escapedBytes",
":=",
"reReplace",
".",
"ReplaceAll",
"(",
"templateResults",
".",
"Bytes",
"(",
")",
",",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
")",
"\n",
"logger",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"string",
"(",
"escapedBytes",
")",
",",
"}",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n\n",
"// Super, now parse this into an Fn::Join representation",
"// so that we can get inline expansion of the AWS pseudo params",
"templateReader",
":=",
"bytes",
".",
"NewReader",
"(",
"escapedBytes",
")",
"\n",
"templateExpr",
",",
"templateExprErr",
":=",
"spartaCF",
".",
"ConvertToTemplateExpression",
"(",
"templateReader",
",",
"nil",
")",
"\n",
"if",
"nil",
"!=",
"templateExprErr",
"{",
"return",
"templateExprErr",
"\n",
"}",
"\n\n",
"dashboardResource",
":=",
"gocf",
".",
"CloudWatchDashboard",
"{",
"}",
"\n",
"dashboardResource",
".",
"DashboardBody",
"=",
"templateExpr",
"\n",
"dashboardResource",
".",
"DashboardName",
"=",
"gocf",
".",
"String",
"(",
"serviceName",
")",
"\n",
"dashboardName",
":=",
"sparta",
".",
"CloudFormationResourceName",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"cfTemplate",
".",
"AddResource",
"(",
"dashboardName",
",",
"&",
"dashboardResource",
")",
"\n\n",
"// Add the output",
"cfTemplate",
".",
"Outputs",
"[",
"OutputDashboardURL",
"]",
"=",
"&",
"gocf",
".",
"Output",
"{",
"Description",
":",
"\"",
"\"",
",",
"Value",
":",
"gocf",
".",
"Join",
"(",
"\"",
"\"",
",",
"gocf",
".",
"String",
"(",
"\"",
"\"",
")",
",",
"gocf",
".",
"Ref",
"(",
"\"",
"\"",
")",
",",
"gocf",
".",
"String",
"(",
"\"",
"\"",
")",
",",
"gocf",
".",
"Ref",
"(",
"\"",
"\"",
")",
",",
"gocf",
".",
"String",
"(",
"\"",
"\"",
")",
",",
"gocf",
".",
"Ref",
"(",
"dashboardName",
")",
")",
",",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // DashboardDecorator returns a ServiceDecoratorHook function that
// can be attached the workflow to create a dashboard | [
"DashboardDecorator",
"returns",
"a",
"ServiceDecoratorHook",
"function",
"that",
"can",
"be",
"attached",
"the",
"workflow",
"to",
"create",
"a",
"dashboard"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/decorator/dashboard.go#L130-L219 |
1,274 | mweagle/Sparta | aws/cloudformation/resources/s3ArtifactPublisherResource.go | Create | func (command S3ArtifactPublisherResource) Create(awsSession *session.Session,
event *CloudFormationLambdaEvent,
logger *logrus.Logger) (map[string]interface{}, error) {
unmarshalErr := json.Unmarshal(event.ResourceProperties, &command)
if unmarshalErr != nil {
return nil, unmarshalErr
}
mapData, mapDataErr := json.Marshal(command.Body)
if mapDataErr != nil {
return nil, mapDataErr
}
itemInput := bytes.NewReader(mapData)
s3PutObjectParams := &s3.PutObjectInput{
Body: itemInput,
Bucket: aws.String(command.Bucket.Literal),
Key: aws.String(command.Key.Literal),
}
s3Svc := s3.New(awsSession)
s3Response, s3ResponseErr := s3Svc.PutObject(s3PutObjectParams)
if s3ResponseErr != nil {
return nil, s3ResponseErr
}
return map[string]interface{}{
"ObjectVersion": s3Response.VersionId,
}, nil
} | go | func (command S3ArtifactPublisherResource) Create(awsSession *session.Session,
event *CloudFormationLambdaEvent,
logger *logrus.Logger) (map[string]interface{}, error) {
unmarshalErr := json.Unmarshal(event.ResourceProperties, &command)
if unmarshalErr != nil {
return nil, unmarshalErr
}
mapData, mapDataErr := json.Marshal(command.Body)
if mapDataErr != nil {
return nil, mapDataErr
}
itemInput := bytes.NewReader(mapData)
s3PutObjectParams := &s3.PutObjectInput{
Body: itemInput,
Bucket: aws.String(command.Bucket.Literal),
Key: aws.String(command.Key.Literal),
}
s3Svc := s3.New(awsSession)
s3Response, s3ResponseErr := s3Svc.PutObject(s3PutObjectParams)
if s3ResponseErr != nil {
return nil, s3ResponseErr
}
return map[string]interface{}{
"ObjectVersion": s3Response.VersionId,
}, nil
} | [
"func",
"(",
"command",
"S3ArtifactPublisherResource",
")",
"Create",
"(",
"awsSession",
"*",
"session",
".",
"Session",
",",
"event",
"*",
"CloudFormationLambdaEvent",
",",
"logger",
"*",
"logrus",
".",
"Logger",
")",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"unmarshalErr",
":=",
"json",
".",
"Unmarshal",
"(",
"event",
".",
"ResourceProperties",
",",
"&",
"command",
")",
"\n",
"if",
"unmarshalErr",
"!=",
"nil",
"{",
"return",
"nil",
",",
"unmarshalErr",
"\n",
"}",
"\n",
"mapData",
",",
"mapDataErr",
":=",
"json",
".",
"Marshal",
"(",
"command",
".",
"Body",
")",
"\n",
"if",
"mapDataErr",
"!=",
"nil",
"{",
"return",
"nil",
",",
"mapDataErr",
"\n",
"}",
"\n",
"itemInput",
":=",
"bytes",
".",
"NewReader",
"(",
"mapData",
")",
"\n",
"s3PutObjectParams",
":=",
"&",
"s3",
".",
"PutObjectInput",
"{",
"Body",
":",
"itemInput",
",",
"Bucket",
":",
"aws",
".",
"String",
"(",
"command",
".",
"Bucket",
".",
"Literal",
")",
",",
"Key",
":",
"aws",
".",
"String",
"(",
"command",
".",
"Key",
".",
"Literal",
")",
",",
"}",
"\n",
"s3Svc",
":=",
"s3",
".",
"New",
"(",
"awsSession",
")",
"\n",
"s3Response",
",",
"s3ResponseErr",
":=",
"s3Svc",
".",
"PutObject",
"(",
"s3PutObjectParams",
")",
"\n",
"if",
"s3ResponseErr",
"!=",
"nil",
"{",
"return",
"nil",
",",
"s3ResponseErr",
"\n",
"}",
"\n",
"return",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"s3Response",
".",
"VersionId",
",",
"}",
",",
"nil",
"\n",
"}"
] | // Create implements the S3 create operation | [
"Create",
"implements",
"the",
"S3",
"create",
"operation"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/cloudformation/resources/s3ArtifactPublisherResource.go#L35-L61 |
1,275 | mweagle/Sparta | aws/cloudformation/resources/s3ArtifactPublisherResource.go | Update | func (command S3ArtifactPublisherResource) Update(awsSession *session.Session,
event *CloudFormationLambdaEvent,
logger *logrus.Logger) (map[string]interface{}, error) {
return command.Create(awsSession, event, logger)
} | go | func (command S3ArtifactPublisherResource) Update(awsSession *session.Session,
event *CloudFormationLambdaEvent,
logger *logrus.Logger) (map[string]interface{}, error) {
return command.Create(awsSession, event, logger)
} | [
"func",
"(",
"command",
"S3ArtifactPublisherResource",
")",
"Update",
"(",
"awsSession",
"*",
"session",
".",
"Session",
",",
"event",
"*",
"CloudFormationLambdaEvent",
",",
"logger",
"*",
"logrus",
".",
"Logger",
")",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"return",
"command",
".",
"Create",
"(",
"awsSession",
",",
"event",
",",
"logger",
")",
"\n",
"}"
] | // Update implements the S3 update operation | [
"Update",
"implements",
"the",
"S3",
"update",
"operation"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/cloudformation/resources/s3ArtifactPublisherResource.go#L64-L68 |
1,276 | mweagle/Sparta | aws/cloudformation/resources/s3ArtifactPublisherResource.go | Delete | func (command S3ArtifactPublisherResource) Delete(awsSession *session.Session,
event *CloudFormationLambdaEvent,
logger *logrus.Logger) (map[string]interface{}, error) {
unmarshalErr := json.Unmarshal(event.ResourceProperties, &command)
if unmarshalErr != nil {
return nil, unmarshalErr
}
s3DeleteObjectParams := &s3.DeleteObjectInput{
Bucket: aws.String(command.Bucket.Literal),
Key: aws.String(command.Key.Literal),
}
s3Svc := s3.New(awsSession)
_, s3ResponseErr := s3Svc.DeleteObject(s3DeleteObjectParams)
if s3ResponseErr != nil {
return nil, s3ResponseErr
}
logger.WithFields(logrus.Fields{
"Bucket": command.Bucket.Literal,
"Key": command.Key.Literal,
}).Info("Object deleted")
return nil, nil
} | go | func (command S3ArtifactPublisherResource) Delete(awsSession *session.Session,
event *CloudFormationLambdaEvent,
logger *logrus.Logger) (map[string]interface{}, error) {
unmarshalErr := json.Unmarshal(event.ResourceProperties, &command)
if unmarshalErr != nil {
return nil, unmarshalErr
}
s3DeleteObjectParams := &s3.DeleteObjectInput{
Bucket: aws.String(command.Bucket.Literal),
Key: aws.String(command.Key.Literal),
}
s3Svc := s3.New(awsSession)
_, s3ResponseErr := s3Svc.DeleteObject(s3DeleteObjectParams)
if s3ResponseErr != nil {
return nil, s3ResponseErr
}
logger.WithFields(logrus.Fields{
"Bucket": command.Bucket.Literal,
"Key": command.Key.Literal,
}).Info("Object deleted")
return nil, nil
} | [
"func",
"(",
"command",
"S3ArtifactPublisherResource",
")",
"Delete",
"(",
"awsSession",
"*",
"session",
".",
"Session",
",",
"event",
"*",
"CloudFormationLambdaEvent",
",",
"logger",
"*",
"logrus",
".",
"Logger",
")",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"unmarshalErr",
":=",
"json",
".",
"Unmarshal",
"(",
"event",
".",
"ResourceProperties",
",",
"&",
"command",
")",
"\n",
"if",
"unmarshalErr",
"!=",
"nil",
"{",
"return",
"nil",
",",
"unmarshalErr",
"\n",
"}",
"\n",
"s3DeleteObjectParams",
":=",
"&",
"s3",
".",
"DeleteObjectInput",
"{",
"Bucket",
":",
"aws",
".",
"String",
"(",
"command",
".",
"Bucket",
".",
"Literal",
")",
",",
"Key",
":",
"aws",
".",
"String",
"(",
"command",
".",
"Key",
".",
"Literal",
")",
",",
"}",
"\n",
"s3Svc",
":=",
"s3",
".",
"New",
"(",
"awsSession",
")",
"\n",
"_",
",",
"s3ResponseErr",
":=",
"s3Svc",
".",
"DeleteObject",
"(",
"s3DeleteObjectParams",
")",
"\n",
"if",
"s3ResponseErr",
"!=",
"nil",
"{",
"return",
"nil",
",",
"s3ResponseErr",
"\n",
"}",
"\n",
"logger",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"command",
".",
"Bucket",
".",
"Literal",
",",
"\"",
"\"",
":",
"command",
".",
"Key",
".",
"Literal",
",",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}"
] | // Delete implements the S3 delete operation | [
"Delete",
"implements",
"the",
"S3",
"delete",
"operation"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/cloudformation/resources/s3ArtifactPublisherResource.go#L71-L93 |
1,277 | mweagle/Sparta | aws/s3/util.go | CreateS3RollbackFunc | func CreateS3RollbackFunc(awsSession *session.Session, s3ArtifactURL string) RollbackFunction {
return func(logger *logrus.Logger) error {
logger.WithFields(logrus.Fields{
"URL": s3ArtifactURL,
}).Info("Deleting S3 object")
artifactURLParts, artifactURLPartsErr := url.Parse(s3ArtifactURL)
if nil != artifactURLPartsErr {
return artifactURLPartsErr
}
// Bucket is the first component
s3Bucket := strings.Split(artifactURLParts.Host, ".")[0]
s3Client := s3.New(awsSession)
params := &s3.DeleteObjectInput{
Bucket: aws.String(s3Bucket),
Key: aws.String(artifactURLParts.Path),
}
versionID := artifactURLParts.Query().Get("versionId")
if versionID != "" {
params.VersionId = aws.String(versionID)
}
_, err := s3Client.DeleteObject(params)
if err != nil {
logger.WithFields(logrus.Fields{
"Error": err,
}).Warn("Failed to delete S3 item during rollback cleanup")
}
return err
}
} | go | func CreateS3RollbackFunc(awsSession *session.Session, s3ArtifactURL string) RollbackFunction {
return func(logger *logrus.Logger) error {
logger.WithFields(logrus.Fields{
"URL": s3ArtifactURL,
}).Info("Deleting S3 object")
artifactURLParts, artifactURLPartsErr := url.Parse(s3ArtifactURL)
if nil != artifactURLPartsErr {
return artifactURLPartsErr
}
// Bucket is the first component
s3Bucket := strings.Split(artifactURLParts.Host, ".")[0]
s3Client := s3.New(awsSession)
params := &s3.DeleteObjectInput{
Bucket: aws.String(s3Bucket),
Key: aws.String(artifactURLParts.Path),
}
versionID := artifactURLParts.Query().Get("versionId")
if versionID != "" {
params.VersionId = aws.String(versionID)
}
_, err := s3Client.DeleteObject(params)
if err != nil {
logger.WithFields(logrus.Fields{
"Error": err,
}).Warn("Failed to delete S3 item during rollback cleanup")
}
return err
}
} | [
"func",
"CreateS3RollbackFunc",
"(",
"awsSession",
"*",
"session",
".",
"Session",
",",
"s3ArtifactURL",
"string",
")",
"RollbackFunction",
"{",
"return",
"func",
"(",
"logger",
"*",
"logrus",
".",
"Logger",
")",
"error",
"{",
"logger",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"s3ArtifactURL",
",",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"artifactURLParts",
",",
"artifactURLPartsErr",
":=",
"url",
".",
"Parse",
"(",
"s3ArtifactURL",
")",
"\n",
"if",
"nil",
"!=",
"artifactURLPartsErr",
"{",
"return",
"artifactURLPartsErr",
"\n",
"}",
"\n",
"// Bucket is the first component",
"s3Bucket",
":=",
"strings",
".",
"Split",
"(",
"artifactURLParts",
".",
"Host",
",",
"\"",
"\"",
")",
"[",
"0",
"]",
"\n",
"s3Client",
":=",
"s3",
".",
"New",
"(",
"awsSession",
")",
"\n",
"params",
":=",
"&",
"s3",
".",
"DeleteObjectInput",
"{",
"Bucket",
":",
"aws",
".",
"String",
"(",
"s3Bucket",
")",
",",
"Key",
":",
"aws",
".",
"String",
"(",
"artifactURLParts",
".",
"Path",
")",
",",
"}",
"\n",
"versionID",
":=",
"artifactURLParts",
".",
"Query",
"(",
")",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"if",
"versionID",
"!=",
"\"",
"\"",
"{",
"params",
".",
"VersionId",
"=",
"aws",
".",
"String",
"(",
"versionID",
")",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"s3Client",
".",
"DeleteObject",
"(",
"params",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"err",
",",
"}",
")",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"}"
] | // CreateS3RollbackFunc creates an S3 rollback function that attempts to delete a previously
// uploaded item. Note that s3ArtifactURL may include a `versionId` query arg
// to denote the specific version to delete. | [
"CreateS3RollbackFunc",
"creates",
"an",
"S3",
"rollback",
"function",
"that",
"attempts",
"to",
"delete",
"a",
"previously",
"uploaded",
"item",
".",
"Note",
"that",
"s3ArtifactURL",
"may",
"include",
"a",
"versionId",
"query",
"arg",
"to",
"denote",
"the",
"specific",
"version",
"to",
"delete",
"."
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/s3/util.go#L26-L54 |
1,278 | mweagle/Sparta | aws/s3/util.go | UploadLocalFileToS3 | func UploadLocalFileToS3(localPath string,
awsSession *session.Session,
S3Bucket string,
S3KeyName string,
logger *logrus.Logger) (string, error) {
// Then do the actual work
/* #nosec */
reader, err := os.Open(localPath)
if nil != err {
return "", fmt.Errorf("failed to open local archive for S3 upload: %s", err.Error())
}
uploadInput := &s3manager.UploadInput{
Bucket: &S3Bucket,
Key: &S3KeyName,
ContentType: aws.String(mime.TypeByExtension(path.Ext(localPath))),
Body: reader,
}
// If we can get the current working directory, let's try and strip
// it from the path just to keep the log statement a bit shorter
logPath := localPath
cwd, cwdErr := os.Getwd()
if cwdErr == nil {
logPath = strings.TrimPrefix(logPath, cwd)
if logPath != localPath {
logPath = fmt.Sprintf(".%s", logPath)
}
}
// Binary size
stat, err := os.Stat(localPath)
if err != nil {
return "", fmt.Errorf("failed to calculate upload size for file: %s", localPath)
}
logger.WithFields(logrus.Fields{
"Path": logPath,
"Bucket": S3Bucket,
"Key": S3KeyName,
"Size": humanize.Bytes(uint64(stat.Size())),
}).Info("Uploading local file to S3")
uploader := s3manager.NewUploader(awsSession)
result, err := uploader.Upload(uploadInput)
if nil != err {
return "", errors.Wrapf(err, "Failed to upload object to S3")
}
if result.VersionID != nil {
logger.WithFields(logrus.Fields{
"URL": result.Location,
"VersionID": string(*result.VersionID),
}).Debug("S3 upload complete")
} else {
logger.WithFields(logrus.Fields{
"URL": result.Location,
}).Debug("S3 upload complete")
}
locationURL := result.Location
if nil != result.VersionID {
// http://docs.aws.amazon.com/AmazonS3/latest/dev/RetrievingObjectVersions.html
locationURL = fmt.Sprintf("%s?versionId=%s", locationURL, string(*result.VersionID))
}
return locationURL, nil
} | go | func UploadLocalFileToS3(localPath string,
awsSession *session.Session,
S3Bucket string,
S3KeyName string,
logger *logrus.Logger) (string, error) {
// Then do the actual work
/* #nosec */
reader, err := os.Open(localPath)
if nil != err {
return "", fmt.Errorf("failed to open local archive for S3 upload: %s", err.Error())
}
uploadInput := &s3manager.UploadInput{
Bucket: &S3Bucket,
Key: &S3KeyName,
ContentType: aws.String(mime.TypeByExtension(path.Ext(localPath))),
Body: reader,
}
// If we can get the current working directory, let's try and strip
// it from the path just to keep the log statement a bit shorter
logPath := localPath
cwd, cwdErr := os.Getwd()
if cwdErr == nil {
logPath = strings.TrimPrefix(logPath, cwd)
if logPath != localPath {
logPath = fmt.Sprintf(".%s", logPath)
}
}
// Binary size
stat, err := os.Stat(localPath)
if err != nil {
return "", fmt.Errorf("failed to calculate upload size for file: %s", localPath)
}
logger.WithFields(logrus.Fields{
"Path": logPath,
"Bucket": S3Bucket,
"Key": S3KeyName,
"Size": humanize.Bytes(uint64(stat.Size())),
}).Info("Uploading local file to S3")
uploader := s3manager.NewUploader(awsSession)
result, err := uploader.Upload(uploadInput)
if nil != err {
return "", errors.Wrapf(err, "Failed to upload object to S3")
}
if result.VersionID != nil {
logger.WithFields(logrus.Fields{
"URL": result.Location,
"VersionID": string(*result.VersionID),
}).Debug("S3 upload complete")
} else {
logger.WithFields(logrus.Fields{
"URL": result.Location,
}).Debug("S3 upload complete")
}
locationURL := result.Location
if nil != result.VersionID {
// http://docs.aws.amazon.com/AmazonS3/latest/dev/RetrievingObjectVersions.html
locationURL = fmt.Sprintf("%s?versionId=%s", locationURL, string(*result.VersionID))
}
return locationURL, nil
} | [
"func",
"UploadLocalFileToS3",
"(",
"localPath",
"string",
",",
"awsSession",
"*",
"session",
".",
"Session",
",",
"S3Bucket",
"string",
",",
"S3KeyName",
"string",
",",
"logger",
"*",
"logrus",
".",
"Logger",
")",
"(",
"string",
",",
"error",
")",
"{",
"// Then do the actual work",
"/* #nosec */",
"reader",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"localPath",
")",
"\n",
"if",
"nil",
"!=",
"err",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"uploadInput",
":=",
"&",
"s3manager",
".",
"UploadInput",
"{",
"Bucket",
":",
"&",
"S3Bucket",
",",
"Key",
":",
"&",
"S3KeyName",
",",
"ContentType",
":",
"aws",
".",
"String",
"(",
"mime",
".",
"TypeByExtension",
"(",
"path",
".",
"Ext",
"(",
"localPath",
")",
")",
")",
",",
"Body",
":",
"reader",
",",
"}",
"\n",
"// If we can get the current working directory, let's try and strip",
"// it from the path just to keep the log statement a bit shorter",
"logPath",
":=",
"localPath",
"\n",
"cwd",
",",
"cwdErr",
":=",
"os",
".",
"Getwd",
"(",
")",
"\n",
"if",
"cwdErr",
"==",
"nil",
"{",
"logPath",
"=",
"strings",
".",
"TrimPrefix",
"(",
"logPath",
",",
"cwd",
")",
"\n",
"if",
"logPath",
"!=",
"localPath",
"{",
"logPath",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"logPath",
")",
"\n",
"}",
"\n",
"}",
"\n",
"// Binary size",
"stat",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"localPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"localPath",
")",
"\n",
"}",
"\n",
"logger",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"logPath",
",",
"\"",
"\"",
":",
"S3Bucket",
",",
"\"",
"\"",
":",
"S3KeyName",
",",
"\"",
"\"",
":",
"humanize",
".",
"Bytes",
"(",
"uint64",
"(",
"stat",
".",
"Size",
"(",
")",
")",
")",
",",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"uploader",
":=",
"s3manager",
".",
"NewUploader",
"(",
"awsSession",
")",
"\n",
"result",
",",
"err",
":=",
"uploader",
".",
"Upload",
"(",
"uploadInput",
")",
"\n",
"if",
"nil",
"!=",
"err",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"result",
".",
"VersionID",
"!=",
"nil",
"{",
"logger",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"result",
".",
"Location",
",",
"\"",
"\"",
":",
"string",
"(",
"*",
"result",
".",
"VersionID",
")",
",",
"}",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"logger",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"result",
".",
"Location",
",",
"}",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"locationURL",
":=",
"result",
".",
"Location",
"\n",
"if",
"nil",
"!=",
"result",
".",
"VersionID",
"{",
"// http://docs.aws.amazon.com/AmazonS3/latest/dev/RetrievingObjectVersions.html",
"locationURL",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"locationURL",
",",
"string",
"(",
"*",
"result",
".",
"VersionID",
")",
")",
"\n",
"}",
"\n",
"return",
"locationURL",
",",
"nil",
"\n",
"}"
] | // UploadLocalFileToS3 takes a local path and uploads the content at localPath
// to the given S3Bucket and KeyPrefix. The final S3 keyname is the S3KeyPrefix+
// the basename of the localPath. | [
"UploadLocalFileToS3",
"takes",
"a",
"local",
"path",
"and",
"uploads",
"the",
"content",
"at",
"localPath",
"to",
"the",
"given",
"S3Bucket",
"and",
"KeyPrefix",
".",
"The",
"final",
"S3",
"keyname",
"is",
"the",
"S3KeyPrefix",
"+",
"the",
"basename",
"of",
"the",
"localPath",
"."
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/s3/util.go#L59-L120 |
1,279 | mweagle/Sparta | aws/s3/util.go | BucketVersioningEnabled | func BucketVersioningEnabled(awsSession *session.Session,
S3Bucket string,
logger *logrus.Logger) (bool, error) {
s3Svc := s3.New(awsSession)
params := &s3.GetBucketVersioningInput{
Bucket: aws.String(S3Bucket), // Required
}
versioningEnabled := false
resp, err := s3Svc.GetBucketVersioning(params)
if err == nil && resp != nil && resp.Status != nil {
// What's the versioning policy?
logger.WithFields(logrus.Fields{
"VersionPolicy": *resp,
"BucketName": S3Bucket,
}).Debug("Bucket version policy")
versioningEnabled = (strings.ToLower(*resp.Status) == "enabled")
}
return versioningEnabled, err
} | go | func BucketVersioningEnabled(awsSession *session.Session,
S3Bucket string,
logger *logrus.Logger) (bool, error) {
s3Svc := s3.New(awsSession)
params := &s3.GetBucketVersioningInput{
Bucket: aws.String(S3Bucket), // Required
}
versioningEnabled := false
resp, err := s3Svc.GetBucketVersioning(params)
if err == nil && resp != nil && resp.Status != nil {
// What's the versioning policy?
logger.WithFields(logrus.Fields{
"VersionPolicy": *resp,
"BucketName": S3Bucket,
}).Debug("Bucket version policy")
versioningEnabled = (strings.ToLower(*resp.Status) == "enabled")
}
return versioningEnabled, err
} | [
"func",
"BucketVersioningEnabled",
"(",
"awsSession",
"*",
"session",
".",
"Session",
",",
"S3Bucket",
"string",
",",
"logger",
"*",
"logrus",
".",
"Logger",
")",
"(",
"bool",
",",
"error",
")",
"{",
"s3Svc",
":=",
"s3",
".",
"New",
"(",
"awsSession",
")",
"\n",
"params",
":=",
"&",
"s3",
".",
"GetBucketVersioningInput",
"{",
"Bucket",
":",
"aws",
".",
"String",
"(",
"S3Bucket",
")",
",",
"// Required",
"}",
"\n",
"versioningEnabled",
":=",
"false",
"\n",
"resp",
",",
"err",
":=",
"s3Svc",
".",
"GetBucketVersioning",
"(",
"params",
")",
"\n",
"if",
"err",
"==",
"nil",
"&&",
"resp",
"!=",
"nil",
"&&",
"resp",
".",
"Status",
"!=",
"nil",
"{",
"// What's the versioning policy?",
"logger",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"*",
"resp",
",",
"\"",
"\"",
":",
"S3Bucket",
",",
"}",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"versioningEnabled",
"=",
"(",
"strings",
".",
"ToLower",
"(",
"*",
"resp",
".",
"Status",
")",
"==",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"versioningEnabled",
",",
"err",
"\n",
"}"
] | // BucketVersioningEnabled determines if a given S3 bucket has object
// versioning enabled. | [
"BucketVersioningEnabled",
"determines",
"if",
"a",
"given",
"S3",
"bucket",
"has",
"object",
"versioning",
"enabled",
"."
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/s3/util.go#L124-L143 |
1,280 | mweagle/Sparta | aws/s3/util.go | BucketRegion | func BucketRegion(awsSession *session.Session,
S3Bucket string,
logger *logrus.Logger) (string, error) {
regionHint := ""
if awsSession.Config.Region != nil {
regionHint = *awsSession.Config.Region
}
awsContext := aws.BackgroundContext()
return s3manager.GetBucketRegion(awsContext,
awsSession,
S3Bucket,
regionHint)
} | go | func BucketRegion(awsSession *session.Session,
S3Bucket string,
logger *logrus.Logger) (string, error) {
regionHint := ""
if awsSession.Config.Region != nil {
regionHint = *awsSession.Config.Region
}
awsContext := aws.BackgroundContext()
return s3manager.GetBucketRegion(awsContext,
awsSession,
S3Bucket,
regionHint)
} | [
"func",
"BucketRegion",
"(",
"awsSession",
"*",
"session",
".",
"Session",
",",
"S3Bucket",
"string",
",",
"logger",
"*",
"logrus",
".",
"Logger",
")",
"(",
"string",
",",
"error",
")",
"{",
"regionHint",
":=",
"\"",
"\"",
"\n",
"if",
"awsSession",
".",
"Config",
".",
"Region",
"!=",
"nil",
"{",
"regionHint",
"=",
"*",
"awsSession",
".",
"Config",
".",
"Region",
"\n",
"}",
"\n",
"awsContext",
":=",
"aws",
".",
"BackgroundContext",
"(",
")",
"\n",
"return",
"s3manager",
".",
"GetBucketRegion",
"(",
"awsContext",
",",
"awsSession",
",",
"S3Bucket",
",",
"regionHint",
")",
"\n",
"}"
] | // BucketRegion returns the AWS region that hosts the bucket | [
"BucketRegion",
"returns",
"the",
"AWS",
"region",
"that",
"hosts",
"the",
"bucket"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/s3/util.go#L146-L158 |
1,281 | mweagle/Sparta | aws/step/sagemaker.go | NewSageMakerTrainingJob | func NewSageMakerTrainingJob(stateName string,
parameters SageMakerTrainingJobParameters) *SageMakerTrainingJob {
smtj := &SageMakerTrainingJob{
BaseTask: BaseTask{
baseInnerState: baseInnerState{
name: stateName,
id: rand.Int63(),
},
},
parameters: parameters,
}
return smtj
} | go | func NewSageMakerTrainingJob(stateName string,
parameters SageMakerTrainingJobParameters) *SageMakerTrainingJob {
smtj := &SageMakerTrainingJob{
BaseTask: BaseTask{
baseInnerState: baseInnerState{
name: stateName,
id: rand.Int63(),
},
},
parameters: parameters,
}
return smtj
} | [
"func",
"NewSageMakerTrainingJob",
"(",
"stateName",
"string",
",",
"parameters",
"SageMakerTrainingJobParameters",
")",
"*",
"SageMakerTrainingJob",
"{",
"smtj",
":=",
"&",
"SageMakerTrainingJob",
"{",
"BaseTask",
":",
"BaseTask",
"{",
"baseInnerState",
":",
"baseInnerState",
"{",
"name",
":",
"stateName",
",",
"id",
":",
"rand",
".",
"Int63",
"(",
")",
",",
"}",
",",
"}",
",",
"parameters",
":",
"parameters",
",",
"}",
"\n",
"return",
"smtj",
"\n",
"}"
] | // NewSageMakerTrainingJob returns an initialized SQSTaskState | [
"NewSageMakerTrainingJob",
"returns",
"an",
"initialized",
"SQSTaskState"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/sagemaker.go#L56-L68 |
1,282 | mweagle/Sparta | aws/step/sagemaker.go | NewSageMakerTransformJob | func NewSageMakerTransformJob(stateName string,
parameters SageMakerTransformJobParameters) *SageMakerTransformJob {
sns := &SageMakerTransformJob{
BaseTask: BaseTask{
baseInnerState: baseInnerState{
name: stateName,
id: rand.Int63(),
},
},
parameters: parameters,
}
return sns
} | go | func NewSageMakerTransformJob(stateName string,
parameters SageMakerTransformJobParameters) *SageMakerTransformJob {
sns := &SageMakerTransformJob{
BaseTask: BaseTask{
baseInnerState: baseInnerState{
name: stateName,
id: rand.Int63(),
},
},
parameters: parameters,
}
return sns
} | [
"func",
"NewSageMakerTransformJob",
"(",
"stateName",
"string",
",",
"parameters",
"SageMakerTransformJobParameters",
")",
"*",
"SageMakerTransformJob",
"{",
"sns",
":=",
"&",
"SageMakerTransformJob",
"{",
"BaseTask",
":",
"BaseTask",
"{",
"baseInnerState",
":",
"baseInnerState",
"{",
"name",
":",
"stateName",
",",
"id",
":",
"rand",
".",
"Int63",
"(",
")",
",",
"}",
",",
"}",
",",
"parameters",
":",
"parameters",
",",
"}",
"\n",
"return",
"sns",
"\n",
"}"
] | // NewSageMakerTransformJob returns an initialized SQSTaskState | [
"NewSageMakerTransformJob",
"returns",
"an",
"initialized",
"SQSTaskState"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/sagemaker.go#L110-L122 |
1,283 | mweagle/Sparta | decorator/safe_deploy.go | codeDeployLambdaUpdateDecorator | func codeDeployLambdaUpdateDecorator(updateType string,
codeDeployApplicationName string,
codeDeployRoleName string) sparta.TemplateDecorator {
return func(serviceName string,
lambdaResourceName string,
lambdaResource gocf.LambdaFunction,
resourceMetadata map[string]interface{},
S3Bucket string,
S3Key string,
buildID string,
template *gocf.Template,
context map[string]interface{},
logger *logrus.Logger) error {
safeDeployResourceName := func(resType string) string {
return sparta.CloudFormationResourceName(serviceName,
lambdaResourceName,
resType)
}
// Create the AWS::Lambda::Version, with DeletionPolicy=Retain
versionResourceName := safeDeployResourceName("version" + buildID)
versionResource := &gocf.LambdaVersion{
FunctionName: gocf.Ref(lambdaResourceName).String(),
}
entry := template.AddResource(versionResourceName, versionResource)
entry.DeletionPolicy = "Retain"
// Create the AWS::CodeDeploy::DeploymentGroup entry that includes a reference
// to the IAM role
codeDeploymentGroupResourceName := safeDeployResourceName("deploymentGroup")
codeDeploymentGroup := &gocf.CodeDeployDeploymentGroup{
ApplicationName: gocf.Ref(codeDeployApplicationName).String(),
AutoRollbackConfiguration: &gocf.CodeDeployDeploymentGroupAutoRollbackConfiguration{
Enabled: gocf.Bool(true),
Events: gocf.StringList(gocf.String("DEPLOYMENT_FAILURE"),
gocf.String("DEPLOYMENT_STOP_ON_ALARM"),
gocf.String("DEPLOYMENT_STOP_ON_REQUEST")),
},
ServiceRoleArn: gocf.GetAtt(codeDeployRoleName, "Arn"),
DeploymentConfigName: gocf.String(fmt.Sprintf("CodeDeployDefault.Lambda%s", updateType)),
DeploymentStyle: &gocf.CodeDeployDeploymentGroupDeploymentStyle{
DeploymentType: gocf.String("BLUE_GREEN"),
DeploymentOption: gocf.String("WITH_TRAFFIC_CONTROL"),
},
}
template.AddResource(codeDeploymentGroupResourceName, codeDeploymentGroup)
// Create the Alias entry...
aliasResourceName := safeDeployResourceName("alias")
aliasResource := &gocf.LambdaAlias{
FunctionVersion: gocf.GetAtt(versionResourceName, "Version").String(),
FunctionName: gocf.Ref(lambdaResourceName).String(),
Name: gocf.String("live"),
}
aliasEntry := template.AddResource(aliasResourceName, aliasResource)
aliasEntry.UpdatePolicy = &gocf.UpdatePolicy{
CodeDeployLambdaAliasUpdate: &gocf.UpdatePolicyCodeDeployLambdaAliasUpdate{
ApplicationName: gocf.Ref(codeDeployApplicationName).String(),
DeploymentGroupName: gocf.Ref(codeDeploymentGroupResourceName).String(),
},
}
return nil
}
} | go | func codeDeployLambdaUpdateDecorator(updateType string,
codeDeployApplicationName string,
codeDeployRoleName string) sparta.TemplateDecorator {
return func(serviceName string,
lambdaResourceName string,
lambdaResource gocf.LambdaFunction,
resourceMetadata map[string]interface{},
S3Bucket string,
S3Key string,
buildID string,
template *gocf.Template,
context map[string]interface{},
logger *logrus.Logger) error {
safeDeployResourceName := func(resType string) string {
return sparta.CloudFormationResourceName(serviceName,
lambdaResourceName,
resType)
}
// Create the AWS::Lambda::Version, with DeletionPolicy=Retain
versionResourceName := safeDeployResourceName("version" + buildID)
versionResource := &gocf.LambdaVersion{
FunctionName: gocf.Ref(lambdaResourceName).String(),
}
entry := template.AddResource(versionResourceName, versionResource)
entry.DeletionPolicy = "Retain"
// Create the AWS::CodeDeploy::DeploymentGroup entry that includes a reference
// to the IAM role
codeDeploymentGroupResourceName := safeDeployResourceName("deploymentGroup")
codeDeploymentGroup := &gocf.CodeDeployDeploymentGroup{
ApplicationName: gocf.Ref(codeDeployApplicationName).String(),
AutoRollbackConfiguration: &gocf.CodeDeployDeploymentGroupAutoRollbackConfiguration{
Enabled: gocf.Bool(true),
Events: gocf.StringList(gocf.String("DEPLOYMENT_FAILURE"),
gocf.String("DEPLOYMENT_STOP_ON_ALARM"),
gocf.String("DEPLOYMENT_STOP_ON_REQUEST")),
},
ServiceRoleArn: gocf.GetAtt(codeDeployRoleName, "Arn"),
DeploymentConfigName: gocf.String(fmt.Sprintf("CodeDeployDefault.Lambda%s", updateType)),
DeploymentStyle: &gocf.CodeDeployDeploymentGroupDeploymentStyle{
DeploymentType: gocf.String("BLUE_GREEN"),
DeploymentOption: gocf.String("WITH_TRAFFIC_CONTROL"),
},
}
template.AddResource(codeDeploymentGroupResourceName, codeDeploymentGroup)
// Create the Alias entry...
aliasResourceName := safeDeployResourceName("alias")
aliasResource := &gocf.LambdaAlias{
FunctionVersion: gocf.GetAtt(versionResourceName, "Version").String(),
FunctionName: gocf.Ref(lambdaResourceName).String(),
Name: gocf.String("live"),
}
aliasEntry := template.AddResource(aliasResourceName, aliasResource)
aliasEntry.UpdatePolicy = &gocf.UpdatePolicy{
CodeDeployLambdaAliasUpdate: &gocf.UpdatePolicyCodeDeployLambdaAliasUpdate{
ApplicationName: gocf.Ref(codeDeployApplicationName).String(),
DeploymentGroupName: gocf.Ref(codeDeploymentGroupResourceName).String(),
},
}
return nil
}
} | [
"func",
"codeDeployLambdaUpdateDecorator",
"(",
"updateType",
"string",
",",
"codeDeployApplicationName",
"string",
",",
"codeDeployRoleName",
"string",
")",
"sparta",
".",
"TemplateDecorator",
"{",
"return",
"func",
"(",
"serviceName",
"string",
",",
"lambdaResourceName",
"string",
",",
"lambdaResource",
"gocf",
".",
"LambdaFunction",
",",
"resourceMetadata",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"S3Bucket",
"string",
",",
"S3Key",
"string",
",",
"buildID",
"string",
",",
"template",
"*",
"gocf",
".",
"Template",
",",
"context",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"logger",
"*",
"logrus",
".",
"Logger",
")",
"error",
"{",
"safeDeployResourceName",
":=",
"func",
"(",
"resType",
"string",
")",
"string",
"{",
"return",
"sparta",
".",
"CloudFormationResourceName",
"(",
"serviceName",
",",
"lambdaResourceName",
",",
"resType",
")",
"\n",
"}",
"\n",
"// Create the AWS::Lambda::Version, with DeletionPolicy=Retain",
"versionResourceName",
":=",
"safeDeployResourceName",
"(",
"\"",
"\"",
"+",
"buildID",
")",
"\n",
"versionResource",
":=",
"&",
"gocf",
".",
"LambdaVersion",
"{",
"FunctionName",
":",
"gocf",
".",
"Ref",
"(",
"lambdaResourceName",
")",
".",
"String",
"(",
")",
",",
"}",
"\n",
"entry",
":=",
"template",
".",
"AddResource",
"(",
"versionResourceName",
",",
"versionResource",
")",
"\n",
"entry",
".",
"DeletionPolicy",
"=",
"\"",
"\"",
"\n\n",
"// Create the AWS::CodeDeploy::DeploymentGroup entry that includes a reference",
"// to the IAM role",
"codeDeploymentGroupResourceName",
":=",
"safeDeployResourceName",
"(",
"\"",
"\"",
")",
"\n",
"codeDeploymentGroup",
":=",
"&",
"gocf",
".",
"CodeDeployDeploymentGroup",
"{",
"ApplicationName",
":",
"gocf",
".",
"Ref",
"(",
"codeDeployApplicationName",
")",
".",
"String",
"(",
")",
",",
"AutoRollbackConfiguration",
":",
"&",
"gocf",
".",
"CodeDeployDeploymentGroupAutoRollbackConfiguration",
"{",
"Enabled",
":",
"gocf",
".",
"Bool",
"(",
"true",
")",
",",
"Events",
":",
"gocf",
".",
"StringList",
"(",
"gocf",
".",
"String",
"(",
"\"",
"\"",
")",
",",
"gocf",
".",
"String",
"(",
"\"",
"\"",
")",
",",
"gocf",
".",
"String",
"(",
"\"",
"\"",
")",
")",
",",
"}",
",",
"ServiceRoleArn",
":",
"gocf",
".",
"GetAtt",
"(",
"codeDeployRoleName",
",",
"\"",
"\"",
")",
",",
"DeploymentConfigName",
":",
"gocf",
".",
"String",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"updateType",
")",
")",
",",
"DeploymentStyle",
":",
"&",
"gocf",
".",
"CodeDeployDeploymentGroupDeploymentStyle",
"{",
"DeploymentType",
":",
"gocf",
".",
"String",
"(",
"\"",
"\"",
")",
",",
"DeploymentOption",
":",
"gocf",
".",
"String",
"(",
"\"",
"\"",
")",
",",
"}",
",",
"}",
"\n",
"template",
".",
"AddResource",
"(",
"codeDeploymentGroupResourceName",
",",
"codeDeploymentGroup",
")",
"\n",
"// Create the Alias entry...",
"aliasResourceName",
":=",
"safeDeployResourceName",
"(",
"\"",
"\"",
")",
"\n",
"aliasResource",
":=",
"&",
"gocf",
".",
"LambdaAlias",
"{",
"FunctionVersion",
":",
"gocf",
".",
"GetAtt",
"(",
"versionResourceName",
",",
"\"",
"\"",
")",
".",
"String",
"(",
")",
",",
"FunctionName",
":",
"gocf",
".",
"Ref",
"(",
"lambdaResourceName",
")",
".",
"String",
"(",
")",
",",
"Name",
":",
"gocf",
".",
"String",
"(",
"\"",
"\"",
")",
",",
"}",
"\n",
"aliasEntry",
":=",
"template",
".",
"AddResource",
"(",
"aliasResourceName",
",",
"aliasResource",
")",
"\n",
"aliasEntry",
".",
"UpdatePolicy",
"=",
"&",
"gocf",
".",
"UpdatePolicy",
"{",
"CodeDeployLambdaAliasUpdate",
":",
"&",
"gocf",
".",
"UpdatePolicyCodeDeployLambdaAliasUpdate",
"{",
"ApplicationName",
":",
"gocf",
".",
"Ref",
"(",
"codeDeployApplicationName",
")",
".",
"String",
"(",
")",
",",
"DeploymentGroupName",
":",
"gocf",
".",
"Ref",
"(",
"codeDeploymentGroupResourceName",
")",
".",
"String",
"(",
")",
",",
"}",
",",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // codeDeployLambdaUpdateDecorator is the per-function decorator
// that adds the necessary information for CodeDeploy | [
"codeDeployLambdaUpdateDecorator",
"is",
"the",
"per",
"-",
"function",
"decorator",
"that",
"adds",
"the",
"necessary",
"information",
"for",
"CodeDeploy"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/decorator/safe_deploy.go#L14-L76 |
1,284 | mweagle/Sparta | aws/step/glue.go | NewGlueState | func NewGlueState(stateName string,
parameters GlueParameters) *GlueState {
sns := &GlueState{
BaseTask: BaseTask{
baseInnerState: baseInnerState{
name: stateName,
id: rand.Int63(),
},
},
parameters: parameters,
}
return sns
} | go | func NewGlueState(stateName string,
parameters GlueParameters) *GlueState {
sns := &GlueState{
BaseTask: BaseTask{
baseInnerState: baseInnerState{
name: stateName,
id: rand.Int63(),
},
},
parameters: parameters,
}
return sns
} | [
"func",
"NewGlueState",
"(",
"stateName",
"string",
",",
"parameters",
"GlueParameters",
")",
"*",
"GlueState",
"{",
"sns",
":=",
"&",
"GlueState",
"{",
"BaseTask",
":",
"BaseTask",
"{",
"baseInnerState",
":",
"baseInnerState",
"{",
"name",
":",
"stateName",
",",
"id",
":",
"rand",
".",
"Int63",
"(",
")",
",",
"}",
",",
"}",
",",
"parameters",
":",
"parameters",
",",
"}",
"\n",
"return",
"sns",
"\n",
"}"
] | // NewGlueState returns an initialized GlueState | [
"NewGlueState",
"returns",
"an",
"initialized",
"GlueState"
] | a646ce10a6728e988448dc3f6f79cd3322854c61 | https://github.com/mweagle/Sparta/blob/a646ce10a6728e988448dc3f6f79cd3322854c61/aws/step/glue.go#L37-L50 |
1,285 | mwitkow/go-conntrack | listener_wrapper.go | TrackWithTcpKeepAlive | func TrackWithTcpKeepAlive(keepalive time.Duration) listenerOpt {
return func(opts *listenerOpts) {
opts.tcpKeepAlive = keepalive
}
} | go | func TrackWithTcpKeepAlive(keepalive time.Duration) listenerOpt {
return func(opts *listenerOpts) {
opts.tcpKeepAlive = keepalive
}
} | [
"func",
"TrackWithTcpKeepAlive",
"(",
"keepalive",
"time",
".",
"Duration",
")",
"listenerOpt",
"{",
"return",
"func",
"(",
"opts",
"*",
"listenerOpts",
")",
"{",
"opts",
".",
"tcpKeepAlive",
"=",
"keepalive",
"\n",
"}",
"\n",
"}"
] | // TrackWithTcpKeepAlive makes sure that any `net.TCPConn` that get accepted have a keep-alive.
// This is useful for HTTP servers in order for, for example laptops, to not use up resources on the
// server while they don't utilise their connection.
// A value of 0 disables it. | [
"TrackWithTcpKeepAlive",
"makes",
"sure",
"that",
"any",
"net",
".",
"TCPConn",
"that",
"get",
"accepted",
"have",
"a",
"keep",
"-",
"alive",
".",
"This",
"is",
"useful",
"for",
"HTTP",
"servers",
"in",
"order",
"for",
"for",
"example",
"laptops",
"to",
"not",
"use",
"up",
"resources",
"on",
"the",
"server",
"while",
"they",
"don",
"t",
"utilise",
"their",
"connection",
".",
"A",
"value",
"of",
"0",
"disables",
"it",
"."
] | cc309e4a22231782e8893f3c35ced0967807a33e | https://github.com/mwitkow/go-conntrack/blob/cc309e4a22231782e8893f3c35ced0967807a33e/listener_wrapper.go#L54-L58 |
1,286 | mwitkow/go-conntrack | listener_wrapper.go | NewListener | func NewListener(inner net.Listener, optFuncs ...listenerOpt) net.Listener {
opts := &listenerOpts{
name: defaultName,
monitoring: true,
tracing: false,
}
for _, f := range optFuncs {
f(opts)
}
if opts.monitoring {
preRegisterListenerMetrics(opts.name)
}
return &connTrackListener{
Listener: inner,
opts: opts,
}
} | go | func NewListener(inner net.Listener, optFuncs ...listenerOpt) net.Listener {
opts := &listenerOpts{
name: defaultName,
monitoring: true,
tracing: false,
}
for _, f := range optFuncs {
f(opts)
}
if opts.monitoring {
preRegisterListenerMetrics(opts.name)
}
return &connTrackListener{
Listener: inner,
opts: opts,
}
} | [
"func",
"NewListener",
"(",
"inner",
"net",
".",
"Listener",
",",
"optFuncs",
"...",
"listenerOpt",
")",
"net",
".",
"Listener",
"{",
"opts",
":=",
"&",
"listenerOpts",
"{",
"name",
":",
"defaultName",
",",
"monitoring",
":",
"true",
",",
"tracing",
":",
"false",
",",
"}",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"optFuncs",
"{",
"f",
"(",
"opts",
")",
"\n",
"}",
"\n",
"if",
"opts",
".",
"monitoring",
"{",
"preRegisterListenerMetrics",
"(",
"opts",
".",
"name",
")",
"\n",
"}",
"\n",
"return",
"&",
"connTrackListener",
"{",
"Listener",
":",
"inner",
",",
"opts",
":",
"opts",
",",
"}",
"\n",
"}"
] | // NewListener returns the given listener wrapped in connection tracking listener. | [
"NewListener",
"returns",
"the",
"given",
"listener",
"wrapped",
"in",
"connection",
"tracking",
"listener",
"."
] | cc309e4a22231782e8893f3c35ced0967807a33e | https://github.com/mwitkow/go-conntrack/blob/cc309e4a22231782e8893f3c35ced0967807a33e/listener_wrapper.go#L66-L82 |
1,287 | mwitkow/go-conntrack | connhelpers/tls.go | TlsConfigWithHttp2Enabled | func TlsConfigWithHttp2Enabled(config *tls.Config) (*tls.Config, error) {
// mostly based on http2 code in the standards library.
if config.CipherSuites != nil {
// If they already provided a CipherSuite list, return
// an error if it has a bad order or is missing
// ECDHE_RSA_WITH_AES_128_GCM_SHA256.
const requiredCipher = tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
haveRequired := false
for _, cs := range config.CipherSuites {
if cs == requiredCipher {
haveRequired = true
}
}
if !haveRequired {
return nil, fmt.Errorf("http2: TLSConfig.CipherSuites is missing HTTP/2-required TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256")
}
}
config.PreferServerCipherSuites = true
haveNPN := false
for _, p := range config.NextProtos {
if p == "h2" {
haveNPN = true
break
}
}
if !haveNPN {
config.NextProtos = append(config.NextProtos, "h2")
}
config.NextProtos = append(config.NextProtos, "h2-14")
// make sure http 1.1 is *after* all of the other ones.
config.NextProtos = append(config.NextProtos, "http/1.1")
return config, nil
} | go | func TlsConfigWithHttp2Enabled(config *tls.Config) (*tls.Config, error) {
// mostly based on http2 code in the standards library.
if config.CipherSuites != nil {
// If they already provided a CipherSuite list, return
// an error if it has a bad order or is missing
// ECDHE_RSA_WITH_AES_128_GCM_SHA256.
const requiredCipher = tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
haveRequired := false
for _, cs := range config.CipherSuites {
if cs == requiredCipher {
haveRequired = true
}
}
if !haveRequired {
return nil, fmt.Errorf("http2: TLSConfig.CipherSuites is missing HTTP/2-required TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256")
}
}
config.PreferServerCipherSuites = true
haveNPN := false
for _, p := range config.NextProtos {
if p == "h2" {
haveNPN = true
break
}
}
if !haveNPN {
config.NextProtos = append(config.NextProtos, "h2")
}
config.NextProtos = append(config.NextProtos, "h2-14")
// make sure http 1.1 is *after* all of the other ones.
config.NextProtos = append(config.NextProtos, "http/1.1")
return config, nil
} | [
"func",
"TlsConfigWithHttp2Enabled",
"(",
"config",
"*",
"tls",
".",
"Config",
")",
"(",
"*",
"tls",
".",
"Config",
",",
"error",
")",
"{",
"// mostly based on http2 code in the standards library.",
"if",
"config",
".",
"CipherSuites",
"!=",
"nil",
"{",
"// If they already provided a CipherSuite list, return",
"// an error if it has a bad order or is missing",
"// ECDHE_RSA_WITH_AES_128_GCM_SHA256.",
"const",
"requiredCipher",
"=",
"tls",
".",
"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
"\n",
"haveRequired",
":=",
"false",
"\n",
"for",
"_",
",",
"cs",
":=",
"range",
"config",
".",
"CipherSuites",
"{",
"if",
"cs",
"==",
"requiredCipher",
"{",
"haveRequired",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"haveRequired",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"config",
".",
"PreferServerCipherSuites",
"=",
"true",
"\n\n",
"haveNPN",
":=",
"false",
"\n",
"for",
"_",
",",
"p",
":=",
"range",
"config",
".",
"NextProtos",
"{",
"if",
"p",
"==",
"\"",
"\"",
"{",
"haveNPN",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"haveNPN",
"{",
"config",
".",
"NextProtos",
"=",
"append",
"(",
"config",
".",
"NextProtos",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"config",
".",
"NextProtos",
"=",
"append",
"(",
"config",
".",
"NextProtos",
",",
"\"",
"\"",
")",
"\n",
"// make sure http 1.1 is *after* all of the other ones.",
"config",
".",
"NextProtos",
"=",
"append",
"(",
"config",
".",
"NextProtos",
",",
"\"",
"\"",
")",
"\n",
"return",
"config",
",",
"nil",
"\n",
"}"
] | // TlsConfigWithHttp2Enabled makes it easy to configure the given `tls.Config` to prefer H2 connections.
// This is useful if you can't use `http.ListenAndServerTLS` when using a custom `net.Listener`. | [
"TlsConfigWithHttp2Enabled",
"makes",
"it",
"easy",
"to",
"configure",
"the",
"given",
"tls",
".",
"Config",
"to",
"prefer",
"H2",
"connections",
".",
"This",
"is",
"useful",
"if",
"you",
"can",
"t",
"use",
"http",
".",
"ListenAndServerTLS",
"when",
"using",
"a",
"custom",
"net",
".",
"Listener",
"."
] | cc309e4a22231782e8893f3c35ced0967807a33e | https://github.com/mwitkow/go-conntrack/blob/cc309e4a22231782e8893f3c35ced0967807a33e/connhelpers/tls.go#L26-L60 |
1,288 | mwitkow/go-conntrack | dialer_reporter.go | PreRegisterDialerMetrics | func PreRegisterDialerMetrics(dialerName string) {
dialerAttemptedTotal.WithLabelValues(dialerName)
dialerConnEstablishedTotal.WithLabelValues(dialerName)
for _, reason := range []failureReason{failedTimeout, failedResolution, failedConnRefused, failedUnknown} {
dialerConnFailedTotal.WithLabelValues(dialerName, string(reason))
}
dialerConnClosedTotal.WithLabelValues(dialerName)
} | go | func PreRegisterDialerMetrics(dialerName string) {
dialerAttemptedTotal.WithLabelValues(dialerName)
dialerConnEstablishedTotal.WithLabelValues(dialerName)
for _, reason := range []failureReason{failedTimeout, failedResolution, failedConnRefused, failedUnknown} {
dialerConnFailedTotal.WithLabelValues(dialerName, string(reason))
}
dialerConnClosedTotal.WithLabelValues(dialerName)
} | [
"func",
"PreRegisterDialerMetrics",
"(",
"dialerName",
"string",
")",
"{",
"dialerAttemptedTotal",
".",
"WithLabelValues",
"(",
"dialerName",
")",
"\n",
"dialerConnEstablishedTotal",
".",
"WithLabelValues",
"(",
"dialerName",
")",
"\n",
"for",
"_",
",",
"reason",
":=",
"range",
"[",
"]",
"failureReason",
"{",
"failedTimeout",
",",
"failedResolution",
",",
"failedConnRefused",
",",
"failedUnknown",
"}",
"{",
"dialerConnFailedTotal",
".",
"WithLabelValues",
"(",
"dialerName",
",",
"string",
"(",
"reason",
")",
")",
"\n",
"}",
"\n",
"dialerConnClosedTotal",
".",
"WithLabelValues",
"(",
"dialerName",
")",
"\n",
"}"
] | // preRegisterDialerMetrics pre-populates Prometheus labels for the given dialer name, to avoid Prometheus missing labels issue. | [
"preRegisterDialerMetrics",
"pre",
"-",
"populates",
"Prometheus",
"labels",
"for",
"the",
"given",
"dialer",
"name",
"to",
"avoid",
"Prometheus",
"missing",
"labels",
"issue",
"."
] | cc309e4a22231782e8893f3c35ced0967807a33e | https://github.com/mwitkow/go-conntrack/blob/cc309e4a22231782e8893f3c35ced0967807a33e/dialer_reporter.go#L66-L73 |
1,289 | mwitkow/go-conntrack | dialer_wrapper.go | DialNameFromContext | func DialNameFromContext(ctx context.Context) string {
val, ok := ctx.Value(dialerNameKey).(string)
if !ok {
return ""
}
return val
} | go | func DialNameFromContext(ctx context.Context) string {
val, ok := ctx.Value(dialerNameKey).(string)
if !ok {
return ""
}
return val
} | [
"func",
"DialNameFromContext",
"(",
"ctx",
"context",
".",
"Context",
")",
"string",
"{",
"val",
",",
"ok",
":=",
"ctx",
".",
"Value",
"(",
"dialerNameKey",
")",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"val",
"\n",
"}"
] | // DialNameFromContext returns the name of the dialer from the context of the DialContext func, if any. | [
"DialNameFromContext",
"returns",
"the",
"name",
"of",
"the",
"dialer",
"from",
"the",
"context",
"of",
"the",
"DialContext",
"func",
"if",
"any",
"."
] | cc309e4a22231782e8893f3c35ced0967807a33e | https://github.com/mwitkow/go-conntrack/blob/cc309e4a22231782e8893f3c35ced0967807a33e/dialer_wrapper.go#L66-L72 |
1,290 | mwitkow/go-conntrack | dialer_wrapper.go | DialNameToContext | func DialNameToContext(ctx context.Context, dialerName string) context.Context {
return context.WithValue(ctx, dialerNameKey, dialerName)
} | go | func DialNameToContext(ctx context.Context, dialerName string) context.Context {
return context.WithValue(ctx, dialerNameKey, dialerName)
} | [
"func",
"DialNameToContext",
"(",
"ctx",
"context",
".",
"Context",
",",
"dialerName",
"string",
")",
"context",
".",
"Context",
"{",
"return",
"context",
".",
"WithValue",
"(",
"ctx",
",",
"dialerNameKey",
",",
"dialerName",
")",
"\n",
"}"
] | // DialNameToContext returns a context that will contain a dialer name override. | [
"DialNameToContext",
"returns",
"a",
"context",
"that",
"will",
"contain",
"a",
"dialer",
"name",
"override",
"."
] | cc309e4a22231782e8893f3c35ced0967807a33e | https://github.com/mwitkow/go-conntrack/blob/cc309e4a22231782e8893f3c35ced0967807a33e/dialer_wrapper.go#L75-L77 |
1,291 | mwitkow/go-conntrack | dialer_wrapper.go | NewDialContextFunc | func NewDialContextFunc(optFuncs ...dialerOpt) func(context.Context, string, string) (net.Conn, error) {
opts := &dialerOpts{name: defaultName, monitoring: true, parentDialContextFunc: (&net.Dialer{}).DialContext}
for _, f := range optFuncs {
f(opts)
}
if opts.monitoring {
PreRegisterDialerMetrics(opts.name)
}
return func(ctx context.Context, network string, addr string) (net.Conn, error) {
name := opts.name
if ctxName := DialNameFromContext(ctx); ctxName != "" {
name = ctxName
}
return dialClientConnTracker(ctx, network, addr, name, opts)
}
} | go | func NewDialContextFunc(optFuncs ...dialerOpt) func(context.Context, string, string) (net.Conn, error) {
opts := &dialerOpts{name: defaultName, monitoring: true, parentDialContextFunc: (&net.Dialer{}).DialContext}
for _, f := range optFuncs {
f(opts)
}
if opts.monitoring {
PreRegisterDialerMetrics(opts.name)
}
return func(ctx context.Context, network string, addr string) (net.Conn, error) {
name := opts.name
if ctxName := DialNameFromContext(ctx); ctxName != "" {
name = ctxName
}
return dialClientConnTracker(ctx, network, addr, name, opts)
}
} | [
"func",
"NewDialContextFunc",
"(",
"optFuncs",
"...",
"dialerOpt",
")",
"func",
"(",
"context",
".",
"Context",
",",
"string",
",",
"string",
")",
"(",
"net",
".",
"Conn",
",",
"error",
")",
"{",
"opts",
":=",
"&",
"dialerOpts",
"{",
"name",
":",
"defaultName",
",",
"monitoring",
":",
"true",
",",
"parentDialContextFunc",
":",
"(",
"&",
"net",
".",
"Dialer",
"{",
"}",
")",
".",
"DialContext",
"}",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"optFuncs",
"{",
"f",
"(",
"opts",
")",
"\n",
"}",
"\n",
"if",
"opts",
".",
"monitoring",
"{",
"PreRegisterDialerMetrics",
"(",
"opts",
".",
"name",
")",
"\n",
"}",
"\n",
"return",
"func",
"(",
"ctx",
"context",
".",
"Context",
",",
"network",
"string",
",",
"addr",
"string",
")",
"(",
"net",
".",
"Conn",
",",
"error",
")",
"{",
"name",
":=",
"opts",
".",
"name",
"\n",
"if",
"ctxName",
":=",
"DialNameFromContext",
"(",
"ctx",
")",
";",
"ctxName",
"!=",
"\"",
"\"",
"{",
"name",
"=",
"ctxName",
"\n",
"}",
"\n",
"return",
"dialClientConnTracker",
"(",
"ctx",
",",
"network",
",",
"addr",
",",
"name",
",",
"opts",
")",
"\n",
"}",
"\n",
"}"
] | // NewDialContextFunc returns a `DialContext` function that tracks outbound connections.
// The signature is compatible with `http.Tranport.DialContext` and is meant to be used there. | [
"NewDialContextFunc",
"returns",
"a",
"DialContext",
"function",
"that",
"tracks",
"outbound",
"connections",
".",
"The",
"signature",
"is",
"compatible",
"with",
"http",
".",
"Tranport",
".",
"DialContext",
"and",
"is",
"meant",
"to",
"be",
"used",
"there",
"."
] | cc309e4a22231782e8893f3c35ced0967807a33e | https://github.com/mwitkow/go-conntrack/blob/cc309e4a22231782e8893f3c35ced0967807a33e/dialer_wrapper.go#L81-L96 |
1,292 | mwitkow/go-conntrack | dialer_wrapper.go | NewDialFunc | func NewDialFunc(optFuncs ...dialerOpt) func(string, string) (net.Conn, error) {
dialContextFunc := NewDialContextFunc(optFuncs...)
return func(network string, addr string) (net.Conn, error) {
return dialContextFunc(context.TODO(), network, addr)
}
} | go | func NewDialFunc(optFuncs ...dialerOpt) func(string, string) (net.Conn, error) {
dialContextFunc := NewDialContextFunc(optFuncs...)
return func(network string, addr string) (net.Conn, error) {
return dialContextFunc(context.TODO(), network, addr)
}
} | [
"func",
"NewDialFunc",
"(",
"optFuncs",
"...",
"dialerOpt",
")",
"func",
"(",
"string",
",",
"string",
")",
"(",
"net",
".",
"Conn",
",",
"error",
")",
"{",
"dialContextFunc",
":=",
"NewDialContextFunc",
"(",
"optFuncs",
"...",
")",
"\n",
"return",
"func",
"(",
"network",
"string",
",",
"addr",
"string",
")",
"(",
"net",
".",
"Conn",
",",
"error",
")",
"{",
"return",
"dialContextFunc",
"(",
"context",
".",
"TODO",
"(",
")",
",",
"network",
",",
"addr",
")",
"\n",
"}",
"\n",
"}"
] | // NewDialFunc returns a `Dial` function that tracks outbound connections.
// The signature is compatible with `http.Tranport.Dial` and is meant to be used there for Go < 1.7. | [
"NewDialFunc",
"returns",
"a",
"Dial",
"function",
"that",
"tracks",
"outbound",
"connections",
".",
"The",
"signature",
"is",
"compatible",
"with",
"http",
".",
"Tranport",
".",
"Dial",
"and",
"is",
"meant",
"to",
"be",
"used",
"there",
"for",
"Go",
"<",
"1",
".",
"7",
"."
] | cc309e4a22231782e8893f3c35ced0967807a33e | https://github.com/mwitkow/go-conntrack/blob/cc309e4a22231782e8893f3c35ced0967807a33e/dialer_wrapper.go#L100-L105 |
1,293 | lox/httpcache | cache.go | NewVFSCache | func NewVFSCache(fs vfs.VFS) Cache {
return &cache{fs: fs, stale: map[string]time.Time{}}
} | go | func NewVFSCache(fs vfs.VFS) Cache {
return &cache{fs: fs, stale: map[string]time.Time{}}
} | [
"func",
"NewVFSCache",
"(",
"fs",
"vfs",
".",
"VFS",
")",
"Cache",
"{",
"return",
"&",
"cache",
"{",
"fs",
":",
"fs",
",",
"stale",
":",
"map",
"[",
"string",
"]",
"time",
".",
"Time",
"{",
"}",
"}",
"\n",
"}"
] | // NewCache returns a cache backend off the provided VFS | [
"NewCache",
"returns",
"a",
"cache",
"backend",
"off",
"the",
"provided",
"VFS"
] | 2de7d84cb2513697e071961c5a5a81060c4382b5 | https://github.com/lox/httpcache/blob/2de7d84cb2513697e071961c5a5a81060c4382b5/cache.go#L53-L55 |
1,294 | lox/httpcache | cache.go | NewDiskCache | func NewDiskCache(dir string) (Cache, error) {
if err := os.MkdirAll(dir, 0777); err != nil {
return nil, err
}
fs, err := vfs.FS(dir)
if err != nil {
return nil, err
}
chfs, err := vfs.Chroot("/", fs)
if err != nil {
return nil, err
}
return NewVFSCache(chfs), nil
} | go | func NewDiskCache(dir string) (Cache, error) {
if err := os.MkdirAll(dir, 0777); err != nil {
return nil, err
}
fs, err := vfs.FS(dir)
if err != nil {
return nil, err
}
chfs, err := vfs.Chroot("/", fs)
if err != nil {
return nil, err
}
return NewVFSCache(chfs), nil
} | [
"func",
"NewDiskCache",
"(",
"dir",
"string",
")",
"(",
"Cache",
",",
"error",
")",
"{",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"dir",
",",
"0777",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"fs",
",",
"err",
":=",
"vfs",
".",
"FS",
"(",
"dir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"chfs",
",",
"err",
":=",
"vfs",
".",
"Chroot",
"(",
"\"",
"\"",
",",
"fs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"NewVFSCache",
"(",
"chfs",
")",
",",
"nil",
"\n",
"}"
] | // NewDiskCache returns a disk-backed cache | [
"NewDiskCache",
"returns",
"a",
"disk",
"-",
"backed",
"cache"
] | 2de7d84cb2513697e071961c5a5a81060c4382b5 | https://github.com/lox/httpcache/blob/2de7d84cb2513697e071961c5a5a81060c4382b5/cache.go#L63-L76 |
1,295 | lox/httpcache | cache.go | Header | func (c *cache) Header(key string) (Header, error) {
path := headerPrefix + formatPrefix + hashKey(key)
f, err := c.fs.Open(path)
if err != nil {
if vfs.IsNotExist(err) {
return Header{}, ErrNotFoundInCache
}
return Header{}, err
}
return readHeaders(bufio.NewReader(f))
} | go | func (c *cache) Header(key string) (Header, error) {
path := headerPrefix + formatPrefix + hashKey(key)
f, err := c.fs.Open(path)
if err != nil {
if vfs.IsNotExist(err) {
return Header{}, ErrNotFoundInCache
}
return Header{}, err
}
return readHeaders(bufio.NewReader(f))
} | [
"func",
"(",
"c",
"*",
"cache",
")",
"Header",
"(",
"key",
"string",
")",
"(",
"Header",
",",
"error",
")",
"{",
"path",
":=",
"headerPrefix",
"+",
"formatPrefix",
"+",
"hashKey",
"(",
"key",
")",
"\n",
"f",
",",
"err",
":=",
"c",
".",
"fs",
".",
"Open",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"vfs",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"Header",
"{",
"}",
",",
"ErrNotFoundInCache",
"\n",
"}",
"\n",
"return",
"Header",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"readHeaders",
"(",
"bufio",
".",
"NewReader",
"(",
"f",
")",
")",
"\n",
"}"
] | // Retrieve the Status and Headers for a given key path | [
"Retrieve",
"the",
"Status",
"and",
"Headers",
"for",
"a",
"given",
"key",
"path"
] | 2de7d84cb2513697e071961c5a5a81060c4382b5 | https://github.com/lox/httpcache/blob/2de7d84cb2513697e071961c5a5a81060c4382b5/cache.go#L94-L105 |
1,296 | lox/httpcache | cache.go | Store | func (c *cache) Store(res *Resource, keys ...string) error {
var buf = &bytes.Buffer{}
if length, err := strconv.ParseInt(res.Header().Get("Content-Length"), 10, 64); err == nil {
if _, err = io.CopyN(buf, res, length); err != nil {
return err
}
} else if _, err = io.Copy(buf, res); err != nil {
return err
}
for _, key := range keys {
delete(c.stale, key)
if err := c.storeBody(buf, key); err != nil {
return err
}
if err := c.storeHeader(res.Status(), res.Header(), key); err != nil {
return err
}
}
return nil
} | go | func (c *cache) Store(res *Resource, keys ...string) error {
var buf = &bytes.Buffer{}
if length, err := strconv.ParseInt(res.Header().Get("Content-Length"), 10, 64); err == nil {
if _, err = io.CopyN(buf, res, length); err != nil {
return err
}
} else if _, err = io.Copy(buf, res); err != nil {
return err
}
for _, key := range keys {
delete(c.stale, key)
if err := c.storeBody(buf, key); err != nil {
return err
}
if err := c.storeHeader(res.Status(), res.Header(), key); err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"c",
"*",
"cache",
")",
"Store",
"(",
"res",
"*",
"Resource",
",",
"keys",
"...",
"string",
")",
"error",
"{",
"var",
"buf",
"=",
"&",
"bytes",
".",
"Buffer",
"{",
"}",
"\n\n",
"if",
"length",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"res",
".",
"Header",
"(",
")",
".",
"Get",
"(",
"\"",
"\"",
")",
",",
"10",
",",
"64",
")",
";",
"err",
"==",
"nil",
"{",
"if",
"_",
",",
"err",
"=",
"io",
".",
"CopyN",
"(",
"buf",
",",
"res",
",",
"length",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"else",
"if",
"_",
",",
"err",
"=",
"io",
".",
"Copy",
"(",
"buf",
",",
"res",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"key",
":=",
"range",
"keys",
"{",
"delete",
"(",
"c",
".",
"stale",
",",
"key",
")",
"\n\n",
"if",
"err",
":=",
"c",
".",
"storeBody",
"(",
"buf",
",",
"key",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"c",
".",
"storeHeader",
"(",
"res",
".",
"Status",
"(",
")",
",",
"res",
".",
"Header",
"(",
")",
",",
"key",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Store a resource against a number of keys | [
"Store",
"a",
"resource",
"against",
"a",
"number",
"of",
"keys"
] | 2de7d84cb2513697e071961c5a5a81060c4382b5 | https://github.com/lox/httpcache/blob/2de7d84cb2513697e071961c5a5a81060c4382b5/cache.go#L108-L132 |
1,297 | lox/httpcache | cache.go | Retrieve | func (c *cache) Retrieve(key string) (*Resource, error) {
f, err := c.fs.Open(bodyPrefix + formatPrefix + hashKey(key))
if err != nil {
if vfs.IsNotExist(err) {
return nil, ErrNotFoundInCache
}
return nil, err
}
h, err := c.Header(key)
if err != nil {
if vfs.IsNotExist(err) {
return nil, ErrNotFoundInCache
}
return nil, err
}
res := NewResource(h.StatusCode, f, h.Header)
if staleTime, exists := c.stale[key]; exists {
if !res.DateAfter(staleTime) {
log.Printf("stale marker of %s found", staleTime)
res.MarkStale()
}
}
return res, nil
} | go | func (c *cache) Retrieve(key string) (*Resource, error) {
f, err := c.fs.Open(bodyPrefix + formatPrefix + hashKey(key))
if err != nil {
if vfs.IsNotExist(err) {
return nil, ErrNotFoundInCache
}
return nil, err
}
h, err := c.Header(key)
if err != nil {
if vfs.IsNotExist(err) {
return nil, ErrNotFoundInCache
}
return nil, err
}
res := NewResource(h.StatusCode, f, h.Header)
if staleTime, exists := c.stale[key]; exists {
if !res.DateAfter(staleTime) {
log.Printf("stale marker of %s found", staleTime)
res.MarkStale()
}
}
return res, nil
} | [
"func",
"(",
"c",
"*",
"cache",
")",
"Retrieve",
"(",
"key",
"string",
")",
"(",
"*",
"Resource",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"c",
".",
"fs",
".",
"Open",
"(",
"bodyPrefix",
"+",
"formatPrefix",
"+",
"hashKey",
"(",
"key",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"vfs",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"nil",
",",
"ErrNotFoundInCache",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"h",
",",
"err",
":=",
"c",
".",
"Header",
"(",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"vfs",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"nil",
",",
"ErrNotFoundInCache",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"res",
":=",
"NewResource",
"(",
"h",
".",
"StatusCode",
",",
"f",
",",
"h",
".",
"Header",
")",
"\n",
"if",
"staleTime",
",",
"exists",
":=",
"c",
".",
"stale",
"[",
"key",
"]",
";",
"exists",
"{",
"if",
"!",
"res",
".",
"DateAfter",
"(",
"staleTime",
")",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"staleTime",
")",
"\n",
"res",
".",
"MarkStale",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"res",
",",
"nil",
"\n",
"}"
] | // Retrieve returns a cached Resource for the given key | [
"Retrieve",
"returns",
"a",
"cached",
"Resource",
"for",
"the",
"given",
"key"
] | 2de7d84cb2513697e071961c5a5a81060c4382b5 | https://github.com/lox/httpcache/blob/2de7d84cb2513697e071961c5a5a81060c4382b5/cache.go#L153-L176 |
1,298 | lox/httpcache | handler.go | freshness | func (h *Handler) freshness(res *Resource, r *cacheRequest) (time.Duration, error) {
maxAge, err := res.MaxAge(h.Shared)
if err != nil {
return time.Duration(0), err
}
if r.CacheControl.Has("max-age") {
reqMaxAge, err := r.CacheControl.Duration("max-age")
if err != nil {
return time.Duration(0), err
}
if reqMaxAge < maxAge {
debugf("using request max-age of %s", reqMaxAge.String())
maxAge = reqMaxAge
}
}
age, err := res.Age()
if err != nil {
return time.Duration(0), err
}
if res.IsStale() {
return time.Duration(0), nil
}
if hFresh := res.HeuristicFreshness(); hFresh > maxAge {
debugf("using heuristic freshness of %q", hFresh)
maxAge = hFresh
}
return maxAge - age, nil
} | go | func (h *Handler) freshness(res *Resource, r *cacheRequest) (time.Duration, error) {
maxAge, err := res.MaxAge(h.Shared)
if err != nil {
return time.Duration(0), err
}
if r.CacheControl.Has("max-age") {
reqMaxAge, err := r.CacheControl.Duration("max-age")
if err != nil {
return time.Duration(0), err
}
if reqMaxAge < maxAge {
debugf("using request max-age of %s", reqMaxAge.String())
maxAge = reqMaxAge
}
}
age, err := res.Age()
if err != nil {
return time.Duration(0), err
}
if res.IsStale() {
return time.Duration(0), nil
}
if hFresh := res.HeuristicFreshness(); hFresh > maxAge {
debugf("using heuristic freshness of %q", hFresh)
maxAge = hFresh
}
return maxAge - age, nil
} | [
"func",
"(",
"h",
"*",
"Handler",
")",
"freshness",
"(",
"res",
"*",
"Resource",
",",
"r",
"*",
"cacheRequest",
")",
"(",
"time",
".",
"Duration",
",",
"error",
")",
"{",
"maxAge",
",",
"err",
":=",
"res",
".",
"MaxAge",
"(",
"h",
".",
"Shared",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"time",
".",
"Duration",
"(",
"0",
")",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"r",
".",
"CacheControl",
".",
"Has",
"(",
"\"",
"\"",
")",
"{",
"reqMaxAge",
",",
"err",
":=",
"r",
".",
"CacheControl",
".",
"Duration",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"time",
".",
"Duration",
"(",
"0",
")",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"reqMaxAge",
"<",
"maxAge",
"{",
"debugf",
"(",
"\"",
"\"",
",",
"reqMaxAge",
".",
"String",
"(",
")",
")",
"\n",
"maxAge",
"=",
"reqMaxAge",
"\n",
"}",
"\n",
"}",
"\n\n",
"age",
",",
"err",
":=",
"res",
".",
"Age",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"time",
".",
"Duration",
"(",
"0",
")",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"res",
".",
"IsStale",
"(",
")",
"{",
"return",
"time",
".",
"Duration",
"(",
"0",
")",
",",
"nil",
"\n",
"}",
"\n\n",
"if",
"hFresh",
":=",
"res",
".",
"HeuristicFreshness",
"(",
")",
";",
"hFresh",
">",
"maxAge",
"{",
"debugf",
"(",
"\"",
"\"",
",",
"hFresh",
")",
"\n",
"maxAge",
"=",
"hFresh",
"\n",
"}",
"\n\n",
"return",
"maxAge",
"-",
"age",
",",
"nil",
"\n",
"}"
] | // freshness returns the duration that a requested resource will be fresh for | [
"freshness",
"returns",
"the",
"duration",
"that",
"a",
"requested",
"resource",
"will",
"be",
"fresh",
"for"
] | 2de7d84cb2513697e071961c5a5a81060c4382b5 | https://github.com/lox/httpcache/blob/2de7d84cb2513697e071961c5a5a81060c4382b5/handler.go#L131-L164 |
1,299 | lox/httpcache | handler.go | pipeUpstream | func (h *Handler) pipeUpstream(w http.ResponseWriter, r *cacheRequest) {
rw := newResponseStreamer(w)
rdr, err := rw.Stream.NextReader()
if err != nil {
debugf("error creating next stream reader: %v", err)
w.Header().Set(CacheHeader, "SKIP")
h.upstream.ServeHTTP(w, r.Request)
return
}
defer rdr.Close()
debugf("piping request upstream")
go func() {
h.upstream.ServeHTTP(rw, r.Request)
rw.Stream.Close()
}()
rw.WaitHeaders()
if r.Method != "HEAD" && !r.isStateChanging() {
return
}
res := rw.Resource()
defer res.Close()
if r.Method == "HEAD" {
h.cache.Freshen(res, r.Key.ForMethod("GET").String())
} else if res.IsNonErrorStatus() {
h.invalidateResource(res, r)
}
} | go | func (h *Handler) pipeUpstream(w http.ResponseWriter, r *cacheRequest) {
rw := newResponseStreamer(w)
rdr, err := rw.Stream.NextReader()
if err != nil {
debugf("error creating next stream reader: %v", err)
w.Header().Set(CacheHeader, "SKIP")
h.upstream.ServeHTTP(w, r.Request)
return
}
defer rdr.Close()
debugf("piping request upstream")
go func() {
h.upstream.ServeHTTP(rw, r.Request)
rw.Stream.Close()
}()
rw.WaitHeaders()
if r.Method != "HEAD" && !r.isStateChanging() {
return
}
res := rw.Resource()
defer res.Close()
if r.Method == "HEAD" {
h.cache.Freshen(res, r.Key.ForMethod("GET").String())
} else if res.IsNonErrorStatus() {
h.invalidateResource(res, r)
}
} | [
"func",
"(",
"h",
"*",
"Handler",
")",
"pipeUpstream",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"cacheRequest",
")",
"{",
"rw",
":=",
"newResponseStreamer",
"(",
"w",
")",
"\n",
"rdr",
",",
"err",
":=",
"rw",
".",
"Stream",
".",
"NextReader",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"debugf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"CacheHeader",
",",
"\"",
"\"",
")",
"\n",
"h",
".",
"upstream",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
".",
"Request",
")",
"\n",
"return",
"\n",
"}",
"\n",
"defer",
"rdr",
".",
"Close",
"(",
")",
"\n\n",
"debugf",
"(",
"\"",
"\"",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"h",
".",
"upstream",
".",
"ServeHTTP",
"(",
"rw",
",",
"r",
".",
"Request",
")",
"\n",
"rw",
".",
"Stream",
".",
"Close",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"rw",
".",
"WaitHeaders",
"(",
")",
"\n\n",
"if",
"r",
".",
"Method",
"!=",
"\"",
"\"",
"&&",
"!",
"r",
".",
"isStateChanging",
"(",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"res",
":=",
"rw",
".",
"Resource",
"(",
")",
"\n",
"defer",
"res",
".",
"Close",
"(",
")",
"\n\n",
"if",
"r",
".",
"Method",
"==",
"\"",
"\"",
"{",
"h",
".",
"cache",
".",
"Freshen",
"(",
"res",
",",
"r",
".",
"Key",
".",
"ForMethod",
"(",
"\"",
"\"",
")",
".",
"String",
"(",
")",
")",
"\n",
"}",
"else",
"if",
"res",
".",
"IsNonErrorStatus",
"(",
")",
"{",
"h",
".",
"invalidateResource",
"(",
"res",
",",
"r",
")",
"\n",
"}",
"\n",
"}"
] | // pipeUpstream makes the request via the upstream handler, the response is not stored or modified | [
"pipeUpstream",
"makes",
"the",
"request",
"via",
"the",
"upstream",
"handler",
"the",
"response",
"is",
"not",
"stored",
"or",
"modified"
] | 2de7d84cb2513697e071961c5a5a81060c4382b5 | https://github.com/lox/httpcache/blob/2de7d84cb2513697e071961c5a5a81060c4382b5/handler.go#L206-L236 |