repo_name
stringlengths 1
52
| repo_creator
stringclasses 6
values | programming_language
stringclasses 4
values | code
stringlengths 0
9.68M
| num_lines
int64 1
234k
|
---|---|---|---|---|
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package client
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/onsi/ginkgo/v2"
"github.com/onsi/gomega/gexec"
)
// CLI is a wrapper around os.execs.
type CLI struct {
path string
workingDir string
}
// AppInitRequest contains the parameters for calling copilot app init.
type AppInitRequest struct {
AppName string
Domain string
Tags map[string]string
}
// InitRequest contains the parameters for calling copilot init.
type InitRequest struct {
AppName string
WorkloadName string
Deploy bool
ImageTag string
Dockerfile string
WorkloadType string
SvcPort string
Schedule string
}
// EnvInitRequest contains the parameters for calling copilot env init.
type EnvInitRequest struct {
AppName string
EnvName string
Profile string
CustomizedEnv bool
VPCImport EnvInitRequestVPCImport
VPCConfig EnvInitRequestVPCConfig
CertificateImport string
}
// EnvInitRequestVPCImport contains the parameters for configuring VPC import when
// calling copilot env init.
type EnvInitRequestVPCImport struct {
ID string
PublicSubnetIDs string
PrivateSubnetIDs string
}
// IsSet returns true if all fields are set.
func (e EnvInitRequestVPCImport) IsSet() bool {
return e.ID != "" && e.PublicSubnetIDs != "" && e.PrivateSubnetIDs != ""
}
// EnvInitRequestVPCConfig contains the parameters for configuring VPC config when
// calling copilot env init.
type EnvInitRequestVPCConfig struct {
CIDR string
AZs string
PublicSubnetCIDRs string
PrivateSubnetCIDRs string
}
// EnvDeployRequest contains the parameters for calling copilot env deploy.
type EnvDeployRequest struct {
AppName string
Name string
}
// EnvShowRequest contains the parameters for calling copilot env show.
type EnvShowRequest struct {
AppName string
EnvName string
}
// SvcInitRequest contains the parameters for calling copilot svc init.
type SvcInitRequest struct {
Name string
SvcType string
Dockerfile string
Image string
SvcPort string
TopicSubscriptions []string
IngressType string
}
// SvcShowRequest contains the parameters for calling copilot svc show.
type SvcShowRequest struct {
Name string
AppName string
Resources bool
}
// SvcStatusRequest contains the parameters for calling copilot svc status.
type SvcStatusRequest struct {
Name string
AppName string
EnvName string
}
// SvcExecRequest contains the parameters for calling copilot svc exec.
type SvcExecRequest struct {
Name string
AppName string
Command string
TaskID string
Container string
EnvName string
}
// SvcLogsRequest contains the parameters for calling copilot svc logs.
type SvcLogsRequest struct {
AppName string
EnvName string
Name string
Since string
}
// SvcPauseRequest contains the parameters for calling copilot svc logs.
type SvcPauseRequest struct {
AppName string
EnvName string
Name string
}
// SvcResumeRequest contains the parameters for calling copilot svc logs.
type SvcResumeRequest struct {
AppName string
EnvName string
Name string
}
// StorageInitRequest contains the parameters for calling copilot storage init.
type StorageInitRequest struct {
StorageName string
StorageType string
WorkloadName string
Lifecycle string
RDSEngine string
InitialDBName string
}
// SvcDeployInput contains the parameters for calling copilot svc deploy.
type SvcDeployInput struct {
Name string
EnvName string
ImageTag string
Force bool
}
// TaskRunInput contains the parameters for calling copilot task run.
type TaskRunInput struct {
AppName string
GroupName string
Image string
Dockerfile string
Subnets []string
SecurityGroups []string
Env string
Command string
EnvVars string
Default bool
Follow bool
}
// TaskExecRequest contains the parameters for calling copilot task exec.
type TaskExecRequest struct {
Name string
AppName string
Command string
EnvName string
}
// TaskDeleteInput contains the parameters for calling copilot task delete.
type TaskDeleteInput struct {
App string
Env string
Name string
Default bool
}
// JobInitInput contains the parameters for calling copilot job init.
type JobInitInput struct {
Name string
Dockerfile string
Schedule string
Retries string
Timeout string
}
// JobDeployInput contains the parameters for calling copilot job deploy.
type JobDeployInput struct {
Name string
EnvName string
ImageTag string
}
// PackageInput contains the parameters for calling copilot job package.
type PackageInput struct {
AppName string
Name string
Env string
Dir string
Tag string
}
// PipelineInitInput contains the parameters for calling copilot pipeline init.
type PipelineInitInput struct {
Name string
URL string
GitBranch string
Environments []string
Type string
}
// PipelineDeployInput contains the parameters for calling copilot pipeline deploy.
type PipelineDeployInput struct {
Name string
}
// PipelineShowInput contains the parameters for calling copilot pipeline show.
type PipelineShowInput struct {
Name string
}
// PipelineStatusInput contains the parameters for calling copilot pipeline status.
type PipelineStatusInput struct {
Name string
}
// NewCLI returns a wrapper around CLI.
func NewCLI() (*CLI, error) {
// These tests should be run in a dockerfile so that
// your file system and docker image repo isn't polluted
// with test data and files. Since this is going to run
// from Docker, the binary will be located in the root bin.
cliPath := filepath.Join("/", "bin", "copilot")
if os.Getenv("DRYRUN") == "true" {
cliPath = filepath.Join("..", "..", "bin", "local", "copilot")
}
if _, err := os.Stat(cliPath); err != nil {
return nil, err
}
return &CLI{
path: cliPath,
}, nil
}
// NewCLIWithDir returns the Copilot CLI such that the commands are run in the specified
// working directory.
func NewCLIWithDir(workingDir string) (*CLI, error) {
cli, err := NewCLI()
if err != nil {
return nil, err
}
cli.workingDir = workingDir
return cli, nil
}
/*
Help runs
copilot --help
*/
func (cli *CLI) Help() (string, error) {
return cli.exec(exec.Command(cli.path, "--help"))
}
/*
Version runs:
copilot --version
*/
func (cli *CLI) Version() (string, error) {
return cli.exec(exec.Command(cli.path, "--version"))
}
/*
Init runs:
copilot init
--app $p
--svc $s
--svc-type $type
--tag $t
--dockerfile $d
--deploy (optionally)
--schedule $schedule (optionally)
--port $port (optionally)
*/
func (cli *CLI) Init(opts *InitRequest) (string, error) {
var deployOption string
var scheduleOption string
var portOption string
if opts.Deploy {
deployOption = "--deploy"
}
if opts.Schedule != "" {
scheduleOption = "--schedule"
}
if opts.SvcPort != "" {
portOption = "--port"
}
return cli.exec(
exec.Command(cli.path, "init",
"--app", opts.AppName,
"--name", opts.WorkloadName,
"--type", opts.WorkloadType,
"--tag", opts.ImageTag,
"--dockerfile", opts.Dockerfile,
deployOption,
scheduleOption, opts.Schedule,
portOption, opts.SvcPort))
}
/*
SvcInit runs:
copilot svc init
--name $n
--svc-type $t
--port $port
*/
func (cli *CLI) SvcInit(opts *SvcInitRequest) (string, error) {
args := []string{
"svc",
"init",
"--name", opts.Name,
"--svc-type", opts.SvcType,
}
// Apply optional flags only if a value is provided.
if opts.SvcPort != "" {
args = append(args, "--port", opts.SvcPort)
}
if opts.Dockerfile != "" {
args = append(args, "--dockerfile", opts.Dockerfile)
}
if opts.Image != "" {
args = append(args, "--image", opts.Image)
}
if len(opts.TopicSubscriptions) > 0 {
args = append(args, "--subscribe-topics", strings.Join(opts.TopicSubscriptions, ","))
}
if opts.IngressType != "" {
args = append(args, "--ingress-type", opts.IngressType)
}
return cli.exec(
exec.Command(cli.path, args...))
}
/*
SvcShow runs:
copilot svc show
--app $p
--name $n
--json
*/
func (cli *CLI) SvcShow(opts *SvcShowRequest) (*SvcShowOutput, error) {
args := []string{
"svc", "show",
"--app", opts.AppName,
"--name", opts.Name,
"--json",
}
if opts.Resources {
args = append(args, "--resources")
}
svcJSON, svcShowErr := cli.exec(
exec.Command(cli.path, args...))
if svcShowErr != nil {
return nil, svcShowErr
}
return toSvcShowOutput(svcJSON)
}
/*
SvcStatus runs:
copilot svc status
--app $p
--env $e
--name $n
--json
*/
func (cli *CLI) SvcStatus(opts *SvcStatusRequest) (*SvcStatusOutput, error) {
svcJSON, svcStatusErr := cli.exec(
exec.Command(cli.path, "svc", "status",
"--app", opts.AppName,
"--name", opts.Name,
"--env", opts.EnvName,
"--json"))
if svcStatusErr != nil {
return nil, svcStatusErr
}
return toSvcStatusOutput(svcJSON)
}
/*
SvcExec runs:
copilot svc exec
--app $p
--env $e
--name $n
--command $cmd
--container $ctnr
--task-id $td
--yes=false
*/
func (cli *CLI) SvcExec(opts *SvcExecRequest) (string, error) {
return cli.exec(
exec.Command(cli.path, "svc", "exec",
"--app", opts.AppName,
"--name", opts.Name,
"--env", opts.EnvName,
"--command", opts.Command,
"--container", opts.Container,
"--task-id", opts.TaskID,
"--yes=false"))
}
/*
SvcDelete runs:
copilot svc delete
--name $n
--yes
*/
func (cli *CLI) SvcDelete(serviceName string) (string, error) {
return cli.exec(
exec.Command(cli.path, "svc", "delete",
"--name", serviceName,
"--yes"))
}
/*
SvcDeploy runs:
copilot svc deploy
--name $n
--env $e
--tag $t
*/
func (cli *CLI) SvcDeploy(opts *SvcDeployInput) (string, error) {
arguments := []string{
"svc", "deploy",
"--name", opts.Name,
"--env", opts.EnvName,
"--tag", opts.ImageTag}
if opts.Force {
arguments = append(arguments, "--force")
}
return cli.exec(
exec.Command(cli.path, arguments...))
}
/*
SvcList runs:
copilot svc ls
--app $p
--json
*/
func (cli *CLI) SvcList(appName string) (*SvcListOutput, error) {
output, err := cli.exec(
exec.Command(cli.path, "svc", "ls",
"--app", appName,
"--json"))
if err != nil {
return nil, err
}
return toSvcListOutput(output)
}
/*
SvcLogs runs:
copilot svc logs
--app $p
--name $n
--since $s
--env $e
--json
*/
func (cli *CLI) SvcLogs(opts *SvcLogsRequest) ([]SvcLogsOutput, error) {
output, err := cli.exec(
exec.Command(cli.path, "svc", "logs",
"--app", opts.AppName,
"--name", opts.Name,
"--since", opts.Since,
"--env", opts.EnvName,
"--json"))
if err != nil {
return nil, err
}
return toSvcLogsOutput(output)
}
/*
SvcPause runs:
copilot svc pause
--app $p
--name $n
--env $e
*/
func (cli *CLI) SvcPause(opts *SvcPauseRequest) (string, error) {
return cli.exec(
exec.Command(cli.path, "svc", "pause",
"--app", opts.AppName,
"--name", opts.Name,
"--env", opts.EnvName,
"--yes"))
}
/*
SvcResume runs:
copilot svc pause
--app $p
--name $n
--env $e
*/
func (cli *CLI) SvcResume(opts *SvcResumeRequest) (string, error) {
return cli.exec(
exec.Command(cli.path, "svc", "resume",
"--app", opts.AppName,
"--name", opts.Name,
"--env", opts.EnvName))
}
/*
StorageInit runs:
copilot storage init
--name $n
--storage-type $t
--workload $w
--engine $e
--initial-db $d
*/
func (cli *CLI) StorageInit(opts *StorageInitRequest) (string, error) {
arguments := []string{
"storage", "init",
"--name", opts.StorageName,
"--storage-type", opts.StorageType,
"--workload", opts.WorkloadName,
"--lifecycle", opts.Lifecycle,
}
if opts.RDSEngine != "" {
arguments = append(arguments, "--engine", opts.RDSEngine)
}
if opts.InitialDBName != "" {
arguments = append(arguments, "--initial-db", opts.InitialDBName)
}
return cli.exec(
exec.Command(cli.path, arguments...))
}
/*
EnvDelete runs:
copilot env delete
--name $n
--yes
*/
func (cli *CLI) EnvDelete(envName string) (string, error) {
return cli.exec(
exec.Command(cli.path, "env", "delete",
"--name", envName,
"--yes"))
}
/*
EnvInit runs:
copilot env init
--name $n
--app $a
--profile $pr
--prod (optional)
--default-config (optional)
--import-private-subnets (optional)
--import-public-subnets (optional)
--import-vpc-id (optional)
--override-private-cidrs (optional)
--override-public-cidrs (optional)
--override-vpc-cidr (optional)
*/
func (cli *CLI) EnvInit(opts *EnvInitRequest) (string, error) {
commands := []string{"env", "init",
"--name", opts.EnvName,
"--app", opts.AppName,
"--profile", opts.Profile,
}
if opts.CertificateImport != "" {
commands = append(commands, "--import-cert-arns", opts.CertificateImport)
}
if !opts.CustomizedEnv {
commands = append(commands, "--default-config")
}
if (opts.VPCImport != EnvInitRequestVPCImport{}) {
commands = append(commands, "--import-vpc-id", opts.VPCImport.ID, "--import-public-subnets",
opts.VPCImport.PublicSubnetIDs, "--import-private-subnets", opts.VPCImport.PrivateSubnetIDs)
}
if (opts.VPCConfig != EnvInitRequestVPCConfig{}) {
commands = append(commands, "--override-vpc-cidr", opts.VPCConfig.CIDR,
"--override-az-names", opts.VPCConfig.AZs,
"--override-public-cidrs", opts.VPCConfig.PublicSubnetCIDRs,
"--override-private-cidrs", opts.VPCConfig.PrivateSubnetCIDRs)
}
return cli.exec(exec.Command(cli.path, commands...))
}
/*
EnvDeploy runs:
copilot env deploy
--name $n
--app $a
*/
func (cli *CLI) EnvDeploy(opts *EnvDeployRequest) (string, error) {
commands := []string{"env", "deploy",
"--name", opts.Name,
"--app", opts.AppName,
}
return cli.exec(exec.Command(cli.path, commands...))
}
/*
EnvShow runs:
copilot env show
--app $a
--name $n
--json
*/
func (cli *CLI) EnvShow(opts *EnvShowRequest) (*EnvShowOutput, error) {
envJSON, envShowErr := cli.exec(
exec.Command(cli.path, "env", "show",
"--app", opts.AppName,
"--name", opts.EnvName,
"--json", "--resources"))
if envShowErr != nil {
return nil, envShowErr
}
return toEnvShowOutput(envJSON)
}
/*
EnvList runs:
copilot env ls
--app $a
--json
*/
func (cli *CLI) EnvList(appName string) (*EnvListOutput, error) {
output, err := cli.exec(
exec.Command(cli.path, "env", "ls",
"--app", appName,
"--json"))
if err != nil {
return nil, err
}
return toEnvListOutput(output)
}
/*
AppInit runs:
copilot app init $a
--domain $d (optionally)
--resource-tags $k1=$v1,$k2=$k2 (optionally)
*/
func (cli *CLI) AppInit(opts *AppInitRequest) (string, error) {
commands := []string{"app", "init", opts.AppName}
if opts.Domain != "" {
commands = append(commands, "--domain", opts.Domain)
}
if len(opts.Tags) > 0 {
commands = append(commands, "--resource-tags")
tags := []string{}
for key, val := range opts.Tags {
tags = append(tags, fmt.Sprintf("%s=%s", key, val))
}
commands = append(commands, strings.Join(tags, ","))
}
return cli.exec(exec.Command(cli.path, commands...))
}
/*
AppShow runs:
copilot app show
--name $n
--json
*/
func (cli *CLI) AppShow(appName string) (*AppShowOutput, error) {
output, err := cli.exec(
exec.Command(cli.path, "app", "show",
"--name", appName,
"--json"))
if err != nil {
return nil, err
}
return toAppShowOutput(output)
}
// PipelineInit runs:
//
// copilot pipeline init
// --name $n
// --url $t
// --git-branch $b
// --environments $e[0],$e[1],...
func (cli *CLI) PipelineInit(opts PipelineInitInput) (string, error) {
args := []string{
"pipeline",
"init",
"--name", opts.Name,
"--url", opts.URL,
"--git-branch", opts.GitBranch,
"--environments", strings.Join(opts.Environments, ","),
"--pipeline-type", opts.Type,
}
return cli.exec(exec.Command(cli.path, args...))
}
// PipelineDeploy runs:
//
// copilot pipeline deploy
// --name $n
// --yes
func (cli *CLI) PipelineDeploy(opts PipelineDeployInput) (string, error) {
args := []string{
"pipeline",
"deploy",
"--name", opts.Name,
"--yes",
}
return cli.exec(exec.Command(cli.path, args...))
}
// PipelineShow runs:
//
// copilot pipeline show
// --name $n
// --json
func (cli *CLI) PipelineShow(opts PipelineShowInput) (PipelineShowOutput, error) {
args := []string{
"pipeline",
"show",
"--name", opts.Name,
"--json",
}
text, err := cli.exec(exec.Command(cli.path, args...))
if err != nil {
return PipelineShowOutput{}, err
}
var out PipelineShowOutput
if err := json.Unmarshal([]byte(text), &out); err != nil {
return PipelineShowOutput{}, err
}
return out, nil
}
// PipelineStatus runs:
//
// copilot pipeline show
// --name $n
// --json
func (cli *CLI) PipelineStatus(opts PipelineStatusInput) (PipelineStatusOutput, error) {
args := []string{
"pipeline",
"status",
"--name", opts.Name,
"--json",
}
text, err := cli.exec(exec.Command(cli.path, args...))
if err != nil {
return PipelineStatusOutput{}, err
}
var out PipelineStatusOutput
if err := json.Unmarshal([]byte(text), &out); err != nil {
return PipelineStatusOutput{}, err
}
return out, nil
}
/*
AppList runs:
copilot app ls
*/
func (cli *CLI) AppList() (string, error) {
return cli.exec(exec.Command(cli.path, "app", "ls"))
}
/*
AppDelete runs:
copilot app delete --yes
*/
func (cli *CLI) AppDelete() (string, error) {
commands := []string{"app", "delete", "--yes"}
return cli.exec(
exec.Command(cli.path, commands...))
}
/*
TaskRun runs:
copilot task run
-n $t
--dockerfile $d
--app $a (optionally)
--env $e (optionally)
--command $c (optionally)
--env-vars $e1=$v1,$e2=$v2 (optionally)
--default (optionally)
--follow (optionally)
*/
func (cli *CLI) TaskRun(input *TaskRunInput) (string, error) {
commands := []string{"task", "run", "-n", input.GroupName, "--dockerfile", input.Dockerfile}
if input.Image != "" {
commands = append(commands, "--image", input.Image)
}
if input.AppName != "" {
commands = append(commands, "--app", input.AppName)
}
if input.Env != "" {
commands = append(commands, "--env", input.Env)
}
if input.Command != "" {
commands = append(commands, "--command", input.Command)
}
if input.EnvVars != "" {
commands = append(commands, "--env-vars", input.EnvVars)
}
if input.Default {
commands = append(commands, "--default")
}
if input.Follow {
commands = append(commands, "--follow")
}
return cli.exec(exec.Command(cli.path, commands...))
}
/*
TaskExec runs:
copilot task exec
--app $p
--env $e
--name $n
--command $cmd
--yes=false
*/
func (cli *CLI) TaskExec(opts *TaskExecRequest) (string, error) {
return cli.exec(
exec.Command(cli.path, "task", "exec",
"--app", opts.AppName,
"--name", opts.Name,
"--env", opts.EnvName,
"--command", opts.Command,
"--yes=false"))
}
/*
TaskDelete runs:
copilot task delete
--name $n
--yes
--default (optionally)
--app $a (optionally)
--env $e (optionally)
*/
func (cli *CLI) TaskDelete(opts *TaskDeleteInput) (string, error) {
args := []string{
"task",
"delete",
"--name", opts.Name,
"--yes",
}
if opts.App != "" {
args = append(args, "--app", opts.App)
}
if opts.Env != "" {
args = append(args, "--env", opts.Env)
}
if opts.Default {
args = append(args, "--default")
}
return cli.exec(
exec.Command(cli.path, args...),
)
}
/*
JobInit runs:
copilot job init
--name $n
--dockerfile $d
--schedule $sched
--retries $r
--timeout $o
*/
func (cli *CLI) JobInit(opts *JobInitInput) (string, error) {
args := []string{
"job",
"init",
"--name", opts.Name,
"--dockerfile", opts.Dockerfile,
"--schedule", opts.Schedule,
}
// Apply optional flags only if a value is provided.
if opts.Retries != "" {
args = append(args, "--retries", opts.Retries)
}
if opts.Timeout != "" {
args = append(args, "--timeout", opts.Timeout)
}
return cli.exec(
exec.Command(cli.path, args...))
}
/*
JobDeploy runs:
copilot job deploy
--name $n
--env $e
--tag $t
*/
func (cli *CLI) JobDeploy(opts *JobDeployInput) (string, error) {
return cli.exec(
exec.Command(cli.path, "job", "deploy",
"--name", opts.Name,
"--env", opts.EnvName,
"--tag", opts.ImageTag))
}
/*
JobDelete runs:
copilot job delete
--name $n
--yes
*/
func (cli *CLI) JobDelete(jobName string) (string, error) {
return cli.exec(
exec.Command(cli.path, "job", "delete",
"--name", jobName,
"--yes"))
}
/*
JobList runs:
copilot job ls
--json?
--local?
*/
func (cli *CLI) JobList(appName string) (*JobListOutput, error) {
output, err := cli.exec(
exec.Command(cli.path, "job", "ls",
"--app", appName,
"--json"))
if err != nil {
return nil, err
}
return toJobListOutput(output)
}
/*
JobPackage runs:
copilot job package
--output-dir $dir
--name $name
--env $env
--app $appname
--tag $tag
*/
func (cli *CLI) JobPackage(opts *PackageInput) (string, error) {
args := []string{
"job",
"package",
"--name", opts.Name,
"--env", opts.Env,
"--app", opts.AppName,
"--output-dir", opts.Dir,
"--tag", opts.Tag,
}
if opts.Dir != "" {
args = append(args, "--output-dir", opts.Dir)
}
if opts.Tag != "" {
args = append(args, "--tag", opts.Tag)
}
return cli.exec(exec.Command(cli.path, args...))
}
/*
SvcPackage runs:
copilot svc package
--output-dir $dir
--name $name
--env $env
--app $appname
*/
func (cli *CLI) SvcPackage(opts *PackageInput) (string, error) {
args := []string{
"svc",
"package",
"--name", opts.Name,
"--env", opts.Env,
"--app", opts.AppName,
}
if opts.Dir != "" {
args = append(args, "--output-dir", opts.Dir)
}
if opts.Tag != "" {
args = append(args, "--tag", opts.Tag)
}
return cli.exec(exec.Command(cli.path, args...))
}
func (cli *CLI) exec(command *exec.Cmd) (string, error) {
// Turn off colors
command.Env = append(os.Environ(), "COLOR=false", "CI=true")
command.Dir = cli.workingDir
sess, err := gexec.Start(command, ginkgo.GinkgoWriter, ginkgo.GinkgoWriter)
if err != nil {
return "", err
}
contents := sess.Wait(100000000).Out.Contents()
if exitCode := sess.ExitCode(); exitCode != 0 {
return string(sess.Err.Contents()), fmt.Errorf("received non 0 exit code")
}
return string(contents), nil
}
| 1,091 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package client
import (
"fmt"
"strings"
cmd "github.com/aws/copilot-cli/e2e/internal/command"
)
// Docker is a wrapper around Docker commands.
type Docker struct{}
// NewDocker returns a wrapper around Docker commands.
func NewDocker() *Docker {
return &Docker{}
}
/*Login runs:
docker login -u AWS --password-stdin $uri
*/
func (d *Docker) Login(uri, password string) error {
command := strings.Join([]string{
"login",
"-u", "AWS",
"--password-stdin", uri,
}, " ")
return d.exec(command, cmd.Stdin(strings.NewReader(password)))
}
/*Build runs:
docker build -t $uri $path
*/
func (d *Docker) Build(uri, path string) error {
command := strings.Join([]string{
"build",
"-t", uri, path,
}, " ")
return d.exec(command)
}
/*Push runs:
docker push $uri
*/
func (d *Docker) Push(uri string) error {
command := strings.Join([]string{
"push", uri,
}, " ")
return d.exec(command)
}
func (d *Docker) exec(command string, opts ...cmd.Option) error {
return BashExec(fmt.Sprintf("docker %s", command), opts...)
}
| 57 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package client
import (
"encoding/json"
"strings"
"time"
)
// SvcStatusOutput is the JSON output of the svc status.
type SvcStatusOutput struct {
Status string `json:"status"`
Service SvcStatusServiceInfo
Tasks []SvcStatusTaskInfo `json:"tasks"`
Alarms []SvcStatusAlarmInfo `json:"alarms"`
LogEvents []*SvcLogsOutput `json:"logEvents"`
}
// SvcStatusServiceInfo contains the status info of a service.
type SvcStatusServiceInfo struct {
DesiredCount int64 `json:"desiredCount"`
RunningCount int64 `json:"runningCount"`
Status string `json:"status"`
LastDeploymentAt time.Time `json:"lastDeploymentAt"`
TaskDefinition string `json:"taskDefinition"`
}
// Image contains very basic info of a container image.
type Image struct {
ID string
Digest string
}
// SvcStatusTaskInfo contains the status info of a task.
type SvcStatusTaskInfo struct {
Health string `json:"health"`
ID string `json:"id"`
Images []Image `json:"images"`
LastStatus string `json:"lastStatus"`
StartedAt time.Time `json:"startedAt"`
StoppedAt time.Time `json:"stoppedAt"`
StoppedReason string `json:"stoppedReason"`
}
// SvcStatusAlarmInfo contains CloudWatch alarm status info.
type SvcStatusAlarmInfo struct {
Arn string `json:"arn"`
Name string `json:"name"`
Reason string `json:"reason"`
Status string `json:"status"`
Type string `json:"type"`
UpdatedTimes time.Time `json:"updatedTimes"`
}
func toSvcStatusOutput(jsonInput string) (*SvcStatusOutput, error) {
var output SvcStatusOutput
return &output, json.Unmarshal([]byte(jsonInput), &output)
}
// SvcShowOutput is the JSON output of the svc show.
type SvcShowOutput struct {
SvcName string `json:"service"`
Type string `json:"type"`
AppName string `json:"application"`
Configs []SvcShowConfigurations `json:"configurations"`
ServiceDiscoveries []SvcShowServiceEndpoints `json:"serviceDiscovery"`
ServiceConnects []SvcShowServiceEndpoints `json:"serviceConnect"`
Routes []SvcShowRoutes `json:"routes"`
Variables []SvcShowVariables `json:"variables"`
Resources map[string][]*SvcShowResourceInfo `json:"resources"`
Secrets []SvcShowSecrets `json:"secrets"`
}
// SvcShowConfigurations contains serialized configuration parameters for a service.
type SvcShowConfigurations struct {
Environment string `json:"environment"`
Port string `json:"port"`
Tasks string `json:"tasks"`
CPU string `json:"cpu"`
Memory string `json:"memory"`
}
// SvcShowRoutes contains serialized route parameters for a web service.
type SvcShowRoutes struct {
Environment string `json:"environment"`
URL string `json:"url"`
Ingress string `json:"ingress"`
}
// SvcShowServiceEndpoints contains serialized endpoint info for a service.
type SvcShowServiceEndpoints struct {
Environment []string `json:"environment"`
Endpoint string `json:"endpoint"`
}
// SvcShowVariables contains serialized environment variables for a service.
type SvcShowVariables struct {
Environment string `json:"environment"`
Name string `json:"name"`
Value string `json:"value"`
}
// SvcShowSecrets contains serialized secrets for a service.
type SvcShowSecrets struct {
Environment string `json:"environment"`
Name string `json:"name"`
Value string `json:"value"`
}
// SvcShowResourceInfo contains serialized resource info for a service.
type SvcShowResourceInfo struct {
Type string `json:"type"`
PhysicalID string `json:"physicalID"`
}
func toSvcShowOutput(jsonInput string) (*SvcShowOutput, error) {
var output SvcShowOutput
return &output, json.Unmarshal([]byte(jsonInput), &output)
}
// SvcListOutput is the JSON output for svc list.
type SvcListOutput struct {
Services []WkldDescription `json:"services"`
}
// WkldDescription contains the brief description of the workload.
type WkldDescription struct {
Name string `json:"name"`
Type string `json:"type"`
AppName string `json:"app"`
}
func toSvcListOutput(jsonInput string) (*SvcListOutput, error) {
var output SvcListOutput
return &output, json.Unmarshal([]byte(jsonInput), &output)
}
// JobListOutput is the JSON output for job list.
type JobListOutput struct {
Jobs []WkldDescription `json:"jobs"`
}
func toJobListOutput(jsonInput string) (*JobListOutput, error) {
var output JobListOutput
return &output, json.Unmarshal([]byte(jsonInput), &output)
}
// SvcLogsOutput is the JSON output of svc logs.
type SvcLogsOutput struct {
LogStreamName string `json:"logStreamName"`
IngestionTime int64 `json:"ingestionTime"`
Timestamp int64 `json:"timestamp"`
Message string `json:"message"`
}
func toSvcLogsOutput(jsonInput string) ([]SvcLogsOutput, error) {
output := []SvcLogsOutput{}
for _, logLine := range strings.Split(strings.TrimSpace(jsonInput), "\n") {
var parsedLogLine SvcLogsOutput
if err := json.Unmarshal([]byte(logLine), &parsedLogLine); err != nil {
return nil, err
}
output = append(output, parsedLogLine)
}
return output, nil
}
// AppShowOutput is the JSON output of app show.
type AppShowOutput struct {
Name string `json:"name"`
URI string `json:"uri"`
}
func toAppShowOutput(jsonInput string) (*AppShowOutput, error) {
var output AppShowOutput
return &output, json.Unmarshal([]byte(jsonInput), &output)
}
// EnvShowOutput is the JSON output of env show.
type EnvShowOutput struct {
Environment EnvDescription `json:"environment"`
Services []EnvShowServices `json:"services"`
Tags map[string]string `json:"tags"`
Resources []map[string]string `json:"resources"`
}
// EnvShowServices contains brief info about a service.
type EnvShowServices struct {
Name string `json:"name"`
Type string `json:"type"`
}
func toEnvShowOutput(jsonInput string) (*EnvShowOutput, error) {
var output EnvShowOutput
return &output, json.Unmarshal([]byte(jsonInput), &output)
}
// EnvListOutput is the JSON output of env list.
type EnvListOutput struct {
Envs []EnvDescription `json:"environments"`
}
// EnvDescription contains descriptive info about an environment.
type EnvDescription struct {
Name string `json:"name"`
App string `json:"app"`
Region string `json:"region"`
Account string `json:"accountID"`
Prod bool `json:"prod"`
RegistryURL string `json:"registryURL"`
ExecutionRole string `json:"executionRoleARN"`
ManagerRole string `json:"managerRoleARN"`
}
func toEnvListOutput(jsonInput string) (*EnvListOutput, error) {
var output EnvListOutput
return &output, json.Unmarshal([]byte(jsonInput), &output)
}
// PipelineShowOutput represents the JSON output of the "pipeline show" command.
type PipelineShowOutput struct {
Name string `json:"name"`
Stages []struct {
Name string `json:"name"`
Category string `json:"category"`
} `json:"stages"`
}
// PipelineStatusOutput represents the JSON output of the "pipeline status" command.
type PipelineStatusOutput struct {
States []struct {
Name string `json:"stageName"`
Actions []struct {
Name string `json:"name"`
Status string `json:"status"`
} `json:"actions"`
} `json:"stageStates"`
}
| 241 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package command
import (
"io"
"os"
"os/exec"
)
// Option is the function signature for customizing the internal *exec.Cmd.
type Option func(cmd *exec.Cmd)
// Stdin sets the internal *exec.Cmd's Stdin field.
func Stdin(r io.Reader) Option {
return func(c *exec.Cmd) {
c.Stdin = r
}
}
// Stdout sets the internal *exec.Cmd's Stdout field.
func Stdout(writer io.Writer) Option {
return func(c *exec.Cmd) {
c.Stdout = writer
}
}
// Run runs the input command with input args with Stdout and Stderr defaulted to os.Stderr.
// Input options will override these defaults.
func Run(name string, args []string, options ...Option) error {
cmd := exec.Command(name, args...)
cmd.Stdout = os.Stderr
cmd.Stderr = os.Stderr
for _, opt := range options {
opt(cmd)
}
return cmd.Run()
}
| 43 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package isolated_test
import (
"fmt"
"testing"
"time"
"github.com/aws/copilot-cli/e2e/internal/client"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var cli *client.CLI
var aws *client.AWS
var appName string
var vpcStackName string
var vpcStackTemplatePath string
var vpcImport client.EnvInitRequestVPCImport
var timeNow = time.Now().Unix()
const svcName = "backend"
const envName = "test"
/**
The Isolated Suite creates an environment with an imported VPC with only
private subnets, deploys a backend service to it, and then tears it down.
*/
func Test_Isolated(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Isolated Suite")
}
var _ = BeforeSuite(func() {
vpcStackName = fmt.Sprintf("e2e-isolated-vpc-stack-%d", timeNow)
vpcStackTemplatePath = "file://vpc.yml"
copilot, err := client.NewCLI()
Expect(err).NotTo(HaveOccurred())
cli = copilot
aws = client.NewAWS()
appName = fmt.Sprintf("e2e-isolated-%d", timeNow)
// Create the VPC stack.
err = aws.CreateStack(vpcStackName, vpcStackTemplatePath)
Expect(err).NotTo(HaveOccurred())
err = aws.WaitStackCreateComplete(vpcStackName)
Expect(err).NotTo(HaveOccurred())
})
var _ = AfterSuite(func() {
_, deleteAppErr := cli.AppDelete()
deleteVPCErr := deleteVPCAndWait()
Expect(deleteAppErr).NotTo(HaveOccurred())
Expect(deleteVPCErr).NotTo(HaveOccurred())
})
func deleteVPCAndWait() error {
err := aws.DeleteStack(vpcStackName)
if err != nil {
return err
}
return aws.WaitStackDeleteComplete(vpcStackName)
}
| 65 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package isolated_test
import (
"errors"
"fmt"
"net/http"
"github.com/aws/copilot-cli/e2e/internal/client"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Isolated", func() {
Context("when creating a new app", Ordered, func() {
var appInitErr error
BeforeAll(func() {
_, appInitErr = cli.AppInit(&client.AppInitRequest{
AppName: appName,
Tags: map[string]string{
"e2e-test": "isolated",
},
})
})
It("app init succeeds", func() {
Expect(appInitErr).NotTo(HaveOccurred())
})
It("app init creates a copilot directory", func() {
Expect("./copilot").Should(BeADirectory())
})
It("app ls includes new app", func() {
Eventually(cli.AppList, "30s", "5s").Should(ContainSubstring(appName))
})
It("app show includes app name", func() {
appShowOutput, err := cli.AppShow(appName)
Expect(err).NotTo(HaveOccurred())
Expect(appShowOutput.Name).To(Equal(appName))
Expect(appShowOutput.URI).To(BeEmpty())
})
})
Context("when deploying resources to be imported", func() {
It("vpc stack exists", func() {
err := aws.WaitStackCreateComplete(vpcStackName)
Expect(err).NotTo(HaveOccurred())
})
It("parse vpc stack output", func() {
outputs, err := aws.VPCStackOutput(vpcStackName)
Expect(err).NotTo(HaveOccurred(), "get VPC stack output")
for _, output := range outputs {
switch output.OutputKey {
case "PrivateSubnets":
vpcImport.PrivateSubnetIDs = output.OutputValue
case "VpcId":
vpcImport.ID = output.OutputValue
}
}
if vpcImport.ID == "" || vpcImport.PrivateSubnetIDs == "" {
err = errors.New("resources are not configured properly")
}
Expect(err).NotTo(HaveOccurred(), "invalid vpc stack output")
})
})
Context("when adding environment with imported vpc resources", Ordered, func() {
var testEnvInitErr error
BeforeAll(func() {
_, testEnvInitErr = cli.EnvInit(&client.EnvInitRequest{
AppName: appName,
EnvName: envName,
Profile: envName,
VPCImport: vpcImport,
CustomizedEnv: true,
})
})
It("env init should succeed for 'test' env", func() {
Expect(testEnvInitErr).NotTo(HaveOccurred())
})
})
Context("when deploying the environment", Ordered, func() {
var testEnvDeployErr error
BeforeAll(func() {
_, testEnvDeployErr = cli.EnvDeploy(&client.EnvDeployRequest{
AppName: appName,
Name: envName,
})
})
It("should succeed", func() {
Expect(testEnvDeployErr).NotTo(HaveOccurred())
})
It("env ls should list test env", func() {
envListOutput, err := cli.EnvList(appName)
Expect(err).NotTo(HaveOccurred())
Expect(len(envListOutput.Envs)).To(Equal(1))
env := envListOutput.Envs[0]
Expect(env.Name).To(Equal(envName))
Expect(env.ExecutionRole).NotTo(BeEmpty())
Expect(env.ManagerRole).NotTo(BeEmpty())
})
})
Context("when creating a backend service in private subnets", Ordered, func() {
var initErr error
BeforeAll(func() {
_, initErr = cli.SvcInit(&client.SvcInitRequest{
Name: svcName,
SvcType: "Backend Service",
Dockerfile: "./backend/Dockerfile",
SvcPort: "80",
})
})
It("should not return an error", func() {
Expect(initErr).NotTo(HaveOccurred())
})
It("svc ls should list the svc", func() {
svcList, svcListError := cli.SvcList(appName)
Expect(svcListError).NotTo(HaveOccurred())
Expect(len(svcList.Services)).To(Equal(1))
Expect(svcList.Services[0].Name).To(Equal("backend"))
})
})
Context("when deploying a svc to 'test' env", Ordered, func() {
var testEnvDeployErr error
BeforeAll(func() {
_, testEnvDeployErr = cli.SvcDeploy(&client.SvcDeployInput{
Name: svcName,
EnvName: envName,
})
})
It("svc deploy should succeed", func() {
Expect(testEnvDeployErr).NotTo(HaveOccurred())
})
})
Context("when running svc show to retrieve the service configuration, resources, and endpoint, then querying the service", Ordered, func() {
var (
svc *client.SvcShowOutput
svcShowError error
)
BeforeAll(func() {
svc, svcShowError = cli.SvcShow(&client.SvcShowRequest{
Name: svcName,
AppName: appName,
Resources: true,
})
})
It("should not return an error", func() {
Expect(svcShowError).NotTo(HaveOccurred())
})
It("should return correct configuration", func() {
Expect(svc.SvcName).To(Equal(svcName))
Expect(svc.AppName).To(Equal(appName))
Expect(len(svc.Configs)).To(Equal(1))
Expect(svc.Configs[0].Environment).To(Equal(envName))
Expect(svc.Configs[0].CPU).To(Equal("256"))
Expect(svc.Configs[0].Memory).To(Equal("512"))
Expect(svc.Configs[0].Port).To(Equal("80"))
Expect(svc.Routes[0].URL).To(ContainSubstring(fmt.Sprintf("http://%s.%s.%s.internal", svcName, envName, appName)))
})
})
Context("when running `svc status`", func() {
It("it should include the service, tasks, and alarm status", func() {
svc, svcStatusErr := cli.SvcStatus(&client.SvcStatusRequest{
AppName: appName,
Name: svcName,
EnvName: envName,
})
Expect(svcStatusErr).NotTo(HaveOccurred())
// Service should be active.
Expect(svc.Service.Status).To(Equal("ACTIVE"))
// Desired count should be minimum auto scaling number.
Expect(svc.Service.DesiredCount).To(Equal(int64(1)))
// Should have correct number of running tasks.
Expect(len(svc.Tasks)).To(Equal(1))
})
})
Context("when running `env show --resources`", func() {
var envShowOutput *client.EnvShowOutput
var envShowErr error
It("should show internal ALB", func() {
envShowOutput, envShowErr = cli.EnvShow(&client.EnvShowRequest{
AppName: appName,
EnvName: envName,
})
Expect(envShowErr).NotTo(HaveOccurred())
Expect(envShowOutput.Resources).To(ContainElement(HaveKeyWithValue("type", "AWS::ElasticLoadBalancingV2::LoadBalancer")))
})
})
Context("when trying to reach the LB DNS", func() {
It("it is not reachable", func() {
var resp *http.Response
var fetchErr error
Eventually(func() (*http.Response, error) {
resp, fetchErr = http.Get(fmt.Sprintf("http://%s.%s.%s.internal", svcName, envName, appName))
return resp, fetchErr
}, "60s", "1s")
Expect(resp).To(BeNil())
})
})
Context("when `curl`ing the LB DNS from within the container", func() {
It("session manager should be installed", func() {
// Use custom SSM plugin as the public version is not compatible to Alpine Linux.
err := client.BashExec("chmod +x ./session-manager-plugin")
Expect(err).NotTo(HaveOccurred())
err = client.BashExec("mv ./session-manager-plugin /bin/session-manager-plugin")
Expect(err).NotTo(HaveOccurred())
})
It("is reachable", func() {
_, svcExecErr := cli.SvcExec(&client.SvcExecRequest{
Name: svcName,
AppName: appName,
Command: fmt.Sprintf(`/bin/sh -c "curl 'http://%s.%s.%s.internal'"`, svcName, envName, appName),
EnvName: envName,
})
Expect(svcExecErr).NotTo(HaveOccurred())
})
})
})
| 232 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package main
import (
"log"
"net/http"
"github.com/julienschmidt/httprouter"
)
// HealthCheck just returns true if the service is up.
func HealthCheck(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
log.Println("🚑 healthcheck ok!")
w.WriteHeader(http.StatusOK)
}
func main() {
router := httprouter.New()
// Health Check
router.GET("/", HealthCheck)
log.Fatal(http.ListenAndServe(":80", router))
}
| 27 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package multi_env_app_test
import (
"fmt"
"testing"
"time"
"github.com/aws/copilot-cli/e2e/internal/client"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var cli *client.CLI
var appName string
func TestMultiEnvProject(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Multiple Environments Suite")
}
var _ = BeforeSuite(func() {
ecsCli, err := client.NewCLI()
cli = ecsCli
Expect(err).NotTo(HaveOccurred())
appName = fmt.Sprintf("e2e-multienv-%d", time.Now().Unix())
})
var _ = AfterSuite(func() {
_, err := cli.AppDelete()
Expect(err).NotTo(HaveOccurred())
})
| 35 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package multi_env_app_test
import (
"fmt"
"net/http"
"os"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/aws/copilot-cli/e2e/internal/client"
)
var (
initErr error
)
var _ = Describe("Multiple Env App", func() {
Context("when creating a new app", Ordered, func() {
BeforeAll(func() {
_, initErr = cli.AppInit(&client.AppInitRequest{
AppName: appName,
Tags: map[string]string{
"e2e-test": "multi-env",
},
})
})
It("app init succeeds", func() {
Expect(initErr).NotTo(HaveOccurred())
})
It("app init creates a copilot directory", func() {
Expect("./copilot").Should(BeADirectory())
})
It("app ls includes new app", func() {
Eventually(cli.AppList, "30s", "5s").Should(ContainSubstring(appName))
})
It("app show includes app name", func() {
appShowOutput, err := cli.AppShow(appName)
Expect(err).NotTo(HaveOccurred())
Expect(appShowOutput.Name).To(Equal(appName))
Expect(appShowOutput.URI).To(BeEmpty())
})
})
Context("when adding cross account environments", Ordered, func() {
var (
testEnvInitErr error
prodEnvInitErr error
)
BeforeAll(func() {
_, testEnvInitErr = cli.EnvInit(&client.EnvInitRequest{
AppName: appName,
EnvName: "test",
Profile: "test",
})
_, prodEnvInitErr = cli.EnvInit(&client.EnvInitRequest{
AppName: appName,
EnvName: "prod",
Profile: "prod",
})
})
It("env init should succeed for test and prod envs", func() {
fmt.Println(testEnvInitErr)
fmt.Println(prodEnvInitErr)
Expect(testEnvInitErr).NotTo(HaveOccurred())
Expect(prodEnvInitErr).NotTo(HaveOccurred())
})
It("should create environment manifests", func() {
Expect("./copilot/environments/test/manifest.yml").Should(BeAnExistingFile())
Expect("./copilot/environments/prod/manifest.yml").Should(BeAnExistingFile())
})
It("env ls should list both envs", func() {
envListOutput, err := cli.EnvList(appName)
Expect(err).NotTo(HaveOccurred())
Expect(len(envListOutput.Envs)).To(Equal(2))
envs := map[string]client.EnvDescription{}
for _, env := range envListOutput.Envs {
envs[env.Name] = env
Expect(env.ExecutionRole).NotTo(BeEmpty())
Expect(env.ManagerRole).NotTo(BeEmpty())
}
Expect(envs["test"]).NotTo(BeNil())
Expect(envs["prod"]).NotTo(BeNil())
// Make sure, for the sake of coverage, these are cross account,
// cross region environments if we're not doing a dryrun.
if os.Getenv("DRYRUN") != "true" {
Expect(envs["test"].Region).NotTo(Equal(envs["prod"].Region))
Expect(envs["test"].Account).NotTo(Equal(envs["prod"].Account))
}
})
It("should show only bootstrap resources in env show", func() {
testEnvShowOutput, testEnvShowError := cli.EnvShow(&client.EnvShowRequest{
AppName: appName,
EnvName: "test",
})
prodEnvShowOutput, prodEnvShowError := cli.EnvShow(&client.EnvShowRequest{
AppName: appName,
EnvName: "prod",
})
Expect(testEnvShowError).NotTo(HaveOccurred())
Expect(prodEnvShowError).NotTo(HaveOccurred())
Expect(testEnvShowOutput.Environment.Name).To(Equal("test"))
Expect(testEnvShowOutput.Environment.App).To(Equal(appName))
Expect(prodEnvShowOutput.Environment.Name).To(Equal("prod"))
Expect(prodEnvShowOutput.Environment.App).To(Equal(appName))
// Contains only bootstrap resources - two IAM roles.
Expect(len(testEnvShowOutput.Resources)).To(Equal(2))
Expect(len(prodEnvShowOutput.Resources)).To(Equal(2))
})
})
Context("when deploying the environments", Ordered, func() {
var testEnvDeployErr, prodEnvDeployErr error
BeforeAll(func() {
_, testEnvDeployErr = cli.EnvDeploy(&client.EnvDeployRequest{
AppName: appName,
Name: "test",
})
_, prodEnvDeployErr = cli.EnvDeploy(&client.EnvDeployRequest{
AppName: appName,
Name: "prod",
})
})
It("should succeed", func() {
Expect(testEnvDeployErr).NotTo(HaveOccurred())
Expect(prodEnvDeployErr).NotTo(HaveOccurred())
})
})
Context("when adding a svc", Ordered, func() {
var (
frontEndInitErr error
)
BeforeAll(func() {
_, frontEndInitErr = cli.SvcInit(&client.SvcInitRequest{
Name: "front-end",
SvcType: "Load Balanced Web Service",
Dockerfile: "./front-end/Dockerfile",
SvcPort: "80",
})
})
It("svc init should succeed", func() {
Expect(frontEndInitErr).NotTo(HaveOccurred())
})
It("svc init should create a svc manifest", func() {
Expect("./copilot/front-end/manifest.yml").Should(BeAnExistingFile())
})
It("svc ls should list the svc", func() {
svcList, svcListError := cli.SvcList(appName)
Expect(svcListError).NotTo(HaveOccurred())
Expect(len(svcList.Services)).To(Equal(1))
Expect(svcList.Services[0].Name).To(Equal("front-end"))
})
It("svc package should output a cloudformation template and params file", func() {
Skip("not implemented yet")
})
})
Context("when deploying a svc to test and prod envs", Ordered, func() {
var (
testDeployErr error
prodEndDeployErr error
svcName string
)
BeforeAll(func() {
svcName = "front-end"
_, testDeployErr = cli.SvcDeploy(&client.SvcDeployInput{
Name: svcName,
EnvName: "test",
ImageTag: "gallopinggurdey",
})
_, prodEndDeployErr = cli.SvcDeploy(&client.SvcDeployInput{
Name: svcName,
EnvName: "prod",
ImageTag: "gallopinggurdey",
})
})
It("svc deploy should succeed to both environment", func() {
Expect(testDeployErr).NotTo(HaveOccurred())
Expect(prodEndDeployErr).NotTo(HaveOccurred())
})
It("svc show should include a valid URL and description for test and prod envs", func() {
svc, svcShowErr := cli.SvcShow(&client.SvcShowRequest{
AppName: appName,
Name: svcName,
})
Expect(svcShowErr).NotTo(HaveOccurred())
Expect(len(svc.Routes)).To(Equal(2))
// Group routes by environment
envRoutes := map[string]client.SvcShowRoutes{}
for _, route := range svc.Routes {
envRoutes[route.Environment] = route
}
Expect(len(svc.ServiceDiscoveries)).To(Equal(2))
var envs, endpoints, wantedEndpoints []string
for _, sd := range svc.ServiceDiscoveries {
envs = append(envs, sd.Environment[0])
endpoints = append(endpoints, sd.Endpoint)
wantedEndpoints = append(wantedEndpoints, fmt.Sprintf("%s.%s.%s.local:80", svc.SvcName, sd.Environment[0], appName))
}
Expect(envs).To(ConsistOf("test", "prod"))
Expect(endpoints).To(ConsistOf(wantedEndpoints))
// Call each environment's endpoint and ensure it returns a 200
for _, env := range []string{"test", "prod"} {
route := envRoutes[env]
Expect(route.Environment).To(Equal(env))
Eventually(func() (int, error) {
resp, fetchErr := http.Get(route.URL)
return resp.StatusCode, fetchErr
}, "30s", "1s").Should(Equal(200))
}
})
It("svc logs should display logs", func() {
for _, envName := range []string{"test", "prod"} {
var svcLogs []client.SvcLogsOutput
var svcLogsErr error
Eventually(func() ([]client.SvcLogsOutput, error) {
svcLogs, svcLogsErr = cli.SvcLogs(&client.SvcLogsRequest{
AppName: appName,
Name: svcName,
EnvName: envName,
Since: "1h",
})
return svcLogs, svcLogsErr
}, "60s", "10s").ShouldNot(BeEmpty())
for _, logLine := range svcLogs {
Expect(logLine.Message).NotTo(Equal(""))
Expect(logLine.LogStreamName).NotTo(Equal(""))
Expect(logLine.Timestamp).NotTo(Equal(0))
Expect(logLine.IngestionTime).NotTo(Equal(0))
}
}
})
It("env show should display info for test and prod envs", func() {
envs := map[string]client.EnvDescription{}
for _, envName := range []string{"test", "prod"} {
envShowOutput, envShowErr := cli.EnvShow(&client.EnvShowRequest{
AppName: appName,
EnvName: envName,
})
Expect(envShowErr).NotTo(HaveOccurred())
Expect(envShowOutput.Environment.Name).To(Equal(envName))
Expect(envShowOutput.Environment.App).To(Equal(appName))
Expect(len(envShowOutput.Services)).To(Equal(1))
Expect(envShowOutput.Services[0].Name).To(Equal(svcName))
Expect(envShowOutput.Services[0].Type).To(Equal("Load Balanced Web Service"))
Expect(len(envShowOutput.Tags)).To(Equal(3))
Expect(envShowOutput.Tags["copilot-application"]).To(Equal(appName))
Expect(envShowOutput.Tags["copilot-environment"]).To(Equal(envName))
Expect(envShowOutput.Tags["e2e-test"]).To(Equal("multi-env"))
envs[envShowOutput.Environment.Name] = envShowOutput.Environment
}
Expect(envs["test"]).NotTo(BeNil())
Expect(envs["prod"]).NotTo(BeNil())
if os.Getenv("DRYRUN") != "true" {
Expect(envs["test"].Region).NotTo(Equal(envs["prod"].Region))
Expect(envs["test"].Account).NotTo(Equal(envs["prod"].Account))
}
Expect(envs["test"].ExecutionRole).NotTo(Equal(envs["prod"].ExecutionRole))
Expect(envs["test"].ManagerRole).NotTo(Equal(envs["prod"].ExecutionRole))
})
})
Context("when setting up a pipeline", func() {
It("pipeline init should create a pipeline manifest", func() {
Skip("not implemented yet")
})
It("pipeline deploy should create a pipeline", func() {
Skip("not implemented yet")
})
})
Context("when pushing a change to the pipeline", func() {
It("the change should be propagated to test and prod environments", func() {
Skip("not implemented yet")
})
})
})
| 314 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package multi_pipeline_test
import (
"fmt"
"testing"
"time"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/aws/copilot-cli/e2e/internal/client"
)
// Command-line tools.
var (
copilot *client.CLI
aws *client.AWS
)
// Application identifiers.
var (
appName = fmt.Sprintf("e2e-multipipeline-%d", time.Now().Unix())
testPipelineName = "my-pipeline-test"
prodPipelineName = "my-pipeline-prod"
)
// CodeCommit credentials.
var (
repoName = appName
repoURL string
codeCommitIAMUser = fmt.Sprintf("%s-cc", appName)
codeCommitCreds *client.IAMServiceCreds
)
func TestPipeline(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Pipeline Suite")
}
var _ = BeforeSuite(func() {
cli, err := client.NewCLIWithDir(repoName)
Expect(err).NotTo(HaveOccurred())
copilot = cli
aws = client.NewAWS()
creds, err := aws.CreateCodeCommitIAMUser(codeCommitIAMUser)
Expect(err).NotTo(HaveOccurred())
codeCommitCreds = creds
})
var _ = AfterSuite(func() {
_, err := copilot.AppDelete()
_ = aws.DeleteCodeCommitRepo(appName)
_ = aws.DeleteCodeCommitIAMUser(codeCommitIAMUser, codeCommitCreds.CredentialID)
Expect(err).NotTo(HaveOccurred())
})
| 60 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package multi_pipeline_test
import (
"fmt"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/aws/copilot-cli/e2e/internal/client"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("pipeline flow", func() {
Context("set up CodeCommit repository", func() {
It("creates the codecommit repository", func() {
url, err := aws.CreateCodeCommitRepo(repoName)
Expect(err).NotTo(HaveOccurred())
repoURL = url
})
It("clones the repository", func() {
endpoint := strings.TrimPrefix(repoURL, "https://")
url := fmt.Sprintf("https://%s:%s@%s", url.PathEscape(codeCommitCreds.UserName), url.PathEscape(codeCommitCreds.Password), endpoint)
Eventually(func() error {
cmd := exec.Command("git", "clone", url)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}, "60s", "5s").ShouldNot(HaveOccurred())
})
It("copies source code to the git repository", func() {
cmd := exec.Command("cp", "-r", "frontend", repoName)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
Expect(cmd.Run()).NotTo(HaveOccurred())
})
It("sets git config", func() {
cmd := exec.Command("git", "config", "user.email", "[email protected]")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Dir = repoName
Expect(cmd.Run()).NotTo(HaveOccurred())
cmd = exec.Command("git", "config", "user.name", "e2etest")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Dir = repoName
Expect(cmd.Run()).NotTo(HaveOccurred())
})
})
Context("create a new app", func() {
It("app init succeeds", func() {
_, err := copilot.AppInit(&client.AppInitRequest{
AppName: appName,
})
Expect(err).NotTo(HaveOccurred())
})
It("app init creates an copilot directory and workspace file", func() {
Expect(filepath.Join(repoName, "copilot")).Should(BeADirectory())
Expect(filepath.Join(repoName, "copilot", ".workspace")).Should(BeAnExistingFile())
})
It("app ls includes new app", func() {
Eventually(copilot.AppList, "30s", "5s").Should(ContainSubstring(appName))
})
It("app show includes app name", func() {
appShowOutput, err := copilot.AppShow(appName)
Expect(err).NotTo(HaveOccurred())
Expect(appShowOutput.Name).To(Equal(appName))
Expect(appShowOutput.URI).To(BeEmpty())
})
})
Context("when adding a new environment", func() {
It("test env init should succeed", func() {
_, err := copilot.EnvInit(&client.EnvInitRequest{
AppName: appName,
EnvName: "test",
Profile: "test",
})
Expect(err).NotTo(HaveOccurred())
})
It("prod env init should succeed", func() {
_, err := copilot.EnvInit(&client.EnvInitRequest{
AppName: appName,
EnvName: "prod",
Profile: "prod",
})
Expect(err).NotTo(HaveOccurred())
})
It("env ls should list both envs", func() {
out, err := copilot.EnvList(appName)
Expect(err).NotTo(HaveOccurred())
Expect(len(out.Envs)).To(Equal(2))
envs := map[string]client.EnvDescription{}
for _, env := range out.Envs {
envs[env.Name] = env
Expect(env.ExecutionRole).NotTo(BeEmpty())
Expect(env.ManagerRole).NotTo(BeEmpty())
}
Expect(envs["test"]).NotTo(BeNil())
Expect(envs["prod"]).NotTo(BeNil())
// Make sure, for the sake of coverage, these are cross account,
// cross region environments if we're not doing a dryrun.
if os.Getenv("DRYRUN") != "true" {
Expect(envs["test"].Region).NotTo(Equal(envs["prod"].Region))
Expect(envs["test"].Account).NotTo(Equal(envs["prod"].Account))
}
})
})
Context("when deploying the environments", func() {
It("test env deploy should succeed", func() {
_, err := copilot.EnvDeploy(&client.EnvDeployRequest{
AppName: appName,
Name: "test",
})
Expect(err).NotTo(HaveOccurred())
})
It("prod env deploy should succeed", func() {
_, err := copilot.EnvDeploy(&client.EnvDeployRequest{
AppName: appName,
Name: "prod",
})
Expect(err).NotTo(HaveOccurred())
})
})
Context("when creating the frontend service", func() {
It("should initialize the service", func() {
_, err := copilot.SvcInit(&client.SvcInitRequest{
Name: "frontend",
SvcType: "Load Balanced Web Service",
Dockerfile: "./frontend/Dockerfile",
SvcPort: "80",
})
Expect(err).NotTo(HaveOccurred())
})
It("should generate a manifest file", func() {
Expect(filepath.Join(repoName, "copilot", "frontend", "manifest.yml")).Should(BeAnExistingFile())
})
It("creates a new addons dir", func() {
cmd := exec.Command("mkdir", "-p", filepath.Join(repoName, "copilot", "frontend", "addons"))
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
Expect(cmd.Run()).NotTo(HaveOccurred())
})
It("copies a template to the addons file", func() {
cmd := exec.Command("cp", "s3template.yml", filepath.Join(repoName, "copilot", "frontend", "addons", "e2e-pipeline-addon.yml"))
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
Expect(cmd.Run()).NotTo(HaveOccurred())
})
It("should list the service", func() {
out, err := copilot.SvcList(appName)
Expect(err).NotTo(HaveOccurred())
Expect(len(out.Services)).To(Equal(1))
Expect(out.Services[0].Name).To(Equal("frontend"))
})
})
Context("when creating the test pipeline manifest", func() {
It("creates a 'test' git branch", func() {
cmd := exec.Command("git", "checkout", "-b", "test")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Dir = repoName
Expect(cmd.Run()).NotTo(HaveOccurred())
})
It("should initialize the pipeline", func() {
_, err := copilot.PipelineInit(client.PipelineInitInput{
Name: testPipelineName,
URL: repoURL,
GitBranch: "test",
Environments: []string{"test"},
Type: "Workloads",
})
Expect(err).NotTo(HaveOccurred())
})
It("should generate pipeline artifacts", func() {
Expect(filepath.Join(repoName, "copilot", "pipelines", testPipelineName, "manifest.yml")).Should(BeAnExistingFile())
Expect(filepath.Join(repoName, "copilot", "pipelines", testPipelineName, "buildspec.yml")).Should(BeAnExistingFile())
})
It("should push repo changes upstream", func() {
cmd := exec.Command("git", "add", ".")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Dir = repoName
Expect(cmd.Run()).NotTo(HaveOccurred())
cmd = exec.Command("git", "commit", "-m", "first commit")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Dir = repoName
Expect(cmd.Run()).NotTo(HaveOccurred())
cmd = exec.Command("git", "push", "--set-upstream", "origin", "test")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Dir = repoName
Expect(cmd.Run()).NotTo(HaveOccurred())
})
})
Context("when creating the prod pipeline manifest", func() {
It("creates a 'prod' git branch", func() {
cmd := exec.Command("git", "checkout", "-b", "prod")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Dir = repoName
Expect(cmd.Run()).NotTo(HaveOccurred())
})
It("should initialize the pipeline", func() {
_, err := copilot.PipelineInit(client.PipelineInitInput{
Name: prodPipelineName,
URL: repoURL,
GitBranch: "prod",
Environments: []string{"prod"},
Type: "Workloads",
})
Expect(err).NotTo(HaveOccurred())
})
It("should generate pipeline artifacts", func() {
Expect(filepath.Join(repoName, "copilot", "pipelines", prodPipelineName, "manifest.yml")).Should(BeAnExistingFile())
Expect(filepath.Join(repoName, "copilot", "pipelines", prodPipelineName, "buildspec.yml")).Should(BeAnExistingFile())
})
It("should push repo changes upstream", func() {
cmd := exec.Command("git", "add", ".")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Dir = repoName
Expect(cmd.Run()).NotTo(HaveOccurred())
cmd = exec.Command("git", "commit", "-m", "first commit")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Dir = repoName
Expect(cmd.Run()).NotTo(HaveOccurred())
cmd = exec.Command("git", "push", "--set-upstream", "origin", "prod")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Dir = repoName
Expect(cmd.Run()).NotTo(HaveOccurred())
})
})
Context("when creating the test pipeline stack", func() {
It("checks out the test git branch", func() {
cmd := exec.Command("git", "checkout", "test")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Dir = repoName
Expect(cmd.Run()).NotTo(HaveOccurred())
})
It("should start creating the pipeline stack", func() {
_, err := copilot.PipelineDeploy(client.PipelineDeployInput{
Name: testPipelineName,
})
Expect(err).NotTo(HaveOccurred())
})
It("should show test pipeline details once the stack is created", func() {
type stage struct {
Name string
Category string
}
wantedStages := []stage{
{
Name: "Source",
Category: "Source",
},
{
Name: "Build",
Category: "Build",
},
{
Name: "DeployTo-test",
Category: "Deploy",
},
}
Eventually(func() error {
out, err := copilot.PipelineShow(client.PipelineShowInput{
Name: testPipelineName,
})
switch {
case err != nil:
return err
case out.Name == "":
return fmt.Errorf("pipeline name is empty: %v", out)
case out.Name != testPipelineName:
return fmt.Errorf("expected pipeline name %q, got %q", testPipelineName, out.Name)
case len(out.Stages) != len(wantedStages):
return fmt.Errorf("pipeline stages do not match: %v", out.Stages)
}
for idx, actualStage := range out.Stages {
if wantedStages[idx].Name != actualStage.Name {
return fmt.Errorf("stage name %s at index %d does not match", actualStage.Name, idx)
}
if wantedStages[idx].Category != actualStage.Category {
return fmt.Errorf("stage category %s at index %d does not match", actualStage.Category, idx)
}
}
return nil
}, "600s", "10s").Should(BeNil())
})
It("should deploy the service to the test environment", func() {
type state struct {
Name string
ActionName string
ActionStatus string
}
wantedStates := []state{
{
Name: "Source",
ActionName: fmt.Sprintf("SourceCodeFor-%s", appName),
ActionStatus: "Succeeded",
},
{
Name: "Build",
ActionName: "Build",
ActionStatus: "Succeeded",
},
{
Name: "DeployTo-test",
ActionName: "CreateOrUpdate-frontend-test",
ActionStatus: "Succeeded",
},
}
Eventually(func() error {
out, err := copilot.PipelineStatus(client.PipelineStatusInput{
Name: testPipelineName,
})
if err != nil {
return err
}
if len(wantedStates) != len(out.States) {
return fmt.Errorf("len of pipeline states do not match: %v", out.States)
}
for idx, actualState := range out.States {
if wantedStates[idx].Name != actualState.Name {
return fmt.Errorf("state name %s at index %d does not match", actualState.Name, idx)
}
if len(actualState.Actions) != 1 {
return fmt.Errorf("no action yet for state name %s", actualState.Name)
}
if wantedStates[idx].ActionName != actualState.Actions[0].Name {
return fmt.Errorf("action name %v for state %s does not match at index %d", actualState.Actions[0], actualState.Name, idx)
}
if wantedStates[idx].ActionStatus != actualState.Actions[0].Status {
return fmt.Errorf("action status %v for state %s does not match at index %d", actualState.Actions[0], actualState.Name, idx)
}
}
return nil
}, "1200s", "15s").Should(BeNil())
})
})
Context("test pipeline service should be queryable post-release", func() {
It("service should include a valid URL", func() {
out, err := copilot.SvcShow(&client.SvcShowRequest{
AppName: appName,
Name: "frontend",
})
Expect(err).NotTo(HaveOccurred())
routes := make(map[string]string)
for _, route := range out.Routes {
routes[route.Environment] = route.URL
}
for _, env := range []string{"test"} {
Eventually(func() (int, error) {
resp, fetchErr := http.Get(routes[env])
return resp.StatusCode, fetchErr
}, "30s", "1s").Should(Equal(200))
}
// Check that the addons stack was created.
Eventually(func() error {
for _, variable := range out.Variables {
if variable.Name == "E2EPIPELINEADDON_NAME" {
return nil
}
}
return fmt.Errorf("addons variable %s not found", "E2EPIPELINEADDON_NAME")
})
})
})
Context("when creating the prod pipeline stack", func() {
It("checks out the prod git branch", func() {
cmd := exec.Command("git", "checkout", "prod")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Dir = repoName
Expect(cmd.Run()).NotTo(HaveOccurred())
})
It("should start creating the pipeline stack", func() {
_, err := copilot.PipelineDeploy(client.PipelineDeployInput{
Name: prodPipelineName,
})
Expect(err).NotTo(HaveOccurred())
})
It("should show prod pipeline details once the stack is created", func() {
type stage struct {
Name string
Category string
}
wantedStages := []stage{
{
Name: "Source",
Category: "Source",
},
{
Name: "Build",
Category: "Build",
},
{
Name: "DeployTo-prod",
Category: "Deploy",
},
}
Eventually(func() error {
out, err := copilot.PipelineShow(client.PipelineShowInput{
Name: prodPipelineName,
})
switch {
case err != nil:
return err
case out.Name == "":
return fmt.Errorf("pipeline name is empty: %v", out)
case out.Name != prodPipelineName:
return fmt.Errorf("expected pipeline name %q, got %q", prodPipelineName, out.Name)
case len(out.Stages) != len(wantedStages):
return fmt.Errorf("pipeline stages do not match: %v", out.Stages)
}
for idx, actualStage := range out.Stages {
if wantedStages[idx].Name != actualStage.Name {
return fmt.Errorf("stage name %s at index %d does not match", actualStage.Name, idx)
}
if wantedStages[idx].Category != actualStage.Category {
return fmt.Errorf("stage category %s at index %d does not match", actualStage.Category, idx)
}
}
return nil
}, "600s", "10s").Should(BeNil())
})
It("should deploy the service to the prod environment", func() {
type state struct {
Name string
ActionName string
ActionStatus string
}
wantedStates := []state{
{
Name: "Source",
ActionName: fmt.Sprintf("SourceCodeFor-%s", appName),
ActionStatus: "Succeeded",
},
{
Name: "Build",
ActionName: "Build",
ActionStatus: "Succeeded",
},
{
Name: "DeployTo-prod",
ActionName: "CreateOrUpdate-frontend-prod",
ActionStatus: "Succeeded",
},
}
Eventually(func() error {
out, err := copilot.PipelineStatus(client.PipelineStatusInput{
Name: prodPipelineName,
})
if err != nil {
return err
}
if len(wantedStates) != len(out.States) {
return fmt.Errorf("len of pipeline states do not match: %v", out.States)
}
for idx, actualState := range out.States {
if wantedStates[idx].Name != actualState.Name {
return fmt.Errorf("state name %s at index %d does not match", actualState.Name, idx)
}
if len(actualState.Actions) != 1 {
return fmt.Errorf("no action yet for state name %s", actualState.Name)
}
if wantedStates[idx].ActionName != actualState.Actions[0].Name {
return fmt.Errorf("action name %v for state %s does not match at index %d", actualState.Actions[0], actualState.Name, idx)
}
if wantedStates[idx].ActionStatus != actualState.Actions[0].Status {
return fmt.Errorf("action status %v for state %s does not match at index %d", actualState.Actions[0], actualState.Name, idx)
}
}
return nil
}, "1200s", "15s").Should(BeNil())
})
})
Context("prod pipeline service should be queryable post-release", func() {
It("service should include a valid URL", func() {
out, err := copilot.SvcShow(&client.SvcShowRequest{
AppName: appName,
Name: "frontend",
})
Expect(err).NotTo(HaveOccurred())
routes := make(map[string]string)
for _, route := range out.Routes {
routes[route.Environment] = route.URL
}
for _, env := range []string{"prod"} {
Eventually(func() (int, error) {
resp, fetchErr := http.Get(routes[env])
return resp.StatusCode, fetchErr
}, "30s", "1s").Should(Equal(200))
}
// Check that the addons stack was created.
Eventually(func() error {
for _, variable := range out.Variables {
if variable.Name == "E2EPIPELINEADDON_NAME" {
return nil
}
}
return fmt.Errorf("addons variable %s not found", "E2EPIPELINEADDON_NAME")
})
})
})
})
| 554 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package multi_svc_app_test
import (
"fmt"
"testing"
"time"
"github.com/aws/copilot-cli/e2e/internal/client"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var cli *client.CLI
var aws *client.AWS
var appName string
/*
The multi svc suite runs through several tests focusing on creating multiple
services in one app.
*/
func TestMultiSvcApp(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Multiple Svc Suite (one workspace)")
}
var _ = BeforeSuite(func() {
ecsCli, err := client.NewCLI()
cli = ecsCli
Expect(err).NotTo(HaveOccurred())
aws = client.NewAWS()
Expect(err).NotTo(HaveOccurred())
appName = fmt.Sprintf("e2e-multisvc-%d", time.Now().Unix())
})
var _ = AfterSuite(func() {
_, err := cli.AppDelete()
Expect(err).NotTo(HaveOccurred())
})
| 42 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package multi_svc_app_test
import (
"fmt"
"io"
"net/http"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/aws/copilot-cli/e2e/internal/client"
)
var (
initErr error
)
var _ = Describe("Multiple Service App", func() {
Context("when creating a new app", Ordered, func() {
BeforeAll(func() {
_, initErr = cli.AppInit(&client.AppInitRequest{
AppName: appName,
})
})
It("app init succeeds", func() {
Expect(initErr).NotTo(HaveOccurred())
})
It("app init creates a copilot directory", func() {
Expect("./copilot").Should(BeADirectory())
})
It("app ls includes new application", func() {
Eventually(cli.AppList, "30s", "5s").Should(ContainSubstring(appName))
})
It("app show includes app name", func() {
appShowOutput, err := cli.AppShow(appName)
Expect(err).NotTo(HaveOccurred())
Expect(appShowOutput.Name).To(Equal(appName))
Expect(appShowOutput.URI).To(BeEmpty())
})
})
Context("when adding a new environment", Ordered, func() {
var (
testEnvInitErr error
)
BeforeAll(func() {
_, testEnvInitErr = cli.EnvInit(&client.EnvInitRequest{
AppName: appName,
EnvName: "test",
Profile: "test",
})
})
It("env init should succeed", func() {
Expect(testEnvInitErr).NotTo(HaveOccurred())
})
})
Context("when deploying the environment", Ordered, func() {
var envDeployErr error
BeforeAll(func() {
_, envDeployErr = cli.EnvDeploy(&client.EnvDeployRequest{
AppName: appName,
Name: "test",
})
})
It("should succeed", func() {
Expect(envDeployErr).NotTo(HaveOccurred())
})
})
Context("when adding a svc", Ordered, func() {
var (
frontEndInitErr error
wwwInitErr error
backEndInitErr error
jobInitErr error
)
BeforeAll(func() {
_, frontEndInitErr = cli.SvcInit(&client.SvcInitRequest{
Name: "front-end",
SvcType: "Load Balanced Web Service",
Dockerfile: "./front-end/Dockerfile",
})
_, wwwInitErr = cli.SvcInit(&client.SvcInitRequest{
Name: "www",
SvcType: "Load Balanced Web Service",
Dockerfile: "./www/Dockerfile",
SvcPort: "80",
})
_, backEndInitErr = cli.SvcInit(&client.SvcInitRequest{
Name: "back-end",
SvcType: "Backend Service",
Dockerfile: "./back-end/Dockerfile",
SvcPort: "80",
})
_, jobInitErr = cli.JobInit(&client.JobInitInput{
Name: "query",
Dockerfile: "./query/Dockerfile",
Schedule: "@every 4m",
})
})
It("svc init should succeed", func() {
Expect(frontEndInitErr).NotTo(HaveOccurred())
Expect(wwwInitErr).NotTo(HaveOccurred())
Expect(backEndInitErr).NotTo(HaveOccurred())
})
It("job init should succeed", func() {
Expect(jobInitErr).NotTo(HaveOccurred())
})
It("svc init should create svc manifests", func() {
Expect("./copilot/front-end/manifest.yml").Should(BeAnExistingFile())
Expect("./copilot/www/manifest.yml").Should(BeAnExistingFile())
Expect("./copilot/back-end/manifest.yml").Should(BeAnExistingFile())
})
It("job init should create job manifest", func() {
Expect("./copilot/query/manifest.yml").Should(BeAnExistingFile())
})
It("svc ls should list the svc", func() {
svcList, svcListError := cli.SvcList(appName)
Expect(svcListError).NotTo(HaveOccurred())
Expect(len(svcList.Services)).To(Equal(3))
svcsByName := map[string]client.WkldDescription{}
for _, svc := range svcList.Services {
svcsByName[svc.Name] = svc
}
for _, svc := range []string{"front-end", "www", "back-end"} {
Expect(svcsByName[svc].Name).To(Equal(svc))
Expect(svcsByName[svc].AppName).To(Equal(appName))
}
})
It("job ls should list the job", func() {
jobList, jobListError := cli.JobList(appName)
Expect(jobListError).NotTo(HaveOccurred())
Expect(len(jobList.Jobs)).To(Equal(1))
jobsByName := map[string]client.WkldDescription{}
for _, job := range jobList.Jobs {
jobsByName[job.Name] = job
}
Expect(jobsByName["query"].Name).To(Equal("query"))
Expect(jobsByName["query"].AppName).To(Equal(appName))
})
It("svc package should output a cloudformation template and params file", func() {
_, svcPackageError := cli.SvcPackage(&client.PackageInput{
Name: "front-end",
AppName: appName,
Env: "test",
Dir: "infrastructure",
Tag: "gallopinggurdey",
})
Expect(svcPackageError).NotTo(HaveOccurred())
Expect("infrastructure/front-end-test.stack.yml").To(BeAnExistingFile())
Expect("infrastructure/front-end-test.params.json").To(BeAnExistingFile())
})
It("job package should output a Cloudformation template and params file", func() {
_, jobPackageError := cli.JobPackage(&client.PackageInput{
Name: "query",
AppName: appName,
Env: "test",
Dir: "infrastructure",
Tag: "thepostalservice",
})
Expect(jobPackageError).NotTo(HaveOccurred())
Expect("infrastructure/query-test.params.json").To(BeAnExistingFile())
Expect("infrastructure/query-test.stack.yml").To(BeAnExistingFile())
})
})
Context("when deploying services and jobs", Ordered, func() {
var (
frontEndDeployErr error
wwwDeployErr error
backEndDeployErr error
jobDeployErr error
routeURL string
)
BeforeAll(func() {
_, backEndDeployErr = cli.SvcDeploy(&client.SvcDeployInput{
Name: "back-end",
EnvName: "test",
ImageTag: "gallopinggurdey",
})
_, frontEndDeployErr = cli.SvcDeploy(&client.SvcDeployInput{
Name: "front-end",
EnvName: "test",
ImageTag: "gallopinggurdey",
})
_, jobDeployErr = cli.JobDeploy(&client.JobDeployInput{
Name: "query",
EnvName: "test",
ImageTag: "thepostalservice",
})
_, wwwDeployErr = cli.SvcDeploy(&client.SvcDeployInput{
Name: "www",
EnvName: "test",
ImageTag: "gallopinggurdey",
})
})
It("svc deploy should succeed", func() {
Expect(frontEndDeployErr).NotTo(HaveOccurred())
Expect(wwwDeployErr).NotTo(HaveOccurred())
Expect(backEndDeployErr).NotTo(HaveOccurred())
})
It("job deploy should succeed", func() {
Expect(jobDeployErr).NotTo(HaveOccurred())
})
It("svc show should include a valid URL and description for test env", func() {
for _, svcName := range []string{"front-end", "www"} {
svc, svcShowErr := cli.SvcShow(&client.SvcShowRequest{
AppName: appName,
Name: svcName,
})
Expect(svcShowErr).NotTo(HaveOccurred())
Expect(len(svc.Routes)).To(Equal(1))
// Call each environment's endpoint and ensure it returns a 200
route := svc.Routes[0]
Expect(route.Environment).To(Equal("test"))
// Since the front-end was added first, it should have no suffix.
if svcName == "front-end" {
Expect(route.URL).ToNot(HaveSuffix(svcName))
}
// Since the www app was added second, it should have app appended to the name.
var resp *http.Response
var fetchErr error
Eventually(func() (int, error) {
resp, fetchErr = http.Get(route.URL)
return resp.StatusCode, fetchErr
}, "60s", "1s").Should(Equal(200))
// Read the response - our deployed apps should return a body with their
// name as the value.
bodyBytes, err := io.ReadAll(resp.Body)
Expect(err).NotTo(HaveOccurred())
Expect(string(bodyBytes)).To(Equal(svcName))
}
})
It("svc status should include the service, tasks, and alarm status", func() {
svcName := "front-end"
svc, svcStatusErr := cli.SvcStatus(&client.SvcStatusRequest{
AppName: appName,
Name: svcName,
EnvName: "test",
})
Expect(svcStatusErr).NotTo(HaveOccurred())
// Service should be active.
Expect(svc.Service.Status).To(Equal("ACTIVE"))
// Desired count should be minimum auto scaling number.
Expect(svc.Service.DesiredCount).To(Equal(int64(2)))
// Should have correct number of running tasks.
Expect(len(svc.Tasks)).To(Equal(2))
// Should have correct number of auto scaling alarms.
Expect(len(svc.Alarms)).To(Equal(4))
})
It("env show should include the name and type for front-end, www, and back-end svcs", func() {
envShowOutput, envShowErr := cli.EnvShow(&client.EnvShowRequest{
AppName: appName,
EnvName: "test",
})
Expect(envShowErr).NotTo(HaveOccurred())
Expect(len(envShowOutput.Services)).To(Equal(3))
svcs := map[string]client.EnvShowServices{}
for _, svc := range envShowOutput.Services {
svcs[svc.Name] = svc
}
Expect(svcs["front-end"]).NotTo(BeNil())
Expect(svcs["front-end"].Type).To(Equal("Load Balanced Web Service"))
Expect(svcs["www"]).NotTo(BeNil())
Expect(svcs["www"].Type).To(Equal("Load Balanced Web Service"))
Expect(svcs["back-end"]).NotTo(BeNil())
Expect(svcs["back-end"].Type).To(Equal("Backend Service"))
})
It("service internal endpoint should be enabled and working", func() {
// The front-end service is set up to have a path called
// "/front-end/service-endpoint-test" - this route
// calls a function which makes a call via the service
// connect/discovery endpoint, "back-end.local". If that back-end
// call succeeds, the back-end returns a response
// "back-end-service". This should be forwarded
// back to us via the front-end api.
// [test] -- http req -> [front-end] -- service-connect -> [back-end]
svcName := "front-end"
svc, svcShowErr := cli.SvcShow(&client.SvcShowRequest{
AppName: appName,
Name: svcName,
})
Expect(svcShowErr).NotTo(HaveOccurred())
Expect(len(svc.Routes)).To(Equal(1))
Expect(len(svc.ServiceConnects)).To(Equal(1))
Expect(svc.ServiceConnects[0].Endpoint).To(Equal(fmt.Sprintf("%s:80", svcName)))
// Calls the front end's service connect/discovery endpoint - which should connect
// to the backend, and pipe the backend response to us.
route := svc.Routes[0]
Expect(route.Environment).To(Equal("test"))
routeURL = route.URL
resp, fetchErr := http.Get(fmt.Sprintf("%s/service-endpoint-test/", route.URL))
Expect(fetchErr).NotTo(HaveOccurred())
Expect(resp.StatusCode).To(Equal(200))
// Read the response - our deployed apps should return a body with their
// name as the value.
bodyBytes, err := io.ReadAll(resp.Body)
Expect(err).NotTo(HaveOccurred())
Expect(string(bodyBytes)).To(Equal("back-end-service"))
})
It("should be able to write to EFS volume", func() {
svcName := "front-end"
svc, svcShowErr := cli.SvcShow(&client.SvcShowRequest{
AppName: appName,
Name: svcName,
})
Expect(svcShowErr).NotTo(HaveOccurred())
Expect(len(svc.Routes)).To(Equal(1))
// Calls the front end's EFS test endpoint - which should create a file in the EFS filesystem.
route := svc.Routes[0]
Expect(route.Environment).To(Equal("test"))
routeURL = route.URL
resp, fetchErr := http.Get(fmt.Sprintf("%s/efs-putter", route.URL))
Expect(fetchErr).NotTo(HaveOccurred())
Expect(resp.StatusCode).To(Equal(200))
})
It("EFS volume should appear in `env show`", func() {
envShowOutput, envShowErr := cli.EnvShow(&client.EnvShowRequest{
AppName: appName,
EnvName: "test",
})
Expect(envShowErr).NotTo(HaveOccurred())
Expect(envShowOutput.Resources).To(ContainElement(HaveKeyWithValue("type", "AWS::EFS::FileSystem")))
})
It("job should have run", func() {
// Job should have run. We check this by hitting the "job-checker" path, which tells us the value
// of the "TEST_JOB_CHECK_VAR" in the frontend service, which will have been updated by a GET on
// /job-setter
Eventually(func() (string, error) {
resp, fetchErr := http.Get(fmt.Sprintf("%s/job-checker/", routeURL))
if fetchErr != nil {
return "", fetchErr
}
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(bodyBytes), nil
}, "4m", "10s").Should(Equal("yes")) // This is shorthand for "error is nil and resp is yes"
})
It("environment variable should be overridden and accessible through GET /magicwords", func() {
// The front-end service has a route called "/magicwords/" which returns the value of
// an environment variable set by a docker argument. If the argument is not overridden
// at build time, the endpoint will return "open caraway" in the body. If the value
// is overridden by the extended build configuration in the manifest, it will return
// "open sesame" in the body.
svcName := "front-end"
svc, svcShowErr := cli.SvcShow(&client.SvcShowRequest{
AppName: appName,
Name: svcName,
})
Expect(svcShowErr).NotTo(HaveOccurred())
Expect(len(svc.Routes)).To(Equal(1))
// Calls the front end's magicwords endpoint
route := svc.Routes[0]
Expect(route.Environment).To(Equal("test"))
resp, fetchErr := http.Get(fmt.Sprintf("%s/magicwords/", route.URL))
Expect(fetchErr).NotTo(HaveOccurred())
Expect(resp.StatusCode).To(Equal(200))
// Read the response - successfully overridden build arg will result
// in a response of "open sesame"
bodyBytes, err := io.ReadAll(resp.Body)
Expect(err).NotTo(HaveOccurred())
Expect(string(bodyBytes)).To(Equal("open sesame"))
})
It("svc logs should display logs", func() {
for _, svcName := range []string{"front-end", "back-end"} {
var svcLogs []client.SvcLogsOutput
var svcLogsErr error
Eventually(func() ([]client.SvcLogsOutput, error) {
svcLogs, svcLogsErr = cli.SvcLogs(&client.SvcLogsRequest{
AppName: appName,
Name: svcName,
EnvName: "test",
Since: "1h",
})
return svcLogs, svcLogsErr
}, "60s", "10s").ShouldNot(BeEmpty())
for _, logLine := range svcLogs {
Expect(logLine.Message).NotTo(Equal(""))
Expect(logLine.LogStreamName).NotTo(Equal(""))
Expect(logLine.Timestamp).NotTo(Equal(0))
Expect(logLine.IngestionTime).NotTo(Equal(0))
}
}
})
})
})
| 439 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package main
import (
"log"
"net/http"
"github.com/julienschmidt/httprouter"
)
// HealthCheck just returns true if the service is up.
func HealthCheck(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
log.Println("🚑 healthcheck ok!")
w.WriteHeader(http.StatusOK)
}
// SimpleGet just returns true no matter what.
func SimpleGet(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
log.Println("Get Succeeded")
w.WriteHeader(http.StatusOK)
w.Write([]byte("back-end"))
}
// Get just returns true no matter what.
func Get(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
log.Println("Get on service endpoint Succeeded")
w.WriteHeader(http.StatusOK)
w.Write([]byte("back-end-service"))
}
func main() {
router := httprouter.New()
router.GET("/back-end/", SimpleGet)
router.GET("/service-endpoint/", Get)
// Health Check
router.GET("/", HealthCheck)
log.Fatal(http.ListenAndServe(":80", router))
}
| 43 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"github.com/julienschmidt/httprouter"
)
var (
// Get the env var "MAGIC_VERB" for testing if the build arg was overridden.
magicVerb = os.Getenv("MAGIC_VERB")
// Get the env var "MAGIC_WORD" for testing if the env var defined in env file is rendered.
magicWord = os.Getenv("MAGIC_WORD")
volumeName = "efsTestVolume"
)
// SimpleGet just returns true no matter what.
func SimpleGet(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
log.Println("Get Succeeded")
w.WriteHeader(http.StatusOK)
w.Write([]byte("front-end"))
}
// ServiceGet calls the back-end service, via service-connect and service-discovery.
// This call should succeed and return the value from the backend service.
// This test assumes the backend app is called "back-end". The 'service-connect' and
// 'service-discovery' endpoint of the back-end service is unreachable from the LB,
// so the only way to get it is through service connect and service discovery.
// The response should be `back-end-service`
func ServiceGet(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
resp, err := http.Get("http://back-end/service-endpoint/")
if err != nil {
log.Printf("🚨 could call service connect endpoint: err=%s\n", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
log.Println("Get on service connect endpoint Succeeded")
sdEndpoint := fmt.Sprintf("http://back-end.%s/service-endpoint/", os.Getenv("COPILOT_SERVICE_DISCOVERY_ENDPOINT"))
resp, err = http.Get(sdEndpoint)
if err != nil {
log.Printf("🚨 could call service discovery endpoint: err=%s\n", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
log.Println("Get on service discovery endpoint Succeeded")
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
w.WriteHeader(http.StatusOK)
w.Write(body)
}
// GetMagicWords returns the environment variable passed in by the arg override
func GetMagicWords(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
log.Println("Get Succeeded")
w.WriteHeader(http.StatusOK)
magicWords := magicVerb + " " + magicWord
log.Println(magicWords)
w.Write([]byte(magicWords))
}
// GetJobCheck returns the value of the environment variable TEST_JOB_CHECK_VAR.
func GetJobCheck(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
log.Println("Get /job-checker/ succeeded")
w.WriteHeader(http.StatusOK)
w.Write([]byte(os.Getenv("TEST_JOB_CHECK_VAR")))
}
// SetJobCheck updates the environment variable TEST_JOB_CHECK_VAR in the container to "yes"
func SetJobCheck(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
log.Println("Get /job-setter/ succeeded")
err := os.Setenv("TEST_JOB_CHECK_VAR", "yes")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
// PutEFSCheck writes a file to the EFS folder in the container.
func PutEFSCheck(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
efsVar := os.Getenv("COPILOT_MOUNT_POINTS")
copilotMountPoints := make(map[string]string)
if err := json.Unmarshal([]byte(efsVar), &copilotMountPoints); err != nil {
log.Println("Unmarshal COPILOT_MOUNT_POINTS env var FAILED")
w.WriteHeader(http.StatusInternalServerError)
return
}
fileName := fmt.Sprintf("%s/testfile", copilotMountPoints[volumeName])
fileObj, err := os.Create(fileName)
if err != nil {
log.Printf("Create test file %s in EFS volume FAILED\n", fileName)
w.WriteHeader(http.StatusInternalServerError)
return
}
defer fileObj.Close()
// Resize file to 10M
if err := fileObj.Truncate(1e7); err != nil {
log.Printf("Resize test file %s in EFS volume FAILED\n", fileName)
w.WriteHeader(http.StatusInternalServerError)
return
}
// Shred file to write 10MiB of data to the filesystem.
shredCmd := exec.Command("shred", "-n", "1", fileName)
if err := shredCmd.Run(); err != nil {
log.Println("Shred test file in EFS volume FAILED")
w.WriteHeader(http.StatusInternalServerError)
return
}
fi, err := os.Stat(fileName)
if err != nil {
log.Printf("Get info for file %s\n", fileName)
w.WriteHeader(http.StatusInternalServerError)
return
}
log.Printf("File size: %d\n", fi.Size())
log.Println("Get /efs-putter succeeded")
w.WriteHeader(http.StatusOK)
}
func main() {
router := httprouter.New()
router.GET("/", SimpleGet)
router.GET("/service-endpoint-test", ServiceGet)
router.GET("/magicwords/", GetMagicWords)
router.GET("/job-checker/", GetJobCheck)
router.GET("/job-setter/", SetJobCheck)
router.GET("/efs-putter", PutEFSCheck)
log.Println("Listening on port 80...")
log.Fatal(http.ListenAndServe(":80", router))
}
| 143 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package main
import (
"log"
"net/http"
"github.com/julienschmidt/httprouter"
)
// SimpleGet just returns true no matter what.
func SimpleGet(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
log.Println("Get Succeeded")
w.WriteHeader(http.StatusOK)
w.Write([]byte("www"))
}
func healthCheckHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
log.Println("Health Check Succeeded")
w.WriteHeader(http.StatusOK)
w.Write([]byte("www"))
}
func main() {
router := httprouter.New()
router.GET("/", healthCheckHandler)
router.GET("/www/", SimpleGet)
log.Fatal(http.ListenAndServe(":80", router))
}
| 32 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package pipeline_test
import (
"fmt"
"testing"
"time"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/aws/copilot-cli/e2e/internal/client"
)
// Command-line tools.
var (
copilot *client.CLI
aws *client.AWS
)
// Application identifiers.
var (
appName = fmt.Sprintf("e2e-pipeline-%d", time.Now().Unix())
pipelineName = "my-pipeline"
)
// CodeCommit credentials.
var (
repoName = appName
repoURL string
codeCommitIAMUser = fmt.Sprintf("%s-cc", appName)
codeCommitCreds *client.IAMServiceCreds
)
func TestPipeline(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Pipeline Suite")
}
var _ = BeforeSuite(func() {
cli, err := client.NewCLIWithDir(repoName)
Expect(err).NotTo(HaveOccurred())
copilot = cli
aws = client.NewAWS()
creds, err := aws.CreateCodeCommitIAMUser(codeCommitIAMUser)
Expect(err).NotTo(HaveOccurred())
codeCommitCreds = creds
})
var _ = AfterSuite(func() {
_, err := copilot.AppDelete()
_ = aws.DeleteCodeCommitRepo(appName)
_ = aws.DeleteCodeCommitIAMUser(codeCommitIAMUser, codeCommitCreds.CredentialID)
Expect(err).NotTo(HaveOccurred())
})
| 59 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package pipeline_test
import (
"fmt"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/aws/copilot-cli/e2e/internal/client"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("pipeline flow", func() {
Context("setup CodeCommit repository", func() {
It("creates the codecommit repository", func() {
url, err := aws.CreateCodeCommitRepo(repoName)
Expect(err).NotTo(HaveOccurred())
repoURL = url
})
It("clones the repository", func() {
endpoint := strings.TrimPrefix(repoURL, "https://")
url := fmt.Sprintf("https://%s:%s@%s", url.PathEscape(codeCommitCreds.UserName), url.PathEscape(codeCommitCreds.Password), endpoint)
Eventually(func() error {
cmd := exec.Command("git", "clone", url)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}, "60s", "5s").ShouldNot(HaveOccurred())
})
It("copies source code to the git repository", func() {
cmd := exec.Command("cp", "-r", "frontend", repoName)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
Expect(cmd.Run()).NotTo(HaveOccurred())
})
})
Context("create a new app", func() {
It("app init succeeds", func() {
_, err := copilot.AppInit(&client.AppInitRequest{
AppName: appName,
})
Expect(err).NotTo(HaveOccurred())
})
It("app init creates an copilot directory and workspace file", func() {
Expect(filepath.Join(repoName, "copilot")).Should(BeADirectory())
Expect(filepath.Join(repoName, "copilot", ".workspace")).Should(BeAnExistingFile())
})
It("app ls includes new app", func() {
Eventually(copilot.AppList, "30s", "5s").Should(ContainSubstring(appName))
})
It("app show includes app name", func() {
appShowOutput, err := copilot.AppShow(appName)
Expect(err).NotTo(HaveOccurred())
Expect(appShowOutput.Name).To(Equal(appName))
Expect(appShowOutput.URI).To(BeEmpty())
})
})
Context("when adding a new environment", func() {
It("test env init should succeed", func() {
_, err := copilot.EnvInit(&client.EnvInitRequest{
AppName: appName,
EnvName: "test",
Profile: "test",
})
Expect(err).NotTo(HaveOccurred())
})
It("prod env init should succeed", func() {
_, err := copilot.EnvInit(&client.EnvInitRequest{
AppName: appName,
EnvName: "prod",
Profile: "prod",
})
Expect(err).NotTo(HaveOccurred())
})
It("env ls should list both envs", func() {
out, err := copilot.EnvList(appName)
Expect(err).NotTo(HaveOccurred())
Expect(len(out.Envs)).To(Equal(2))
envs := map[string]client.EnvDescription{}
for _, env := range out.Envs {
envs[env.Name] = env
Expect(env.ExecutionRole).NotTo(BeEmpty())
Expect(env.ManagerRole).NotTo(BeEmpty())
}
Expect(envs["test"]).NotTo(BeNil())
Expect(envs["prod"]).NotTo(BeNil())
})
})
Context("when deploying the environments", func() {
It("test env deploy should succeed", func() {
_, err := copilot.EnvDeploy(&client.EnvDeployRequest{
AppName: appName,
Name: "test",
})
Expect(err).NotTo(HaveOccurred())
})
It("prod env deploy should succeed", func() {
_, err := copilot.EnvDeploy(&client.EnvDeployRequest{
AppName: appName,
Name: "prod",
})
Expect(err).NotTo(HaveOccurred())
})
})
Context("when creating the frontend service", func() {
It("should initialize the service", func() {
_, err := copilot.SvcInit(&client.SvcInitRequest{
Name: "frontend",
SvcType: "Load Balanced Web Service",
Dockerfile: "./frontend/Dockerfile",
SvcPort: "80",
})
Expect(err).NotTo(HaveOccurred())
})
It("should generate a manifest file", func() {
Expect(filepath.Join(repoName, "copilot", "frontend", "manifest.yml")).Should(BeAnExistingFile())
})
It("should list the service", func() {
out, err := copilot.SvcList(appName)
Expect(err).NotTo(HaveOccurred())
Expect(len(out.Services)).To(Equal(1))
Expect(out.Services[0].Name).To(Equal("frontend"))
})
})
Context("when creating the pipeline manifest", func() {
It("should initialize the pipeline", func() {
_, err := copilot.PipelineInit(client.PipelineInitInput{
Name: pipelineName,
URL: repoURL,
GitBranch: "master",
Environments: []string{"test", "prod"},
Type: "Workloads",
})
Expect(err).NotTo(HaveOccurred())
})
It("should generate pipeline artifacts", func() {
Expect(filepath.Join(repoName, "copilot", "pipelines", pipelineName, "manifest.yml")).Should(BeAnExistingFile())
Expect(filepath.Join(repoName, "copilot", "pipelines", pipelineName, "buildspec.yml")).Should(BeAnExistingFile())
})
It("should push repo changes upstream", func() {
cmd := exec.Command("git", "config", "user.email", "[email protected]")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Dir = repoName
Expect(cmd.Run()).NotTo(HaveOccurred())
cmd = exec.Command("git", "config", "user.name", "e2etest")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Dir = repoName
Expect(cmd.Run()).NotTo(HaveOccurred())
cmd = exec.Command("git", "add", ".")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Dir = repoName
Expect(cmd.Run()).NotTo(HaveOccurred())
cmd = exec.Command("git", "commit", "-m", "first commit")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Dir = repoName
Expect(cmd.Run()).NotTo(HaveOccurred())
cmd = exec.Command("git", "push")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Dir = repoName
Expect(cmd.Run()).NotTo(HaveOccurred())
})
})
Context("when creating the pipeline stack", func() {
It("should start creating the pipeline stack", func() {
_, err := copilot.PipelineDeploy(client.PipelineDeployInput{
Name: pipelineName,
})
Expect(err).NotTo(HaveOccurred())
})
It("should show pipeline details once the stack is created", func() {
type stage struct {
Name string
Category string
}
wantedStages := []stage{
{
Name: "Source",
Category: "Source",
},
{
Name: "Build",
Category: "Build",
},
{
Name: "DeployTo-test",
Category: "Deploy",
},
{
Name: "DeployTo-prod",
Category: "Deploy",
},
}
Eventually(func() error {
out, err := copilot.PipelineShow(client.PipelineShowInput{
Name: pipelineName,
})
switch {
case err != nil:
return err
case out.Name == "":
return fmt.Errorf("pipeline name is empty: %v", out)
case out.Name != pipelineName:
return fmt.Errorf("expected pipeline name %q, got %q", pipelineName, out.Name)
case len(out.Stages) != len(wantedStages):
return fmt.Errorf("pipeline stages do not match: %v", out.Stages)
}
for idx, actualStage := range out.Stages {
if wantedStages[idx].Name != actualStage.Name {
return fmt.Errorf("stage name %s at index %d does not match", actualStage.Name, idx)
}
if wantedStages[idx].Category != actualStage.Category {
return fmt.Errorf("stage category %s at index %d does not match", actualStage.Category, idx)
}
}
return nil
}, "600s", "10s").Should(BeNil())
})
It("should deploy the services to both environments", func() {
type state struct {
Name string
ActionName string
ActionStatus string
}
wantedStates := []state{
{
Name: "Source",
ActionName: fmt.Sprintf("SourceCodeFor-%s", appName),
ActionStatus: "Succeeded",
},
{
Name: "Build",
ActionName: "Build",
ActionStatus: "Succeeded",
},
{
Name: "DeployTo-test",
ActionName: "CreateOrUpdate-frontend-test",
ActionStatus: "Succeeded",
},
{
Name: "DeployTo-prod",
ActionName: "CreateOrUpdate-frontend-prod",
ActionStatus: "Succeeded",
},
}
Eventually(func() error {
out, err := copilot.PipelineStatus(client.PipelineStatusInput{
Name: pipelineName,
})
if err != nil {
return err
}
if len(wantedStates) != len(out.States) {
return fmt.Errorf("len of pipeline states do not match: %v", out.States)
}
for idx, actualState := range out.States {
if wantedStates[idx].Name != actualState.Name {
return fmt.Errorf("state name %s at index %d does not match", actualState.Name, idx)
}
if len(actualState.Actions) != 1 {
return fmt.Errorf("no action yet for state name %s", actualState.Name)
}
if wantedStates[idx].ActionName != actualState.Actions[0].Name {
return fmt.Errorf("action name %v for state %s does not match at index %d", actualState.Actions[0], actualState.Name, idx)
}
if wantedStates[idx].ActionStatus != actualState.Actions[0].Status {
return fmt.Errorf("action status %v for state %s does not match at index %d", actualState.Actions[0], actualState.Name, idx)
}
}
return nil
}, "1200s", "15s").Should(BeNil())
})
})
Context("services should be queryable post-release", func() {
It("services should include a valid URL", func() {
out, err := copilot.SvcShow(&client.SvcShowRequest{
AppName: appName,
Name: "frontend",
})
Expect(err).NotTo(HaveOccurred())
routes := make(map[string]string)
for _, route := range out.Routes {
routes[route.Environment] = route.URL
}
for _, env := range []string{"test", "prod"} {
Eventually(func() (int, error) {
resp, fetchErr := http.Get(routes[env])
return resp.StatusCode, fetchErr
}, "30s", "1s").Should(Equal(200))
}
})
})
})
| 330 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package root_test
import (
"testing"
"github.com/aws/copilot-cli/e2e/internal/client"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var cli *client.CLI
func TestRoot(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Root Suite")
}
var _ = BeforeSuite(func() {
ecsCli, err := client.NewCLI()
cli = ecsCli
Expect(err).NotTo(HaveOccurred())
})
| 26 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package root_test
import (
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Root", func() {
Context("--help", func() {
It("should output help text", func() {
output, err := cli.Help()
Expect(err).NotTo(HaveOccurred())
Expect(output).To(ContainSubstring("Launch and manage containerized applications on AWS."))
Expect(output).To(ContainSubstring("Getting Started"))
Expect(output).To(ContainSubstring("Develop"))
Expect(output).To(ContainSubstring("Release"))
Expect(output).To(ContainSubstring("Settings"))
})
})
Context("--version", func() {
It("should output a valid semantic version", func() {
output, err := cli.Version()
Expect(err).NotTo(HaveOccurred())
// Versions look like copilot version: v0.0.4-34-g133b977
// the extra bit at the end is if the build isn't a tagged release.
Expect(output).To(MatchRegexp(`copilot version: v\d*\.\d*\.\d*.*`))
})
})
})
| 34 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package sidecars_test
import (
"fmt"
"math"
"math/rand"
"testing"
"time"
"github.com/aws/copilot-cli/e2e/internal/client"
"github.com/aws/copilot-cli/e2e/internal/command"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var cli *client.CLI
var aws *client.AWS
var docker *client.Docker
var appName string
var envName string
var svcName string
var sidecarImageURI string
var sidecarRepoName string
// The Sidecars suite runs creates a new service with sidecar containers.
func TestSidecars(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Sidecars Suite")
}
var _ = BeforeSuite(func() {
ecsCli, err := client.NewCLI()
cli = ecsCli
Expect(err).NotTo(HaveOccurred())
aws = client.NewAWS()
docker = client.NewDocker()
appName = fmt.Sprintf("e2e-sidecars-%d", time.Now().Unix())
envName = "test"
svcName = "hello"
sidecarRepoName = fmt.Sprintf("e2e-sidecars-nginx-%d", time.Now().Unix())
})
var _ = AfterSuite(func() {
_, appDeleteErr := cli.AppDelete()
repoDeleteErr := command.Run("aws", []string{"ecr", "delete-repository", "--repository-name", sidecarRepoName, "--force"})
Expect(appDeleteErr).NotTo(HaveOccurred())
Expect(repoDeleteErr).NotTo(HaveOccurred())
})
// exponentialBackoffWithJitter backoff exponentially with jitter based on 200ms base
// component of backoff fixed to ensure minimum total wait time on
// slow targets.
func exponentialBackoffWithJitter(attempt int) {
base := int(math.Pow(2, float64(attempt)))
time.Sleep(time.Duration((rand.Intn(50)*base + base*150) * int(time.Millisecond)))
}
| 60 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package sidecars_test
import (
"fmt"
"io"
"math/rand"
"net/http"
"os"
"strings"
"github.com/aws/copilot-cli/e2e/internal/client"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
const manifest = `# The manifest for the "hello" service.
# Read the full specification for the "Load Balanced Web Service" type at:
# https://aws.github.io/copilot-cli/docs/manifest/lb-web-service/
# Your service name will be used in naming your resources like log groups, ECS services, etc.
name: hello
# The "architecture" of the service you're running.
type: Load Balanced Web Service
image:
# Path to your service's Dockerfile.
build: hello/Dockerfile
# Port exposed through your container to route traffic to it.
port: 3000
depends_on:
nginx: start
env_file: ./magic.env
http:
# Requests to this path will be forwarded to your service.
# To match all requests you can use the "/" path.
path: 'api'
# You can specify a custom health check path. The default is "/"
healthcheck: '/api/health-check'
targetContainer: 'nginx'
# Number of CPU units for the task.
cpu: 256
# Amount of memory in MiB used by the task.
memory: 512
# Number of tasks that should be running in your service.
count: 1
sidecars:
nginx:
port: 80
image: %s # Image URL for sidecar container.
variables:
NGINX_PORT: %s
env_file: ./magic.env
logging:
env_file: ./magic.env
destination:
Name: cloudwatch
region: us-east-1
log_group_name: /copilot/%s
log_stream_prefix: copilot/
`
const nginxPort = "80"
var _ = Describe("sidecars flow", func() {
Context("when creating a new app", Ordered, func() {
var (
initErr error
)
BeforeAll(func() {
_, initErr = cli.AppInit(&client.AppInitRequest{
AppName: appName,
})
})
It("app init succeeds", func() {
Expect(initErr).NotTo(HaveOccurred())
})
It("app init creates an copilot directory", func() {
Expect("./copilot").Should(BeADirectory())
})
It("app ls includes new app", func() {
Eventually(cli.AppList, "30s", "5s").Should(ContainSubstring(appName))
})
It("app show includes app name", func() {
appShowOutput, err := cli.AppShow(appName)
Expect(err).NotTo(HaveOccurred())
Expect(appShowOutput.Name).To(Equal(appName))
Expect(appShowOutput.URI).To(BeEmpty())
})
})
Context("when adding a new environment", Ordered, func() {
var (
testEnvInitErr error
)
BeforeAll(func() {
_, testEnvInitErr = cli.EnvInit(&client.EnvInitRequest{
AppName: appName,
EnvName: envName,
Profile: envName,
})
})
It("env init should succeed", func() {
Expect(testEnvInitErr).NotTo(HaveOccurred())
})
})
Context("when deploying the environment", Ordered, func() {
var envDeployErr error
BeforeAll(func() {
_, envDeployErr = cli.EnvDeploy(&client.EnvDeployRequest{
AppName: appName,
Name: envName,
})
})
It("should succeed", func() {
Expect(envDeployErr).NotTo(HaveOccurred())
})
})
Context("when creating a service", Ordered, func() {
var (
svcInitErr error
)
BeforeAll(func() {
_, svcInitErr = cli.SvcInit(&client.SvcInitRequest{
Name: svcName,
SvcType: "Load Balanced Web Service",
Dockerfile: "./hello/Dockerfile",
SvcPort: "3000",
})
})
It("svc init should succeed", func() {
Expect(svcInitErr).NotTo(HaveOccurred())
})
It("svc init should create svc manifests", func() {
Expect("./copilot/hello/manifest.yml").Should(BeAnExistingFile())
})
It("svc ls should list the service", func() {
svcList, svcListError := cli.SvcList(appName)
Expect(svcListError).NotTo(HaveOccurred())
Expect(len(svcList.Services)).To(Equal(1))
svcsByName := map[string]client.WkldDescription{}
for _, svc := range svcList.Services {
svcsByName[svc.Name] = svc
}
for _, svc := range []string{svcName} {
Expect(svcsByName[svc].AppName).To(Equal(appName))
Expect(svcsByName[svc].Name).To(Equal(svc))
}
})
})
Context("build and push sidecar image to ECR repo", func() {
var uri string
var err error
tag := "vortexstreet"
It("create new ECR repo for sidecar", func() {
uri, err = aws.CreateECRRepo(sidecarRepoName)
Expect(err).NotTo(HaveOccurred(), "create ECR repo for sidecar")
sidecarImageURI = fmt.Sprintf("%s:%s", uri, tag)
})
It("push sidecar image", func() {
var password string
password, err = aws.ECRLoginPassword()
Expect(err).NotTo(HaveOccurred(), "get ecr login password")
err = docker.Login(uri, password)
Expect(err).NotTo(HaveOccurred(), "docker login")
err = docker.Build(sidecarImageURI, "./nginx")
Expect(err).NotTo(HaveOccurred(), "build sidecar image")
err = docker.Push(sidecarImageURI)
Expect(err).NotTo(HaveOccurred(), "push to ECR repo")
})
})
Context("write local manifest and addon files", func() {
var newManifest string
It("overwrite existing manifest", func() {
logGroupName := fmt.Sprintf("%s-test-%s", appName, svcName)
newManifest = fmt.Sprintf(manifest, sidecarImageURI, nginxPort, logGroupName)
err := os.WriteFile("./copilot/hello/manifest.yml", []byte(newManifest), 0644)
Expect(err).NotTo(HaveOccurred(), "overwrite manifest")
})
It("add addons folder for Firelens permissions", func() {
err := os.MkdirAll("./copilot/hello/addons", 0777)
Expect(err).NotTo(HaveOccurred(), "create addons dir")
fds, err := os.ReadDir("./hello/addons")
Expect(err).NotTo(HaveOccurred(), "read addons dir")
for _, fd := range fds {
func() {
destFile, err := os.Create(fmt.Sprintf("./copilot/hello/addons/%s", fd.Name()))
Expect(err).NotTo(HaveOccurred(), "create destination file")
defer destFile.Close()
srcFile, err := os.Open(fmt.Sprintf("./hello/addons/%s", fd.Name()))
Expect(err).NotTo(HaveOccurred(), "open source file")
defer srcFile.Close()
_, err = io.Copy(destFile, srcFile)
Expect(err).NotTo(HaveOccurred(), "copy file")
}()
}
})
})
Context("when deploying svc", Ordered, func() {
var (
appDeployErr error
)
BeforeAll(func() {
_, appDeployErr = cli.SvcDeploy(&client.SvcDeployInput{
Name: svcName,
EnvName: envName,
ImageTag: "gallopinggurdey",
})
})
It("svc deploy should succeed", func() {
Expect(appDeployErr).NotTo(HaveOccurred())
})
It("svc show should include a valid URL and description for test env", func() {
svc, svcShowErr := cli.SvcShow(&client.SvcShowRequest{
AppName: appName,
Name: svcName,
})
Expect(svcShowErr).NotTo(HaveOccurred())
Expect(len(svc.Routes)).To(Equal(1))
// Call each environment's endpoint and ensure it returns a 200
route := svc.Routes[0]
Expect(route.Environment).To(Equal(envName))
uri := route.URL + "/health-check"
// Service should be ready.
resp := &http.Response{}
var fetchErr error
Eventually(func() (int, error) {
resp, fetchErr = http.Get(uri)
return resp.StatusCode, fetchErr
}, "30s", "1s").Should(Equal(200))
// Read the response - our deployed apps should return a body with their
// name as the value.
bodyBytes, err := io.ReadAll(resp.Body)
Expect(err).NotTo(HaveOccurred())
Expect(string(bodyBytes)).To(Equal("Ready"))
})
It("should have env file in sidecar definitions", func() {
taskDefinitionName := fmt.Sprintf("%s-%s-%s", appName, envName, svcName)
envFiles, err := aws.GetEnvFilesFromTaskDefinition(taskDefinitionName)
Expect(err).NotTo(HaveOccurred())
Expect(envFiles).To(HaveKey(svcName))
Expect(envFiles).To(HaveKey("nginx"))
Expect(envFiles).To(HaveKey("firelens_log_router"))
})
It("svc logs should display logs", func() {
var firelensCreated bool
var svcLogs []client.SvcLogsOutput
var svcLogsErr error
for i := 0; i < 10; i++ {
svcLogs, svcLogsErr = cli.SvcLogs(&client.SvcLogsRequest{
AppName: appName,
Name: svcName,
EnvName: envName,
Since: "1h",
})
if svcLogsErr != nil {
exponentialBackoffWithJitter(i)
continue
}
for _, logLine := range svcLogs {
if strings.Contains(logLine.LogStreamName, fmt.Sprintf("copilot/%s-firelens-", svcName)) {
firelensCreated = true
}
}
if firelensCreated {
break
}
exponentialBackoffWithJitter(i)
}
Expect(svcLogsErr).NotTo(HaveOccurred())
Expect(firelensCreated).To(Equal(true))
// Randomly check if a log line is valid.
logLine := rand.Intn(len(svcLogs))
Expect(svcLogs[logLine].Message).NotTo(Equal(""))
Expect(svcLogs[logLine].LogStreamName).NotTo(Equal(""))
Expect(svcLogs[logLine].Timestamp).NotTo(Equal(0))
Expect(svcLogs[logLine].IngestionTime).NotTo(Equal(0))
})
})
})
| 313 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package static_site_test
import (
"fmt"
"os"
"testing"
"time"
"github.com/aws/copilot-cli/e2e/internal/client"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var cli *client.CLI
var appName string
const domainName = "static-site.copilot-e2e-tests.ecs.aws.dev"
var timeNow = time.Now().Unix()
func TestStaticSite(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Static Site Suite")
}
var _ = BeforeSuite(func() {
copilotCLI, err := client.NewCLI()
Expect(err).NotTo(HaveOccurred())
cli = copilotCLI
appName = fmt.Sprintf("t%d", timeNow)
err = os.Setenv("DOMAINNAME", domainName)
Expect(err).NotTo(HaveOccurred())
})
var _ = AfterSuite(func() {})
| 39 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package static_site_test
import (
"fmt"
"io"
"net/http"
"strings"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/aws/copilot-cli/e2e/internal/client"
)
var _ = Describe("Static Site", func() {
Context("when creating a new app", Ordered, func() {
var appInitErr error
BeforeAll(func() {
_, appInitErr = cli.AppInit(&client.AppInitRequest{
AppName: appName,
Domain: domainName,
})
})
It("app init succeeds", func() {
Expect(appInitErr).NotTo(HaveOccurred())
})
It("app init creates a copilot directory", func() {
Expect("./copilot").Should(BeADirectory())
})
It("app ls includes new application", func() {
Eventually(cli.AppList, "30s", "5s").Should(ContainSubstring(appName))
})
It("app show includes domain name", func() {
appShowOutput, err := cli.AppShow(appName)
Expect(err).NotTo(HaveOccurred())
Expect(appShowOutput.Name).To(Equal(appName))
Expect(appShowOutput.URI).To(Equal(domainName))
})
})
Context("when adding new environment", Ordered, func() {
var err error
BeforeAll(func() {
_, err = cli.EnvInit(&client.EnvInitRequest{
AppName: appName,
EnvName: "test",
Profile: "test",
})
})
It("env init should succeed", func() {
Expect(err).NotTo(HaveOccurred())
})
})
Context("when deploying the environments", Ordered, func() {
var envDeployErr error
BeforeAll(func() {
_, envDeployErr = cli.EnvDeploy(&client.EnvDeployRequest{
AppName: appName,
Name: "test",
})
})
It("env deploy should succeed", func() {
Expect(envDeployErr).NotTo(HaveOccurred())
})
})
Context("when initializing Static Site", Ordered, func() {
var svcInitErr error
BeforeAll(func() {
_, svcInitErr = cli.SvcInit(&client.SvcInitRequest{
Name: "svc",
SvcType: "Static Site",
})
})
It("svc init should succeed", func() {
Expect(svcInitErr).NotTo(HaveOccurred())
})
})
Context("when deploying a Static Site", Ordered, func() {
It("deployment should succeed", func() {
_, err := cli.SvcDeploy(&client.SvcDeployInput{
Name: "svc",
EnvName: "test",
})
Expect(err).NotTo(HaveOccurred())
})
It("svc show should contain the expected domain and the request should succeed", func() {
svc, err := cli.SvcShow(&client.SvcShowRequest{
Name: "svc",
AppName: appName,
})
Expect(err).NotTo(HaveOccurred())
Expect(len(svc.Routes)).To(Equal(1))
route := svc.Routes[0]
wantedURLs := map[string]string{
"test": fmt.Sprintf("https://v1.%s", domainName),
}
// Validate route has the expected HTTPS endpoint.
Expect(route.URL).To(ContainSubstring(wantedURLs[route.Environment]))
url := wantedURLs[route.Environment]
// Make sure the service response is OK.
var resp *http.Response
var fetchErr error
resp, fetchErr = http.Get(url)
Expect(fetchErr).NotTo(HaveOccurred())
Expect(resp.StatusCode).To(Equal(200))
bodyBytes, err := io.ReadAll(resp.Body)
Expect(err).NotTo(HaveOccurred())
Expect(string(bodyBytes)).To(Equal("hello"))
// HTTP should work.
resp, fetchErr = http.Get(strings.Replace(url, "https", "http", 1))
Expect(fetchErr).NotTo(HaveOccurred())
Expect(resp.StatusCode).To(Equal(200))
// Make sure we route to index.html for sub-path.
resp, fetchErr = http.Get(fmt.Sprintf("%s/static", url))
Expect(fetchErr).NotTo(HaveOccurred())
Expect(resp.StatusCode).To(Equal(200))
bodyBytes, err = io.ReadAll(resp.Body)
Expect(err).NotTo(HaveOccurred())
Expect(string(bodyBytes)).To(Equal("bye"))
})
})
Context("when deleting the app", Ordered, func() {
var appDeleteErr error
BeforeAll(func() {
_, appDeleteErr = cli.AppDelete()
})
It("app delete should succeed", func() {
Expect(appDeleteErr).NotTo(HaveOccurred())
})
})
})
| 148 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package task
import (
"fmt"
"testing"
"time"
"github.com/aws/copilot-cli/e2e/internal/client"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var cli *client.CLI
var aws *client.AWS
var appName, envName, groupName, taskStackName, repoName string
/**
The task suite runs through several tests focusing on running one-off tasks with different configurations.
*/
func TestTask(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Task Suite")
}
var _ = BeforeSuite(func() {
ecsCli, err := client.NewCLI()
cli = ecsCli
Expect(err).NotTo(HaveOccurred())
aws = client.NewAWS()
appName = fmt.Sprintf("e2e-task-%d", time.Now().Unix())
envName = "test"
groupName = fmt.Sprintf("e2e-task-%d", time.Now().Unix())
// We name task stack in format of "task-${groupName}".
// See https://github.com/aws/copilot-cli/blob/e9e3114561e740c367fb83b5e075750f232ad639/internal/pkg/deploy/cloudformation/stack/name.go#L26.
taskStackName = fmt.Sprintf("task-%s", groupName)
// We name ECR repo name in format of "copilot-${groupName}".
// See https://github.com/aws/copilot-cli/blob/e9e3114561e740c367fb83b5e075750f232ad639/templates/task/cf.yml#L75.
repoName = fmt.Sprintf("copilot-%s", groupName)
})
var _ = AfterSuite(func() {
_, err := cli.TaskDelete(&client.TaskDeleteInput{
App: appName,
Env: envName,
Name: groupName,
Default: false,
})
Expect(err).NotTo(HaveOccurred(), "delete task")
_, err = cli.AppDelete()
Expect(err).NotTo(HaveOccurred(), "delete Copilot application")
})
| 56 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package task
import (
"github.com/aws/copilot-cli/e2e/internal/client"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Task", func() {
Context("when creating a new app", Ordered, func() {
var err error
BeforeAll(func() {
_, err = cli.AppInit(&client.AppInitRequest{
AppName: appName,
})
})
It("app init succeeds", func() {
Expect(err).NotTo(HaveOccurred())
})
})
Context("when adding a new environment", Ordered, func() {
var (
err error
)
BeforeAll(func() {
_, err = cli.EnvInit(&client.EnvInitRequest{
AppName: appName,
EnvName: envName,
Profile: envName,
})
})
It("env init should succeed", func() {
Expect(err).NotTo(HaveOccurred())
})
})
Context("when deploying the environment", Ordered, func() {
var envDeployErr error
BeforeAll(func() {
_, envDeployErr = cli.EnvDeploy(&client.EnvDeployRequest{
AppName: appName,
Name: envName,
})
})
It("should succeed", func() {
Expect(envDeployErr).NotTo(HaveOccurred())
})
})
Context("when running in an environment", Ordered, func() {
var err error
BeforeAll(func() {
_, err = cli.TaskRun(&client.TaskRunInput{
GroupName: groupName,
Dockerfile: "./backend/Dockerfile",
AppName: appName,
Env: envName,
})
})
It("should succeed", func() {
Expect(err).NotTo(HaveOccurred())
})
})
Context("when running in default cluster and subnets", Ordered, func() {
var err error
var taskLogs string
BeforeAll(func() {
taskLogs, err = cli.TaskRun(&client.TaskRunInput{
GroupName: groupName,
Dockerfile: "./backend/Dockerfile",
Default: true,
Follow: true,
})
})
It("should succeed", func() {
Expect(err).NotTo(HaveOccurred())
})
It("task running", func() {
Expect(taskLogs).To(ContainSubstring("e2e success: task running."))
})
})
Context("when running in specific subnets and security groups", func() {
It("should succeed", func() {
Skip("Not implemented yet")
})
It("task running", func() {
Skip("Test is not implemented yet")
})
})
Context("when running with command and environment variables", Ordered, func() {
var err error
var taskLogs string
BeforeAll(func() {
taskLogs, err = cli.TaskRun(&client.TaskRunInput{
GroupName: groupName,
Dockerfile: "./backend/Dockerfile",
Command: "/bin/sh check_override.sh",
EnvVars: "STATUS=OVERRIDDEN",
Default: true,
Follow: true,
})
})
It("should succeed", func() {
Expect(err).NotTo(HaveOccurred())
})
It("environment variables overridden", func() {
Expect(taskLogs).To(ContainSubstring("e2e environment variables: OVERRIDDEN"))
})
})
Context("when running with an image", func() {
It("should succeed", func() {
Skip("Not implemented yet")
})
It("task running", func() {
Skip("Test is not implemented yet")
})
})
})
| 145 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package worker_test
import (
"fmt"
"testing"
"time"
"github.com/aws/copilot-cli/e2e/internal/client"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var (
cli *client.CLI
appName string
)
const (
lbwsServiceName = "frontend"
workerServiceName = "worker"
counterServiceName = "counter"
envName = "test"
)
func TestWorker(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Worker Service Suite")
}
var _ = BeforeSuite(func() {
var err error
cli, err = client.NewCLI()
Expect(err).NotTo(HaveOccurred())
appName = fmt.Sprintf("e2e-worker-%d", time.Now().Unix())
})
var _ = AfterSuite(func() {
_, err := cli.AppDelete()
Expect(err).NotTo(HaveOccurred())
})
| 45 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package worker_test
import (
"errors"
"fmt"
"io"
"net/http"
"os"
"strconv"
"github.com/aws/copilot-cli/e2e/internal/client"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Worker Service E2E Test", func() {
Context("create an application", func() {
It("app init succeeds", func() {
_, err := cli.AppInit(&client.AppInitRequest{
AppName: appName,
})
Expect(err).NotTo(HaveOccurred())
})
It("app init creates a copilot directory", func() {
Expect("./copilot").Should(BeADirectory())
})
It("app show includes app name", func() {
appShowOutput, err := cli.AppShow(appName)
Expect(err).NotTo(HaveOccurred())
Expect(appShowOutput.Name).To(Equal(appName))
Expect(appShowOutput.URI).To(BeEmpty())
})
})
Context("add an environment", func() {
It("env init should succeed", func() {
_, err := cli.EnvInit(&client.EnvInitRequest{
AppName: appName,
EnvName: envName,
Profile: envName,
})
Expect(err).NotTo(HaveOccurred())
})
})
Context("when deploying the environment", func() {
It("env deploy should succeed", func() {
_, err := cli.EnvDeploy(&client.EnvDeployRequest{
AppName: appName,
Name: envName,
})
Expect(err).NotTo(HaveOccurred())
})
})
Context("create a load balanced web service", func() {
It("svc init should succeed", func() {
_, err := cli.SvcInit(&client.SvcInitRequest{
Name: lbwsServiceName,
SvcType: "Load Balanced Web Service",
Dockerfile: "./frontend/Dockerfile",
})
Expect(err).NotTo(HaveOccurred())
})
It("adds a topic to push to the service", func() {
Expect("./copilot/frontend/manifest.yml").Should(BeAnExistingFile())
f, err := os.OpenFile("./copilot/frontend/manifest.yml", os.O_APPEND|os.O_WRONLY, 0644)
Expect(err).NotTo(HaveOccurred())
defer f.Close()
// Append publish section to manifest.
_, err = f.WriteString(`
publish:
topics:
- name: events
`)
Expect(err).NotTo(HaveOccurred())
})
It("deploys the load balanced web service", func() {
_, err := cli.SvcDeploy(&client.SvcDeployInput{
Name: lbwsServiceName,
EnvName: envName,
ImageTag: "gallopinggurdey",
})
Expect(err).NotTo(HaveOccurred())
})
})
Context("deploys the worker service", func() {
It("svc init should succeed", func() {
_, err := cli.SvcInit(&client.SvcInitRequest{
Name: workerServiceName,
SvcType: "Worker Service",
Dockerfile: "./worker/Dockerfile",
TopicSubscriptions: []string{fmt.Sprintf("%s:%s", lbwsServiceName, "events")},
})
Expect(err).NotTo(HaveOccurred())
})
It("adds a topic to push to the service", func() {
Expect("./copilot/worker/manifest.yml").Should(BeAnExistingFile())
f, err := os.OpenFile("./copilot/worker/manifest.yml", os.O_APPEND|os.O_WRONLY, 0644)
Expect(err).NotTo(HaveOccurred())
defer f.Close()
// Append publish section to manifest.
_, err = f.WriteString(`
publish:
topics:
- name: processed-msg-count
`)
Expect(err).NotTo(HaveOccurred())
})
It("deploys the worker service", func() {
_, err := cli.SvcDeploy(&client.SvcDeployInput{
Name: workerServiceName,
EnvName: envName,
ImageTag: "gallopinggurdey",
})
Expect(err).NotTo(HaveOccurred())
})
It("should have the SQS queue and service discovery injected as env vars", func() {
svc, err := cli.SvcShow(&client.SvcShowRequest{
AppName: appName,
Name: workerServiceName,
})
Expect(err).NotTo(HaveOccurred())
var hasQueueURI bool
var svcDiscovery bool
var hasTopic bool
for _, envVar := range svc.Variables {
switch envVar.Name {
case "COPILOT_QUEUE_URI":
hasQueueURI = true
case "COPILOT_SERVICE_DISCOVERY_ENDPOINT":
svcDiscovery = true
case "COPILOT_SNS_TOPIC_ARNS":
hasTopic = true
}
}
if !hasQueueURI {
Expect(errors.New("worker service is missing env var 'COPILOT_QUEUE_URI'")).NotTo(HaveOccurred())
}
if !svcDiscovery {
Expect(errors.New("worker service is missing env var 'COPILOT_SERVICE_DISCOVERY_ENDPOINT'")).NotTo(HaveOccurred())
}
if !hasTopic {
Expect(errors.New("worker service is missing env var 'COPILOT_SNS_TOPIC_ARNS'")).NotTo(HaveOccurred())
}
})
})
Context("deploys the counter service", func() {
It("svc init should succeed", func() {
_, err := cli.SvcInit(&client.SvcInitRequest{
Name: counterServiceName,
SvcType: "Worker Service",
Dockerfile: "./counter/Dockerfile",
TopicSubscriptions: []string{fmt.Sprintf("%s:%s", workerServiceName, "processed-msg-count")},
})
Expect(err).NotTo(HaveOccurred())
})
It("deploys the counter service", func() {
_, err := cli.SvcDeploy(&client.SvcDeployInput{
Name: counterServiceName,
EnvName: envName,
ImageTag: "gallopinggurdey",
})
Expect(err).NotTo(HaveOccurred())
})
It("should have the SQS queue and service discovery injected as env vars", func() {
svc, err := cli.SvcShow(&client.SvcShowRequest{
AppName: appName,
Name: workerServiceName,
})
Expect(err).NotTo(HaveOccurred())
var hasQueueURI bool
var svcDiscovery bool
for _, envVar := range svc.Variables {
switch envVar.Name {
case "COPILOT_QUEUE_URI":
hasQueueURI = true
case "COPILOT_SERVICE_DISCOVERY_ENDPOINT":
svcDiscovery = true
}
}
if !hasQueueURI {
Expect(errors.New("worker service is missing env var 'COPILOT_QUEUE_URI'")).NotTo(HaveOccurred())
}
if !svcDiscovery {
Expect(errors.New("worker service is missing env var 'COPILOT_SERVICE_DISCOVERY_ENDPOINT'")).NotTo(HaveOccurred())
}
})
})
Context("should have consumed messages", func() {
It("frontend service should have received acknowledgement", func() {
svc, err := cli.SvcShow(&client.SvcShowRequest{
AppName: appName,
Name: lbwsServiceName,
})
Expect(err).NotTo(HaveOccurred())
Expect(len(svc.Routes)).To(Equal(1))
route := svc.Routes[0]
Expect(route.Environment).To(Equal(envName))
Eventually(func() error {
resp, err := http.Get(fmt.Sprintf("%s/status", route.URL))
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("response status is %d and not %d", resp.StatusCode, http.StatusOK)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
fmt.Printf("response: %s\n", string(body))
// The LBWS sets its state to "consumed" when the worker service processes a message
if string(body) != "consumed" {
return fmt.Errorf("the message content is '%s', but expected '%s'", string(body), "consumed")
}
return nil
}, "60s", "1s").ShouldNot(HaveOccurred())
})
It("frontend service should eventually have at least 5 message consumed", func() {
svc, err := cli.SvcShow(&client.SvcShowRequest{
AppName: appName,
Name: lbwsServiceName,
})
Expect(err).NotTo(HaveOccurred())
Expect(len(svc.Routes)).To(Equal(1))
route := svc.Routes[0]
Expect(route.Environment).To(Equal(envName))
Eventually(func() error {
resp, err := http.Get(fmt.Sprintf("%s/count", route.URL))
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("response status is %d and not %d", resp.StatusCode, http.StatusOK)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
fmt.Printf("response: %s\n", string(body))
// The counter service add to the counter when the worker service processes a message
count, _ := strconv.Atoi(string(body))
if count < 5 {
return fmt.Errorf("the counter is %v, but expected to be at least %v", count, 5)
}
return nil
}, "100s", "10s").ShouldNot(HaveOccurred())
})
})
})
| 272 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package addon contains the service to manage addons.
package addon
import (
"fmt"
"path/filepath"
"strconv"
"strings"
"github.com/dustin/go-humanize/english"
"gopkg.in/yaml.v3"
)
const (
// StackName is the name of the addons nested stack resource.
StackName = "AddonsStack"
)
var (
wkldAddonsParameterReservedKeys = []string{"App", "Env", "Name"}
envAddonsParameterReservedKeys = []string{"App", "Env"}
)
var (
yamlExtensions = []string{".yaml", ".yml"}
parameterFileNames = func() []string {
const paramFilePrefix = "addons.parameters"
var fnames []string
for _, ext := range yamlExtensions {
fnames = append(fnames, fmt.Sprintf("%s%s", paramFilePrefix, ext))
}
return fnames
}()
)
// WorkspaceAddonsReader finds and reads addons from a workspace.
type WorkspaceAddonsReader interface {
WorkloadAddonsAbsPath(name string) string
WorkloadAddonFileAbsPath(wkldName, fName string) string
EnvAddonsAbsPath() string
EnvAddonFileAbsPath(fName string) string
ListFiles(dirPath string) ([]string, error)
ReadFile(fPath string) ([]byte, error)
}
// WorkloadStack represents a CloudFormation stack for workload addons.
type WorkloadStack struct {
stack
workloadName string
}
// EnvironmentStack represents a CloudFormation stack for environment addons.
type EnvironmentStack struct {
stack
}
type stack struct {
template *cfnTemplate
parameters yaml.Node
}
type parser struct {
ws WorkspaceAddonsReader
addonsDirPath func() string
addonsFilePath func(fName string) string
validateParameters func(tplParams, customParams yaml.Node) error
}
// ParseFromWorkload parses the 'addon/' directory for the given workload
// and returns a Stack created by merging the CloudFormation templates
// files found there. If no addons are found, ParseFromWorkload returns a nil
// Stack and ErrAddonsNotFound.
func ParseFromWorkload(workloadName string, ws WorkspaceAddonsReader) (*WorkloadStack, error) {
parser := parser{
ws: ws,
addonsDirPath: func() string {
return ws.WorkloadAddonsAbsPath(workloadName)
},
addonsFilePath: func(fName string) string {
return ws.WorkloadAddonFileAbsPath(workloadName, fName)
},
validateParameters: func(tplParams, customParams yaml.Node) error {
return validateParameters(tplParams, customParams, wkldAddonsParameterReservedKeys)
},
}
stack, err := parser.stack()
if err != nil {
return nil, err
}
return &WorkloadStack{
stack: *stack,
workloadName: workloadName,
}, nil
}
// ParseFromEnv parses the 'addon/' directory for environments
// and returns a Stack created by merging the CloudFormation templates
// files found there. If no addons are found, ParseFromWorkload returns a nil
// Stack and ErrAddonsNotFound.
func ParseFromEnv(ws WorkspaceAddonsReader) (*EnvironmentStack, error) {
parser := parser{
ws: ws,
addonsDirPath: ws.EnvAddonsAbsPath,
addonsFilePath: ws.EnvAddonFileAbsPath,
validateParameters: func(tplParams, customParams yaml.Node) error {
return validateParameters(tplParams, customParams, envAddonsParameterReservedKeys)
},
}
stack, err := parser.stack()
if err != nil {
return nil, err
}
return &EnvironmentStack{
stack: *stack,
}, nil
}
// Template returns Stack's CloudFormation template as a yaml string.
func (s *stack) Template() (string, error) {
if s.template == nil {
return "", nil
}
return s.encode(s.template)
}
// Parameters returns Stack's CloudFormation parameters as a yaml string.
func (s *stack) Parameters() (string, error) {
if s.parameters.IsZero() {
return "", nil
}
return s.encode(s.parameters)
}
// encode encodes v as a yaml string indented with 2 spaces.
func (s *stack) encode(v any) (string, error) {
str := &strings.Builder{}
enc := yaml.NewEncoder(str)
enc.SetIndent(2)
if err := enc.Encode(v); err != nil {
return "", err
}
return str.String(), nil
}
func (p *parser) stack() (*stack, error) {
path := p.addonsDirPath()
fNames, err := p.ws.ListFiles(path)
if err != nil {
return nil, fmt.Errorf("list addons under path %s: %w", path, &ErrAddonsNotFound{
ParentErr: err,
})
}
template, err := p.parseTemplate(fNames)
if err != nil {
return nil, err
}
params, err := p.parseParameters(fNames)
if err != nil {
return nil, err
}
if err := p.validateParameters(template.Parameters, params); err != nil {
return nil, err
}
return &stack{
template: template,
parameters: params,
}, nil
}
// parseTemplate merges CloudFormation templates under the "addons/" directory into a single CloudFormation
// template and returns it.
//
// If the addons directory doesn't exist or no yaml files are found in
// the addons directory, it returns the empty string and
// ErrAddonsNotFound.
func (p *parser) parseTemplate(fNames []string) (*cfnTemplate, error) {
templateFiles := filterFiles(fNames, yamlMatcher, nonParamsMatcher)
if len(templateFiles) == 0 {
return nil, &ErrAddonsNotFound{}
}
mergedTemplate := newCFNTemplate("merged")
for _, fname := range templateFiles {
path := p.addonsFilePath(fname)
out, err := p.ws.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("read addons file %q under path %s: %w", fname, path, err)
}
tpl := newCFNTemplate(fname)
if err := yaml.Unmarshal(out, tpl); err != nil {
return nil, fmt.Errorf("unmarshal addon %s under path %s: %w", fname, path, err)
}
if err := mergedTemplate.merge(tpl); err != nil {
return nil, err
}
}
return mergedTemplate, nil
}
// parseParameters returns the content of user-defined additional CloudFormation Parameters
// to pass from the parent stack to Template.
//
// If there are addons but no parameters file defined, then returns "" and nil for error.
// If there are multiple parameters files, then returns "" and cannot define multiple parameter files error.
// If the addons parameters use the reserved parameter names, then returns "" and a reserved parameter error.
func (p *parser) parseParameters(fNames []string) (yaml.Node, error) {
paramFiles := filterFiles(fNames, paramsMatcher)
if len(paramFiles) == 0 {
return yaml.Node{}, nil
}
if len(paramFiles) > 1 {
return yaml.Node{}, fmt.Errorf("defining %s is not allowed under addons/", english.WordSeries(parameterFileNames, "and"))
}
paramFile := paramFiles[0]
path := p.addonsFilePath(paramFile)
raw, err := p.ws.ReadFile(path)
if err != nil {
return yaml.Node{}, fmt.Errorf("read parameter file %s under path %s: %w", paramFile, path, err)
}
content := struct {
Parameters yaml.Node `yaml:"Parameters"`
}{}
if err := yaml.Unmarshal(raw, &content); err != nil {
return yaml.Node{}, fmt.Errorf("unmarshal 'Parameters' in file %s: %w", paramFile, err)
}
if content.Parameters.IsZero() {
return yaml.Node{}, fmt.Errorf("must define field 'Parameters' in file %s under path %s", paramFile, path)
}
return content.Parameters, nil
}
func validateParameters(tplParamsNode, customParamsNode yaml.Node, reservedKeys []string) error {
customParams := make(map[string]yaml.Node)
if err := customParamsNode.Decode(customParams); err != nil {
return fmt.Errorf("decode \"Parameters\" section of the parameters file: %w", err)
}
tplParams := make(map[string]yaml.Node)
if err := tplParamsNode.Decode(tplParams); err != nil {
return fmt.Errorf("decode \"Parameters\" section of the template file: %w", err)
}
// The reserved keys should be present/absent in the template/parameters file.
for _, k := range reservedKeys {
if _, ok := tplParams[k]; !ok {
return fmt.Errorf("required parameter %q is missing from the template", k)
}
if _, ok := customParams[k]; ok {
return fmt.Errorf("reserved parameters %s cannot be declared", english.WordSeries(quoteSlice(reservedKeys), "and"))
}
customParams[k] = yaml.Node{}
}
for k := range customParams {
if _, ok := tplParams[k]; !ok {
return fmt.Errorf("template does not require the parameter %q in parameters file", k)
}
}
type parameter struct {
Default yaml.Node `yaml:"Default"`
}
for k, v := range tplParams {
var p parameter
if err := v.Decode(&p); err != nil {
return fmt.Errorf("error decoding: %w", err)
}
if !p.Default.IsZero() {
continue
}
if _, ok := customParams[k]; !ok {
return fmt.Errorf("parameter %q in template must have a default value or is included in parameters file", k)
}
}
return nil
}
func filterFiles(files []string, matchers ...func(string) bool) []string {
var matchedFiles []string
for _, f := range files {
matches := true
for _, match := range matchers {
if !match(f) {
matches = false
break
}
}
if matches {
matchedFiles = append(matchedFiles, f)
}
}
return matchedFiles
}
func yamlMatcher(fileName string) bool {
return contains(yamlExtensions, filepath.Ext(fileName))
}
func paramsMatcher(fileName string) bool {
return contains(parameterFileNames, fileName)
}
func nonParamsMatcher(fileName string) bool {
return !paramsMatcher(fileName)
}
func contains(arr []string, el string) bool {
for _, item := range arr {
if item == el {
return true
}
}
return false
}
func quoteSlice(elems []string) []string {
if len(elems) == 0 {
return nil
}
quotedElems := make([]string, len(elems))
for i, el := range elems {
quotedElems[i] = strconv.Quote(el)
}
return quotedElems
}
| 329 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package addon
import (
"errors"
"fmt"
"os"
"path/filepath"
"testing"
"github.com/aws/copilot-cli/internal/pkg/addon/mocks"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
"gopkg.in/yaml.v3"
)
func TestWorkload_Template(t *testing.T) {
const (
testSvcName = "mysvc"
testJobName = "resizer"
)
testErr := errors.New("some error")
testCases := map[string]struct {
workloadName string
setupMocks func(m addonMocks)
wantedTemplate string
wantedErr error
wantedAddonsNotFoundError bool
}{
"return ErrAddonsNotFound if addons doesn't exist in a service": {
workloadName: testSvcName,
setupMocks: func(m addonMocks) {
m.ws.EXPECT().WorkloadAddonsAbsPath(testSvcName).Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return(nil, testErr)
},
wantedErr: fmt.Errorf("list addons under path mockPath: %w", &ErrAddonsNotFound{
ParentErr: testErr,
}),
},
"return ErrAddonsNotFound if addons doesn't exist in a job": {
workloadName: testJobName,
setupMocks: func(m addonMocks) {
m.ws.EXPECT().WorkloadAddonsAbsPath(testJobName).Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return(nil, testErr)
},
wantedErr: fmt.Errorf("list addons under path mockPath: %w", &ErrAddonsNotFound{
ParentErr: testErr,
}),
},
"return ErrAddonsNotFound if addons directory is empty in a service": {
workloadName: testSvcName,
setupMocks: func(m addonMocks) {
m.ws.EXPECT().WorkloadAddonsAbsPath(testSvcName).Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return([]string{}, nil)
},
wantedErr: &ErrAddonsNotFound{
ParentErr: nil,
},
},
"return ErrAddonsNotFound if addons directory does not contain yaml files in a service": {
workloadName: testSvcName,
setupMocks: func(m addonMocks) {
m.ws.EXPECT().WorkloadAddonsAbsPath(testSvcName).Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return([]string{"gitkeep"}, nil)
},
wantedErr: &ErrAddonsNotFound{
ParentErr: nil,
},
},
"ignore addons.parameters.yml files": {
workloadName: testSvcName,
setupMocks: func(m addonMocks) {
m.ws.EXPECT().WorkloadAddonsAbsPath(testSvcName).Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return([]string{"addons.parameters.yml", "addons.parameters.yaml"}, nil)
},
wantedErr: &ErrAddonsNotFound{
ParentErr: nil,
},
},
"return err on invalid Metadata fields": {
workloadName: testSvcName,
setupMocks: func(m addonMocks) {
m.ws.EXPECT().WorkloadAddonsAbsPath(testSvcName).Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return([]string{"first.yaml", "invalid-metadata.yaml"}, nil)
first, _ := os.ReadFile(filepath.Join("testdata", "merge", "first.yaml"))
m.ws.EXPECT().WorkloadAddonFileAbsPath(testSvcName, "first.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(first, nil)
second, _ := os.ReadFile(filepath.Join("testdata", "merge", "invalid-metadata.yaml"))
m.ws.EXPECT().WorkloadAddonFileAbsPath(testSvcName, "invalid-metadata.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(second, nil)
},
wantedErr: errors.New(`metadata key "Services" defined in "first.yaml" at Ln 4, Col 7 is different than in "invalid-metadata.yaml" at Ln 3, Col 5`),
},
"returns err on invalid Parameters fields": {
workloadName: testSvcName,
setupMocks: func(m addonMocks) {
m.ws.EXPECT().WorkloadAddonsAbsPath(testSvcName).Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return([]string{"first.yaml", "invalid-parameters.yaml"}, nil)
first, _ := os.ReadFile(filepath.Join("testdata", "merge", "first.yaml"))
m.ws.EXPECT().WorkloadAddonFileAbsPath(testSvcName, "first.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(first, nil)
second, _ := os.ReadFile(filepath.Join("testdata", "merge", "invalid-parameters.yaml"))
m.ws.EXPECT().WorkloadAddonFileAbsPath(testSvcName, "invalid-parameters.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(second, nil)
},
wantedErr: errors.New(`parameter logical ID "Name" defined in "first.yaml" at Ln 15, Col 9 is different than in "invalid-parameters.yaml" at Ln 3, Col 7`),
},
"returns err on invalid Mappings fields": {
workloadName: testSvcName,
setupMocks: func(m addonMocks) {
m.ws.EXPECT().WorkloadAddonsAbsPath(testSvcName).Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return([]string{"first.yaml", "invalid-mappings.yaml"}, nil)
first, _ := os.ReadFile(filepath.Join("testdata", "merge", "first.yaml"))
m.ws.EXPECT().WorkloadAddonFileAbsPath(testSvcName, "first.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(first, nil)
second, _ := os.ReadFile(filepath.Join("testdata", "merge", "invalid-mappings.yaml"))
m.ws.EXPECT().WorkloadAddonFileAbsPath(testSvcName, "invalid-mappings.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(second, nil)
},
wantedErr: errors.New(`mapping "MyTableDynamoDBSettings.test" defined in "first.yaml" at Ln 21, Col 13 is different than in "invalid-mappings.yaml" at Ln 4, Col 7`),
},
"returns err on invalid Conditions fields": {
workloadName: testSvcName,
setupMocks: func(m addonMocks) {
m.ws.EXPECT().WorkloadAddonsAbsPath(testSvcName).Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return([]string{"first.yaml", "invalid-conditions.yaml"}, nil)
first, _ := os.ReadFile(filepath.Join("testdata", "merge", "first.yaml"))
m.ws.EXPECT().WorkloadAddonFileAbsPath(testSvcName, "first.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(first, nil)
second, _ := os.ReadFile(filepath.Join("testdata", "merge", "invalid-conditions.yaml"))
m.ws.EXPECT().WorkloadAddonFileAbsPath(testSvcName, "invalid-conditions.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(second, nil)
},
wantedErr: errors.New(`condition "IsProd" defined in "first.yaml" at Ln 28, Col 13 is different than in "invalid-conditions.yaml" at Ln 2, Col 13`),
},
"returns err on invalid Resources fields": {
workloadName: testSvcName,
setupMocks: func(m addonMocks) {
m.ws.EXPECT().WorkloadAddonsAbsPath(testSvcName).Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return([]string{"first.yaml", "invalid-resources.yaml"}, nil)
first, _ := os.ReadFile(filepath.Join("testdata", "merge", "first.yaml"))
m.ws.EXPECT().WorkloadAddonFileAbsPath(testSvcName, "first.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(first, nil)
second, _ := os.ReadFile(filepath.Join("testdata", "merge", "invalid-resources.yaml"))
m.ws.EXPECT().WorkloadAddonFileAbsPath(testSvcName, "invalid-resources.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(second, nil)
},
wantedErr: errors.New(`resource "MyTable" defined in "first.yaml" at Ln 34, Col 9 is different than in "invalid-resources.yaml" at Ln 3, Col 5`),
},
"returns err on invalid Outputs fields": {
workloadName: testSvcName,
setupMocks: func(m addonMocks) {
m.ws.EXPECT().WorkloadAddonsAbsPath(testSvcName).Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return([]string{"first.yaml", "invalid-outputs.yaml"}, nil)
first, _ := os.ReadFile(filepath.Join("testdata", "merge", "first.yaml"))
m.ws.EXPECT().WorkloadAddonFileAbsPath(testSvcName, "first.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(first, nil)
second, _ := os.ReadFile(filepath.Join("testdata", "merge", "invalid-outputs.yaml"))
m.ws.EXPECT().WorkloadAddonFileAbsPath(testSvcName, "invalid-outputs.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(second, nil)
},
wantedErr: errors.New(`output "MyTableAccessPolicy" defined in "first.yaml" at Ln 85, Col 9 is different than in "invalid-outputs.yaml" at Ln 3, Col 5`),
},
"merge fields successfully": {
workloadName: testSvcName,
setupMocks: func(m addonMocks) {
m.ws.EXPECT().WorkloadAddonsAbsPath(testSvcName).Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return([]string{"first.yaml", "second.yaml"}, nil)
first, _ := os.ReadFile(filepath.Join("testdata", "merge", "first.yaml"))
m.ws.EXPECT().WorkloadAddonFileAbsPath(testSvcName, "first.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(first, nil)
second, _ := os.ReadFile(filepath.Join("testdata", "merge", "second.yaml"))
m.ws.EXPECT().WorkloadAddonFileAbsPath(testSvcName, "second.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(second, nil)
},
wantedTemplate: func() string {
wanted, _ := os.ReadFile(filepath.Join("testdata", "merge", "wanted.yaml"))
return string(wanted)
}(),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mocks := addonMocks{
ws: mocks.NewMockWorkspaceAddonsReader(ctrl),
}
if tc.setupMocks != nil {
tc.setupMocks(mocks)
}
// WHEN
stack, err := ParseFromWorkload(tc.workloadName, mocks.ws)
if tc.wantedErr != nil {
require.EqualError(t, err, tc.wantedErr.Error())
return
}
require.NoError(t, err)
require.Equal(t, tc.workloadName, stack.workloadName)
template, err := stack.Template()
require.NoError(t, err)
require.Equal(t, tc.wantedTemplate, template)
})
}
}
func TestWorkload_Parameters(t *testing.T) {
mockTemplate := `Parameters:
App:
Type: String
Env:
Type: String
Name:
Type: String
`
testCases := map[string]struct {
setupMocks func(m addonMocks)
wantedParams string
wantedErr error
}{
"returns ErrAddonsNotFound if there is no addons/ directory defined": {
setupMocks: func(m addonMocks) {
m.ws.EXPECT().WorkloadAddonsAbsPath("api").Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return(nil, errors.New("some error"))
},
wantedErr: fmt.Errorf(`list addons under path mockPath: %w`, &ErrAddonsNotFound{
ParentErr: errors.New("some error"),
}),
},
"returns empty string and nil if there are no parameter files under addons/": {
setupMocks: func(m addonMocks) {
m.ws.EXPECT().WorkloadAddonsAbsPath("api").Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return([]string{"database.yaml"}, nil)
m.ws.EXPECT().WorkloadAddonFileAbsPath("api", "database.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return([]byte(mockTemplate), nil)
},
},
"returns an error if there are multiple parameter files defined under addons/": {
setupMocks: func(m addonMocks) {
m.ws.EXPECT().WorkloadAddonsAbsPath("api").Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return([]string{"database.yml", "addons.parameters.yml", "addons.parameters.yaml"}, nil)
m.ws.EXPECT().WorkloadAddonFileAbsPath("api", "database.yml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(nil, nil)
},
wantedErr: errors.New("defining addons.parameters.yaml and addons.parameters.yml is not allowed under addons/"),
},
"returns an error if cannot read parameter file under addons/": {
setupMocks: func(m addonMocks) {
m.ws.EXPECT().WorkloadAddonsAbsPath("api").Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return([]string{"template.yml", "addons.parameters.yml"}, nil)
m.ws.EXPECT().WorkloadAddonFileAbsPath("api", "template.yml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(nil, nil)
m.ws.EXPECT().WorkloadAddonFileAbsPath("api", "addons.parameters.yml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(nil, errors.New("some error"))
},
wantedErr: errors.New("read parameter file addons.parameters.yml under path mockPath: some error"),
},
"returns an error if there are no 'Parameters' field defined in a parameters file": {
setupMocks: func(m addonMocks) {
m.ws.EXPECT().WorkloadAddonsAbsPath("api").Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return([]string{"template.yaml", "addons.parameters.yml"}, nil)
m.ws.EXPECT().WorkloadAddonFileAbsPath("api", "template.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(nil, nil)
m.ws.EXPECT().WorkloadAddonFileAbsPath("api", "addons.parameters.yml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return([]byte(""), nil)
},
wantedErr: errors.New("must define field 'Parameters' in file addons.parameters.yml under path mockPath"),
},
"returns an error if reserved parameter fields is redefined in a parameters file": {
setupMocks: func(m addonMocks) {
m.ws.EXPECT().WorkloadAddonsAbsPath("api").Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return([]string{"template.yaml", "addons.parameters.yml"}, nil)
m.ws.EXPECT().WorkloadAddonFileAbsPath("api", "template.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return([]byte(mockTemplate), nil)
m.ws.EXPECT().WorkloadAddonFileAbsPath("api", "addons.parameters.yml").Return("mockParametersPath")
m.ws.EXPECT().ReadFile("mockParametersPath").Return([]byte(`
Parameters:
App: !Ref AppName
Env: !Ref EnvName
Name: !Ref WorkloadName
EventsQueue:
!Ref EventsQueue
DiscoveryServiceArn: !GetAtt DiscoveryService.Arn
`), nil)
},
wantedErr: errors.New(`reserved parameters "App", "Env" and "Name" cannot be declared`),
},
"returns the content of Parameters on success": {
setupMocks: func(m addonMocks) {
m.ws.EXPECT().WorkloadAddonsAbsPath("api").Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return([]string{"template.yaml", "addons.parameters.yaml"}, nil)
m.ws.EXPECT().WorkloadAddonFileAbsPath("api", "template.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return([]byte(`Parameters:
App:
Type: String
Env:
Type: String
Name:
Type: String
EventsQueue:
Type: String
ServiceName:
Type: String
SecurityGroupId:
Type: String
DiscoveryServiceArn:
Type: String
`), nil)
m.ws.EXPECT().WorkloadAddonFileAbsPath("api", "addons.parameters.yaml").Return("mockParametersPath")
m.ws.EXPECT().ReadFile("mockParametersPath").Return([]byte(`
Parameters:
EventsQueue:
!Ref EventsQueue
ServiceName: !Ref Service
SecurityGroupId:
Fn::GetAtt: [ServiceSecurityGroup, Id]
DiscoveryServiceArn: !GetAtt DiscoveryService.Arn
`), nil)
},
wantedParams: `EventsQueue: !Ref EventsQueue
ServiceName: !Ref Service
SecurityGroupId:
Fn::GetAtt: [ServiceSecurityGroup, Id]
DiscoveryServiceArn: !GetAtt DiscoveryService.Arn
`,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mocks := addonMocks{
ws: mocks.NewMockWorkspaceAddonsReader(ctrl),
}
if tc.setupMocks != nil {
tc.setupMocks(mocks)
}
// WHEN
stack, err := ParseFromWorkload("api", mocks.ws)
if tc.wantedErr != nil {
require.EqualError(t, err, tc.wantedErr.Error())
return
}
require.NoError(t, err)
require.Equal(t, "api", stack.workloadName)
params, err := stack.Parameters()
require.NoError(t, err)
require.Equal(t, tc.wantedParams, params)
})
}
}
func TestEnv_Template(t *testing.T) {
testErr := errors.New("some error")
testCases := map[string]struct {
setupMocks func(m addonMocks)
wantedTemplate string
wantedErr error
}{
"return ErrAddonsNotFound if addons doesn't exist in an environment": {
setupMocks: func(m addonMocks) {
m.ws.EXPECT().EnvAddonsAbsPath().Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return(nil, testErr)
},
wantedErr: fmt.Errorf("list addons under path mockPath: %w", &ErrAddonsNotFound{
ParentErr: testErr,
}),
},
"return ErrAddonsNotFound if addons directory is empty in an environment": {
setupMocks: func(m addonMocks) {
m.ws.EXPECT().EnvAddonsAbsPath().Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return([]string{}, nil)
},
wantedErr: &ErrAddonsNotFound{},
},
"return ErrAddonsNotFound if addons directory does not contain yaml files in an environment": {
setupMocks: func(m addonMocks) {
m.ws.EXPECT().EnvAddonsAbsPath().Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return([]string{"gitkeep"}, nil)
},
wantedErr: &ErrAddonsNotFound{},
},
"ignore addons.parameters.yml files": {
setupMocks: func(m addonMocks) {
m.ws.EXPECT().EnvAddonsAbsPath().Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return([]string{"addons.parameters.yml", "addons.parameters.yaml"}, nil)
},
wantedErr: &ErrAddonsNotFound{},
},
"return err on invalid Metadata fields": {
setupMocks: func(m addonMocks) {
m.ws.EXPECT().EnvAddonsAbsPath().Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return([]string{"first.yaml", "invalid-metadata.yaml"}, nil)
first, _ := os.ReadFile(filepath.Join("testdata", "merge", "first.yaml"))
m.ws.EXPECT().EnvAddonFileAbsPath("first.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(first, nil)
second, _ := os.ReadFile(filepath.Join("testdata", "merge", "invalid-metadata.yaml"))
m.ws.EXPECT().EnvAddonFileAbsPath("invalid-metadata.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(second, nil)
},
wantedErr: errors.New(`metadata key "Services" defined in "first.yaml" at Ln 4, Col 7 is different than in "invalid-metadata.yaml" at Ln 3, Col 5`),
},
"returns err on invalid Parameters fields": {
setupMocks: func(m addonMocks) {
m.ws.EXPECT().EnvAddonsAbsPath().Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return([]string{"first.yaml", "invalid-parameters.yaml"}, nil)
first, _ := os.ReadFile(filepath.Join("testdata", "merge", "first.yaml"))
m.ws.EXPECT().EnvAddonFileAbsPath("first.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(first, nil)
second, _ := os.ReadFile(filepath.Join("testdata", "merge", "invalid-parameters.yaml"))
m.ws.EXPECT().EnvAddonFileAbsPath("invalid-parameters.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(second, nil)
},
wantedErr: errors.New(`parameter logical ID "Name" defined in "first.yaml" at Ln 15, Col 9 is different than in "invalid-parameters.yaml" at Ln 3, Col 7`),
},
"returns err on invalid Mappings fields": {
setupMocks: func(m addonMocks) {
m.ws.EXPECT().EnvAddonsAbsPath().Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return([]string{"first.yaml", "invalid-mappings.yaml"}, nil)
first, _ := os.ReadFile(filepath.Join("testdata", "merge", "first.yaml"))
m.ws.EXPECT().EnvAddonFileAbsPath("first.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(first, nil)
second, _ := os.ReadFile(filepath.Join("testdata", "merge", "invalid-mappings.yaml"))
m.ws.EXPECT().EnvAddonFileAbsPath("invalid-mappings.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(second, nil)
},
wantedErr: errors.New(`mapping "MyTableDynamoDBSettings.test" defined in "first.yaml" at Ln 21, Col 13 is different than in "invalid-mappings.yaml" at Ln 4, Col 7`),
},
"returns err on invalid Conditions fields": {
setupMocks: func(m addonMocks) {
m.ws.EXPECT().EnvAddonsAbsPath().Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return([]string{"first.yaml", "invalid-conditions.yaml"}, nil)
first, _ := os.ReadFile(filepath.Join("testdata", "merge", "first.yaml"))
m.ws.EXPECT().EnvAddonFileAbsPath("first.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(first, nil)
second, _ := os.ReadFile(filepath.Join("testdata", "merge", "invalid-conditions.yaml"))
m.ws.EXPECT().EnvAddonFileAbsPath("invalid-conditions.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(second, nil)
},
wantedErr: errors.New(`condition "IsProd" defined in "first.yaml" at Ln 28, Col 13 is different than in "invalid-conditions.yaml" at Ln 2, Col 13`),
},
"returns err on invalid Resources fields": {
setupMocks: func(m addonMocks) {
m.ws.EXPECT().EnvAddonsAbsPath().Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return([]string{"first.yaml", "invalid-resources.yaml"}, nil)
first, _ := os.ReadFile(filepath.Join("testdata", "merge", "first.yaml"))
m.ws.EXPECT().EnvAddonFileAbsPath("first.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(first, nil)
second, _ := os.ReadFile(filepath.Join("testdata", "merge", "invalid-resources.yaml"))
m.ws.EXPECT().EnvAddonFileAbsPath("invalid-resources.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(second, nil)
},
wantedErr: errors.New(`resource "MyTable" defined in "first.yaml" at Ln 34, Col 9 is different than in "invalid-resources.yaml" at Ln 3, Col 5`),
},
"returns err on invalid Outputs fields": {
setupMocks: func(m addonMocks) {
m.ws.EXPECT().EnvAddonsAbsPath().Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return([]string{"first.yaml", "invalid-outputs.yaml"}, nil)
first, _ := os.ReadFile(filepath.Join("testdata", "merge", "first.yaml"))
m.ws.EXPECT().EnvAddonFileAbsPath("first.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(first, nil)
second, _ := os.ReadFile(filepath.Join("testdata", "merge", "invalid-outputs.yaml"))
m.ws.EXPECT().EnvAddonFileAbsPath("invalid-outputs.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(second, nil)
},
wantedErr: errors.New(`output "MyTableAccessPolicy" defined in "first.yaml" at Ln 85, Col 9 is different than in "invalid-outputs.yaml" at Ln 3, Col 5`),
},
"merge fields successfully": {
setupMocks: func(m addonMocks) {
m.ws.EXPECT().EnvAddonsAbsPath().Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return([]string{"first.yaml", "second.yaml"}, nil)
first, _ := os.ReadFile(filepath.Join("testdata", "merge", "env", "first.yaml"))
m.ws.EXPECT().EnvAddonFileAbsPath("first.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(first, nil)
second, _ := os.ReadFile(filepath.Join("testdata", "merge", "env", "second.yaml"))
m.ws.EXPECT().EnvAddonFileAbsPath("second.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(second, nil)
},
wantedTemplate: func() string {
wanted, _ := os.ReadFile(filepath.Join("testdata", "merge", "env", "wanted.yaml"))
return string(wanted)
}(),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := addonMocks{
ws: mocks.NewMockWorkspaceAddonsReader(ctrl),
}
if tc.setupMocks != nil {
tc.setupMocks(m)
}
// WHEN
stack, err := ParseFromEnv(m.ws)
if tc.wantedErr != nil {
require.EqualError(t, err, tc.wantedErr.Error())
return
}
require.NoError(t, err)
template, err := stack.Template()
require.NoError(t, err)
require.Equal(t, tc.wantedTemplate, template)
})
}
}
func TestEnv_Parameters(t *testing.T) {
mockTemplate := `Parameters:
App:
Type: String
Env:
Type: String`
testCases := map[string]struct {
setupMocks func(m addonMocks)
wantedParams string
wantedErr error
}{
"returns ErrAddonsNotFound if there is no addons/ directory defined": {
setupMocks: func(m addonMocks) {
m.ws.EXPECT().EnvAddonsAbsPath().Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return(nil, errors.New("some error"))
},
wantedErr: fmt.Errorf("list addons under path mockPath: %w", &ErrAddonsNotFound{
ParentErr: errors.New("some error"),
}),
},
"returns empty string and nil if there are no parameter files under addons/": {
setupMocks: func(m addonMocks) {
m.ws.EXPECT().EnvAddonsAbsPath().Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return([]string{"database.yaml"}, nil)
m.ws.EXPECT().EnvAddonFileAbsPath("database.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return([]byte(mockTemplate), nil)
},
},
"returns an error if there are multiple parameter files defined under addons/": {
setupMocks: func(m addonMocks) {
m.ws.EXPECT().EnvAddonsAbsPath().Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return([]string{"database.yml", "addons.parameters.yml", "addons.parameters.yaml"}, nil)
m.ws.EXPECT().EnvAddonFileAbsPath("database.yml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(nil, nil)
},
wantedErr: errors.New("defining addons.parameters.yaml and addons.parameters.yml is not allowed under addons/"),
},
"returns an error if cannot read parameter file under addons/": {
setupMocks: func(m addonMocks) {
m.ws.EXPECT().EnvAddonsAbsPath().Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return([]string{"template.yml", "addons.parameters.yml"}, nil)
m.ws.EXPECT().EnvAddonFileAbsPath("template.yml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(nil, nil)
m.ws.EXPECT().EnvAddonFileAbsPath("addons.parameters.yml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(nil, errors.New("some error"))
},
wantedErr: errors.New("read parameter file addons.parameters.yml under path mockPath: some error"),
},
"returns an error if there are no 'Parameters' field defined in a parameters file": {
setupMocks: func(m addonMocks) {
m.ws.EXPECT().EnvAddonsAbsPath().Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return([]string{"template.yaml", "addons.parameters.yml"}, nil)
m.ws.EXPECT().EnvAddonFileAbsPath("template.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return(nil, nil)
m.ws.EXPECT().EnvAddonFileAbsPath("addons.parameters.yml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return([]byte(""), nil)
},
wantedErr: errors.New("must define field 'Parameters' in file addons.parameters.yml under path mockPath"),
},
"returns an error if reserved parameter fields is redefined in a parameters file": {
setupMocks: func(m addonMocks) {
m.ws.EXPECT().EnvAddonsAbsPath().Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return([]string{"template.yaml", "addons.parameters.yml"}, nil)
m.ws.EXPECT().EnvAddonFileAbsPath("template.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return([]byte(mockTemplate), nil)
m.ws.EXPECT().EnvAddonFileAbsPath("addons.parameters.yml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return([]byte(`
Parameters:
App: !Ref AppName
Env: !Ref EnvName
EventsQueue:
!Ref EventsQueue
DiscoveryServiceArn: !GetAtt DiscoveryService.Arn
`), nil)
},
wantedErr: errors.New(`reserved parameters "App" and "Env" cannot be declared`),
},
"returns the content of Parameters on success": {
setupMocks: func(m addonMocks) {
m.ws.EXPECT().EnvAddonsAbsPath().Return("mockPath")
m.ws.EXPECT().ListFiles("mockPath").Return([]string{"template.yaml", "addons.parameters.yaml"}, nil)
m.ws.EXPECT().EnvAddonFileAbsPath("template.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return([]byte(`Parameters:
App:
Type: String
Env:
Type: String
EventsQueue:
Type: String
ServiceName:
Type: String
SecurityGroupId:
Type: String
DiscoveryServiceArn:
Type: String
`), nil)
m.ws.EXPECT().EnvAddonFileAbsPath("addons.parameters.yaml").Return("mockPath")
m.ws.EXPECT().ReadFile("mockPath").Return([]byte(`
Parameters:
EventsQueue:
!Ref EventsQueue
ServiceName: !Ref Service
SecurityGroupId:
Fn::GetAtt: [ServiceSecurityGroup, Id]
DiscoveryServiceArn: !GetAtt DiscoveryService.Arn
`), nil)
},
wantedParams: `EventsQueue: !Ref EventsQueue
ServiceName: !Ref Service
SecurityGroupId:
Fn::GetAtt: [ServiceSecurityGroup, Id]
DiscoveryServiceArn: !GetAtt DiscoveryService.Arn
`,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mocks := addonMocks{
ws: mocks.NewMockWorkspaceAddonsReader(ctrl),
}
if tc.setupMocks != nil {
tc.setupMocks(mocks)
}
// WHEN
stack, err := ParseFromEnv(mocks.ws)
if tc.wantedErr != nil {
require.EqualError(t, err, tc.wantedErr.Error())
return
}
require.NoError(t, err)
params, err := stack.Parameters()
require.NoError(t, err)
require.Equal(t, tc.wantedParams, params)
})
}
}
func Test_validaTemplateParameters(t *testing.T) {
type content struct {
Parameters yaml.Node `yaml:"Parameters"`
}
testCases := map[string]struct {
rawParams string
rawTpl string
wantedError error
}{
"template parameters with default values are not required in parameters file": {
rawParams: `Parameters:`,
rawTpl: `Parameters:
App:
Type: String
Description: Your application's name.
Env:
Type: String
Description: The environment name your service, job, or workflow is being deployed to.
IsProd:
Type: String
Default: "false"
`,
},
"some template parameters are missing from the parameters file": {
rawParams: `Parameters:`,
rawTpl: `Parameters:
App:
Type: String
Description: Your application's name.
Env:
Type: String
Description: The environment name your service, job, or workflow is being deployed to.
InstanceType:
Type: 'AWS::SSM::Parameter::Value<String>'
`,
wantedError: errors.New(`parameter "InstanceType" in template must have a default value or is included in parameters file`),
},
"template does not have required parameters": {
rawParams: `Parameters:`,
rawTpl: `Parameters:
App:
Type: String
Description: Your application's name.
IsProd:
Type: String
Default: "false"
`,
wantedError: errors.New(`required parameter "Env" is missing from the template`),
},
"parameters file contains reserved keys": {
rawParams: `Parameters:
App: !Ref AppName
Env: !Ref EnvName
Name: !Ref WorkloadName
EventsQueue:
!Ref EventsQueue
DiscoveryServiceArn: !GetAtt DiscoveryService.Arn`,
rawTpl: `Parameters:
App:
Type: String
Description: Your application's name.
Env:
Type: String
Description: The environment name your service, job, or workflow is being deployed to.
InstanceType:
Type: 'AWS::SSM::Parameter::Value<String>'`,
wantedError: errors.New(`reserved parameters "App" and "Env" cannot be declared`),
},
"parameters file contains parameters that are not required by the template": {
rawParams: `Parameters:
ServiceName: !Ref Service`,
rawTpl: `Parameters:
App:
Type: String
Description: Your application's name.
Env:
Type: String
Description: The environment name your service, job, or workflow is being deployed to.
IsProd:
Type: String
Default: "false"
`,
wantedError: errors.New(`template does not require the parameter "ServiceName" in parameters file`),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
parameters := content{}
err := yaml.Unmarshal([]byte(tc.rawParams), ¶meters)
require.NoError(t, err)
tpl := content{}
err = yaml.Unmarshal([]byte(tc.rawTpl), &tpl)
require.NoError(t, err)
err = validateParameters(tpl.Parameters, parameters.Parameters, envAddonsParameterReservedKeys)
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
}
})
}
}
| 807 |
copilot-cli | aws | Go | //go:build integration || localintegration
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package addon_test
import (
"encoding"
"fmt"
"os"
"path/filepath"
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/copilot-cli/internal/pkg/addon"
"github.com/stretchr/testify/require"
"gopkg.in/yaml.v3"
)
func TestAddons(t *testing.T) {
testCases := map[string]struct {
addonMarshaler encoding.BinaryMarshaler
outFileName string
}{
"aurora": {
addonMarshaler: addon.WorkloadServerlessV2Template(addon.RDSProps{
ClusterName: "aurora",
Engine: "MySQL",
InitialDBName: "main",
Envs: []string{"test"},
}),
outFileName: "aurora.yml",
},
"ddb": {
addonMarshaler: addon.WorkloadDDBTemplate(&addon.DynamoDBProps{
StorageProps: &addon.StorageProps{
Name: "ddb",
},
Attributes: []addon.DDBAttribute{
{
Name: aws.String("primary"),
DataType: aws.String("S"),
},
{
Name: aws.String("sort"),
DataType: aws.String("N"),
},
{
Name: aws.String("othersort"),
DataType: aws.String("B"),
},
},
SortKey: aws.String("sort"),
PartitionKey: aws.String("primary"),
LSIs: []addon.DDBLocalSecondaryIndex{
{
Name: aws.String("othersort"),
PartitionKey: aws.String("primary"),
SortKey: aws.String("othersort"),
},
},
HasLSI: true,
}),
outFileName: "ddb.yml",
},
"s3": {
addonMarshaler: addon.WorkloadS3Template(&addon.S3Props{
StorageProps: &addon.StorageProps{
Name: "bucket",
},
}),
outFileName: "bucket.yml",
},
}
for name, tc := range testCases {
testName := fmt.Sprintf("CF Template should be equal/%s", name)
t.Run(testName, func(t *testing.T) {
actualBytes, err := tc.addonMarshaler.MarshalBinary()
require.NoError(t, err, "cf should render")
cfActual := make(map[interface{}]interface{})
require.NoError(t, yaml.Unmarshal(actualBytes, cfActual))
expected, err := os.ReadFile(filepath.Join("testdata", "storage", tc.outFileName))
require.NoError(t, err, "should be able to read expected bytes")
expectedBytes := []byte(expected)
mExpected := make(map[interface{}]interface{})
require.NoError(t, yaml.Unmarshal(expectedBytes, mExpected))
require.Equal(t, mExpected, cfActual)
})
}
}
| 96 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package addon
import (
"errors"
"fmt"
"reflect"
"gopkg.in/yaml.v3"
)
type cfnSection int
const (
metadataSection cfnSection = iota + 1
parametersSection
mappingsSection
conditionsSection
transformSection
resourcesSection
outputsSection
)
// cfnTemplate represents a parsed YAML AWS CloudFormation template.
type cfnTemplate struct {
Metadata yaml.Node `yaml:"Metadata,omitempty"`
Parameters yaml.Node `yaml:"Parameters,omitempty"`
Mappings yaml.Node `yaml:"Mappings,omitempty"`
Conditions yaml.Node `yaml:"Conditions,omitempty"`
Transform yaml.Node `yaml:"Transform,omitempty"`
Resources yaml.Node `yaml:"Resources"` // Don't omit as this is the only section that's required by CloudFormation.
Outputs yaml.Node `yaml:"Outputs,omitempty"`
name string
templateNameFor map[*yaml.Node]string // Maps a node to the name of the first template where it was defined.
}
func newCFNTemplate(name string) *cfnTemplate {
return &cfnTemplate{
name: name,
templateNameFor: make(map[*yaml.Node]string),
}
}
// merge combines non-empty fields of other with t's fields.
func (t *cfnTemplate) merge(other *cfnTemplate) error {
if err := t.mergeMetadata(other.Metadata); err != nil {
return wrapKeyAlreadyExistsErr(metadataSection, t, other, err)
}
if err := t.mergeParameters(other.Parameters); err != nil {
return wrapKeyAlreadyExistsErr(parametersSection, t, other, err)
}
if err := t.mergeMappings(other.Mappings); err != nil {
return wrapKeyAlreadyExistsErr(mappingsSection, t, other, err)
}
if err := t.mergeConditions(other.Conditions); err != nil {
return wrapKeyAlreadyExistsErr(conditionsSection, t, other, err)
}
if err := t.mergeTransform(other.Transform); err != nil {
return wrapKeyAlreadyExistsErr(transformSection, t, other, err)
}
if err := t.mergeResources(other.Resources); err != nil {
return wrapKeyAlreadyExistsErr(resourcesSection, t, other, err)
}
if err := t.mergeOutputs(other.Outputs); err != nil {
return wrapKeyAlreadyExistsErr(outputsSection, t, other, err)
}
t.assignNewNodesTo(other.name)
return nil
}
// mergeMetadata updates t's Metadata with additional metadata.
// If the key already exists in Metadata but with a different definition, returns errMetadataAlreadyExists.
func (t *cfnTemplate) mergeMetadata(metadata yaml.Node) error {
return mergeSingleLevelMaps(&t.Metadata, &metadata)
}
// mergeParameters updates t's Parameters with additional parameters.
// If the parameterLogicalID already exists but with a different value, returns errParameterAlreadyExists.
func (t *cfnTemplate) mergeParameters(params yaml.Node) error {
return mergeSingleLevelMaps(&t.Parameters, ¶ms)
}
// mergeMappings updates t's Mappings with additional mappings.
// If a mapping already exists with a different value, returns errMappingAlreadyExists.
func (t *cfnTemplate) mergeMappings(mappings yaml.Node) error {
return mergeTwoLevelMaps(&t.Mappings, &mappings)
}
// mergeConditions updates t's Conditions with additional conditions.
// If a condition already exists with a different value, returns errConditionAlreadyExists.
func (t *cfnTemplate) mergeConditions(conditions yaml.Node) error {
return mergeSingleLevelMaps(&t.Conditions, &conditions)
}
// mergeTransform adds transform's contents to t's Transform.
func (t *cfnTemplate) mergeTransform(transform yaml.Node) error {
addToSet(&t.Transform, &transform)
return nil
}
// mergeResources updates t's Resources with additional resources.
// If a resource already exists with a different value, returns errResourceAlreadyExists.
func (t *cfnTemplate) mergeResources(resources yaml.Node) error {
return mergeSingleLevelMaps(&t.Resources, &resources)
}
// mergeOutputs updates t's Outputs with additional outputs.
// If an output already exists with a different value, returns errOutputAlreadyExists.
func (t *cfnTemplate) mergeOutputs(outputs yaml.Node) error {
return mergeSingleLevelMaps(&t.Outputs, &outputs)
}
// assignNewNodesTo associates every new node added to the template t with the tplName.
func (t *cfnTemplate) assignNewNodesTo(tplName string) {
if t == nil {
return
}
var assign func(node *yaml.Node)
assign = func(node *yaml.Node) {
if node == nil {
return
}
if _, ok := t.templateNameFor[node]; ok {
// node is already associated with a previous template.
return
}
t.templateNameFor[node] = tplName
for _, c := range node.Content {
assign(c)
}
}
// Call assign() only on fields that represent CloudFormation sections.
tpl := reflect.ValueOf(*t)
for i := 0; i < tpl.NumField(); i += 1 {
field := tpl.Field(i)
if !field.CanInterface() {
// Fields that are not exported will panic if we call Interface(), therefore
// check the type only against exported cfnTemplate fields.
continue
}
if section, ok := field.Interface().(yaml.Node); ok {
assign(§ion)
}
}
}
// mergeTwoLevelMaps merges the top and second level keys of src node to dst.
// It assumes that both nodes are nested maps. For example, a node can hold:
// Mapping01: # Top Level is a map.
// Key01: # Second Level is also a map.
// Name: Value01
// Key02: # Second Level.
// Name: Value02
//
// If a second-level key exists in both src and dst but has different values, then returns an errKeyAlreadyExists.
// If a second-level key exists in src but not in dst, it merges the second level key to dst.
// If a top-level key exists in src but not in dst, merges it.
func mergeTwoLevelMaps(dst, src *yaml.Node) error {
secondLevelHandler := func(key string, dstVal, srcVal *yaml.Node) error {
if err := mergeSingleLevelMaps(dstVal, srcVal); err != nil {
var keyExistsErr *errKeyAlreadyExists
if errors.As(err, &keyExistsErr) {
keyExistsErr.Key = fmt.Sprintf("%s.%s", key, keyExistsErr.Key)
return keyExistsErr
}
return err
}
return nil
}
return mergeMapNodes(dst, src, secondLevelHandler)
}
// mergeSingleLevelMaps merges the keys of src node to dst.
// It assumes that both nodes are a map. For example, a node can hold:
// Resources:
// MyResourceName:
// ... # If the contents of "MyResourceName" are not equal in both src and dst then err.
//
// If a key exists in both src and dst but has different values, then returns an errKeyAlreadyExists.
// If a key exists in both src and dst and the values are equal, then do nothing.
// If a key exists in src but not in dst, merges it.
func mergeSingleLevelMaps(dst, src *yaml.Node) error {
areValuesEqualHandler := func(key string, dstVal, srcVal *yaml.Node) error {
if !isEqual(dstVal, srcVal) {
return &errKeyAlreadyExists{
Key: key,
First: dstVal,
Second: srcVal,
}
}
return nil
}
return mergeMapNodes(dst, src, areValuesEqualHandler)
}
type keyExistsHandler func(key string, dstVal, srcVal *yaml.Node) error
// mergeMapNodes merges the src node to dst.
// It assumes that both nodes have a "mapping" type. See https://yaml.org/spec/1.2/spec.html#id2802432
//
// If a key exists in src but not in dst, then adds the key and value to dst.
// If a key exists in both src and dst, invokes the keyExistsHandler.
func mergeMapNodes(dst, src *yaml.Node, handler keyExistsHandler) error {
if src.IsZero() {
return nil
}
if dst.IsZero() {
*dst = *src
return nil
}
dstMap := mappingNode(dst)
var newContent []*yaml.Node
for _, srcContent := range mappingContents(src) {
srcKey := srcContent.keyNode.Value
dstValueNode, ok := dstMap[srcKey]
if !ok {
// The key doesn't exist in dst, we want to retain the two src nodes.
newContent = append(newContent, srcContent.keyNode, srcContent.valueNode)
continue
}
if err := handler(srcKey, dstValueNode, srcContent.valueNode); err != nil {
return err
}
}
dst.Content = append(dst.Content, newContent...)
return nil
}
// addToSet adds a non-zero node to a set. If the node represents a sequence,
// then adds its contents to the set.
//
// If the node or its contents already exist in the set, does nothing.
// Otherwise, appends the node or its contents to the set.
func addToSet(set, node *yaml.Node) {
if node.IsZero() {
return
}
nodes := []*yaml.Node{node}
if node.Kind == yaml.SequenceNode {
// If node is a list, we should add its contents to the set instead.
nodes = node.Content
}
if set.IsZero() {
*set = yaml.Node{
Kind: yaml.SequenceNode,
Content: nodes,
}
return
}
var newElements []*yaml.Node
for _, c := range set.Content {
for _, n := range nodes {
if !isEqual(c, n) {
newElements = append(newElements, n)
}
}
}
set.Content = append(set.Content, newElements...)
}
// mappingNode transforms a flat "mapping" yaml.Node to a hashmap.
func mappingNode(n *yaml.Node) map[string]*yaml.Node {
m := make(map[string]*yaml.Node)
for i := 0; i < len(n.Content); i += 2 {
m[n.Content[i].Value] = n.Content[i+1]
}
return m
}
type mappingContent struct {
keyNode *yaml.Node
valueNode *yaml.Node
}
func mappingContents(mappingNode *yaml.Node) []mappingContent {
var results []mappingContent
for i := 0; i < len(mappingNode.Content); i += 2 {
// The content of a map always come in pairs.
// The first element represents a key, ex: {Value: "ELBIngressGroup", Kind: ScalarNode, Tag: "!!str", Content: nil}
// The second element holds the value, ex: {Value: "", Kind: MappingNode, Tag:"!!map", Content:[...]}
results = append(results, mappingContent{
keyNode: mappingNode.Content[i],
valueNode: mappingNode.Content[i+1],
})
}
return results
}
// isEqual returns true if the first and second nodes are deeply equal in all of their values except stylistic ones.
//
// We ignore the style (ex: single quote vs. double) in which the nodes are defined, the comments associated with
// the nodes, and the indentation and position of the nodes as they're only visual properties and don't matter.
func isEqual(first *yaml.Node, second *yaml.Node) bool {
if first == nil {
return second == nil
}
if second == nil {
return false
}
if len(first.Content) != len(second.Content) {
return false
}
hasSameContent := true
for i := 0; i < len(first.Content); i += 1 {
hasSameContent = hasSameContent && isEqual(first.Content[i], second.Content[i])
}
return first.Kind == second.Kind &&
first.Tag == second.Tag &&
first.Value == second.Value &&
first.Anchor == second.Anchor &&
isEqual(first.Alias, second.Alias) &&
hasSameContent
}
| 325 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package addon
import (
"errors"
"fmt"
"gopkg.in/yaml.v3"
)
// ErrAddonsNotFound occurs when an addons directory for a workload is either not found or empty.
type ErrAddonsNotFound struct {
ParentErr error
}
func (e *ErrAddonsNotFound) Error() string {
if e.ParentErr != nil {
return fmt.Sprintf("no addons found: %v", e.ParentErr)
}
return "no addons found"
}
type errKeyAlreadyExists struct {
Key string
First *yaml.Node
Second *yaml.Node
FirstFileName string
SecondFileName string
}
func (e *errKeyAlreadyExists) Error() string {
return fmt.Sprintf(`"%s" defined in "%s" at Ln %d, Col %d is different than in "%s" at Ln %d, Col %d`,
e.Key, e.FirstFileName, e.First.Line, e.First.Column, e.SecondFileName, e.Second.Line, e.Second.Column)
}
// errMetadataAlreadyExists occurs if two addons have the same key in their "Metadata" section but with different values.
type errMetadataAlreadyExists struct {
*errKeyAlreadyExists
}
func (e *errMetadataAlreadyExists) Error() string {
return fmt.Sprintf(`metadata key %s`, e.errKeyAlreadyExists.Error())
}
// errParameterAlreadyExists occurs if two addons have the same parameter logical ID but with different values.
type errParameterAlreadyExists struct {
*errKeyAlreadyExists
}
func (e *errParameterAlreadyExists) Error() string {
return fmt.Sprintf(`parameter logical ID %s`, e.errKeyAlreadyExists.Error())
}
// errMappingAlreadyExists occurs if the named values for the same Mappings key have different values.
type errMappingAlreadyExists struct {
*errKeyAlreadyExists
}
func (e *errMappingAlreadyExists) Error() string {
return fmt.Sprintf(`mapping %s`, e.errKeyAlreadyExists.Error())
}
// errConditionAlreadyExists occurs if two addons have the same Conditions key but with different values.
type errConditionAlreadyExists struct {
*errKeyAlreadyExists
}
func (e *errConditionAlreadyExists) Error() string {
return fmt.Sprintf(`condition %s`, e.errKeyAlreadyExists.Error())
}
// errResourceAlreadyExists occurs if two addons have the same resource under Resources but with different values.
type errResourceAlreadyExists struct {
*errKeyAlreadyExists
}
func (e *errResourceAlreadyExists) Error() string {
return fmt.Sprintf(`resource %s`, e.errKeyAlreadyExists.Error())
}
// errOutputAlreadyExists occurs if two addons have the same output under Outputs but with different values.
type errOutputAlreadyExists struct {
*errKeyAlreadyExists
}
func (e *errOutputAlreadyExists) Error() string {
return fmt.Sprintf(`output %s`, e.errKeyAlreadyExists.Error())
}
// wrapKeyAlreadyExistsErr wraps the err if its an errKeyAlreadyExists error with additional cfn section metadata.
// If the error is not an errKeyAlreadyExists, then return it as is.
func wrapKeyAlreadyExistsErr(section cfnSection, merged, newTpl *cfnTemplate, err error) error {
var keyExistsErr *errKeyAlreadyExists
if !errors.As(err, &keyExistsErr) {
return err
}
keyExistsErr.FirstFileName = merged.templateNameFor[keyExistsErr.First]
keyExistsErr.SecondFileName = newTpl.name
switch section {
case metadataSection:
return &errMetadataAlreadyExists{
keyExistsErr,
}
case parametersSection:
return &errParameterAlreadyExists{
keyExistsErr,
}
case mappingsSection:
return &errMappingAlreadyExists{
keyExistsErr,
}
case conditionsSection:
return &errConditionAlreadyExists{
keyExistsErr,
}
case resourcesSection:
return &errResourceAlreadyExists{
keyExistsErr,
}
case outputsSection:
return &errOutputAlreadyExists{
keyExistsErr,
}
default:
return keyExistsErr
}
}
| 132 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package addon
import (
"errors"
"fmt"
"strings"
"gopkg.in/yaml.v3"
)
// AWS CloudFormation resource types.
const (
secretManagerSecretType = "AWS::SecretsManager::Secret"
iamManagedPolicyType = "AWS::IAM::ManagedPolicy"
securityGroupType = "AWS::EC2::SecurityGroup"
)
// Output represents an output from a CloudFormation template.
type Output struct {
// Name is the Logical ID of the output.
Name string
// IsSecret is true if the output value refers to a SecretsManager ARN. Otherwise, false.
IsSecret bool
// IsManagedPolicy is true if the output value refers to an IAM ManagedPolicy ARN. Otherwise, false.
IsManagedPolicy bool
// SecurityGroup is true if the output value refers a SecurityGroup ARN. Otherwise, false.
IsSecurityGroup bool
}
// Outputs parses the Outputs section of a CloudFormation template to extract logical IDs and returns them.
func Outputs(template string) ([]Output, error) {
type cfnTemplate struct {
Resources yaml.Node `yaml:"Resources"`
Outputs yaml.Node `yaml:"Outputs"`
}
var tpl cfnTemplate
if err := yaml.Unmarshal([]byte(template), &tpl); err != nil {
return nil, fmt.Errorf("unmarshal addon cloudformation template: %w", err)
}
typeFor, err := parseTypeByLogicalID(&tpl.Resources)
if err != nil {
return nil, err
}
outputNodes, err := parseOutputNodes(&tpl.Outputs)
if err != nil {
return nil, err
}
var outputs []Output
for _, outputNode := range outputNodes {
output := Output{
Name: outputNode.name(),
IsSecret: false,
IsManagedPolicy: false,
IsSecurityGroup: false,
}
ref, ok := outputNode.ref()
if ok {
output.IsSecret = typeFor[ref] == secretManagerSecretType
output.IsManagedPolicy = typeFor[ref] == iamManagedPolicyType
output.IsSecurityGroup = typeFor[ref] == securityGroupType
}
outputs = append(outputs, output)
}
return outputs, nil
}
// parseTypeByLogicalID returns a map where the key is the resource's logical ID and the value is the CloudFormation Type
// of the resource such as "AWS::IAM::Role".
func parseTypeByLogicalID(resourcesNode *yaml.Node) (typeFor map[string]string, err error) {
if resourcesNode.Kind != yaml.MappingNode {
// "Resources" is a required field in CloudFormation, check if it's defined as a map.
return nil, errors.New(`"Resources" field in cloudformation template is not a map`)
}
typeFor = make(map[string]string)
for _, content := range mappingContents(resourcesNode) {
logicalIDNode := content.keyNode
fieldsNode := content.valueNode
fields := struct {
Type string `yaml:"Type"`
}{}
if err := fieldsNode.Decode(&fields); err != nil {
return nil, fmt.Errorf(`decode the "Type" field of resource "%s": %w`, logicalIDNode.Value, err)
}
typeFor[logicalIDNode.Value] = fields.Type
}
return typeFor, nil
}
func parseOutputNodes(outputsNode *yaml.Node) ([]*outputNode, error) {
if outputsNode.IsZero() {
// "Outputs" is an optional field so we can skip it.
return nil, nil
}
if outputsNode.Kind != yaml.MappingNode {
return nil, errors.New(`"Outputs" field in cloudformation template is not a map`)
}
var nodes []*outputNode
for _, content := range mappingContents(outputsNode) {
nameNode := content.keyNode
fields := struct {
Value yaml.Node `yaml:"Value"`
}{}
if err := content.valueNode.Decode(&fields); err != nil {
return nil, fmt.Errorf(`decode the "Value" field of output "%s": %w`, nameNode.Value, err)
}
nodes = append(nodes, &outputNode{
nameNode: nameNode,
valueNode: &fields.Value,
})
}
return nodes, nil
}
type outputNode struct {
nameNode *yaml.Node
valueNode *yaml.Node
}
func (n *outputNode) name() string {
return n.nameNode.Value
}
func (n *outputNode) ref() (string, bool) {
switch n.valueNode.Kind {
case yaml.ScalarNode:
// It's a string like "!Ref MyDynamoDBTable"
if n.valueNode.Tag != "!Ref" {
return "", false
}
return strings.TrimSpace(n.valueNode.Value), true
case yaml.MappingNode:
// Check if it's a map like "Ref: MyDynamoDBTable"
fields := struct {
Ref string `yaml:"Ref"`
}{}
_ = n.valueNode.Decode(&fields)
if fields.Ref == "" {
return "", false
}
return fields.Ref, true
default:
return "", false
}
}
| 155 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package addon
import (
"errors"
"os"
"path/filepath"
"strings"
"testing"
"github.com/stretchr/testify/require"
)
func TestOutputs(t *testing.T) {
testCases := map[string]struct {
template string
testdataFileName string
wantedOut []Output
wantedErr error
}{
"returns an error if Resources is not defined as a map": {
template: "Resources: hello",
wantedErr: errors.New(`"Resources" field in cloudformation template is not a map`),
},
"returns an error if a resource does not define a \"Type\" field": {
template: `
Resources:
Hello: World
`,
wantedErr: errors.New(`decode the "Type" field of resource "Hello"`),
},
"returns an error if Outputs is not defined as a map": {
template: `
Resources:
MyDBInstance:
Type: AWS::RDS::DBInstance
Outputs: hello
`,
wantedErr: errors.New(`"Outputs" field in cloudformation template is not a map`),
},
"returns an error if an output does not define a \"Value\" field": {
template: `
Resources:
MyDBInstance:
Type: AWS::RDS::DBInstance
Outputs:
Hello: World
`,
wantedErr: errors.New(`decode the "Value" field of output "Hello"`),
},
"returns a nil list if there are no outputs defined": {
template: `
Resources:
MyDBInstance:
Type: AWS::RDS::DBInstance
`,
},
"injects parameters defined in addons as environment variables": {
// See #1565
template: `
Parameters:
MinPort:
Type: Number
Default: 40000
MaxPort:
Type: Number
Default: 49999
Resources:
EnvironmentSecurityGroupIngressTCPWebRTC:
Type: AWS::EC2::SecurityGroupIngress
Properties:
Description: Ingress TCP for WebRTC media streams
GroupId:
Fn::ImportValue:
!Sub "${App}-${Env}-EnvironmentSecurityGroup"
IpProtocol: tcp
CidrIp: '0.0.0.0/0'
FromPort: !Ref MinPort # <- Problem is here
ToPort: !Ref MaxPort # <- Problem is here
Outputs:
MediasoupMinPort:
Value: !Ref MinPort
MediasoupMaxPort:
Value: !Ref MaxPort`,
wantedOut: []Output{
{
Name: "MediasoupMinPort",
},
{
Name: "MediasoupMaxPort",
},
},
},
"parses CFN template with an IAM managed policy and secret": {
testdataFileName: "template.yml",
wantedOut: []Output{
{
Name: "AdditionalResourcesPolicyArn",
IsManagedPolicy: true,
},
{
Name: "MyRDSInstanceRotationSecretArn",
IsSecret: true,
},
{
Name: "MyDynamoDBTableName",
},
{
Name: "MyDynamoDBTableArn",
},
{
Name: "TestExport",
},
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
template := tc.template
if tc.testdataFileName != "" {
content, err := os.ReadFile(filepath.Join("testdata", "outputs", tc.testdataFileName))
require.NoError(t, err)
template = string(content)
}
// WHEN
out, err := Outputs(template)
// THEN
if tc.wantedErr != nil {
require.NotNil(t, err, "expected a non-nil error to be returned")
require.True(t, strings.HasPrefix(err.Error(), tc.wantedErr.Error()), "expected the error %v to be wrapped by our prefix %v", err, tc.wantedErr)
} else {
require.NoError(t, err)
require.ElementsMatch(t, tc.wantedOut, out)
}
})
}
}
| 148 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package addon
import (
"archive/zip"
"bytes"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"io/fs"
"path/filepath"
"strings"
"github.com/aws/copilot-cli/internal/pkg/aws/s3"
"github.com/aws/copilot-cli/internal/pkg/template"
"github.com/aws/copilot-cli/internal/pkg/template/artifactpath"
"github.com/spf13/afero"
"gopkg.in/yaml.v3"
)
type uploader interface {
Upload(bucket, key string, data io.Reader) (string, error)
}
// packagePropertyConfig defines how to package a particular property in a cloudformation resource.
// There are two ways replacements occur. Given a resource configuration like:
// MyResource:
// Type: AWS::Resource::Type
// Properties:
// <Property>: file/path
//
// Without BucketNameProperty and ObjectKeyProperty, `file/path` is directly replaced with
// the S3 location the contents were uploaded to, resulting in this:
// MyResource:
// Type: AWS::Resource::Type
// Properties:
// <Property>: s3://bucket/hash
//
// If BucketNameProperty and ObjectKeyProperty are set, the value of <Property> is changed to a map
// with BucketNameProperty and ObjectKeyProperty as the keys.
// MyResource:
// Type: AWS::Resource::Type
// Properties:
// <Property>:
// <BucketNameProperty>: bucket
// <ObjectKeyProperty>: hash
type packagePropertyConfig struct {
// PropertyPath is the key in a cloudformation resource's 'Properties' map to be packaged.
// Nested properties are represented by multiple keys in the slice, so the field
// Properties:
// Code:
// S3: ./file-name
// is represented by []string{"Code", "S3"}.
PropertyPath []string
// BucketNameProperty represents the key in a submap of Property, created
// after uploading an asset to S3. If this and ObjectKeyProperty are empty,
// a submap will not be created and an S3 location URI will replace value of Property.
BucketNameProperty string
// ObjectKeyProperty represents the key in a submap of Property, created
// after uploading an asset to S3. If this and BucketNameProperty are empty,
// a submap will not be created and an S3 location URI will replace value of Property.
ObjectKeyProperty string
// ForceZip will force a zip file to be created even if the given file path
// points to a file. Directories are always zipped.
ForceZip bool
}
func (p *packagePropertyConfig) isStringReplacement() bool {
return len(p.BucketNameProperty) == 0 && len(p.ObjectKeyProperty) == 0
}
// resourcePackageConfig maps a CloudFormation resource type to configuration
// for how to transform it's properties.
//
// This list of resources should stay in sync with
// https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/package.html.
var resourcePackageConfig = map[string][]packagePropertyConfig{
"AWS::ApiGateway::RestApi": {
{
PropertyPath: []string{"BodyS3Location"},
BucketNameProperty: "Bucket",
ObjectKeyProperty: "Key",
},
},
"AWS::Lambda::Function": {
{
PropertyPath: []string{"Code"},
BucketNameProperty: "S3Bucket",
ObjectKeyProperty: "S3Key",
ForceZip: true,
},
},
"AWS::Lambda::LayerVersion": {
{
PropertyPath: []string{"Content"},
BucketNameProperty: "S3Bucket",
ObjectKeyProperty: "S3Key",
ForceZip: true,
},
},
"AWS::Serverless::Function": {
{
PropertyPath: []string{"CodeUri"},
ForceZip: true,
},
},
"AWS::Serverless::LayerVersion": {
{
PropertyPath: []string{"ContentUri"},
ForceZip: true,
},
},
"AWS::Serverless::Application": {
{
PropertyPath: []string{"Location"},
},
},
"AWS::AppSync::GraphQLSchema": {
{
PropertyPath: []string{"DefinitionS3Location"},
},
},
"AWS::AppSync::Resolver": {
{
PropertyPath: []string{"RequestMappingTemplateS3Location"},
},
{
PropertyPath: []string{"ResponseMappingTemplateS3Location"},
},
},
"AWS::AppSync::FunctionConfiguration": {
{
PropertyPath: []string{"RequestMappingTemplateS3Location"},
},
{
PropertyPath: []string{"ResponseMappingTemplateS3Location"},
},
},
"AWS::Serverless::Api": {
{
PropertyPath: []string{"DefinitionUri"},
},
},
"AWS::ElasticBeanstalk::ApplicationVersion": {
{
PropertyPath: []string{"SourceBundle"},
BucketNameProperty: "S3Bucket",
ObjectKeyProperty: "S3Key",
},
},
"AWS::CloudFormation::Stack": {
{
// This implementation does not recursively package
// the local template pointed to by TemplateURL.
PropertyPath: []string{"TemplateURL"},
},
},
"AWS::Glue::Job": {
{
PropertyPath: []string{"Command", "ScriptLocation"},
},
},
"AWS::StepFunctions::StateMachine": {
{
PropertyPath: []string{"DefinitionS3Location"},
BucketNameProperty: "Bucket",
ObjectKeyProperty: "Key",
},
},
"AWS::Serverless::StateMachine": {
{
PropertyPath: []string{"DefinitionUri"},
BucketNameProperty: "Bucket",
ObjectKeyProperty: "Key",
},
},
"AWS::CodeCommit::Repository": {
{
PropertyPath: []string{"Code", "S3"},
BucketNameProperty: "Bucket",
ObjectKeyProperty: "Key",
ForceZip: true,
},
},
}
// PackageConfig contains data needed to package a Stack.
type PackageConfig struct {
Bucket string
Uploader uploader
WorkspacePath string
FS afero.Fs
s3Path func(hash string) string
}
// Package finds references to local files in Stack's template, uploads
// the files to S3, and replaces the file path with the S3 location.
func (s *EnvironmentStack) Package(cfg PackageConfig) error {
cfg.s3Path = artifactpath.EnvironmentAddonAsset
return s.packageAssets(cfg)
}
// Package finds references to local files in Stack's template, uploads
// the files to S3, and replaces the file path with the S3 location.
func (s *WorkloadStack) Package(cfg PackageConfig) error {
cfg.s3Path = func(hash string) string {
return artifactpath.AddonAsset(s.workloadName, hash)
}
return s.packageAssets(cfg)
}
func (s *stack) packageAssets(cfg PackageConfig) error {
err := cfg.packageIncludeTransforms(&s.template.Metadata, &s.template.Mappings, &s.template.Conditions, &s.template.Transform, &s.template.Resources, &s.template.Outputs)
if err != nil {
return fmt.Errorf("package transforms: %w", err)
}
// package resources
for name, node := range mappingNode(&s.template.Resources) {
resType := yamlMapGet(node, "Type").Value
confs, ok := resourcePackageConfig[resType]
if !ok {
continue
}
props := yamlMapGet(node, "Properties")
for _, conf := range confs {
if err := cfg.packageProperty(props, conf); err != nil {
return fmt.Errorf("package property %q of %q: %w", strings.Join(conf.PropertyPath, "."), name, err)
}
}
}
return nil
}
// packageIncludeTransforms searches each node in nodes for the CFN
// intrinsic function "Fn::Transform" with the "AWS::Include" macro. If it
// detects one, and the "Location" parameter is set to a local path, it'll
// upload those files to S3. If node is a yaml map or sequence, it will
// recursively traverse those nodes.
func (p *PackageConfig) packageIncludeTransforms(nodes ...*yaml.Node) error {
pkg := func(node *yaml.Node) error {
if node == nil || node.Kind != yaml.MappingNode {
return nil
}
for key, val := range mappingNode(node) {
switch {
case key == "Fn::Transform":
name := yamlMapGet(val, "Name")
if name.Value != "AWS::Include" {
continue
}
loc := yamlMapGet(yamlMapGet(val, "Parameters"), "Location")
if !isFilePath(loc.Value) {
continue
}
obj, err := p.uploadAddonAsset(loc.Value, false)
if err != nil {
return fmt.Errorf("upload asset: %w", err)
}
loc.Value = s3.Location(obj.Bucket, obj.Key)
case val.Kind == yaml.MappingNode:
if err := p.packageIncludeTransforms(val); err != nil {
return err
}
case val.Kind == yaml.SequenceNode:
if err := p.packageIncludeTransforms(val.Content...); err != nil {
return err
}
}
}
return nil
}
for i := range nodes {
if err := pkg(nodes[i]); err != nil {
return err
}
}
return nil
}
// yamlMapGet parses node as a yaml map and searches key. If found,
// it returns the value node of key. If node is not a yaml MappingNode
// or key is not in the map, a zero value yaml.Node is returned, not a nil value,
// to avoid panics and simplify accessing values from the returned node.
//
// If you need access many values from yaml map, consider mappingNode() instead, as
// yamlMapGet will iterate through keys in the map each time vs a constant lookup.
func yamlMapGet(node *yaml.Node, key string) *yaml.Node {
if node == nil || node.Kind != yaml.MappingNode {
return &yaml.Node{}
}
for i := 0; i < len(node.Content); i += 2 {
if node.Content[i].Value == key {
return node.Content[i+1]
}
}
return &yaml.Node{}
}
func (p *PackageConfig) packageProperty(resourceProperties *yaml.Node, propCfg packagePropertyConfig) error {
target := resourceProperties
for _, key := range propCfg.PropertyPath {
target = yamlMapGet(target, key)
}
if target.IsZero() || target.Kind != yaml.ScalarNode {
// only transform if the node is a scalar node
return nil
}
if !isFilePath(target.Value) {
return nil
}
obj, err := p.uploadAddonAsset(target.Value, propCfg.ForceZip)
if err != nil {
return fmt.Errorf("upload asset: %w", err)
}
if propCfg.isStringReplacement() {
target.Value = s3.Location(obj.Bucket, obj.Key)
return nil
}
return target.Encode(map[string]string{
propCfg.BucketNameProperty: obj.Bucket,
propCfg.ObjectKeyProperty: obj.Key,
})
}
// isFilePath returns true if the path URI doesn't have a
// a schema indicating it's an s3 or http URI.
func isFilePath(path string) bool {
if path == "" || strings.HasPrefix(path, "s3://") || strings.HasPrefix(path, "http://") || strings.HasPrefix(path, "https://") {
return false
}
return true
}
func (p *PackageConfig) uploadAddonAsset(assetPath string, forceZip bool) (template.S3ObjectLocation, error) {
// make path absolute from wsPath
if !filepath.IsAbs(assetPath) {
assetPath = filepath.Join(p.WorkspacePath, assetPath)
}
info, err := p.FS.Stat(assetPath)
if err != nil {
return template.S3ObjectLocation{}, fmt.Errorf("stat: %w", err)
}
getAsset := p.fileAsset
if forceZip || info.IsDir() {
getAsset = p.zipAsset
}
asset, err := getAsset(assetPath)
if err != nil {
return template.S3ObjectLocation{}, fmt.Errorf("create asset: %w", err)
}
s3Path := p.s3Path(asset.hash)
url, err := p.Uploader.Upload(p.Bucket, s3Path, asset.data)
if err != nil {
return template.S3ObjectLocation{}, fmt.Errorf("upload %s to s3 bucket %s: %w", assetPath, p.Bucket, err)
}
bucket, key, err := s3.ParseURL(url)
if err != nil {
return template.S3ObjectLocation{}, fmt.Errorf("parse s3 url: %w", err)
}
return template.S3ObjectLocation{
Bucket: bucket,
Key: key,
}, nil
}
type asset struct {
data io.Reader
hash string
}
// zipAsset creates an asset from the directory or file specified by root
// where the data is the compressed zip archive, and the hash is
// a hash of each files name, permission, and content. The zip file
// itself is not hashed to avoid a changing hash when non-relevant
// file metadata changes, like modification time.
func (p *PackageConfig) zipAsset(root string) (asset, error) {
buf := &bytes.Buffer{}
archive := zip.NewWriter(buf)
defer archive.Close()
hash := sha256.New()
if err := afero.Walk(p.FS, root, func(path string, info fs.FileInfo, err error) error {
switch {
case err != nil:
return err
case info.IsDir():
return nil
}
fname, err := filepath.Rel(root, path)
switch {
case err != nil:
return fmt.Errorf("rel: %w", err)
case fname == ".": // happens when root == path; when a file (not a dir) is passed to `zipAsset()`
fname = info.Name()
}
f, err := p.FS.Open(path)
if err != nil {
return fmt.Errorf("open: %w", err)
}
defer f.Close()
header, err := zip.FileInfoHeader(info)
if err != nil {
return fmt.Errorf("create zip file header: %w", err)
}
header.Name = fname
header.Method = zip.Deflate
zf, err := archive.CreateHeader(header)
if err != nil {
return fmt.Errorf("create zip file %q: %w", fname, err)
}
// include the file name and permissions as part of the hash
hash.Write([]byte(fmt.Sprintf("%s %s", fname, info.Mode().String())))
_, err = io.Copy(io.MultiWriter(zf, hash), f)
return err
}); err != nil {
return asset{}, err
}
return asset{
data: buf,
hash: hex.EncodeToString(hash.Sum(nil)),
}, nil
}
// fileAsset creates an asset from the file specified by path.
// The data is the content of the file, and the hash is the
// a hash of the file content.
func (p *PackageConfig) fileAsset(path string) (asset, error) {
hash := sha256.New()
buf := &bytes.Buffer{}
f, err := p.FS.Open(path)
if err != nil {
return asset{}, fmt.Errorf("open: %w", err)
}
defer f.Close()
_, err = io.Copy(io.MultiWriter(buf, hash), f)
if err != nil {
return asset{}, fmt.Errorf("copy: %w", err)
}
return asset{
data: buf,
hash: hex.EncodeToString(hash.Sum(nil)),
}, nil
}
| 484 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package addon
import (
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"strings"
"testing"
"github.com/aws/copilot-cli/internal/pkg/addon/mocks"
"github.com/aws/copilot-cli/internal/pkg/aws/s3"
"github.com/golang/mock/gomock"
"github.com/spf13/afero"
"github.com/stretchr/testify/require"
"gopkg.in/yaml.v3"
)
type addonMocks struct {
uploader *mocks.Mockuploader
ws *mocks.MockWorkspaceAddonsReader
}
func TestPackage(t *testing.T) {
const (
wlName = "mock-wl"
wsPath = "/"
bucket = "mockBucket"
)
lambdaZipHash := sha256.New()
indexZipHash := sha256.New()
indexFileHash := sha256.New()
// fs has the following structure:
// .
// ├─ lambda
// │ ├─ index.js (contains lambda function)
// ┴ └─ test.js (empty)
fs := afero.NewMemMapFs()
fs.Mkdir("/lambda", 0644)
f, _ := fs.Create("/lambda/index.js")
defer f.Close()
info, _ := f.Stat()
io.MultiWriter(lambdaZipHash, indexZipHash).Write([]byte("index.js " + info.Mode().String()))
io.MultiWriter(f, lambdaZipHash, indexZipHash, indexFileHash).Write([]byte(`exports.handler = function(event, context) {}`))
f2, _ := fs.Create("/lambda/test.js")
info, _ = f2.Stat()
lambdaZipHash.Write([]byte("test.js " + info.Mode().String()))
lambdaZipS3Path := fmt.Sprintf("manual/addons/mock-wl/assets/%s", hex.EncodeToString(lambdaZipHash.Sum(nil)))
indexZipS3Path := fmt.Sprintf("manual/addons/mock-wl/assets/%s", hex.EncodeToString(indexZipHash.Sum(nil)))
indexFileS3Path := fmt.Sprintf("manual/addons/mock-wl/assets/%s", hex.EncodeToString(indexFileHash.Sum(nil)))
tests := map[string]struct {
inTemplate string
outTemplate string
pkgError string
setupMocks func(m addonMocks)
}{
"AWS::Lambda::Function, zipped file": {
setupMocks: func(m addonMocks) {
m.uploader.EXPECT().Upload(bucket, indexZipS3Path, gomock.Any()).Return(s3.URL("us-west-2", bucket, "asdf"), nil)
},
inTemplate: `
Resources:
Test:
Metadata:
"testKey": "testValue"
Type: AWS::Lambda::Function
Properties:
Code: lambda/index.js
Handler: "index.handler"
Timeout: 900
MemorySize: 512
Role: !GetAtt "TestRole.Arn"
Runtime: nodejs16.x
`,
outTemplate: `
Resources:
Test:
Metadata:
"testKey": "testValue"
Type: AWS::Lambda::Function
Properties:
Code:
S3Bucket: mockBucket
S3Key: asdf
Handler: "index.handler"
Timeout: 900
MemorySize: 512
Role: !GetAtt "TestRole.Arn"
Runtime: nodejs16.x
`,
},
"AWS::Glue::Job, non-zipped file": {
setupMocks: func(m addonMocks) {
m.uploader.EXPECT().Upload(bucket, indexFileS3Path, gomock.Any()).Return(s3.URL("us-east-2", bucket, "asdf"), nil)
},
inTemplate: `
Resources:
Test:
Metadata:
"testKey": "testValue"
Type: AWS::Glue::Job
Properties:
Command:
ScriptLocation: lambda/index.js
`,
outTemplate: `
Resources:
Test:
Metadata:
"testKey": "testValue"
Type: AWS::Glue::Job
Properties:
Command:
ScriptLocation: s3://mockBucket/asdf
`,
},
"AWS::CodeCommit::Repository, directory without slash": {
setupMocks: func(m addonMocks) {
m.uploader.EXPECT().Upload(bucket, lambdaZipS3Path, gomock.Any()).Return(s3.URL("ap-northeast-1", bucket, "asdf"), nil)
},
inTemplate: `
Resources:
Test:
Metadata:
"testKey": "testValue"
Type: AWS::CodeCommit::Repository
Properties:
Code:
S3: lambda
`,
outTemplate: `
Resources:
Test:
Metadata:
"testKey": "testValue"
Type: AWS::CodeCommit::Repository
Properties:
Code:
S3:
Bucket: mockBucket
Key: asdf
`,
},
"AWS::ApiGateway::RestApi, directory with slash": {
setupMocks: func(m addonMocks) {
m.uploader.EXPECT().Upload(bucket, lambdaZipS3Path, gomock.Any()).Return(s3.URL("eu-west-1", bucket, "asdf"), nil)
},
inTemplate: `
Resources:
Test:
Metadata:
"testKey": "testValue"
Type: AWS::ApiGateway::RestApi
Properties:
BodyS3Location: lambda/
`,
outTemplate: `
Resources:
Test:
Metadata:
"testKey": "testValue"
Type: AWS::ApiGateway::RestApi
Properties:
BodyS3Location:
Bucket: mockBucket
Key: asdf
`,
},
"AWS::AppSync::Resolver, multiple replacements in one resource": {
setupMocks: func(m addonMocks) {
m.uploader.EXPECT().Upload(bucket, lambdaZipS3Path, gomock.Any()).Return(s3.URL("ca-central-1", bucket, "asdf"), nil)
m.uploader.EXPECT().Upload(bucket, indexFileS3Path, gomock.Any()).Return(s3.URL("ca-central-1", bucket, "hjkl"), nil)
},
inTemplate: `
Resources:
Test:
Metadata:
"testKey": "testValue"
Type: AWS::AppSync::Resolver
Properties:
RequestMappingTemplateS3Location: lambda
ResponseMappingTemplateS3Location: lambda/index.js
`,
outTemplate: `
Resources:
Test:
Metadata:
"testKey": "testValue"
Type: AWS::AppSync::Resolver
Properties:
RequestMappingTemplateS3Location: s3://mockBucket/asdf
ResponseMappingTemplateS3Location: s3://mockBucket/hjkl
`,
},
"Fn::Transform in lambda function": {
setupMocks: func(m addonMocks) {
m.uploader.EXPECT().Upload(bucket, indexFileS3Path, gomock.Any()).Return(s3.URL("us-west-2", bucket, "asdf"), nil)
m.uploader.EXPECT().Upload(bucket, lambdaZipS3Path, gomock.Any()).Return(s3.URL("us-west-2", bucket, "hjkl"), nil)
},
inTemplate: `
Resources:
Test:
Metadata:
"hihi": "byebye"
Type: AWS::Lambda::Function
Properties:
Fn::Transform:
# test comment uno
Name: "AWS::Include"
Parameters:
# test comment dos
Location: ./lambda/index.js
Code: lambda
Handler: "index.handler"
Timeout: 900
MemorySize: 512
Role: !GetAtt "TestRole.Arn"
Runtime: nodejs16.x
`,
outTemplate: `
Resources:
Test:
Metadata:
"hihi": "byebye"
Type: AWS::Lambda::Function
Properties:
Fn::Transform:
# test comment uno
Name: "AWS::Include"
Parameters:
# test comment dos
Location: s3://mockBucket/asdf
Code:
S3Bucket: mockBucket
S3Key: hjkl
Handler: "index.handler"
Timeout: 900
MemorySize: 512
Role: !GetAtt "TestRole.Arn"
Runtime: nodejs16.x
`,
},
"Fn::Transform nested in a yaml mapping and sequence node": {
setupMocks: func(m addonMocks) {
m.uploader.EXPECT().Upload(bucket, indexFileS3Path, gomock.Any()).Return(s3.URL("us-west-2", bucket, "asdf"), nil).Times(2)
},
inTemplate: `
Resources:
Test:
Type: AWS::Fake::Resource
Properties:
SequenceProperty:
- KeyOne: ValOne
KeyTwo: ValTwo
- Fn::Transform:
Name: "AWS::Include"
Parameters:
Location: ./lambda/index.js
MappingProperty:
KeyOne: ValOne
Fn::Transform:
Name: "AWS::Include"
Parameters:
Location: ./lambda/index.js
`,
outTemplate: `
Resources:
Test:
Type: AWS::Fake::Resource
Properties:
SequenceProperty:
- KeyOne: ValOne
KeyTwo: ValTwo
- Fn::Transform:
Name: "AWS::Include"
Parameters:
Location: s3://mockBucket/asdf
MappingProperty:
KeyOne: ValOne
Fn::Transform:
Name: "AWS::Include"
Parameters:
Location: s3://mockBucket/asdf
`,
},
"Fn::Transform ignores top level Transform": {
// example from https://medium.com/swlh/using-the-cloudformation-aws-include-macro-9e3056cf75b0
setupMocks: func(m addonMocks) {
m.uploader.EXPECT().Upload(bucket, indexFileS3Path, gomock.Any()).Return(s3.URL("us-west-2", "chris.hare", "common-tags.yaml"), nil)
},
inTemplate: `
Parameters:
CreatedBy:
Type: String
Description: Email address of the person creating the resource.
Transform:
Name: 'AWS::Include'
Parameters:
Location: 's3://chris.hare/alb-cw-mapping.yaml'
Resources:
bucket:
Type: AWS::S3::Bucket
Properties:
Fn::Transform:
Name: 'AWS::Include'
Parameters:
Location: './lambda/index.js'
Outputs:
bucketDomainName:
Value: !GetAtt bucket.DomainName
bucket:
Value: !Ref bucket
`,
outTemplate: `
Parameters:
CreatedBy:
Type: String
Description: Email address of the person creating the resource.
Transform:
Name: 'AWS::Include'
Parameters:
Location: 's3://chris.hare/alb-cw-mapping.yaml'
Resources:
bucket:
Type: AWS::S3::Bucket
Properties:
Fn::Transform:
Name: 'AWS::Include'
Parameters:
Location: 's3://chris.hare/common-tags.yaml'
Outputs:
bucketDomainName:
Value: !GetAtt bucket.DomainName
bucket:
Value: !Ref bucket
`,
},
"error on file not existing": {
inTemplate: `
Resources:
Test:
Type: AWS::Lambda::Function
Properties:
Code: does/not/exist.js
`,
pkgError: `package property "Code" of "Test": upload asset: stat: open /does/not/exist.js: file does not exist`,
},
"error on file upload error": {
setupMocks: func(m addonMocks) {
m.uploader.EXPECT().Upload(bucket, indexZipS3Path, gomock.Any()).Return("", errors.New("mockError"))
},
inTemplate: `
Resources:
Test:
Type: AWS::Lambda::Function
Properties:
Code: lambda/index.js
`,
pkgError: `package property "Code" of "Test": upload asset: upload /lambda/index.js to s3 bucket mockBucket: mockError`,
},
"error on file not existing for Fn::Transform": {
inTemplate: `
Resources:
Test:
Type: AWS::Lambda::Function
Properties:
Fn::Transform:
Name: "AWS::Include"
Parameters:
Location: does/not/exist.yml
`,
pkgError: `package transforms: upload asset: stat: open /does/not/exist.yml: file does not exist`,
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mocks := addonMocks{
uploader: mocks.NewMockuploader(ctrl),
ws: mocks.NewMockWorkspaceAddonsReader(ctrl),
}
if tc.setupMocks != nil {
tc.setupMocks(mocks)
}
stack := &WorkloadStack{
workloadName: wlName,
stack: stack{
template: newCFNTemplate("merged"),
},
}
require.NoError(t, yaml.Unmarshal([]byte(tc.inTemplate), stack.template))
config := PackageConfig{
Bucket: bucket,
WorkspacePath: wsPath,
Uploader: mocks.uploader,
FS: fs,
}
err := stack.Package(config)
if tc.pkgError != "" {
require.EqualError(t, err, tc.pkgError)
return
}
require.NoError(t, err)
tmpl, err := stack.Template()
require.NoError(t, err)
require.Equal(t, strings.TrimSpace(tc.outTemplate), strings.TrimSpace(tmpl))
})
}
}
func TestEnvironmentAddonStack_PackagePackage(t *testing.T) {
const (
wsPath = "/"
bucket = "mockBucket"
)
lambdaZipHash := sha256.New()
indexZipHash := sha256.New()
indexFileHash := sha256.New()
// fs has the following structure:
// .
// ├─ lambda
// │ ├─ index.js (contains lambda function)
// ┴ └─ test.js (empty)
fs := afero.NewMemMapFs()
fs.Mkdir("/lambda", 0644)
f, _ := fs.Create("/lambda/index.js")
defer f.Close()
info, _ := f.Stat()
io.MultiWriter(lambdaZipHash, indexZipHash).Write([]byte("index.js " + info.Mode().String()))
io.MultiWriter(f, lambdaZipHash, indexZipHash, indexFileHash).Write([]byte(`exports.handler = function(event, context) {}`))
f2, _ := fs.Create("/lambda/test.js")
info, _ = f2.Stat()
lambdaZipHash.Write([]byte("test.js " + info.Mode().String()))
indexZipS3PathForEnvironmentAddon := fmt.Sprintf("manual/addons/environments/assets/%s", hex.EncodeToString(indexZipHash.Sum(nil)))
t.Run("package zipped AWS::Lambda::Function for environment addons", func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
// Set up mocks.
m := addonMocks{
uploader: mocks.NewMockuploader(ctrl),
ws: mocks.NewMockWorkspaceAddonsReader(ctrl),
}
m.uploader.EXPECT().Upload(bucket, indexZipS3PathForEnvironmentAddon, gomock.Any()).Return(s3.URL("us-west-2", bucket, "asdf"), nil)
// WHEN.
inTemplate := `
Resources:
Test:
Metadata:
"testKey": "testValue"
Type: AWS::Lambda::Function
Properties:
Code: lambda/index.js
Handler: "index.handler"
Timeout: 900
MemorySize: 512
Role: !GetAtt "TestRole.Arn"
Runtime: nodejs16.x
`
stack := &EnvironmentStack{
stack: stack{
template: newCFNTemplate("merged"),
},
}
require.NoError(t, yaml.Unmarshal([]byte(inTemplate), stack.template))
config := PackageConfig{
Bucket: bucket,
WorkspacePath: wsPath,
Uploader: m.uploader,
FS: fs,
}
err := stack.Package(config)
// Expect.
outTemplate := `
Resources:
Test:
Metadata:
"testKey": "testValue"
Type: AWS::Lambda::Function
Properties:
Code:
S3Bucket: mockBucket
S3Key: asdf
Handler: "index.handler"
Timeout: 900
MemorySize: 512
Role: !GetAtt "TestRole.Arn"
Runtime: nodejs16.x
`
require.NoError(t, err)
tmpl, err := stack.Template()
require.NoError(t, err)
require.Equal(t, strings.TrimSpace(outTemplate), strings.TrimSpace(tmpl))
})
}
| 523 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package addon contains the service to manage addons.
package addon
import (
"fmt"
"regexp"
"strings"
"github.com/aws/copilot-cli/internal/pkg/template"
)
const (
dynamoDbTemplatePath = "addons/ddb/cf.yml"
s3TemplatePath = "addons/s3/cf.yml"
rdsTemplatePath = "addons/aurora/cf.yml"
rdsV2TemplatePath = "addons/aurora/serverlessv2.yml"
rdsRDWSTemplatePath = "addons/aurora/rdws/cf.yml"
rdsV2RDWSTemplatePath = "addons/aurora/rdws/serverlessv2.yml"
rdsRDWSParamsPath = "addons/aurora/rdws/addons.parameters.yml"
envS3TemplatePath = "addons/s3/env/cf.yml"
envS3AccessPolicyTemplatePath = "addons/s3/env/access_policy.yml"
envDynamoDBTemplatePath = "addons/ddb/env/cf.yml"
envDynamoDBAccessPolicyTemplatePath = "addons/ddb/env/access_policy.yml"
envRDSTemplatePath = "addons/aurora/env/serverlessv2.yml"
envRDSParamsPath = "addons/aurora/env/addons.parameters.yml"
envRDSForRDWSTemplatePath = "addons/aurora/env/rdws/serverlessv2.yml"
envRDSIngressForRDWSTemplatePath = "addons/aurora/env/rdws/ingress.yml"
envRDSIngressForRDWSParamsPath = "addons/aurora/env/rdws/ingress.addons.parameters.yml"
)
const (
// Aurora Serverless versions.
auroraServerlessVersionV1 = "v1"
auroraServerlessVersionV2 = "v2"
)
// Engine types for RDS Aurora Serverless.
const (
RDSEngineTypeMySQL = "MySQL"
RDSEngineTypePostgreSQL = "PostgreSQL"
)
var regexpMatchAttribute = regexp.MustCompile(`^(\S+):([sbnSBN])`)
var storageTemplateFunctions = map[string]interface{}{
"logicalIDSafe": template.StripNonAlphaNumFunc,
"envVarName": template.EnvVarNameFunc,
"envVarSecret": template.EnvVarSecretFunc,
"toSnakeCase": template.ToSnakeCaseFunc,
}
// StorageProps holds basic input properties for S3Props and DynamoDBProps.
type StorageProps struct {
Name string
}
// S3Props contains S3-specific properties.
type S3Props struct {
*StorageProps
}
// WorkloadS3Template creates a marshaler for a workload-level S3 addon.
func WorkloadS3Template(input *S3Props) *S3Template {
return &S3Template{
S3Props: *input,
parser: template.New(),
tmplPath: s3TemplatePath,
}
}
// EnvS3Template creates a new marshaler for an environment-level S3 addon.
func EnvS3Template(input *S3Props) *S3Template {
return &S3Template{
S3Props: *input,
parser: template.New(),
tmplPath: envS3TemplatePath,
}
}
// S3Template contains configuration options which fully describe an S3 bucket.
// Implements the encoding.BinaryMarshaler interface.
type S3Template struct {
S3Props
parser template.Parser
tmplPath string
}
// MarshalBinary serializes the content of the template into binary.
func (s *S3Template) MarshalBinary() ([]byte, error) {
content, err := s.parser.Parse(s.tmplPath, *s, template.WithFuncs(storageTemplateFunctions))
if err != nil {
return nil, err
}
return content.Bytes(), nil
}
// DynamoDBProps contains DynamoDB-specific properties.
type DynamoDBProps struct {
*StorageProps
Attributes []DDBAttribute
LSIs []DDBLocalSecondaryIndex
SortKey *string
PartitionKey *string
HasLSI bool
}
// WorkloadDDBTemplate creates a marshaler for a workload-level DynamoDB addon specifying attributes,
// primary key schema, and local secondary index configuration.
func WorkloadDDBTemplate(input *DynamoDBProps) *DynamoDBTemplate {
return &DynamoDBTemplate{
DynamoDBProps: *input,
parser: template.New(),
tmplPath: dynamoDbTemplatePath,
}
}
// EnvDDBTemplate creates a marshaller for an environment-level DynamoDB addon.
func EnvDDBTemplate(input *DynamoDBProps) *DynamoDBTemplate {
return &DynamoDBTemplate{
DynamoDBProps: *input,
parser: template.New(),
tmplPath: envDynamoDBTemplatePath,
}
}
// DynamoDBTemplate contains configuration options which fully describe a DynamoDB table.
// Implements the encoding.BinaryMarshaler interface.
type DynamoDBTemplate struct {
DynamoDBProps
parser template.Parser
tmplPath string
}
// MarshalBinary serializes the content of the template into binary.
func (d *DynamoDBTemplate) MarshalBinary() ([]byte, error) {
content, err := d.parser.Parse(d.tmplPath, *d, template.WithFuncs(storageTemplateFunctions))
if err != nil {
return nil, err
}
return content.Bytes(), nil
}
// BuildPartitionKey generates the properties required to specify the partition key
// based on customer inputs.
func (p *DynamoDBProps) BuildPartitionKey(partitionKey string) error {
partitionKeyAttribute, err := DDBAttributeFromKey(partitionKey)
if err != nil {
return err
}
p.Attributes = append(p.Attributes, partitionKeyAttribute)
p.PartitionKey = partitionKeyAttribute.Name
return nil
}
// BuildSortKey generates the correct property configuration based on customer inputs.
func (p *DynamoDBProps) BuildSortKey(noSort bool, sortKey string) (bool, error) {
if noSort || sortKey == "" {
return false, nil
}
sortKeyAttribute, err := DDBAttributeFromKey(sortKey)
if err != nil {
return false, err
}
p.Attributes = append(p.Attributes, sortKeyAttribute)
p.SortKey = sortKeyAttribute.Name
return true, nil
}
// BuildLocalSecondaryIndex generates the correct LocalSecondaryIndex property configuration
// based on customer input to ensure that the CF template is valid. BuildLocalSecondaryIndex
// should be called last, after BuildPartitionKey && BuildSortKey
func (p *DynamoDBProps) BuildLocalSecondaryIndex(noLSI bool, lsiSorts []string) (bool, error) {
// If there isn't yet a partition key on the struct, we can't do anything with this call.
if p.PartitionKey == nil {
return false, fmt.Errorf("partition key not specified")
}
// If a sort key hasn't been specified, or the customer has specified that there is no LSI,
// or there is implicitly no LSI based on the input lsiSorts value, do nothing.
if p.SortKey == nil || noLSI || len(lsiSorts) == 0 {
p.HasLSI = false
return false, nil
}
for _, att := range lsiSorts {
currAtt, err := DDBAttributeFromKey(att)
if err != nil {
return false, err
}
p.Attributes = append(p.Attributes, currAtt)
}
p.HasLSI = true
lsiConfig, err := newLSI(*p.PartitionKey, lsiSorts)
if err != nil {
return false, err
}
p.LSIs = lsiConfig
return true, nil
}
// DDBAttribute holds the attribute definition of a DynamoDB attribute (keys, local secondary indices).
type DDBAttribute struct {
Name *string
DataType *string // Must be one of "N", "S", "B"
}
// DDBAttributeFromKey parses the DDB type and name out of keys specified in the form "Email:S"
func DDBAttributeFromKey(input string) (DDBAttribute, error) {
attrs := regexpMatchAttribute.FindStringSubmatch(input)
if len(attrs) == 0 {
return DDBAttribute{}, fmt.Errorf("parse attribute from key: %s", input)
}
upperString := strings.ToUpper(attrs[2])
return DDBAttribute{
Name: &attrs[1],
DataType: &upperString,
}, nil
}
// DDBLocalSecondaryIndex holds a representation of an LSI.
type DDBLocalSecondaryIndex struct {
PartitionKey *string
SortKey *string
Name *string
}
// AccessPolicyProps holds properties to configure an access policy to an S3 or DDB storage.
type AccessPolicyProps StorageProps
// EnvS3AccessPolicyTemplate creates a new marshaler for the access policy attached to a workload
// for permissions into an environment-level S3 addon.
func EnvS3AccessPolicyTemplate(input *AccessPolicyProps) *AccessPolicyTemplate {
return &AccessPolicyTemplate{
AccessPolicyProps: *input,
parser: template.New(),
tmplPath: envS3AccessPolicyTemplatePath,
}
}
// EnvDDBAccessPolicyTemplate creates a marshaller for the access policy attached to a workload
// for permissions into an environment-level DynamoDB addon.
func EnvDDBAccessPolicyTemplate(input *AccessPolicyProps) *AccessPolicyTemplate {
return &AccessPolicyTemplate{
AccessPolicyProps: *input,
parser: template.New(),
tmplPath: envDynamoDBAccessPolicyTemplatePath,
}
}
// AccessPolicyTemplate contains configuration options which describe an access policy to an S3 or DDB storage.
// Implements the encoding.BinaryMarshaler interface.
type AccessPolicyTemplate struct {
AccessPolicyProps
parser template.Parser
tmplPath string
}
// MarshalBinary serializes the content of the template into binary.
func (t *AccessPolicyTemplate) MarshalBinary() ([]byte, error) {
content, err := t.parser.Parse(t.tmplPath, *t, template.WithFuncs(storageTemplateFunctions))
if err != nil {
return nil, err
}
return content.Bytes(), nil
}
// RDSProps holds RDS-specific properties.
type RDSProps struct {
ClusterName string // The name of the cluster.
Engine string // The engine type of the RDS Aurora Serverless cluster.
InitialDBName string // The name of the initial database created inside the cluster.
ParameterGroup string // The parameter group to use for the cluster.
Envs []string // The copilot environments found inside the current app.
}
// WorkloadServerlessV1Template creates a marshaler for a workload-level Aurora Serverless v1 addon.
func WorkloadServerlessV1Template(input RDSProps) *RDSTemplate {
return &RDSTemplate{
RDSProps: input,
parser: template.New(),
tmplPath: rdsTemplatePath,
}
}
// RDWSServerlessV1Template creates a marshaler for an Aurora Serverless v1 addon attached on an RDWS.
func RDWSServerlessV1Template(input RDSProps) *RDSTemplate {
return &RDSTemplate{
RDSProps: input,
parser: template.New(),
tmplPath: rdsRDWSTemplatePath,
}
}
// WorkloadServerlessV2Template creates a marshaler for a workload-level Aurora Serverless v2 addon.
func WorkloadServerlessV2Template(input RDSProps) *RDSTemplate {
return &RDSTemplate{
RDSProps: input,
parser: template.New(),
tmplPath: rdsV2TemplatePath,
}
}
// RDWSServerlessV2Template creates a marshaler for an Aurora Serverless v2 addon attached on an RDWS.
func RDWSServerlessV2Template(input RDSProps) *RDSTemplate {
return &RDSTemplate{
RDSProps: input,
parser: template.New(),
tmplPath: rdsV2RDWSTemplatePath,
}
}
// EnvServerlessTemplate creates a marshaler for an environment-level Aurora Serverless v2 addon.
func EnvServerlessTemplate(input RDSProps) *RDSTemplate {
return &RDSTemplate{
RDSProps: input,
parser: template.New(),
tmplPath: envRDSTemplatePath,
}
}
// EnvServerlessForRDWSTemplate creates a marshaler for an environment-level Aurora Serverless v2 addon
// whose ingress is an RDWS.
func EnvServerlessForRDWSTemplate(input RDSProps) *RDSTemplate {
return &RDSTemplate{
RDSProps: input,
parser: template.New(),
tmplPath: envRDSForRDWSTemplatePath,
}
}
// RDSIngressProps holds properties to create a security group ingress to an RDS storage.
type RDSIngressProps struct {
ClusterName string // The name of the cluster.
Engine string // The engine type of the RDS Aurora Serverless cluster.
}
// EnvServerlessRDWSIngressTemplate creates a marshaler for the security group ingress attached to an RDWS
// for permissions into an environment-level Aurora Serverless v2 addon.
func EnvServerlessRDWSIngressTemplate(input RDSIngressProps) *RDSIngressTemplate {
return &RDSIngressTemplate{
RDSIngressProps: input,
parser: template.New(),
tmplPath: envRDSIngressForRDWSTemplatePath,
}
}
// RDSIngressTemplate contains configuration options which describe an ingress to an RDS cluster.
// Implements the encoding.BinaryMarshaler interface.
type RDSIngressTemplate struct {
RDSIngressProps
parser template.Parser
tmplPath string
}
// MarshalBinary serializes the content of the template into binary.
func (t *RDSIngressTemplate) MarshalBinary() ([]byte, error) {
content, err := t.parser.Parse(t.tmplPath, *t, template.WithFuncs(storageTemplateFunctions))
if err != nil {
return nil, err
}
return content.Bytes(), nil
}
// RDSTemplate contains configuration options which fully describe aa RDS Aurora Serverless cluster.
// Implements the encoding.BinaryMarshaler interface.
type RDSTemplate struct {
RDSProps
parser template.Parser
tmplPath string
}
// MarshalBinary serializes the content of the template into binary.
func (r *RDSTemplate) MarshalBinary() ([]byte, error) {
content, err := r.parser.Parse(r.tmplPath, *r, template.WithFuncs(storageTemplateFunctions))
if err != nil {
return nil, err
}
return content.Bytes(), nil
}
// RDWSParamsForRDS creates a new RDS parameters marshaler.
func RDWSParamsForRDS() *RDSParams {
return &RDSParams{
parser: template.New(),
tmplPath: rdsRDWSParamsPath,
}
}
// EnvParamsForRDS creates a parameter marshaler for an environment-level RDS addon.
func EnvParamsForRDS() *RDSParams {
return &RDSParams{
parser: template.New(),
tmplPath: envRDSParamsPath,
}
}
// RDWSParamsForEnvRDS creates a parameter marshaler for the ingress attached to an RDWS
// for permissions into an environment-level RDS addon.
func RDWSParamsForEnvRDS() *RDSParams {
return &RDSParams{
parser: template.New(),
tmplPath: envRDSIngressForRDWSParamsPath,
}
}
// RDSParams represents the addons.parameters.yml file for a RDS Aurora Serverless cluster.
type RDSParams struct {
parser template.Parser
tmplPath string
}
// MarshalBinary serializes the content of the params file into binary.
func (r *RDSParams) MarshalBinary() ([]byte, error) {
content, err := r.parser.Parse(r.tmplPath, *r, template.WithFuncs(storageTemplateFunctions))
if err != nil {
return nil, err
}
return content.Bytes(), nil
}
func newLSI(partitionKey string, lsis []string) ([]DDBLocalSecondaryIndex, error) {
var output []DDBLocalSecondaryIndex
for _, lsi := range lsis {
lsiAttr, err := DDBAttributeFromKey(lsi)
if err != nil {
return nil, err
}
output = append(output, DDBLocalSecondaryIndex{
PartitionKey: &partitionKey,
SortKey: lsiAttr.Name,
Name: lsiAttr.Name,
})
}
return output, nil
}
| 438 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package addon contains the service to manage addons.
package addon
import (
"bytes"
"errors"
"fmt"
"testing"
"github.com/aws/copilot-cli/internal/pkg/template"
"github.com/aws/copilot-cli/internal/pkg/template/mocks"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
func TestDynamoDBTemplate_MarshalBinary(t *testing.T) {
testCases := map[string]struct {
mockDependencies func(ctrl *gomock.Controller, ddb *DynamoDBTemplate)
wantedBinary []byte
wantedError error
}{
"error parsing template": {
mockDependencies: func(ctrl *gomock.Controller, ddb *DynamoDBTemplate) {
m := mocks.NewMockParser(ctrl)
ddb.parser = m
m.EXPECT().Parse("mockPath", *ddb, gomock.Any()).Return(nil, errors.New("some error"))
},
wantedError: errors.New("some error"),
},
"returns rendered content": {
mockDependencies: func(ctrl *gomock.Controller, ddb *DynamoDBTemplate) {
m := mocks.NewMockParser(ctrl)
ddb.parser = m
m.EXPECT().Parse("mockPath", *ddb, gomock.Any()).Return(&template.Content{Buffer: bytes.NewBufferString("hello")}, nil)
},
wantedBinary: []byte("hello"),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
addon := &DynamoDBTemplate{
tmplPath: "mockPath",
}
tc.mockDependencies(ctrl, addon)
// WHEN
b, err := addon.MarshalBinary()
// THEN
require.Equal(t, tc.wantedError, err)
require.Equal(t, tc.wantedBinary, b)
})
}
}
func TestS3Template_MarshalBinary(t *testing.T) {
testCases := map[string]struct {
mockDependencies func(ctrl *gomock.Controller, s3 *S3Template)
wantedBinary []byte
wantedError error
}{
"error parsing template": {
mockDependencies: func(ctrl *gomock.Controller, s3 *S3Template) {
m := mocks.NewMockParser(ctrl)
s3.parser = m
m.EXPECT().Parse("mockPath", *s3, gomock.Any()).Return(nil, errors.New("some error"))
},
wantedError: errors.New("some error"),
},
"returns rendered content": {
mockDependencies: func(ctrl *gomock.Controller, s3 *S3Template) {
m := mocks.NewMockParser(ctrl)
s3.parser = m
m.EXPECT().Parse("mockPath", *s3, gomock.Any()).Return(&template.Content{Buffer: bytes.NewBufferString("hello")}, nil)
},
wantedBinary: []byte("hello"),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
addon := &S3Template{
tmplPath: "mockPath",
}
tc.mockDependencies(ctrl, addon)
// WHEN
b, err := addon.MarshalBinary()
// THEN
require.Equal(t, tc.wantedError, err)
require.Equal(t, tc.wantedBinary, b)
})
}
}
func TestRDSTemplate_MarshalBinary(t *testing.T) {
testCases := map[string]struct {
version string
engine string
mockDependencies func(ctrl *gomock.Controller, r *RDSTemplate)
wantedBinary []byte
wantedError error
}{
"error parsing template": {
version: auroraServerlessVersionV1,
engine: RDSEngineTypePostgreSQL,
mockDependencies: func(ctrl *gomock.Controller, r *RDSTemplate) {
m := mocks.NewMockParser(ctrl)
r.parser = m
m.EXPECT().Parse(gomock.Any(), *r, gomock.Any()).Return(nil, errors.New("some error"))
},
wantedError: errors.New("some error"),
},
"renders postgresql v1 content": {
version: auroraServerlessVersionV1,
engine: RDSEngineTypePostgreSQL,
mockDependencies: func(ctrl *gomock.Controller, r *RDSTemplate) {
m := mocks.NewMockParser(ctrl)
r.parser = m
m.EXPECT().Parse(gomock.Eq("mockPath"), *r, gomock.Any()).
Return(&template.Content{Buffer: bytes.NewBufferString("psql")}, nil)
},
wantedBinary: []byte("psql"),
},
"renders mysql v1 content": {
version: auroraServerlessVersionV1,
engine: RDSEngineTypeMySQL,
mockDependencies: func(ctrl *gomock.Controller, r *RDSTemplate) {
m := mocks.NewMockParser(ctrl)
r.parser = m
m.EXPECT().Parse(gomock.Eq("mockPath"), *r, gomock.Any()).
Return(&template.Content{Buffer: bytes.NewBufferString("mysql")}, nil)
},
wantedBinary: []byte("mysql"),
},
"renders postgresql v2 content": {
version: auroraServerlessVersionV2,
engine: RDSEngineTypePostgreSQL,
mockDependencies: func(ctrl *gomock.Controller, r *RDSTemplate) {
m := mocks.NewMockParser(ctrl)
r.parser = m
m.EXPECT().Parse(gomock.Eq("mockPath"), *r, gomock.Any()).
Return(&template.Content{Buffer: bytes.NewBufferString("psql")}, nil)
},
wantedBinary: []byte("psql"),
},
"renders mysql v2 content": {
version: auroraServerlessVersionV2,
engine: RDSEngineTypeMySQL,
mockDependencies: func(ctrl *gomock.Controller, r *RDSTemplate) {
m := mocks.NewMockParser(ctrl)
r.parser = m
m.EXPECT().Parse(gomock.Eq("mockPath"), *r, gomock.Any()).
Return(&template.Content{Buffer: bytes.NewBufferString("mysql")}, nil)
},
wantedBinary: []byte("mysql"),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
addon := &RDSTemplate{
RDSProps: RDSProps{
Engine: tc.engine,
},
tmplPath: "mockPath",
}
tc.mockDependencies(ctrl, addon)
// WHEN
b, err := addon.MarshalBinary()
// THEN
require.Equal(t, tc.wantedError, err)
require.Equal(t, tc.wantedBinary, b)
})
}
}
func TestRDSParams_MarshalBinary(t *testing.T) {
testCases := map[string]struct {
mockDependencies func(ctrl *gomock.Controller, r *RDSParams)
wantedBinary []byte
wantedError error
}{
"error parsing template": {
mockDependencies: func(ctrl *gomock.Controller, r *RDSParams) {
m := mocks.NewMockParser(ctrl)
r.parser = m
m.EXPECT().Parse(gomock.Any(), *r, gomock.Any()).Return(nil, errors.New("some error"))
},
wantedError: errors.New("some error"),
},
"renders param file with expected path": {
mockDependencies: func(ctrl *gomock.Controller, r *RDSParams) {
m := mocks.NewMockParser(ctrl)
r.parser = m
r.tmplPath = "mockPath"
m.EXPECT().Parse(gomock.Eq("mockPath"), *r, gomock.Any()).
Return(&template.Content{Buffer: bytes.NewBufferString("bloop")}, nil)
},
wantedBinary: []byte("bloop"),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
params := &RDSParams{}
tc.mockDependencies(ctrl, params)
// WHEN
b, err := params.MarshalBinary()
// THEN
require.Equal(t, tc.wantedError, err)
require.Equal(t, tc.wantedBinary, b)
})
}
}
func TestDDBAttributeFromKey(t *testing.T) {
testCases := map[string]struct {
input string
wantName string
wantType string
wantError error
}{
"good case": {
input: "userID:S",
wantName: "userID",
wantType: "S",
wantError: nil,
},
"bad case": {
input: "userID",
wantError: fmt.Errorf("parse attribute from key: %s", "userID"),
},
"non-ideal input": {
input: "userId_cool-table.d:binary",
wantName: "userId_cool-table.d",
wantType: "B",
wantError: nil,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
got, err := DDBAttributeFromKey(tc.input)
if tc.wantError != nil {
require.EqualError(t, err, tc.wantError.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantName, *got.Name)
require.Equal(t, tc.wantType, *got.DataType)
}
})
}
}
func TestNewLSI(t *testing.T) {
testPartitionKey := "Email"
testSortKey := "Goodness"
testCases := map[string]struct {
inPartitionKey string
inLSIs []string
wantedLSI []DDBLocalSecondaryIndex
wantError error
}{
"happy case": {
inPartitionKey: "Email",
inLSIs: []string{"Goodness:N"},
wantedLSI: []DDBLocalSecondaryIndex{
{
Name: &testSortKey,
PartitionKey: &testPartitionKey,
SortKey: &testSortKey,
},
},
},
"no error getting attribute": {
inPartitionKey: "Email",
inLSIs: []string{"goodness"},
wantError: fmt.Errorf("parse attribute from key: goodness"),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
got, err := newLSI(tc.inPartitionKey, tc.inLSIs)
if tc.wantError != nil {
require.EqualError(t, err, tc.wantError.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedLSI, got)
}
})
}
}
func TestBuildPartitionKey(t *testing.T) {
wantDataType := "S"
wantName := "userID"
testCases := map[string]struct {
input string
wantPartitionKey string
wantAttributes []DDBAttribute
wantError error
}{
"good case": {
input: "userID:S",
wantPartitionKey: wantName,
wantAttributes: []DDBAttribute{
{
DataType: &wantDataType,
Name: &wantName,
},
},
wantError: nil,
},
"error getting attribute": {
input: "userID",
wantError: fmt.Errorf("parse attribute from key: userID"),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
props := DynamoDBProps{}
err := props.BuildPartitionKey(tc.input)
if tc.wantError != nil {
require.EqualError(t, err, tc.wantError.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantPartitionKey, *props.PartitionKey)
require.Equal(t, tc.wantAttributes, props.Attributes)
}
})
}
}
func TestBuildSortKey(t *testing.T) {
wantDataType := "S"
wantName := "userID"
testCases := map[string]struct {
inSortKey string
inNoSort bool
wantSortKey string
wantHasSortKey bool
wantAttributes []DDBAttribute
wantError error
}{
"with sort key": {
inSortKey: "userID:S",
inNoSort: false,
wantSortKey: wantName,
wantAttributes: []DDBAttribute{
{
DataType: &wantDataType,
Name: &wantName,
},
},
wantHasSortKey: true,
wantError: nil,
},
"with noSort specified": {
inNoSort: true,
inSortKey: "userID:S",
wantSortKey: "",
wantHasSortKey: false,
},
"no sort key without noSort specified": {
inNoSort: false,
inSortKey: "",
wantSortKey: "",
wantHasSortKey: false,
},
"error getting attribute": {
inSortKey: "userID",
wantError: fmt.Errorf("parse attribute from key: userID"),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
props := DynamoDBProps{}
got, err := props.BuildSortKey(tc.inNoSort, tc.inSortKey)
if tc.wantError != nil {
require.EqualError(t, err, tc.wantError.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantAttributes, props.Attributes)
require.Equal(t, tc.wantHasSortKey, got)
if tc.wantSortKey == "" {
require.Nil(t, props.SortKey)
} else {
require.Equal(t, tc.wantSortKey, *props.SortKey)
}
}
})
}
}
func TestBuildLocalSecondaryIndex(t *testing.T) {
wantSortKey := "userID"
wantPartitionKey := "email"
wantLSIName := "points"
wantLSIType := "N"
testCases := map[string]struct {
inPartitionKey *string
inSortKey *string
inNoLSI bool
inLSISorts []string
wantedLSI []DDBLocalSecondaryIndex
wantedAttributes []DDBAttribute
wantedHasLSI bool
wantedError error
}{
"error if no partition key": {
inPartitionKey: nil,
wantedError: fmt.Errorf("partition key not specified"),
},
"no LSI if sort key not specified": {
inPartitionKey: &wantPartitionKey,
inSortKey: nil,
inLSISorts: []string{"points:N"},
wantedHasLSI: false,
},
"no LSI if noLSI specified": {
inPartitionKey: &wantPartitionKey,
inSortKey: &wantSortKey,
inLSISorts: []string{"points:N"},
inNoLSI: true,
wantedHasLSI: false,
},
"no LSI if length of LSIs is 0": {
inPartitionKey: &wantPartitionKey,
inSortKey: &wantSortKey,
inNoLSI: false,
wantedHasLSI: false,
},
"LSI specified correctly": {
inPartitionKey: &wantPartitionKey,
inSortKey: &wantSortKey,
inNoLSI: false,
inLSISorts: []string{wantLSIName + ":" + wantLSIType},
wantedHasLSI: true,
wantedLSI: []DDBLocalSecondaryIndex{
{
Name: &wantLSIName,
PartitionKey: &wantPartitionKey,
SortKey: &wantLSIName,
},
},
wantedAttributes: []DDBAttribute{
{
DataType: &wantLSIType,
Name: &wantLSIName,
},
},
wantedError: nil,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
props := DynamoDBProps{}
props.PartitionKey = tc.inPartitionKey
props.SortKey = tc.inSortKey
got, err := props.BuildLocalSecondaryIndex(tc.inNoLSI, tc.inLSISorts)
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedHasLSI, props.HasLSI)
require.Equal(t, tc.wantedHasLSI, got)
for idx, att := range props.Attributes {
require.Equal(t, *tc.wantedAttributes[idx].DataType, *att.DataType)
require.Equal(t, *tc.wantedAttributes[idx].Name, *att.Name)
}
for idx, lsi := range props.LSIs {
require.Equal(t, *tc.wantedLSI[idx].Name, *lsi.Name)
require.Equal(t, *tc.wantedLSI[idx].PartitionKey, *lsi.PartitionKey)
require.Equal(t, *tc.wantedLSI[idx].SortKey, *lsi.SortKey)
}
}
})
}
}
func TestConstructors(t *testing.T) {
t.Run("marshaler for workload-level S3", func(t *testing.T) {
out := WorkloadS3Template(&S3Props{})
require.Equal(t, s3TemplatePath, out.tmplPath)
})
t.Run("marshaler for env-level S3", func(t *testing.T) {
out := EnvS3Template(&S3Props{})
require.Equal(t, envS3TemplatePath, out.tmplPath)
})
t.Run("marshaler for the access policy of an env-level S3", func(t *testing.T) {
out := EnvS3AccessPolicyTemplate(&AccessPolicyProps{})
require.Equal(t, envS3AccessPolicyTemplatePath, out.tmplPath)
})
t.Run("marshaler for workload-level ddb", func(t *testing.T) {
out := WorkloadDDBTemplate(&DynamoDBProps{})
require.Equal(t, dynamoDbTemplatePath, out.tmplPath)
})
t.Run("marshaler for env-level ddb", func(t *testing.T) {
out := EnvDDBTemplate(&DynamoDBProps{})
require.Equal(t, envDynamoDBTemplatePath, out.tmplPath)
})
t.Run("marshaler for the access policy of an env-level ddb", func(t *testing.T) {
out := EnvDDBAccessPolicyTemplate(&AccessPolicyProps{})
require.Equal(t, envDynamoDBAccessPolicyTemplatePath, out.tmplPath)
})
t.Run("marshaler for non-RDWS workload-level aurora serverless v1", func(t *testing.T) {
out := WorkloadServerlessV1Template(RDSProps{})
require.Equal(t, rdsTemplatePath, out.tmplPath)
})
t.Run("marshaler for non-RDWS workload-level aurora serverless v2", func(t *testing.T) {
out := WorkloadServerlessV2Template(RDSProps{})
require.Equal(t, rdsV2TemplatePath, out.tmplPath)
})
t.Run("parameter marshaler for RDWS workload-level aurora serverless v1/v2", func(t *testing.T) {
out := RDWSParamsForRDS()
require.Equal(t, rdsRDWSParamsPath, out.tmplPath)
})
t.Run("marshaler for RDWS workload-level aurora serverless v1", func(t *testing.T) {
out := RDWSServerlessV1Template(RDSProps{})
require.Equal(t, rdsRDWSTemplatePath, out.tmplPath)
})
t.Run("marshaler for RDWS workload-level aurora serverless v2", func(t *testing.T) {
out := RDWSServerlessV2Template(RDSProps{})
require.Equal(t, rdsV2RDWSTemplatePath, out.tmplPath)
})
t.Run("parameter marshaler for env-level aurora accessible by a workload", func(t *testing.T) {
out := EnvParamsForRDS()
require.Equal(t, envRDSParamsPath, out.tmplPath)
})
t.Run("marshaler for env-level aurora accessible by a non-RDWS", func(t *testing.T) {
out := EnvServerlessTemplate(RDSProps{})
require.Equal(t, envRDSTemplatePath, out.tmplPath)
})
t.Run("marshaler for env-level aurora accessible by an RDWS", func(t *testing.T) {
out := EnvServerlessForRDWSTemplate(RDSProps{})
require.Equal(t, envRDSForRDWSTemplatePath, out.tmplPath)
})
t.Run("parameter marshaler for the ingress attached to an RDWS for an env-level aurora", func(t *testing.T) {
out := RDWSParamsForEnvRDS()
require.Equal(t, envRDSIngressForRDWSParamsPath, out.tmplPath)
})
t.Run("marshaler for the ingress attached to an RDWS for an env-level aurora", func(t *testing.T) {
out := EnvServerlessRDWSIngressTemplate(RDSIngressProps{})
require.Equal(t, envRDSIngressForRDWSTemplatePath, out.tmplPath)
})
}
| 601 |
copilot-cli | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: ./internal/pkg/addon/addons.go
// Package mocks is a generated GoMock package.
package mocks
import (
reflect "reflect"
gomock "github.com/golang/mock/gomock"
)
// MockWorkspaceAddonsReader is a mock of WorkspaceAddonsReader interface.
type MockWorkspaceAddonsReader struct {
ctrl *gomock.Controller
recorder *MockWorkspaceAddonsReaderMockRecorder
}
// MockWorkspaceAddonsReaderMockRecorder is the mock recorder for MockWorkspaceAddonsReader.
type MockWorkspaceAddonsReaderMockRecorder struct {
mock *MockWorkspaceAddonsReader
}
// NewMockWorkspaceAddonsReader creates a new mock instance.
func NewMockWorkspaceAddonsReader(ctrl *gomock.Controller) *MockWorkspaceAddonsReader {
mock := &MockWorkspaceAddonsReader{ctrl: ctrl}
mock.recorder = &MockWorkspaceAddonsReaderMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockWorkspaceAddonsReader) EXPECT() *MockWorkspaceAddonsReaderMockRecorder {
return m.recorder
}
// EnvAddonFileAbsPath mocks base method.
func (m *MockWorkspaceAddonsReader) EnvAddonFileAbsPath(fName string) string {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "EnvAddonFileAbsPath", fName)
ret0, _ := ret[0].(string)
return ret0
}
// EnvAddonFileAbsPath indicates an expected call of EnvAddonFileAbsPath.
func (mr *MockWorkspaceAddonsReaderMockRecorder) EnvAddonFileAbsPath(fName interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EnvAddonFileAbsPath", reflect.TypeOf((*MockWorkspaceAddonsReader)(nil).EnvAddonFileAbsPath), fName)
}
// EnvAddonsAbsPath mocks base method.
func (m *MockWorkspaceAddonsReader) EnvAddonsAbsPath() string {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "EnvAddonsAbsPath")
ret0, _ := ret[0].(string)
return ret0
}
// EnvAddonsAbsPath indicates an expected call of EnvAddonsAbsPath.
func (mr *MockWorkspaceAddonsReaderMockRecorder) EnvAddonsAbsPath() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EnvAddonsAbsPath", reflect.TypeOf((*MockWorkspaceAddonsReader)(nil).EnvAddonsAbsPath))
}
// ListFiles mocks base method.
func (m *MockWorkspaceAddonsReader) ListFiles(dirPath string) ([]string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListFiles", dirPath)
ret0, _ := ret[0].([]string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ListFiles indicates an expected call of ListFiles.
func (mr *MockWorkspaceAddonsReaderMockRecorder) ListFiles(dirPath interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListFiles", reflect.TypeOf((*MockWorkspaceAddonsReader)(nil).ListFiles), dirPath)
}
// ReadFile mocks base method.
func (m *MockWorkspaceAddonsReader) ReadFile(fPath string) ([]byte, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ReadFile", fPath)
ret0, _ := ret[0].([]byte)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ReadFile indicates an expected call of ReadFile.
func (mr *MockWorkspaceAddonsReaderMockRecorder) ReadFile(fPath interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReadFile", reflect.TypeOf((*MockWorkspaceAddonsReader)(nil).ReadFile), fPath)
}
// WorkloadAddonFileAbsPath mocks base method.
func (m *MockWorkspaceAddonsReader) WorkloadAddonFileAbsPath(wkldName, fName string) string {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "WorkloadAddonFileAbsPath", wkldName, fName)
ret0, _ := ret[0].(string)
return ret0
}
// WorkloadAddonFileAbsPath indicates an expected call of WorkloadAddonFileAbsPath.
func (mr *MockWorkspaceAddonsReaderMockRecorder) WorkloadAddonFileAbsPath(wkldName, fName interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WorkloadAddonFileAbsPath", reflect.TypeOf((*MockWorkspaceAddonsReader)(nil).WorkloadAddonFileAbsPath), wkldName, fName)
}
// WorkloadAddonsAbsPath mocks base method.
func (m *MockWorkspaceAddonsReader) WorkloadAddonsAbsPath(name string) string {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "WorkloadAddonsAbsPath", name)
ret0, _ := ret[0].(string)
return ret0
}
// WorkloadAddonsAbsPath indicates an expected call of WorkloadAddonsAbsPath.
func (mr *MockWorkspaceAddonsReaderMockRecorder) WorkloadAddonsAbsPath(name interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WorkloadAddonsAbsPath", reflect.TypeOf((*MockWorkspaceAddonsReader)(nil).WorkloadAddonsAbsPath), name)
}
| 121 |
copilot-cli | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: ./internal/pkg/addon/package.go
// Package mocks is a generated GoMock package.
package mocks
import (
io "io"
reflect "reflect"
gomock "github.com/golang/mock/gomock"
)
// Mockuploader is a mock of uploader interface.
type Mockuploader struct {
ctrl *gomock.Controller
recorder *MockuploaderMockRecorder
}
// MockuploaderMockRecorder is the mock recorder for Mockuploader.
type MockuploaderMockRecorder struct {
mock *Mockuploader
}
// NewMockuploader creates a new mock instance.
func NewMockuploader(ctrl *gomock.Controller) *Mockuploader {
mock := &Mockuploader{ctrl: ctrl}
mock.recorder = &MockuploaderMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *Mockuploader) EXPECT() *MockuploaderMockRecorder {
return m.recorder
}
// Upload mocks base method.
func (m *Mockuploader) Upload(bucket, key string, data io.Reader) (string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Upload", bucket, key, data)
ret0, _ := ret[0].(string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Upload indicates an expected call of Upload.
func (mr *MockuploaderMockRecorder) Upload(bucket, key, data interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Upload", reflect.TypeOf((*Mockuploader)(nil).Upload), bucket, key, data)
}
| 51 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package apprunner provides a client to retrieve Copilot App Runner information.
package apprunner
import (
"fmt"
"time"
"github.com/aws/aws-sdk-go/aws/session"
awsapprunner "github.com/aws/aws-sdk-go/service/apprunner"
"github.com/aws/copilot-cli/internal/pkg/aws/apprunner"
"github.com/aws/copilot-cli/internal/pkg/aws/resourcegroups"
"github.com/aws/copilot-cli/internal/pkg/deploy"
)
const (
serviceResourceType = "apprunner:service"
)
type appRunnerClient interface {
DescribeOperation(operationId, svcARN string) (*awsapprunner.OperationSummary, error)
StartDeployment(svcARN string) (string, error)
DescribeService(svcARN string) (*apprunner.Service, error)
WaitForOperation(operationId, svcARN string) error
}
type resourceGetter interface {
GetResourcesByTags(resourceType string, tags map[string]string) ([]*resourcegroups.Resource, error)
}
// Client retrieves Copilot information from App Runner endpoint.
type Client struct {
appRunnerClient appRunnerClient
rgGetter resourceGetter
}
// New inits a new Client.
func New(sess *session.Session) *Client {
return &Client{
rgGetter: resourcegroups.New(sess),
appRunnerClient: apprunner.New(sess),
}
}
// ForceUpdateService forces a new update for an App Runner service given Copilot service info.
func (c Client) ForceUpdateService(app, env, svc string) error {
svcARN, err := c.serviceARN(app, env, svc)
if err != nil {
return err
}
id, err := c.appRunnerClient.StartDeployment(svcARN)
if err != nil {
return err
}
return c.appRunnerClient.WaitForOperation(id, svcARN)
}
// LastUpdatedAt returns the last updated time of the app runner service.
func (c Client) LastUpdatedAt(app, env, svc string) (time.Time, error) {
svcARN, err := c.serviceARN(app, env, svc)
if err != nil {
return time.Time{}, err
}
desc, err := c.appRunnerClient.DescribeService(svcARN)
if err != nil {
return time.Time{}, fmt.Errorf("describe service: %w", err)
}
return desc.DateUpdated, nil
}
func (c Client) serviceARN(app, env, svc string) (string, error) {
services, err := c.rgGetter.GetResourcesByTags(serviceResourceType, map[string]string{
deploy.AppTagKey: app,
deploy.EnvTagKey: env,
deploy.ServiceTagKey: svc,
})
if err != nil {
return "", fmt.Errorf("get App Runner service with tags (%s, %s, %s): %w", app, env, svc, err)
}
if len(services) == 0 {
return "", fmt.Errorf("no App Runner service found for %s in environment %s", svc, env)
}
if len(services) > 1 {
return "", fmt.Errorf("more than one App Runner service with the name %s found in environment %s", svc, env)
}
return services[0].ARN, nil
}
| 90 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package apprunner
import (
"errors"
"fmt"
"testing"
"time"
"github.com/aws/copilot-cli/internal/pkg/apprunner/mocks"
"github.com/aws/copilot-cli/internal/pkg/aws/apprunner"
"github.com/aws/copilot-cli/internal/pkg/aws/resourcegroups"
"github.com/aws/copilot-cli/internal/pkg/deploy"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
type clientMocks struct {
rgMock *mocks.MockresourceGetter
appRunnerMock *mocks.MockappRunnerClient
}
func TestClient_ForceUpdateService(t *testing.T) {
mockError := errors.New("some error")
const (
mockApp = "mockApp"
mockSvc = "mockSvc"
mockEnv = "mockEnv"
mockSvcARN = "mockSvcARN"
mockOperationID = "mockOperationID"
)
getRgInput := map[string]string{
deploy.AppTagKey: mockApp,
deploy.EnvTagKey: mockEnv,
deploy.ServiceTagKey: mockSvc,
}
tests := map[string]struct {
mock func(m *clientMocks)
wantErr error
}{
"fail get the app runner service": {
mock: func(m *clientMocks) {
m.rgMock.EXPECT().GetResourcesByTags(serviceResourceType, getRgInput).Return(nil, mockError)
},
wantErr: fmt.Errorf("get App Runner service with tags (mockApp, mockEnv, mockSvc): some error"),
},
"no app runner service found": {
mock: func(m *clientMocks) {
m.rgMock.EXPECT().GetResourcesByTags(serviceResourceType, getRgInput).
Return([]*resourcegroups.Resource{}, nil)
},
wantErr: fmt.Errorf("no App Runner service found for mockSvc in environment mockEnv"),
},
"more than one app runner service found": {
mock: func(m *clientMocks) {
m.rgMock.EXPECT().GetResourcesByTags(serviceResourceType, getRgInput).
Return([]*resourcegroups.Resource{
{}, {},
}, nil)
},
wantErr: fmt.Errorf("more than one App Runner service with the name mockSvc found in environment mockEnv"),
},
"error if fail to start new deployment": {
mock: func(m *clientMocks) {
m.rgMock.EXPECT().GetResourcesByTags(serviceResourceType, getRgInput).
Return([]*resourcegroups.Resource{
{
ARN: mockSvcARN,
},
}, nil)
m.appRunnerMock.EXPECT().StartDeployment(mockSvcARN).Return("", mockError)
},
wantErr: fmt.Errorf("some error"),
},
"error if fail to wait for deployment": {
mock: func(m *clientMocks) {
m.rgMock.EXPECT().GetResourcesByTags(serviceResourceType, getRgInput).
Return([]*resourcegroups.Resource{
{
ARN: mockSvcARN,
},
}, nil)
m.appRunnerMock.EXPECT().StartDeployment(mockSvcARN).Return(mockOperationID, nil)
m.appRunnerMock.EXPECT().WaitForOperation(mockOperationID, mockSvcARN).Return(mockError)
},
wantErr: fmt.Errorf("some error"),
},
"success": {
mock: func(m *clientMocks) {
m.rgMock.EXPECT().GetResourcesByTags(serviceResourceType, getRgInput).
Return([]*resourcegroups.Resource{
{
ARN: mockSvcARN,
},
}, nil)
m.appRunnerMock.EXPECT().StartDeployment(mockSvcARN).Return(mockOperationID, nil)
m.appRunnerMock.EXPECT().WaitForOperation(mockOperationID, mockSvcARN).Return(nil)
},
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockRg := mocks.NewMockresourceGetter(ctrl)
mockAppRunner := mocks.NewMockappRunnerClient(ctrl)
m := &clientMocks{
rgMock: mockRg,
appRunnerMock: mockAppRunner,
}
tc.mock(m)
c := Client{
appRunnerClient: mockAppRunner,
rgGetter: mockRg,
}
gotErr := c.ForceUpdateService(mockApp, mockEnv, mockSvc)
if tc.wantErr != nil {
require.EqualError(t, gotErr, tc.wantErr.Error())
} else {
require.NoError(t, gotErr)
}
})
}
}
func TestClient_LastUpdatedAt(t *testing.T) {
mockError := errors.New("some error")
const (
mockApp = "mockApp"
mockSvc = "mockSvc"
mockEnv = "mockEnv"
mockSvcARN = "mockSvcARN"
)
mockTime := time.Unix(1494505756, 0)
getRgInput := map[string]string{
deploy.AppTagKey: mockApp,
deploy.EnvTagKey: mockEnv,
deploy.ServiceTagKey: mockSvc,
}
tests := map[string]struct {
mock func(m *clientMocks)
wantErr error
want time.Time
}{
"error if fail to describe service": {
mock: func(m *clientMocks) {
m.rgMock.EXPECT().GetResourcesByTags(serviceResourceType, getRgInput).
Return([]*resourcegroups.Resource{
{
ARN: mockSvcARN,
},
}, nil)
m.appRunnerMock.EXPECT().DescribeService(mockSvcARN).Return(nil, mockError)
},
wantErr: fmt.Errorf("describe service: some error"),
},
"succeed": {
mock: func(m *clientMocks) {
m.rgMock.EXPECT().GetResourcesByTags(serviceResourceType, getRgInput).
Return([]*resourcegroups.Resource{
{
ARN: mockSvcARN,
},
}, nil)
m.appRunnerMock.EXPECT().DescribeService(mockSvcARN).Return(&apprunner.Service{
DateUpdated: mockTime,
}, nil)
},
want: mockTime,
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockRg := mocks.NewMockresourceGetter(ctrl)
mockAppRunner := mocks.NewMockappRunnerClient(ctrl)
m := &clientMocks{
rgMock: mockRg,
appRunnerMock: mockAppRunner,
}
tc.mock(m)
c := Client{
appRunnerClient: mockAppRunner,
rgGetter: mockRg,
}
got, gotErr := c.LastUpdatedAt(mockApp, mockEnv, mockSvc)
if tc.wantErr != nil {
require.EqualError(t, gotErr, tc.wantErr.Error())
} else {
require.NoError(t, gotErr)
require.Equal(t, tc.want, got)
}
})
}
}
| 211 |
copilot-cli | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: ./internal/pkg/apprunner/apprunner.go
// Package mocks is a generated GoMock package.
package mocks
import (
reflect "reflect"
apprunner "github.com/aws/aws-sdk-go/service/apprunner"
apprunner0 "github.com/aws/copilot-cli/internal/pkg/aws/apprunner"
resourcegroups "github.com/aws/copilot-cli/internal/pkg/aws/resourcegroups"
gomock "github.com/golang/mock/gomock"
)
// MockappRunnerClient is a mock of appRunnerClient interface.
type MockappRunnerClient struct {
ctrl *gomock.Controller
recorder *MockappRunnerClientMockRecorder
}
// MockappRunnerClientMockRecorder is the mock recorder for MockappRunnerClient.
type MockappRunnerClientMockRecorder struct {
mock *MockappRunnerClient
}
// NewMockappRunnerClient creates a new mock instance.
func NewMockappRunnerClient(ctrl *gomock.Controller) *MockappRunnerClient {
mock := &MockappRunnerClient{ctrl: ctrl}
mock.recorder = &MockappRunnerClientMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockappRunnerClient) EXPECT() *MockappRunnerClientMockRecorder {
return m.recorder
}
// DescribeOperation mocks base method.
func (m *MockappRunnerClient) DescribeOperation(operationId, svcARN string) (*apprunner.OperationSummary, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DescribeOperation", operationId, svcARN)
ret0, _ := ret[0].(*apprunner.OperationSummary)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DescribeOperation indicates an expected call of DescribeOperation.
func (mr *MockappRunnerClientMockRecorder) DescribeOperation(operationId, svcARN interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeOperation", reflect.TypeOf((*MockappRunnerClient)(nil).DescribeOperation), operationId, svcARN)
}
// DescribeService mocks base method.
func (m *MockappRunnerClient) DescribeService(svcARN string) (*apprunner0.Service, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DescribeService", svcARN)
ret0, _ := ret[0].(*apprunner0.Service)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DescribeService indicates an expected call of DescribeService.
func (mr *MockappRunnerClientMockRecorder) DescribeService(svcARN interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeService", reflect.TypeOf((*MockappRunnerClient)(nil).DescribeService), svcARN)
}
// StartDeployment mocks base method.
func (m *MockappRunnerClient) StartDeployment(svcARN string) (string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "StartDeployment", svcARN)
ret0, _ := ret[0].(string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// StartDeployment indicates an expected call of StartDeployment.
func (mr *MockappRunnerClientMockRecorder) StartDeployment(svcARN interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StartDeployment", reflect.TypeOf((*MockappRunnerClient)(nil).StartDeployment), svcARN)
}
// WaitForOperation mocks base method.
func (m *MockappRunnerClient) WaitForOperation(operationId, svcARN string) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "WaitForOperation", operationId, svcARN)
ret0, _ := ret[0].(error)
return ret0
}
// WaitForOperation indicates an expected call of WaitForOperation.
func (mr *MockappRunnerClientMockRecorder) WaitForOperation(operationId, svcARN interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WaitForOperation", reflect.TypeOf((*MockappRunnerClient)(nil).WaitForOperation), operationId, svcARN)
}
// MockresourceGetter is a mock of resourceGetter interface.
type MockresourceGetter struct {
ctrl *gomock.Controller
recorder *MockresourceGetterMockRecorder
}
// MockresourceGetterMockRecorder is the mock recorder for MockresourceGetter.
type MockresourceGetterMockRecorder struct {
mock *MockresourceGetter
}
// NewMockresourceGetter creates a new mock instance.
func NewMockresourceGetter(ctrl *gomock.Controller) *MockresourceGetter {
mock := &MockresourceGetter{ctrl: ctrl}
mock.recorder = &MockresourceGetterMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockresourceGetter) EXPECT() *MockresourceGetterMockRecorder {
return m.recorder
}
// GetResourcesByTags mocks base method.
func (m *MockresourceGetter) GetResourcesByTags(resourceType string, tags map[string]string) ([]*resourcegroups.Resource, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetResourcesByTags", resourceType, tags)
ret0, _ := ret[0].([]*resourcegroups.Resource)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetResourcesByTags indicates an expected call of GetResourcesByTags.
func (mr *MockresourceGetterMockRecorder) GetResourcesByTags(resourceType, tags interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetResourcesByTags", reflect.TypeOf((*MockresourceGetter)(nil).GetResourcesByTags), resourceType, tags)
}
| 135 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package aas provides a client to make API requests to Application Auto Scaling.
package aas
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
aas "github.com/aws/aws-sdk-go/service/applicationautoscaling"
"github.com/aws/aws-sdk-go/aws/session"
)
const (
// ECS service resource ID format: service/${clusterName}/${serviceName}.
fmtECSResourceID = "service/%s/%s"
ecsServiceNamespace = "ecs"
)
type api interface {
DescribeScalingPolicies(input *aas.DescribeScalingPoliciesInput) (*aas.DescribeScalingPoliciesOutput, error)
}
// ApplicationAutoscaling wraps an Amazon Application Auto Scaling client.
type ApplicationAutoscaling struct {
client api
}
// New returns a ApplicationAutoscaling struct configured against the input session.
func New(s *session.Session) *ApplicationAutoscaling {
return &ApplicationAutoscaling{
client: aas.New(s),
}
}
// ECSServiceAlarmNames returns names of the CloudWatch alarms associated with the
// scaling policies attached to the ECS service.
func (a *ApplicationAutoscaling) ECSServiceAlarmNames(cluster, service string) ([]string, error) {
resourceID := fmt.Sprintf(fmtECSResourceID, cluster, service)
var alarms []string
var err error
resp := &aas.DescribeScalingPoliciesOutput{}
for {
resp, err = a.client.DescribeScalingPolicies(&aas.DescribeScalingPoliciesInput{
ResourceId: aws.String(resourceID),
ServiceNamespace: aws.String(ecsServiceNamespace),
NextToken: resp.NextToken,
})
if err != nil {
return nil, fmt.Errorf("describe scaling policies for ECS service %s/%s: %w", cluster, service, err)
}
for _, policy := range resp.ScalingPolicies {
for _, alarm := range policy.Alarms {
alarms = append(alarms, aws.StringValue(alarm.AlarmName))
}
}
if resp.NextToken == nil {
break
}
}
return alarms, nil
}
| 65 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package aas
import (
"errors"
"fmt"
"testing"
"github.com/aws/aws-sdk-go/aws"
aas "github.com/aws/aws-sdk-go/service/applicationautoscaling"
"github.com/aws/copilot-cli/internal/pkg/aws/aas/mocks"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
type aasMocks struct {
client *mocks.Mockapi
}
func TestCloudWatch_ECSServiceAutoscalingAlarms(t *testing.T) {
const (
mockCluster = "mockCluster"
mockService = "mockService"
mockResourceID = "service/mockCluster/mockService"
mockNextToken = "mockNextToken"
)
mockError := errors.New("some error")
testCases := map[string]struct {
setupMocks func(m aasMocks)
wantErr error
wantAlarmNames []string
}{
"errors if failed to retrieve auto scaling alarm names": {
setupMocks: func(m aasMocks) {
m.client.EXPECT().DescribeScalingPolicies(gomock.Any()).Return(nil, mockError)
},
wantErr: fmt.Errorf("describe scaling policies for ECS service mockCluster/mockService: some error"),
},
"success": {
setupMocks: func(m aasMocks) {
m.client.EXPECT().DescribeScalingPolicies(&aas.DescribeScalingPoliciesInput{
ResourceId: aws.String(mockResourceID),
ServiceNamespace: aws.String(ecsServiceNamespace),
}).Return(&aas.DescribeScalingPoliciesOutput{
ScalingPolicies: []*aas.ScalingPolicy{
{
Alarms: []*aas.Alarm{
{
AlarmName: aws.String("mockAlarm1"),
},
{
AlarmName: aws.String("mockAlarm2"),
},
},
},
{
Alarms: []*aas.Alarm{
{
AlarmName: aws.String("mockAlarm3"),
},
},
},
},
}, nil)
},
wantAlarmNames: []string{"mockAlarm1", "mockAlarm2", "mockAlarm3"},
},
"success with pagination": {
setupMocks: func(m aasMocks) {
gomock.InOrder(
m.client.EXPECT().DescribeScalingPolicies(&aas.DescribeScalingPoliciesInput{
ResourceId: aws.String(mockResourceID),
ServiceNamespace: aws.String(ecsServiceNamespace),
}).Return(&aas.DescribeScalingPoliciesOutput{
ScalingPolicies: []*aas.ScalingPolicy{
{
Alarms: []*aas.Alarm{
{
AlarmName: aws.String("mockAlarm1"),
},
},
},
},
NextToken: aws.String(mockNextToken),
}, nil),
m.client.EXPECT().DescribeScalingPolicies(&aas.DescribeScalingPoliciesInput{
ResourceId: aws.String(mockResourceID),
ServiceNamespace: aws.String(ecsServiceNamespace),
NextToken: aws.String(mockNextToken),
}).Return(&aas.DescribeScalingPoliciesOutput{
ScalingPolicies: []*aas.ScalingPolicy{
{
Alarms: []*aas.Alarm{
{
AlarmName: aws.String("mockAlarm2"),
},
},
},
},
}, nil),
)
},
wantAlarmNames: []string{"mockAlarm1", "mockAlarm2"},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockClient := mocks.NewMockapi(ctrl)
mocks := aasMocks{
client: mockClient,
}
tc.setupMocks(mocks)
aasSvc := ApplicationAutoscaling{
client: mockClient,
}
gotAlarmNames, gotErr := aasSvc.ECSServiceAlarmNames(mockCluster, mockService)
if gotErr != nil {
require.EqualError(t, tc.wantErr, gotErr.Error())
} else {
require.Equal(t, tc.wantAlarmNames, gotAlarmNames)
}
})
}
}
| 142 |
copilot-cli | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: ./internal/pkg/aws/aas/aas.go
// Package mocks is a generated GoMock package.
package mocks
import (
reflect "reflect"
applicationautoscaling "github.com/aws/aws-sdk-go/service/applicationautoscaling"
gomock "github.com/golang/mock/gomock"
)
// Mockapi is a mock of api interface.
type Mockapi struct {
ctrl *gomock.Controller
recorder *MockapiMockRecorder
}
// MockapiMockRecorder is the mock recorder for Mockapi.
type MockapiMockRecorder struct {
mock *Mockapi
}
// NewMockapi creates a new mock instance.
func NewMockapi(ctrl *gomock.Controller) *Mockapi {
mock := &Mockapi{ctrl: ctrl}
mock.recorder = &MockapiMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *Mockapi) EXPECT() *MockapiMockRecorder {
return m.recorder
}
// DescribeScalingPolicies mocks base method.
func (m *Mockapi) DescribeScalingPolicies(input *applicationautoscaling.DescribeScalingPoliciesInput) (*applicationautoscaling.DescribeScalingPoliciesOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DescribeScalingPolicies", input)
ret0, _ := ret[0].(*applicationautoscaling.DescribeScalingPoliciesOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DescribeScalingPolicies indicates an expected call of DescribeScalingPolicies.
func (mr *MockapiMockRecorder) DescribeScalingPolicies(input interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeScalingPolicies", reflect.TypeOf((*Mockapi)(nil).DescribeScalingPolicies), input)
}
| 51 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package acm provides a client to make API requests to AWS Certificate Manager.
package acm
import (
"context"
"fmt"
"strings"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/acm"
"github.com/dustin/go-humanize/english"
"golang.org/x/sync/errgroup"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/session"
)
const (
waitForFindValidAliasesTimeout = 10 * time.Second
)
type api interface {
DescribeCertificateWithContext(ctx aws.Context, input *acm.DescribeCertificateInput, opts ...request.Option) (*acm.DescribeCertificateOutput, error)
}
// ACM wraps an AWS Certificate Manager client.
type ACM struct {
client api
}
// New returns an ACM struct configured against the input session.
func New(s *session.Session) *ACM {
return &ACM{
client: acm.New(s),
}
}
// ValidateCertAliases validates if aliases are all valid against the provided ACM certificates.
func (a *ACM) ValidateCertAliases(aliases []string, certs []string) error {
validAliases := make(map[string]bool)
domainsOfCert := make(map[string][]string)
ctx, cancelWait := context.WithTimeout(context.Background(), waitForFindValidAliasesTimeout)
defer cancelWait()
g, ctx := errgroup.WithContext(ctx)
var mux sync.Mutex
for i := range certs {
cert := certs[i]
g.Go(func() error {
domains, err := a.validDomainsOfCert(ctx, cert)
if err != nil {
return err
}
validCertAliases := filterValidAliases(domains, aliases)
mux.Lock()
defer mux.Unlock()
domainsOfCert[cert] = domains
for _, alias := range validCertAliases {
validAliases[alias] = true
}
return nil
})
}
if err := g.Wait(); err != nil {
return err
}
for _, alias := range aliases {
if !validAliases[alias] {
return &errInValidAliasAgainstCert{
certs: certs,
alias: alias,
domainsOfCert: domainsOfCert,
}
}
}
return nil
}
func (a *ACM) validDomainsOfCert(ctx context.Context, cert string) ([]string, error) {
resp, err := a.client.DescribeCertificateWithContext(ctx, &acm.DescribeCertificateInput{
CertificateArn: aws.String(cert),
})
if err != nil {
return nil, fmt.Errorf("describe certificate %s: %w", cert, err)
}
var domainsOfCert []*string
domainsOfCert = append(domainsOfCert, resp.Certificate.SubjectAlternativeNames...)
return aws.StringValueSlice(domainsOfCert), err
}
func filterValidAliases(domains []string, aliases []string) []string {
domainSet := make(map[string]bool, len(domains))
for _, v := range domains {
domainSet[v] = true
}
var validAliases []string
for _, alias := range aliases {
// See https://docs.aws.amazon.com/acm/latest/userguide/acm-certificate.html
wildCardMatchedAlias := "*" + alias[strings.Index(alias, "."):]
if domainSet[alias] || domainSet[wildCardMatchedAlias] {
validAliases = append(validAliases, alias)
}
}
return validAliases
}
type errInValidAliasAgainstCert struct {
certs []string
alias string
domainsOfCert map[string][]string
}
func (e *errInValidAliasAgainstCert) Error() string {
return fmt.Sprintf("%s is not a valid domain against %s", e.alias, strings.Join(e.certs, ","))
}
func (e *errInValidAliasAgainstCert) RecommendActions() string {
var logMsg string
logMsg = fmt.Sprintf("Please use aliases that are protected by %s your imported:\n", english.Plural(len(e.certs), "certificate", ""))
for cert, sans := range e.domainsOfCert {
logMsg += fmt.Sprintf("%q: %s\n", cert, english.WordSeries(sans, ","))
}
return logMsg
}
| 129 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package acm
import (
"errors"
"fmt"
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/acm"
"github.com/aws/copilot-cli/internal/pkg/aws/acm/mocks"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
type acmMocks struct {
client *mocks.Mockapi
}
func TestACM_ValidateCertAliases(t *testing.T) {
const ()
mockError := errors.New("some error")
testCases := map[string]struct {
setupMocks func(m acmMocks)
inAliases []string
inCerts []string
wantErr error
wantAlarmNames []string
}{
"errors if failed to describe certificates": {
inAliases: []string{"copilot.com"},
inCerts: []string{"mockCertARN"},
setupMocks: func(m acmMocks) {
m.client.EXPECT().DescribeCertificateWithContext(gomock.Any(), &acm.DescribeCertificateInput{
CertificateArn: aws.String("mockCertARN"),
}).Return(nil, mockError)
},
wantErr: fmt.Errorf("describe certificate mockCertARN: some error"),
},
"invalid alias": {
inAliases: []string{"v1.copilot.com", "myapp.v1.copilot.com"},
inCerts: []string{"mockCertARN"},
setupMocks: func(m acmMocks) {
m.client.EXPECT().DescribeCertificateWithContext(gomock.Any(), &acm.DescribeCertificateInput{
CertificateArn: aws.String("mockCertARN"),
}).Return(&acm.DescribeCertificateOutput{
Certificate: &acm.CertificateDetail{
SubjectAlternativeNames: aws.StringSlice([]string{"example.com", "*.copilot.com"}),
},
}, nil)
},
wantErr: fmt.Errorf("myapp.v1.copilot.com is not a valid domain against mockCertARN"),
},
"success": {
inAliases: []string{"v1.copilot.com", "example.com"},
inCerts: []string{"mockCertARN1", "mockCertARN2"},
setupMocks: func(m acmMocks) {
m.client.EXPECT().DescribeCertificateWithContext(gomock.Any(), &acm.DescribeCertificateInput{
CertificateArn: aws.String("mockCertARN1"),
}).Return(&acm.DescribeCertificateOutput{
Certificate: &acm.CertificateDetail{
SubjectAlternativeNames: aws.StringSlice([]string{"copilot.com", "*.copilot.com"}),
},
}, nil)
m.client.EXPECT().DescribeCertificateWithContext(gomock.Any(), &acm.DescribeCertificateInput{
CertificateArn: aws.String("mockCertARN2"),
}).Return(&acm.DescribeCertificateOutput{
Certificate: &acm.CertificateDetail{
SubjectAlternativeNames: aws.StringSlice([]string{"example.com"}),
},
}, nil)
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockClient := mocks.NewMockapi(ctrl)
mocks := acmMocks{
client: mockClient,
}
tc.setupMocks(mocks)
acmSvc := ACM{
client: mockClient,
}
gotErr := acmSvc.ValidateCertAliases(tc.inAliases, tc.inCerts)
if gotErr != nil {
require.EqualError(t, tc.wantErr, gotErr.Error())
} else {
require.NoError(t, tc.wantErr)
}
})
}
}
| 110 |
copilot-cli | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: ./internal/pkg/aws/acm/acm.go
// Package mocks is a generated GoMock package.
package mocks
import (
reflect "reflect"
aws "github.com/aws/aws-sdk-go/aws"
request "github.com/aws/aws-sdk-go/aws/request"
acm "github.com/aws/aws-sdk-go/service/acm"
gomock "github.com/golang/mock/gomock"
)
// Mockapi is a mock of api interface.
type Mockapi struct {
ctrl *gomock.Controller
recorder *MockapiMockRecorder
}
// MockapiMockRecorder is the mock recorder for Mockapi.
type MockapiMockRecorder struct {
mock *Mockapi
}
// NewMockapi creates a new mock instance.
func NewMockapi(ctrl *gomock.Controller) *Mockapi {
mock := &Mockapi{ctrl: ctrl}
mock.recorder = &MockapiMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *Mockapi) EXPECT() *MockapiMockRecorder {
return m.recorder
}
// DescribeCertificateWithContext mocks base method.
func (m *Mockapi) DescribeCertificateWithContext(ctx aws.Context, input *acm.DescribeCertificateInput, opts ...request.Option) (*acm.DescribeCertificateOutput, error) {
m.ctrl.T.Helper()
varargs := []interface{}{ctx, input}
for _, a := range opts {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "DescribeCertificateWithContext", varargs...)
ret0, _ := ret[0].(*acm.DescribeCertificateOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DescribeCertificateWithContext indicates an expected call of DescribeCertificateWithContext.
func (mr *MockapiMockRecorder) DescribeCertificateWithContext(ctx, input interface{}, opts ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{ctx, input}, opts...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeCertificateWithContext", reflect.TypeOf((*Mockapi)(nil).DescribeCertificateWithContext), varargs...)
}
| 58 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package apprunner provides a client to make API requests to AppRunner Service.
package apprunner
import (
"fmt"
"regexp"
"sort"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/arn"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/apprunner"
)
const (
fmtAppRunnerServiceLogGroupName = "/aws/apprunner/%s/%s/service"
fmtAppRunnerApplicationLogGroupName = "/aws/apprunner/%s/%s/application"
// App Runner Statuses
opStatusSucceeded = "SUCCEEDED"
opStatusFailed = "FAILED"
svcStatusPaused = "PAUSED"
svcStatusRunning = "RUNNING"
// App Runner ImageRepositoryTypes
repositoryTypeECR = "ECR"
repositoryTypeECRPublic = "ECR_PUBLIC"
// EndpointsID is the ID to look up the App Runner service endpoint.
EndpointsID = apprunner.EndpointsID
)
type api interface {
DescribeService(input *apprunner.DescribeServiceInput) (*apprunner.DescribeServiceOutput, error)
ListOperations(input *apprunner.ListOperationsInput) (*apprunner.ListOperationsOutput, error)
ListServices(input *apprunner.ListServicesInput) (*apprunner.ListServicesOutput, error)
PauseService(input *apprunner.PauseServiceInput) (*apprunner.PauseServiceOutput, error)
ResumeService(input *apprunner.ResumeServiceInput) (*apprunner.ResumeServiceOutput, error)
StartDeployment(input *apprunner.StartDeploymentInput) (*apprunner.StartDeploymentOutput, error)
DescribeObservabilityConfiguration(input *apprunner.DescribeObservabilityConfigurationInput) (*apprunner.DescribeObservabilityConfigurationOutput, error)
DescribeVpcIngressConnection(input *apprunner.DescribeVpcIngressConnectionInput) (*apprunner.DescribeVpcIngressConnectionOutput, error)
}
// AppRunner wraps an AWS AppRunner client.
type AppRunner struct {
client api
}
// New returns a Service configured against the input session.
func New(s *session.Session) *AppRunner {
return &AppRunner{
client: apprunner.New(s),
}
}
// DescribeService returns a description of an AppRunner service given its ARN.
func (a *AppRunner) DescribeService(svcARN string) (*Service, error) {
resp, err := a.client.DescribeService(&apprunner.DescribeServiceInput{
ServiceArn: aws.String(svcARN),
})
if err != nil {
return nil, fmt.Errorf("describe service %s: %w", svcARN, err)
}
var envVars []*EnvironmentVariable
for k, v := range resp.Service.SourceConfiguration.ImageRepository.ImageConfiguration.RuntimeEnvironmentVariables {
envVars = append(envVars, &EnvironmentVariable{
Name: k,
Value: aws.StringValue(v),
})
}
sort.SliceStable(envVars, func(i int, j int) bool { return envVars[i].Name < envVars[j].Name })
var secrets []*EnvironmentSecret
for k, v := range resp.Service.SourceConfiguration.ImageRepository.ImageConfiguration.RuntimeEnvironmentSecrets {
secrets = append(secrets, &EnvironmentSecret{
Name: k,
Value: aws.StringValue(v),
})
}
sort.SliceStable(secrets, func(i int, j int) bool { return secrets[i].Name < secrets[j].Name })
var observabilityConfiguration ObservabilityConfiguration
if resp.Service.ObservabilityConfiguration != nil && aws.BoolValue(resp.Service.ObservabilityConfiguration.ObservabilityEnabled) {
if out, err := a.client.DescribeObservabilityConfiguration(&apprunner.DescribeObservabilityConfigurationInput{
ObservabilityConfigurationArn: resp.Service.ObservabilityConfiguration.ObservabilityConfigurationArn,
}); err == nil {
// NOTE: swallow the error otherwise, because observability is an optional description of the service.
// Example error: when "EnvManagerRole" doesn't have the "apprunner:ObservabilityConfiguration" permission.
observabilityConfiguration = ObservabilityConfiguration{
TraceConfiguration: (*TraceConfiguration)(out.ObservabilityConfiguration.TraceConfiguration),
}
}
}
return &Service{
ServiceARN: aws.StringValue(resp.Service.ServiceArn),
Name: aws.StringValue(resp.Service.ServiceName),
ID: aws.StringValue(resp.Service.ServiceId),
Status: aws.StringValue(resp.Service.Status),
ServiceURL: aws.StringValue(resp.Service.ServiceUrl),
DateCreated: *resp.Service.CreatedAt,
DateUpdated: *resp.Service.UpdatedAt,
EnvironmentVariables: envVars,
CPU: *resp.Service.InstanceConfiguration.Cpu,
Memory: *resp.Service.InstanceConfiguration.Memory,
ImageID: *resp.Service.SourceConfiguration.ImageRepository.ImageIdentifier,
Port: *resp.Service.SourceConfiguration.ImageRepository.ImageConfiguration.Port,
Observability: observabilityConfiguration,
EnvironmentSecrets: secrets,
}, nil
}
// ServiceARN returns the ARN of an AppRunner service given its service name.
func (a *AppRunner) ServiceARN(svc string) (string, error) {
var nextToken *string
for {
resp, err := a.client.ListServices(&apprunner.ListServicesInput{
NextToken: nextToken,
})
if err != nil {
return "", fmt.Errorf("list AppRunner services: %w", err)
}
for _, service := range resp.ServiceSummaryList {
if aws.StringValue(service.ServiceName) == svc {
return aws.StringValue(service.ServiceArn), nil
}
}
if resp.NextToken == nil {
break
}
nextToken = resp.NextToken
}
return "", fmt.Errorf("no AppRunner service found for %s", svc)
}
// PauseService pause the running App Runner service.
func (a *AppRunner) PauseService(svcARN string) error {
resp, err := a.client.PauseService(&apprunner.PauseServiceInput{
ServiceArn: aws.String(svcARN),
})
if err != nil {
return fmt.Errorf("pause service operation failed: %w", err)
}
if resp.OperationId == nil && aws.StringValue(resp.Service.Status) == svcStatusPaused {
return nil
}
if err := a.WaitForOperation(aws.StringValue(resp.OperationId), svcARN); err != nil {
return err
}
return nil
}
// ResumeService resumes a paused App Runner service.
func (a *AppRunner) ResumeService(svcARN string) error {
resp, err := a.client.ResumeService(&apprunner.ResumeServiceInput{
ServiceArn: aws.String(svcARN),
})
if err != nil {
return fmt.Errorf("resume service operation failed: %w", err)
}
if resp.OperationId == nil && aws.StringValue(resp.Service.Status) == svcStatusRunning {
return nil
}
if err := a.WaitForOperation(aws.StringValue(resp.OperationId), svcARN); err != nil {
return err
}
return nil
}
// StartDeployment initiates a manual deployment to an AWS App Runner service.
func (a *AppRunner) StartDeployment(svcARN string) (string, error) {
out, err := a.client.StartDeployment(&apprunner.StartDeploymentInput{
ServiceArn: aws.String(svcARN),
})
if err != nil {
return "", fmt.Errorf("start new deployment: %w", err)
}
return aws.StringValue(out.OperationId), nil
}
// DescribeOperation return OperationSummary for given OperationId and ServiceARN.
func (a *AppRunner) DescribeOperation(operationId, svcARN string) (*apprunner.OperationSummary, error) {
var nextToken *string
for {
resp, err := a.client.ListOperations(&apprunner.ListOperationsInput{
ServiceArn: aws.String(svcARN),
NextToken: nextToken,
})
if err != nil {
return nil, fmt.Errorf("list operations: %w", err)
}
for _, operation := range resp.OperationSummaryList {
if aws.StringValue(operation.Id) == operationId {
return operation, nil
}
}
if resp.NextToken == nil {
break
}
nextToken = resp.NextToken
}
return nil, fmt.Errorf("no operation found %s", operationId)
}
// WaitForOperation waits for a service operation.
func (a *AppRunner) WaitForOperation(operationId, svcARN string) error {
for {
resp, err := a.DescribeOperation(operationId, svcARN)
if err != nil {
return fmt.Errorf("error describing operation %s: %w", operationId, err)
}
switch status := aws.StringValue(resp.Status); status {
case opStatusSucceeded:
return nil
case opStatusFailed:
return &ErrWaitServiceOperationFailed{
operationId: operationId,
}
}
time.Sleep(3 * time.Second)
}
}
// PrivateURL returns the url associated with a VPC Ingress Connection.
func (a *AppRunner) PrivateURL(vicARN string) (string, error) {
resp, err := a.client.DescribeVpcIngressConnection(&apprunner.DescribeVpcIngressConnectionInput{
VpcIngressConnectionArn: aws.String(vicARN),
})
if err != nil {
return "", fmt.Errorf("describe vpc ingress connection %q: %w", vicARN, err)
}
return aws.StringValue(resp.VpcIngressConnection.DomainName), nil
}
// ParseServiceName returns the service name.
// For example: arn:aws:apprunner:us-west-2:1234567890:service/my-service/fc1098ac269245959ba78fd58bdd4bf
// will return my-service
func ParseServiceName(svcARN string) (string, error) {
parsedARN, err := arn.Parse(svcARN)
if err != nil {
return "", err
}
resources := strings.Split(parsedARN.Resource, "/")
if len(resources) != 3 {
return "", fmt.Errorf("cannot parse resource for ARN %s", svcARN)
}
return resources[1], nil
}
// ParseServiceID returns the service id.
// For example: arn:aws:apprunner:us-west-2:1234567890:service/my-service/fc1098ac269245959ba78fd58bdd4bf
// will return fc1098ac269245959ba78fd58bdd4bf
func ParseServiceID(svcARN string) (string, error) {
parsedARN, err := arn.Parse(svcARN)
if err != nil {
return "", err
}
resources := strings.Split(parsedARN.Resource, "/")
if len(resources) != 3 {
return "", fmt.Errorf("cannot parse resource for ARN %s", svcARN)
}
return resources[2], nil
}
// LogGroupName returns the log group name given the app runner service's name.
// An application log group is formatted as "/aws/apprunner/<svcName>/<svcID>/application".
func LogGroupName(svcARN string) (string, error) {
svcName, err := ParseServiceName(svcARN)
if err != nil {
return "", fmt.Errorf("get service name: %w", err)
}
svcID, err := ParseServiceID(svcARN)
if err != nil {
return "", fmt.Errorf("get service id: %w", err)
}
return fmt.Sprintf(fmtAppRunnerApplicationLogGroupName, svcName, svcID), nil
}
// SystemLogGroupName returns the service log group name given the app runner service's name.
// A service log group is formatted as "/aws/apprunner/<svcName>/<svcID>/service".
func SystemLogGroupName(svcARN string) (string, error) {
svcName, err := ParseServiceName(svcARN)
if err != nil {
return "", fmt.Errorf("get service name: %w", err)
}
svcID, err := ParseServiceID(svcARN)
if err != nil {
return "", fmt.Errorf("get service id: %w", err)
}
return fmt.Sprintf(fmtAppRunnerServiceLogGroupName, svcName, svcID), nil
}
// ImageIsSupported returns true if the image identifier is supported by App Runner.
func ImageIsSupported(imageIdentifier string) bool {
return imageIsECR(imageIdentifier) || imageIsECRPublic(imageIdentifier)
}
// DetermineImageRepositoryType returns the App Runner ImageRepositoryType enum value for the provided image identifier,
// or returns an error if the imageIdentifier is not supported by App Runner or the ImageRepositoryType cannot be
// determined.
func DetermineImageRepositoryType(imageIdentifier string) (string, error) {
if !ImageIsSupported(imageIdentifier) {
return "", fmt.Errorf("image is not supported by App Runner: %s", imageIdentifier)
}
if imageIsECR(imageIdentifier) {
return repositoryTypeECR, nil
}
if imageIsECRPublic(imageIdentifier) {
return repositoryTypeECRPublic, nil
}
return "", fmt.Errorf("unable to determine the image repository type for image: %s", imageIdentifier)
}
func imageIsECR(imageIdentifier string) bool {
matched, _ := regexp.Match(`^\d{12}\.dkr\.ecr\.[^\.]+\.amazonaws\.com/`, []byte(imageIdentifier))
return matched
}
func imageIsECRPublic(imageIdentifier string) bool {
matched, _ := regexp.Match(`^public\.ecr\.aws/`, []byte(imageIdentifier))
return matched
}
| 331 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package apprunner
import (
"errors"
"fmt"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/apprunner"
"github.com/aws/copilot-cli/internal/pkg/aws/apprunner/mocks"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
func TestAppRunner_DescribeService(t *testing.T) {
mockTime, _ := time.Parse(time.RFC3339, "2006-01-02T15:04:05+00:00")
testCases := map[string]struct {
serviceArn string
mockAppRunnerClient func(m *mocks.Mockapi)
wantErr error
wantSvc Service
}{
"success": {
serviceArn: "mock-svc-arn",
mockAppRunnerClient: func(m *mocks.Mockapi) {
m.EXPECT().DescribeService(&apprunner.DescribeServiceInput{
ServiceArn: aws.String("mock-svc-arn"),
}).Return(&apprunner.DescribeServiceOutput{
Service: &apprunner.Service{
ServiceArn: aws.String("111111111111.apprunner.us-east-1.amazonaws.com/service/testsvc/test-svc-id"),
ServiceId: aws.String("test-svc-id"),
ServiceName: aws.String("testapp-testenv-testsvc"),
ServiceUrl: aws.String("tumkjmvjif.public.us-east-1.apprunner.aws.dev"),
Status: aws.String("RUNNING"),
CreatedAt: &mockTime,
UpdatedAt: &mockTime,
InstanceConfiguration: &apprunner.InstanceConfiguration{
Cpu: aws.String("1024"),
Memory: aws.String("2048"),
},
SourceConfiguration: &apprunner.SourceConfiguration{
ImageRepository: &apprunner.ImageRepository{
ImageIdentifier: aws.String("111111111111.dkr.ecr.us-east-1.amazonaws.com/testapp/testsvc:8cdef9a"),
ImageConfiguration: &apprunner.ImageConfiguration{
RuntimeEnvironmentVariables: aws.StringMap(map[string]string{
"LOG_LEVEL": "info",
"COPILOT_APPLICATION_NAME": "testapp",
}),
RuntimeEnvironmentSecrets: aws.StringMap(map[string]string{
"zzz123": "parameter/zzz123",
"my-ssm-secret": "arn:aws:ssm:us-east-1:111111111111:parameter/jan11ssm",
}),
Port: aws.String("80"),
},
},
},
},
}, nil)
},
wantSvc: Service{
ServiceARN: "111111111111.apprunner.us-east-1.amazonaws.com/service/testsvc/test-svc-id",
Name: "testapp-testenv-testsvc",
ID: "test-svc-id",
Status: "RUNNING",
ServiceURL: "tumkjmvjif.public.us-east-1.apprunner.aws.dev",
DateCreated: mockTime,
DateUpdated: mockTime,
EnvironmentVariables: []*EnvironmentVariable{
{
Name: "COPILOT_APPLICATION_NAME",
Value: "testapp",
},
{
Name: "LOG_LEVEL",
Value: "info",
},
},
EnvironmentSecrets: []*EnvironmentSecret{
{
Name: "my-ssm-secret",
Value: "arn:aws:ssm:us-east-1:111111111111:parameter/jan11ssm",
},
{
Name: "zzz123",
Value: "parameter/zzz123",
},
},
CPU: "1024",
Memory: "2048",
Port: "80",
ImageID: "111111111111.dkr.ecr.us-east-1.amazonaws.com/testapp/testsvc:8cdef9a",
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockAppRunnerClient := mocks.NewMockapi(ctrl)
tc.mockAppRunnerClient(mockAppRunnerClient)
service := AppRunner{
client: mockAppRunnerClient,
}
gotSvc, gotErr := service.DescribeService(tc.serviceArn)
if gotErr != nil {
require.EqualError(t, tc.wantErr, gotErr.Error())
} else {
require.Equal(t, tc.wantSvc, *gotSvc)
}
})
}
}
func TestAppRunner_ServiceARN(t *testing.T) {
const (
mockSvc = "mockSvc"
mockSvcARN = "mockSvcArn"
)
testError := errors.New("some error")
testCases := map[string]struct {
mockAppRunnerClient func(m *mocks.Mockapi)
wantErr error
wantSvcARN string
}{
"success": {
mockAppRunnerClient: func(m *mocks.Mockapi) {
m.EXPECT().ListServices(&apprunner.ListServicesInput{}).Return(&apprunner.ListServicesOutput{
ServiceSummaryList: []*apprunner.ServiceSummary{
{
ServiceName: aws.String("mockSvc"),
ServiceArn: aws.String("mockSvcArn"),
},
{
ServiceName: aws.String("mockSvc2"),
ServiceArn: aws.String("mockSvcArn2"),
},
},
}, nil)
},
wantSvcARN: mockSvcARN,
},
"errors if fail to get services": {
mockAppRunnerClient: func(m *mocks.Mockapi) {
m.EXPECT().ListServices(&apprunner.ListServicesInput{}).Return(nil, testError)
},
wantErr: fmt.Errorf("list AppRunner services: some error"),
},
"errors if no service found": {
mockAppRunnerClient: func(m *mocks.Mockapi) {
m.EXPECT().ListServices(&apprunner.ListServicesInput{}).Return(&apprunner.ListServicesOutput{
ServiceSummaryList: []*apprunner.ServiceSummary{
{
ServiceName: aws.String("mockSvc2"),
ServiceArn: aws.String("mockSvcArn2"),
},
},
}, nil)
},
wantErr: fmt.Errorf("no AppRunner service found for mockSvc"),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockAppRunnerClient := mocks.NewMockapi(ctrl)
tc.mockAppRunnerClient(mockAppRunnerClient)
service := AppRunner{
client: mockAppRunnerClient,
}
svcArn, err := service.ServiceARN("mockSvc")
if err != nil {
require.EqualError(t, tc.wantErr, err.Error())
} else {
require.Equal(t, tc.wantSvcARN, svcArn)
}
})
}
}
func Test_ParseServiceName(t *testing.T) {
testCases := map[string]struct {
svcARN string
wantErr error
wantSvcName string
}{
"invalid ARN": {
svcARN: "mockBadSvcARN",
wantErr: fmt.Errorf("arn: invalid prefix"),
},
"empty svc ARN": {
svcARN: "",
wantErr: fmt.Errorf("arn: invalid prefix"),
},
"successfully parse name from service ARN": {
svcARN: "arn:aws:apprunner:us-west-2:1234567890:service/my-service/svc-id",
wantSvcName: "my-service",
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
svcName, err := ParseServiceName(tc.svcARN)
if tc.wantErr != nil {
require.EqualError(t, err, tc.wantErr.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantSvcName, svcName)
}
})
}
}
func Test_ParseServiceID(t *testing.T) {
testCases := map[string]struct {
svcARN string
wantErr error
wantSvcID string
}{
"invalid ARN": {
svcARN: "mockBadSvcARN",
wantErr: fmt.Errorf("arn: invalid prefix"),
},
"empty svc ARN": {
svcARN: "",
wantErr: fmt.Errorf("arn: invalid prefix"),
},
"successfully parse ID from service ARN": {
svcARN: "arn:aws:apprunner:us-west-2:1234567890:service/my-service/svc-id",
wantSvcID: "svc-id",
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
svcID, err := ParseServiceID(tc.svcARN)
if tc.wantErr != nil {
require.EqualError(t, err, tc.wantErr.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantSvcID, svcID)
}
})
}
}
func Test_LogGroupName(t *testing.T) {
testCases := map[string]struct {
svcARN string
wantErr error
wantLogGroupName string
}{
"errors if ARN is invalid": {
svcARN: "this is not a valid arn",
wantErr: fmt.Errorf("get service name: arn: invalid prefix"),
},
"errors if ARN is missing ID": {
svcARN: "arn:aws:apprunner:us-west-2:1234567890:service/my-service",
wantErr: fmt.Errorf("get service name: cannot parse resource for ARN arn:aws:apprunner:us-west-2:1234567890:service/my-service"),
},
"success": {
svcARN: "arn:aws:apprunner:us-west-2:1234567890:service/my-service/svc-id",
wantLogGroupName: "/aws/apprunner/my-service/svc-id/application",
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
logGroupName, err := LogGroupName(tc.svcARN)
if tc.wantErr != nil {
require.EqualError(t, err, tc.wantErr.Error())
} else {
require.Equal(t, nil, err)
require.Equal(t, tc.wantLogGroupName, logGroupName)
}
})
}
}
func Test_SystemLogGroupName(t *testing.T) {
testCases := map[string]struct {
svcARN string
wantErr error
wantLogGroupName string
}{
"errors if ARN is invalid": {
svcARN: "this is not a valid arn",
wantErr: fmt.Errorf("get service name: arn: invalid prefix"),
},
"errors if ARN is missing ID": {
svcARN: "arn:aws:apprunner:us-west-2:1234567890:service/my-service",
wantErr: fmt.Errorf("get service name: cannot parse resource for ARN arn:aws:apprunner:us-west-2:1234567890:service/my-service"),
},
"success": {
svcARN: "arn:aws:apprunner:us-west-2:1234567890:service/my-service/svc-id",
wantLogGroupName: "/aws/apprunner/my-service/svc-id/service",
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
logGroupName, err := SystemLogGroupName(tc.svcARN)
if tc.wantErr != nil {
require.EqualError(t, err, tc.wantErr.Error())
} else {
require.Equal(t, nil, err)
require.Equal(t, tc.wantLogGroupName, logGroupName)
}
})
}
}
func TestAppRunner_DescribeOperation(t *testing.T) {
const (
mockOperationId = "mock-operation"
mockSvcARN = "mockSvcArn"
)
mockOperationSummary := apprunner.OperationSummary{
Id: aws.String("mock-operation"),
TargetArn: aws.String("mockSvcArn"),
Status: aws.String("SUCCEEDED"),
}
testError := errors.New("some error")
testCases := map[string]struct {
mockAppRunnerClient func(m *mocks.Mockapi)
wantErr error
wantSvcOperation *apprunner.OperationSummary
}{
"error if fail to get operation": {
mockAppRunnerClient: func(m *mocks.Mockapi) {
m.EXPECT().ListOperations(&apprunner.ListOperationsInput{ServiceArn: aws.String(mockSvcARN)}).Return(nil, testError)
},
wantErr: fmt.Errorf("list operations: some error"),
},
"error if no operation found for given operation id": {
mockAppRunnerClient: func(m *mocks.Mockapi) {
m.EXPECT().ListOperations(&apprunner.ListOperationsInput{ServiceArn: aws.String(mockSvcARN)}).Return(&apprunner.ListOperationsOutput{
OperationSummaryList: []*apprunner.OperationSummary{
{
Id: aws.String("badOperationId"),
TargetArn: aws.String(mockSvcARN),
},
},
}, nil)
},
wantErr: fmt.Errorf("no operation found mock-operation"),
},
"success": {
mockAppRunnerClient: func(m *mocks.Mockapi) {
m.EXPECT().ListOperations(&apprunner.ListOperationsInput{ServiceArn: aws.String(mockSvcARN)}).Return(&apprunner.ListOperationsOutput{
OperationSummaryList: []*apprunner.OperationSummary{
{
Id: aws.String(mockOperationId),
TargetArn: aws.String(mockSvcARN),
Status: aws.String("SUCCEEDED"),
},
},
}, nil)
},
wantSvcOperation: &mockOperationSummary,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockAppRunnerClient := mocks.NewMockapi(ctrl)
tc.mockAppRunnerClient(mockAppRunnerClient)
service := AppRunner{
client: mockAppRunnerClient,
}
operation, err := service.DescribeOperation(mockOperationId, mockSvcARN)
if err != nil {
require.EqualError(t, tc.wantErr, err.Error())
} else {
require.Equal(t, tc.wantSvcOperation, operation)
}
})
}
}
func TestAppRunner_PrivateURL(t *testing.T) {
const mockARN = "mockVicArn"
tests := map[string]struct {
mockAppRunnerClient func(m *mocks.Mockapi)
expectedErr string
expectedURL string
}{
"error if error from sdk": {
mockAppRunnerClient: func(m *mocks.Mockapi) {
m.EXPECT().DescribeVpcIngressConnection(&apprunner.DescribeVpcIngressConnectionInput{
VpcIngressConnectionArn: aws.String(mockARN),
}).Return(nil, errors.New("some error"))
},
expectedErr: `describe vpc ingress connection "mockVicArn": some error`,
},
"success": {
mockAppRunnerClient: func(m *mocks.Mockapi) {
m.EXPECT().DescribeVpcIngressConnection(&apprunner.DescribeVpcIngressConnectionInput{
VpcIngressConnectionArn: aws.String(mockARN),
}).Return(&apprunner.DescribeVpcIngressConnectionOutput{
VpcIngressConnection: &apprunner.VpcIngressConnection{
DomainName: aws.String("example.com"),
},
}, nil)
},
expectedURL: "example.com",
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockAppRunnerClient := mocks.NewMockapi(ctrl)
tc.mockAppRunnerClient(mockAppRunnerClient)
service := AppRunner{
client: mockAppRunnerClient,
}
url, err := service.PrivateURL(mockARN)
if tc.expectedErr != "" {
require.EqualError(t, err, tc.expectedErr)
}
require.Equal(t, tc.expectedURL, url)
})
}
}
func TestAppRunner_PauseService(t *testing.T) {
const (
mockOperationId = "mock-operation"
mockSvcARN = "mockSvcArn"
)
testCases := map[string]struct {
mockAppRunnerClient func(m *mocks.Mockapi)
wantErr error
wantSvcOperation *apprunner.OperationSummary
}{
"success if service is already paused": {
mockAppRunnerClient: func(m *mocks.Mockapi) {
m.EXPECT().PauseService(&apprunner.PauseServiceInput{ServiceArn: aws.String(mockSvcARN)}).Return(&apprunner.PauseServiceOutput{
OperationId: nil,
Service: &apprunner.Service{
ServiceArn: aws.String(mockSvcARN),
Status: aws.String("PAUSED"),
},
}, nil)
},
},
"waits until operation succeeds": {
mockAppRunnerClient: func(m *mocks.Mockapi) {
m.EXPECT().PauseService(&apprunner.PauseServiceInput{ServiceArn: aws.String(mockSvcARN)}).Return(&apprunner.PauseServiceOutput{
OperationId: aws.String(mockOperationId),
Service: &apprunner.Service{
ServiceArn: aws.String(mockSvcARN),
},
}, nil)
m.EXPECT().ListOperations(&apprunner.ListOperationsInput{ServiceArn: aws.String(mockSvcARN)}).Return(&apprunner.ListOperationsOutput{
OperationSummaryList: []*apprunner.OperationSummary{
{
Id: aws.String(mockOperationId),
TargetArn: aws.String(mockSvcARN),
Status: aws.String("SUCCEEDED"),
},
},
}, nil)
},
},
"return error if operation failed": {
mockAppRunnerClient: func(m *mocks.Mockapi) {
m.EXPECT().PauseService(&apprunner.PauseServiceInput{ServiceArn: aws.String(mockSvcARN)}).Return(&apprunner.PauseServiceOutput{
OperationId: aws.String(mockOperationId),
Service: &apprunner.Service{
ServiceArn: aws.String(mockSvcARN),
},
}, nil)
m.EXPECT().ListOperations(&apprunner.ListOperationsInput{ServiceArn: aws.String(mockSvcARN)}).Return(&apprunner.ListOperationsOutput{
OperationSummaryList: []*apprunner.OperationSummary{
{
Id: aws.String(mockOperationId),
TargetArn: aws.String(mockSvcARN),
Status: aws.String("FAILED"),
},
},
}, nil)
},
wantErr: fmt.Errorf("operation failed mock-operation"),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockAppRunnerClient := mocks.NewMockapi(ctrl)
tc.mockAppRunnerClient(mockAppRunnerClient)
service := AppRunner{
client: mockAppRunnerClient,
}
err := service.PauseService(mockSvcARN)
if tc.wantErr != nil {
require.EqualError(t, err, tc.wantErr.Error())
} else {
require.NoError(t, err)
}
})
}
}
func TestAppRunner_ResumeService(t *testing.T) {
const (
mockOperationId = "mock-operation"
mockSvcARN = "mockSvcArn"
)
testCases := map[string]struct {
mockAppRunnerClient func(m *mocks.Mockapi)
wantErr error
wantSvcOperation *apprunner.OperationSummary
}{
"success if service is already running": {
mockAppRunnerClient: func(m *mocks.Mockapi) {
m.EXPECT().ResumeService(&apprunner.ResumeServiceInput{ServiceArn: aws.String(mockSvcARN)}).Return(&apprunner.ResumeServiceOutput{
OperationId: nil,
Service: &apprunner.Service{
ServiceArn: aws.String(mockSvcARN),
Status: aws.String("RUNNING"),
},
}, nil)
},
},
"waits until operation succeeds": {
mockAppRunnerClient: func(m *mocks.Mockapi) {
m.EXPECT().ResumeService(&apprunner.ResumeServiceInput{ServiceArn: aws.String(mockSvcARN)}).Return(&apprunner.ResumeServiceOutput{
OperationId: aws.String(mockOperationId),
Service: &apprunner.Service{
ServiceArn: aws.String(mockSvcARN),
},
}, nil)
m.EXPECT().ListOperations(&apprunner.ListOperationsInput{ServiceArn: aws.String(mockSvcARN)}).Return(&apprunner.ListOperationsOutput{
OperationSummaryList: []*apprunner.OperationSummary{
{
Id: aws.String(mockOperationId),
TargetArn: aws.String(mockSvcARN),
Status: aws.String("SUCCEEDED"),
},
},
}, nil)
},
},
"return error if operation failed": {
mockAppRunnerClient: func(m *mocks.Mockapi) {
m.EXPECT().ResumeService(&apprunner.ResumeServiceInput{ServiceArn: aws.String(mockSvcARN)}).Return(&apprunner.ResumeServiceOutput{
OperationId: aws.String(mockOperationId),
Service: &apprunner.Service{
ServiceArn: aws.String(mockSvcARN),
},
}, nil)
m.EXPECT().ListOperations(&apprunner.ListOperationsInput{ServiceArn: aws.String(mockSvcARN)}).Return(&apprunner.ListOperationsOutput{
OperationSummaryList: []*apprunner.OperationSummary{
{
Id: aws.String(mockOperationId),
TargetArn: aws.String(mockSvcARN),
Status: aws.String("FAILED"),
},
},
}, nil)
},
wantErr: fmt.Errorf("operation failed mock-operation"),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockAppRunnerClient := mocks.NewMockapi(ctrl)
tc.mockAppRunnerClient(mockAppRunnerClient)
service := AppRunner{
client: mockAppRunnerClient,
}
err := service.ResumeService(mockSvcARN)
if tc.wantErr != nil {
require.EqualError(t, err, tc.wantErr.Error())
} else {
require.NoError(t, err)
}
})
}
}
func TestAppRunner_StartDeployment(t *testing.T) {
const (
mockOperationId = "mock-operation"
mockSvcARN = "mockSvcArn"
)
testCases := map[string]struct {
mockAppRunnerClient func(m *mocks.Mockapi)
wantErr error
wantOperationID string
}{
"error if fail to start new deployment": {
mockAppRunnerClient: func(m *mocks.Mockapi) {
m.EXPECT().StartDeployment(&apprunner.StartDeploymentInput{
ServiceArn: aws.String(mockSvcARN),
}).Return(nil, errors.New("some error"))
},
wantErr: fmt.Errorf("start new deployment: some error"),
},
"success": {
mockAppRunnerClient: func(m *mocks.Mockapi) {
m.EXPECT().StartDeployment(&apprunner.StartDeploymentInput{
ServiceArn: aws.String(mockSvcARN),
}).Return(&apprunner.StartDeploymentOutput{
OperationId: aws.String(mockOperationId),
}, nil)
},
wantOperationID: mockOperationId,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockAppRunnerClient := mocks.NewMockapi(ctrl)
tc.mockAppRunnerClient(mockAppRunnerClient)
service := AppRunner{
client: mockAppRunnerClient,
}
got, err := service.StartDeployment(mockSvcARN)
if tc.wantErr != nil {
require.EqualError(t, err, tc.wantErr.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantOperationID, got)
}
})
}
}
func TestAppRunner_ImageIsSupported(t *testing.T) {
testCases := map[string]struct {
in string
want bool
}{
"ECR tagged image": {
in: "111111111111.dkr.ecr.us-east-1.amazonaws.com/test/frontend:latest",
want: true,
},
"ECR image digest": {
in: "111111111111.dkr.ecr.us-east-1.amazonaws.com/test/frontend@sha256:f349f1cf8c3404f4b15b733d443a46f417d2959659645cddb2c5b380eeb0c2ad",
want: true,
},
"ECR Public image": {
in: "public.ecr.aws/bitnami/wordpress:latest",
want: true,
},
"Dockerhub image URI": {
in: "registry.hub.docker.com/amazon/amazon-ecs-sample",
want: false,
},
"Dockerhub image name": {
in: "amazon/amazon-ecs-sample",
want: false,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
received := ImageIsSupported(tc.in)
require.Equal(t, tc.want, received)
})
}
}
func TestAppRunner_DetermineImageRepositoryType(t *testing.T) {
testCases := map[string]struct {
in string
want string
wantErr error
}{
"ECR tagged image": {
in: "111111111111.dkr.ecr.us-east-1.amazonaws.com/test/frontend:latest",
want: repositoryTypeECR,
},
"ECR image digest": {
in: "111111111111.dkr.ecr.us-east-1.amazonaws.com/test/frontend@sha256:f349f1cf8c3404f4b15b733d443a46f417d2959659645cddb2c5b380eeb0c2ad",
want: repositoryTypeECR,
},
"ECR Public image": {
in: "public.ecr.aws/bitnami/wordpress:latest",
want: repositoryTypeECRPublic,
},
"Dockerhub image URI": {
in: "registry.hub.docker.com/amazon/amazon-ecs-sample",
wantErr: fmt.Errorf("image is not supported by App Runner: registry.hub.docker.com/amazon/amazon-ecs-sample"),
},
"Dockerhub image name": {
in: "amazon/amazon-ecs-sample",
wantErr: fmt.Errorf("image is not supported by App Runner: amazon/amazon-ecs-sample"),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
received, err := DetermineImageRepositoryType(tc.in)
if tc.wantErr != nil {
require.EqualError(t, err, tc.wantErr.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.want, received)
}
})
}
}
| 763 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package apprunner
import (
"fmt"
)
// ErrWaitServiceOperationFailed occurs when the service operation failed.
type ErrWaitServiceOperationFailed struct {
operationId string
}
func (e *ErrWaitServiceOperationFailed) Error() string {
return fmt.Sprintf("operation failed %s", e.operationId)
}
// Timeout allows ErrWaitServiceOperationFailed to implement a timeout error interface.
func (e *ErrWaitServiceOperationFailed) Timeout() bool {
return true
}
| 23 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package apprunner provides a client to make API requests to AppRunner Service.
package apprunner
import (
"time"
"github.com/aws/aws-sdk-go/service/apprunner"
)
// Service wraps up AppRunner Service struct.
type Service struct {
ServiceARN string
Name string
ID string
Status string
ServiceURL string
DateCreated time.Time
DateUpdated time.Time
CPU string
Memory string
ImageID string
Port string
EnvironmentVariables []*EnvironmentVariable
Observability ObservabilityConfiguration
EnvironmentSecrets []*EnvironmentSecret
}
// EnvironmentVariable contains the name and value of an environment variable.
type EnvironmentVariable struct {
Name string
Value string
}
// EnvironmentSecret contains the name and value of a Secret from SSM Parameter Store or Secrets Manager.
type EnvironmentSecret struct {
Name string
Value string
}
// ObservabilityConfiguration contains observability related configuration. Currently only tracing configuration is available.
type ObservabilityConfiguration struct {
TraceConfiguration *TraceConfiguration
}
// TraceConfiguration wraps AppRunner TraceConfiguration.
type TraceConfiguration apprunner.TraceConfiguration
| 50 |
copilot-cli | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: ./internal/pkg/aws/apprunner/apprunner.go
// Package mocks is a generated GoMock package.
package mocks
import (
reflect "reflect"
apprunner "github.com/aws/aws-sdk-go/service/apprunner"
gomock "github.com/golang/mock/gomock"
)
// Mockapi is a mock of api interface.
type Mockapi struct {
ctrl *gomock.Controller
recorder *MockapiMockRecorder
}
// MockapiMockRecorder is the mock recorder for Mockapi.
type MockapiMockRecorder struct {
mock *Mockapi
}
// NewMockapi creates a new mock instance.
func NewMockapi(ctrl *gomock.Controller) *Mockapi {
mock := &Mockapi{ctrl: ctrl}
mock.recorder = &MockapiMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *Mockapi) EXPECT() *MockapiMockRecorder {
return m.recorder
}
// DescribeObservabilityConfiguration mocks base method.
func (m *Mockapi) DescribeObservabilityConfiguration(input *apprunner.DescribeObservabilityConfigurationInput) (*apprunner.DescribeObservabilityConfigurationOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DescribeObservabilityConfiguration", input)
ret0, _ := ret[0].(*apprunner.DescribeObservabilityConfigurationOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DescribeObservabilityConfiguration indicates an expected call of DescribeObservabilityConfiguration.
func (mr *MockapiMockRecorder) DescribeObservabilityConfiguration(input interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeObservabilityConfiguration", reflect.TypeOf((*Mockapi)(nil).DescribeObservabilityConfiguration), input)
}
// DescribeService mocks base method.
func (m *Mockapi) DescribeService(input *apprunner.DescribeServiceInput) (*apprunner.DescribeServiceOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DescribeService", input)
ret0, _ := ret[0].(*apprunner.DescribeServiceOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DescribeService indicates an expected call of DescribeService.
func (mr *MockapiMockRecorder) DescribeService(input interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeService", reflect.TypeOf((*Mockapi)(nil).DescribeService), input)
}
// DescribeVpcIngressConnection mocks base method.
func (m *Mockapi) DescribeVpcIngressConnection(input *apprunner.DescribeVpcIngressConnectionInput) (*apprunner.DescribeVpcIngressConnectionOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DescribeVpcIngressConnection", input)
ret0, _ := ret[0].(*apprunner.DescribeVpcIngressConnectionOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DescribeVpcIngressConnection indicates an expected call of DescribeVpcIngressConnection.
func (mr *MockapiMockRecorder) DescribeVpcIngressConnection(input interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeVpcIngressConnection", reflect.TypeOf((*Mockapi)(nil).DescribeVpcIngressConnection), input)
}
// ListOperations mocks base method.
func (m *Mockapi) ListOperations(input *apprunner.ListOperationsInput) (*apprunner.ListOperationsOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListOperations", input)
ret0, _ := ret[0].(*apprunner.ListOperationsOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ListOperations indicates an expected call of ListOperations.
func (mr *MockapiMockRecorder) ListOperations(input interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListOperations", reflect.TypeOf((*Mockapi)(nil).ListOperations), input)
}
// ListServices mocks base method.
func (m *Mockapi) ListServices(input *apprunner.ListServicesInput) (*apprunner.ListServicesOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListServices", input)
ret0, _ := ret[0].(*apprunner.ListServicesOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ListServices indicates an expected call of ListServices.
func (mr *MockapiMockRecorder) ListServices(input interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListServices", reflect.TypeOf((*Mockapi)(nil).ListServices), input)
}
// PauseService mocks base method.
func (m *Mockapi) PauseService(input *apprunner.PauseServiceInput) (*apprunner.PauseServiceOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "PauseService", input)
ret0, _ := ret[0].(*apprunner.PauseServiceOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// PauseService indicates an expected call of PauseService.
func (mr *MockapiMockRecorder) PauseService(input interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PauseService", reflect.TypeOf((*Mockapi)(nil).PauseService), input)
}
// ResumeService mocks base method.
func (m *Mockapi) ResumeService(input *apprunner.ResumeServiceInput) (*apprunner.ResumeServiceOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ResumeService", input)
ret0, _ := ret[0].(*apprunner.ResumeServiceOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ResumeService indicates an expected call of ResumeService.
func (mr *MockapiMockRecorder) ResumeService(input interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ResumeService", reflect.TypeOf((*Mockapi)(nil).ResumeService), input)
}
// StartDeployment mocks base method.
func (m *Mockapi) StartDeployment(input *apprunner.StartDeploymentInput) (*apprunner.StartDeploymentOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "StartDeployment", input)
ret0, _ := ret[0].(*apprunner.StartDeploymentOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// StartDeployment indicates an expected call of StartDeployment.
func (mr *MockapiMockRecorder) StartDeployment(input interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StartDeployment", reflect.TypeOf((*Mockapi)(nil).StartDeployment), input)
}
| 156 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package cloudformation
import (
"context"
"fmt"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/cloudformation"
"github.com/google/uuid"
)
const (
// The change set name must match the regex [a-zA-Z][-a-zA-Z0-9]*. The generated UUID can start with a number,
// by prefixing the uuid with a word we guarantee that we start with a letter.
fmtChangeSetName = "copilot-%s"
// Status reasons that can occur if the change set execution status is "FAILED".
noChangesReason = "NO_CHANGES_REASON"
noUpdatesReason = "NO_UPDATES_REASON"
)
// ChangeSetDescription is the output of the DescribeChangeSet action.
type ChangeSetDescription struct {
ExecutionStatus string
StatusReason string
CreationTime time.Time
Changes []*cloudformation.Change
}
type changeSetType int
func (t changeSetType) String() string {
switch t {
case updateChangeSetType:
return cloudformation.ChangeSetTypeUpdate
default:
return cloudformation.ChangeSetTypeCreate
}
}
const (
createChangeSetType changeSetType = iota
updateChangeSetType
)
type changeSet struct {
name string
stackName string
csType changeSetType
client changeSetAPI
}
func newCreateChangeSet(cfnClient changeSetAPI, stackName string) (*changeSet, error) {
id, err := uuid.NewRandom()
if err != nil {
return nil, fmt.Errorf("generate random id for Change Set: %w", err)
}
return &changeSet{
name: fmt.Sprintf(fmtChangeSetName, id.String()),
stackName: stackName,
csType: createChangeSetType,
client: cfnClient,
}, nil
}
func newUpdateChangeSet(cfnClient changeSetAPI, stackName string) (*changeSet, error) {
id, err := uuid.NewRandom()
if err != nil {
return nil, fmt.Errorf("generate random id for Change Set: %w", err)
}
return &changeSet{
name: fmt.Sprintf(fmtChangeSetName, id.String()),
stackName: stackName,
csType: updateChangeSetType,
client: cfnClient,
}, nil
}
func (cs *changeSet) String() string {
return fmt.Sprintf("change set %s for stack %s", cs.name, cs.stackName)
}
// create creates a ChangeSet, waits until it's created, and returns the ChangeSet ID on success.
func (cs *changeSet) create(conf *stackConfig) error {
input := &cloudformation.CreateChangeSetInput{
ChangeSetName: aws.String(cs.name),
StackName: aws.String(cs.stackName),
ChangeSetType: aws.String(cs.csType.String()),
Parameters: conf.Parameters,
Tags: conf.Tags,
RoleARN: conf.RoleARN,
IncludeNestedStacks: aws.Bool(true),
Capabilities: aws.StringSlice([]string{
cloudformation.CapabilityCapabilityIam,
cloudformation.CapabilityCapabilityNamedIam,
cloudformation.CapabilityCapabilityAutoExpand,
}),
}
if conf.TemplateBody != "" {
input.TemplateBody = aws.String(conf.TemplateBody)
}
if conf.TemplateURL != "" {
input.TemplateURL = aws.String(conf.TemplateURL)
}
out, err := cs.client.CreateChangeSet(input)
if err != nil {
return fmt.Errorf("create %s: %w", cs, err)
}
err = cs.client.WaitUntilChangeSetCreateCompleteWithContext(context.Background(), &cloudformation.DescribeChangeSetInput{
ChangeSetName: out.Id,
}, waiters...)
if err != nil {
return fmt.Errorf("wait for creation of %s: %w", cs, err)
}
// Since the ChangeSet creation succeeded, use the full ARN instead of the name.
// Using the full ID is essential in case the ChangeSet execution status is obsolete.
// If we call DescribeChangeSet using the ChangeSet name and Stack name on an obsolete changeset, the results is empty.
// On the other hand, if you DescribeChangeSet using the full ID then the ChangeSet summary is retrieved correctly.
cs.name = aws.StringValue(out.Id)
return nil
}
// describe collects all the changes and statuses that the change set will apply and returns them.
func (cs *changeSet) describe() (*ChangeSetDescription, error) {
var executionStatus, statusReason string
var creationTime time.Time
var changes []*cloudformation.Change
var nextToken *string
for {
out, err := cs.client.DescribeChangeSet(&cloudformation.DescribeChangeSetInput{
ChangeSetName: aws.String(cs.name),
StackName: aws.String(cs.stackName),
NextToken: nextToken,
})
if err != nil {
return nil, fmt.Errorf("describe %s: %w", cs, err)
}
executionStatus = aws.StringValue(out.ExecutionStatus)
statusReason = aws.StringValue(out.StatusReason)
creationTime = aws.TimeValue(out.CreationTime)
changes = append(changes, out.Changes...)
nextToken = out.NextToken
if nextToken == nil { // no more results left
break
}
}
return &ChangeSetDescription{
ExecutionStatus: executionStatus,
StatusReason: statusReason,
CreationTime: creationTime,
Changes: changes,
}, nil
}
// execute executes a created change set.
func (cs *changeSet) execute() error {
descr, err := cs.describe()
if err != nil {
return err
}
if descr.ExecutionStatus != cloudformation.ExecutionStatusAvailable {
// Ignore execute request if the change set does not contain any modifications.
if descr.StatusReason == noChangesReason {
return nil
}
if descr.StatusReason == noUpdatesReason {
return nil
}
return &ErrChangeSetNotExecutable{
cs: cs,
descr: descr,
}
}
_, err = cs.client.ExecuteChangeSet(&cloudformation.ExecuteChangeSetInput{
ChangeSetName: aws.String(cs.name),
StackName: aws.String(cs.stackName),
})
if err != nil {
return fmt.Errorf("execute %s: %w", cs, err)
}
return nil
}
// executeWithNoRollback executes a created change set without automatic stack rollback.
func (cs *changeSet) executeWithNoRollback() error {
descr, err := cs.describe()
if err != nil {
return err
}
if descr.ExecutionStatus != cloudformation.ExecutionStatusAvailable {
// Ignore execute request if the change set does not contain any modifications.
if descr.StatusReason == noChangesReason {
return nil
}
if descr.StatusReason == noUpdatesReason {
return nil
}
return &ErrChangeSetNotExecutable{
cs: cs,
descr: descr,
}
}
_, err = cs.client.ExecuteChangeSet(&cloudformation.ExecuteChangeSetInput{
ChangeSetName: aws.String(cs.name),
StackName: aws.String(cs.stackName),
DisableRollback: aws.Bool(true),
})
if err != nil {
return fmt.Errorf("execute %s: %w", cs, err)
}
return nil
}
// createAndExecute calls create and then execute.
// If the change set is empty, returns a ErrChangeSetEmpty.
func (cs *changeSet) createAndExecute(conf *stackConfig) error {
if err := cs.create(conf); err != nil {
// It's possible that there are no changes between the previous and proposed stack change sets.
// We make a call to describe the change set to see if that is indeed the case and handle it gracefully.
descr, descrErr := cs.describe()
if descrErr != nil {
return fmt.Errorf("check if changeset is empty: %v: %w", err, descrErr)
}
// The change set was empty - so we clean it up. The status reason will be like
// "The submitted information didn't contain changes. Submit different information to create a change set."
// We try to clean up the change set because there's a limit on the number
// of failed change sets a customer can have on a particular stack.
// See https://cloudonaut.io/aws-cli-cloudformation-deploy-limit-exceeded/.
if len(descr.Changes) == 0 && strings.Contains(descr.StatusReason, "didn't contain changes") {
_ = cs.delete()
return &ErrChangeSetEmpty{
cs: cs,
}
}
return fmt.Errorf("%w: %s", err, descr.StatusReason)
}
if conf.DisableRollback {
return cs.executeWithNoRollback()
}
return cs.execute()
}
// delete removes the change set.
func (cs *changeSet) delete() error {
_, err := cs.client.DeleteChangeSet(&cloudformation.DeleteChangeSetInput{
ChangeSetName: aws.String(cs.name),
StackName: aws.String(cs.stackName),
})
if err != nil {
return fmt.Errorf("delete %s: %w", cs, err)
}
return nil
}
| 265 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package cloudformation provides a client to make API requests to AWS CloudFormation.
package cloudformation
import (
"context"
"errors"
"fmt"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudformation"
)
type eventMatcher func(*cloudformation.StackEvent) bool
var eventErrorStates = []string{
cloudformation.ResourceStatusCreateFailed,
cloudformation.ResourceStatusDeleteFailed,
cloudformation.ResourceStatusImportFailed,
cloudformation.ResourceStatusUpdateFailed,
cloudformation.ResourceStatusImportRollbackFailed,
}
var waiters = []request.WaiterOption{
request.WithWaiterDelay(request.ConstantWaiterDelay(5 * time.Second)), // How long to wait in between poll cfn for updates.
request.WithWaiterMaxAttempts(1080), // Wait for at most 90 mins for any cfn action.
}
// CloudFormation represents a client to make requests to AWS CloudFormation.
type CloudFormation struct {
client
}
// New creates a new CloudFormation client.
func New(s *session.Session) *CloudFormation {
return &CloudFormation{
cloudformation.New(s),
}
}
// Create deploys a new CloudFormation stack using Change Sets.
// If the stack already exists in a failed state, deletes the stack and re-creates it.
func (c *CloudFormation) Create(stack *Stack) (changeSetID string, err error) {
descr, err := c.Describe(stack.Name)
if err != nil {
var stackNotFound *ErrStackNotFound
if !errors.As(err, &stackNotFound) {
return "", err
}
// If the stack does not exist, create it.
return c.create(stack)
}
status := StackStatus(aws.StringValue(descr.StackStatus))
if status.requiresCleanup() {
// If the stack exists, but failed to create, we'll clean it up and then re-create it.
if err := c.DeleteAndWait(stack.Name); err != nil {
return "", fmt.Errorf("clean up previously failed stack %s: %w", stack.Name, err)
}
return c.create(stack)
}
if status.InProgress() {
return "", &ErrStackUpdateInProgress{
Name: stack.Name,
}
}
return "", &ErrStackAlreadyExists{
Name: stack.Name,
Stack: descr,
}
}
// CreateAndWait calls Create and then WaitForCreate.
func (c *CloudFormation) CreateAndWait(stack *Stack) error {
if _, err := c.Create(stack); err != nil {
return err
}
return c.WaitForCreate(context.Background(), stack.Name)
}
// DescribeChangeSet gathers and returns all changes for a change set.
func (c *CloudFormation) DescribeChangeSet(changeSetID, stackName string) (*ChangeSetDescription, error) {
cs := &changeSet{name: changeSetID, stackName: stackName, client: c.client}
out, err := cs.describe()
if err != nil {
return nil, err
}
return out, nil
}
// WaitForCreate blocks until the stack is created or until the max attempt window expires.
func (c *CloudFormation) WaitForCreate(ctx context.Context, stackName string) error {
err := c.client.WaitUntilStackCreateCompleteWithContext(ctx, &cloudformation.DescribeStacksInput{
StackName: aws.String(stackName),
}, waiters...)
if err != nil {
return fmt.Errorf("wait until stack %s create is complete: %w", stackName, err)
}
return nil
}
// Update updates an existing CloudFormation with the new configuration.
// If there are no changes for the stack, deletes the empty change set and returns ErrChangeSetEmpty.
func (c *CloudFormation) Update(stack *Stack) (changeSetID string, err error) {
descr, err := c.Describe(stack.Name)
if err != nil {
return "", err
}
status := StackStatus(aws.StringValue(descr.StackStatus))
if status.InProgress() {
return "", &ErrStackUpdateInProgress{
Name: stack.Name,
}
}
return c.update(stack)
}
// UpdateAndWait calls Update and then blocks until the stack is updated or until the max attempt window expires.
func (c *CloudFormation) UpdateAndWait(stack *Stack) error {
if _, err := c.Update(stack); err != nil {
return err
}
return c.WaitForUpdate(context.Background(), stack.Name)
}
// WaitForUpdate blocks until the stack is updated or until the max attempt window expires.
func (c *CloudFormation) WaitForUpdate(ctx context.Context, stackName string) error {
err := c.client.WaitUntilStackUpdateCompleteWithContext(ctx, &cloudformation.DescribeStacksInput{
StackName: aws.String(stackName),
}, waiters...)
if err != nil {
return fmt.Errorf("wait until stack %s update is complete: %w", stackName, err)
}
return nil
}
// Delete removes an existing CloudFormation stack.
// If the stack doesn't exist then do nothing.
func (c *CloudFormation) Delete(stackName string) error {
_, err := c.client.DeleteStack(&cloudformation.DeleteStackInput{
StackName: aws.String(stackName),
})
if err != nil {
if !stackDoesNotExist(err) {
return fmt.Errorf("delete stack %s: %w", stackName, err)
}
// Move on if stack is already deleted.
}
return nil
}
// DeleteAndWait calls Delete then blocks until the stack is deleted or until the max attempt window expires.
func (c *CloudFormation) DeleteAndWait(stackName string) error {
return c.deleteAndWait(&cloudformation.DeleteStackInput{
StackName: aws.String(stackName),
})
}
// DeleteAndWaitWithRoleARN is DeleteAndWait but with a role ARN that AWS CloudFormation assumes to delete the stack.
func (c *CloudFormation) DeleteAndWaitWithRoleARN(stackName, roleARN string) error {
return c.deleteAndWait(&cloudformation.DeleteStackInput{
StackName: aws.String(stackName),
RoleARN: aws.String(roleARN),
})
}
// Describe returns a description of an existing stack.
// If the stack does not exist, returns ErrStackNotFound.
func (c *CloudFormation) Describe(name string) (*StackDescription, error) {
out, err := c.client.DescribeStacks(&cloudformation.DescribeStacksInput{
StackName: aws.String(name),
})
if err != nil {
if stackDoesNotExist(err) {
return nil, &ErrStackNotFound{name: name}
}
return nil, fmt.Errorf("describe stack %s: %w", name, err)
}
if len(out.Stacks) == 0 {
return nil, &ErrStackNotFound{name: name}
}
descr := StackDescription(*out.Stacks[0])
return &descr, nil
}
// Exists returns true if the CloudFormation stack exists, false otherwise.
// If an error occurs for another reason than ErrStackNotFound, then returns the error.
func (c *CloudFormation) Exists(name string) (bool, error) {
if _, err := c.Describe(name); err != nil {
var notFound *ErrStackNotFound
if errors.As(err, ¬Found) {
return false, nil
}
return false, err
}
return true, nil
}
// MetadataOpts sets up optional parameters for Metadata function.
type MetadataOpts *cloudformation.GetTemplateSummaryInput
// MetadataWithStackName sets up the stack name for cloudformation.GetTemplateSummaryInput.
func MetadataWithStackName(name string) MetadataOpts {
return &cloudformation.GetTemplateSummaryInput{
StackName: aws.String(name),
}
}
// MetadataWithStackSetName sets up the stack set name for cloudformation.GetTemplateSummaryInput.
func MetadataWithStackSetName(name string) MetadataOpts {
return &cloudformation.GetTemplateSummaryInput{
StackSetName: aws.String(name),
}
}
// Metadata returns the Metadata property of the CloudFormation stack(set)'s template.
func (c *CloudFormation) Metadata(opt MetadataOpts) (string, error) {
out, err := c.GetTemplateSummary(opt)
if err != nil {
return "", fmt.Errorf("get template summary: %w", err)
}
return aws.StringValue(out.Metadata), nil
}
// TemplateBody returns the template body of an existing stack.
// If the stack does not exist, returns ErrStackNotFound.
func (c *CloudFormation) TemplateBody(name string) (string, error) {
out, err := c.client.GetTemplate(&cloudformation.GetTemplateInput{
StackName: aws.String(name),
})
if err != nil {
if stackDoesNotExist(err) {
return "", &ErrStackNotFound{name: name}
}
return "", fmt.Errorf("get template %s: %w", name, err)
}
return aws.StringValue(out.TemplateBody), nil
}
// TemplateBodyFromChangeSet returns the template body of a stack based on a change set.
// If the stack does not exist, then returns ErrStackNotFound.
func (c *CloudFormation) TemplateBodyFromChangeSet(changeSetID, stackName string) (string, error) {
out, err := c.client.GetTemplate(&cloudformation.GetTemplateInput{
ChangeSetName: aws.String(changeSetID),
StackName: aws.String(stackName),
})
if err != nil {
if stackDoesNotExist(err) {
return "", &ErrStackNotFound{name: stackName}
}
return "", fmt.Errorf("get template for stack %s and change set %s: %w", stackName, changeSetID, err)
}
return aws.StringValue(out.TemplateBody), nil
}
// Outputs returns the outputs of a stack description.
func (c *CloudFormation) Outputs(stack *Stack) (map[string]string, error) {
stackDescription, err := c.Describe(stack.Name)
if err != nil {
return nil, fmt.Errorf("retrieve outputs of stack description: %w", err)
}
outputs := make(map[string]string)
for _, output := range stackDescription.Outputs {
outputs[aws.StringValue(output.OutputKey)] = aws.StringValue(output.OutputValue)
}
return outputs, nil
}
// Events returns the list of stack events in **chronological** order.
func (c *CloudFormation) Events(stackName string) ([]StackEvent, error) {
return c.events(stackName, func(in *cloudformation.StackEvent) bool { return true })
}
// StackResources returns the list of resources created as part of a CloudFormation stack.
func (c *CloudFormation) StackResources(name string) ([]*StackResource, error) {
out, err := c.DescribeStackResources(&cloudformation.DescribeStackResourcesInput{
StackName: aws.String(name),
})
if err != nil {
return nil, fmt.Errorf("describe resources for stack %s: %w", name, err)
}
var resources []*StackResource
for _, r := range out.StackResources {
if r == nil {
continue
}
sr := StackResource(*r)
resources = append(resources, &sr)
}
return resources, nil
}
func (c *CloudFormation) events(stackName string, match eventMatcher) ([]StackEvent, error) {
var nextToken *string
var events []StackEvent
for {
out, err := c.client.DescribeStackEvents(&cloudformation.DescribeStackEventsInput{
NextToken: nextToken,
StackName: aws.String(stackName),
})
if err != nil {
return nil, fmt.Errorf("describe stack events for stack %s: %w", stackName, err)
}
for _, event := range out.StackEvents {
if match(event) {
events = append(events, StackEvent(*event))
}
}
nextToken = out.NextToken
if nextToken == nil {
break
}
}
// Reverse the events so that they're returned in chronological order.
// Taken from https://github.com/golang/go/wiki/SliceTricks#reversing.
for i := len(events)/2 - 1; i >= 0; i-- {
opp := len(events) - 1 - i
events[i], events[opp] = events[opp], events[i]
}
return events, nil
}
// ErrorEvents returns the list of events with "failed" status in **chronological order**
func (c *CloudFormation) ErrorEvents(stackName string) ([]StackEvent, error) {
return c.events(stackName, func(in *cloudformation.StackEvent) bool {
for _, status := range eventErrorStates {
if aws.StringValue(in.ResourceStatus) == status {
return true
}
}
return false
})
}
// ListStacksWithTags returns all the stacks in the current AWS account and region with the specified matching
// tags. If a tag key is provided but the value is empty, the method will match tags with any value for the given key.
func (c *CloudFormation) ListStacksWithTags(tags map[string]string) ([]StackDescription, error) {
match := makeTagMatcher(tags)
var nextToken *string
var summaries []StackDescription
for {
out, err := c.client.DescribeStacks(&cloudformation.DescribeStacksInput{
NextToken: nextToken,
})
if err != nil {
return nil, fmt.Errorf("list stacks: %w", err)
}
for _, summary := range out.Stacks {
stackTags := summary.Tags
if match(stackTags) {
summaries = append(summaries, StackDescription(*summary))
}
}
nextToken = out.NextToken
if nextToken == nil {
break
}
}
return summaries, nil
}
func (c *CloudFormation) create(stack *Stack) (string, error) {
cs, err := newCreateChangeSet(c.client, stack.Name)
if err != nil {
return "", err
}
if err := cs.createAndExecute(stack.stackConfig); err != nil {
return "", err
}
return cs.name, nil
}
func (c *CloudFormation) update(stack *Stack) (string, error) {
cs, err := newUpdateChangeSet(c.client, stack.Name)
if err != nil {
return "", err
}
if err := cs.createAndExecute(stack.stackConfig); err != nil {
return "", err
}
return cs.name, nil
}
func (c *CloudFormation) deleteAndWait(in *cloudformation.DeleteStackInput) error {
_, err := c.client.DeleteStack(in)
if err != nil {
if !stackDoesNotExist(err) {
return fmt.Errorf("delete stack %s: %w", aws.StringValue(in.StackName), err)
}
return nil // If the stack is already deleted, don't wait for it.
}
err = c.client.WaitUntilStackDeleteCompleteWithContext(context.Background(), &cloudformation.DescribeStacksInput{
StackName: in.StackName,
}, waiters...)
if err != nil {
return fmt.Errorf("wait until stack %s delete is complete: %w", aws.StringValue(in.StackName), err)
}
return nil
}
// makeTagMatcher takes a set of wanted tags and returns a function which matches if the given set of
// `cloudformation.Tag`s contains tags with all wanted keys and values
func makeTagMatcher(wantedTags map[string]string) func([]*cloudformation.Tag) bool {
// Match all stacks if no desired tags are specified.
if len(wantedTags) == 0 {
return func([]*cloudformation.Tag) bool { return true }
}
return func(tags []*cloudformation.Tag) bool {
// Define a map to determine whether each wanted tag is a match.
tagsMatched := make(map[string]bool, len(wantedTags))
// Populate the hash set and match map
for k := range wantedTags {
tagsMatched[k] = false
}
// Loop over all tags on the stack and decide whether they match any of the wanted tags.
for _, tag := range tags {
tagKey := aws.StringValue(tag.Key)
tagValue := aws.StringValue(tag.Value)
if wantedTags[tagKey] == tagValue || wantedTags[tagKey] == "" {
tagsMatched[tagKey] = true
}
}
// Only return true if all wanted tags are present and match in the stack's tags.
for _, v := range tagsMatched {
if !v {
return false
}
}
return true
}
}
| 445 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package cloudformation
import (
"bytes"
"context"
"errors"
"fmt"
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/cloudformation"
"github.com/aws/copilot-cli/internal/pkg/aws/cloudformation/mocks"
"github.com/golang/mock/gomock"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
)
const (
mockChangeSetName = "copilot-31323334-3536-4738-b930-313233333435"
mockChangeSetID = "arn:aws:cloudformation:us-west-2:111:changeSet/copilot-31323334-3536-4738-b930-313233333435/9edc39b0-ee18-440d-823e-3dda74646b2"
)
var (
mockStack = NewStack("id", "template")
errDoesNotExist = awserr.New("ValidationError", "does not exist", nil)
)
func TestCloudFormation_Create(t *testing.T) {
testCases := map[string]struct {
inStack *Stack
createMock func(ctrl *gomock.Controller) client
wantedErr error
}{
"fail if checking the stack description fails": {
inStack: mockStack,
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().DescribeStacks(&cloudformation.DescribeStacksInput{
StackName: aws.String(mockStack.Name),
}).Return(nil, errors.New("some unexpected error"))
return m
},
wantedErr: fmt.Errorf("describe stack %s: %w", mockStack.Name, errors.New("some unexpected error")),
},
"fail if a stack exists that's already in progress": {
inStack: mockStack,
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().DescribeStacks(gomock.Any()).Return(&cloudformation.DescribeStacksOutput{
Stacks: []*cloudformation.Stack{
{
StackStatus: aws.String(cloudformation.StackStatusCreateInProgress),
},
},
}, nil)
return m
},
wantedErr: &ErrStackUpdateInProgress{
Name: mockStack.Name,
},
},
"fail if a successfully created stack already exists": {
inStack: mockStack,
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().DescribeStacks(gomock.Any()).Return(&cloudformation.DescribeStacksOutput{
Stacks: []*cloudformation.Stack{
{
StackStatus: aws.String(cloudformation.StackStatusCreateComplete),
},
},
}, nil)
return m
},
wantedErr: &ErrStackAlreadyExists{
Name: mockStack.Name,
Stack: &StackDescription{
StackStatus: aws.String(cloudformation.StackStatusCreateComplete),
},
},
},
"creates the stack if it doesn't exist": {
inStack: mockStack,
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().DescribeStacks(gomock.Any()).Return(nil, errDoesNotExist)
addCreateDeployCalls(m)
return m
},
},
"creates the stack with automatic stack rollback disabled": {
inStack: NewStack("id", "template", WithDisableRollback()),
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().DescribeStacks(gomock.Any()).Return(nil, errDoesNotExist)
m.EXPECT().CreateChangeSet(&cloudformation.CreateChangeSetInput{
ChangeSetName: aws.String(mockChangeSetName),
StackName: aws.String(mockStack.Name),
ChangeSetType: aws.String(cloudformation.ChangeSetTypeCreate),
TemplateBody: aws.String(mockStack.TemplateBody),
Parameters: nil,
Tags: nil,
RoleARN: nil,
IncludeNestedStacks: aws.Bool(true),
Capabilities: aws.StringSlice([]string{
cloudformation.CapabilityCapabilityIam,
cloudformation.CapabilityCapabilityNamedIam,
cloudformation.CapabilityCapabilityAutoExpand,
}),
}).Return(&cloudformation.CreateChangeSetOutput{
Id: aws.String(mockChangeSetID),
StackId: aws.String(mockStack.Name),
}, nil)
m.EXPECT().WaitUntilChangeSetCreateCompleteWithContext(gomock.Any(), &cloudformation.DescribeChangeSetInput{
ChangeSetName: aws.String(mockChangeSetID),
}, gomock.Any())
m.EXPECT().DescribeChangeSet(&cloudformation.DescribeChangeSetInput{
ChangeSetName: aws.String(mockChangeSetID),
StackName: aws.String(mockStack.Name),
}).Return(&cloudformation.DescribeChangeSetOutput{
Changes: []*cloudformation.Change{
{
ResourceChange: &cloudformation.ResourceChange{
ResourceType: aws.String("ecs service"),
},
Type: aws.String(cloudformation.ChangeTypeResource),
},
},
ExecutionStatus: aws.String(cloudformation.ExecutionStatusAvailable),
StatusReason: aws.String("some reason"),
}, nil)
m.EXPECT().ExecuteChangeSet(&cloudformation.ExecuteChangeSetInput{
ChangeSetName: aws.String(mockChangeSetID),
StackName: aws.String(mockStack.Name),
DisableRollback: aws.Bool(true),
})
return m
},
},
"creates the stack with templateURL": {
inStack: mockStack,
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().DescribeStacks(gomock.Any()).Return(nil, errDoesNotExist)
addCreateDeployCalls(m)
return m
},
},
"creates the stack after cleaning the previously failed execution": {
inStack: mockStack,
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().DescribeStacks(gomock.Any()).Return(&cloudformation.DescribeStacksOutput{
Stacks: []*cloudformation.Stack{
{
StackStatus: aws.String(cloudformation.StackStatusRollbackComplete),
},
},
}, nil)
m.EXPECT().DeleteStack(&cloudformation.DeleteStackInput{
StackName: aws.String(mockStack.Name),
})
m.EXPECT().WaitUntilStackDeleteCompleteWithContext(gomock.Any(), &cloudformation.DescribeStacksInput{
StackName: aws.String(mockStack.Name),
}, gomock.Any(), gomock.Any())
addCreateDeployCalls(m)
return m
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
seed := bytes.NewBufferString("12345678901233456789") // always generate the same UUID
uuid.SetRand(seed)
defer uuid.SetRand(nil)
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
c := CloudFormation{
client: tc.createMock(ctrl),
}
// WHEN
id, err := c.Create(tc.inStack)
// THEN
if tc.wantedErr != nil {
require.EqualError(t, err, tc.wantedErr.Error())
} else {
require.NoError(t, err)
require.Equal(t, mockChangeSetID, id)
}
})
}
}
func TestCloudFormation_DescribeChangeSet(t *testing.T) {
t.Run("returns an error if the DescribeChangeSet action fails", func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := mocks.NewMockclient(ctrl)
m.EXPECT().DescribeChangeSet(gomock.Any()).Return(nil, errors.New("some error"))
cfn := CloudFormation{
client: m,
}
// WHEN
out, err := cfn.DescribeChangeSet(mockChangeSetID, "phonetool-test")
// THEN
require.EqualError(t, err, fmt.Sprintf("describe change set %s for stack phonetool-test: some error", mockChangeSetID))
require.Nil(t, out)
})
t.Run("calls DescribeChangeSet repeatedly if there is a next token", func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := mocks.NewMockclient(ctrl)
wantedChanges := []*cloudformation.Change{
{
ResourceChange: &cloudformation.ResourceChange{
ResourceType: aws.String("AWS::ECS::Service"),
},
},
{
ResourceChange: &cloudformation.ResourceChange{
ResourceType: aws.String("AWS::ECS::Cluster"),
},
},
}
gomock.InOrder(
m.EXPECT().DescribeChangeSet(&cloudformation.DescribeChangeSetInput{
ChangeSetName: aws.String(mockChangeSetID),
StackName: aws.String("phonetool-test"),
NextToken: nil,
}).Return(&cloudformation.DescribeChangeSetOutput{
Changes: []*cloudformation.Change{
wantedChanges[0],
},
NextToken: aws.String("1111"),
}, nil),
m.EXPECT().DescribeChangeSet(&cloudformation.DescribeChangeSetInput{
ChangeSetName: aws.String(mockChangeSetID),
StackName: aws.String("phonetool-test"),
NextToken: aws.String("1111"),
}).Return(&cloudformation.DescribeChangeSetOutput{
Changes: []*cloudformation.Change{
wantedChanges[1],
},
}, nil),
)
cfn := CloudFormation{
client: m,
}
// WHEN
out, err := cfn.DescribeChangeSet(mockChangeSetID, "phonetool-test")
// THEN
require.NoError(t, err)
require.Equal(t, wantedChanges, out.Changes)
})
}
func TestCloudFormation_WaitForCreate(t *testing.T) {
testCases := map[string]struct {
createMock func(ctrl *gomock.Controller) client
wantedErr error
}{
"wraps error on failure": {
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().WaitUntilStackCreateCompleteWithContext(gomock.Any(), &cloudformation.DescribeStacksInput{
StackName: aws.String(mockStack.Name),
}, gomock.Any()).Return(errors.New("some error"))
return m
},
wantedErr: fmt.Errorf("wait until stack %s create is complete: %w", mockStack.Name, errors.New("some error")),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
c := CloudFormation{
client: tc.createMock(ctrl),
}
// WHEN
err := c.WaitForCreate(context.Background(), mockStack.Name)
// THEN
require.Equal(t, tc.wantedErr, err)
})
}
}
func TestCloudFormation_Update(t *testing.T) {
const (
mockStackName = "id"
mockChangeSetName = "copilot-31323334-3536-4738-b930-313233333435"
)
testCases := map[string]struct {
inStack *Stack
createMock func(ctrl *gomock.Controller) client
wantedErr error
}{
"fail if the stack is already in progress": {
inStack: mockStack,
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().DescribeStacks(gomock.Any()).Return(&cloudformation.DescribeStacksOutput{
Stacks: []*cloudformation.Stack{{StackStatus: aws.String(cloudformation.StackStatusUpdateInProgress)}},
}, nil)
return m
},
wantedErr: &ErrStackUpdateInProgress{
Name: mockStack.Name,
},
},
"error if fail to create the changeset because of random issue": {
inStack: mockStack,
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().DescribeStacks(gomock.Any()).Return(&cloudformation.DescribeStacksOutput{
Stacks: []*cloudformation.Stack{{StackStatus: aws.String(cloudformation.StackStatusUpdateComplete)}},
}, nil)
m.EXPECT().CreateChangeSet(gomock.Any()).Return(nil, errors.New("some error"))
m.EXPECT().DescribeChangeSet(gomock.Any()).
Return(&cloudformation.DescribeChangeSetOutput{
Changes: []*cloudformation.Change{},
StatusReason: aws.String("some other reason"),
}, nil)
return m
},
wantedErr: fmt.Errorf("create change set copilot-31323334-3536-4738-b930-313233333435 for stack id: some error: some other reason"),
},
"error if fail to wait until the changeset creation complete": {
inStack: mockStack,
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().DescribeStacks(gomock.Any()).Return(&cloudformation.DescribeStacksOutput{
Stacks: []*cloudformation.Stack{{StackStatus: aws.String(cloudformation.StackStatusUpdateComplete)}},
}, nil)
m.EXPECT().CreateChangeSet(gomock.Any()).Return(&cloudformation.CreateChangeSetOutput{
Id: aws.String(mockChangeSetName),
}, nil)
m.EXPECT().WaitUntilChangeSetCreateCompleteWithContext(gomock.Any(), &cloudformation.DescribeChangeSetInput{
ChangeSetName: aws.String(mockChangeSetName),
}, gomock.Any()).Return(errors.New("some error"))
m.EXPECT().DescribeChangeSet(gomock.Any()).
Return(&cloudformation.DescribeChangeSetOutput{
StatusReason: aws.String("some reason"),
}, nil)
return m
},
wantedErr: fmt.Errorf("wait for creation of change set copilot-31323334-3536-4738-b930-313233333435 for stack id: some error: some reason"),
},
"error if fail to describe change set after creation failed": {
inStack: mockStack,
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().DescribeStacks(gomock.Any()).Return(&cloudformation.DescribeStacksOutput{
Stacks: []*cloudformation.Stack{{StackStatus: aws.String(cloudformation.StackStatusUpdateComplete)}},
}, nil)
m.EXPECT().CreateChangeSet(gomock.Any()).Return(nil, errors.New("some error"))
m.EXPECT().DescribeChangeSet(gomock.Any()).
Return(&cloudformation.DescribeChangeSetOutput{
NextToken: aws.String("mockNext"),
}, nil)
m.EXPECT().DescribeChangeSet(&cloudformation.DescribeChangeSetInput{
ChangeSetName: aws.String(mockChangeSetName),
StackName: aws.String(mockStackName),
NextToken: aws.String("mockNext")}).
Return(nil, errors.New("some error"))
return m
},
wantedErr: fmt.Errorf("check if changeset is empty: create change set copilot-31323334-3536-4738-b930-313233333435 for stack id: some error: describe change set copilot-31323334-3536-4738-b930-313233333435 for stack id: some error"),
},
"delete change set and throw ErrChangeSetEmpty if failed to create the change set because it is empty": {
inStack: mockStack,
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().DescribeStacks(gomock.Any()).Return(&cloudformation.DescribeStacksOutput{
Stacks: []*cloudformation.Stack{{StackStatus: aws.String(cloudformation.StackStatusUpdateComplete)}},
}, nil)
m.EXPECT().CreateChangeSet(gomock.Any()).Return(nil, errors.New("some error"))
m.EXPECT().DescribeChangeSet(gomock.Any()).
Return(&cloudformation.DescribeChangeSetOutput{
Changes: []*cloudformation.Change{},
StatusReason: aws.String("The submitted information didn't contain changes. Submit different information to create a change set."),
}, nil)
m.EXPECT().DeleteChangeSet(&cloudformation.DeleteChangeSetInput{
ChangeSetName: aws.String(mockChangeSetName),
StackName: aws.String(mockStackName),
}).Return(nil, nil)
return m
},
wantedErr: fmt.Errorf("change set with name copilot-31323334-3536-4738-b930-313233333435 for stack id has no changes"),
},
"error if creation succeed but failed to describe change set": {
inStack: mockStack,
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().DescribeStacks(gomock.Any()).Return(&cloudformation.DescribeStacksOutput{
Stacks: []*cloudformation.Stack{{StackStatus: aws.String(cloudformation.StackStatusUpdateComplete)}},
}, nil)
m.EXPECT().CreateChangeSet(gomock.Any()).Return(&cloudformation.CreateChangeSetOutput{
Id: aws.String(mockChangeSetName),
}, nil)
m.EXPECT().WaitUntilChangeSetCreateCompleteWithContext(gomock.Any(), &cloudformation.DescribeChangeSetInput{
ChangeSetName: aws.String(mockChangeSetName),
}, gomock.Any()).Return(nil)
m.EXPECT().DescribeChangeSet(gomock.Any()).
Return(nil, errors.New("some error"))
return m
},
wantedErr: fmt.Errorf("describe change set copilot-31323334-3536-4738-b930-313233333435 for stack id: some error"),
},
"ignore execute request if the change set does not contain any modifications": {
inStack: mockStack,
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().DescribeStacks(gomock.Any()).Return(&cloudformation.DescribeStacksOutput{
Stacks: []*cloudformation.Stack{{StackStatus: aws.String(cloudformation.StackStatusUpdateComplete)}},
}, nil)
m.EXPECT().CreateChangeSet(&cloudformation.CreateChangeSetInput{
ChangeSetName: aws.String(mockChangeSetName),
StackName: aws.String(mockStackName),
ChangeSetType: aws.String("UPDATE"),
IncludeNestedStacks: aws.Bool(true),
Capabilities: aws.StringSlice([]string{
cloudformation.CapabilityCapabilityIam,
cloudformation.CapabilityCapabilityNamedIam,
cloudformation.CapabilityCapabilityAutoExpand,
}),
TemplateBody: aws.String("template"),
}).Return(&cloudformation.CreateChangeSetOutput{
Id: aws.String(mockChangeSetName),
}, nil)
m.EXPECT().WaitUntilChangeSetCreateCompleteWithContext(gomock.Any(), &cloudformation.DescribeChangeSetInput{
ChangeSetName: aws.String(mockChangeSetName),
}, gomock.Any()).Return(nil)
m.EXPECT().DescribeChangeSet(&cloudformation.DescribeChangeSetInput{
ChangeSetName: aws.String(mockChangeSetName),
StackName: aws.String(mockStackName)}).
Return(&cloudformation.DescribeChangeSetOutput{
ExecutionStatus: aws.String(cloudformation.ExecutionStatusUnavailable),
StatusReason: aws.String(noChangesReason),
}, nil)
return m
},
},
"error if change set is not executable": {
inStack: mockStack,
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().DescribeStacks(gomock.Any()).Return(&cloudformation.DescribeStacksOutput{
Stacks: []*cloudformation.Stack{{StackStatus: aws.String(cloudformation.StackStatusUpdateComplete)}},
}, nil)
m.EXPECT().CreateChangeSet(gomock.Any()).Return(&cloudformation.CreateChangeSetOutput{
Id: aws.String(mockChangeSetName),
}, nil)
m.EXPECT().WaitUntilChangeSetCreateCompleteWithContext(gomock.Any(), &cloudformation.DescribeChangeSetInput{
ChangeSetName: aws.String(mockChangeSetName),
}, gomock.Any()).Return(nil)
m.EXPECT().DescribeChangeSet(gomock.Any()).
Return(&cloudformation.DescribeChangeSetOutput{
ExecutionStatus: aws.String(cloudformation.ExecutionStatusUnavailable),
StatusReason: aws.String("some other reason"),
}, nil)
return m
},
wantedErr: fmt.Errorf("execute change set copilot-31323334-3536-4738-b930-313233333435 for stack id because status is UNAVAILABLE with reason some other reason"),
},
"error if fail to execute change set": {
inStack: mockStack,
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().DescribeStacks(gomock.Any()).Return(&cloudformation.DescribeStacksOutput{
Stacks: []*cloudformation.Stack{{StackStatus: aws.String(cloudformation.StackStatusUpdateComplete)}},
}, nil)
m.EXPECT().CreateChangeSet(gomock.Any()).Return(&cloudformation.CreateChangeSetOutput{
Id: aws.String(mockChangeSetName),
}, nil)
m.EXPECT().WaitUntilChangeSetCreateCompleteWithContext(gomock.Any(), &cloudformation.DescribeChangeSetInput{
ChangeSetName: aws.String(mockChangeSetName),
}, gomock.Any()).Return(nil)
m.EXPECT().DescribeChangeSet(gomock.Any()).
Return(&cloudformation.DescribeChangeSetOutput{
ExecutionStatus: aws.String(cloudformation.ExecutionStatusAvailable),
}, nil)
m.EXPECT().ExecuteChangeSet(gomock.Any()).Return(nil, errors.New("some error"))
return m
},
wantedErr: fmt.Errorf("execute change set copilot-31323334-3536-4738-b930-313233333435 for stack id: some error"),
},
"updates the stack with automatic stack rollback disabled": {
inStack: NewStack("id", "template", WithDisableRollback()),
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().DescribeStacks(gomock.Any()).Return(&cloudformation.DescribeStacksOutput{
Stacks: []*cloudformation.Stack{{StackStatus: aws.String(cloudformation.StackStatusUpdateComplete)}},
}, nil)
m.EXPECT().CreateChangeSet(&cloudformation.CreateChangeSetInput{
ChangeSetName: aws.String(mockChangeSetName),
StackName: aws.String(mockStackName),
ChangeSetType: aws.String("UPDATE"),
IncludeNestedStacks: aws.Bool(true),
Capabilities: aws.StringSlice([]string{
cloudformation.CapabilityCapabilityIam,
cloudformation.CapabilityCapabilityNamedIam,
cloudformation.CapabilityCapabilityAutoExpand,
}),
TemplateBody: aws.String("template"),
}).Return(&cloudformation.CreateChangeSetOutput{
Id: aws.String(mockChangeSetName),
}, nil)
m.EXPECT().WaitUntilChangeSetCreateCompleteWithContext(gomock.Any(), &cloudformation.DescribeChangeSetInput{
ChangeSetName: aws.String(mockChangeSetName),
}, gomock.Any()).Return(nil)
m.EXPECT().DescribeChangeSet(&cloudformation.DescribeChangeSetInput{
ChangeSetName: aws.String(mockChangeSetName),
StackName: aws.String(mockStackName)}).
Return(&cloudformation.DescribeChangeSetOutput{
ExecutionStatus: aws.String(cloudformation.ExecutionStatusAvailable),
}, nil)
m.EXPECT().ExecuteChangeSet(&cloudformation.ExecuteChangeSetInput{
ChangeSetName: aws.String(mockChangeSetName),
StackName: aws.String(mockStackName),
DisableRollback: aws.Bool(true),
}).Return(&cloudformation.ExecuteChangeSetOutput{}, nil)
return m
},
},
"success": {
inStack: mockStack,
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().DescribeStacks(gomock.Any()).Return(&cloudformation.DescribeStacksOutput{
Stacks: []*cloudformation.Stack{{StackStatus: aws.String(cloudformation.StackStatusUpdateComplete)}},
}, nil)
m.EXPECT().CreateChangeSet(&cloudformation.CreateChangeSetInput{
ChangeSetName: aws.String(mockChangeSetName),
StackName: aws.String(mockStackName),
ChangeSetType: aws.String("UPDATE"),
IncludeNestedStacks: aws.Bool(true),
Capabilities: aws.StringSlice([]string{
cloudformation.CapabilityCapabilityIam,
cloudformation.CapabilityCapabilityNamedIam,
cloudformation.CapabilityCapabilityAutoExpand,
}),
TemplateBody: aws.String("template"),
}).Return(&cloudformation.CreateChangeSetOutput{
Id: aws.String(mockChangeSetName),
}, nil)
m.EXPECT().WaitUntilChangeSetCreateCompleteWithContext(gomock.Any(), &cloudformation.DescribeChangeSetInput{
ChangeSetName: aws.String(mockChangeSetName),
}, gomock.Any()).Return(nil)
m.EXPECT().DescribeChangeSet(&cloudformation.DescribeChangeSetInput{
ChangeSetName: aws.String(mockChangeSetName),
StackName: aws.String(mockStackName)}).
Return(&cloudformation.DescribeChangeSetOutput{
ExecutionStatus: aws.String(cloudformation.ExecutionStatusAvailable),
}, nil)
m.EXPECT().ExecuteChangeSet(&cloudformation.ExecuteChangeSetInput{
ChangeSetName: aws.String(mockChangeSetName),
StackName: aws.String(mockStackName),
}).Return(&cloudformation.ExecuteChangeSetOutput{}, nil)
return m
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
seed := bytes.NewBufferString("12345678901233456789") // always generate the same UUID
uuid.SetRand(seed)
defer uuid.SetRand(nil)
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
c := CloudFormation{
client: tc.createMock(ctrl),
}
// WHEN
id, err := c.Update(tc.inStack)
// THEN
if tc.wantedErr != nil {
require.EqualError(t, err, tc.wantedErr.Error())
} else {
require.NoError(t, err)
require.Equal(t, mockChangeSetName, id)
}
})
}
}
func TestCloudFormation_UpdateAndWait(t *testing.T) {
testCases := map[string]struct {
createMock func(ctrl *gomock.Controller) client
wantedErr error
}{
"waits until the stack is created": {
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().DescribeStacks(gomock.Any()).Return(&cloudformation.DescribeStacksOutput{
Stacks: []*cloudformation.Stack{
{
StackStatus: aws.String(cloudformation.StackStatusCreateComplete),
},
},
}, nil)
addUpdateDeployCalls(m)
m.EXPECT().WaitUntilStackUpdateCompleteWithContext(gomock.Any(), &cloudformation.DescribeStacksInput{
StackName: aws.String(mockStack.Name),
}, gomock.Any()).Return(nil)
return m
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
seed := bytes.NewBufferString("12345678901233456789") // always generate the same UUID
uuid.SetRand(seed)
defer uuid.SetRand(nil)
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
c := CloudFormation{
client: tc.createMock(ctrl),
}
// WHEN
err := c.UpdateAndWait(mockStack)
// THEN
require.Equal(t, tc.wantedErr, err)
})
}
}
func TestCloudFormation_Delete(t *testing.T) {
testCases := map[string]struct {
createMock func(ctrl *gomock.Controller) client
wantedErr error
}{
"fails on unexpected error": {
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().DeleteStack(gomock.Any()).Return(nil, errors.New("some error"))
return m
},
wantedErr: fmt.Errorf("delete stack %s: %w", mockStack.Name, errors.New("some error")),
},
"exits successfully if stack does not exist": {
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().DeleteStack(&cloudformation.DeleteStackInput{
StackName: aws.String(mockStack.Name),
}).Return(nil, errDoesNotExist)
return m
},
},
"exits successfully if stack can be deleted": {
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().DeleteStack(&cloudformation.DeleteStackInput{
StackName: aws.String(mockStack.Name),
}).Return(nil, nil)
return m
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
c := CloudFormation{
client: tc.createMock(ctrl),
}
// WHEN
err := c.Delete(mockStack.Name)
// THEN
require.Equal(t, tc.wantedErr, err)
})
}
}
func TestCloudFormation_DeleteAndWait(t *testing.T) {
testCases := map[string]struct {
createMock func(ctrl *gomock.Controller) client
wantedErr error
}{
"skip waiting if stack does not exist": {
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().DeleteStack(gomock.Any()).Return(nil, errDoesNotExist)
m.EXPECT().WaitUntilStackDeleteCompleteWithContext(gomock.Any(), gomock.Any(), gomock.Any()).Times(0)
return m
},
},
"wait for stack deletion if stack is being deleted": {
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().DeleteStack(&cloudformation.DeleteStackInput{
StackName: aws.String(mockStack.Name),
}).Return(nil, nil)
m.EXPECT().WaitUntilStackDeleteCompleteWithContext(gomock.Any(), &cloudformation.DescribeStacksInput{
StackName: aws.String(mockStack.Name),
}, gomock.Any())
return m
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
c := CloudFormation{
client: tc.createMock(ctrl),
}
// WHEN
err := c.DeleteAndWait(mockStack.Name)
// THEN
require.Equal(t, tc.wantedErr, err)
})
}
}
func TestStackDescriber_Metadata(t *testing.T) {
testCases := map[string]struct {
isStackSet bool
createMock func(ctrl *gomock.Controller) client
wantedMetadata string
wantedErr error
}{
"should wrap cfn error on unexpected error": {
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().GetTemplateSummary(gomock.Any()).Return(nil, errors.New("some error"))
return m
},
wantedErr: errors.New("get template summary: some error"),
},
"should return Metadata property of template summary on success for stack": {
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().GetTemplateSummary(&cloudformation.GetTemplateSummaryInput{
StackName: aws.String("phonetool"),
}).Return(&cloudformation.GetTemplateSummaryOutput{
Metadata: aws.String("hello"),
}, nil)
return m
},
wantedMetadata: "hello",
},
"should return Metadata property of template summary on success for stack set": {
isStackSet: true,
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().GetTemplateSummary(&cloudformation.GetTemplateSummaryInput{
StackSetName: aws.String("phonetool"),
}).Return(&cloudformation.GetTemplateSummaryOutput{
Metadata: aws.String("hello"),
}, nil)
return m
},
wantedMetadata: "hello",
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
c := CloudFormation{
client: tc.createMock(ctrl),
}
// WHEN
name := MetadataWithStackName("phonetool")
if tc.isStackSet {
name = MetadataWithStackSetName("phonetool")
}
actual, err := c.Metadata(name)
// THEN
if tc.wantedErr != nil {
require.EqualError(t, err, tc.wantedErr.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedMetadata, actual)
}
})
}
}
func TestCloudFormation_Describe(t *testing.T) {
testCases := map[string]struct {
createMock func(ctrl *gomock.Controller) client
wantedDescr *StackDescription
wantedErr error
}{
"return ErrStackNotFound if stack does not exist": {
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().DescribeStacks(gomock.Any()).Return(nil, errDoesNotExist)
return m
},
wantedErr: &ErrStackNotFound{name: mockStack.Name},
},
"returns ErrStackNotFound if the list returned is empty": {
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().DescribeStacks(gomock.Any()).Return(&cloudformation.DescribeStacksOutput{
Stacks: []*cloudformation.Stack{},
}, nil)
return m
},
wantedErr: &ErrStackNotFound{name: mockStack.Name},
},
"returns a StackDescription if stack exists": {
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().DescribeStacks(gomock.Any()).Return(&cloudformation.DescribeStacksOutput{
Stacks: []*cloudformation.Stack{
{
StackName: aws.String(mockStack.Name),
},
},
}, nil)
return m
},
wantedDescr: &StackDescription{
StackName: aws.String(mockStack.Name),
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
c := CloudFormation{
client: tc.createMock(ctrl),
}
// WHEN
descr, err := c.Describe(mockStack.Name)
// THEN
require.Equal(t, tc.wantedDescr, descr)
require.Equal(t, tc.wantedErr, err)
})
}
}
func TestCloudFormation_Exists(t *testing.T) {
t.Run("should return underlying error on unexpected describe error", func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
wantedErr := errors.New("some error")
m := mocks.NewMockclient(ctrl)
m.EXPECT().DescribeStacks(gomock.Any()).Return(nil, wantedErr)
c := CloudFormation{
client: m,
}
// WHEN
_, err := c.Exists("phonetool-test")
// THEN
require.EqualError(t, err, "describe stack phonetool-test: some error")
})
t.Run("should return false if the stack is not found", func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := mocks.NewMockclient(ctrl)
m.EXPECT().DescribeStacks(gomock.Any()).Return(nil, errDoesNotExist)
c := CloudFormation{
client: m,
}
// WHEN
exists, err := c.Exists("phonetool-test")
// THEN
require.NoError(t, err)
require.False(t, exists)
})
t.Run("should return true if the stack is found", func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := mocks.NewMockclient(ctrl)
m.EXPECT().DescribeStacks(&cloudformation.DescribeStacksInput{
StackName: aws.String("phonetool-test"),
}).Return(&cloudformation.DescribeStacksOutput{
Stacks: []*cloudformation.Stack{{}},
}, nil)
c := CloudFormation{
client: m,
}
// WHEN
exists, err := c.Exists("phonetool-test")
// THEN
require.NoError(t, err)
require.True(t, exists)
})
}
func TestCloudFormation_TemplateBody(t *testing.T) {
testCases := map[string]struct {
createMock func(ctrl *gomock.Controller) client
wantedBody string
wantedErr error
}{
"return ErrStackNotFound if stack does not exist": {
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().GetTemplate(gomock.Any()).Return(nil, errDoesNotExist)
return m
},
wantedErr: &ErrStackNotFound{name: mockStack.Name},
},
"returns the template body if the stack exists": {
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().GetTemplate(&cloudformation.GetTemplateInput{
StackName: aws.String(mockStack.Name),
}).Return(&cloudformation.GetTemplateOutput{
TemplateBody: aws.String("hello"),
}, nil)
return m
},
wantedBody: "hello",
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
c := CloudFormation{
client: tc.createMock(ctrl),
}
// WHEN
body, err := c.TemplateBody(mockStack.Name)
// THEN
require.Equal(t, tc.wantedBody, body)
require.Equal(t, tc.wantedErr, err)
})
}
}
func TestCloudFormation_TemplateBodyFromChangeSet(t *testing.T) {
testCases := map[string]struct {
createMock func(ctrl *gomock.Controller) client
wantedBody string
wantedErr string
}{
"return ErrStackNotFound if stack does not exist": {
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().GetTemplate(gomock.Any()).Return(nil, errDoesNotExist)
return m
},
wantedErr: (&ErrStackNotFound{name: mockStack.Name}).Error(),
},
"returns wrapped error on expected error": {
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().GetTemplate(gomock.Any()).Return(nil, errors.New("some error"))
return m
},
wantedErr: fmt.Sprintf("get template for stack %s and change set %s: some error", mockStack.Name, mockChangeSetID),
},
"returns the template body if the change set and stack exists": {
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().GetTemplate(&cloudformation.GetTemplateInput{
ChangeSetName: aws.String(mockChangeSetID),
StackName: aws.String(mockStack.Name),
}).Return(&cloudformation.GetTemplateOutput{
TemplateBody: aws.String("hello"),
}, nil)
return m
},
wantedBody: "hello",
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
c := CloudFormation{
client: tc.createMock(ctrl),
}
// WHEN
body, err := c.TemplateBodyFromChangeSet(mockChangeSetID, mockStack.Name)
// THEN
if tc.wantedErr == "" {
require.NoError(t, err)
require.Equal(t, tc.wantedBody, body)
} else {
require.EqualError(t, err, tc.wantedErr)
}
})
}
}
func TestCloudFormation_Outputs(t *testing.T) {
testCases := map[string]struct {
createMock func(ctrl *gomock.Controller) client
wantedOutputs map[string]string
wantedErr string
}{
"successfully returns outputs": {
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().DescribeStacks(gomock.Any()).Return(&cloudformation.DescribeStacksOutput{
Stacks: []*cloudformation.Stack{
{
StackName: aws.String(mockStack.Name),
Outputs: []*cloudformation.Output{
{
OutputKey: aws.String("PipelineConnection"),
OutputValue: aws.String("mockARN"),
},
},
},
},
}, nil)
return m
},
wantedOutputs: map[string]string{
"PipelineConnection": "mockARN",
},
},
"wraps error from Describe()": {
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().DescribeStacks(gomock.Any()).Return(nil, fmt.Errorf("some error"))
return m
},
wantedOutputs: nil,
wantedErr: "retrieve outputs of stack description: describe stack id: some error",
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
c := CloudFormation{
client: tc.createMock(ctrl),
}
// WHEN
outputs, err := c.Outputs(mockStack)
// THEN
if tc.wantedErr != "" {
require.EqualError(t, err, tc.wantedErr)
} else {
require.Equal(t, tc.wantedOutputs, outputs)
}
})
}
}
func TestCloudFormation_ErrorEvents(t *testing.T) {
mockEvents := []*cloudformation.StackEvent{
{
LogicalResourceId: aws.String("abc123"),
ResourceType: aws.String("ECS::Service"),
ResourceStatus: aws.String("CREATE_FAILED"),
ResourceStatusReason: aws.String("Space elevator disconnected. (Service moonshot)"),
},
{
LogicalResourceId: aws.String("xyz"),
ResourceType: aws.String("ECS::Service"),
ResourceStatus: aws.String("CREATE_COMPLETE"),
ResourceStatusReason: aws.String("Moon landing achieved. (Service moonshot)"),
},
}
testCases := map[string]struct {
mockCf func(mockclient *mocks.Mockclient)
wantedErr string
wantedEvents []StackEvent
}{
"completes successfully": {
mockCf: func(m *mocks.Mockclient) {
m.EXPECT().DescribeStackEvents(&cloudformation.DescribeStackEventsInput{
StackName: aws.String(mockStack.Name),
}).Return(&cloudformation.DescribeStackEventsOutput{
StackEvents: mockEvents,
}, nil)
},
wantedEvents: []StackEvent{
{
LogicalResourceId: aws.String("abc123"),
ResourceType: aws.String("ECS::Service"),
ResourceStatus: aws.String("CREATE_FAILED"),
ResourceStatusReason: aws.String("Space elevator disconnected. (Service moonshot)"),
},
},
},
"error retrieving events": {
mockCf: func(m *mocks.Mockclient) {
m.EXPECT().DescribeStackEvents(gomock.Any()).Return(nil, errors.New("some error"))
},
wantedErr: "describe stack events for stack id: some error",
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockCf := mocks.NewMockclient(ctrl)
tc.mockCf(mockCf)
c := CloudFormation{
client: mockCf,
}
// WHEN
events, err := c.ErrorEvents(mockStack.Name)
// THEN
if tc.wantedErr != "" {
require.EqualError(t, err, tc.wantedErr)
} else {
require.Equal(t, tc.wantedEvents, events)
}
})
}
}
func TestCloudFormation_Events(t *testing.T) {
testCases := map[string]struct {
createMock func(ctrl *gomock.Controller) client
wantedEvents []StackEvent
wantedErr error
}{
"return events in chronological order": {
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().DescribeStackEvents(&cloudformation.DescribeStackEventsInput{
StackName: aws.String(mockStack.Name),
}).Return(&cloudformation.DescribeStackEventsOutput{
StackEvents: []*cloudformation.StackEvent{
{
ResourceType: aws.String("ecs"),
},
{
ResourceType: aws.String("s3"),
},
},
}, nil)
return m
},
wantedEvents: []StackEvent{
{
ResourceType: aws.String("s3"),
},
{
ResourceType: aws.String("ecs"),
},
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
c := CloudFormation{
client: tc.createMock(ctrl),
}
// WHEN
events, err := c.Events(mockStack.Name)
// THEN
require.Equal(t, tc.wantedEvents, events)
require.Equal(t, tc.wantedErr, err)
})
}
}
func TestStackDescriber_StackResources(t *testing.T) {
testCases := map[string]struct {
createMock func(ctrl *gomock.Controller) client
wantedStackResources []*StackResource
wantedError error
}{
"return a wrapped error if fail to describe stack resources": {
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().DescribeStackResources(gomock.Any()).Return(nil, errors.New("some error"))
return m
},
wantedError: fmt.Errorf("describe resources for stack phonetool-test-api: some error"),
},
"returns type-casted stack resources on success": {
createMock: func(ctrl *gomock.Controller) client {
m := mocks.NewMockclient(ctrl)
m.EXPECT().DescribeStackResources(&cloudformation.DescribeStackResourcesInput{
StackName: aws.String("phonetool-test-api"),
}).Return(&cloudformation.DescribeStackResourcesOutput{
StackResources: []*cloudformation.StackResource{
{
StackName: aws.String("phonetool-test-api"),
},
},
}, nil)
return m
},
wantedStackResources: []*StackResource{
{
StackName: aws.String("phonetool-test-api"),
},
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
c := CloudFormation{
client: tc.createMock(ctrl),
}
// WHEN
actual, err := c.StackResources("phonetool-test-api")
// THEN
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
require.ElementsMatch(t, tc.wantedStackResources, actual)
}
})
}
}
func TestCloudFormation_ListStacksWithTags(t *testing.T) {
mockAppTag := cloudformation.Tag{
Key: aws.String("copilot-application"),
Value: aws.String("phonetool"),
}
mockEnvTag := cloudformation.Tag{
Key: aws.String("copilot-environment"),
Value: aws.String("test-pdx"),
}
mockTaskTag1 := cloudformation.Tag{
Key: aws.String("copilot-task"),
Value: aws.String("db-migrate"),
}
mockTaskTag2 := cloudformation.Tag{
Key: aws.String("copilot-task"),
Value: aws.String("default-oneoff"),
}
mockStack1 := cloudformation.Stack{
StackName: aws.String("task-appenv"),
Tags: []*cloudformation.Tag{
&mockAppTag,
&mockEnvTag,
&mockTaskTag1,
},
}
mockStack2 := cloudformation.Stack{
StackName: aws.String("task-default-oneoff"),
Tags: []*cloudformation.Tag{
&mockTaskTag2,
},
}
mockStack3 := cloudformation.Stack{
StackName: aws.String("phonetool-test-pdx"),
Tags: []*cloudformation.Tag{
&mockAppTag,
&mockEnvTag,
},
}
mockStacks := &cloudformation.DescribeStacksOutput{
Stacks: []*cloudformation.Stack{
&mockStack1,
&mockStack2,
&mockStack3,
},
}
testCases := map[string]struct {
inTags map[string]string
mockCf func(*mocks.Mockclient)
wantedStacks []StackDescription
wantedErr string
}{
"successfully lists stacks with tags": {
inTags: map[string]string{
"copilot-application": "phonetool",
"copilot-environment": "test-pdx",
},
mockCf: func(m *mocks.Mockclient) {
m.EXPECT().DescribeStacks(&cloudformation.DescribeStacksInput{}).Return(mockStacks, nil)
},
wantedStacks: []StackDescription{
{
StackName: aws.String("task-appenv"),
Tags: []*cloudformation.Tag{
&mockAppTag,
&mockEnvTag,
&mockTaskTag1,
},
},
{
StackName: aws.String("phonetool-test-pdx"),
Tags: []*cloudformation.Tag{
&mockAppTag,
&mockEnvTag,
},
},
},
},
"lists all stacks with wildcard tag": {
inTags: map[string]string{
"copilot-task": "",
},
mockCf: func(m *mocks.Mockclient) {
m.EXPECT().DescribeStacks(&cloudformation.DescribeStacksInput{}).Return(&cloudformation.DescribeStacksOutput{
NextToken: aws.String("abc"),
Stacks: []*cloudformation.Stack{
&mockStack1,
},
}, nil)
m.EXPECT().DescribeStacks(&cloudformation.DescribeStacksInput{
NextToken: aws.String("abc"),
}).Return(&cloudformation.DescribeStacksOutput{
Stacks: []*cloudformation.Stack{
&mockStack2,
&mockStack3,
},
}, nil)
},
wantedStacks: []StackDescription{
{
StackName: aws.String("task-appenv"),
Tags: []*cloudformation.Tag{
&mockAppTag,
&mockEnvTag,
&mockTaskTag1,
},
},
{
StackName: aws.String("task-default-oneoff"),
Tags: []*cloudformation.Tag{
&mockTaskTag2,
},
},
},
},
"empty map returns all stacks": {
inTags: map[string]string{},
mockCf: func(m *mocks.Mockclient) {
m.EXPECT().DescribeStacks(&cloudformation.DescribeStacksInput{}).Return(mockStacks, nil)
},
wantedStacks: []StackDescription{
{
StackName: aws.String("task-appenv"),
Tags: []*cloudformation.Tag{
&mockAppTag,
&mockEnvTag,
&mockTaskTag1,
},
},
{
StackName: aws.String("task-default-oneoff"),
Tags: []*cloudformation.Tag{
&mockTaskTag2,
},
},
{
StackName: aws.String("phonetool-test-pdx"),
Tags: []*cloudformation.Tag{
&mockAppTag,
&mockEnvTag,
},
},
},
},
"error listing stacks": {
inTags: map[string]string{},
mockCf: func(m *mocks.Mockclient) {
m.EXPECT().DescribeStacks(&cloudformation.DescribeStacksInput{}).Return(nil, errors.New("some error"))
},
wantedErr: "list stacks: some error",
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockClient := mocks.NewMockclient(ctrl)
tc.mockCf(mockClient)
c := CloudFormation{
client: mockClient,
}
// WHEN
stacks, err := c.ListStacksWithTags(tc.inTags)
// THEN
if tc.wantedErr != "" {
require.EqualError(t, err, tc.wantedErr)
} else {
require.Equal(t, tc.wantedStacks, stacks)
}
})
}
}
func addCreateDeployCalls(m *mocks.Mockclient) {
addDeployCalls(m, cloudformation.ChangeSetTypeCreate)
}
func addUpdateDeployCalls(m *mocks.Mockclient) {
addDeployCalls(m, cloudformation.ChangeSetTypeUpdate)
}
func addDeployCalls(m *mocks.Mockclient, changeSetType string) {
m.EXPECT().CreateChangeSet(&cloudformation.CreateChangeSetInput{
ChangeSetName: aws.String(mockChangeSetName),
StackName: aws.String(mockStack.Name),
ChangeSetType: aws.String(changeSetType),
TemplateBody: aws.String(mockStack.TemplateBody),
Parameters: nil,
Tags: nil,
RoleARN: nil,
IncludeNestedStacks: aws.Bool(true),
Capabilities: aws.StringSlice([]string{
cloudformation.CapabilityCapabilityIam,
cloudformation.CapabilityCapabilityNamedIam,
cloudformation.CapabilityCapabilityAutoExpand,
}),
}).Return(&cloudformation.CreateChangeSetOutput{
Id: aws.String(mockChangeSetID),
StackId: aws.String(mockStack.Name),
}, nil)
m.EXPECT().WaitUntilChangeSetCreateCompleteWithContext(gomock.Any(), &cloudformation.DescribeChangeSetInput{
ChangeSetName: aws.String(mockChangeSetID),
}, gomock.Any())
m.EXPECT().DescribeChangeSet(&cloudformation.DescribeChangeSetInput{
ChangeSetName: aws.String(mockChangeSetID),
StackName: aws.String(mockStack.Name),
}).Return(&cloudformation.DescribeChangeSetOutput{
Changes: []*cloudformation.Change{
{
ResourceChange: &cloudformation.ResourceChange{
ResourceType: aws.String("ecs service"),
},
Type: aws.String(cloudformation.ChangeTypeResource),
},
},
ExecutionStatus: aws.String(cloudformation.ExecutionStatusAvailable),
StatusReason: aws.String("some reason"),
}, nil)
m.EXPECT().ExecuteChangeSet(&cloudformation.ExecuteChangeSetInput{
ChangeSetName: aws.String(mockChangeSetID),
StackName: aws.String(mockStack.Name),
})
}
| 1,529 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package cloudformation
import (
"fmt"
"strings"
"github.com/aws/aws-sdk-go/aws/awserr"
)
// ErrChangeSetEmpty occurs when the change set does not contain any new or updated resources.
type ErrChangeSetEmpty struct {
cs *changeSet
}
func (e *ErrChangeSetEmpty) Error() string {
return fmt.Sprintf("change set with name %s for stack %s has no changes", e.cs.name, e.cs.stackName)
}
// NewMockErrChangeSetEmpty creates a mock ErrChangeSetEmpty.
func NewMockErrChangeSetEmpty() *ErrChangeSetEmpty {
return &ErrChangeSetEmpty{
cs: &changeSet{
name: "mockChangeSet",
stackName: "mockStack",
},
}
}
// ErrStackAlreadyExists occurs when a CloudFormation stack already exists with a given name.
type ErrStackAlreadyExists struct {
Name string
Stack *StackDescription
}
func (e *ErrStackAlreadyExists) Error() string {
return fmt.Sprintf("stack %s already exists", e.Name)
}
// ErrStackNotFound occurs when a CloudFormation stack does not exist.
type ErrStackNotFound struct {
name string
}
func (e *ErrStackNotFound) Error() string {
return fmt.Sprintf("stack named %s cannot be found", e.name)
}
// ErrChangeSetNotExecutable occurs when the change set cannot be executed.
type ErrChangeSetNotExecutable struct {
cs *changeSet
descr *ChangeSetDescription
}
func (e *ErrChangeSetNotExecutable) Error() string {
return fmt.Sprintf("execute change set %s for stack %s because status is %s with reason %s", e.cs.name, e.cs.stackName, e.descr.ExecutionStatus, e.descr.StatusReason)
}
// ErrStackUpdateInProgress occurs when we try to update a stack that's already being updated.
type ErrStackUpdateInProgress struct {
Name string
}
func (e *ErrStackUpdateInProgress) Error() string {
return fmt.Sprintf("stack %s is currently being updated and cannot be deployed to", e.Name)
}
// stackDoesNotExist returns true if the underlying error is a stack doesn't exist.
func stackDoesNotExist(err error) bool {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case "ValidationError":
// A ValidationError occurs if we describe a stack which doesn't exist.
if strings.Contains(aerr.Message(), "does not exist") {
return true
}
}
}
return false
}
| 83 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package cloudformation
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/service/cloudformation"
)
type changeSetAPI interface {
CreateChangeSet(*cloudformation.CreateChangeSetInput) (*cloudformation.CreateChangeSetOutput, error)
WaitUntilChangeSetCreateCompleteWithContext(aws.Context, *cloudformation.DescribeChangeSetInput, ...request.WaiterOption) error
DescribeChangeSet(*cloudformation.DescribeChangeSetInput) (*cloudformation.DescribeChangeSetOutput, error)
ExecuteChangeSet(*cloudformation.ExecuteChangeSetInput) (*cloudformation.ExecuteChangeSetOutput, error)
DeleteChangeSet(*cloudformation.DeleteChangeSetInput) (*cloudformation.DeleteChangeSetOutput, error)
}
type client interface {
changeSetAPI
GetTemplateSummary(in *cloudformation.GetTemplateSummaryInput) (*cloudformation.GetTemplateSummaryOutput, error)
DescribeStacks(*cloudformation.DescribeStacksInput) (*cloudformation.DescribeStacksOutput, error)
DescribeStackEvents(*cloudformation.DescribeStackEventsInput) (*cloudformation.DescribeStackEventsOutput, error)
DescribeStackResources(input *cloudformation.DescribeStackResourcesInput) (*cloudformation.DescribeStackResourcesOutput, error)
GetTemplate(input *cloudformation.GetTemplateInput) (*cloudformation.GetTemplateOutput, error)
DeleteStack(*cloudformation.DeleteStackInput) (*cloudformation.DeleteStackOutput, error)
WaitUntilStackCreateCompleteWithContext(aws.Context, *cloudformation.DescribeStacksInput, ...request.WaiterOption) error
WaitUntilStackUpdateCompleteWithContext(aws.Context, *cloudformation.DescribeStacksInput, ...request.WaiterOption) error
WaitUntilStackDeleteCompleteWithContext(aws.Context, *cloudformation.DescribeStacksInput, ...request.WaiterOption) error
}
| 33 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package cloudformation
import (
"fmt"
"gopkg.in/yaml.v3"
)
// ParseTemplateDescriptions parses a YAML CloudFormation template to retrieve all human readable
// descriptions associated with a resource. It assumes that all description comments are defined immediately
// under the logical ID of the resource.
//
// For example, if a resource in a template is defined as:
// Cluster:
// # An ECS Cluster to hold your services.
// Type: AWS::ECS::Cluster
//
// The output will be descriptionFor["Cluster"] = "An ECS Cluster to hold your services."
func ParseTemplateDescriptions(body string) (descriptionFor map[string]string, err error) {
type template struct {
Resources map[string]yaml.Node `yaml:"Resources"`
}
var tpl template
if err := yaml.Unmarshal([]byte(body), &tpl); err != nil {
return nil, fmt.Errorf("unmarshal cloudformation template: %w", err)
}
type metadata struct {
Description string `yaml:"aws:copilot:description"`
}
type resource struct {
Metadata metadata `yaml:"Metadata"`
}
descriptionFor = make(map[string]string)
for logicalID, value := range tpl.Resources {
var r resource
if err := value.Decode(&r); err != nil {
return nil, fmt.Errorf("decode resource Metadata for description: %w", err)
}
if description := r.Metadata.Description; description != "" {
descriptionFor[logicalID] = description
}
}
return descriptionFor, nil
}
| 49 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package cloudformation
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
func TestParseTemplateDescriptions(t *testing.T) {
testCases := map[string]struct {
testFile string
wantedDescriptions map[string]string
}{
"parse environment template": {
testFile: "env.yaml",
wantedDescriptions: map[string]string{
"VPC": "Virtual private cloud on 2 availability zones to control network boundaries.",
"PublicRouteTable": "Routing table for services to talk with each other.",
"InternetGateway": "Internet gateway to connect the network to the internet.",
"PublicSubnet1": "A public subnet in your first AZ for internet facing services.",
"PublicSubnet2": "A public subnet in your second AZ for internet facing services.",
"Cluster": "An ECS Cluster to hold your services.",
"PublicLoadBalancer": "An application load balancer to distribute traffic to your Load Balanced Web Services.",
},
},
"parse load balanced web service template": {
testFile: "lb-web-svc.yaml",
wantedDescriptions: map[string]string{
"LogGroup": "A CloudWatch log group to store your logs.",
"TaskDefinition": "An ECS TaskDefinition where your containers are defined.",
"DiscoveryService": "Service discovery to communicate with other services in your VPC.",
"EnvControllerAction": "Updating your environment to enable load balancers.",
"Service": "An ECS service to run and maintain your tasks.",
"TargetGroup": "A target group to connect your service to the load balancer.",
"AddonsStack": "An addons stack for your additional AWS resources.",
"TaskRole": "A task role to manage permissions for your containers.",
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
body, err := os.ReadFile(filepath.Join("testdata", "parse", tc.testFile))
require.NoError(t, err, tc.testFile, "unexpected error while reading testdata file")
// WHEN
descriptions, err := ParseTemplateDescriptions(string(body))
// THEN
require.NoError(t, err, "parsing the cloudformation template should not error")
require.Equal(t, tc.wantedDescriptions, descriptions, "descriptions should match")
})
}
}
| 61 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package cloudformation
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/cloudformation"
)
// Stack represents a AWS CloudFormation stack.
type Stack struct {
Name string
*stackConfig
}
type stackConfig struct {
TemplateBody string
TemplateURL string
Parameters []*cloudformation.Parameter
Tags []*cloudformation.Tag
RoleARN *string
DisableRollback bool
}
// StackOption allows you to initialize a Stack with additional properties.
type StackOption func(s *Stack)
// NewStack creates a stack with the given name and template body.
func NewStack(name, template string, opts ...StackOption) *Stack {
s := &Stack{
Name: name,
stackConfig: &stackConfig{
TemplateBody: template,
},
}
for _, opt := range opts {
opt(s)
}
return s
}
// NewStackWithURL creates a stack with a URL to the template.
func NewStackWithURL(name, templateURL string, opts ...StackOption) *Stack {
s := &Stack{
Name: name,
stackConfig: &stackConfig{
TemplateURL: templateURL,
},
}
for _, opt := range opts {
opt(s)
}
return s
}
// WithParameters passes parameters to a stack.
func WithParameters(params map[string]string) StackOption {
return func(s *Stack) {
var flatParams []*cloudformation.Parameter
for k, v := range params {
flatParams = append(flatParams, &cloudformation.Parameter{
ParameterKey: aws.String(k),
ParameterValue: aws.String(v),
})
}
s.Parameters = flatParams
}
}
// WithTags applies the tags to a stack.
func WithTags(tags map[string]string) StackOption {
return func(s *Stack) {
var flatTags []*cloudformation.Tag
for k, v := range tags {
flatTags = append(flatTags, &cloudformation.Tag{
Key: aws.String(k),
Value: aws.String(v),
})
}
s.Tags = flatTags
}
}
// WithRoleARN specifies the role that CloudFormation will assume when creating the stack.
func WithRoleARN(roleARN string) StackOption {
return func(s *Stack) {
s.RoleARN = aws.String(roleARN)
}
}
// WithDisableRollback disables CloudFormation's automatic stack rollback upon failure for the stack.
func WithDisableRollback() StackOption {
return func(s *Stack) {
s.DisableRollback = true
}
}
// StackEvent is an alias the SDK's StackEvent type.
type StackEvent cloudformation.StackEvent
// StackDescription is an alias the SDK's Stack type.
type StackDescription cloudformation.Stack
// StackResource is an alias the SDK's StackResource type.
type StackResource cloudformation.StackResource
// SDK returns the underlying struct from the AWS SDK.
func (d *StackDescription) SDK() *cloudformation.Stack {
raw := cloudformation.Stack(*d)
return &raw
}
| 113 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package cloudformation
import (
"strings"
"github.com/aws/aws-sdk-go/service/cloudformation"
)
var (
successStackStatuses = []string{
cloudformation.StackStatusCreateComplete,
cloudformation.StackStatusDeleteComplete,
cloudformation.StackStatusUpdateComplete,
cloudformation.StackStatusUpdateCompleteCleanupInProgress,
cloudformation.StackStatusImportComplete,
}
failureStackStatuses = []string{
cloudformation.StackStatusCreateFailed,
cloudformation.StackStatusDeleteFailed,
cloudformation.ResourceStatusUpdateFailed,
cloudformation.StackStatusRollbackInProgress,
cloudformation.StackStatusRollbackComplete,
cloudformation.StackStatusRollbackFailed,
cloudformation.StackStatusUpdateRollbackComplete,
cloudformation.StackStatusUpdateRollbackCompleteCleanupInProgress,
cloudformation.StackStatusUpdateRollbackInProgress,
cloudformation.StackStatusUpdateRollbackFailed,
cloudformation.ResourceStatusImportRollbackInProgress,
cloudformation.ResourceStatusImportRollbackFailed,
}
)
// StackStatus represents the status of a stack.
type StackStatus string
// requiresCleanup returns true if the stack was created, but failed and should be deleted.
func (ss StackStatus) requiresCleanup() bool {
return cloudformation.StackStatusRollbackComplete == string(ss) || cloudformation.StackStatusRollbackFailed == string(ss)
}
// InProgress returns true if the stack is currently being updated.
func (ss StackStatus) InProgress() bool {
return strings.HasSuffix(string(ss), "IN_PROGRESS")
}
// UpsertInProgress returns true if the resource is updating or being created.
func (ss StackStatus) UpsertInProgress() bool {
return ss == cloudformation.StackStatusCreateInProgress || ss == cloudformation.StackStatusUpdateInProgress
}
// IsSuccess returns true if the resource mutated successfully.
func (ss StackStatus) IsSuccess() bool {
for _, success := range successStackStatuses {
if string(ss) == success {
return true
}
}
return false
}
// IsFailure returns true if the resource failed to mutate.
func (ss StackStatus) IsFailure() bool {
for _, failure := range failureStackStatuses {
if string(ss) == failure {
return true
}
}
return false
}
// String implements the fmt.Stringer interface.
func (ss StackStatus) String() string {
return string(ss)
}
| 79 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package cloudformation
import (
"testing"
"github.com/aws/aws-sdk-go/service/cloudformation"
"github.com/stretchr/testify/require"
)
func TestStackStatus_InProgress(t *testing.T) {
testCases := map[string]struct {
status string
wanted bool
}{
"should be false if stack is created succesfully": {
status: cloudformation.StackStatusCreateComplete,
wanted: false,
},
"should be false if stack creation failed": {
status: cloudformation.StackStatusCreateFailed,
wanted: false,
},
"should be true if stack creation is in progress": {
status: cloudformation.StackStatusCreateInProgress,
wanted: true,
},
"should be true if stack update is in progress": {
status: cloudformation.StackStatusUpdateInProgress,
wanted: true,
},
"should be true if stack deletion is in progress": {
status: cloudformation.StackStatusDeleteInProgress,
wanted: true,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
actual := StackStatus(tc.status).InProgress()
require.Equal(t, tc.wanted, actual)
})
}
}
func TestStackStatus_UpsertInProgress(t *testing.T) {
testCases := map[string]struct {
status string
wanted bool
}{
"should be true for update in progress": {
status: cloudformation.StackStatusUpdateInProgress,
wanted: true,
},
"should be true for create in progress": {
status: cloudformation.StackStatusCreateInProgress,
wanted: true,
},
"should be false if created": {
status: cloudformation.StackStatusCreateComplete,
wanted: false,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
actual := StackStatus(tc.status).UpsertInProgress()
require.Equal(t, tc.wanted, actual)
})
}
}
func TestStackStatus_IsSuccess(t *testing.T) {
testCases := map[string]struct {
status string
wanted bool
}{
"should be true for CREATE_COMPLETE": {
status: "CREATE_COMPLETE",
wanted: true,
},
"should be true for DELETE_COMPLETE": {
status: "DELETE_COMPLETE",
wanted: true,
},
"should be true for UPDATE_COMPLETE": {
status: "UPDATE_COMPLETE",
wanted: true,
},
"should be false for CREATE_FAILED": {
status: "CREATE_FAILED",
wanted: false,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
require.Equal(t, tc.wanted, StackStatus(tc.status).IsSuccess())
})
}
}
func TestStackStatus_Failure(t *testing.T) {
testCases := map[string]struct {
status string
wanted bool
}{
"should be true for CREATE_FAILED": {
status: "CREATE_FAILED",
wanted: true,
},
"should be true for DELETE_FAILED": {
status: "DELETE_FAILED",
wanted: true,
},
"should be true for ROLLBACK_IN_PROGRESS": {
status: "ROLLBACK_IN_PROGRESS",
wanted: true,
},
"should be true for UPDATE_FAILED": {
status: "UPDATE_FAILED",
wanted: true,
},
"should be false for CREATE_COMPLETE": {
status: "CREATE_COMPLETE",
wanted: false,
},
"should be false for DELETE_COMPLETE": {
status: "DELETE_COMPLETE",
wanted: false,
},
"should be false for UPDATE_COMPLETE": {
status: "UPDATE_COMPLETE",
wanted: false,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
require.Equal(t, tc.wanted, StackStatus(tc.status).IsFailure())
})
}
}
func TestStackStatus_String(t *testing.T) {
var s StackStatus = "hello"
require.Equal(t, "hello", s.String())
}
| 151 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package cloudformation
import (
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/cloudformation"
"github.com/stretchr/testify/require"
)
func TestNewStack(t *testing.T) {
// WHEN
s := NewStack("hello", "world",
WithParameters(map[string]string{
"Port": "80",
}),
WithTags(map[string]string{
"copilot-application": "phonetool",
}),
WithRoleARN("arn"))
// THEN
require.Equal(t, "hello", s.Name)
require.Equal(t, "world", s.TemplateBody)
require.Equal(t, []*cloudformation.Parameter{
{
ParameterKey: aws.String("Port"),
ParameterValue: aws.String("80"),
},
}, s.Parameters)
require.Equal(t, []*cloudformation.Tag{
{
Key: aws.String("copilot-application"),
Value: aws.String("phonetool"),
},
}, s.Tags)
require.Equal(t, aws.String("arn"), s.RoleARN)
}
func TestNewStackWithURL(t *testing.T) {
// WHEN
s := NewStackWithURL("hello", "worldlyURL",
WithParameters(map[string]string{
"Port": "80",
}),
WithTags(map[string]string{
"copilot-application": "phonetool",
}),
WithRoleARN("arn"))
// THEN
require.Equal(t, "hello", s.Name)
require.Equal(t, "worldlyURL", s.TemplateURL)
require.Equal(t, []*cloudformation.Parameter{
{
ParameterKey: aws.String("Port"),
ParameterValue: aws.String("80"),
},
}, s.Parameters)
require.Equal(t, []*cloudformation.Tag{
{
Key: aws.String("copilot-application"),
Value: aws.String("phonetool"),
},
}, s.Tags)
require.Equal(t, aws.String("arn"), s.RoleARN)
}
| 71 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package cloudformationtest
import (
"context"
sdk "github.com/aws/aws-sdk-go/service/cloudformation"
cfn "github.com/aws/copilot-cli/internal/pkg/aws/cloudformation"
)
// Double is a test double for cloudformation.CloudFormation
type Double struct {
CreateFn func(stack *cfn.Stack) (string, error)
CreateAndWaitFn func(stack *cfn.Stack) error
DescribeChangeSetFn func(changeSetID, stackName string) (*cfn.ChangeSetDescription, error)
WaitForCreateFn func(ctx context.Context, stackName string) error
UpdateFn func(stack *cfn.Stack) (string, error)
UpdateAndWaitFn func(stack *cfn.Stack) error
WaitForUpdateFn func(ctx context.Context, stackName string) error
DeleteFn func(stackName string) error
DeleteAndWaitFn func(stackName string) error
DeleteAndWaitWithRoleARNFn func(stackName, roleARN string) error
DescribeFn func(name string) (*cfn.StackDescription, error)
ExistsFn func(name string) (bool, error)
MetadataFn func(opt cfn.MetadataOpts) (string, error)
TemplateBodyFn func(name string) (string, error)
TemplateBodyFromChangeSetFn func(changeSetID, stackName string) (string, error)
OutputsFn func(stack *cfn.Stack) (map[string]string, error)
EventsFn func(stackName string) ([]cfn.StackEvent, error)
StackResourcesFn func(name string) ([]*cfn.StackResource, error)
ErrorEventsFn func(stackName string) ([]cfn.StackEvent, error)
ListStacksWithTagsFn func(tags map[string]string) ([]cfn.StackDescription, error)
DescribeStackEventsFn func(input *sdk.DescribeStackEventsInput) (*sdk.DescribeStackEventsOutput, error)
}
// Create calls the stubbed function.
func (d *Double) Create(stack *cfn.Stack) (string, error) {
return d.CreateFn(stack)
}
// CreateAndWait calls the stubbed function.
func (d *Double) CreateAndWait(stack *cfn.Stack) error {
return d.CreateAndWaitFn(stack)
}
// DescribeChangeSet calls the stubbed function.
func (d *Double) DescribeChangeSet(id, stack string) (*cfn.ChangeSetDescription, error) {
return d.DescribeChangeSetFn(id, stack)
}
// WaitForCreate calls the stubbed function.
func (d *Double) WaitForCreate(ctx context.Context, stack string) error {
return d.WaitForCreateFn(ctx, stack)
}
// Update calls the stubbed function.
func (d *Double) Update(stack *cfn.Stack) (string, error) {
return d.UpdateFn(stack)
}
// UpdateAndWait calls the stubbed function.
func (d *Double) UpdateAndWait(stack *cfn.Stack) error {
return d.UpdateAndWaitFn(stack)
}
// WaitForUpdate calls the stubbed function.
func (d *Double) WaitForUpdate(ctx context.Context, stackName string) error {
return d.WaitForUpdateFn(ctx, stackName)
}
// Delete calls the stubbed function.
func (d *Double) Delete(stackName string) error {
return d.DeleteFn(stackName)
}
// DeleteAndWait calls the stubbed function.
func (d *Double) DeleteAndWait(stackName string) error {
return d.DeleteAndWaitFn(stackName)
}
// DeleteAndWaitWithRoleARN calls the stubbed function.
func (d *Double) DeleteAndWaitWithRoleARN(stackName, roleARN string) error {
return d.DeleteAndWaitWithRoleARNFn(stackName, roleARN)
}
// Describe calls the stubbed function.
func (d *Double) Describe(name string) (*cfn.StackDescription, error) {
return d.DescribeFn(name)
}
// Exists calls the stubbed function.
func (d *Double) Exists(name string) (bool, error) {
return d.ExistsFn(name)
}
// Metadata calls the stubbed function.
func (d *Double) Metadata(opt cfn.MetadataOpts) (string, error) {
return d.MetadataFn(opt)
}
// TemplateBody calls the stubbed function.
func (d *Double) TemplateBody(name string) (string, error) {
return d.TemplateBodyFn(name)
}
// TemplateBodyFromChangeSet calls the stubbed function.
func (d *Double) TemplateBodyFromChangeSet(changeSetID, stackName string) (string, error) {
return d.TemplateBodyFromChangeSetFn(changeSetID, stackName)
}
// Outputs calls the stubbed function.
func (d *Double) Outputs(stack *cfn.Stack) (map[string]string, error) {
return d.OutputsFn(stack)
}
// Events calls the stubbed function.
func (d *Double) Events(stackName string) ([]cfn.StackEvent, error) {
return d.EventsFn(stackName)
}
// StackResources calls the stubbed function.
func (d *Double) StackResources(name string) ([]*cfn.StackResource, error) {
return d.StackResourcesFn(name)
}
// ErrorEvents calls the stubbed function.
func (d *Double) ErrorEvents(stackName string) ([]cfn.StackEvent, error) {
return d.ErrorEventsFn(stackName)
}
// ListStacksWithTags calls the stubbed function.
func (d *Double) ListStacksWithTags(tags map[string]string) ([]cfn.StackDescription, error) {
return d.ListStacksWithTagsFn(tags)
}
// DescribeStackEvents calls the stubbed function.
func (d *Double) DescribeStackEvents(input *sdk.DescribeStackEventsInput) (*sdk.DescribeStackEventsOutput, error) {
return d.DescribeStackEventsFn(input)
}
| 142 |
copilot-cli | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: ./internal/pkg/aws/cloudformation/interfaces.go
// Package mocks is a generated GoMock package.
package mocks
import (
reflect "reflect"
aws "github.com/aws/aws-sdk-go/aws"
request "github.com/aws/aws-sdk-go/aws/request"
cloudformation "github.com/aws/aws-sdk-go/service/cloudformation"
gomock "github.com/golang/mock/gomock"
)
// MockchangeSetAPI is a mock of changeSetAPI interface.
type MockchangeSetAPI struct {
ctrl *gomock.Controller
recorder *MockchangeSetAPIMockRecorder
}
// MockchangeSetAPIMockRecorder is the mock recorder for MockchangeSetAPI.
type MockchangeSetAPIMockRecorder struct {
mock *MockchangeSetAPI
}
// NewMockchangeSetAPI creates a new mock instance.
func NewMockchangeSetAPI(ctrl *gomock.Controller) *MockchangeSetAPI {
mock := &MockchangeSetAPI{ctrl: ctrl}
mock.recorder = &MockchangeSetAPIMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockchangeSetAPI) EXPECT() *MockchangeSetAPIMockRecorder {
return m.recorder
}
// CreateChangeSet mocks base method.
func (m *MockchangeSetAPI) CreateChangeSet(arg0 *cloudformation.CreateChangeSetInput) (*cloudformation.CreateChangeSetOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CreateChangeSet", arg0)
ret0, _ := ret[0].(*cloudformation.CreateChangeSetOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// CreateChangeSet indicates an expected call of CreateChangeSet.
func (mr *MockchangeSetAPIMockRecorder) CreateChangeSet(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateChangeSet", reflect.TypeOf((*MockchangeSetAPI)(nil).CreateChangeSet), arg0)
}
// DeleteChangeSet mocks base method.
func (m *MockchangeSetAPI) DeleteChangeSet(arg0 *cloudformation.DeleteChangeSetInput) (*cloudformation.DeleteChangeSetOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DeleteChangeSet", arg0)
ret0, _ := ret[0].(*cloudformation.DeleteChangeSetOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DeleteChangeSet indicates an expected call of DeleteChangeSet.
func (mr *MockchangeSetAPIMockRecorder) DeleteChangeSet(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteChangeSet", reflect.TypeOf((*MockchangeSetAPI)(nil).DeleteChangeSet), arg0)
}
// DescribeChangeSet mocks base method.
func (m *MockchangeSetAPI) DescribeChangeSet(arg0 *cloudformation.DescribeChangeSetInput) (*cloudformation.DescribeChangeSetOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DescribeChangeSet", arg0)
ret0, _ := ret[0].(*cloudformation.DescribeChangeSetOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DescribeChangeSet indicates an expected call of DescribeChangeSet.
func (mr *MockchangeSetAPIMockRecorder) DescribeChangeSet(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeChangeSet", reflect.TypeOf((*MockchangeSetAPI)(nil).DescribeChangeSet), arg0)
}
// ExecuteChangeSet mocks base method.
func (m *MockchangeSetAPI) ExecuteChangeSet(arg0 *cloudformation.ExecuteChangeSetInput) (*cloudformation.ExecuteChangeSetOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ExecuteChangeSet", arg0)
ret0, _ := ret[0].(*cloudformation.ExecuteChangeSetOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ExecuteChangeSet indicates an expected call of ExecuteChangeSet.
func (mr *MockchangeSetAPIMockRecorder) ExecuteChangeSet(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ExecuteChangeSet", reflect.TypeOf((*MockchangeSetAPI)(nil).ExecuteChangeSet), arg0)
}
// WaitUntilChangeSetCreateCompleteWithContext mocks base method.
func (m *MockchangeSetAPI) WaitUntilChangeSetCreateCompleteWithContext(arg0 aws.Context, arg1 *cloudformation.DescribeChangeSetInput, arg2 ...request.WaiterOption) error {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "WaitUntilChangeSetCreateCompleteWithContext", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// WaitUntilChangeSetCreateCompleteWithContext indicates an expected call of WaitUntilChangeSetCreateCompleteWithContext.
func (mr *MockchangeSetAPIMockRecorder) WaitUntilChangeSetCreateCompleteWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WaitUntilChangeSetCreateCompleteWithContext", reflect.TypeOf((*MockchangeSetAPI)(nil).WaitUntilChangeSetCreateCompleteWithContext), varargs...)
}
// Mockclient is a mock of client interface.
type Mockclient struct {
ctrl *gomock.Controller
recorder *MockclientMockRecorder
}
// MockclientMockRecorder is the mock recorder for Mockclient.
type MockclientMockRecorder struct {
mock *Mockclient
}
// NewMockclient creates a new mock instance.
func NewMockclient(ctrl *gomock.Controller) *Mockclient {
mock := &Mockclient{ctrl: ctrl}
mock.recorder = &MockclientMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *Mockclient) EXPECT() *MockclientMockRecorder {
return m.recorder
}
// CreateChangeSet mocks base method.
func (m *Mockclient) CreateChangeSet(arg0 *cloudformation.CreateChangeSetInput) (*cloudformation.CreateChangeSetOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CreateChangeSet", arg0)
ret0, _ := ret[0].(*cloudformation.CreateChangeSetOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// CreateChangeSet indicates an expected call of CreateChangeSet.
func (mr *MockclientMockRecorder) CreateChangeSet(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateChangeSet", reflect.TypeOf((*Mockclient)(nil).CreateChangeSet), arg0)
}
// DeleteChangeSet mocks base method.
func (m *Mockclient) DeleteChangeSet(arg0 *cloudformation.DeleteChangeSetInput) (*cloudformation.DeleteChangeSetOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DeleteChangeSet", arg0)
ret0, _ := ret[0].(*cloudformation.DeleteChangeSetOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DeleteChangeSet indicates an expected call of DeleteChangeSet.
func (mr *MockclientMockRecorder) DeleteChangeSet(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteChangeSet", reflect.TypeOf((*Mockclient)(nil).DeleteChangeSet), arg0)
}
// DeleteStack mocks base method.
func (m *Mockclient) DeleteStack(arg0 *cloudformation.DeleteStackInput) (*cloudformation.DeleteStackOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DeleteStack", arg0)
ret0, _ := ret[0].(*cloudformation.DeleteStackOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DeleteStack indicates an expected call of DeleteStack.
func (mr *MockclientMockRecorder) DeleteStack(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteStack", reflect.TypeOf((*Mockclient)(nil).DeleteStack), arg0)
}
// DescribeChangeSet mocks base method.
func (m *Mockclient) DescribeChangeSet(arg0 *cloudformation.DescribeChangeSetInput) (*cloudformation.DescribeChangeSetOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DescribeChangeSet", arg0)
ret0, _ := ret[0].(*cloudformation.DescribeChangeSetOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DescribeChangeSet indicates an expected call of DescribeChangeSet.
func (mr *MockclientMockRecorder) DescribeChangeSet(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeChangeSet", reflect.TypeOf((*Mockclient)(nil).DescribeChangeSet), arg0)
}
// DescribeStackEvents mocks base method.
func (m *Mockclient) DescribeStackEvents(arg0 *cloudformation.DescribeStackEventsInput) (*cloudformation.DescribeStackEventsOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DescribeStackEvents", arg0)
ret0, _ := ret[0].(*cloudformation.DescribeStackEventsOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DescribeStackEvents indicates an expected call of DescribeStackEvents.
func (mr *MockclientMockRecorder) DescribeStackEvents(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeStackEvents", reflect.TypeOf((*Mockclient)(nil).DescribeStackEvents), arg0)
}
// DescribeStackResources mocks base method.
func (m *Mockclient) DescribeStackResources(input *cloudformation.DescribeStackResourcesInput) (*cloudformation.DescribeStackResourcesOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DescribeStackResources", input)
ret0, _ := ret[0].(*cloudformation.DescribeStackResourcesOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DescribeStackResources indicates an expected call of DescribeStackResources.
func (mr *MockclientMockRecorder) DescribeStackResources(input interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeStackResources", reflect.TypeOf((*Mockclient)(nil).DescribeStackResources), input)
}
// DescribeStacks mocks base method.
func (m *Mockclient) DescribeStacks(arg0 *cloudformation.DescribeStacksInput) (*cloudformation.DescribeStacksOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DescribeStacks", arg0)
ret0, _ := ret[0].(*cloudformation.DescribeStacksOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DescribeStacks indicates an expected call of DescribeStacks.
func (mr *MockclientMockRecorder) DescribeStacks(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeStacks", reflect.TypeOf((*Mockclient)(nil).DescribeStacks), arg0)
}
// ExecuteChangeSet mocks base method.
func (m *Mockclient) ExecuteChangeSet(arg0 *cloudformation.ExecuteChangeSetInput) (*cloudformation.ExecuteChangeSetOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ExecuteChangeSet", arg0)
ret0, _ := ret[0].(*cloudformation.ExecuteChangeSetOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ExecuteChangeSet indicates an expected call of ExecuteChangeSet.
func (mr *MockclientMockRecorder) ExecuteChangeSet(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ExecuteChangeSet", reflect.TypeOf((*Mockclient)(nil).ExecuteChangeSet), arg0)
}
// GetTemplate mocks base method.
func (m *Mockclient) GetTemplate(input *cloudformation.GetTemplateInput) (*cloudformation.GetTemplateOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetTemplate", input)
ret0, _ := ret[0].(*cloudformation.GetTemplateOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetTemplate indicates an expected call of GetTemplate.
func (mr *MockclientMockRecorder) GetTemplate(input interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTemplate", reflect.TypeOf((*Mockclient)(nil).GetTemplate), input)
}
// GetTemplateSummary mocks base method.
func (m *Mockclient) GetTemplateSummary(in *cloudformation.GetTemplateSummaryInput) (*cloudformation.GetTemplateSummaryOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetTemplateSummary", in)
ret0, _ := ret[0].(*cloudformation.GetTemplateSummaryOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetTemplateSummary indicates an expected call of GetTemplateSummary.
func (mr *MockclientMockRecorder) GetTemplateSummary(in interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTemplateSummary", reflect.TypeOf((*Mockclient)(nil).GetTemplateSummary), in)
}
// WaitUntilChangeSetCreateCompleteWithContext mocks base method.
func (m *Mockclient) WaitUntilChangeSetCreateCompleteWithContext(arg0 aws.Context, arg1 *cloudformation.DescribeChangeSetInput, arg2 ...request.WaiterOption) error {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "WaitUntilChangeSetCreateCompleteWithContext", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// WaitUntilChangeSetCreateCompleteWithContext indicates an expected call of WaitUntilChangeSetCreateCompleteWithContext.
func (mr *MockclientMockRecorder) WaitUntilChangeSetCreateCompleteWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WaitUntilChangeSetCreateCompleteWithContext", reflect.TypeOf((*Mockclient)(nil).WaitUntilChangeSetCreateCompleteWithContext), varargs...)
}
// WaitUntilStackCreateCompleteWithContext mocks base method.
func (m *Mockclient) WaitUntilStackCreateCompleteWithContext(arg0 aws.Context, arg1 *cloudformation.DescribeStacksInput, arg2 ...request.WaiterOption) error {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "WaitUntilStackCreateCompleteWithContext", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// WaitUntilStackCreateCompleteWithContext indicates an expected call of WaitUntilStackCreateCompleteWithContext.
func (mr *MockclientMockRecorder) WaitUntilStackCreateCompleteWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WaitUntilStackCreateCompleteWithContext", reflect.TypeOf((*Mockclient)(nil).WaitUntilStackCreateCompleteWithContext), varargs...)
}
// WaitUntilStackDeleteCompleteWithContext mocks base method.
func (m *Mockclient) WaitUntilStackDeleteCompleteWithContext(arg0 aws.Context, arg1 *cloudformation.DescribeStacksInput, arg2 ...request.WaiterOption) error {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "WaitUntilStackDeleteCompleteWithContext", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// WaitUntilStackDeleteCompleteWithContext indicates an expected call of WaitUntilStackDeleteCompleteWithContext.
func (mr *MockclientMockRecorder) WaitUntilStackDeleteCompleteWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WaitUntilStackDeleteCompleteWithContext", reflect.TypeOf((*Mockclient)(nil).WaitUntilStackDeleteCompleteWithContext), varargs...)
}
// WaitUntilStackUpdateCompleteWithContext mocks base method.
func (m *Mockclient) WaitUntilStackUpdateCompleteWithContext(arg0 aws.Context, arg1 *cloudformation.DescribeStacksInput, arg2 ...request.WaiterOption) error {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "WaitUntilStackUpdateCompleteWithContext", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// WaitUntilStackUpdateCompleteWithContext indicates an expected call of WaitUntilStackUpdateCompleteWithContext.
func (mr *MockclientMockRecorder) WaitUntilStackUpdateCompleteWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WaitUntilStackUpdateCompleteWithContext", reflect.TypeOf((*Mockclient)(nil).WaitUntilStackUpdateCompleteWithContext), varargs...)
}
| 366 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package stackset
// Description represents a created stack set resource.
type Description struct {
ID string
Name string
Template string
}
| 12 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package stackset
import (
"fmt"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/cloudformation"
)
// ErrStackSetOutOfDate occurs when we try to read and then update a StackSet but between reading it
// and actually updating it, someone else either started or completed an update.
type ErrStackSetOutOfDate struct {
name string
parentErr error
}
func (e *ErrStackSetOutOfDate) Error() string {
return fmt.Sprintf("stack set %q update was out of date (feel free to try again): %v", e.name, e.parentErr)
}
// ErrStackSetNotFound occurs when a stack set with the given name does not exist.
type ErrStackSetNotFound struct {
name string
}
// Error implements the error interface.
func (e *ErrStackSetNotFound) Error() string {
return fmt.Sprintf("stack set %q not found", e.name)
}
// IsEmpty reports whether this error is occurs on an empty cloudformation resource.
func (e *ErrStackSetNotFound) IsEmpty() bool {
return true
}
// ErrStackSetInstancesNotFound occurs when a stack set operation should be applied to instances but they don't exist.
type ErrStackSetInstancesNotFound struct {
name string
}
// Error implements the error interface.
func (e *ErrStackSetInstancesNotFound) Error() string {
return fmt.Sprintf("stack set %q has no instances", e.name)
}
// IsEmpty reports whether this error is occurs on an empty cloudformation resource.
func (e *ErrStackSetInstancesNotFound) IsEmpty() bool {
return true
}
// isAlreadyExistingStackSet returns true if the underlying error is a stack already exists error.
func isAlreadyExistingStackSet(err error) bool {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case cloudformation.ErrCodeNameAlreadyExistsException:
return true
}
}
return false
}
// isOutdatedStackSet returns true if the underlying error is because the operation was already performed.
func isOutdatedStackSet(err error) bool {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case cloudformation.ErrCodeOperationIdAlreadyExistsException, cloudformation.ErrCodeOperationInProgressException, cloudformation.ErrCodeStaleRequestException:
return true
}
}
return false
}
// isNotFoundStackSet returns true if the stack set does not exist.
func isNotFoundStackSet(err error) bool {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case cloudformation.ErrCodeStackSetNotFoundException:
return true
}
}
return false
}
| 86 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package stackset
import (
"errors"
"testing"
"github.com/stretchr/testify/require"
)
func TestErrStackSetOutOfDate_Error(t *testing.T) {
err := &ErrStackSetOutOfDate{
name: "demo-infrastructure",
parentErr: errors.New("some error"),
}
require.EqualError(t, err, `stack set "demo-infrastructure" update was out of date (feel free to try again): some error`)
}
func TestErrStackSetNotFound_Error(t *testing.T) {
err := &ErrStackSetNotFound{
name: "demo-infrastructure",
}
require.EqualError(t, err, `stack set "demo-infrastructure" not found`)
}
func TestErrStackSetInstancesNotFound_Error(t *testing.T) {
err := &ErrStackSetInstancesNotFound{
name: "demo-infrastructure",
}
require.EqualError(t, err, `stack set "demo-infrastructure" has no instances`)
}
| 37 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package stackset provides a client to make API requests to an AWS CloudFormation StackSet resource.
package stackset
import (
"errors"
"fmt"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudformation"
)
type api interface {
CreateStackSet(*cloudformation.CreateStackSetInput) (*cloudformation.CreateStackSetOutput, error)
UpdateStackSet(*cloudformation.UpdateStackSetInput) (*cloudformation.UpdateStackSetOutput, error)
ListStackSetOperations(input *cloudformation.ListStackSetOperationsInput) (*cloudformation.ListStackSetOperationsOutput, error)
DeleteStackSet(*cloudformation.DeleteStackSetInput) (*cloudformation.DeleteStackSetOutput, error)
DescribeStackSet(*cloudformation.DescribeStackSetInput) (*cloudformation.DescribeStackSetOutput, error)
DescribeStackSetOperation(*cloudformation.DescribeStackSetOperationInput) (*cloudformation.DescribeStackSetOperationOutput, error)
CreateStackInstances(*cloudformation.CreateStackInstancesInput) (*cloudformation.CreateStackInstancesOutput, error)
DeleteStackInstances(*cloudformation.DeleteStackInstancesInput) (*cloudformation.DeleteStackInstancesOutput, error)
ListStackInstances(*cloudformation.ListStackInstancesInput) (*cloudformation.ListStackInstancesOutput, error)
}
// StackSet represents an AWS CloudFormation client to interact with stack sets.
type StackSet struct {
client api
}
// New creates a new client to make requests against stack sets.
func New(s *session.Session) *StackSet {
return &StackSet{
client: cloudformation.New(s),
}
}
// CreateOrUpdateOption allows to initialize or update a stack set with additional properties.
type CreateOrUpdateOption func(interface{})
// Create creates a new stack set resource, if one already exists then do nothing.
func (ss *StackSet) Create(name, template string, opts ...CreateOrUpdateOption) error {
in := &cloudformation.CreateStackSetInput{
StackSetName: aws.String(name),
TemplateBody: aws.String(template),
}
for _, opt := range opts {
opt(in)
}
_, err := ss.client.CreateStackSet(in)
if err != nil {
if !isAlreadyExistingStackSet(err) {
return fmt.Errorf("create stack set %s: %w", name, err)
}
}
return nil
}
// Describe returns a description of a created stack set.
func (ss *StackSet) Describe(name string) (Description, error) {
resp, err := ss.client.DescribeStackSet(&cloudformation.DescribeStackSetInput{
StackSetName: aws.String(name),
})
if err != nil {
return Description{}, fmt.Errorf("describe stack set %s: %w", name, err)
}
return Description{
ID: aws.StringValue(resp.StackSet.StackSetId),
Name: aws.StringValue(resp.StackSet.StackSetName),
Template: aws.StringValue(resp.StackSet.TemplateBody),
}, nil
}
// Operation represents information about a stack set operation.
type Operation struct {
ID string
Status OpStatus
Reason string
}
// DescribeOperation returns a description of the operation.
func (ss *StackSet) DescribeOperation(name, opID string) (Operation, error) {
resp, err := ss.client.DescribeStackSetOperation(&cloudformation.DescribeStackSetOperationInput{
StackSetName: aws.String(name),
OperationId: aws.String(opID),
})
if err != nil {
return Operation{}, fmt.Errorf("describe operation %s for stack set %s: %w", opID, name, err)
}
return Operation{
ID: opID,
Status: OpStatus(aws.StringValue(resp.StackSetOperation.Status)),
Reason: aws.StringValue(resp.StackSetOperation.StatusReason),
}, nil
}
// Update updates all the instances in a stack set with the new template and returns the operation ID.
func (ss *StackSet) Update(name, template string, opts ...CreateOrUpdateOption) (string, error) {
return ss.update(name, template, opts...)
}
// UpdateAndWait updates a stack set with a new template, and waits until the operation completes.
func (ss *StackSet) UpdateAndWait(name, template string, opts ...CreateOrUpdateOption) error {
id, err := ss.update(name, template, opts...)
if err != nil {
return err
}
return ss.WaitForOperation(name, id)
}
// DeleteAllInstances removes all stack instances from a stack set and returns the operation ID.
// If the stack set does not exist, then return [ErrStackSetNotFound].
// If the stack set does not have any instances, then return [ErrStackSetInstancesNotFound].
// Both errors should satisfy [IsEmptyStackSetErr], otherwise it's an unexpected error.
func (ss *StackSet) DeleteAllInstances(name string) (string, error) {
summaries, err := ss.InstanceSummaries(name)
if err != nil {
// If the stack set doesn't exist - just move on.
if isNotFoundStackSet(errors.Unwrap(err)) {
return "", &ErrStackSetNotFound{
name: name,
}
}
return "", err
}
if len(summaries) == 0 {
return "", &ErrStackSetInstancesNotFound{
name: name,
}
}
// We want to delete all the stack instances, so we create a set of account IDs and regions.
uniqueAccounts := make(map[string]bool)
uniqueRegions := make(map[string]bool)
for _, summary := range summaries {
uniqueAccounts[summary.Account] = true
uniqueRegions[summary.Region] = true
}
var regions []string
var accounts []string
for account := range uniqueAccounts {
accounts = append(accounts, account)
}
for region := range uniqueRegions {
regions = append(regions, region)
}
out, err := ss.client.DeleteStackInstances(&cloudformation.DeleteStackInstancesInput{
StackSetName: aws.String(name),
Accounts: aws.StringSlice(accounts),
Regions: aws.StringSlice(regions),
RetainStacks: aws.Bool(false),
})
if err != nil {
return "", fmt.Errorf("delete stack instances in regions %v for accounts %v for stackset %s: %w",
regions, accounts, name, err)
}
return aws.StringValue(out.OperationId), nil
}
// Delete deletes the stack set, if the stack set does not exist then just return nil.
func (ss *StackSet) Delete(name string) error {
if _, err := ss.client.DeleteStackSet(&cloudformation.DeleteStackSetInput{
StackSetName: aws.String(name),
}); err != nil {
if !isNotFoundStackSet(err) {
return fmt.Errorf("delete stack set %s: %w", name, err)
}
}
return nil
}
// CreateInstances creates new stack instances within the regions
// of the specified AWS accounts and returns the operation ID.
func (ss *StackSet) CreateInstances(name string, accounts, regions []string) (string, error) {
return ss.createInstances(name, accounts, regions)
}
// CreateInstancesAndWait creates new stack instances in the regions of the specified AWS accounts, and waits until the operation completes.
func (ss *StackSet) CreateInstancesAndWait(name string, accounts, regions []string) error {
id, err := ss.createInstances(name, accounts, regions)
if err != nil {
return err
}
return ss.WaitForOperation(name, id)
}
// InstanceSummary represents the identifiers for a stack instance.
type InstanceSummary struct {
StackID string
Account string
Region string
Status InstanceStatus
}
// InstanceSummariesOption allows to filter instance summaries to retrieve for the stack set.
type InstanceSummariesOption func(input *cloudformation.ListStackInstancesInput)
// InstanceSummaries returns a list of unique identifiers for all the stack instances in a stack set.
func (ss *StackSet) InstanceSummaries(name string, opts ...InstanceSummariesOption) ([]InstanceSummary, error) {
in := &cloudformation.ListStackInstancesInput{
StackSetName: aws.String(name),
}
for _, opt := range opts {
opt(in)
}
var summaries []InstanceSummary
for {
resp, err := ss.client.ListStackInstances(in)
if err != nil {
return nil, fmt.Errorf("list stack instances for stack set %s: %w", name, err)
}
for _, cfnSummary := range resp.Summaries {
summary := InstanceSummary{
StackID: aws.StringValue(cfnSummary.StackId),
Account: aws.StringValue(cfnSummary.Account),
Region: aws.StringValue(cfnSummary.Region),
}
if status := cfnSummary.StackInstanceStatus; status != nil {
summary.Status = InstanceStatus(aws.StringValue(status.DetailedStatus))
}
summaries = append(summaries, summary)
}
in.NextToken = resp.NextToken
if in.NextToken == nil {
break
}
}
return summaries, nil
}
func (ss *StackSet) update(name, template string, opts ...CreateOrUpdateOption) (string, error) {
in := &cloudformation.UpdateStackSetInput{
StackSetName: aws.String(name),
TemplateBody: aws.String(template),
OperationPreferences: &cloudformation.StackSetOperationPreferences{
RegionConcurrencyType: aws.String(cloudformation.RegionConcurrencyTypeParallel),
},
}
for _, opt := range opts {
opt(in)
}
resp, err := ss.client.UpdateStackSet(in)
if err != nil {
if isOutdatedStackSet(err) {
return "", &ErrStackSetOutOfDate{
name: name,
parentErr: err,
}
}
return "", fmt.Errorf("update stack set %s: %w", name, err)
}
return aws.StringValue(resp.OperationId), nil
}
func (ss *StackSet) createInstances(name string, accounts, regions []string) (string, error) {
resp, err := ss.client.CreateStackInstances(&cloudformation.CreateStackInstancesInput{
StackSetName: aws.String(name),
Accounts: aws.StringSlice(accounts),
Regions: aws.StringSlice(regions),
})
if err != nil {
return "", fmt.Errorf("create stack instances for stack set %s in regions %v for accounts %v: %w",
name, regions, accounts, err)
}
return aws.StringValue(resp.OperationId), nil
}
// WaitForStackSetLastOperationComplete waits until the stackset's last operation completes.
func (ss *StackSet) WaitForStackSetLastOperationComplete(name string) error {
for {
resp, err := ss.client.ListStackSetOperations(&cloudformation.ListStackSetOperationsInput{
StackSetName: aws.String(name),
})
if err != nil {
return fmt.Errorf("list operations for stack set %s: %w", name, err)
}
if len(resp.Summaries) == 0 {
return nil
}
operation := resp.Summaries[0]
switch aws.StringValue(operation.Status) {
case cloudformation.StackSetOperationStatusRunning:
case cloudformation.StackSetOperationStatusStopping:
case cloudformation.StackSetOperationStatusQueued:
default:
return nil
}
time.Sleep(3 * time.Second)
}
}
// WaitForOperation waits for the operation with opID to reaches a successful completion status.
func (ss *StackSet) WaitForOperation(name, opID string) error {
for {
response, err := ss.client.DescribeStackSetOperation(&cloudformation.DescribeStackSetOperationInput{
StackSetName: aws.String(name),
OperationId: aws.String(opID),
})
if err != nil {
return fmt.Errorf("describe operation %s for stack set %s: %w", opID, name, err)
}
if aws.StringValue(response.StackSetOperation.Status) == opStatusSucceeded {
return nil
}
if aws.StringValue(response.StackSetOperation.Status) == opStatusStopped {
return fmt.Errorf("operation %s for stack set %s was manually stopped", opID, name)
}
if aws.StringValue(response.StackSetOperation.Status) == opStatusFailed {
return fmt.Errorf("operation %s for stack set %s failed", opID, name)
}
time.Sleep(3 * time.Second)
}
}
// WithDescription sets a description for a stack set.
func WithDescription(description string) CreateOrUpdateOption {
return func(input interface{}) {
switch v := input.(type) {
case *cloudformation.CreateStackSetInput:
{
v.Description = aws.String(description)
}
case *cloudformation.UpdateStackSetInput:
{
v.Description = aws.String(description)
}
}
}
}
// WithExecutionRoleName sets an execution role name for a stack set.
func WithExecutionRoleName(roleName string) CreateOrUpdateOption {
return func(input interface{}) {
switch v := input.(type) {
case *cloudformation.CreateStackSetInput:
{
v.ExecutionRoleName = aws.String(roleName)
}
case *cloudformation.UpdateStackSetInput:
{
v.ExecutionRoleName = aws.String(roleName)
}
}
}
}
// WithAdministrationRoleARN sets an administration role arn for a stack set.
func WithAdministrationRoleARN(roleARN string) CreateOrUpdateOption {
return func(input interface{}) {
switch v := input.(type) {
case *cloudformation.CreateStackSetInput:
{
v.AdministrationRoleARN = aws.String(roleARN)
}
case *cloudformation.UpdateStackSetInput:
{
v.AdministrationRoleARN = aws.String(roleARN)
}
}
}
}
// WithTags sets tags to all the resources in a stack set.
func WithTags(tags map[string]string) CreateOrUpdateOption {
return func(input interface{}) {
var flatTags []*cloudformation.Tag
for k, v := range tags {
flatTags = append(flatTags, &cloudformation.Tag{
Key: aws.String(k),
Value: aws.String(v),
})
}
switch v := input.(type) {
case *cloudformation.CreateStackSetInput:
{
v.Tags = flatTags
}
case *cloudformation.UpdateStackSetInput:
{
v.Tags = flatTags
}
}
}
}
// WithOperationID sets the operation ID of a stack set operation.
// This functional option can only be used while updating a stack set, otherwise it's a no-op.
func WithOperationID(operationID string) CreateOrUpdateOption {
return func(input interface{}) {
switch v := input.(type) {
case *cloudformation.UpdateStackSetInput:
{
v.OperationId = aws.String(operationID)
}
}
}
}
// FilterSummariesByAccountID limits the accountID for the stack instance summaries to retrieve.
func FilterSummariesByAccountID(accountID string) InstanceSummariesOption {
return func(input *cloudformation.ListStackInstancesInput) {
input.StackInstanceAccount = aws.String(accountID)
}
}
// FilterSummariesByRegion limits the region for the stack instance summaries to retrieve.
func FilterSummariesByRegion(region string) InstanceSummariesOption {
return func(input *cloudformation.ListStackInstancesInput) {
input.StackInstanceRegion = aws.String(region)
}
}
// FilterSummariesByDetailedStatus limits the stack instance summaries to the passed status values.
func FilterSummariesByDetailedStatus(values []InstanceStatus) InstanceSummariesOption {
return func(input *cloudformation.ListStackInstancesInput) {
for _, value := range values {
input.Filters = append(input.Filters, &cloudformation.StackInstanceFilter{
Name: aws.String(cloudformation.StackInstanceFilterNameDetailedStatus),
Values: aws.String(string(value)),
})
}
}
}
| 433 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package stackset
import (
"errors"
"fmt"
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/cloudformation"
"github.com/aws/copilot-cli/internal/pkg/aws/cloudformation/stackset/mocks"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
const testName = "stackset"
var testError = errors.New("some error")
func TestStackSet_Create(t *testing.T) {
const (
testTemplate = "body"
testDescription = "amazing stack set"
testExecutionRole = "execARN"
testAdministrationRole = "adminARN"
)
testTags := map[string]string{
"owner": "boss",
}
testCases := map[string]struct {
mockClient func(ctrl *gomock.Controller) api
wantedError error
}{
"succeeds if new stack set": {
mockClient: func(ctrl *gomock.Controller) api {
m := mocks.NewMockapi(ctrl)
m.EXPECT().CreateStackSet(&cloudformation.CreateStackSetInput{
AdministrationRoleARN: aws.String(testAdministrationRole),
Description: aws.String(testDescription),
ExecutionRoleName: aws.String(testExecutionRole),
StackSetName: aws.String(testName),
Tags: []*cloudformation.Tag{
{
Key: aws.String("owner"),
Value: aws.String("boss"),
},
},
TemplateBody: aws.String(testTemplate),
})
return m
},
},
"succeeds if stack set already exists": {
mockClient: func(ctrl *gomock.Controller) api {
m := mocks.NewMockapi(ctrl)
m.EXPECT().CreateStackSet(gomock.Any()).Return(nil, awserr.New(cloudformation.ErrCodeNameAlreadyExistsException, "", nil))
return m
},
},
"wraps error on unexpected failure": {
mockClient: func(ctrl *gomock.Controller) api {
m := mocks.NewMockapi(ctrl)
m.EXPECT().CreateStackSet(gomock.Any()).Return(nil, testError)
return m
},
wantedError: fmt.Errorf("create stack set %s: %w", testName, testError),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
client := StackSet{
client: tc.mockClient(ctrl),
}
// WHEN
err := client.Create(testName, testTemplate,
WithDescription(testDescription),
WithAdministrationRoleARN(testAdministrationRole),
WithExecutionRoleName(testExecutionRole),
WithTags(testTags))
// THEN
require.Equal(t, tc.wantedError, err)
})
}
}
func TestStackSet_Describe(t *testing.T) {
testCases := map[string]struct {
mockClient func(ctrl *gomock.Controller) api
wantedDescr Description
wantedError error
}{
"succeeds": {
mockClient: func(ctrl *gomock.Controller) api {
m := mocks.NewMockapi(ctrl)
m.EXPECT().DescribeStackSet(&cloudformation.DescribeStackSetInput{
StackSetName: aws.String(testName),
}).Return(&cloudformation.DescribeStackSetOutput{
StackSet: &cloudformation.StackSet{
StackSetId: aws.String(testName),
StackSetName: aws.String(testName),
TemplateBody: aws.String("body"),
},
}, nil)
return m
},
wantedDescr: Description{
ID: testName,
Name: testName,
Template: "body",
},
},
"wraps error on unexpected failure": {
mockClient: func(ctrl *gomock.Controller) api {
m := mocks.NewMockapi(ctrl)
m.EXPECT().DescribeStackSet(gomock.Any()).Return(nil, testError)
return m
},
wantedError: fmt.Errorf("describe stack set %s: %w", testName, testError),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
client := StackSet{
client: tc.mockClient(ctrl),
}
// WHEN
descr, err := client.Describe(testName)
// THEN
require.Equal(t, tc.wantedDescr, descr)
require.Equal(t, tc.wantedError, err)
})
}
}
func TestStackSet_DescribeOperation(t *testing.T) {
const testOpID = "1"
testCases := map[string]struct {
mockClient func(ctrl *gomock.Controller) api
wantedOp Operation
wantedError error
}{
"returns the operation description on successful call": {
mockClient: func(ctrl *gomock.Controller) api {
m := mocks.NewMockapi(ctrl)
m.EXPECT().DescribeStackSetOperation(&cloudformation.DescribeStackSetOperationInput{
StackSetName: aws.String(testName),
OperationId: aws.String(testOpID),
}).Return(&cloudformation.DescribeStackSetOperationOutput{
StackSetOperation: &cloudformation.StackSetOperation{
Status: aws.String(cloudformation.StackSetOperationStatusStopped),
StatusReason: aws.String("manually stopped"),
},
}, nil)
return m
},
wantedOp: Operation{
ID: testOpID,
Status: OpStatus(cloudformation.StackSetOperationStatusStopped),
Reason: "manually stopped",
},
},
"wraps error on unexpected failure": {
mockClient: func(ctrl *gomock.Controller) api {
m := mocks.NewMockapi(ctrl)
m.EXPECT().DescribeStackSetOperation(gomock.Any()).Return(nil, testError)
return m
},
wantedError: errors.New("describe operation 1 for stack set stackset: some error"),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
client := StackSet{
client: tc.mockClient(ctrl),
}
// WHEN
op, err := client.DescribeOperation(testName, testOpID)
// THEN
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedOp, op)
}
})
}
}
func TestStackSet_Update(t *testing.T) {
const (
testTemplate = "body"
testDescription = "amazing stack set"
testExecutionRole = "execARN"
testAdministrationRole = "adminARN"
testOperationID = "2"
)
var (
testTags = map[string]string{
"owner": "boss",
}
errOpExists = awserr.New(cloudformation.ErrCodeOperationIdAlreadyExistsException, "", nil)
errOpInProg = awserr.New(cloudformation.ErrCodeOperationInProgressException, "", nil)
errOpStale = awserr.New(cloudformation.ErrCodeStaleRequestException, "", nil)
)
testCases := map[string]struct {
mockClient func(ctrl *gomock.Controller) api
wantedOpID string
wantedError error
}{
"updates stack with operation is valid": {
mockClient: func(ctrl *gomock.Controller) api {
m := mocks.NewMockapi(ctrl)
m.EXPECT().UpdateStackSet(&cloudformation.UpdateStackSetInput{
OperationId: aws.String(testOperationID),
AdministrationRoleARN: aws.String(testAdministrationRole),
Description: aws.String(testDescription),
ExecutionRoleName: aws.String(testExecutionRole),
StackSetName: aws.String(testName),
Tags: []*cloudformation.Tag{
{
Key: aws.String("owner"),
Value: aws.String("boss"),
},
},
OperationPreferences: &cloudformation.StackSetOperationPreferences{
RegionConcurrencyType: aws.String(cloudformation.RegionConcurrencyTypeParallel),
},
TemplateBody: aws.String(testTemplate),
}).Return(&cloudformation.UpdateStackSetOutput{
OperationId: aws.String(testOperationID),
}, nil)
return m
},
wantedOpID: testOperationID,
},
"returns ErrStackSetOutOfDate if operation exists already": {
mockClient: func(ctrl *gomock.Controller) api {
m := mocks.NewMockapi(ctrl)
m.EXPECT().UpdateStackSet(gomock.Any()).Return(nil, errOpExists)
return m
},
wantedError: &ErrStackSetOutOfDate{
name: testName,
parentErr: errOpExists,
},
},
"returns ErrStackSetOutOfDate if operation in progress": {
mockClient: func(ctrl *gomock.Controller) api {
m := mocks.NewMockapi(ctrl)
m.EXPECT().UpdateStackSet(gomock.Any()).Return(nil, errOpInProg)
return m
},
wantedError: &ErrStackSetOutOfDate{
name: testName,
parentErr: errOpInProg,
},
},
"returns ErrStackSetOutOfDate if operation is stale": {
mockClient: func(ctrl *gomock.Controller) api {
m := mocks.NewMockapi(ctrl)
m.EXPECT().UpdateStackSet(gomock.Any()).Return(nil, errOpStale)
return m
},
wantedError: &ErrStackSetOutOfDate{
name: testName,
parentErr: errOpStale,
},
},
"wrap error on unexpected failure": {
mockClient: func(ctrl *gomock.Controller) api {
m := mocks.NewMockapi(ctrl)
m.EXPECT().UpdateStackSet(gomock.Any()).Return(nil, testError)
return m
},
wantedError: fmt.Errorf("update stack set %s: %w", testName, testError),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
client := StackSet{
client: tc.mockClient(ctrl),
}
// WHEN
opID, err := client.Update(testName, testTemplate,
WithOperationID(testOperationID),
WithDescription(testDescription),
WithAdministrationRoleARN(testAdministrationRole),
WithExecutionRoleName(testExecutionRole),
WithTags(testTags))
// THEN
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedOpID, opID)
}
})
}
}
func TestStackSet_UpdateAndWait(t *testing.T) {
const testTemplate = "body"
testCases := map[string]struct {
mockClient func(ctrl *gomock.Controller) api
wantedError error
}{
"waits until operation succeeds": {
mockClient: func(ctrl *gomock.Controller) api {
m := mocks.NewMockapi(ctrl)
m.EXPECT().UpdateStackSet(gomock.Any()).Return(&cloudformation.UpdateStackSetOutput{
OperationId: aws.String("1"),
}, nil)
m.EXPECT().DescribeStackSetOperation(&cloudformation.DescribeStackSetOperationInput{
StackSetName: aws.String(testName),
OperationId: aws.String("1"),
}).Return(&cloudformation.DescribeStackSetOperationOutput{
StackSetOperation: &cloudformation.StackSetOperation{
Status: aws.String(opStatusSucceeded),
},
}, nil)
return m
},
},
"returns a wrapped error if operation stopped": {
mockClient: func(ctrl *gomock.Controller) api {
m := mocks.NewMockapi(ctrl)
m.EXPECT().UpdateStackSet(gomock.Any()).Return(&cloudformation.UpdateStackSetOutput{
OperationId: aws.String("1"),
}, nil)
m.EXPECT().DescribeStackSetOperation(gomock.Any()).Return(&cloudformation.DescribeStackSetOperationOutput{
StackSetOperation: &cloudformation.StackSetOperation{
Status: aws.String(opStatusStopped),
},
}, nil)
return m
},
wantedError: fmt.Errorf("operation %s for stack set %s was manually stopped", "1", testName),
},
"returns a wrapped error if operation failed": {
mockClient: func(ctrl *gomock.Controller) api {
m := mocks.NewMockapi(ctrl)
m.EXPECT().UpdateStackSet(gomock.Any()).Return(&cloudformation.UpdateStackSetOutput{
OperationId: aws.String("1"),
}, nil)
m.EXPECT().DescribeStackSetOperation(gomock.Any()).Return(&cloudformation.DescribeStackSetOperationOutput{
StackSetOperation: &cloudformation.StackSetOperation{
Status: aws.String(opStatusFailed),
},
}, nil)
return m
},
wantedError: fmt.Errorf("operation %s for stack set %s failed", "1", testName),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
client := StackSet{
client: tc.mockClient(ctrl),
}
// WHEN
err := client.UpdateAndWait(testName, testTemplate)
// THEN
require.Equal(t, tc.wantedError, err)
})
}
}
func TestStackSet_WaitForStackSetLastOperationComplete(t *testing.T) {
testCases := map[string]struct {
mockClient func(ctrl *gomock.Controller) api
wantedError error
}{
"waits until operation succeeds": {
mockClient: func(ctrl *gomock.Controller) api {
m := mocks.NewMockapi(ctrl)
m.EXPECT().ListStackSetOperations(&cloudformation.ListStackSetOperationsInput{
StackSetName: aws.String(testName),
}).Return(&cloudformation.ListStackSetOperationsOutput{
Summaries: []*cloudformation.StackSetOperationSummary{
{
Status: aws.String(cloudformation.StackSetOperationStatusRunning),
},
},
}, nil)
m.EXPECT().ListStackSetOperations(&cloudformation.ListStackSetOperationsInput{
StackSetName: aws.String(testName),
}).Return(&cloudformation.ListStackSetOperationsOutput{
Summaries: []*cloudformation.StackSetOperationSummary{
{
Status: aws.String(cloudformation.StackSetOperationStatusSucceeded),
},
},
}, nil)
return m
},
},
"return if no operation": {
mockClient: func(ctrl *gomock.Controller) api {
m := mocks.NewMockapi(ctrl)
m.EXPECT().ListStackSetOperations(&cloudformation.ListStackSetOperationsInput{
StackSetName: aws.String(testName),
}).Return(&cloudformation.ListStackSetOperationsOutput{
Summaries: []*cloudformation.StackSetOperationSummary{},
}, nil)
return m
},
},
"error if fail to list stackset operation": {
mockClient: func(ctrl *gomock.Controller) api {
m := mocks.NewMockapi(ctrl)
m.EXPECT().ListStackSetOperations(&cloudformation.ListStackSetOperationsInput{
StackSetName: aws.String(testName),
}).Return(nil, errors.New("some error"))
return m
},
wantedError: fmt.Errorf("list operations for stack set stackset: some error"),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
client := StackSet{
client: tc.mockClient(ctrl),
}
// WHEN
err := client.WaitForStackSetLastOperationComplete(testName)
// THEN
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
}
})
}
}
func TestStackSet_DeleteAllInstances(t *testing.T) {
testCases := map[string]struct {
mockClient func(t *testing.T, ctrl *gomock.Controller) api
wantedOpID string
wantedError error
}{
"return ErrStackSetNotFound if the stack set does not exist": {
mockClient: func(t *testing.T, ctrl *gomock.Controller) api {
m := mocks.NewMockapi(ctrl)
m.EXPECT().ListStackInstances(gomock.Any()).Return(nil, awserr.New(cloudformation.ErrCodeStackSetNotFoundException, "", nil))
return m
},
wantedError: &ErrStackSetNotFound{name: testName},
},
"returns ErrStackSetInstancesNotFound if there are no stack set instances": {
mockClient: func(t *testing.T, ctrl *gomock.Controller) api {
m := mocks.NewMockapi(ctrl)
m.EXPECT().ListStackInstances(gomock.Any()).Return(&cloudformation.ListStackInstancesOutput{
Summaries: []*cloudformation.StackInstanceSummary{},
}, nil)
return m
},
wantedError: &ErrStackSetInstancesNotFound{name: testName},
},
"successfully deletes stack instances and returns the operation ID": {
mockClient: func(t *testing.T, ctrl *gomock.Controller) api {
m := mocks.NewMockapi(ctrl)
m.EXPECT().ListStackInstances(gomock.Any()).Return(&cloudformation.ListStackInstancesOutput{
Summaries: []*cloudformation.StackInstanceSummary{
{
Account: aws.String("1111"),
Region: aws.String("us-east-1"),
},
{
Account: aws.String("2222"),
Region: aws.String("us-east-1"),
},
{
Account: aws.String("1111"),
Region: aws.String("us-west-2"),
},
},
}, nil)
m.EXPECT().DeleteStackInstances(gomock.Any()).
DoAndReturn(func(in *cloudformation.DeleteStackInstancesInput) (*cloudformation.DeleteStackInstancesOutput, error) {
require.Equal(t, testName, aws.StringValue(in.StackSetName))
require.ElementsMatch(t, []string{"1111", "2222"}, aws.StringValueSlice(in.Accounts))
require.ElementsMatch(t, []string{"us-east-1", "us-west-2"}, aws.StringValueSlice(in.Regions))
require.False(t, aws.BoolValue(in.RetainStacks))
return &cloudformation.DeleteStackInstancesOutput{
OperationId: aws.String("1"),
}, nil
})
return m
},
wantedOpID: "1",
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
client := StackSet{
client: tc.mockClient(t, ctrl),
}
// WHEN
opID, err := client.DeleteAllInstances(testName)
// THEN
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedOpID, opID)
}
})
}
}
func TestStackSet_Delete(t *testing.T) {
testCases := map[string]struct {
mockClient func(ctrl *gomock.Controller) api
wantedError error
}{
"successfully exits if stack set does not exist": {
mockClient: func(ctrl *gomock.Controller) api {
m := mocks.NewMockapi(ctrl)
m.EXPECT().DeleteStackSet(gomock.Any()).Return(nil, awserr.New(cloudformation.ErrCodeStackSetNotFoundException, "", nil))
return m
},
},
"wraps error on unexpected failure": {
mockClient: func(ctrl *gomock.Controller) api {
m := mocks.NewMockapi(ctrl)
m.EXPECT().DeleteStackSet(gomock.Any()).Return(nil, testError)
return m
},
wantedError: fmt.Errorf("delete stack set %s: %w", testName, testError),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
client := StackSet{
client: tc.mockClient(ctrl),
}
// WHEN
err := client.Delete(testName)
// THEN
require.Equal(t, tc.wantedError, err)
})
}
}
func TestStackSet_CreateInstances(t *testing.T) {
var (
testAccounts = []string{"1234"}
testRegions = []string{"us-west-1"}
)
testCases := map[string]struct {
mockClient func(ctrl *gomock.Controller) api
wantedOpID string
wantedError error
}{
"successfully creates stack instances": {
mockClient: func(ctrl *gomock.Controller) api {
m := mocks.NewMockapi(ctrl)
m.EXPECT().CreateStackInstances(&cloudformation.CreateStackInstancesInput{
StackSetName: aws.String(testName),
Accounts: aws.StringSlice(testAccounts),
Regions: aws.StringSlice(testRegions),
}).Return(&cloudformation.CreateStackInstancesOutput{
OperationId: aws.String("1"),
}, nil)
return m
},
wantedOpID: "1",
},
"wraps error on unexpected failure": {
mockClient: func(ctrl *gomock.Controller) api {
m := mocks.NewMockapi(ctrl)
m.EXPECT().CreateStackInstances(gomock.Any()).Return(nil, testError)
return m
},
wantedError: fmt.Errorf("create stack instances for stack set %s in regions %v for accounts %v: %w",
testName,
testRegions,
testAccounts,
testError),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
client := StackSet{
client: tc.mockClient(ctrl),
}
// WHEN
opID, err := client.CreateInstances(testName, testAccounts, testRegions)
// THEN
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedOpID, opID)
}
})
}
}
func TestStackSet_InstanceSummaries(t *testing.T) {
const (
testAccountID = "1234"
testRegion = "us-west-1"
)
testCases := map[string]struct {
mockClient func(ctrl *gomock.Controller) api
wantedSummaries []InstanceSummary
wantedError error
}{
"returns summaries": {
mockClient: func(ctrl *gomock.Controller) api {
m := mocks.NewMockapi(ctrl)
m.EXPECT().ListStackInstances(&cloudformation.ListStackInstancesInput{
StackSetName: aws.String(testName),
StackInstanceAccount: aws.String(testAccountID),
StackInstanceRegion: aws.String(testRegion),
}).Return(&cloudformation.ListStackInstancesOutput{
Summaries: []*cloudformation.StackInstanceSummary{
{
StackId: aws.String(testName),
Account: aws.String(testAccountID),
Region: aws.String(testRegion),
},
},
}, nil)
return m
},
wantedSummaries: []InstanceSummary{
{
StackID: testName,
Account: testAccountID,
Region: testRegion,
},
},
},
"wraps error on unexpected failure": {
mockClient: func(ctrl *gomock.Controller) api {
m := mocks.NewMockapi(ctrl)
m.EXPECT().ListStackInstances(gomock.Any()).Return(nil, testError)
return m
},
wantedError: fmt.Errorf("list stack instances for stack set %s: %w", testName, testError),
},
"keeps iterating until there is no more next token": {
mockClient: func(ctrl *gomock.Controller) api {
m := mocks.NewMockapi(ctrl)
gomock.InOrder(
m.EXPECT().ListStackInstances(&cloudformation.ListStackInstancesInput{
StackSetName: aws.String(testName),
StackInstanceAccount: aws.String(testAccountID),
StackInstanceRegion: aws.String(testRegion),
}).Return(&cloudformation.ListStackInstancesOutput{
Summaries: []*cloudformation.StackInstanceSummary{
{
StackId: aws.String("1111"),
Account: aws.String(testAccountID),
Region: aws.String("us-west-2"),
StackInstanceStatus: &cloudformation.StackInstanceComprehensiveStatus{
DetailedStatus: aws.String(instanceStatusRunning),
},
},
},
NextToken: aws.String("token"),
}, nil),
m.EXPECT().ListStackInstances(&cloudformation.ListStackInstancesInput{
StackSetName: aws.String(testName),
StackInstanceAccount: aws.String(testAccountID),
StackInstanceRegion: aws.String(testRegion),
NextToken: aws.String("token"),
}).Return(&cloudformation.ListStackInstancesOutput{
Summaries: []*cloudformation.StackInstanceSummary{
{
StackId: aws.String("2222"),
Account: aws.String(testAccountID),
Region: aws.String("us-east-1"),
StackInstanceStatus: &cloudformation.StackInstanceComprehensiveStatus{
DetailedStatus: aws.String(instanceStatusSucceeded),
},
},
},
}, nil),
)
return m
},
wantedSummaries: []InstanceSummary{
{
StackID: "1111",
Account: testAccountID,
Region: "us-west-2",
Status: InstanceStatus(instanceStatusRunning),
},
{
StackID: "2222",
Account: testAccountID,
Region: "us-east-1",
Status: InstanceStatus(instanceStatusSucceeded),
},
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
client := StackSet{
client: tc.mockClient(ctrl),
}
// WHEN
summaries, err := client.InstanceSummaries(
testName,
FilterSummariesByAccountID(testAccountID),
FilterSummariesByRegion(testRegion))
// THEN
require.ElementsMatch(t, tc.wantedSummaries, summaries)
require.Equal(t, tc.wantedError, err)
})
}
}
func TestStackSet_WaitForOperation(t *testing.T) {
const (
testName = "demo-infrastructure"
testOpID = "1"
)
testCases := map[string]struct {
mockClient func(ctrl *gomock.Controller) api
wantedErr error
}{
"returns nil if the operation status is successful": {
mockClient: func(ctrl *gomock.Controller) api {
m := mocks.NewMockapi(ctrl)
m.EXPECT().DescribeStackSetOperation(&cloudformation.DescribeStackSetOperationInput{
StackSetName: aws.String(testName),
OperationId: aws.String(testOpID),
}).Return(&cloudformation.DescribeStackSetOperationOutput{
StackSetOperation: &cloudformation.StackSetOperation{
Status: aws.String(cloudformation.StackSetOperationStatusSucceeded),
},
}, nil)
return m
},
},
"returns an error if the operation stopped": {
mockClient: func(ctrl *gomock.Controller) api {
m := mocks.NewMockapi(ctrl)
m.EXPECT().DescribeStackSetOperation(&cloudformation.DescribeStackSetOperationInput{
StackSetName: aws.String(testName),
OperationId: aws.String(testOpID),
}).Return(&cloudformation.DescribeStackSetOperationOutput{
StackSetOperation: &cloudformation.StackSetOperation{
Status: aws.String(cloudformation.StackSetOperationStatusStopped),
},
}, nil)
return m
},
wantedErr: errors.New("operation 1 for stack set demo-infrastructure was manually stopped"),
},
"returns an error if the operation failed": {
mockClient: func(ctrl *gomock.Controller) api {
m := mocks.NewMockapi(ctrl)
m.EXPECT().DescribeStackSetOperation(&cloudformation.DescribeStackSetOperationInput{
StackSetName: aws.String(testName),
OperationId: aws.String(testOpID),
}).Return(&cloudformation.DescribeStackSetOperationOutput{
StackSetOperation: &cloudformation.StackSetOperation{
Status: aws.String(cloudformation.StackSetOperationStatusFailed),
},
}, nil)
return m
},
wantedErr: errors.New("operation 1 for stack set demo-infrastructure failed"),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
client := StackSet{
client: tc.mockClient(ctrl),
}
// WHEN
err := client.WaitForOperation(testName, testOpID)
// THEN
if tc.wantedErr != nil {
require.EqualError(t, err, tc.wantedErr.Error())
} else {
require.NoError(t, err)
}
})
}
}
| 863 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package stackset
import "github.com/aws/aws-sdk-go/service/cloudformation"
const (
opStatusSucceeded = cloudformation.StackSetOperationStatusSucceeded
opStatusStopped = cloudformation.StackSetOperationStatusStopped
opStatusFailed = cloudformation.StackSetOperationStatusFailed
opStatusRunning = cloudformation.StackSetOperationStatusRunning
opStatusStopping = cloudformation.StackSetOperationStatusStopping
opStatusQueued = cloudformation.StackSetOperationStatusQueued
)
const (
instanceStatusPending = cloudformation.StackInstanceDetailedStatusPending
instanceStatusRunning = cloudformation.StackInstanceDetailedStatusRunning
instanceStatusSucceeded = cloudformation.StackInstanceDetailedStatusSucceeded
instanceStatusFailed = cloudformation.StackInstanceDetailedStatusFailed
instanceStatusCancelled = cloudformation.StackInstanceDetailedStatusCancelled
instanceStatusInoperable = cloudformation.StackInstanceDetailedStatusInoperable
)
// OpStatus represents a stack set operation status.
type OpStatus string
// IsCompleted returns true if the operation is in a final state.
func (s OpStatus) IsCompleted() bool {
return s.IsSuccess() || s.IsFailure()
}
// InProgress returns true if the operation has started but hasn't reached a final state yet.
func (s OpStatus) InProgress() bool {
switch s {
case opStatusQueued, opStatusRunning, opStatusStopping:
return true
default:
return false
}
}
// IsSuccess returns true if the operation is completed successfully.
func (s OpStatus) IsSuccess() bool {
return s == opStatusSucceeded
}
// IsFailure returns true if the operation terminated in failure.
func (s OpStatus) IsFailure() bool {
return s == opStatusStopped || s == opStatusFailed
}
// String implements the fmt.Stringer interface.
func (s OpStatus) String() string {
return string(s)
}
// InstanceStatus represents a stack set's instance detailed status.
type InstanceStatus string
// IsCompleted returns true if the operation is in a final state.
func (s InstanceStatus) IsCompleted() bool {
return s.IsSuccess() || s.IsFailure()
}
// InProgress returns true if the instance is being updated with a new template.
func (s InstanceStatus) InProgress() bool {
return s == instanceStatusPending || s == instanceStatusRunning
}
// IsSuccess returns true if the instance is up-to-date with the stack set template.
func (s InstanceStatus) IsSuccess() bool {
return s == instanceStatusSucceeded
}
// IsFailure returns true if the instance cannot be updated and needs to be recovered.
func (s InstanceStatus) IsFailure() bool {
return s == instanceStatusFailed || s == instanceStatusCancelled || s == instanceStatusInoperable
}
// String implements the fmt.Stringer interface.
func (s InstanceStatus) String() string {
return string(s)
}
| 86 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package stackset
import (
"testing"
"github.com/aws/aws-sdk-go/service/cloudformation"
"github.com/stretchr/testify/require"
)
func TestOpStatus_IsCompleted(t *testing.T) {
testCases := map[string]struct {
status string
wanted bool
}{
"false when queued": {
status: cloudformation.StackSetOperationStatusQueued,
},
"false when running": {
status: cloudformation.StackSetOperationStatusRunning,
},
"false when stopping": {
status: cloudformation.StackSetOperationStatusStopping,
},
"true when succeeded": {
status: cloudformation.StackSetOperationStatusSucceeded,
wanted: true,
},
"true when stopped": {
status: cloudformation.StackSetOperationStatusStopped,
wanted: true,
},
"true when failed": {
status: cloudformation.StackSetOperationStatusFailed,
wanted: true,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
require.Equal(t, tc.wanted, OpStatus(tc.status).IsCompleted())
})
}
}
func TestOpStatus_IsSuccess(t *testing.T) {
testCases := map[string]struct {
status string
wanted bool
}{
"false when queued": {
status: cloudformation.StackSetOperationStatusQueued,
},
"false when running": {
status: cloudformation.StackSetOperationStatusRunning,
},
"false when stopping": {
status: cloudformation.StackSetOperationStatusStopping,
},
"true when succeeded": {
status: cloudformation.StackSetOperationStatusSucceeded,
wanted: true,
},
"false when stopped": {
status: cloudformation.StackSetOperationStatusStopped,
},
"false when failed": {
status: cloudformation.StackSetOperationStatusFailed,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
require.Equal(t, tc.wanted, OpStatus(tc.status).IsSuccess())
})
}
}
func TestOpStatus_InProgress(t *testing.T) {
testCases := map[string]struct {
status string
wanted bool
}{
"true when queued": {
status: cloudformation.StackSetOperationStatusQueued,
wanted: true,
},
"true when running": {
status: cloudformation.StackSetOperationStatusRunning,
wanted: true,
},
"true when stopping": {
status: cloudformation.StackSetOperationStatusStopping,
wanted: true,
},
"false when succeeded": {
status: cloudformation.StackSetOperationStatusSucceeded,
},
"false when stopped": {
status: cloudformation.StackSetOperationStatusStopped,
},
"false when failed": {
status: cloudformation.StackSetOperationStatusFailed,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
require.Equal(t, tc.wanted, OpStatus(tc.status).InProgress())
})
}
}
func TestOpStatus_IsFailure(t *testing.T) {
testCases := map[string]struct {
status string
wanted bool
}{
"false when queued": {
status: cloudformation.StackSetOperationStatusQueued,
},
"false when running": {
status: cloudformation.StackSetOperationStatusRunning,
},
"false when stopping": {
status: cloudformation.StackSetOperationStatusStopping,
},
"false when succeeded": {
status: cloudformation.StackSetOperationStatusSucceeded,
},
"true when stopped": {
status: cloudformation.StackSetOperationStatusStopped,
wanted: true,
},
"true when failed": {
status: cloudformation.StackSetOperationStatusFailed,
wanted: true,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
require.Equal(t, tc.wanted, OpStatus(tc.status).IsFailure())
})
}
}
func TestOpStatus_String(t *testing.T) {
var s OpStatus = "hello"
require.Equal(t, "hello", s.String())
}
func TestInstanceStatus_IsCompleted(t *testing.T) {
testCases := map[string]struct {
status string
wanted bool
}{
"false when pending": {
status: cloudformation.StackInstanceDetailedStatusPending,
},
"false when running": {
status: cloudformation.StackInstanceDetailedStatusRunning,
},
"true when succeeded": {
status: cloudformation.StackInstanceDetailedStatusSucceeded,
wanted: true,
},
"true when failed": {
status: cloudformation.StackInstanceDetailedStatusFailed,
wanted: true,
},
"true when cancelled": {
status: cloudformation.StackInstanceDetailedStatusCancelled,
wanted: true,
},
"true when inoperable": {
status: cloudformation.StackInstanceDetailedStatusInoperable,
wanted: true,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
require.Equal(t, tc.wanted, InstanceStatus(tc.status).IsCompleted())
})
}
}
func TestInstanceStatus_InProgress(t *testing.T) {
testCases := map[string]struct {
status string
wanted bool
}{
"true when pending": {
status: cloudformation.StackInstanceDetailedStatusPending,
wanted: true,
},
"true when running": {
status: cloudformation.StackInstanceDetailedStatusRunning,
wanted: true,
},
"false when succeeded": {
status: cloudformation.StackInstanceDetailedStatusSucceeded,
},
"false when failed": {
status: cloudformation.StackInstanceDetailedStatusFailed,
},
"false when cancelled": {
status: cloudformation.StackInstanceDetailedStatusCancelled,
},
"false when inoperable": {
status: cloudformation.StackInstanceDetailedStatusInoperable,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
require.Equal(t, tc.wanted, InstanceStatus(tc.status).InProgress())
})
}
}
func TestInstanceStatus_IsSuccess(t *testing.T) {
testCases := map[string]struct {
status string
wanted bool
}{
"false when pending": {
status: cloudformation.StackInstanceDetailedStatusPending,
},
"false when running": {
status: cloudformation.StackInstanceDetailedStatusRunning,
},
"true when succeeded": {
status: cloudformation.StackInstanceDetailedStatusSucceeded,
wanted: true,
},
"false when failed": {
status: cloudformation.StackInstanceDetailedStatusFailed,
},
"false when cancelled": {
status: cloudformation.StackInstanceDetailedStatusCancelled,
},
"false when inoperable": {
status: cloudformation.StackInstanceDetailedStatusInoperable,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
require.Equal(t, tc.wanted, InstanceStatus(tc.status).IsSuccess())
})
}
}
func TestInstanceStatus_IsFailure(t *testing.T) {
testCases := map[string]struct {
status string
wanted bool
}{
"false when pending": {
status: cloudformation.StackInstanceDetailedStatusPending,
},
"false when running": {
status: cloudformation.StackInstanceDetailedStatusRunning,
},
"false when succeeded": {
status: cloudformation.StackInstanceDetailedStatusSucceeded,
},
"true when failed": {
status: cloudformation.StackInstanceDetailedStatusFailed,
wanted: true,
},
"true when cancelled": {
status: cloudformation.StackInstanceDetailedStatusCancelled,
wanted: true,
},
"true when inoperable": {
status: cloudformation.StackInstanceDetailedStatusInoperable,
wanted: true,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
require.Equal(t, tc.wanted, InstanceStatus(tc.status).IsFailure())
})
}
}
func TestInstanceStatus_String(t *testing.T) {
var s InstanceStatus = "hello"
require.Equal(t, "hello", s.String())
}
| 297 |
copilot-cli | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: ./internal/pkg/aws/cloudformation/stackset/stackset.go
// Package mocks is a generated GoMock package.
package mocks
import (
reflect "reflect"
cloudformation "github.com/aws/aws-sdk-go/service/cloudformation"
gomock "github.com/golang/mock/gomock"
)
// Mockapi is a mock of api interface.
type Mockapi struct {
ctrl *gomock.Controller
recorder *MockapiMockRecorder
}
// MockapiMockRecorder is the mock recorder for Mockapi.
type MockapiMockRecorder struct {
mock *Mockapi
}
// NewMockapi creates a new mock instance.
func NewMockapi(ctrl *gomock.Controller) *Mockapi {
mock := &Mockapi{ctrl: ctrl}
mock.recorder = &MockapiMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *Mockapi) EXPECT() *MockapiMockRecorder {
return m.recorder
}
// CreateStackInstances mocks base method.
func (m *Mockapi) CreateStackInstances(arg0 *cloudformation.CreateStackInstancesInput) (*cloudformation.CreateStackInstancesOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CreateStackInstances", arg0)
ret0, _ := ret[0].(*cloudformation.CreateStackInstancesOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// CreateStackInstances indicates an expected call of CreateStackInstances.
func (mr *MockapiMockRecorder) CreateStackInstances(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateStackInstances", reflect.TypeOf((*Mockapi)(nil).CreateStackInstances), arg0)
}
// CreateStackSet mocks base method.
func (m *Mockapi) CreateStackSet(arg0 *cloudformation.CreateStackSetInput) (*cloudformation.CreateStackSetOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CreateStackSet", arg0)
ret0, _ := ret[0].(*cloudformation.CreateStackSetOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// CreateStackSet indicates an expected call of CreateStackSet.
func (mr *MockapiMockRecorder) CreateStackSet(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateStackSet", reflect.TypeOf((*Mockapi)(nil).CreateStackSet), arg0)
}
// DeleteStackInstances mocks base method.
func (m *Mockapi) DeleteStackInstances(arg0 *cloudformation.DeleteStackInstancesInput) (*cloudformation.DeleteStackInstancesOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DeleteStackInstances", arg0)
ret0, _ := ret[0].(*cloudformation.DeleteStackInstancesOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DeleteStackInstances indicates an expected call of DeleteStackInstances.
func (mr *MockapiMockRecorder) DeleteStackInstances(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteStackInstances", reflect.TypeOf((*Mockapi)(nil).DeleteStackInstances), arg0)
}
// DeleteStackSet mocks base method.
func (m *Mockapi) DeleteStackSet(arg0 *cloudformation.DeleteStackSetInput) (*cloudformation.DeleteStackSetOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DeleteStackSet", arg0)
ret0, _ := ret[0].(*cloudformation.DeleteStackSetOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DeleteStackSet indicates an expected call of DeleteStackSet.
func (mr *MockapiMockRecorder) DeleteStackSet(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteStackSet", reflect.TypeOf((*Mockapi)(nil).DeleteStackSet), arg0)
}
// DescribeStackSet mocks base method.
func (m *Mockapi) DescribeStackSet(arg0 *cloudformation.DescribeStackSetInput) (*cloudformation.DescribeStackSetOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DescribeStackSet", arg0)
ret0, _ := ret[0].(*cloudformation.DescribeStackSetOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DescribeStackSet indicates an expected call of DescribeStackSet.
func (mr *MockapiMockRecorder) DescribeStackSet(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeStackSet", reflect.TypeOf((*Mockapi)(nil).DescribeStackSet), arg0)
}
// DescribeStackSetOperation mocks base method.
func (m *Mockapi) DescribeStackSetOperation(arg0 *cloudformation.DescribeStackSetOperationInput) (*cloudformation.DescribeStackSetOperationOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DescribeStackSetOperation", arg0)
ret0, _ := ret[0].(*cloudformation.DescribeStackSetOperationOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DescribeStackSetOperation indicates an expected call of DescribeStackSetOperation.
func (mr *MockapiMockRecorder) DescribeStackSetOperation(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeStackSetOperation", reflect.TypeOf((*Mockapi)(nil).DescribeStackSetOperation), arg0)
}
// ListStackInstances mocks base method.
func (m *Mockapi) ListStackInstances(arg0 *cloudformation.ListStackInstancesInput) (*cloudformation.ListStackInstancesOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListStackInstances", arg0)
ret0, _ := ret[0].(*cloudformation.ListStackInstancesOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ListStackInstances indicates an expected call of ListStackInstances.
func (mr *MockapiMockRecorder) ListStackInstances(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListStackInstances", reflect.TypeOf((*Mockapi)(nil).ListStackInstances), arg0)
}
// ListStackSetOperations mocks base method.
func (m *Mockapi) ListStackSetOperations(input *cloudformation.ListStackSetOperationsInput) (*cloudformation.ListStackSetOperationsOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListStackSetOperations", input)
ret0, _ := ret[0].(*cloudformation.ListStackSetOperationsOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ListStackSetOperations indicates an expected call of ListStackSetOperations.
func (mr *MockapiMockRecorder) ListStackSetOperations(input interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListStackSetOperations", reflect.TypeOf((*Mockapi)(nil).ListStackSetOperations), input)
}
// UpdateStackSet mocks base method.
func (m *Mockapi) UpdateStackSet(arg0 *cloudformation.UpdateStackSetInput) (*cloudformation.UpdateStackSetOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "UpdateStackSet", arg0)
ret0, _ := ret[0].(*cloudformation.UpdateStackSetOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// UpdateStackSet indicates an expected call of UpdateStackSet.
func (mr *MockapiMockRecorder) UpdateStackSet(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateStackSet", reflect.TypeOf((*Mockapi)(nil).UpdateStackSet), arg0)
}
| 171 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package cloudfront
const (
// CertRegion is the only AWS region accepted by CloudFront while attaching certificates to a distribution.
CertRegion = "us-east-1"
// S3BucketOriginDomainFormat is the Regex validation format for S3 bucket as CloudFront origin domain
// See https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesDomainName
S3BucketOriginDomainFormat = `.+\.s3.*\.\w+-\w+-\d+\.amazonaws\.com`
)
| 13 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package cloudwatch
import (
"fmt"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/cloudwatch"
)
const (
anomalyDetectionBandExpression = "ANOMALY_DETECTION_BAND"
// {metricTitle} {breachingRelationship} {threshold} for {datapointsCount} datapoints within {duration}
fmtStaticMetricCondition = "%s %s %.2f for %d datapoints within %s"
)
type alarmThresholdTypes int
const (
predictive alarmThresholdTypes = iota
dynamic
static
)
type comparisonOperator string
func (c comparisonOperator) humanString() string {
switch c {
case cloudwatch.ComparisonOperatorGreaterThanOrEqualToThreshold:
return "≥"
case cloudwatch.ComparisonOperatorGreaterThanThreshold:
return ">"
case cloudwatch.ComparisonOperatorLessThanThreshold:
return "<"
case cloudwatch.ComparisonOperatorLessThanOrEqualToThreshold:
return "≤"
case cloudwatch.ComparisonOperatorLessThanLowerOrGreaterThanUpperThreshold:
return "outside"
case cloudwatch.ComparisonOperatorLessThanLowerThreshold:
return "<"
case cloudwatch.ComparisonOperatorGreaterThanUpperThreshold:
return ">"
default:
return ""
}
}
type metricAlarm cloudwatch.MetricAlarm
func (a metricAlarm) condition() string {
thresholdType := a.alarmThresholdType()
metricName := aws.StringValue(a.MetricName)
period := aws.Int64Value(a.Period)
evaluationPeriod := aws.Int64Value(a.EvaluationPeriods)
datapointsToAlarm := aws.Int64Value(a.DatapointsToAlarm)
if datapointsToAlarm == 0 {
// https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-alarm.html#cfn-cloudwatch-alarm-datapointstoalarm
datapointsToAlarm = evaluationPeriod
}
operator := comparisonOperator(aws.StringValue(a.ComparisonOperator))
switch thresholdType {
case static:
return fmt.Sprintf(fmtStaticMetricCondition, metricName, operator.humanString(),
aws.Float64Value(a.Threshold), datapointsToAlarm, humanizePeriod(evaluationPeriod, period))
default:
return "-"
}
}
func (a metricAlarm) alarmThresholdType() alarmThresholdTypes {
if a.ThresholdMetricId == nil || len(a.Metrics) < 2 {
return static
}
thresholdMetric := a.thresholdMetric()
if thresholdMetric != nil {
if strings.HasPrefix(aws.StringValue(thresholdMetric.Expression), anomalyDetectionBandExpression) {
return predictive
}
}
return dynamic
}
func (a metricAlarm) thresholdMetric() *cloudwatch.MetricDataQuery {
if a.ThresholdMetricId == nil {
return nil
}
for _, m := range a.Metrics {
if aws.StringValue(m.Id) == aws.StringValue(a.ThresholdMetricId) {
return m
}
}
return nil
}
func humanizePeriod(evaluationPeriod, period int64) string {
durationPeriod := time.Duration(evaluationPeriod*period) * time.Second
return strings.TrimSpace(humanizeDuration(time.Now(), time.Now().Add(durationPeriod), "", ""))
}
| 103 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package cloudwatch provides a client to make API requests to Amazon CloudWatch Service.
package cloudwatch
import (
"fmt"
"strings"
"time"
rg "github.com/aws/copilot-cli/internal/pkg/aws/resourcegroups"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/arn"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatch"
"github.com/dustin/go-humanize"
)
const (
cloudwatchResourceType = "cloudwatch:alarm"
compositeAlarmType = "Composite"
metricAlarmType = "Metric"
)
// humanizeDuration is overridden in tests so that its output is constant as time passes.
var humanizeDuration = humanize.RelTime
type api interface {
DescribeAlarms(input *cloudwatch.DescribeAlarmsInput) (*cloudwatch.DescribeAlarmsOutput, error)
}
type resourceGetter interface {
GetResourcesByTags(resourceType string, tags map[string]string) ([]*rg.Resource, error)
}
// CloudWatch wraps an Amazon CloudWatch client.
type CloudWatch struct {
client api
rgClient resourceGetter
}
// AlarmStatus contains CloudWatch alarm status.
type AlarmStatus struct {
Arn string `json:"arn"`
Name string `json:"name"`
Condition string `json:"condition"`
Status string `json:"status"`
Type string `json:"type"`
UpdatedTimes time.Time `json:"updatedTimes"`
}
// AlarmDescription contains CloudWatch alarm config.
// Also available: MetricName, ComparisonOperator, DatapointsToAlarm, EvaluationPeriods, Threshold, Unit.
type AlarmDescription struct {
Name string `json:"name"`
Description string `json:"description"`
Environment string `json:"environment"`
}
// New returns a CloudWatch struct configured against the input session.
func New(s *session.Session) *CloudWatch {
return &CloudWatch{
client: cloudwatch.New(s),
rgClient: rg.New(s),
}
}
// AlarmsWithTags returns the statuses of all the CloudWatch alarms that have the resource tags.
func (cw *CloudWatch) AlarmsWithTags(tags map[string]string) ([]AlarmStatus, error) {
var alarmNames []string
resources, err := cw.rgClient.GetResourcesByTags(cloudwatchResourceType, tags)
if err != nil {
return nil, err
}
for _, resource := range resources {
name, err := getAlarmName(resource.ARN)
if err != nil {
return nil, err
}
alarmNames = append(alarmNames, name)
}
if len(alarmNames) == 0 {
return nil, nil
}
return cw.AlarmStatuses(WithNames(alarmNames))
}
// DescribeAlarmOpts sets the optional parameter for DescribeAlarms
type DescribeAlarmOpts func(input *cloudwatch.DescribeAlarmsInput)
// WithNames sets DescribeAlarms to filter on alarm names.
func WithNames(names []string) DescribeAlarmOpts {
return func(in *cloudwatch.DescribeAlarmsInput) {
in.AlarmNames = aws.StringSlice(names)
}
}
// WithPrefix sets DescribeAlarms to filter on a name prefix.
func WithPrefix(prefix string) DescribeAlarmOpts {
return func(in *cloudwatch.DescribeAlarmsInput) {
in.AlarmNamePrefix = aws.String(prefix)
}
}
// AlarmStatuses returns the statuses of alarms optionally filtered (by name, prefix, etc.).
// If the optional parameter is passed in but is nil, the statuses of ALL alarms in the
// account will be returned!
func (cw *CloudWatch) AlarmStatuses(opts ...DescribeAlarmOpts) ([]AlarmStatus, error) {
var alarmStatuses []AlarmStatus
in := &cloudwatch.DescribeAlarmsInput{}
if len(opts) > 0 {
for _, opt := range opts {
opt(in)
}
}
for {
alarmResp, err := cw.client.DescribeAlarms(in)
if err != nil {
return nil, fmt.Errorf("describe CloudWatch alarms: %w", err)
}
if alarmResp == nil {
break
}
alarmStatuses = append(alarmStatuses, cw.compositeAlarmsStatus(alarmResp.CompositeAlarms)...)
alarmStatuses = append(alarmStatuses, cw.metricAlarmsStatus(alarmResp.MetricAlarms)...)
if alarmResp.NextToken == nil {
break
}
in.NextToken = alarmResp.NextToken
}
return alarmStatuses, nil
}
// AlarmDescriptions returns the config of alarms filtered by name.
func (cw *CloudWatch) AlarmDescriptions(alarmNames []string) ([]*AlarmDescription, error) {
if len(alarmNames) == 0 {
return nil, nil
}
var alarmDescriptions []*AlarmDescription
in := &cloudwatch.DescribeAlarmsInput{
AlarmNames: aws.StringSlice(alarmNames),
}
for {
alarmResp, err := cw.client.DescribeAlarms(in)
if err != nil {
return nil, fmt.Errorf("describe CloudWatch alarms: %w", err)
}
if alarmResp == nil {
break
}
alarmDescriptions = append(alarmDescriptions, cw.compositeAlarmsDescriptions(alarmResp.CompositeAlarms)...)
alarmDescriptions = append(alarmDescriptions, cw.metricAlarmsDescriptions(alarmResp.MetricAlarms)...)
if alarmResp.NextToken == nil {
break
}
in.NextToken = alarmResp.NextToken
}
return alarmDescriptions, nil
}
func (cw *CloudWatch) compositeAlarmsDescriptions(alarms []*cloudwatch.CompositeAlarm) []*AlarmDescription {
var alarmDescriptionList []*AlarmDescription
for _, alarm := range alarms {
if alarm == nil {
continue
}
alarmDescriptionList = append(alarmDescriptionList, &AlarmDescription{
Name: aws.StringValue(alarm.AlarmName),
Description: aws.StringValue(alarm.AlarmDescription),
})
}
return alarmDescriptionList
}
func (cw *CloudWatch) metricAlarmsDescriptions(alarms []*cloudwatch.MetricAlarm) []*AlarmDescription {
var alarmDescriptionsList []*AlarmDescription
for _, alarm := range alarms {
if alarm == nil {
continue
}
alarmDescriptionsList = append(alarmDescriptionsList, &AlarmDescription{
Name: aws.StringValue(alarm.AlarmName),
Description: aws.StringValue(alarm.AlarmDescription),
})
}
return alarmDescriptionsList
}
func (cw *CloudWatch) compositeAlarmsStatus(alarms []*cloudwatch.CompositeAlarm) []AlarmStatus {
var alarmStatusList []AlarmStatus
for _, alarm := range alarms {
if alarm == nil {
continue
}
alarmStatusList = append(alarmStatusList, AlarmStatus{
Arn: aws.StringValue(alarm.AlarmArn),
Name: aws.StringValue(alarm.AlarmName),
Condition: aws.StringValue(alarm.AlarmRule),
Status: aws.StringValue(alarm.StateValue),
Type: compositeAlarmType,
UpdatedTimes: *alarm.StateUpdatedTimestamp,
})
}
return alarmStatusList
}
func (cw *CloudWatch) metricAlarmsStatus(alarms []*cloudwatch.MetricAlarm) []AlarmStatus {
var alarmStatusList []AlarmStatus
for _, alarm := range alarms {
if alarm == nil {
continue
}
metricAlarm := metricAlarm(*alarm)
alarmStatusList = append(alarmStatusList, AlarmStatus{
Arn: aws.StringValue(metricAlarm.AlarmArn),
Name: aws.StringValue(metricAlarm.AlarmName),
Condition: metricAlarm.condition(),
Status: aws.StringValue(metricAlarm.StateValue),
Type: metricAlarmType,
UpdatedTimes: *metricAlarm.StateUpdatedTimestamp,
})
}
return alarmStatusList
}
// getAlarmName gets the alarm name given a specific alarm ARN.
// For example: arn:aws:cloudwatch:us-west-2:1234567890:alarm:SDc-ReadCapacityUnitsLimit-BasicAlarm
// returns SDc-ReadCapacityUnitsLimit-BasicAlarm
func getAlarmName(alarmARN string) (string, error) {
resp, err := arn.Parse(alarmARN)
if err != nil {
return "", fmt.Errorf("parse alarm ARN %s: %w", alarmARN, err)
}
alarmNameList := strings.Split(resp.Resource, ":")
if len(alarmNameList) != 2 {
return "", fmt.Errorf("unknown ARN resource format %s", resp.Resource)
}
return alarmNameList[1], nil
}
| 242 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package cloudwatch
import (
"errors"
"fmt"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/cloudwatch"
"github.com/aws/copilot-cli/internal/pkg/aws/cloudwatch/mocks"
rg "github.com/aws/copilot-cli/internal/pkg/aws/resourcegroups"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
type cloudWatchMocks struct {
cw *mocks.Mockapi
rg *mocks.MockresourceGetter
}
func TestCloudWatch_AlarmsWithTags(t *testing.T) {
const (
appName = "mockApp"
mockAlarmArn = "arn:aws:cloudwatch:us-west-2:1234567890:alarm:mockAlarmName"
)
mockError := errors.New("some error")
mockTime, _ := time.Parse(time.RFC3339, "2006-01-02T15:04:05+00:00")
testTags := map[string]string{
"copilot-application": appName,
}
testCases := map[string]struct {
setupMocks func(m cloudWatchMocks)
wantErr error
wantAlarmStatus []AlarmStatus
}{
"errors if failed to search resources": {
setupMocks: func(m cloudWatchMocks) {
m.rg.EXPECT().GetResourcesByTags(cloudwatchResourceType, gomock.Eq(testTags)).Return(nil, mockError)
},
wantErr: mockError,
},
"errors if failed to get alarm names because of invalid ARN": {
setupMocks: func(m cloudWatchMocks) {
m.rg.EXPECT().GetResourcesByTags(cloudwatchResourceType, gomock.Eq(testTags)).Return([]*rg.Resource{{ARN: "badArn"}}, nil)
},
wantErr: fmt.Errorf("parse alarm ARN badArn: arn: invalid prefix"),
},
"errors if failed to get alarm names because of bad ARN resource": {
setupMocks: func(m cloudWatchMocks) {
m.rg.EXPECT().GetResourcesByTags(cloudwatchResourceType, gomock.Eq(testTags)).Return([]*rg.Resource{{ARN: "arn:aws:cloudwatch:us-west-2:1234567890:alarm:badAlarm:Names"}}, nil)
},
wantErr: fmt.Errorf("unknown ARN resource format alarm:badAlarm:Names"),
},
"errors if failed to describe CloudWatch alarms": {
setupMocks: func(m cloudWatchMocks) {
gomock.InOrder(
m.rg.EXPECT().GetResourcesByTags(cloudwatchResourceType, gomock.Eq(testTags)).Return([]*rg.Resource{{ARN: mockAlarmArn}}, nil),
m.cw.EXPECT().DescribeAlarms(&cloudwatch.DescribeAlarmsInput{
AlarmNames: aws.StringSlice([]string{"mockAlarmName"}),
}).Return(nil, mockError),
)
},
wantErr: fmt.Errorf("describe CloudWatch alarms: some error"),
},
"return if no alarms found": {
setupMocks: func(m cloudWatchMocks) {
m.rg.EXPECT().GetResourcesByTags(cloudwatchResourceType, gomock.Eq(testTags)).Return([]*rg.Resource{}, nil)
},
wantAlarmStatus: nil,
},
"should invoke DescribeAlarms on alarms that have matching tags": {
setupMocks: func(m cloudWatchMocks) {
gomock.InOrder(
m.rg.EXPECT().GetResourcesByTags(cloudwatchResourceType, gomock.Eq(testTags)).Return([]*rg.Resource{{ARN: mockAlarmArn}}, nil),
m.cw.EXPECT().DescribeAlarms(&cloudwatch.DescribeAlarmsInput{
AlarmNames: aws.StringSlice([]string{"mockAlarmName"}),
}).Return(&cloudwatch.DescribeAlarmsOutput{
MetricAlarms: []*cloudwatch.MetricAlarm{
{
AlarmArn: aws.String(mockAlarmArn),
AlarmName: aws.String("mockAlarmName"),
ComparisonOperator: aws.String(cloudwatch.ComparisonOperatorGreaterThanOrEqualToThreshold),
EvaluationPeriods: aws.Int64(int64(300)),
Period: aws.Int64(int64(5)),
Threshold: aws.Float64(float64(70)),
MetricName: aws.String("mockMetricName"),
StateValue: aws.String("mockState"),
StateUpdatedTimestamp: &mockTime,
},
},
CompositeAlarms: nil,
}, nil))
},
wantAlarmStatus: []AlarmStatus{
{
Arn: mockAlarmArn,
Name: "mockAlarmName",
Type: "Metric",
Condition: "mockMetricName ≥ 70.00 for 300 datapoints within 25 minutes",
Status: "mockState",
UpdatedTimes: mockTime,
}},
}}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockcwClient := mocks.NewMockapi(ctrl)
mockrgClient := mocks.NewMockresourceGetter(ctrl)
mocks := cloudWatchMocks{
cw: mockcwClient,
rg: mockrgClient,
}
tc.setupMocks(mocks)
cwSvc := CloudWatch{
client: mockcwClient,
rgClient: mockrgClient,
}
gotAlarmStatus, gotErr := cwSvc.AlarmsWithTags(testTags)
if gotErr != nil {
require.EqualError(t, tc.wantErr, gotErr.Error())
} else {
require.Equal(t, tc.wantAlarmStatus, gotAlarmStatus)
}
})
}
}
func TestCloudWatch_AlarmStatuses(t *testing.T) {
const (
mockPrefix = "some-prefix"
mockName = "mock-alarm-name"
mockAlarmArn = "arn:aws:cloudwatch:us-west-2:1234567890:alarm:mockAlarmName"
mockArn1 = mockAlarmArn + "1"
mockArn2 = mockAlarmArn + "2"
)
mockError := errors.New("some error")
mockTime, _ := time.Parse(time.RFC3339, "2006-01-02T15:04:05+00:00")
testCases := map[string]struct {
setupMocks func(m cloudWatchMocks)
in DescribeAlarmOpts
wantedErr error
wantedAlarmStatuses []AlarmStatus
}{
"errors if fail to describe alarms": {
in: WithPrefix(mockPrefix),
setupMocks: func(m cloudWatchMocks) {
m.cw.EXPECT().DescribeAlarms(&cloudwatch.DescribeAlarmsInput{
AlarmNamePrefix: aws.String(mockPrefix),
}).Return(nil, mockError)
},
wantedErr: errors.New("describe CloudWatch alarms: some error"),
},
"return if no alarms with prefix found": {
in: WithPrefix(mockPrefix),
setupMocks: func(m cloudWatchMocks) {
m.cw.EXPECT().DescribeAlarms(&cloudwatch.DescribeAlarmsInput{
AlarmNamePrefix: aws.String(mockPrefix),
}).Return(nil, nil)
},
},
"success with prefix": {
in: WithPrefix(mockPrefix),
setupMocks: func(m cloudWatchMocks) {
m.cw.EXPECT().DescribeAlarms(&cloudwatch.DescribeAlarmsInput{
AlarmNamePrefix: aws.String(mockPrefix),
}).Return(&cloudwatch.DescribeAlarmsOutput{
MetricAlarms: []*cloudwatch.MetricAlarm{
{
AlarmArn: aws.String(mockAlarmArn),
AlarmName: aws.String(mockName),
ComparisonOperator: aws.String(cloudwatch.ComparisonOperatorGreaterThanOrEqualToThreshold),
EvaluationPeriods: aws.Int64(int64(300)),
Period: aws.Int64(int64(5)),
Threshold: aws.Float64(float64(70)),
MetricName: aws.String("mockMetricName"),
StateValue: aws.String("mockState"),
StateUpdatedTimestamp: &mockTime,
},
},
CompositeAlarms: nil,
}, nil)
},
wantedAlarmStatuses: []AlarmStatus{
{
Arn: mockAlarmArn,
Name: mockName,
Type: "Metric",
Condition: "mockMetricName ≥ 70.00 for 300 datapoints within 25 minutes",
Status: "mockState",
UpdatedTimes: mockTime,
}},
},
"success with static metric": {
in: WithNames([]string{mockName}),
setupMocks: func(m cloudWatchMocks) {
gomock.InOrder(
m.cw.EXPECT().DescribeAlarms(&cloudwatch.DescribeAlarmsInput{
AlarmNames: aws.StringSlice([]string{mockName}),
}).Return(&cloudwatch.DescribeAlarmsOutput{
MetricAlarms: []*cloudwatch.MetricAlarm{
{
AlarmArn: aws.String(mockAlarmArn),
AlarmName: aws.String(mockName),
ComparisonOperator: aws.String(cloudwatch.ComparisonOperatorGreaterThanOrEqualToThreshold),
EvaluationPeriods: aws.Int64(int64(300)),
Period: aws.Int64(int64(5)),
Threshold: aws.Float64(float64(70)),
MetricName: aws.String("mockMetricName"),
StateValue: aws.String("mockState"),
StateUpdatedTimestamp: &mockTime,
},
},
}, nil),
)
},
wantedAlarmStatuses: []AlarmStatus{
{
Arn: mockAlarmArn,
Name: mockName,
Type: "Metric",
Condition: "mockMetricName ≥ 70.00 for 300 datapoints within 25 minutes",
Status: "mockState",
UpdatedTimes: mockTime,
},
},
},
"success with predictive metric": {
in: WithNames([]string{mockName}),
setupMocks: func(m cloudWatchMocks) {
gomock.InOrder(
m.cw.EXPECT().DescribeAlarms(&cloudwatch.DescribeAlarmsInput{
AlarmNames: aws.StringSlice([]string{mockName}),
}).Return(&cloudwatch.DescribeAlarmsOutput{
MetricAlarms: []*cloudwatch.MetricAlarm{
{
AlarmArn: aws.String(mockArn1),
AlarmName: aws.String(mockName),
ComparisonOperator: aws.String(cloudwatch.ComparisonOperatorLessThanLowerOrGreaterThanUpperThreshold),
Metrics: []*cloudwatch.MetricDataQuery{
{
Id: aws.String("m1"),
MetricStat: &cloudwatch.MetricStat{
Period: aws.Int64(120),
Metric: &cloudwatch.Metric{
MetricName: aws.String("mockMetricName"),
},
},
ReturnData: aws.Bool(true),
},
{
Id: aws.String("m2"),
Expression: aws.String("ANOMALY_DETECTION_BAND(m1, 2)"),
ReturnData: aws.Bool(true),
},
},
ThresholdMetricId: aws.String("m2"),
StateValue: aws.String("mockState"),
StateUpdatedTimestamp: &mockTime,
},
},
}, nil),
)
},
wantedAlarmStatuses: []AlarmStatus{
{
Arn: mockArn1,
Name: mockName,
Type: "Metric",
Condition: "-",
Status: "mockState",
UpdatedTimes: mockTime,
},
},
},
"success with predictive or dynamic metrics": {
in: WithNames([]string{mockName}),
setupMocks: func(m cloudWatchMocks) {
gomock.InOrder(
m.cw.EXPECT().DescribeAlarms(&cloudwatch.DescribeAlarmsInput{
AlarmNames: aws.StringSlice([]string{mockName}),
}).Return(&cloudwatch.DescribeAlarmsOutput{
MetricAlarms: []*cloudwatch.MetricAlarm{
{
AlarmArn: aws.String(mockArn1),
AlarmName: aws.String(mockName),
ComparisonOperator: aws.String(cloudwatch.ComparisonOperatorGreaterThanUpperThreshold),
Metrics: []*cloudwatch.MetricDataQuery{
{
Id: aws.String("m1"),
MetricStat: &cloudwatch.MetricStat{
Period: aws.Int64(120),
Metric: &cloudwatch.Metric{
MetricName: aws.String("mockMetricName1"),
},
},
ReturnData: aws.Bool(true),
},
{
Id: aws.String("m2"),
Expression: aws.String("mockExpression"),
ReturnData: aws.Bool(true),
},
},
ThresholdMetricId: aws.String("m2"),
StateValue: aws.String("mockState"),
StateUpdatedTimestamp: &mockTime,
},
{
AlarmArn: aws.String(mockArn2),
AlarmName: aws.String("mockAlarmName2"),
ComparisonOperator: aws.String(cloudwatch.ComparisonOperatorGreaterThanThreshold),
Metrics: []*cloudwatch.MetricDataQuery{
{
Id: aws.String("m1"),
MetricStat: &cloudwatch.MetricStat{
Period: aws.Int64(120),
Metric: &cloudwatch.Metric{
MetricName: aws.String("mockMetricName2"),
},
},
ReturnData: aws.Bool(true),
},
{
Id: aws.String("m2"),
Expression: aws.String("mockExpression"),
ReturnData: aws.Bool(true),
},
},
ThresholdMetricId: aws.String("m2"),
StateValue: aws.String("mockState"),
StateUpdatedTimestamp: &mockTime,
},
},
}, nil),
)
},
wantedAlarmStatuses: []AlarmStatus{
{
Arn: mockArn1,
Name: mockName,
Type: "Metric",
Condition: "-",
Status: "mockState",
UpdatedTimes: mockTime,
},
{
Arn: mockArn2,
Name: "mockAlarmName2",
Type: "Metric",
Condition: "-",
Status: "mockState",
UpdatedTimes: mockTime,
},
},
},
"success with pagination": {
in: WithNames([]string{"mockAlarmName1", "mockAlarmName2"}),
setupMocks: func(m cloudWatchMocks) {
gomock.InOrder(
m.cw.EXPECT().DescribeAlarms(&cloudwatch.DescribeAlarmsInput{
AlarmNames: aws.StringSlice([]string{"mockAlarmName1", "mockAlarmName2"}),
}).Return(&cloudwatch.DescribeAlarmsOutput{
NextToken: aws.String("mockNextToken"),
CompositeAlarms: []*cloudwatch.CompositeAlarm{
{
AlarmArn: aws.String(mockArn1),
AlarmName: aws.String("mockAlarmName1"),
AlarmRule: aws.String("mockAlarmRule"),
StateValue: aws.String("mockState"),
StateUpdatedTimestamp: &mockTime,
},
nil,
},
}, nil),
m.cw.EXPECT().DescribeAlarms(&cloudwatch.DescribeAlarmsInput{
NextToken: aws.String("mockNextToken"),
AlarmNames: aws.StringSlice([]string{"mockAlarmName1", "mockAlarmName2"}),
}).Return(&cloudwatch.DescribeAlarmsOutput{
MetricAlarms: []*cloudwatch.MetricAlarm{
{
AlarmArn: aws.String(mockArn2),
AlarmName: aws.String("mockAlarmName2"),
ComparisonOperator: aws.String(cloudwatch.ComparisonOperatorLessThanThreshold),
EvaluationPeriods: aws.Int64(int64(60)),
Period: aws.Int64(int64(5)),
DatapointsToAlarm: aws.Int64(int64(3)),
Threshold: aws.Float64(float64(63)),
MetricName: aws.String("mockMetricName1"),
StateValue: aws.String("mockState"),
StateUpdatedTimestamp: &mockTime,
},
nil,
},
}, nil),
)
},
wantedAlarmStatuses: []AlarmStatus{
{
Arn: mockArn1,
Name: "mockAlarmName1",
Type: "Composite",
Condition: "mockAlarmRule",
Status: "mockState",
UpdatedTimes: mockTime,
},
{
Arn: mockArn2,
Name: "mockAlarmName2",
Type: "Metric",
Condition: "mockMetricName1 < 63.00 for 3 datapoints within 5 minutes",
Status: "mockState",
UpdatedTimes: mockTime,
},
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockcwClient := mocks.NewMockapi(ctrl)
mocks := cloudWatchMocks{
cw: mockcwClient,
}
tc.setupMocks(mocks)
cwSvc := CloudWatch{
client: mockcwClient,
}
gotAlarmStatuses, gotErr := cwSvc.AlarmStatuses(tc.in)
if gotErr != nil {
require.EqualError(t, gotErr, tc.wantedErr.Error())
} else {
require.Equal(t, tc.wantedAlarmStatuses, gotAlarmStatuses)
}
})
}
}
func TestCloudWatch_AlarmDescriptions(t *testing.T) {
const (
name1 = "mock-alarm-name1"
name2 = "mock-alarm-name2"
desc1 = "mock alarm description 1"
desc2 = "mock alarm description 2"
)
mockNames := []string{name1, name2}
mockError := errors.New("some error")
testCases := map[string]struct {
setupMocks func(m cloudWatchMocks)
in []string
wantedErr error
wantedAlarmDescriptions []*AlarmDescription
}{
"errors if fail to describe alarms": {
in: mockNames,
setupMocks: func(m cloudWatchMocks) {
m.cw.EXPECT().DescribeAlarms(&cloudwatch.DescribeAlarmsInput{
AlarmNames: aws.StringSlice(mockNames),
}).Return(nil, mockError)
},
wantedErr: errors.New("describe CloudWatch alarms: some error"),
},
"return if no alarms with names": {
in: mockNames,
setupMocks: func(m cloudWatchMocks) {
m.cw.EXPECT().DescribeAlarms(&cloudwatch.DescribeAlarmsInput{
AlarmNames: aws.StringSlice(mockNames),
}).Return(nil, nil)
},
},
"success": {
in: mockNames,
setupMocks: func(m cloudWatchMocks) {
m.cw.EXPECT().DescribeAlarms(&cloudwatch.DescribeAlarmsInput{
AlarmNames: aws.StringSlice(mockNames),
}).Return(&cloudwatch.DescribeAlarmsOutput{
MetricAlarms: []*cloudwatch.MetricAlarm{
{
AlarmName: aws.String(name1),
AlarmDescription: aws.String(desc1),
},
{
AlarmName: aws.String(name2),
AlarmDescription: aws.String(desc2),
},
},
CompositeAlarms: nil,
}, nil)
},
wantedAlarmDescriptions: []*AlarmDescription{
{
Name: name1,
Description: desc1,
},
{
Name: name2,
Description: desc2,
},
},
},
"success with pagination": {
in: mockNames,
setupMocks: func(m cloudWatchMocks) {
gomock.InOrder(
m.cw.EXPECT().DescribeAlarms(&cloudwatch.DescribeAlarmsInput{
AlarmNames: aws.StringSlice(mockNames),
}).Return(&cloudwatch.DescribeAlarmsOutput{
NextToken: aws.String("mockNextToken"),
CompositeAlarms: []*cloudwatch.CompositeAlarm{
{
AlarmName: aws.String(name1),
AlarmDescription: aws.String(desc1),
},
nil,
},
}, nil),
m.cw.EXPECT().DescribeAlarms(&cloudwatch.DescribeAlarmsInput{
NextToken: aws.String("mockNextToken"),
AlarmNames: aws.StringSlice(mockNames),
}).Return(&cloudwatch.DescribeAlarmsOutput{
MetricAlarms: []*cloudwatch.MetricAlarm{
{
AlarmName: aws.String(name2),
AlarmDescription: aws.String(desc2),
},
nil,
},
}, nil),
)
},
wantedAlarmDescriptions: []*AlarmDescription{
{
Name: name1,
Description: desc1,
},
{
Name: name2,
Description: desc2,
},
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockcwClient := mocks.NewMockapi(ctrl)
mocks := cloudWatchMocks{
cw: mockcwClient,
}
tc.setupMocks(mocks)
cwSvc := CloudWatch{
client: mockcwClient,
}
gotAlarmDescriptions, gotErr := cwSvc.AlarmDescriptions(tc.in)
if gotErr != nil {
require.EqualError(t, gotErr, tc.wantedErr.Error())
} else {
require.Equal(t, tc.wantedAlarmDescriptions, gotAlarmDescriptions)
}
})
}
}
| 605 |
copilot-cli | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: ./internal/pkg/aws/cloudwatch/cloudwatch.go
// Package mocks is a generated GoMock package.
package mocks
import (
reflect "reflect"
cloudwatch "github.com/aws/aws-sdk-go/service/cloudwatch"
resourcegroups "github.com/aws/copilot-cli/internal/pkg/aws/resourcegroups"
gomock "github.com/golang/mock/gomock"
)
// Mockapi is a mock of api interface.
type Mockapi struct {
ctrl *gomock.Controller
recorder *MockapiMockRecorder
}
// MockapiMockRecorder is the mock recorder for Mockapi.
type MockapiMockRecorder struct {
mock *Mockapi
}
// NewMockapi creates a new mock instance.
func NewMockapi(ctrl *gomock.Controller) *Mockapi {
mock := &Mockapi{ctrl: ctrl}
mock.recorder = &MockapiMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *Mockapi) EXPECT() *MockapiMockRecorder {
return m.recorder
}
// DescribeAlarms mocks base method.
func (m *Mockapi) DescribeAlarms(input *cloudwatch.DescribeAlarmsInput) (*cloudwatch.DescribeAlarmsOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DescribeAlarms", input)
ret0, _ := ret[0].(*cloudwatch.DescribeAlarmsOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DescribeAlarms indicates an expected call of DescribeAlarms.
func (mr *MockapiMockRecorder) DescribeAlarms(input interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeAlarms", reflect.TypeOf((*Mockapi)(nil).DescribeAlarms), input)
}
// MockresourceGetter is a mock of resourceGetter interface.
type MockresourceGetter struct {
ctrl *gomock.Controller
recorder *MockresourceGetterMockRecorder
}
// MockresourceGetterMockRecorder is the mock recorder for MockresourceGetter.
type MockresourceGetterMockRecorder struct {
mock *MockresourceGetter
}
// NewMockresourceGetter creates a new mock instance.
func NewMockresourceGetter(ctrl *gomock.Controller) *MockresourceGetter {
mock := &MockresourceGetter{ctrl: ctrl}
mock.recorder = &MockresourceGetterMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockresourceGetter) EXPECT() *MockresourceGetterMockRecorder {
return m.recorder
}
// GetResourcesByTags mocks base method.
func (m *MockresourceGetter) GetResourcesByTags(resourceType string, tags map[string]string) ([]*resourcegroups.Resource, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetResourcesByTags", resourceType, tags)
ret0, _ := ret[0].([]*resourcegroups.Resource)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetResourcesByTags indicates an expected call of GetResourcesByTags.
func (mr *MockresourceGetterMockRecorder) GetResourcesByTags(resourceType, tags interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetResourcesByTags", reflect.TypeOf((*MockresourceGetter)(nil).GetResourcesByTags), resourceType, tags)
}
| 90 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package cloudwatchlogs provides a client to make API requests to Amazon CloudWatch Logs.
package cloudwatchlogs
import (
"fmt"
"sort"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatchlogs"
)
const (
// SleepDuration is the sleep time for making the next request for log events.
SleepDuration = 1 * time.Second
)
var (
fatalCodes = []string{"FATA", "FATAL", "fatal", "ERR", "ERROR", "error"}
warningCodes = []string{"WARN", "warn", "WARNING", "warning"}
)
type api interface {
DescribeLogStreams(input *cloudwatchlogs.DescribeLogStreamsInput) (*cloudwatchlogs.DescribeLogStreamsOutput, error)
GetLogEvents(input *cloudwatchlogs.GetLogEventsInput) (*cloudwatchlogs.GetLogEventsOutput, error)
}
// CloudWatchLogs wraps an AWS Cloudwatch Logs client.
type CloudWatchLogs struct {
client api
}
// LogEventsOutput contains the output for LogEvents
type LogEventsOutput struct {
// Retrieved log events.
Events []*Event
// Timestamp for the last event
StreamLastEventTime map[string]int64
}
// LogEventsOpts wraps the parameters to call LogEvents.
type LogEventsOpts struct {
LogGroup string
LogStreamPrefixFilters []string // If nil, retrieve logs from all log streams.
Limit *int64
StartTime *int64
EndTime *int64
StreamLastEventTime map[string]int64
LogStreamLimit int
}
// New returns a CloudWatchLogs configured against the input session.
func New(s *session.Session) *CloudWatchLogs {
return &CloudWatchLogs{
client: cloudwatchlogs.New(s),
}
}
// logStreams returns all name of the log streams in a log group with optional limit and prefix filters.
func (c *CloudWatchLogs) logStreams(logGroup string, logStreamLimit int, logStreamPrefixes ...string) ([]string, error) {
var logStreamNames []string
logStreamsResp := &cloudwatchlogs.DescribeLogStreamsOutput{}
for {
var err error
logStreamsResp, err = c.client.DescribeLogStreams(&cloudwatchlogs.DescribeLogStreamsInput{
LogGroupName: aws.String(logGroup),
Descending: aws.Bool(true),
OrderBy: aws.String(cloudwatchlogs.OrderByLastEventTime),
NextToken: logStreamsResp.NextToken,
})
if err != nil {
return nil, fmt.Errorf("describe log streams of log group %s: %w", logGroup, err)
}
if len(logStreamsResp.LogStreams) == 0 {
return nil, fmt.Errorf("no log stream found in log group %s", logGroup)
}
var streams []string
for _, logStream := range logStreamsResp.LogStreams {
name := aws.StringValue(logStream.LogStreamName)
if name == "" {
continue
}
streams = append(streams, name)
}
if len(logStreamPrefixes) != 0 {
logStreamNames = append(logStreamNames, filterStringSliceByPrefix(streams, logStreamPrefixes)...)
} else {
logStreamNames = append(logStreamNames, streams...)
}
if logStreamLimit != 0 && len(logStreamNames) >= logStreamLimit {
break
}
if token := logStreamsResp.NextToken; aws.StringValue(token) == "" {
break
}
}
return truncateStreams(logStreamLimit, logStreamNames), nil
}
// LogEvents returns an array of Cloudwatch Logs events.
func (c *CloudWatchLogs) LogEvents(opts LogEventsOpts) (*LogEventsOutput, error) {
var events []*Event
in := initGetLogEventsInput(opts)
logStreams, err := c.logStreams(opts.LogGroup, opts.LogStreamLimit, opts.LogStreamPrefixFilters...)
if err != nil {
return nil, err
}
streamLastEventTime := make(map[string]int64)
for k, v := range opts.StreamLastEventTime {
streamLastEventTime[k] = v
}
for _, logStream := range logStreams {
// Set override value
in.SetLogStreamName(logStream)
if streamLastEventTime[logStream] != 0 {
// If last event for this log stream exists, increment last log event timestamp
// by one to get logs after the last event.
in.SetStartTime(streamLastEventTime[logStream] + 1)
}
// TODO: https://github.com/aws/copilot-cli/pull/628#discussion_r374291068 and https://github.com/aws/copilot-cli/pull/628#discussion_r374294362
resp, err := c.client.GetLogEvents(in)
if err != nil {
return nil, fmt.Errorf("get log events of %s/%s: %w", opts.LogGroup, logStream, err)
}
for _, event := range resp.Events {
log := &Event{
LogStreamName: logStream,
IngestionTime: aws.Int64Value(event.IngestionTime),
Message: aws.StringValue(event.Message),
Timestamp: aws.Int64Value(event.Timestamp),
}
events = append(events, log)
}
if len(resp.Events) != 0 {
streamLastEventTime[logStream] = *resp.Events[len(resp.Events)-1].Timestamp
}
}
sort.SliceStable(events, func(i, j int) bool { return events[i].Timestamp < events[j].Timestamp })
limit := int(aws.Int64Value(in.Limit))
if limit != 0 {
return &LogEventsOutput{
Events: truncateEvents(limit, events),
StreamLastEventTime: streamLastEventTime,
}, nil
}
return &LogEventsOutput{
Events: events,
StreamLastEventTime: streamLastEventTime,
}, nil
}
func truncateEvents(limit int, events []*Event) []*Event {
if len(events) <= limit {
return events
}
return events[len(events)-limit:] // Only grab the last N elements where N = limit
}
func truncateStreams(limit int, streams []string) []string {
if limit == 0 || len(streams) <= limit {
return streams
}
return streams[:limit]
}
func initGetLogEventsInput(opts LogEventsOpts) *cloudwatchlogs.GetLogEventsInput {
return &cloudwatchlogs.GetLogEventsInput{
LogGroupName: aws.String(opts.LogGroup),
StartTime: opts.StartTime,
EndTime: opts.EndTime,
Limit: opts.Limit,
}
}
// Example: if the prefixes is []string{"a"} and all is []string{"a", "b", "ab"}
// then it returns []string{"a", "ab"}. Empty string prefixes are not supported.
func filterStringSliceByPrefix(all, prefixes []string) []string {
trie := buildTrie(prefixes)
var matches []string
for _, str := range all {
if trie.isPrefixOf(str) {
matches = append(matches, str)
}
}
return matches
}
type trieNode struct {
children map[rune]*trieNode
hasWord bool
}
func newTrieNode() *trieNode {
return &trieNode{
children: make(map[rune]*trieNode),
}
}
type trie struct {
root *trieNode
}
func buildTrie(strs []string) trie {
root := newTrieNode()
for _, str := range strs {
node := root
for _, char := range str {
if _, ok := node.children[char]; !ok {
node.children[char] = newTrieNode()
}
node = node.children[char]
}
node.hasWord = true
}
return trie{root: root}
}
func (t *trie) isPrefixOf(str string) bool {
node := t.root
for _, char := range str {
child, ok := node.children[char]
if !ok {
return false
}
if child.hasWord {
return true
}
node = child
}
return false
}
| 241 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package cloudwatchlogs
import (
"errors"
"fmt"
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/cloudwatchlogs"
"github.com/aws/copilot-cli/internal/pkg/aws/cloudwatchlogs/mocks"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
func TestLogEvents(t *testing.T) {
mockError := errors.New("some error")
testCases := map[string]struct {
logGroupName string
logStream []string
startTime *int64
endTime *int64
limit *int64
logStreamLimit int
lastEventTime map[string]int64
mockcloudwatchlogsClient func(m *mocks.Mockapi)
wantLogEvents []*Event
wantLastEventTime map[string]int64
wantErr error
}{
"should get log stream name and return log events": {
logGroupName: "mockLogGroup",
logStream: []string{"copilot/mockLogGroup/foo", "copilot/mockLogGroup/bar"},
mockcloudwatchlogsClient: func(m *mocks.Mockapi) {
m.EXPECT().DescribeLogStreams(&cloudwatchlogs.DescribeLogStreamsInput{
LogGroupName: aws.String("mockLogGroup"),
Descending: aws.Bool(true),
OrderBy: aws.String("LastEventTime"),
}).Return(&cloudwatchlogs.DescribeLogStreamsOutput{
LogStreams: []*cloudwatchlogs.LogStream{
{
LogStreamName: aws.String("copilot/mockLogGroup/fooLogStream"),
},
{
LogStreamName: aws.String("copilot/mockLogGroup/barLogStream"),
},
{
LogStreamName: aws.String("copilot/mockLogGroup/booLogStream"),
},
},
}, nil)
m.EXPECT().GetLogEvents(&cloudwatchlogs.GetLogEventsInput{
LogGroupName: aws.String("mockLogGroup"),
LogStreamName: aws.String("copilot/mockLogGroup/fooLogStream"),
}).Return(&cloudwatchlogs.GetLogEventsOutput{
Events: []*cloudwatchlogs.OutputLogEvent{
{
Message: aws.String("some log"),
Timestamp: aws.Int64(1),
},
},
}, nil)
m.EXPECT().GetLogEvents(&cloudwatchlogs.GetLogEventsInput{
LogGroupName: aws.String("mockLogGroup"),
LogStreamName: aws.String("copilot/mockLogGroup/barLogStream"),
}).Return(&cloudwatchlogs.GetLogEventsOutput{
Events: []*cloudwatchlogs.OutputLogEvent{
{
Message: aws.String("other log"),
Timestamp: aws.Int64(0),
},
},
}, nil)
},
wantLogEvents: []*Event{
{
LogStreamName: "copilot/mockLogGroup/barLogStream",
Message: "other log",
Timestamp: 0,
},
{
LogStreamName: "copilot/mockLogGroup/fooLogStream",
Message: "some log",
Timestamp: 1,
},
},
wantLastEventTime: map[string]int64{
"copilot/mockLogGroup/fooLogStream": 1,
"copilot/mockLogGroup/barLogStream": 0,
},
wantErr: nil,
},
"should override startTime to be last event time when follow mode": {
logGroupName: "mockLogGroup",
startTime: aws.Int64(1234567),
lastEventTime: map[string]int64{
"copilot/mockLogGroup/mockLogStream": 1234890,
},
mockcloudwatchlogsClient: func(m *mocks.Mockapi) {
m.EXPECT().DescribeLogStreams(&cloudwatchlogs.DescribeLogStreamsInput{
LogGroupName: aws.String("mockLogGroup"),
Descending: aws.Bool(true),
OrderBy: aws.String("LastEventTime"),
}).Return(&cloudwatchlogs.DescribeLogStreamsOutput{
LogStreams: []*cloudwatchlogs.LogStream{
{
LogStreamName: aws.String("copilot/mockLogGroup/mockLogStream"),
},
},
}, nil)
m.EXPECT().GetLogEvents(&cloudwatchlogs.GetLogEventsInput{
StartTime: aws.Int64(1234891),
LogGroupName: aws.String("mockLogGroup"),
LogStreamName: aws.String("copilot/mockLogGroup/mockLogStream"),
}).Return(&cloudwatchlogs.GetLogEventsOutput{
Events: []*cloudwatchlogs.OutputLogEvent{
{
Message: aws.String("some log"),
Timestamp: aws.Int64(1234892),
},
},
}, nil)
},
wantLogEvents: []*Event{
{
LogStreamName: "copilot/mockLogGroup/mockLogStream",
Message: "some log",
Timestamp: 1234892,
},
},
wantLastEventTime: map[string]int64{
"copilot/mockLogGroup/mockLogStream": 1234892,
},
wantErr: nil,
},
"should return limited number of log events": {
logGroupName: "mockLogGroup",
limit: aws.Int64(1),
mockcloudwatchlogsClient: func(m *mocks.Mockapi) {
m.EXPECT().DescribeLogStreams(&cloudwatchlogs.DescribeLogStreamsInput{
LogGroupName: aws.String("mockLogGroup"),
Descending: aws.Bool(true),
OrderBy: aws.String("LastEventTime"),
}).Return(&cloudwatchlogs.DescribeLogStreamsOutput{
LogStreams: []*cloudwatchlogs.LogStream{
{
LogStreamName: aws.String("copilot/mockLogGroup/mockLogStream"),
},
},
}, nil)
m.EXPECT().GetLogEvents(&cloudwatchlogs.GetLogEventsInput{
Limit: aws.Int64(1),
LogGroupName: aws.String("mockLogGroup"),
LogStreamName: aws.String("copilot/mockLogGroup/mockLogStream"),
}).Return(&cloudwatchlogs.GetLogEventsOutput{
Events: []*cloudwatchlogs.OutputLogEvent{
{
Message: aws.String("some log"),
Timestamp: aws.Int64(0),
},
{
Message: aws.String("other log"),
Timestamp: aws.Int64(1),
},
},
}, nil)
},
wantLogEvents: []*Event{
{
LogStreamName: "copilot/mockLogGroup/mockLogStream",
Message: "other log",
Timestamp: 1,
},
},
wantLastEventTime: map[string]int64{
"copilot/mockLogGroup/mockLogStream": 1,
},
wantErr: nil,
},
"returns error if fail to describe log streams": {
logGroupName: "mockLogGroup",
mockcloudwatchlogsClient: func(m *mocks.Mockapi) {
m.EXPECT().DescribeLogStreams(&cloudwatchlogs.DescribeLogStreamsInput{
LogGroupName: aws.String("mockLogGroup"),
Descending: aws.Bool(true),
OrderBy: aws.String("LastEventTime"),
}).Return(nil, mockError)
},
wantLogEvents: nil,
wantErr: fmt.Errorf("describe log streams of log group %s: %w", "mockLogGroup", mockError),
},
"returns error if no log stream found": {
logGroupName: "mockLogGroup",
mockcloudwatchlogsClient: func(m *mocks.Mockapi) {
m.EXPECT().DescribeLogStreams(&cloudwatchlogs.DescribeLogStreamsInput{
LogGroupName: aws.String("mockLogGroup"),
Descending: aws.Bool(true),
OrderBy: aws.String("LastEventTime"),
}).Return(&cloudwatchlogs.DescribeLogStreamsOutput{
LogStreams: []*cloudwatchlogs.LogStream{},
}, nil)
},
wantLogEvents: nil,
wantErr: fmt.Errorf("no log stream found in log group %s", "mockLogGroup"),
},
"returns error if fail to get log events": {
logGroupName: "mockLogGroup",
mockcloudwatchlogsClient: func(m *mocks.Mockapi) {
m.EXPECT().DescribeLogStreams(&cloudwatchlogs.DescribeLogStreamsInput{
LogGroupName: aws.String("mockLogGroup"),
Descending: aws.Bool(true),
OrderBy: aws.String("LastEventTime"),
}).Return(&cloudwatchlogs.DescribeLogStreamsOutput{
LogStreams: []*cloudwatchlogs.LogStream{
{
LogStreamName: aws.String("mockLogStream"),
},
},
}, nil)
m.EXPECT().GetLogEvents(&cloudwatchlogs.GetLogEventsInput{
LogGroupName: aws.String("mockLogGroup"),
LogStreamName: aws.String("mockLogStream"),
}).Return(nil, mockError)
},
wantLogEvents: nil,
wantErr: fmt.Errorf("get log events of %s/%s: %w", "mockLogGroup", "mockLogStream", mockError),
},
"should filter out wrong prefixes": {
logGroupName: "mockLogGroup",
logStream: []string{"copilot/"},
mockcloudwatchlogsClient: func(m *mocks.Mockapi) {
m.EXPECT().DescribeLogStreams(&cloudwatchlogs.DescribeLogStreamsInput{
LogGroupName: aws.String("mockLogGroup"),
Descending: aws.Bool(true),
OrderBy: aws.String("LastEventTime"),
}).Return(&cloudwatchlogs.DescribeLogStreamsOutput{
LogStreams: []*cloudwatchlogs.LogStream{
{
LogStreamName: aws.String("copilot/mockLogGroup/mockLogStream"),
},
{
LogStreamName: aws.String("states/copilot-mockLogGroup/abcde"),
},
},
}, nil)
m.EXPECT().GetLogEvents(&cloudwatchlogs.GetLogEventsInput{
LogGroupName: aws.String("mockLogGroup"),
LogStreamName: aws.String("copilot/mockLogGroup/mockLogStream"),
}).Return(&cloudwatchlogs.GetLogEventsOutput{
Events: []*cloudwatchlogs.OutputLogEvent{
{
Message: aws.String("some log"),
Timestamp: aws.Int64(0),
},
},
}, nil)
},
wantLogEvents: []*Event{
{
LogStreamName: "copilot/mockLogGroup/mockLogStream",
Message: "some log",
Timestamp: 0,
},
},
wantLastEventTime: map[string]int64{
"copilot/mockLogGroup/mockLogStream": 0,
},
wantErr: nil,
},
"should limit log streams fetched": {
logGroupName: "mockLogGroup",
logStreamLimit: 2,
limit: aws.Int64(2),
logStream: []string{"copilot/"},
mockcloudwatchlogsClient: func(m *mocks.Mockapi) {
m.EXPECT().DescribeLogStreams(&cloudwatchlogs.DescribeLogStreamsInput{
LogGroupName: aws.String("mockLogGroup"),
Descending: aws.Bool(true),
OrderBy: aws.String("LastEventTime"),
}).Return(&cloudwatchlogs.DescribeLogStreamsOutput{
LogStreams: []*cloudwatchlogs.LogStream{
{
LogStreamName: aws.String("copilot/mockLogGroup/mockLogStream"),
LastEventTimestamp: aws.Int64(5),
},
{
LogStreamName: aws.String("copilot/mockLogGroup/mockLogStream2"),
LastEventTimestamp: aws.Int64(4),
},
{
LogStreamName: aws.String("states/abcde"),
LastEventTimestamp: aws.Int64(3),
},
{
LogStreamName: aws.String("copilot/mockLogGroup/mockLogStream3"),
LastEventTimestamp: aws.Int64(1),
},
},
}, nil)
m.EXPECT().GetLogEvents(&cloudwatchlogs.GetLogEventsInput{
LogGroupName: aws.String("mockLogGroup"),
LogStreamName: aws.String("copilot/mockLogGroup/mockLogStream"),
Limit: aws.Int64(2),
}).Return(&cloudwatchlogs.GetLogEventsOutput{
Events: []*cloudwatchlogs.OutputLogEvent{
{
Message: aws.String("some log"),
Timestamp: aws.Int64(5),
},
},
}, nil)
m.EXPECT().GetLogEvents(&cloudwatchlogs.GetLogEventsInput{
LogGroupName: aws.String("mockLogGroup"),
LogStreamName: aws.String("copilot/mockLogGroup/mockLogStream2"),
Limit: aws.Int64(2),
}).Return(&cloudwatchlogs.GetLogEventsOutput{
Events: []*cloudwatchlogs.OutputLogEvent{
{
Message: aws.String("other log"),
Timestamp: aws.Int64(1),
},
{
Message: aws.String("important log"),
Timestamp: aws.Int64(4),
},
},
}, nil)
},
wantLogEvents: []*Event{
{
LogStreamName: "copilot/mockLogGroup/mockLogStream",
Timestamp: 5,
Message: "some log",
},
{
LogStreamName: "copilot/mockLogGroup/mockLogStream2",
Timestamp: 4,
Message: "important log",
},
},
wantLastEventTime: map[string]int64{
"copilot/mockLogGroup/mockLogStream": 5,
"copilot/mockLogGroup/mockLogStream2": 4,
},
wantErr: nil,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockcloudwatchlogsClient := mocks.NewMockapi(ctrl)
tc.mockcloudwatchlogsClient(mockcloudwatchlogsClient)
service := CloudWatchLogs{
client: mockcloudwatchlogsClient,
}
gotLogEventsOutput, gotErr := service.LogEvents(LogEventsOpts{
LogGroup: tc.logGroupName,
EndTime: tc.endTime,
Limit: tc.limit,
LogStreamPrefixFilters: tc.logStream,
StartTime: tc.startTime,
StreamLastEventTime: tc.lastEventTime,
LogStreamLimit: tc.logStreamLimit,
})
if gotErr != nil {
require.Equal(t, tc.wantErr, gotErr)
} else {
require.NoError(t, gotErr)
require.ElementsMatch(t, tc.wantLogEvents, gotLogEventsOutput.Events)
require.Equal(t, tc.wantLastEventTime, gotLogEventsOutput.StreamLastEventTime)
}
})
}
}
| 394 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package cloudwatchlogs contains utility functions for Cloudwatch Logs client.
package cloudwatchlogs
import (
"encoding/json"
"fmt"
"regexp"
"github.com/aws/copilot-cli/internal/pkg/term/color"
c "github.com/fatih/color"
)
const (
shortLogStreamNameLength = 25
)
// Event represents a log event.
type Event struct {
LogStreamName string `json:"logStreamName"`
IngestionTime int64 `json:"ingestionTime"`
Message string `json:"message"`
Timestamp int64 `json:"timestamp"`
}
// JSONString returns the stringified LogEvent struct with json format.
func (l *Event) JSONString() (string, error) {
b, err := json.Marshal(l)
if err != nil {
return "", fmt.Errorf("marshal a log event: %w", err)
}
return fmt.Sprintf("%s\n", b), nil
}
// HumanString returns the stringified LogEvent struct with human readable format.
func (l *Event) HumanString() string {
for _, code := range fatalCodes {
l.Message = colorCodeMessage(l.Message, code, color.Red)
}
for _, code := range warningCodes {
l.Message = colorCodeMessage(l.Message, code, color.Yellow)
}
return fmt.Sprintf("%s %s\n", color.Grey.Sprint(l.shortLogStreamName()), l.Message)
}
func (l *Event) shortLogStreamName() string {
if len(l.LogStreamName) < shortLogStreamNameLength {
return l.LogStreamName
}
return l.LogStreamName[0:shortLogStreamNameLength]
}
// colorCodeMessage returns the given message with color applied to every occurence of code
func colorCodeMessage(message string, code string, colorToApply *c.Color) string {
if c.NoColor {
return message
}
pattern := fmt.Sprintf("\\b%s\\b", code)
re := regexp.MustCompile(pattern)
return re.ReplaceAllString(message, colorToApply.Sprint(code))
}
| 64 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package cloudwatchlogs
import (
"fmt"
"testing"
"github.com/aws/copilot-cli/internal/pkg/term/color"
c "github.com/fatih/color"
"github.com/stretchr/testify/require"
)
func TestColorCodeMessage(t *testing.T) {
color.DisableColorBasedOnEnvVar()
testCases := map[string]struct {
givenMessage string
givenCode string
givenColor *c.Color
wantMessage string
}{
"should not apply color to a fatal code if it exists in a message as a substring": {
givenMessage: "e2e environment variables have been OVERRIDEN",
givenCode: "ERR",
givenColor: color.Red,
wantMessage: "e2e environment variables have been OVERRIDEN",
},
"should apply color to a fatal code if exists in a message": {
givenMessage: "An Error has occured",
givenCode: "Error",
givenColor: color.Red,
wantMessage: fmt.Sprintf("An %s has occured", color.Red.Sprint("Error")),
},
"should not apply color to a warning code if exists in a message as a substring": {
givenMessage: "Forewarning",
givenCode: "warning",
givenColor: color.Yellow,
wantMessage: "Forewarning",
},
"should apply color to a warning code if exists in a message": {
givenMessage: "Warning something has happened",
givenCode: "Warning",
givenColor: color.Yellow,
wantMessage: fmt.Sprintf("%s something has happened", color.Yellow.Sprint("Warning")),
},
"should apply color to a fatal code if code is next to special character": {
givenMessage: "error: something happened",
givenCode: "error",
givenColor: color.Red,
wantMessage: fmt.Sprintf("%s: something happened", color.Red.Sprint("error")),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
color.DisableColorBasedOnEnvVar()
got := colorCodeMessage(tc.givenMessage, tc.givenCode, tc.givenColor)
require.Equal(t, tc.wantMessage, got)
})
}
}
| 62 |
copilot-cli | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: ./internal/pkg/aws/cloudwatchlogs/cloudwatchlogs.go
// Package mocks is a generated GoMock package.
package mocks
import (
reflect "reflect"
cloudwatchlogs "github.com/aws/aws-sdk-go/service/cloudwatchlogs"
gomock "github.com/golang/mock/gomock"
)
// Mockapi is a mock of api interface.
type Mockapi struct {
ctrl *gomock.Controller
recorder *MockapiMockRecorder
}
// MockapiMockRecorder is the mock recorder for Mockapi.
type MockapiMockRecorder struct {
mock *Mockapi
}
// NewMockapi creates a new mock instance.
func NewMockapi(ctrl *gomock.Controller) *Mockapi {
mock := &Mockapi{ctrl: ctrl}
mock.recorder = &MockapiMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *Mockapi) EXPECT() *MockapiMockRecorder {
return m.recorder
}
// DescribeLogStreams mocks base method.
func (m *Mockapi) DescribeLogStreams(input *cloudwatchlogs.DescribeLogStreamsInput) (*cloudwatchlogs.DescribeLogStreamsOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DescribeLogStreams", input)
ret0, _ := ret[0].(*cloudwatchlogs.DescribeLogStreamsOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DescribeLogStreams indicates an expected call of DescribeLogStreams.
func (mr *MockapiMockRecorder) DescribeLogStreams(input interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeLogStreams", reflect.TypeOf((*Mockapi)(nil).DescribeLogStreams), input)
}
// GetLogEvents mocks base method.
func (m *Mockapi) GetLogEvents(input *cloudwatchlogs.GetLogEventsInput) (*cloudwatchlogs.GetLogEventsOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetLogEvents", input)
ret0, _ := ret[0].(*cloudwatchlogs.GetLogEventsOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetLogEvents indicates an expected call of GetLogEvents.
func (mr *MockapiMockRecorder) GetLogEvents(input interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetLogEvents", reflect.TypeOf((*Mockapi)(nil).GetLogEvents), input)
}
| 66 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package codepipeline provides a client to make API requests to Amazon Elastic Container Service.
package codepipeline
import (
"errors"
"fmt"
"time"
"github.com/xlab/treeprint"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/arn"
"github.com/aws/aws-sdk-go/aws/session"
cp "github.com/aws/aws-sdk-go/service/codepipeline"
rg "github.com/aws/copilot-cli/internal/pkg/aws/resourcegroups"
"github.com/aws/copilot-cli/internal/pkg/term/color"
)
type api interface {
GetPipeline(*cp.GetPipelineInput) (*cp.GetPipelineOutput, error)
GetPipelineState(*cp.GetPipelineStateInput) (*cp.GetPipelineStateOutput, error)
ListPipelineExecutions(input *cp.ListPipelineExecutionsInput) (*cp.ListPipelineExecutionsOutput, error)
RetryStageExecution(input *cp.RetryStageExecutionInput) (*cp.RetryStageExecutionOutput, error)
}
type resourceGetter interface {
GetResourcesByTags(resourceType string, tags map[string]string) ([]*rg.Resource, error)
}
// CodePipeline wraps the AWS CodePipeline client.
type CodePipeline struct {
client api
rgClient resourceGetter
}
// Pipeline represents an existing CodePipeline resource.
type Pipeline struct {
// Name is the resource name of the pipeline in CodePipeline, e.g. myapp-mypipeline-RANDOMSTRING.
Name string `json:"pipelineName"`
Region string `json:"region"`
AccountID string `json:"accountId"`
Stages []*Stage `json:"stages"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
// Stage wraps the codepipeline pipeline stage.
type Stage struct {
Name string `json:"name"`
Category string `json:"category"`
Provider string `json:"provider"`
Details string `json:"details"`
}
// PipelineState represents a Pipeline's status.
type PipelineState struct {
PipelineName string `json:"pipelineName"`
StageStates []*StageState `json:"stageStates"`
UpdatedAt time.Time `json:"updatedAt"`
}
// StageState wraps a CodePipeline stage state.
type StageState struct {
StageName string `json:"stageName"`
Actions []StageAction `json:"actions,omitempty"`
Transition string `json:"transition"`
}
// StageAction wraps a CodePipeline stage action.
type StageAction struct {
Name string `json:"name"`
Status string `json:"status"`
}
// AggregateStatus returns the collective status of a stage by looking at each individual action's status.
// It returns "InProgress" if there are any actions that are in progress.
// It returns "Failed" if there are actions that failed or were abandoned.
// It returns "Succeeded" if all actions succeeded.
// It returns "" if there is no prior execution.
func (ss StageState) AggregateStatus() string {
status := map[string]int{
"": 0,
"InProgress": 0,
"Failed": 0,
"Abandoned": 0,
"Succeeded": 0,
}
for _, action := range ss.Actions {
status[action.Status]++
}
if status["InProgress"] > 0 {
return "InProgress"
} else if status["Failed"]+status["Abandoned"] > 0 {
return "Failed"
} else if status["Succeeded"] > 0 && status["Succeeded"] == len(ss.Actions) {
return "Succeeded"
}
return ""
}
// New returns a CodePipeline client configured against the input session.
func New(s *session.Session) *CodePipeline {
return &CodePipeline{
client: cp.New(s),
rgClient: rg.New(s),
}
}
// GetPipeline retrieves information from a given pipeline.
func (c *CodePipeline) GetPipeline(name string) (*Pipeline, error) {
input := &cp.GetPipelineInput{
Name: aws.String(name),
}
resp, err := c.client.GetPipeline(input)
if err != nil {
return nil, fmt.Errorf("get pipeline %s: %w", name, err)
}
pipeline := resp.Pipeline
metadata := resp.Metadata
pipelineArn := aws.StringValue(metadata.PipelineArn)
parsedArn, err := arn.Parse(pipelineArn)
if err != nil {
return nil, fmt.Errorf("parse pipeline ARN: %s", pipelineArn)
}
var stages []*Stage
for _, s := range pipeline.Stages {
stage, err := c.getStage(s)
if err != nil {
return nil, fmt.Errorf("get stage for pipeline: %s", pipelineArn)
}
stages = append(stages, stage)
}
return &Pipeline{
Name: aws.StringValue(pipeline.Name),
Region: parsedArn.Region,
AccountID: parsedArn.AccountID,
Stages: stages,
CreatedAt: *metadata.Created,
UpdatedAt: *metadata.Updated,
}, nil
}
// HumanString returns the stringified Stage struct with human readable format.
// Example output:
// DeployTo-test Deploy Cloudformation stackname: dinder-test-test
func (s *Stage) HumanString() string {
return fmt.Sprintf("%s\t%s\t%s\t%s\n", s.Name, s.Category, s.Provider, s.Details)
}
// RetryStageExecution tries to re-initiate a failed stage for the given pipeline.
func (c *CodePipeline) RetryStageExecution(pipelineName, stageName string) error {
executionID, err := c.pipelineExecutionID(pipelineName)
if err != nil {
return fmt.Errorf("retrieve pipeline execution ID: %w", err)
}
if _, err = c.client.RetryStageExecution(&cp.RetryStageExecutionInput{
PipelineExecutionId: &executionID,
PipelineName: &pipelineName,
RetryMode: aws.String(cp.StageRetryModeFailedActions),
StageName: &stageName,
}); err != nil {
noFailedActions := &cp.StageNotRetryableException{}
if !errors.As(err, &noFailedActions) {
return fmt.Errorf("retry pipeline source stage: %w", err)
}
}
return nil
}
// GetPipelineState retrieves status information from a given pipeline.
func (c *CodePipeline) GetPipelineState(name string) (*PipelineState, error) {
input := &cp.GetPipelineStateInput{
Name: aws.String(name),
}
resp, err := c.client.GetPipelineState(input)
if err != nil {
return nil, fmt.Errorf("get pipeline state %s: %w", name, err)
}
var stageStates []*StageState
for _, stage := range resp.StageStates {
var stageName string
if stage.StageName != nil {
stageName = aws.StringValue(stage.StageName)
}
var transition string
if stage.InboundTransitionState != nil {
transition = "DISABLED"
if *stage.InboundTransitionState.Enabled {
transition = "ENABLED"
}
}
var actions []StageAction
for _, actionState := range stage.ActionStates {
if actionState.LatestExecution != nil {
actions = append(actions, StageAction{
Name: aws.StringValue(actionState.ActionName),
Status: aws.StringValue(actionState.LatestExecution.Status),
})
}
}
stageStates = append(stageStates, &StageState{
StageName: stageName,
Actions: actions,
Transition: transition,
})
}
return &PipelineState{
PipelineName: aws.StringValue(resp.PipelineName),
StageStates: stageStates,
UpdatedAt: *resp.Updated,
}, nil
}
// HumanString returns the stringified PipelineState struct with human readable format.
// Example output:
// DeployTo-test Deploy Cloudformation stackname: dinder-test-test
func (ss *StageState) HumanString() string {
status := ss.AggregateStatus()
transition := ss.Transition
stageString := fmt.Sprintf("%s\t%s\t%s", ss.StageName, fmtStatus(transition), fmtStatus(status))
tree := treeprint.NewWithRoot(stageString)
for _, action := range ss.Actions {
tree.AddNode(action.humanString())
}
return tree.String()
}
func (c *CodePipeline) getStage(s *cp.StageDeclaration) (*Stage, error) {
name := aws.StringValue(s.Name)
var category, provider, details string
if len(s.Actions) > 0 {
// Currently, we only support Source, Build and Deploy stages, all of which must contain at least one action.
action := s.Actions[0]
category = aws.StringValue(action.ActionTypeId.Category)
provider = aws.StringValue(action.ActionTypeId.Provider)
config := action.Configuration
switch category {
case "Source":
// https://docs.aws.amazon.com/codepipeline/latest/userguide/reference-pipeline-structure.html#structure-configuration-examples
switch provider {
case "GitHub":
details = fmt.Sprintf("Repository: %s/%s", aws.StringValue(config["Owner"]), aws.StringValue(config["Repo"]))
case "CodeCommit":
details = fmt.Sprintf("Repository: %s", aws.StringValue(config["RepositoryName"]))
case "CodeStarSourceConnection":
details = fmt.Sprintf("Repository: %s", aws.StringValue(config["FullRepositoryId"]))
}
case "Build":
// Currently, we use CodeBuild only for the build stage: https://docs.aws.amazon.com/codepipeline/latest/userguide/action-reference-CodeBuild.html#action-reference-CodeBuild-config
details = fmt.Sprintf("BuildProject: %s", aws.StringValue(config["ProjectName"]))
case "Deploy":
// Currently, we use Cloudformation only for the build stage: https://docs.aws.amazon.com/codepipeline/latest/userguide/action-reference-CloudFormation.html#action-reference-CloudFormation-config
details = fmt.Sprintf("StackName: %s", aws.StringValue(config["StackName"]))
}
}
stage := &Stage{
Name: name,
Category: category,
Provider: provider,
Details: details,
}
return stage, nil
}
// pipelineExecutionID returns the ExecutionID of the most recent execution of a pipeline.
func (c *CodePipeline) pipelineExecutionID(pipelineName string) (string, error) {
input := &cp.ListPipelineExecutionsInput{
MaxResults: aws.Int64(1),
PipelineName: &pipelineName,
}
output, err := c.client.ListPipelineExecutions(input)
if err != nil {
return "", fmt.Errorf("list pipeline execution for %s: %w", pipelineName, err)
}
if len(output.PipelineExecutionSummaries) == 0 {
return "", fmt.Errorf("no pipeline execution IDs found for %s", pipelineName)
}
return aws.StringValue(output.PipelineExecutionSummaries[0].PipelineExecutionId), nil
}
func (sa StageAction) humanString() string {
return sa.Name + "\t\t" + fmtStatus(sa.Status)
}
func fmtStatus(status string) string {
const empty = " -"
switch status {
case "":
return empty
case "InProgress":
return color.Emphasize(status)
case "Failed":
return color.Red.Sprint(status)
case "DISABLED":
return color.Faint.Sprint(status)
default:
return status
}
}
| 314 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package codepipeline
import (
"errors"
"fmt"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/copilot-cli/internal/pkg/aws/codepipeline/mocks"
"github.com/golang/mock/gomock"
"github.com/aws/aws-sdk-go/service/codepipeline"
"github.com/stretchr/testify/require"
)
type codepipelineMocks struct {
cp *mocks.Mockapi
rg *mocks.MockresourceGetter
}
func TestCodePipeline_GetPipeline(t *testing.T) {
mockPipelineName := "pipeline-dinder-badgoose-repo"
mockError := errors.New("mockError")
mockTime := time.Now()
mockArn := "arn:aws:codepipeline:us-west-2:1234567890:pipeline-dinder-badgoose-repo"
mockSourceStage := &codepipeline.StageDeclaration{
Name: aws.String("Source"),
Actions: []*codepipeline.ActionDeclaration{
{
ActionTypeId: &codepipeline.ActionTypeId{
Category: aws.String("Source"),
Owner: aws.String("ThirdParty"),
Provider: aws.String("GitHub"),
Version: aws.String("1"),
},
Configuration: map[string]*string{
"Owner": aws.String("badgoose"),
"Repo": aws.String("repo"),
"Branch": aws.String("main"),
"OAuthToken": aws.String("****"),
},
Name: aws.String("SourceCodeFor-dinder"),
OutputArtifacts: []*codepipeline.OutputArtifact{
{
Name: aws.String("SCCheckoutArtifact"),
},
},
RunOrder: aws.Int64(1),
},
},
}
mockBuildStage := &codepipeline.StageDeclaration{
Name: aws.String("Build"),
Actions: []*codepipeline.ActionDeclaration{
{
ActionTypeId: &codepipeline.ActionTypeId{
Category: aws.String("Build"),
Owner: aws.String("AWS"),
Provider: aws.String("CodeBuild"),
Version: aws.String("1"),
},
Configuration: map[string]*string{
"ProjectName": aws.String("pipeline-dinder-badgoose-repo-BuildProject"),
},
InputArtifacts: []*codepipeline.InputArtifact{
{
Name: aws.String("SCCheckoutArtifact"),
},
},
Name: aws.String("Build"),
OutputArtifacts: []*codepipeline.OutputArtifact{
{
Name: aws.String("BuildOutput"),
},
},
RunOrder: aws.Int64(1),
},
},
}
mockTestStage := &codepipeline.StageDeclaration{
Name: aws.String("DeployTo-test"),
Actions: []*codepipeline.ActionDeclaration{
{
ActionTypeId: &codepipeline.ActionTypeId{
Category: aws.String("Deploy"),
Owner: aws.String("AWS"),
Provider: aws.String("CloudFormation"),
Version: aws.String("1"),
},
Configuration: map[string]*string{
"TemplatePath": aws.String("BuildOutput::infrastructure/test.stack.yml"),
"ActionMode": aws.String("CREATE_UPDATE"),
"Capabilities": aws.String("CAPABILITY_NAMED_IAM"),
"ChangeSetName": aws.String("dinder-test-test"),
"RoleArn": aws.String("arn:aws:iam::1234567890:role/trivia-test-CFNExecutionRole"),
"StackName": aws.String("dinder-test-test"),
"TemplateConfiguration": aws.String("BuildOutput::infrastructure/test-test.params.json"),
},
InputArtifacts: []*codepipeline.InputArtifact{
{Name: aws.String("BuildOutput")},
},
Name: aws.String("CreateOrUpdate-test-test"),
Region: aws.String("us-west-2"),
RoleArn: aws.String("arn:aws:iam::12344567890:role/dinder-test-EnvManagerRole"),
RunOrder: aws.Int64(2),
},
},
}
mockStages := []*codepipeline.StageDeclaration{mockSourceStage, mockBuildStage, mockTestStage}
mockStageWithNoAction := &codepipeline.StageDeclaration{
Name: aws.String("DummyStage"),
Actions: []*codepipeline.ActionDeclaration{},
}
mockOutput := &codepipeline.GetPipelineOutput{
Pipeline: &codepipeline.PipelineDeclaration{
Name: aws.String(mockPipelineName),
Stages: mockStages,
},
Metadata: &codepipeline.PipelineMetadata{
Created: &mockTime,
Updated: &mockTime,
PipelineArn: aws.String(mockArn),
},
}
tests := map[string]struct {
inPipelineName string
callMocks func(m codepipelineMocks)
expectedOut *Pipeline
expectedError error
}{
"happy path": {
inPipelineName: mockPipelineName,
callMocks: func(m codepipelineMocks) {
m.cp.EXPECT().GetPipeline(&codepipeline.GetPipelineInput{
Name: aws.String(mockPipelineName),
}).Return(mockOutput, nil)
},
expectedOut: &Pipeline{
Name: mockPipelineName,
Region: "us-west-2",
AccountID: "1234567890",
Stages: []*Stage{
{
Name: "Source",
Category: "Source",
Provider: "GitHub",
Details: "Repository: badgoose/repo",
},
{
Name: "Build",
Category: "Build",
Provider: "CodeBuild",
Details: "BuildProject: pipeline-dinder-badgoose-repo-BuildProject",
},
{
Name: "DeployTo-test",
Category: "Deploy",
Provider: "CloudFormation",
Details: "StackName: dinder-test-test",
},
},
CreatedAt: mockTime,
UpdatedAt: mockTime,
},
expectedError: nil,
},
"should only populate stage name if stage has no actions": {
inPipelineName: mockPipelineName,
callMocks: func(m codepipelineMocks) {
m.cp.EXPECT().GetPipeline(&codepipeline.GetPipelineInput{
Name: aws.String(mockPipelineName),
}).Return(
&codepipeline.GetPipelineOutput{
Pipeline: &codepipeline.PipelineDeclaration{
Name: aws.String(mockPipelineName),
Stages: []*codepipeline.StageDeclaration{mockSourceStage, mockStageWithNoAction},
},
Metadata: &codepipeline.PipelineMetadata{
Created: &mockTime,
Updated: &mockTime,
PipelineArn: aws.String(mockArn),
},
}, nil)
},
expectedOut: &Pipeline{
Name: mockPipelineName,
Region: "us-west-2",
AccountID: "1234567890",
Stages: []*Stage{
{
Name: "Source",
Category: "Source",
Provider: "GitHub",
Details: "Repository: badgoose/repo",
},
{
Name: "DummyStage",
Category: "",
Provider: "",
Details: "",
},
},
CreatedAt: mockTime,
UpdatedAt: mockTime,
},
expectedError: nil,
},
"should wrap error from codepipeline client": {
inPipelineName: mockPipelineName,
callMocks: func(m codepipelineMocks) {
m.cp.EXPECT().GetPipeline(&codepipeline.GetPipelineInput{
Name: aws.String(mockPipelineName),
}).Return(nil, mockError)
},
expectedOut: nil,
expectedError: fmt.Errorf("get pipeline %s: %w", mockPipelineName, mockError),
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockClient := mocks.NewMockapi(ctrl)
mockrgClient := mocks.NewMockresourceGetter(ctrl)
mocks := codepipelineMocks{
cp: mockClient,
rg: mockrgClient,
}
tc.callMocks(mocks)
cp := CodePipeline{
client: mockClient,
rgClient: mockrgClient,
}
// WHEN
actualOut, err := cp.GetPipeline(tc.inPipelineName)
// THEN
require.Equal(t, tc.expectedError, err)
require.Equal(t, tc.expectedOut, actualOut)
})
}
}
func TestCodePipeline_GetPipelineState(t *testing.T) {
mockPipelineName := "pipeline-dinder-badgoose-repo"
mockTime := time.Now()
mockOutput := &codepipeline.GetPipelineStateOutput{
PipelineName: aws.String(mockPipelineName),
StageStates: []*codepipeline.StageState{
{
ActionStates: []*codepipeline.ActionState{
{
ActionName: aws.String("action1"),
LatestExecution: &codepipeline.ActionExecution{Status: aws.String(codepipeline.ActionExecutionStatusSucceeded)},
},
{
ActionName: aws.String("action2"),
LatestExecution: &codepipeline.ActionExecution{Status: aws.String(codepipeline.ActionExecutionStatusSucceeded)},
},
},
StageName: aws.String("Source"),
},
{
InboundTransitionState: &codepipeline.TransitionState{Enabled: aws.Bool(true)},
ActionStates: []*codepipeline.ActionState{
{
ActionName: aws.String("action1"),
LatestExecution: &codepipeline.ActionExecution{Status: aws.String(codepipeline.ActionExecutionStatusFailed)},
},
{
ActionName: aws.String("action2"),
LatestExecution: &codepipeline.ActionExecution{Status: aws.String(codepipeline.ActionExecutionStatusInProgress)},
},
{
ActionName: aws.String("action3"),
LatestExecution: &codepipeline.ActionExecution{Status: aws.String(codepipeline.ActionExecutionStatusSucceeded)},
},
},
StageName: aws.String("Build"),
},
{
InboundTransitionState: &codepipeline.TransitionState{Enabled: aws.Bool(true)},
ActionStates: []*codepipeline.ActionState{
{
ActionName: aws.String("action1"),
LatestExecution: &codepipeline.ActionExecution{Status: aws.String(codepipeline.ActionExecutionStatusSucceeded)},
},
{
ActionName: aws.String("TestCommands"),
LatestExecution: &codepipeline.ActionExecution{Status: aws.String(codepipeline.ActionExecutionStatusFailed)},
},
},
StageName: aws.String("DeployTo-test"),
},
{
InboundTransitionState: &codepipeline.TransitionState{Enabled: aws.Bool(false)},
StageName: aws.String("DeployTo-prod"),
},
},
Updated: &mockTime,
}
mockError := errors.New("mockError")
tests := map[string]struct {
inPipelineName string
callMocks func(m codepipelineMocks)
expectedOut *PipelineState
expectedError error
}{
"happy path": {
inPipelineName: mockPipelineName,
callMocks: func(m codepipelineMocks) {
m.cp.EXPECT().GetPipelineState(&codepipeline.GetPipelineStateInput{
Name: aws.String(mockPipelineName),
}).Return(mockOutput, nil)
},
expectedOut: &PipelineState{
PipelineName: mockPipelineName,
StageStates: []*StageState{
{
StageName: "Source",
Actions: []StageAction{
{
Name: "action1",
Status: "Succeeded",
},
{
Name: "action2",
Status: "Succeeded",
},
},
Transition: "",
},
{
StageName: "Build",
Actions: []StageAction{
{
Name: "action1",
Status: "Failed",
},
{
Name: "action2",
Status: "InProgress",
},
{
Name: "action3",
Status: "Succeeded",
},
},
Transition: "ENABLED",
},
{
StageName: "DeployTo-test",
Actions: []StageAction{
{
Name: "action1",
Status: "Succeeded",
},
{
Name: "TestCommands",
Status: "Failed",
},
},
Transition: "ENABLED",
},
{
StageName: "DeployTo-prod",
Transition: "DISABLED",
},
},
UpdatedAt: mockTime,
},
expectedError: nil,
},
"should wrap error from CodePipeline client": {
inPipelineName: mockPipelineName,
callMocks: func(m codepipelineMocks) {
m.cp.EXPECT().GetPipelineState(&codepipeline.GetPipelineStateInput{
Name: aws.String(mockPipelineName),
}).Return(nil, mockError)
},
expectedOut: nil,
expectedError: fmt.Errorf("get pipeline state %s: %w", mockPipelineName, mockError),
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockClient := mocks.NewMockapi(ctrl)
mocks := codepipelineMocks{
cp: mockClient,
}
tc.callMocks(mocks)
cp := CodePipeline{
client: mockClient,
}
// WHEN
actualOut, err := cp.GetPipelineState(tc.inPipelineName)
// THEN
require.Equal(t, tc.expectedError, err)
require.Equal(t, tc.expectedOut, actualOut)
})
}
}
func TestCodePipeline_RetryStageExecution(t *testing.T) {
mockPipelineName := "pipeline-dinder-badgoose-repo"
mockStageName := "Source"
failedActions := codepipeline.StageRetryModeFailedActions
notRetryable := codepipeline.StageNotRetryableException{}
mockPipelineExecutionID := aws.String("12345678-fake-exec-utio-nid987654321")
mockBadOutput := &codepipeline.ListPipelineExecutionsOutput{
PipelineExecutionSummaries: []*codepipeline.PipelineExecutionSummary{},
}
mockErr := errors.New("some error")
mockOutput := &codepipeline.RetryStageExecutionOutput{
PipelineExecutionId: aws.String("12345678-fake-exec-utio-nid987654321"),
}
tests := map[string]struct {
callMocks func(m codepipelineMocks)
expectedOut *string
expectedError error
}{
"returns nil when executes as expected": {
callMocks: func(m codepipelineMocks) {
m.cp.EXPECT().ListPipelineExecutions(
&codepipeline.ListPipelineExecutionsInput{
MaxResults: aws.Int64(1),
PipelineName: aws.String(mockPipelineName)}).Return(&codepipeline.ListPipelineExecutionsOutput{
PipelineExecutionSummaries: []*codepipeline.PipelineExecutionSummary{
{
PipelineExecutionId: aws.String("12345678-fake-exec-utio-nid987654321"),
},
},
}, nil)
m.cp.EXPECT().RetryStageExecution(
&codepipeline.RetryStageExecutionInput{
PipelineExecutionId: mockPipelineExecutionID,
PipelineName: aws.String(mockPipelineName),
RetryMode: aws.String(failedActions),
StageName: aws.String(mockStageName),
}).Return(mockOutput, nil)
},
expectedOut: nil,
},
"catches error and returns nil if pipeline succeeds before failing so not a 'retry'": {
callMocks: func(m codepipelineMocks) {
m.cp.EXPECT().ListPipelineExecutions(
&codepipeline.ListPipelineExecutionsInput{
MaxResults: aws.Int64(1),
PipelineName: aws.String(mockPipelineName)}).Return(&codepipeline.ListPipelineExecutionsOutput{
PipelineExecutionSummaries: []*codepipeline.PipelineExecutionSummary{
{
PipelineExecutionId: aws.String("12345678-fake-exec-utio-nid987654321"),
},
},
}, nil)
m.cp.EXPECT().RetryStageExecution(
&codepipeline.RetryStageExecutionInput{
PipelineExecutionId: mockPipelineExecutionID,
PipelineName: aws.String(mockPipelineName),
RetryMode: aws.String(failedActions),
StageName: aws.String(mockStageName),
}).Return(nil, notRetryable.OrigErr()) // OrigErr always returns nil, so may not actually catch the StageNotRetryableException
},
expectedOut: nil,
},
"returns wrapped error if ListPipelineExecutions fails": {
callMocks: func(m codepipelineMocks) {
m.cp.EXPECT().ListPipelineExecutions(
&codepipeline.ListPipelineExecutionsInput{
MaxResults: aws.Int64(1),
PipelineName: aws.String(mockPipelineName)}).Return(nil, mockErr)
m.cp.EXPECT().RetryStageExecution(
&codepipeline.RetryStageExecutionInput{
PipelineExecutionId: mockPipelineExecutionID,
PipelineName: aws.String(mockPipelineName),
RetryMode: aws.String(failedActions),
StageName: aws.String(mockStageName),
}).Times(0)
},
expectedOut: nil,
expectedError: fmt.Errorf("retrieve pipeline execution ID: list pipeline execution for pipeline-dinder-badgoose-repo: some error"),
},
"returns wrapped error if no pipeline execution IDs are returned": {
callMocks: func(m codepipelineMocks) {
m.cp.EXPECT().ListPipelineExecutions(
&codepipeline.ListPipelineExecutionsInput{
MaxResults: aws.Int64(1),
PipelineName: aws.String(mockPipelineName)}).Return(mockBadOutput, nil)
m.cp.EXPECT().RetryStageExecution(
&codepipeline.RetryStageExecutionInput{
PipelineExecutionId: mockPipelineExecutionID,
PipelineName: aws.String(mockPipelineName),
RetryMode: aws.String(failedActions),
StageName: aws.String(mockStageName),
}).Times(0)
},
expectedOut: nil,
expectedError: fmt.Errorf("retrieve pipeline execution ID: no pipeline execution IDs found for pipeline-dinder-badgoose-repo"),
},
"returns wrapped error if RetryStageExecution fails": {
callMocks: func(m codepipelineMocks) {
m.cp.EXPECT().ListPipelineExecutions(
&codepipeline.ListPipelineExecutionsInput{
MaxResults: aws.Int64(1),
PipelineName: aws.String(mockPipelineName)}).Return(&codepipeline.ListPipelineExecutionsOutput{
PipelineExecutionSummaries: []*codepipeline.PipelineExecutionSummary{
{
PipelineExecutionId: aws.String("12345678-fake-exec-utio-nid987654321"),
},
},
}, nil)
m.cp.EXPECT().RetryStageExecution(
&codepipeline.RetryStageExecutionInput{
PipelineExecutionId: mockPipelineExecutionID,
PipelineName: aws.String(mockPipelineName),
RetryMode: aws.String(failedActions),
StageName: aws.String(mockStageName),
}).Return(nil, mockErr)
},
expectedOut: nil,
expectedError: fmt.Errorf("retry pipeline source stage: some error"),
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockClient := mocks.NewMockapi(ctrl)
mockrgClient := mocks.NewMockresourceGetter(ctrl)
mocks := codepipelineMocks{
cp: mockClient,
rg: mockrgClient,
}
tc.callMocks(mocks)
cp := CodePipeline{
client: mockClient,
rgClient: mockrgClient,
}
// WHEN
actualErr := cp.RetryStageExecution(mockPipelineName, mockStageName)
// THEN
if actualErr != nil {
require.EqualError(t, actualErr, tc.expectedError.Error())
}
})
}
}
| 582 |
copilot-cli | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: ./internal/pkg/aws/codepipeline/codepipeline.go
// Package mocks is a generated GoMock package.
package mocks
import (
reflect "reflect"
codepipeline "github.com/aws/aws-sdk-go/service/codepipeline"
resourcegroups "github.com/aws/copilot-cli/internal/pkg/aws/resourcegroups"
gomock "github.com/golang/mock/gomock"
)
// Mockapi is a mock of api interface.
type Mockapi struct {
ctrl *gomock.Controller
recorder *MockapiMockRecorder
}
// MockapiMockRecorder is the mock recorder for Mockapi.
type MockapiMockRecorder struct {
mock *Mockapi
}
// NewMockapi creates a new mock instance.
func NewMockapi(ctrl *gomock.Controller) *Mockapi {
mock := &Mockapi{ctrl: ctrl}
mock.recorder = &MockapiMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *Mockapi) EXPECT() *MockapiMockRecorder {
return m.recorder
}
// GetPipeline mocks base method.
func (m *Mockapi) GetPipeline(arg0 *codepipeline.GetPipelineInput) (*codepipeline.GetPipelineOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetPipeline", arg0)
ret0, _ := ret[0].(*codepipeline.GetPipelineOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetPipeline indicates an expected call of GetPipeline.
func (mr *MockapiMockRecorder) GetPipeline(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPipeline", reflect.TypeOf((*Mockapi)(nil).GetPipeline), arg0)
}
// GetPipelineState mocks base method.
func (m *Mockapi) GetPipelineState(arg0 *codepipeline.GetPipelineStateInput) (*codepipeline.GetPipelineStateOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetPipelineState", arg0)
ret0, _ := ret[0].(*codepipeline.GetPipelineStateOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetPipelineState indicates an expected call of GetPipelineState.
func (mr *MockapiMockRecorder) GetPipelineState(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPipelineState", reflect.TypeOf((*Mockapi)(nil).GetPipelineState), arg0)
}
// ListPipelineExecutions mocks base method.
func (m *Mockapi) ListPipelineExecutions(input *codepipeline.ListPipelineExecutionsInput) (*codepipeline.ListPipelineExecutionsOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListPipelineExecutions", input)
ret0, _ := ret[0].(*codepipeline.ListPipelineExecutionsOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ListPipelineExecutions indicates an expected call of ListPipelineExecutions.
func (mr *MockapiMockRecorder) ListPipelineExecutions(input interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListPipelineExecutions", reflect.TypeOf((*Mockapi)(nil).ListPipelineExecutions), input)
}
// RetryStageExecution mocks base method.
func (m *Mockapi) RetryStageExecution(input *codepipeline.RetryStageExecutionInput) (*codepipeline.RetryStageExecutionOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RetryStageExecution", input)
ret0, _ := ret[0].(*codepipeline.RetryStageExecutionOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// RetryStageExecution indicates an expected call of RetryStageExecution.
func (mr *MockapiMockRecorder) RetryStageExecution(input interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RetryStageExecution", reflect.TypeOf((*Mockapi)(nil).RetryStageExecution), input)
}
// MockresourceGetter is a mock of resourceGetter interface.
type MockresourceGetter struct {
ctrl *gomock.Controller
recorder *MockresourceGetterMockRecorder
}
// MockresourceGetterMockRecorder is the mock recorder for MockresourceGetter.
type MockresourceGetterMockRecorder struct {
mock *MockresourceGetter
}
// NewMockresourceGetter creates a new mock instance.
func NewMockresourceGetter(ctrl *gomock.Controller) *MockresourceGetter {
mock := &MockresourceGetter{ctrl: ctrl}
mock.recorder = &MockresourceGetterMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockresourceGetter) EXPECT() *MockresourceGetterMockRecorder {
return m.recorder
}
// GetResourcesByTags mocks base method.
func (m *MockresourceGetter) GetResourcesByTags(resourceType string, tags map[string]string) ([]*resourcegroups.Resource, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetResourcesByTags", resourceType, tags)
ret0, _ := ret[0].([]*resourcegroups.Resource)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetResourcesByTags indicates an expected call of GetResourcesByTags.
func (mr *MockresourceGetterMockRecorder) GetResourcesByTags(resourceType, tags interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetResourcesByTags", reflect.TypeOf((*MockresourceGetter)(nil).GetResourcesByTags), resourceType, tags)
}
| 135 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package codestar provides a client to make API requests to AWS CodeStar Connections.
package codestar
import (
"context"
"fmt"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/codestarconnections"
)
type api interface {
GetConnection(input *codestarconnections.GetConnectionInput) (*codestarconnections.GetConnectionOutput, error)
ListConnections(input *codestarconnections.ListConnectionsInput) (*codestarconnections.ListConnectionsOutput, error)
}
// CodeStar represents a client to make requests to AWS CodeStarConnections.
type CodeStar struct {
client api
}
// New creates a new CodeStar client.
func New(s *session.Session) *CodeStar {
return &CodeStar{
codestarconnections.New(s),
}
}
// WaitUntilConnectionStatusAvailable blocks until the connection status has been updated from `PENDING` to `AVAILABLE` or until the max attempt window expires.
func (c *CodeStar) WaitUntilConnectionStatusAvailable(ctx context.Context, connectionARN string) error {
var interval time.Duration // Defaults to 0.
for {
select {
case <-ctx.Done():
return fmt.Errorf("timed out waiting for connection %s status to change from PENDING to AVAILABLE", connectionARN)
case <-time.After(interval):
output, err := c.client.GetConnection(&codestarconnections.GetConnectionInput{ConnectionArn: aws.String(connectionARN)})
if err != nil {
return fmt.Errorf("get connection details for %s: %w", connectionARN, err)
}
if aws.StringValue(output.Connection.ConnectionStatus) == codestarconnections.ConnectionStatusAvailable {
return nil
}
interval = 5 * time.Second
}
}
}
// GetConnectionARN retrieves all of the CSC connections in the current account and returns the ARN correlating to the
// connection name passed in.
func (c *CodeStar) GetConnectionARN(connectionName string) (connectionARN string, err error) {
output, err := c.client.ListConnections(&codestarconnections.ListConnectionsInput{})
if err != nil {
return "", fmt.Errorf("get list of connections in AWS account: %w", err)
}
connections := output.Connections
for output.NextToken != nil {
output, err = c.client.ListConnections(&codestarconnections.ListConnectionsInput{
NextToken: output.NextToken,
})
if err != nil {
return "", fmt.Errorf("get list of connections in AWS account: %w", err)
}
connections = append(connections, output.Connections...)
}
for _, connection := range connections {
if aws.StringValue(connection.ConnectionName) == connectionName {
// Duplicate connection names are supposed to result in replacement, so okay to return first match.
return aws.StringValue(connection.ConnectionArn), nil
}
}
return "", fmt.Errorf("cannot find a connectionARN associated with %s", connectionName)
}
| 80 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package codestar
import (
"context"
"errors"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/codestarconnections"
"github.com/aws/copilot-cli/internal/pkg/aws/codestar/mocks"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
func TestCodestar_WaitUntilStatusAvailable(t *testing.T) {
t.Run("times out if connection status not changed to available in allotted time", func(t *testing.T) {
// GIVEN
ctx, cancel := context.WithDeadline(context.Background(), time.Now())
defer cancel()
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := mocks.NewMockapi(ctrl)
m.EXPECT().GetConnection(gomock.Any()).Return(
&codestarconnections.GetConnectionOutput{Connection: &codestarconnections.Connection{
ConnectionStatus: aws.String(codestarconnections.ConnectionStatusPending),
},
}, nil).AnyTimes()
connection := &CodeStar{
client: m,
}
connectionARN := "mockConnectionARN"
// WHEN
err := connection.WaitUntilConnectionStatusAvailable(ctx, connectionARN)
// THEN
require.EqualError(t, err, "timed out waiting for connection mockConnectionARN status to change from PENDING to AVAILABLE")
})
t.Run("returns a wrapped error on GetConnection call failure", func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := mocks.NewMockapi(ctrl)
m.EXPECT().GetConnection(gomock.Any()).Return(nil, errors.New("some error"))
connection := &CodeStar{
client: m,
}
connectionARN := "mockConnectionARN"
// WHEN
err := connection.WaitUntilConnectionStatusAvailable(context.Background(), connectionARN)
// THEN
require.EqualError(t, err, "get connection details for mockConnectionARN: some error")
})
t.Run("waits until connection status is returned as 'available' and exits gracefully", func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := mocks.NewMockapi(ctrl)
connection := &CodeStar{
client: m,
}
connectionARN := "mockConnectionARN"
m.EXPECT().GetConnection(&codestarconnections.GetConnectionInput{
ConnectionArn: aws.String(connectionARN),
}).Return(
&codestarconnections.GetConnectionOutput{Connection: &codestarconnections.Connection{
ConnectionStatus: aws.String(codestarconnections.ConnectionStatusAvailable),
},
}, nil)
// WHEN
err := connection.WaitUntilConnectionStatusAvailable(context.Background(), connectionARN)
// THEN
require.NoError(t, err)
})
}
func TestCodeStar_GetConnectionARN(t *testing.T) {
t.Run("returns wrapped error if ListConnections is unsuccessful", func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
m := mocks.NewMockapi(ctrl)
m.EXPECT().ListConnections(gomock.Any()).Return(nil, errors.New("some error"))
connection := &CodeStar{
client: m,
}
// WHEN
ARN, err := connection.GetConnectionARN("someConnectionName")
// THEN
require.EqualError(t, err, "get list of connections in AWS account: some error")
require.Equal(t, "", ARN)
})
t.Run("returns an error if no connections in the account match the one in the pipeline manifest", func(t *testing.T) {
// GIVEN
connectionName := "string cheese"
ctrl := gomock.NewController(t)
m := mocks.NewMockapi(ctrl)
m.EXPECT().ListConnections(gomock.Any()).Return(
&codestarconnections.ListConnectionsOutput{
Connections: []*codestarconnections.Connection{
{ConnectionName: aws.String("gouda")},
{ConnectionName: aws.String("fontina")},
{ConnectionName: aws.String("brie")},
},
}, nil)
connection := &CodeStar{
client: m,
}
// WHEN
ARN, err := connection.GetConnectionARN(connectionName)
// THEN
require.Equal(t, "", ARN)
require.EqualError(t, err, "cannot find a connectionARN associated with string cheese")
})
t.Run("returns a match", func(t *testing.T) {
// GIVEN
connectionName := "string cheese"
ctrl := gomock.NewController(t)
m := mocks.NewMockapi(ctrl)
m.EXPECT().ListConnections(gomock.Any()).Return(
&codestarconnections.ListConnectionsOutput{
Connections: []*codestarconnections.Connection{
{
ConnectionName: aws.String("gouda"),
ConnectionArn: aws.String("notThisOne"),
},
{
ConnectionName: aws.String("string cheese"),
ConnectionArn: aws.String("thisCheesyFakeARN"),
},
{
ConnectionName: aws.String("fontina"),
ConnectionArn: aws.String("norThisOne"),
},
},
}, nil)
connection := &CodeStar{
client: m,
}
// WHEN
ARN, err := connection.GetConnectionARN(connectionName)
// THEN
require.Equal(t, "thisCheesyFakeARN", ARN)
require.NoError(t, err)
})
t.Run("checks all connections and returns a match when paginated", func(t *testing.T) {
// GIVEN
connectionName := "string cheese"
mockNextToken := "next"
ctrl := gomock.NewController(t)
m := mocks.NewMockapi(ctrl)
m.EXPECT().ListConnections(gomock.Any()).Return(
&codestarconnections.ListConnectionsOutput{
Connections: []*codestarconnections.Connection{
{
ConnectionName: aws.String("gouda"),
ConnectionArn: aws.String("notThisOne"),
},
{
ConnectionName: aws.String("fontina"),
ConnectionArn: aws.String("thisCheesyFakeARN"),
},
},
NextToken: &mockNextToken,
}, nil)
m.EXPECT().ListConnections(&codestarconnections.ListConnectionsInput{
NextToken: &mockNextToken,
}).Return(
&codestarconnections.ListConnectionsOutput{
Connections: []*codestarconnections.Connection{
{
ConnectionName: aws.String("string cheese"),
ConnectionArn: aws.String("thisOne"),
},
},
}, nil)
connection := &CodeStar{
client: m,
}
// WHEN
ARN, err := connection.GetConnectionARN(connectionName)
// THEN
require.Equal(t, "thisOne", ARN)
require.NoError(t, err)
})
}
| 217 |
copilot-cli | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: ./internal/pkg/aws/codestar/codestar.go
// Package mocks is a generated GoMock package.
package mocks
import (
reflect "reflect"
codestarconnections "github.com/aws/aws-sdk-go/service/codestarconnections"
gomock "github.com/golang/mock/gomock"
)
// Mockapi is a mock of api interface.
type Mockapi struct {
ctrl *gomock.Controller
recorder *MockapiMockRecorder
}
// MockapiMockRecorder is the mock recorder for Mockapi.
type MockapiMockRecorder struct {
mock *Mockapi
}
// NewMockapi creates a new mock instance.
func NewMockapi(ctrl *gomock.Controller) *Mockapi {
mock := &Mockapi{ctrl: ctrl}
mock.recorder = &MockapiMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *Mockapi) EXPECT() *MockapiMockRecorder {
return m.recorder
}
// GetConnection mocks base method.
func (m *Mockapi) GetConnection(input *codestarconnections.GetConnectionInput) (*codestarconnections.GetConnectionOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetConnection", input)
ret0, _ := ret[0].(*codestarconnections.GetConnectionOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetConnection indicates an expected call of GetConnection.
func (mr *MockapiMockRecorder) GetConnection(input interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetConnection", reflect.TypeOf((*Mockapi)(nil).GetConnection), input)
}
// ListConnections mocks base method.
func (m *Mockapi) ListConnections(input *codestarconnections.ListConnectionsInput) (*codestarconnections.ListConnectionsOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListConnections", input)
ret0, _ := ret[0].(*codestarconnections.ListConnectionsOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ListConnections indicates an expected call of ListConnections.
func (mr *MockapiMockRecorder) ListConnections(input interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListConnections", reflect.TypeOf((*Mockapi)(nil).ListConnections), input)
}
| 66 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package ec2 provides a client to make API requests to Amazon Elastic Compute Cloud.
package ec2
import (
"fmt"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
)
const (
defaultForAZFilterName = "default-for-az"
internetGatewayIDPrefix = "igw-"
cloudFrontPrefixListName = "com.amazonaws.global.cloudfront.origin-facing"
// FmtTagFilter is the filter name format for tag filters
FmtTagFilter = "tag:%s"
tagKeyFilter = "tag-key"
)
var (
// FilterForDefaultVPCSubnets is a pre-defined filter for the default subnets at the availability zone.
FilterForDefaultVPCSubnets = Filter{
Name: defaultForAZFilterName,
Values: []string{"true"},
}
)
type api interface {
DescribeSubnets(*ec2.DescribeSubnetsInput) (*ec2.DescribeSubnetsOutput, error)
DescribeSecurityGroups(*ec2.DescribeSecurityGroupsInput) (*ec2.DescribeSecurityGroupsOutput, error)
DescribeVpcs(input *ec2.DescribeVpcsInput) (*ec2.DescribeVpcsOutput, error)
DescribeVpcAttribute(input *ec2.DescribeVpcAttributeInput) (*ec2.DescribeVpcAttributeOutput, error)
DescribeNetworkInterfaces(input *ec2.DescribeNetworkInterfacesInput) (*ec2.DescribeNetworkInterfacesOutput, error)
DescribeRouteTables(input *ec2.DescribeRouteTablesInput) (*ec2.DescribeRouteTablesOutput, error)
DescribeAvailabilityZones(input *ec2.DescribeAvailabilityZonesInput) (*ec2.DescribeAvailabilityZonesOutput, error)
DescribeManagedPrefixLists(input *ec2.DescribeManagedPrefixListsInput) (*ec2.DescribeManagedPrefixListsOutput, error)
}
// Filter contains the name and values of a filter.
type Filter struct {
// Name of a filter that will be applied to subnets,
// for available filter names see: https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeSubnets.html.
Name string
// Value of the filter.
Values []string
}
// FilterForTags takes a key and optional values to construct an EC2 filter.
func FilterForTags(key string, values ...string) Filter {
if len(values) == 0 {
return Filter{Name: tagKeyFilter, Values: []string{key}}
}
return Filter{
Name: fmt.Sprintf(FmtTagFilter, key),
Values: values,
}
}
// EC2 wraps an AWS EC2 client.
type EC2 struct {
client api
}
// New returns a EC2 configured against the input session.
func New(s *session.Session) *EC2 {
return &EC2{
client: ec2.New(s),
}
}
// Resource contains the ID and name of a EC2 resource.
type Resource struct {
ID string
Name string
}
// VPC contains the ID and name of a VPC.
type VPC struct {
Resource
}
// Subnet contains the ID and name of a subnet.
type Subnet struct {
Resource
CIDRBlock string
}
// AZ represents an availability zone.
type AZ Resource
// String formats the elements of a VPC into a display-ready string.
// For example: VPCResource{"ID": "vpc-0576efeea396efee2", "Name": "video-store-test"}
// will return "vpc-0576efeea396efee2 (copilot-video-store-test)".
// while VPCResource{"ID": "subnet-018ccb78d353cec9b", "Name": "public-subnet-1"}
// will return "subnet-018ccb78d353cec9b (public-subnet-1)"
func (r *Resource) String() string {
if r.Name != "" {
return fmt.Sprintf("%s (%s)", r.ID, r.Name)
}
return r.ID
}
// ExtractVPC extracts the vpc ID from the resource display string.
// For example: vpc-0576efeea396efee2 (copilot-video-store-test)
// will return VPC{ID: "vpc-0576efeea396efee2", Name: "copilot-video-store-test"}.
func ExtractVPC(label string) (*VPC, error) {
resource, err := extractResource(label)
if err != nil {
return nil, err
}
return &VPC{
Resource: *resource,
}, nil
}
// ExtractSubnet extracts the subnet ID from the resource display string.
func ExtractSubnet(label string) (*Subnet, error) {
resource, err := extractResource(label)
if err != nil {
return nil, err
}
return &Subnet{
Resource: *resource,
}, nil
}
func extractResource(label string) (*Resource, error) {
if label == "" {
return nil, fmt.Errorf("extract resource ID from string: %s", label)
}
splitResource := strings.SplitN(label, " ", 2)
// TODO: switch to regex to make more robust
var name string
if len(splitResource) == 2 {
name = strings.Trim(splitResource[1], "()")
}
return &Resource{
ID: splitResource[0],
Name: name,
}, nil
}
// PublicIP returns the public ip associated with the network interface.
func (c *EC2) PublicIP(eni string) (string, error) {
response, err := c.client.DescribeNetworkInterfaces(&ec2.DescribeNetworkInterfacesInput{
NetworkInterfaceIds: aws.StringSlice([]string{eni}),
})
if err != nil {
return "", fmt.Errorf("describe network interface with ENI %s: %w", eni, err)
}
// `response.NetworkInterfaces` contains at least one result; if no matching ENI is found, the API call will return
// an error instead of an empty list of `NetworkInterfaces` (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeNetworkInterfaces.html)
association := response.NetworkInterfaces[0].Association
if association == nil {
return "", fmt.Errorf("no association information found for ENI %s", eni)
}
return aws.StringValue(association.PublicIp), nil
}
// ListVPCs returns names and IDs (or just IDs, if Name tag does not exist) of all VPCs.
func (c *EC2) ListVPCs() ([]VPC, error) {
var ec2vpcs []*ec2.Vpc
response, err := c.client.DescribeVpcs(&ec2.DescribeVpcsInput{})
if err != nil {
return nil, fmt.Errorf("describe VPCs: %w", err)
}
ec2vpcs = append(ec2vpcs, response.Vpcs...)
for response.NextToken != nil {
response, err = c.client.DescribeVpcs(&ec2.DescribeVpcsInput{
NextToken: response.NextToken,
})
if err != nil {
return nil, fmt.Errorf("describe VPCs: %w", err)
}
ec2vpcs = append(ec2vpcs, response.Vpcs...)
}
var vpcs []VPC
for _, vpc := range ec2vpcs {
var name string
for _, tag := range vpc.Tags {
if aws.StringValue(tag.Key) == "Name" {
name = aws.StringValue(tag.Value)
}
}
vpcs = append(vpcs, VPC{
Resource: Resource{
ID: aws.StringValue(vpc.VpcId),
Name: name,
},
})
}
return vpcs, nil
}
// ListAZs returns the list of opted-in and available availability zones.
func (c *EC2) ListAZs() ([]AZ, error) {
resp, err := c.client.DescribeAvailabilityZones(&ec2.DescribeAvailabilityZonesInput{
Filters: []*ec2.Filter{
{
Name: aws.String("zone-type"),
Values: aws.StringSlice([]string{"availability-zone"}),
},
{
Name: aws.String("state"),
Values: aws.StringSlice([]string{"available"}),
},
},
})
if err != nil {
return nil, fmt.Errorf("describe availability zones: %w", err)
}
var out []AZ
for _, az := range resp.AvailabilityZones {
out = append(out, AZ{
ID: aws.StringValue(az.ZoneId),
Name: aws.StringValue(az.ZoneName),
})
}
return out, nil
}
// HasDNSSupport returns if DNS resolution is enabled for the VPC.
func (c *EC2) HasDNSSupport(vpcID string) (bool, error) {
resp, err := c.client.DescribeVpcAttribute(&ec2.DescribeVpcAttributeInput{
VpcId: aws.String(vpcID),
Attribute: aws.String(ec2.VpcAttributeNameEnableDnsSupport),
})
if err != nil {
return false, fmt.Errorf("describe %s attribute for VPC %s: %w", ec2.VpcAttributeNameEnableDnsSupport, vpcID, err)
}
return aws.BoolValue(resp.EnableDnsSupport.Value), nil
}
// VPCSubnets are all subnets within a VPC.
type VPCSubnets struct {
Public []Subnet
Private []Subnet
}
// ListVPCSubnets lists all subnets with a given VPC ID. Note that public subnets
// are subnets associated with an internet gateway through a route table.
// And the rest of the subnets are private.
func (c *EC2) ListVPCSubnets(vpcID string) (*VPCSubnets, error) {
vpcFilter := Filter{
Name: "vpc-id",
Values: []string{vpcID},
}
routeTables, err := c.routeTables(vpcFilter)
if err != nil {
return nil, err
}
rtIndex := indexRouteTables(routeTables)
var publicSubnets, privateSubnets []Subnet
respSubnets, err := c.subnets(vpcFilter)
if err != nil {
return nil, err
}
for _, subnet := range respSubnets {
var name string
for _, tag := range subnet.Tags {
if aws.StringValue(tag.Key) == "Name" {
name = aws.StringValue(tag.Value)
}
}
s := Subnet{
Resource: Resource{
ID: aws.StringValue(subnet.SubnetId),
Name: name,
},
CIDRBlock: aws.StringValue(subnet.CidrBlock),
}
if rtIndex.IsPublicSubnet(s.ID) {
publicSubnets = append(publicSubnets, s)
} else {
privateSubnets = append(privateSubnets, s)
}
}
return &VPCSubnets{
Public: publicSubnets,
Private: privateSubnets,
}, nil
}
// SubnetIDs finds the subnet IDs with optional filters.
func (c *EC2) SubnetIDs(filters ...Filter) ([]string, error) {
subnets, err := c.subnets(filters...)
if err != nil {
return nil, err
}
subnetIDs := make([]string, len(subnets))
for idx, subnet := range subnets {
subnetIDs[idx] = aws.StringValue(subnet.SubnetId)
}
return subnetIDs, nil
}
// SecurityGroups finds the security group IDs with optional filters.
func (c *EC2) SecurityGroups(filters ...Filter) ([]string, error) {
inputFilters := toEC2Filter(filters)
response, err := c.client.DescribeSecurityGroups(&ec2.DescribeSecurityGroupsInput{
Filters: inputFilters,
})
if err != nil {
return nil, fmt.Errorf("describe security groups: %w", err)
}
securityGroups := make([]string, len(response.SecurityGroups))
for idx, sg := range response.SecurityGroups {
securityGroups[idx] = aws.StringValue(sg.GroupId)
}
return securityGroups, nil
}
func (c *EC2) subnets(filters ...Filter) ([]*ec2.Subnet, error) {
inputFilters := toEC2Filter(filters)
var subnets []*ec2.Subnet
response, err := c.client.DescribeSubnets(&ec2.DescribeSubnetsInput{
Filters: inputFilters,
})
if err != nil {
return nil, fmt.Errorf("describe subnets: %w", err)
}
subnets = append(subnets, response.Subnets...)
for response.NextToken != nil {
response, err = c.client.DescribeSubnets(&ec2.DescribeSubnetsInput{
Filters: inputFilters,
NextToken: response.NextToken,
})
if err != nil {
return nil, fmt.Errorf("describe subnets: %w", err)
}
subnets = append(subnets, response.Subnets...)
}
if len(subnets) == 0 {
return nil, fmt.Errorf("cannot find any subnets")
}
return subnets, nil
}
func (c *EC2) routeTables(filters ...Filter) ([]*ec2.RouteTable, error) {
var routeTables []*ec2.RouteTable
input := &ec2.DescribeRouteTablesInput{
Filters: toEC2Filter(filters),
}
for {
resp, err := c.client.DescribeRouteTables(input)
if err != nil {
return nil, fmt.Errorf("describe route tables: %w", err)
}
routeTables = append(routeTables, resp.RouteTables...)
if resp.NextToken == nil {
break
}
input.NextToken = resp.NextToken
}
return routeTables, nil
}
func toEC2Filter(filters []Filter) []*ec2.Filter {
var ec2Filter []*ec2.Filter
for _, filter := range filters {
ec2Filter = append(ec2Filter, &ec2.Filter{
Name: aws.String(filter.Name),
Values: aws.StringSlice(filter.Values),
})
}
return ec2Filter
}
type routeTable ec2.RouteTable
// IsMain returns true if the route table is the default route table for the VPC.
// If a subnet is not associated with a particular route table, then it will default to the main route table.
func (rt *routeTable) IsMain() bool {
for _, association := range rt.Associations {
if aws.BoolValue(association.Main) {
return true
}
}
return false
}
// HasIGW returns true if the route table has a route to an internet gateway.
func (rt *routeTable) HasIGW() bool {
for _, route := range rt.Routes {
if strings.HasPrefix(aws.StringValue(route.GatewayId), internetGatewayIDPrefix) {
return true
}
}
return false
}
// AssociatedSubnets returns the list of subnet IDs associated with the route table.
func (rt *routeTable) AssociatedSubnets() []string {
var subnetIDs []string
for _, association := range rt.Associations {
if association.SubnetId == nil {
continue
}
subnetIDs = append(subnetIDs, aws.StringValue(association.SubnetId))
}
return subnetIDs
}
// routeTableIndex holds cached data to quickly return information about route tables in a VPC.
type routeTableIndex struct {
// Route table that subnets default to. There is always one main table in the VPC.
mainTable *routeTable
// Explicit route table association for a subnet. A subnet can only be associated to one route table.
routeTableForSubnet map[string]*routeTable
}
func indexRouteTables(tables []*ec2.RouteTable) *routeTableIndex {
index := &routeTableIndex{
routeTableForSubnet: make(map[string]*routeTable),
}
for _, table := range tables { // Index all properties in a single pass.
table := (*routeTable)(table)
for _, subnetID := range table.AssociatedSubnets() {
index.routeTableForSubnet[subnetID] = table
}
if table.IsMain() {
index.mainTable = table
}
}
return index
}
// IsPublicSubnet returns true if the subnet has a route to an internet gateway.
// We consider the subnet to have internet access if there is an explicit route in the route table to an internet gateway.
// Or if there is an implicit route, where the subnet defaults to the main route table with an internet gateway.
func (idx *routeTableIndex) IsPublicSubnet(subnetID string) bool {
rt, ok := idx.routeTableForSubnet[subnetID]
if ok {
return rt.HasIGW()
}
return idx.mainTable.HasIGW()
}
// managedPrefixList returns the DescribeManagedPrefixListsOutput of a query by name.
func (c *EC2) managedPrefixList(prefixListName string) (*ec2.DescribeManagedPrefixListsOutput, error) {
prefixListOutput, err := c.client.DescribeManagedPrefixLists(&ec2.DescribeManagedPrefixListsInput{
Filters: []*ec2.Filter{
{
Name: aws.String("prefix-list-name"),
Values: aws.StringSlice([]string{prefixListName}),
},
},
})
if err != nil {
return nil, fmt.Errorf("describe managed prefix list with name %s: %w", prefixListName, err)
}
return prefixListOutput, nil
}
// CloudFrontManagedPrefixListID returns the PrefixListId of the associated cloudfront prefix list as a *string.
func (c *EC2) CloudFrontManagedPrefixListID() (string, error) {
prefixListsOutput, err := c.managedPrefixList(cloudFrontPrefixListName)
if err != nil {
return "", err
}
var ids []string
for _, v := range prefixListsOutput.PrefixLists {
ids = append(ids, *v.PrefixListId)
}
if len(ids) == 0 {
return "", fmt.Errorf("cannot find any prefix list with name: %s", cloudFrontPrefixListName)
}
if len(ids) > 1 {
return "", fmt.Errorf("found more than one prefix list with the name %s: %v", cloudFrontPrefixListName, ids)
}
return ids[0], nil
}
| 497 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package ec2
import (
"errors"
"fmt"
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/copilot-cli/internal/pkg/aws/ec2/mocks"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
var (
inAppEnvFilters = []Filter{
{
Name: fmt.Sprintf(FmtTagFilter, "copilot-application"),
Values: []string{"my-app"},
},
{
Name: fmt.Sprintf(FmtTagFilter, "copilot-environment"),
Values: []string{"my-env"},
},
}
subnet1 = &ec2.Subnet{
SubnetId: aws.String("subnet-1"),
MapPublicIpOnLaunch: aws.Bool(false),
}
subnet2 = &ec2.Subnet{
SubnetId: aws.String("subnet-2"),
MapPublicIpOnLaunch: aws.Bool(true),
}
subnet3 = &ec2.Subnet{
SubnetId: aws.String("subnet-3"),
MapPublicIpOnLaunch: aws.Bool(true),
}
)
func TestEC2_FilterForTags(t *testing.T) {
testCases := map[string]struct {
inValues []string
wanted Filter
}{
"with no values": {
wanted: Filter{
Name: "tag-key",
Values: []string{"mockKey"},
},
},
"with values": {
inValues: []string{"foo", "bar"},
wanted: Filter{
Name: "tag:mockKey",
Values: []string{"foo", "bar"},
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
filter := FilterForTags("mockKey", tc.inValues...)
require.Equal(t, tc.wanted, filter)
})
}
}
func TestEC2_extractResource(t *testing.T) {
testCases := map[string]struct {
displayString string
wantedError error
wantedResource *Resource
}{
"returns error if string is empty": {
displayString: "",
wantedError: fmt.Errorf("extract resource ID from string: "),
},
"returns just the VPC ID if no name present": {
displayString: "vpc-imagr8vpcstring",
wantedError: nil,
wantedResource: &Resource{
ID: "vpc-imagr8vpcstring",
},
},
"returns both the VPC ID and name if both present": {
displayString: "vpc-imagr8vpcstring (copilot-app-name-env)",
wantedError: nil,
wantedResource: &Resource{
ID: "vpc-imagr8vpcstring",
Name: "copilot-app-name-env",
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
resource, err := extractResource(tc.displayString)
if tc.wantedError != nil {
require.EqualError(t, tc.wantedError, err.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedResource, resource)
}
})
}
}
func TestEC2_ListVPC(t *testing.T) {
testCases := map[string]struct {
mockEC2Client func(m *mocks.Mockapi)
wantedError error
wantedVPC []VPC
}{
"fail to describe vpcs": {
mockEC2Client: func(m *mocks.Mockapi) {
m.EXPECT().DescribeVpcs(gomock.Any()).Return(nil, errors.New("some error"))
},
wantedError: fmt.Errorf("describe VPCs: some error"),
},
"success": {
mockEC2Client: func(m *mocks.Mockapi) {
m.EXPECT().DescribeVpcs(&ec2.DescribeVpcsInput{}).Return(&ec2.DescribeVpcsOutput{
Vpcs: []*ec2.Vpc{
{
VpcId: aws.String("mockVPCID1"),
},
},
NextToken: aws.String("mockNextToken"),
}, nil)
m.EXPECT().DescribeVpcs(&ec2.DescribeVpcsInput{
NextToken: aws.String("mockNextToken"),
}).Return(&ec2.DescribeVpcsOutput{
Vpcs: []*ec2.Vpc{
{
VpcId: aws.String("mockVPCID2"),
Tags: []*ec2.Tag{
{
Key: aws.String("Name"),
Value: aws.String("mockVPC2Name"),
},
},
},
},
}, nil)
},
wantedVPC: []VPC{
{
Resource: Resource{
ID: "mockVPCID1",
},
},
{
Resource: Resource{
ID: "mockVPCID2",
Name: "mockVPC2Name",
},
},
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
mockAPI := mocks.NewMockapi(ctrl)
tc.mockEC2Client(mockAPI)
ec2Client := EC2{
client: mockAPI,
}
vpcs, err := ec2Client.ListVPCs()
if tc.wantedError != nil {
require.EqualError(t, tc.wantedError, err.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedVPC, vpcs)
}
})
}
}
func TestEC2_ListAZs(t *testing.T) {
testCases := map[string]struct {
mockClient func(m *mocks.Mockapi)
wantedErr string
wantedAZs []AZ
}{
"return wrapped error on unexpected call error": {
mockClient: func(m *mocks.Mockapi) {
m.EXPECT().DescribeAvailabilityZones(gomock.Any()).Return(nil, errors.New("some error"))
},
wantedErr: "describe availability zones: some error",
},
"returns AZs that are available and opted-in": {
mockClient: func(m *mocks.Mockapi) {
m.EXPECT().DescribeAvailabilityZones(&ec2.DescribeAvailabilityZonesInput{
Filters: []*ec2.Filter{
{
Name: aws.String("zone-type"),
Values: aws.StringSlice([]string{"availability-zone"}),
},
{
Name: aws.String("state"),
Values: aws.StringSlice([]string{"available"}),
},
},
}).Return(&ec2.DescribeAvailabilityZonesOutput{
AvailabilityZones: []*ec2.AvailabilityZone{
{
GroupName: aws.String("us-west-2"),
NetworkBorderGroup: aws.String("us-west-2"),
OptInStatus: aws.String("opt-in-not-required"),
RegionName: aws.String("us-west-2"),
State: aws.String("available"),
ZoneId: aws.String("usw2-az1"),
ZoneName: aws.String("us-west-2a"),
ZoneType: aws.String("availability-zone"),
},
{
GroupName: aws.String("us-west-2"),
NetworkBorderGroup: aws.String("us-west-2"),
OptInStatus: aws.String("opt-in-not-required"),
RegionName: aws.String("us-west-2"),
State: aws.String("available"),
ZoneId: aws.String("usw2-az2"),
ZoneName: aws.String("us-west-2b"),
ZoneType: aws.String("availability-zone"),
},
},
}, nil)
},
wantedAZs: []AZ{
{
ID: "usw2-az1",
Name: "us-west-2a",
},
{
ID: "usw2-az2",
Name: "us-west-2b",
},
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := mocks.NewMockapi(ctrl)
tc.mockClient(m)
ec2 := EC2{client: m}
// WHEN
azs, err := ec2.ListAZs()
// THEN
if tc.wantedErr != "" {
require.EqualError(t, err, tc.wantedErr)
} else {
require.NoError(t, err)
require.ElementsMatch(t, tc.wantedAZs, azs)
}
})
}
}
func TestEC2_managedPrefixList(t *testing.T) {
const (
mockPrefixListName = "mockName"
mockPrefixListId = "mockId"
mockNextToken = "mockNextToken"
)
mockError := errors.New("some error")
mockFilter := []*ec2.Filter{
{
Name: aws.String("prefix-list-name"),
Values: aws.StringSlice([]string{mockPrefixListName}),
},
}
mockPrefixList := []*ec2.ManagedPrefixList{
{
PrefixListId: aws.String(mockPrefixListId),
},
}
testCases := map[string]struct {
mockEC2Client func(m *mocks.Mockapi)
wantedError error
wantedErrorMsgPrefix string
wantedList *ec2.DescribeManagedPrefixListsOutput
}{
"query returns error": {
mockEC2Client: func(m *mocks.Mockapi) {
m.EXPECT().DescribeManagedPrefixLists(gomock.Any()).Return(nil, mockError)
},
wantedError: fmt.Errorf("describe managed prefix list with name %s: %w", mockPrefixListName, mockError),
},
"query returns succesfully": {
mockEC2Client: func(m *mocks.Mockapi) {
m.EXPECT().DescribeManagedPrefixLists(&ec2.DescribeManagedPrefixListsInput{
Filters: mockFilter,
}).Return(&ec2.DescribeManagedPrefixListsOutput{
NextToken: aws.String(mockNextToken),
PrefixLists: []*ec2.ManagedPrefixList{
{
PrefixListId: aws.String(mockPrefixListId),
},
},
}, nil)
},
wantedList: &ec2.DescribeManagedPrefixListsOutput{
NextToken: aws.String(mockNextToken),
PrefixLists: mockPrefixList,
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
mockAPI := mocks.NewMockapi(ctrl)
tc.mockEC2Client(mockAPI)
ec2Client := EC2{
client: mockAPI,
}
output, err := ec2Client.managedPrefixList(mockPrefixListName)
if tc.wantedError != nil {
require.EqualError(t, tc.wantedError, err.Error())
} else if tc.wantedErrorMsgPrefix != "" {
require.Error(t, err)
require.Contains(t, err.Error(), tc.wantedErrorMsgPrefix)
return
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedList, output, "managed prefix lists output must be equal")
}
})
}
}
func TestEC2_CloudFrontManagedPrefixListId(t *testing.T) {
const (
mockPrefixListName = cloudFrontPrefixListName
mockPrefixListId = "mockId"
mockNextToken = "mockNextToken"
)
mockError := errors.New("some error")
mockFilter := []*ec2.Filter{
{
Name: aws.String("prefix-list-name"),
Values: aws.StringSlice([]string{mockPrefixListName}),
},
}
testCases := map[string]struct {
mockEC2Client func(m *mocks.Mockapi)
wantedError error
wantedErrorMsgPrefix string
wantedId string
}{
"query returns error": {
mockEC2Client: func(m *mocks.Mockapi) {
m.EXPECT().DescribeManagedPrefixLists(gomock.Any()).Return(nil, mockError)
},
wantedError: fmt.Errorf("describe managed prefix list with name %s: %w", mockPrefixListName, mockError),
},
"query returns no prefix list ids": {
mockEC2Client: func(m *mocks.Mockapi) {
m.EXPECT().DescribeManagedPrefixLists(&ec2.DescribeManagedPrefixListsInput{
Filters: mockFilter,
}).Return(&ec2.DescribeManagedPrefixListsOutput{
NextToken: aws.String(mockNextToken),
PrefixLists: []*ec2.ManagedPrefixList{},
}, nil)
},
wantedError: fmt.Errorf("cannot find any prefix list with name: %s", mockPrefixListName),
},
"query returns too many prefix list ids": {
mockEC2Client: func(m *mocks.Mockapi) {
m.EXPECT().DescribeManagedPrefixLists(&ec2.DescribeManagedPrefixListsInput{
Filters: mockFilter,
}).Return(&ec2.DescribeManagedPrefixListsOutput{
NextToken: aws.String(mockNextToken),
PrefixLists: []*ec2.ManagedPrefixList{
{
PrefixListId: aws.String(mockPrefixListId),
},
{
PrefixListId: aws.String(mockPrefixListId),
},
},
}, nil)
},
wantedErrorMsgPrefix: `found more than one prefix list with the name `,
},
"query returns succesfully": {
mockEC2Client: func(m *mocks.Mockapi) {
m.EXPECT().DescribeManagedPrefixLists(&ec2.DescribeManagedPrefixListsInput{
Filters: mockFilter,
}).Return(&ec2.DescribeManagedPrefixListsOutput{
NextToken: aws.String(mockNextToken),
PrefixLists: []*ec2.ManagedPrefixList{
{
PrefixListId: aws.String(mockPrefixListId),
},
},
}, nil)
},
wantedId: mockPrefixListId,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
mockAPI := mocks.NewMockapi(ctrl)
tc.mockEC2Client(mockAPI)
ec2Client := EC2{
client: mockAPI,
}
id, err := ec2Client.CloudFrontManagedPrefixListID()
if tc.wantedError != nil {
require.EqualError(t, tc.wantedError, err.Error())
} else if tc.wantedErrorMsgPrefix != "" {
require.Error(t, err)
require.Contains(t, err.Error(), tc.wantedErrorMsgPrefix)
return
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedId, id, "ids must be equal")
}
})
}
}
func TestEC2_ListVPCSubnets(t *testing.T) {
const (
mockVPCID = "mockVPC"
mockNextToken = "mockNextToken"
)
mockfilter := []*ec2.Filter{
{
Name: aws.String("vpc-id"),
Values: aws.StringSlice([]string{mockVPCID}),
},
}
mockError := errors.New("some error")
testCases := map[string]struct {
mockEC2Client func(m *mocks.Mockapi)
wantedError error
wantedPublicSubnets []Subnet
wantedPrivateSubnets []Subnet
}{
"fail to describe route tables": {
mockEC2Client: func(m *mocks.Mockapi) {
m.EXPECT().DescribeRouteTables(gomock.Any()).Return(nil, mockError)
},
wantedError: fmt.Errorf("describe route tables: some error"),
},
"fail to describe subnets": {
mockEC2Client: func(m *mocks.Mockapi) {
m.EXPECT().DescribeRouteTables(&ec2.DescribeRouteTablesInput{
Filters: mockfilter,
}).Return(&ec2.DescribeRouteTablesOutput{}, nil)
m.EXPECT().DescribeSubnets(gomock.Any()).Return(nil, mockError)
},
wantedError: fmt.Errorf("describe subnets: some error"),
},
"can retrieve subnets explicitly associated with an internet gateway": {
mockEC2Client: func(m *mocks.Mockapi) {
m.EXPECT().DescribeRouteTables(&ec2.DescribeRouteTablesInput{
Filters: mockfilter,
}).Return(&ec2.DescribeRouteTablesOutput{
RouteTables: []*ec2.RouteTable{
{
Associations: []*ec2.RouteTableAssociation{
{
SubnetId: aws.String("subnet1"),
},
},
Routes: []*ec2.Route{
{
GatewayId: aws.String("local"),
},
},
},
},
NextToken: aws.String(mockNextToken),
}, nil)
m.EXPECT().DescribeRouteTables(&ec2.DescribeRouteTablesInput{
Filters: mockfilter,
NextToken: aws.String(mockNextToken),
}).Return(&ec2.DescribeRouteTablesOutput{
RouteTables: []*ec2.RouteTable{
{
Associations: []*ec2.RouteTableAssociation{
{
SubnetId: aws.String("subnet2"),
},
{
SubnetId: aws.String("subnet3"),
},
},
Routes: []*ec2.Route{
{
GatewayId: aws.String("igw-0333791c413f9e2d8"),
},
},
},
},
}, nil)
m.EXPECT().DescribeSubnets(&ec2.DescribeSubnetsInput{
Filters: mockfilter,
}).Return(&ec2.DescribeSubnetsOutput{
Subnets: []*ec2.Subnet{
{
SubnetId: aws.String("subnet1"),
CidrBlock: aws.String("10.0.0.0/24"),
},
{
SubnetId: aws.String("subnet2"),
CidrBlock: aws.String("10.0.1.0/24"),
},
{
SubnetId: aws.String("subnet3"),
Tags: []*ec2.Tag{
{
Key: aws.String("Name"),
Value: aws.String("mySubnet"),
},
},
CidrBlock: aws.String("10.0.2.0/24"),
},
},
}, nil)
},
wantedPublicSubnets: []Subnet{
{
Resource: Resource{
ID: "subnet2",
},
CIDRBlock: "10.0.1.0/24",
},
{
Resource: Resource{
ID: "subnet3",
Name: "mySubnet",
},
CIDRBlock: "10.0.2.0/24",
},
},
wantedPrivateSubnets: []Subnet{
{
Resource: Resource{
ID: "subnet1",
},
CIDRBlock: "10.0.0.0/24",
},
},
},
"can retrieve subnets that are implicitly associated with an internet gateway": {
mockEC2Client: func(m *mocks.Mockapi) {
m.EXPECT().DescribeRouteTables(&ec2.DescribeRouteTablesInput{
Filters: mockfilter,
}).Return(&ec2.DescribeRouteTablesOutput{
RouteTables: []*ec2.RouteTable{
{
Associations: []*ec2.RouteTableAssociation{
{
Main: aws.Bool(true),
},
},
Routes: []*ec2.Route{
{
GatewayId: aws.String("local"),
DestinationCidrBlock: aws.String("172.31.0.0/16"),
},
{
GatewayId: aws.String("igw-3542f24c"),
DestinationCidrBlock: aws.String("0.0.0.0/0"),
},
},
},
},
}, nil)
m.EXPECT().DescribeSubnets(&ec2.DescribeSubnetsInput{
Filters: mockfilter,
}).Return(&ec2.DescribeSubnetsOutput{
Subnets: []*ec2.Subnet{
{
SubnetId: aws.String("subnet1"),
CidrBlock: aws.String("172.31.16.0/20"),
},
{
SubnetId: aws.String("subnet2"),
CidrBlock: aws.String("172.31.48.0/20"),
},
{
SubnetId: aws.String("subnet3"),
CidrBlock: aws.String("172.31.32.0/20"),
},
},
}, nil)
},
wantedPublicSubnets: []Subnet{
{
Resource: Resource{
ID: "subnet1",
},
CIDRBlock: "172.31.16.0/20",
},
{
Resource: Resource{
ID: "subnet2",
},
CIDRBlock: "172.31.48.0/20",
},
{
Resource: Resource{
ID: "subnet3",
},
CIDRBlock: "172.31.32.0/20",
},
},
wantedPrivateSubnets: nil,
},
"prioritizes explicit route table association over implicit while detecting public subnets": {
mockEC2Client: func(m *mocks.Mockapi) {
m.EXPECT().DescribeRouteTables(&ec2.DescribeRouteTablesInput{
Filters: mockfilter,
}).Return(&ec2.DescribeRouteTablesOutput{
RouteTables: []*ec2.RouteTable{
{
Associations: []*ec2.RouteTableAssociation{
{
Main: aws.Bool(false),
SubnetId: aws.String("subnet1"),
},
},
Routes: []*ec2.Route{
{
GatewayId: aws.String("local"),
DestinationCidrBlock: aws.String("172.31.0.0/16"),
},
},
},
{
Associations: []*ec2.RouteTableAssociation{
{
Main: aws.Bool(true),
},
},
Routes: []*ec2.Route{
{
GatewayId: aws.String("local"),
DestinationCidrBlock: aws.String("172.31.0.0/16"),
},
{
GatewayId: aws.String("igw-3542f24c"),
DestinationCidrBlock: aws.String("0.0.0.0/0"),
},
},
},
},
}, nil)
m.EXPECT().DescribeSubnets(&ec2.DescribeSubnetsInput{
Filters: mockfilter,
}).Return(&ec2.DescribeSubnetsOutput{
Subnets: []*ec2.Subnet{
{
SubnetId: aws.String("subnet1"),
CidrBlock: aws.String("172.31.16.0/20"),
},
{
SubnetId: aws.String("subnet2"),
CidrBlock: aws.String("172.31.48.0/20"),
},
},
}, nil)
},
wantedPublicSubnets: []Subnet{
{
Resource: Resource{
ID: "subnet2",
},
CIDRBlock: "172.31.48.0/20",
},
},
wantedPrivateSubnets: []Subnet{
{
Resource: Resource{
ID: "subnet1",
},
CIDRBlock: "172.31.16.0/20",
},
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
mockAPI := mocks.NewMockapi(ctrl)
tc.mockEC2Client(mockAPI)
ec2Client := EC2{
client: mockAPI,
}
subnets, err := ec2Client.ListVPCSubnets(mockVPCID)
if tc.wantedError != nil {
require.EqualError(t, tc.wantedError, err.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedPublicSubnets, subnets.Public, "public subnets must equal")
require.Equal(t, tc.wantedPrivateSubnets, subnets.Private, "private subnets must equal")
}
})
}
}
func TestEC2_PublicIP(t *testing.T) {
testCases := map[string]struct {
inENI string
mockEC2Client func(m *mocks.Mockapi)
wantedIP string
wantedErr error
}{
"failed to describe network interfaces": {
inENI: "eni-1",
mockEC2Client: func(m *mocks.Mockapi) {
m.EXPECT().DescribeNetworkInterfaces(&ec2.DescribeNetworkInterfacesInput{
NetworkInterfaceIds: aws.StringSlice([]string{"eni-1"}),
}).Return(nil, errors.New("some error"))
},
wantedErr: errors.New("describe network interface with ENI eni-1: some error"),
},
"no association information found": {
inENI: "eni-1",
mockEC2Client: func(m *mocks.Mockapi) {
m.EXPECT().DescribeNetworkInterfaces(&ec2.DescribeNetworkInterfacesInput{
NetworkInterfaceIds: aws.StringSlice([]string{"eni-1"}),
}).Return(&ec2.DescribeNetworkInterfacesOutput{
NetworkInterfaces: []*ec2.NetworkInterface{
{},
},
}, nil)
},
wantedErr: errors.New("no association information found for ENI eni-1"),
},
"successfully get public ip": {
inENI: "eni-1",
mockEC2Client: func(m *mocks.Mockapi) {
m.EXPECT().DescribeNetworkInterfaces(&ec2.DescribeNetworkInterfacesInput{
NetworkInterfaceIds: aws.StringSlice([]string{"eni-1"}),
}).Return(&ec2.DescribeNetworkInterfacesOutput{
NetworkInterfaces: []*ec2.NetworkInterface{
{
Association: &ec2.NetworkInterfaceAssociation{
PublicIp: aws.String("1.2.3"),
},
},
},
}, nil)
},
wantedIP: "1.2.3",
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
mockAPI := mocks.NewMockapi(ctrl)
tc.mockEC2Client(mockAPI)
ec2Client := EC2{
client: mockAPI,
}
out, err := ec2Client.PublicIP(tc.inENI)
if tc.wantedErr != nil {
require.EqualError(t, tc.wantedErr, err.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedIP, out)
}
})
}
}
func TestEC2_SubnetIDs(t *testing.T) {
mockNextToken := aws.String("mockNextToken")
testCases := map[string]struct {
inFilter []Filter
mockEC2Client func(m *mocks.Mockapi)
wantedError error
wantedARNs []string
}{
"failed to get subnets": {
inFilter: inAppEnvFilters,
mockEC2Client: func(m *mocks.Mockapi) {
m.EXPECT().DescribeSubnets(&ec2.DescribeSubnetsInput{
Filters: toEC2Filter(inAppEnvFilters),
}).Return(nil, errors.New("error describing subnets"))
},
wantedError: fmt.Errorf("describe subnets: error describing subnets"),
},
"cannot get any subnets": {
inFilter: inAppEnvFilters,
mockEC2Client: func(m *mocks.Mockapi) {
m.EXPECT().DescribeSubnets(&ec2.DescribeSubnetsInput{
Filters: toEC2Filter(inAppEnvFilters),
}).Return(&ec2.DescribeSubnetsOutput{
Subnets: []*ec2.Subnet{},
}, nil)
},
wantedError: fmt.Errorf("cannot find any subnets"),
},
"successfully get subnets": {
inFilter: inAppEnvFilters,
mockEC2Client: func(m *mocks.Mockapi) {
m.EXPECT().DescribeSubnets(&ec2.DescribeSubnetsInput{
Filters: toEC2Filter(inAppEnvFilters),
}).Return(&ec2.DescribeSubnetsOutput{
Subnets: []*ec2.Subnet{
subnet1, subnet2,
},
}, nil)
},
wantedARNs: []string{"subnet-1", "subnet-2"},
},
"successfully get subnets with pagination": {
inFilter: inAppEnvFilters,
mockEC2Client: func(m *mocks.Mockapi) {
m.EXPECT().DescribeSubnets(&ec2.DescribeSubnetsInput{
Filters: toEC2Filter(inAppEnvFilters),
}).Return(&ec2.DescribeSubnetsOutput{
Subnets: []*ec2.Subnet{
subnet1, subnet2,
},
NextToken: mockNextToken,
}, nil)
m.EXPECT().DescribeSubnets(&ec2.DescribeSubnetsInput{
Filters: toEC2Filter(inAppEnvFilters),
NextToken: mockNextToken,
}).Return(&ec2.DescribeSubnetsOutput{
Subnets: []*ec2.Subnet{
subnet3,
},
}, nil)
},
wantedARNs: []string{"subnet-1", "subnet-2", "subnet-3"},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
mockAPI := mocks.NewMockapi(ctrl)
tc.mockEC2Client(mockAPI)
ec2Client := EC2{
client: mockAPI,
}
arns, err := ec2Client.SubnetIDs(tc.inFilter...)
if tc.wantedError != nil {
require.EqualError(t, tc.wantedError, err.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedARNs, arns)
}
})
}
}
func TestEC2_SecurityGroups(t *testing.T) {
testCases := map[string]struct {
inFilter []Filter
mockEC2Client func(m *mocks.Mockapi)
wantedError error
wantedARNs []string
}{
"failed to get security groups": {
inFilter: inAppEnvFilters,
mockEC2Client: func(m *mocks.Mockapi) {
m.EXPECT().DescribeSecurityGroups(&ec2.DescribeSecurityGroupsInput{
Filters: toEC2Filter(inAppEnvFilters),
}).Return(nil, errors.New("error getting security groups"))
},
wantedError: errors.New("describe security groups: error getting security groups"),
},
"get security groups success": {
inFilter: inAppEnvFilters,
mockEC2Client: func(m *mocks.Mockapi) {
m.EXPECT().DescribeSecurityGroups(&ec2.DescribeSecurityGroupsInput{
Filters: toEC2Filter(inAppEnvFilters),
}).Return(&ec2.DescribeSecurityGroupsOutput{
SecurityGroups: []*ec2.SecurityGroup{
{
GroupId: aws.String("sg-1"),
},
{
GroupId: aws.String("sg-2"),
},
},
}, nil)
},
wantedARNs: []string{"sg-1", "sg-2"},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
mockAPI := mocks.NewMockapi(ctrl)
tc.mockEC2Client(mockAPI)
ec2Client := EC2{
client: mockAPI,
}
arns, err := ec2Client.SecurityGroups(inAppEnvFilters...)
if tc.wantedError != nil {
require.EqualError(t, tc.wantedError, err.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedARNs, arns)
}
})
}
}
func TestEC2_HasDNSSupport(t *testing.T) {
testCases := map[string]struct {
vpcID string
mockEC2Client func(m *mocks.Mockapi)
wantedError error
wantedSupport bool
}{
"fail to descibe VPC attribute": {
vpcID: "mockVPCID",
mockEC2Client: func(m *mocks.Mockapi) {
m.EXPECT().DescribeVpcAttribute(gomock.Any()).Return(nil, errors.New("some error"))
},
wantedError: fmt.Errorf("describe enableDnsSupport attribute for VPC mockVPCID: some error"),
},
"success": {
vpcID: "mockVPCID",
mockEC2Client: func(m *mocks.Mockapi) {
m.EXPECT().DescribeVpcAttribute(&ec2.DescribeVpcAttributeInput{
VpcId: aws.String("mockVPCID"),
Attribute: aws.String(ec2.VpcAttributeNameEnableDnsSupport),
}).Return(&ec2.DescribeVpcAttributeOutput{
EnableDnsSupport: &ec2.AttributeBooleanValue{
Value: aws.Bool(true),
},
}, nil)
},
wantedSupport: true,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
mockAPI := mocks.NewMockapi(ctrl)
tc.mockEC2Client(mockAPI)
ec2Client := EC2{
client: mockAPI,
}
support, err := ec2Client.HasDNSSupport(tc.vpcID)
if tc.wantedError != nil {
require.EqualError(t, tc.wantedError, err.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedSupport, support)
}
})
}
}
| 1,014 |
copilot-cli | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: ./internal/pkg/aws/ec2/ec2.go
// Package mocks is a generated GoMock package.
package mocks
import (
reflect "reflect"
ec2 "github.com/aws/aws-sdk-go/service/ec2"
gomock "github.com/golang/mock/gomock"
)
// Mockapi is a mock of api interface.
type Mockapi struct {
ctrl *gomock.Controller
recorder *MockapiMockRecorder
}
// MockapiMockRecorder is the mock recorder for Mockapi.
type MockapiMockRecorder struct {
mock *Mockapi
}
// NewMockapi creates a new mock instance.
func NewMockapi(ctrl *gomock.Controller) *Mockapi {
mock := &Mockapi{ctrl: ctrl}
mock.recorder = &MockapiMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *Mockapi) EXPECT() *MockapiMockRecorder {
return m.recorder
}
// DescribeAvailabilityZones mocks base method.
func (m *Mockapi) DescribeAvailabilityZones(input *ec2.DescribeAvailabilityZonesInput) (*ec2.DescribeAvailabilityZonesOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DescribeAvailabilityZones", input)
ret0, _ := ret[0].(*ec2.DescribeAvailabilityZonesOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DescribeAvailabilityZones indicates an expected call of DescribeAvailabilityZones.
func (mr *MockapiMockRecorder) DescribeAvailabilityZones(input interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeAvailabilityZones", reflect.TypeOf((*Mockapi)(nil).DescribeAvailabilityZones), input)
}
// DescribeManagedPrefixLists mocks base method.
func (m *Mockapi) DescribeManagedPrefixLists(input *ec2.DescribeManagedPrefixListsInput) (*ec2.DescribeManagedPrefixListsOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DescribeManagedPrefixLists", input)
ret0, _ := ret[0].(*ec2.DescribeManagedPrefixListsOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DescribeManagedPrefixLists indicates an expected call of DescribeManagedPrefixLists.
func (mr *MockapiMockRecorder) DescribeManagedPrefixLists(input interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeManagedPrefixLists", reflect.TypeOf((*Mockapi)(nil).DescribeManagedPrefixLists), input)
}
// DescribeNetworkInterfaces mocks base method.
func (m *Mockapi) DescribeNetworkInterfaces(input *ec2.DescribeNetworkInterfacesInput) (*ec2.DescribeNetworkInterfacesOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DescribeNetworkInterfaces", input)
ret0, _ := ret[0].(*ec2.DescribeNetworkInterfacesOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DescribeNetworkInterfaces indicates an expected call of DescribeNetworkInterfaces.
func (mr *MockapiMockRecorder) DescribeNetworkInterfaces(input interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeNetworkInterfaces", reflect.TypeOf((*Mockapi)(nil).DescribeNetworkInterfaces), input)
}
// DescribeRouteTables mocks base method.
func (m *Mockapi) DescribeRouteTables(input *ec2.DescribeRouteTablesInput) (*ec2.DescribeRouteTablesOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DescribeRouteTables", input)
ret0, _ := ret[0].(*ec2.DescribeRouteTablesOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DescribeRouteTables indicates an expected call of DescribeRouteTables.
func (mr *MockapiMockRecorder) DescribeRouteTables(input interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeRouteTables", reflect.TypeOf((*Mockapi)(nil).DescribeRouteTables), input)
}
// DescribeSecurityGroups mocks base method.
func (m *Mockapi) DescribeSecurityGroups(arg0 *ec2.DescribeSecurityGroupsInput) (*ec2.DescribeSecurityGroupsOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DescribeSecurityGroups", arg0)
ret0, _ := ret[0].(*ec2.DescribeSecurityGroupsOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DescribeSecurityGroups indicates an expected call of DescribeSecurityGroups.
func (mr *MockapiMockRecorder) DescribeSecurityGroups(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeSecurityGroups", reflect.TypeOf((*Mockapi)(nil).DescribeSecurityGroups), arg0)
}
// DescribeSubnets mocks base method.
func (m *Mockapi) DescribeSubnets(arg0 *ec2.DescribeSubnetsInput) (*ec2.DescribeSubnetsOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DescribeSubnets", arg0)
ret0, _ := ret[0].(*ec2.DescribeSubnetsOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DescribeSubnets indicates an expected call of DescribeSubnets.
func (mr *MockapiMockRecorder) DescribeSubnets(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeSubnets", reflect.TypeOf((*Mockapi)(nil).DescribeSubnets), arg0)
}
// DescribeVpcAttribute mocks base method.
func (m *Mockapi) DescribeVpcAttribute(input *ec2.DescribeVpcAttributeInput) (*ec2.DescribeVpcAttributeOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DescribeVpcAttribute", input)
ret0, _ := ret[0].(*ec2.DescribeVpcAttributeOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DescribeVpcAttribute indicates an expected call of DescribeVpcAttribute.
func (mr *MockapiMockRecorder) DescribeVpcAttribute(input interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeVpcAttribute", reflect.TypeOf((*Mockapi)(nil).DescribeVpcAttribute), input)
}
// DescribeVpcs mocks base method.
func (m *Mockapi) DescribeVpcs(input *ec2.DescribeVpcsInput) (*ec2.DescribeVpcsOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DescribeVpcs", input)
ret0, _ := ret[0].(*ec2.DescribeVpcsOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DescribeVpcs indicates an expected call of DescribeVpcs.
func (mr *MockapiMockRecorder) DescribeVpcs(input interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeVpcs", reflect.TypeOf((*Mockapi)(nil).DescribeVpcs), input)
}
| 156 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package ecr provides a client to make API requests to Amazon EC2 Container Registry.
package ecr
import (
"encoding/base64"
"errors"
"fmt"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/arn"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/endpoints"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ecr"
"github.com/aws/copilot-cli/internal/pkg/term/log"
)
const (
urlFmtString = "%s.dkr.ecr.%s.amazonaws.com/%s"
urlFmtStringForCN = "%s.dkr.ecr.%s.amazonaws.com.cn/%s"
arnResourcePrefix = "repository/"
batchDeleteLimit = 100
)
type api interface {
DescribeImages(*ecr.DescribeImagesInput) (*ecr.DescribeImagesOutput, error)
GetAuthorizationToken(*ecr.GetAuthorizationTokenInput) (*ecr.GetAuthorizationTokenOutput, error)
DescribeRepositories(*ecr.DescribeRepositoriesInput) (*ecr.DescribeRepositoriesOutput, error)
BatchDeleteImage(*ecr.BatchDeleteImageInput) (*ecr.BatchDeleteImageOutput, error)
}
// ECR wraps an AWS ECR client.
type ECR struct {
client api
}
// New returns a ECR configured against the input session.
func New(s *session.Session) ECR {
return ECR{
client: ecr.New(s),
}
}
// Auth returns the basic authentication credentials needed to push images.
func (c ECR) Auth() (username string, password string, err error) {
response, err := c.client.GetAuthorizationToken(&ecr.GetAuthorizationTokenInput{})
if err != nil {
return "", "", fmt.Errorf("get ECR auth: %w", err)
}
authToken, err := base64.StdEncoding.DecodeString(*response.AuthorizationData[0].AuthorizationToken)
if err != nil {
return "", "", fmt.Errorf("decode auth token: %w", err)
}
tokenStrings := strings.Split(string(authToken), ":")
return tokenStrings[0], tokenStrings[1], nil
}
// RepositoryURI returns the ECR repository URI.
func (c ECR) RepositoryURI(name string) (string, error) {
result, err := c.client.DescribeRepositories(&ecr.DescribeRepositoriesInput{
RepositoryNames: aws.StringSlice([]string{name}),
})
if err != nil {
return "", fmt.Errorf("ecr describe repository %s: %w", name, err)
}
foundRepositories := result.Repositories
if len(foundRepositories) <= 0 {
return "", errors.New("no repositories found")
}
repo := result.Repositories[0]
return *repo.RepositoryUri, nil
}
// Image houses metadata for ECR repository images.
type Image struct {
Digest string
}
func (i Image) imageIdentifier() *ecr.ImageIdentifier {
return &ecr.ImageIdentifier{
ImageDigest: aws.String(i.Digest),
}
}
// ListImages calls the ECR DescribeImages API and returns a list of
// Image metadata for images in the input ECR repository name.
func (c ECR) ListImages(repoName string) ([]Image, error) {
var images []Image
resp, err := c.client.DescribeImages(&ecr.DescribeImagesInput{
RepositoryName: aws.String(repoName),
})
if err != nil {
return nil, fmt.Errorf("ecr repo %s describe images: %w", repoName, err)
}
for _, imageDetails := range resp.ImageDetails {
images = append(images, Image{
Digest: *imageDetails.ImageDigest,
})
}
for resp.NextToken != nil {
resp, err = c.client.DescribeImages(&ecr.DescribeImagesInput{
RepositoryName: aws.String(repoName),
NextToken: resp.NextToken,
})
if err != nil {
return nil, fmt.Errorf("ecr repo %s describe images: %w", repoName, err)
}
for _, imageDetails := range resp.ImageDetails {
images = append(images, Image{
Digest: *imageDetails.ImageDigest,
})
}
}
return images, nil
}
// DeleteImages calls the ECR BatchDeleteImage API with the input image list and repository name.
func (c ECR) DeleteImages(images []Image, repoName string) error {
if len(images) == 0 {
return nil
}
var imageIdentifiers []*ecr.ImageIdentifier
for _, image := range images {
imageIdentifiers = append(imageIdentifiers, image.imageIdentifier())
}
var imageIdentifiersBatch [][]*ecr.ImageIdentifier
for batchDeleteLimit < len(imageIdentifiers) {
imageIdentifiers, imageIdentifiersBatch = imageIdentifiers[batchDeleteLimit:], append(imageIdentifiersBatch, imageIdentifiers[0:batchDeleteLimit])
}
imageIdentifiersBatch = append(imageIdentifiersBatch, imageIdentifiers)
for _, identifiers := range imageIdentifiersBatch {
resp, err := c.client.BatchDeleteImage(&ecr.BatchDeleteImageInput{
RepositoryName: aws.String(repoName),
ImageIds: identifiers,
})
if resp != nil {
for _, failure := range resp.Failures {
log.Warningf("failed to delete %s:%s : %s %s\n", failure.ImageId.ImageDigest, failure.ImageId.ImageTag, failure.FailureCode, failure.FailureReason)
}
}
if err != nil {
return fmt.Errorf("ecr repo %s batch delete image: %w", repoName, err)
}
}
return nil
}
// ClearRepository orchestrates a ListImages call followed by a DeleteImages
// call to delete all images from the input ECR repository name.
func (c ECR) ClearRepository(repoName string) error {
images, err := c.ListImages(repoName)
if err == nil {
// TODO: add retry handling in case images are added to a repository after a call to ListImages
return c.DeleteImages(images, repoName)
}
if isRepoNotFoundErr(errors.Unwrap(err)) {
return nil
}
return err
}
// URIFromARN converts an ECR Repo ARN to a Repository URI
func URIFromARN(repositoryARN string) (string, error) {
repoARN, err := arn.Parse(repositoryARN)
if err != nil {
return "", fmt.Errorf("parsing repository ARN %s: %w", repositoryARN, err)
}
urlFmtStr := urlFmtString
if repoARN.Partition == endpoints.AwsCnPartitionID {
urlFmtStr = urlFmtStringForCN
}
// Repo ARNs look like arn:aws:ecr:region:012345678910:repository/test
// so we have to strip the repository out.
repoName := strings.TrimPrefix(repoARN.Resource, arnResourcePrefix)
return fmt.Sprintf(urlFmtStr,
repoARN.AccountID,
repoARN.Region,
repoName), nil
}
func isRepoNotFoundErr(err error) bool {
aerr, ok := err.(awserr.Error)
if !ok {
return false
}
if aerr.Code() == "RepositoryNotFoundException" {
return true
}
return false
}
| 207 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package ecr
import (
"encoding/base64"
"errors"
"fmt"
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/ecr"
"github.com/aws/copilot-cli/internal/pkg/aws/ecr/mocks"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
func TestAuth(t *testing.T) {
mockError := errors.New("error")
mockUsername := "mockUsername"
mockPassword := "mockPassword"
encoded := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", mockUsername, mockPassword)))
testCases := map[string]struct {
mockECRClient func(m *mocks.Mockapi)
wantedUsername string
wantedPassword string
wantErr error
}{
"should return wrapped error given error returned from GetAuthorizationToken": {
mockECRClient: func(m *mocks.Mockapi) {
m.EXPECT().GetAuthorizationToken(gomock.Any()).Return(nil, mockError)
},
wantErr: fmt.Errorf("get ECR auth: %w", mockError),
},
"should return Auth data": {
mockECRClient: func(m *mocks.Mockapi) {
m.EXPECT().GetAuthorizationToken(gomock.Any()).Return(&ecr.GetAuthorizationTokenOutput{
AuthorizationData: []*ecr.AuthorizationData{
{
AuthorizationToken: aws.String(encoded),
},
},
}, nil)
},
wantedUsername: mockUsername,
wantedPassword: mockPassword,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockECRAPI := mocks.NewMockapi(ctrl)
tc.mockECRClient(mockECRAPI)
client := ECR{
mockECRAPI,
}
gotUsername, gotPassword, gotErr := client.Auth()
require.Equal(t, tc.wantedUsername, gotUsername)
require.Equal(t, tc.wantedPassword, gotPassword)
require.Equal(t, tc.wantErr, gotErr)
})
}
}
func TestRepositoryURI(t *testing.T) {
mockError := errors.New("error")
mockRepoName := "mockRepoName"
mockRepoURI := "mockRepoURI"
testCases := map[string]struct {
mockECRClient func(m *mocks.Mockapi)
wantURI string
wantErr error
}{
"should return wrapped error given error returned from DescribeRepositories": {
mockECRClient: func(m *mocks.Mockapi) {
m.EXPECT().DescribeRepositories(gomock.Any()).Return(nil, mockError)
},
wantErr: fmt.Errorf("ecr describe repository %s: %w", mockRepoName, mockError),
},
"should return error given no repositories returned in list": {
mockECRClient: func(m *mocks.Mockapi) {
m.EXPECT().DescribeRepositories(&ecr.DescribeRepositoriesInput{
RepositoryNames: aws.StringSlice([]string{mockRepoName}),
}).Return(&ecr.DescribeRepositoriesOutput{
Repositories: []*ecr.Repository{},
}, nil)
},
wantErr: errors.New("no repositories found"),
},
"should return repository URI": {
mockECRClient: func(m *mocks.Mockapi) {
m.EXPECT().DescribeRepositories(&ecr.DescribeRepositoriesInput{
RepositoryNames: aws.StringSlice([]string{mockRepoName}),
}).Return(&ecr.DescribeRepositoriesOutput{
Repositories: []*ecr.Repository{
{
RepositoryUri: aws.String(mockRepoURI),
},
},
}, nil)
},
wantURI: mockRepoURI,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockECRAPI := mocks.NewMockapi(ctrl)
tc.mockECRClient(mockECRAPI)
client := ECR{
mockECRAPI,
}
gotURI, gotErr := client.RepositoryURI(mockRepoName)
require.Equal(t, tc.wantURI, gotURI)
require.Equal(t, tc.wantErr, gotErr)
})
}
}
func TestURIFromARN(t *testing.T) {
testCases := map[string]struct {
givenARN string
wantedURI string
wantErr error
}{
"valid arn": {
givenARN: "arn:aws:ecr:us-west-2:0123456789:repository/myrepo",
wantedURI: "0123456789.dkr.ecr.us-west-2.amazonaws.com/myrepo",
},
"valid arn in china partition": {
givenARN: "arn:aws-cn:ecr:cn-north-1:0123456789:repository/myrepo",
wantedURI: "0123456789.dkr.ecr.cn-north-1.amazonaws.com.cn/myrepo",
},
"valid arn with namespace": {
givenARN: "arn:aws:ecr:us-west-2:0123456789:repository/myproject/myapp",
wantedURI: "0123456789.dkr.ecr.us-west-2.amazonaws.com/myproject/myapp",
},
"separate region": {
givenARN: "arn:aws:ecr:us-east-1:0123456789:repository/myproject/myapp",
wantedURI: "0123456789.dkr.ecr.us-east-1.amazonaws.com/myproject/myapp",
},
"invalid ARN": {
givenARN: "myproject/myapp",
wantErr: fmt.Errorf("parsing repository ARN myproject/myapp: arn: invalid prefix"),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
uri, err := URIFromARN(tc.givenARN)
if tc.wantErr != nil {
require.Error(t, err)
require.EqualError(t, err, tc.wantErr.Error())
} else {
require.Equal(t, tc.wantedURI, uri)
}
})
}
}
func TestListImages(t *testing.T) {
mockRepoName := "mockRepoName"
mockError := errors.New("mockError")
mockDigest := "mockDigest"
mockNextToken := "next"
tests := map[string]struct {
mockECRClient func(m *mocks.Mockapi)
wantImages []Image
wantError error
}{
"should wrap error returned by ECR DescribeImages": {
mockECRClient: func(m *mocks.Mockapi) {
m.EXPECT().DescribeImages(gomock.Any()).Return(nil, mockError)
},
wantImages: nil,
wantError: fmt.Errorf("ecr repo %s describe images: %w", mockRepoName, mockError),
},
"should return Image list": {
mockECRClient: func(m *mocks.Mockapi) {
m.EXPECT().DescribeImages(gomock.Any()).Return(&ecr.DescribeImagesOutput{
ImageDetails: []*ecr.ImageDetail{
{
ImageDigest: aws.String(mockDigest),
},
},
}, nil)
},
wantImages: []Image{{Digest: mockDigest}},
wantError: nil,
},
"should return all images when paginated": {
mockECRClient: func(m *mocks.Mockapi) {
m.EXPECT().DescribeImages(&ecr.DescribeImagesInput{
RepositoryName: aws.String(mockRepoName),
}).Return(&ecr.DescribeImagesOutput{
ImageDetails: []*ecr.ImageDetail{
{
ImageDigest: aws.String(mockDigest),
},
},
NextToken: &mockNextToken,
}, nil)
m.EXPECT().DescribeImages(&ecr.DescribeImagesInput{
RepositoryName: aws.String(mockRepoName),
NextToken: &mockNextToken,
}).Return(&ecr.DescribeImagesOutput{
ImageDetails: []*ecr.ImageDetail{
{
ImageDigest: aws.String(mockDigest),
},
},
}, nil)
},
wantImages: []Image{{Digest: mockDigest}, {Digest: mockDigest}},
wantError: nil,
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockECRAPI := mocks.NewMockapi(ctrl)
tc.mockECRClient(mockECRAPI)
client := ECR{
mockECRAPI,
}
gotImages, gotError := client.ListImages(mockRepoName)
require.ElementsMatch(t, tc.wantImages, gotImages)
require.Equal(t, tc.wantError, gotError)
})
}
}
func TestDeleteImages(t *testing.T) {
mockRepoName := "mockRepoName"
mockError := errors.New("mockError")
mockDigest := "mockDigest"
mockImages := []Image{
{
Digest: mockDigest,
},
}
mockFailCode := "400"
mockFailReason := "some reason"
// with only one image identifier
var imageIdentifiers []*ecr.ImageIdentifier
for _, image := range mockImages {
imageIdentifiers = append(imageIdentifiers, image.imageIdentifier())
}
var mockBatchImages []Image
for ii := 0; ii < batchDeleteLimit+1; ii++ {
mockBatchImages = append(mockBatchImages, mockImages[0])
}
// with a batch limit number of image identifiers
var batchImageIdentifiers []*ecr.ImageIdentifier
for ii := 0; ii < batchDeleteLimit; ii++ {
batchImageIdentifiers = append(batchImageIdentifiers, mockImages[0].imageIdentifier())
}
tests := map[string]struct {
images []Image
mockECRClient func(m *mocks.Mockapi)
wantError error
}{
"should not return error if input Image list is empty": {
images: nil,
mockECRClient: func(m *mocks.Mockapi) {},
wantError: nil,
},
"should wrap error return from BatchDeleteImage": {
images: mockImages,
mockECRClient: func(m *mocks.Mockapi) {
m.EXPECT().BatchDeleteImage(gomock.Any()).Return(nil, mockError)
},
wantError: fmt.Errorf("ecr repo %s batch delete image: %w", mockRepoName, mockError),
},
"should return nil if call to BatchDeleteImage successful": {
images: mockImages,
mockECRClient: func(m *mocks.Mockapi) {
m.EXPECT().BatchDeleteImage(&ecr.BatchDeleteImageInput{
RepositoryName: aws.String(mockRepoName),
ImageIds: imageIdentifiers,
}).Return(&ecr.BatchDeleteImageOutput{}, nil)
},
wantError: nil,
},
fmt.Sprintf("should be able to batch delete more than %d images", batchDeleteLimit): {
images: mockBatchImages,
mockECRClient: func(m *mocks.Mockapi) {
m.EXPECT().BatchDeleteImage(&ecr.BatchDeleteImageInput{
RepositoryName: aws.String(mockRepoName),
ImageIds: batchImageIdentifiers,
}).Return(&ecr.BatchDeleteImageOutput{}, nil).Times(1)
m.EXPECT().BatchDeleteImage(&ecr.BatchDeleteImageInput{
RepositoryName: aws.String(mockRepoName),
ImageIds: imageIdentifiers,
}).Return(&ecr.BatchDeleteImageOutput{}, nil).Times(1)
},
wantError: nil,
},
"warns if fail to delete some images": {
images: mockImages,
mockECRClient: func(m *mocks.Mockapi) {
m.EXPECT().BatchDeleteImage(&ecr.BatchDeleteImageInput{
RepositoryName: aws.String(mockRepoName),
ImageIds: imageIdentifiers,
}).Return(&ecr.BatchDeleteImageOutput{
Failures: []*ecr.ImageFailure{
{
FailureCode: &mockFailCode,
FailureReason: &mockFailReason,
ImageId: imageIdentifiers[0],
},
},
}, nil)
},
wantError: nil,
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockECRAPI := mocks.NewMockapi(ctrl)
tc.mockECRClient(mockECRAPI)
client := ECR{
mockECRAPI,
}
got := client.DeleteImages(tc.images, mockRepoName)
require.Equal(t, tc.wantError, got)
})
}
}
func TestClearRepository(t *testing.T) {
mockRepoName := "mockRepoName"
mockAwsError := awserr.New("someErrorCode", "some error", nil)
mockError := errors.New("some error")
mockRepoNotFoundError := awserr.New("RepositoryNotFoundException", "some error", nil)
mockDigest := "mockDigest"
mockImageID := ecr.ImageIdentifier{
ImageDigest: aws.String(mockDigest),
}
tests := map[string]struct {
mockECRClient func(m *mocks.Mockapi)
wantError error
}{
"should clear repo if exists": {
mockECRClient: func(m *mocks.Mockapi) {
m.EXPECT().DescribeImages(&ecr.DescribeImagesInput{
RepositoryName: aws.String(mockRepoName),
}).Return(&ecr.DescribeImagesOutput{
ImageDetails: []*ecr.ImageDetail{
{
ImageDigest: aws.String(mockDigest),
},
},
}, nil)
m.EXPECT().BatchDeleteImage(&ecr.BatchDeleteImageInput{
RepositoryName: aws.String(mockRepoName),
ImageIds: []*ecr.ImageIdentifier{&mockImageID},
}).Return(&ecr.BatchDeleteImageOutput{}, nil)
},
wantError: nil,
},
"returns nil if repo not exists": {
mockECRClient: func(m *mocks.Mockapi) {
m.EXPECT().DescribeImages(&ecr.DescribeImagesInput{
RepositoryName: aws.String(mockRepoName),
}).Return(nil, mockRepoNotFoundError)
},
wantError: nil,
},
"returns error if fail to check repo existence": {
mockECRClient: func(m *mocks.Mockapi) {
m.EXPECT().DescribeImages(&ecr.DescribeImagesInput{
RepositoryName: aws.String(mockRepoName),
}).Return(nil, mockAwsError)
},
wantError: fmt.Errorf("ecr repo mockRepoName describe images: %w", mockAwsError),
},
"returns error if fail to check repo existence because of non-awserr error type": {
mockECRClient: func(m *mocks.Mockapi) {
m.EXPECT().DescribeImages(&ecr.DescribeImagesInput{
RepositoryName: aws.String(mockRepoName),
}).Return(nil, mockError)
},
wantError: fmt.Errorf("ecr repo mockRepoName describe images: %w", mockError),
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockECRAPI := mocks.NewMockapi(ctrl)
tc.mockECRClient(mockECRAPI)
client := ECR{
mockECRAPI,
}
gotError := client.ClearRepository(mockRepoName)
require.Equal(t, tc.wantError, gotError)
})
}
}
| 453 |
copilot-cli | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: ./internal/pkg/aws/ecr/ecr.go
// Package mocks is a generated GoMock package.
package mocks
import (
reflect "reflect"
ecr "github.com/aws/aws-sdk-go/service/ecr"
gomock "github.com/golang/mock/gomock"
)
// Mockapi is a mock of api interface.
type Mockapi struct {
ctrl *gomock.Controller
recorder *MockapiMockRecorder
}
// MockapiMockRecorder is the mock recorder for Mockapi.
type MockapiMockRecorder struct {
mock *Mockapi
}
// NewMockapi creates a new mock instance.
func NewMockapi(ctrl *gomock.Controller) *Mockapi {
mock := &Mockapi{ctrl: ctrl}
mock.recorder = &MockapiMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *Mockapi) EXPECT() *MockapiMockRecorder {
return m.recorder
}
// BatchDeleteImage mocks base method.
func (m *Mockapi) BatchDeleteImage(arg0 *ecr.BatchDeleteImageInput) (*ecr.BatchDeleteImageOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "BatchDeleteImage", arg0)
ret0, _ := ret[0].(*ecr.BatchDeleteImageOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// BatchDeleteImage indicates an expected call of BatchDeleteImage.
func (mr *MockapiMockRecorder) BatchDeleteImage(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BatchDeleteImage", reflect.TypeOf((*Mockapi)(nil).BatchDeleteImage), arg0)
}
// DescribeImages mocks base method.
func (m *Mockapi) DescribeImages(arg0 *ecr.DescribeImagesInput) (*ecr.DescribeImagesOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DescribeImages", arg0)
ret0, _ := ret[0].(*ecr.DescribeImagesOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DescribeImages indicates an expected call of DescribeImages.
func (mr *MockapiMockRecorder) DescribeImages(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeImages", reflect.TypeOf((*Mockapi)(nil).DescribeImages), arg0)
}
// DescribeRepositories mocks base method.
func (m *Mockapi) DescribeRepositories(arg0 *ecr.DescribeRepositoriesInput) (*ecr.DescribeRepositoriesOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DescribeRepositories", arg0)
ret0, _ := ret[0].(*ecr.DescribeRepositoriesOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DescribeRepositories indicates an expected call of DescribeRepositories.
func (mr *MockapiMockRecorder) DescribeRepositories(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeRepositories", reflect.TypeOf((*Mockapi)(nil).DescribeRepositories), arg0)
}
// GetAuthorizationToken mocks base method.
func (m *Mockapi) GetAuthorizationToken(arg0 *ecr.GetAuthorizationTokenInput) (*ecr.GetAuthorizationTokenOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetAuthorizationToken", arg0)
ret0, _ := ret[0].(*ecr.GetAuthorizationTokenOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetAuthorizationToken indicates an expected call of GetAuthorizationToken.
func (mr *MockapiMockRecorder) GetAuthorizationToken(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAuthorizationToken", reflect.TypeOf((*Mockapi)(nil).GetAuthorizationToken), arg0)
}
| 96 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package ecs provides a client to make API requests to Amazon Elastic Container Service.
package ecs
import (
"errors"
"fmt"
"time"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ecs"
"github.com/aws/copilot-cli/internal/pkg/exec"
)
const (
clusterStatusActive = "ACTIVE"
waitServiceStablePollingInterval = 15 * time.Second
waitServiceStableMaxTry = 80
stableServiceDeploymentNum = 1
// EndpointsID is the ID to look up the ECS service endpoint.
EndpointsID = ecs.EndpointsID
)
type api interface {
DescribeClusters(input *ecs.DescribeClustersInput) (*ecs.DescribeClustersOutput, error)
DescribeServices(input *ecs.DescribeServicesInput) (*ecs.DescribeServicesOutput, error)
DescribeTasks(input *ecs.DescribeTasksInput) (*ecs.DescribeTasksOutput, error)
DescribeTaskDefinition(input *ecs.DescribeTaskDefinitionInput) (*ecs.DescribeTaskDefinitionOutput, error)
ExecuteCommand(input *ecs.ExecuteCommandInput) (*ecs.ExecuteCommandOutput, error)
ListTasks(input *ecs.ListTasksInput) (*ecs.ListTasksOutput, error)
RunTask(input *ecs.RunTaskInput) (*ecs.RunTaskOutput, error)
StopTask(input *ecs.StopTaskInput) (*ecs.StopTaskOutput, error)
UpdateService(input *ecs.UpdateServiceInput) (*ecs.UpdateServiceOutput, error)
WaitUntilTasksRunning(input *ecs.DescribeTasksInput) error
}
type ssmSessionStarter interface {
StartSession(ssmSession *ecs.Session) error
}
// ECS wraps an AWS ECS client.
type ECS struct {
client api
newSessStarter func() ssmSessionStarter
maxServiceStableTries int
pollIntervalDuration time.Duration
}
// RunTaskInput holds the fields needed to run tasks.
type RunTaskInput struct {
Cluster string
Count int
Subnets []string
SecurityGroups []string
TaskFamilyName string
StartedBy string
PlatformVersion string
EnableExec bool
}
// ExecuteCommandInput holds the fields needed to execute commands in a running container.
type ExecuteCommandInput struct {
Cluster string
Command string
Task string
Container string
}
// New returns a Service configured against the input session.
func New(s *session.Session) *ECS {
return &ECS{
client: ecs.New(s),
newSessStarter: func() ssmSessionStarter {
return exec.NewSSMPluginCommand(s)
},
maxServiceStableTries: waitServiceStableMaxTry,
pollIntervalDuration: waitServiceStablePollingInterval,
}
}
// TaskDefinition calls ECS API and returns the task definition.
func (e *ECS) TaskDefinition(taskDefName string) (*TaskDefinition, error) {
resp, err := e.client.DescribeTaskDefinition(&ecs.DescribeTaskDefinitionInput{
TaskDefinition: aws.String(taskDefName),
})
if err != nil {
return nil, fmt.Errorf("describe task definition %s: %w", taskDefName, err)
}
td := TaskDefinition(*resp.TaskDefinition)
return &td, nil
}
// Service calls ECS API and returns the specified service running in the cluster.
func (e *ECS) Service(clusterName, serviceName string) (*Service, error) {
resp, err := e.client.DescribeServices(&ecs.DescribeServicesInput{
Cluster: aws.String(clusterName),
Services: aws.StringSlice([]string{serviceName}),
})
if err != nil {
return nil, fmt.Errorf("describe service %s: %w", serviceName, err)
}
for _, service := range resp.Services {
if aws.StringValue(service.ServiceName) == serviceName {
svc := Service(*service)
return &svc, nil
}
}
return nil, fmt.Errorf("cannot find service %s", serviceName)
}
// UpdateServiceOpts sets the optional parameter for UpdateService.
type UpdateServiceOpts func(*ecs.UpdateServiceInput)
// WithForceUpdate sets ForceNewDeployment to force an update.
func WithForceUpdate() UpdateServiceOpts {
return func(in *ecs.UpdateServiceInput) {
in.ForceNewDeployment = aws.Bool(true)
}
}
// UpdateService calls ECS API and updates the specific service running in the cluster.
func (e *ECS) UpdateService(clusterName, serviceName string, opts ...UpdateServiceOpts) error {
in := &ecs.UpdateServiceInput{
Cluster: aws.String(clusterName),
Service: aws.String(serviceName),
}
for _, opt := range opts {
opt(in)
}
svc, err := e.client.UpdateService(in)
if err != nil {
return fmt.Errorf("update service %s from cluster %s: %w", serviceName, clusterName, err)
}
s := Service(*svc.Service)
if err := e.waitUntilServiceStable(&s); err != nil {
return fmt.Errorf("wait until service %s becomes stable: %w", serviceName, err)
}
return nil
}
// waitUntilServiceStable waits until the service is stable.
// See https://docs.aws.amazon.com/cli/latest/reference/ecs/wait/services-stable.html
func (e *ECS) waitUntilServiceStable(svc *Service) error {
var err error
var tryNum int
for {
if len(svc.Deployments) == stableServiceDeploymentNum &&
aws.Int64Value(svc.DesiredCount) == aws.Int64Value(svc.RunningCount) {
// This conditional is sufficient to determine that the service is stable AND has successfully updated (hence not rolled-back).
// The stable service cannot be a rolled-back service because a rollback can only be triggered by circuit breaker after ~1hr,
// by which time we would have already timed out.
return nil
}
if tryNum >= e.maxServiceStableTries {
return &ErrWaitServiceStableTimeout{
maxRetries: e.maxServiceStableTries,
}
}
svc, err = e.Service(aws.StringValue(svc.ClusterArn), aws.StringValue(svc.ServiceName))
if err != nil {
return err
}
tryNum++
time.Sleep(e.pollIntervalDuration)
}
}
// ServiceRunningTasks calls ECS API and returns the ECS tasks spun up by the service, with the desired status to be set to be RUNNING.
func (e *ECS) ServiceRunningTasks(cluster, service string) ([]*Task, error) {
return e.listTasks(cluster, withService(service), withRunningTasks())
}
// StoppedServiceTasks calls ECS API and returns stopped ECS tasks in a service.
func (e *ECS) StoppedServiceTasks(cluster, service string) ([]*Task, error) {
return e.listTasks(cluster, withService(service), withStoppedTasks())
}
// RunningTasksInFamily calls ECS API and returns ECS tasks with the desired status to be RUNNING
// within the same task definition family.
func (e *ECS) RunningTasksInFamily(cluster, family string) ([]*Task, error) {
return e.listTasks(cluster, withFamily(family), withRunningTasks())
}
// RunningTasks calls ECS API and returns ECS tasks with the desired status to be RUNNING.
func (e *ECS) RunningTasks(cluster string) ([]*Task, error) {
return e.listTasks(cluster, withRunningTasks())
}
type listTasksOpts func(*ecs.ListTasksInput)
func withService(svcName string) listTasksOpts {
return func(in *ecs.ListTasksInput) {
in.ServiceName = aws.String(svcName)
}
}
func withFamily(family string) listTasksOpts {
return func(in *ecs.ListTasksInput) {
in.Family = aws.String(family)
}
}
func withRunningTasks() listTasksOpts {
return func(in *ecs.ListTasksInput) {
in.DesiredStatus = aws.String(ecs.DesiredStatusRunning)
}
}
func withStoppedTasks() listTasksOpts {
return func(in *ecs.ListTasksInput) {
in.DesiredStatus = aws.String(ecs.DesiredStatusStopped)
}
}
func (e *ECS) listTasks(cluster string, opts ...listTasksOpts) ([]*Task, error) {
var tasks []*Task
in := &ecs.ListTasksInput{
Cluster: aws.String(cluster),
}
for _, opt := range opts {
opt(in)
}
for {
listTaskResp, err := e.client.ListTasks(in)
if err != nil {
return nil, fmt.Errorf("list running tasks: %w", err)
}
if len(listTaskResp.TaskArns) == 0 {
return tasks, nil
}
descTaskResp, err := e.client.DescribeTasks(&ecs.DescribeTasksInput{
Cluster: aws.String(cluster),
Tasks: listTaskResp.TaskArns,
Include: aws.StringSlice([]string{ecs.TaskFieldTags}),
})
if err != nil {
return nil, fmt.Errorf("describe running tasks in cluster %s: %w", cluster, err)
}
for _, task := range descTaskResp.Tasks {
t := Task(*task)
tasks = append(tasks, &t)
}
if listTaskResp.NextToken == nil {
break
}
in.NextToken = listTaskResp.NextToken
}
return tasks, nil
}
// StopTasksOpts sets the optional parameter for StopTasks.
type StopTasksOpts func(*ecs.StopTaskInput)
// WithStopTaskReason sets an optional message specified when a task is stopped.
func WithStopTaskReason(reason string) StopTasksOpts {
return func(in *ecs.StopTaskInput) {
in.Reason = aws.String(reason)
}
}
// WithStopTaskCluster sets the cluster that hosts the task to stop.
func WithStopTaskCluster(cluster string) StopTasksOpts {
return func(in *ecs.StopTaskInput) {
in.Cluster = aws.String(cluster)
}
}
// StopTasks stops multiple running tasks given their IDs or ARNs.
func (e *ECS) StopTasks(tasks []string, opts ...StopTasksOpts) error {
in := &ecs.StopTaskInput{}
for _, opt := range opts {
opt(in)
}
for _, task := range tasks {
in.Task = aws.String(task)
if _, err := e.client.StopTask(in); err != nil {
return fmt.Errorf("stop task %s: %w", task, err)
}
}
return nil
}
// DefaultCluster returns the default cluster ARN in the account and region.
func (e *ECS) DefaultCluster() (string, error) {
resp, err := e.client.DescribeClusters(&ecs.DescribeClustersInput{})
if err != nil {
return "", fmt.Errorf("get default cluster: %w", err)
}
if len(resp.Clusters) == 0 {
return "", ErrNoDefaultCluster
}
// NOTE: right now at most 1 default cluster is possible, so cluster[0] must be the default cluster
cluster := resp.Clusters[0]
if aws.StringValue(cluster.Status) != clusterStatusActive {
return "", ErrNoDefaultCluster
}
return aws.StringValue(cluster.ClusterArn), nil
}
// HasDefaultCluster tries to find the default cluster and returns true if there is one.
func (e *ECS) HasDefaultCluster() (bool, error) {
if _, err := e.DefaultCluster(); err != nil {
if errors.Is(err, ErrNoDefaultCluster) {
return false, nil
}
return false, err
}
return true, nil
}
// RunTask runs a number of tasks with the task definition and network configurations in a cluster, and returns after
// the task(s) is running or fails to run, along with task ARNs if possible.
func (e *ECS) RunTask(input RunTaskInput) ([]*Task, error) {
resp, err := e.client.RunTask(&ecs.RunTaskInput{
Cluster: aws.String(input.Cluster),
Count: aws.Int64(int64(input.Count)),
LaunchType: aws.String(ecs.LaunchTypeFargate),
StartedBy: aws.String(input.StartedBy),
TaskDefinition: aws.String(input.TaskFamilyName),
NetworkConfiguration: &ecs.NetworkConfiguration{
AwsvpcConfiguration: &ecs.AwsVpcConfiguration{
AssignPublicIp: aws.String(ecs.AssignPublicIpEnabled),
Subnets: aws.StringSlice(input.Subnets),
SecurityGroups: aws.StringSlice(input.SecurityGroups),
},
},
EnableExecuteCommand: aws.Bool(input.EnableExec),
PlatformVersion: aws.String(input.PlatformVersion),
PropagateTags: aws.String(ecs.PropagateTagsTaskDefinition),
})
if err != nil {
return nil, fmt.Errorf("run task(s) %s: %w", input.TaskFamilyName, err)
}
taskARNs := make([]string, len(resp.Tasks))
for idx, task := range resp.Tasks {
taskARNs[idx] = aws.StringValue(task.TaskArn)
}
waitErr := e.client.WaitUntilTasksRunning(&ecs.DescribeTasksInput{
Cluster: aws.String(input.Cluster),
Tasks: aws.StringSlice(taskARNs),
Include: aws.StringSlice([]string{ecs.TaskFieldTags}),
})
if waitErr != nil && !isRequestTimeoutErr(waitErr) {
return nil, fmt.Errorf("wait for tasks to be running: %w", waitErr)
}
tasks, describeErr := e.DescribeTasks(input.Cluster, taskARNs)
if describeErr != nil {
return nil, describeErr
}
if waitErr != nil {
return nil, &ErrWaiterResourceNotReadyForTasks{tasks: tasks, awsErrResourceNotReady: waitErr}
}
return tasks, nil
}
// DescribeTasks returns the tasks with the taskARNs in the cluster.
func (e *ECS) DescribeTasks(cluster string, taskARNs []string) ([]*Task, error) {
resp, err := e.client.DescribeTasks(&ecs.DescribeTasksInput{
Cluster: aws.String(cluster),
Tasks: aws.StringSlice(taskARNs),
Include: aws.StringSlice([]string{ecs.TaskFieldTags}),
})
if err != nil {
return nil, fmt.Errorf("describe tasks: %w", err)
}
tasks := make([]*Task, len(resp.Tasks))
for idx, task := range resp.Tasks {
t := Task(*task)
tasks[idx] = &t
}
return tasks, nil
}
// ExecuteCommand executes commands in a running container, and then terminate the session.
func (e *ECS) ExecuteCommand(in ExecuteCommandInput) (err error) {
execCmdresp, err := e.client.ExecuteCommand(&ecs.ExecuteCommandInput{
Cluster: aws.String(in.Cluster),
Command: aws.String(in.Command),
Container: aws.String(in.Container),
Interactive: aws.Bool(true),
Task: aws.String(in.Task),
})
if err != nil {
return &ErrExecuteCommand{err: err}
}
sessID := aws.StringValue(execCmdresp.Session.SessionId)
if err = e.newSessStarter().StartSession(execCmdresp.Session); err != nil {
err = fmt.Errorf("start session %s using ssm plugin: %w", sessID, err)
}
return err
}
// NetworkConfiguration returns the network configuration of a service.
func (e *ECS) NetworkConfiguration(cluster, serviceName string) (*NetworkConfiguration, error) {
service, err := e.service(cluster, serviceName)
if err != nil {
return nil, err
}
networkConfig := service.NetworkConfiguration
if networkConfig == nil || networkConfig.AwsvpcConfiguration == nil {
return nil, fmt.Errorf("cannot find the awsvpc configuration for service %s", serviceName)
}
return &NetworkConfiguration{
AssignPublicIp: aws.StringValue(networkConfig.AwsvpcConfiguration.AssignPublicIp),
SecurityGroups: aws.StringValueSlice(networkConfig.AwsvpcConfiguration.SecurityGroups),
Subnets: aws.StringValueSlice(networkConfig.AwsvpcConfiguration.Subnets),
}, nil
}
func (e *ECS) service(clusterName, serviceName string) (*Service, error) {
resp, err := e.client.DescribeServices(&ecs.DescribeServicesInput{
Cluster: aws.String(clusterName),
Services: aws.StringSlice([]string{serviceName}),
})
if err != nil {
return nil, fmt.Errorf("describe service %s: %w", serviceName, err)
}
for _, service := range resp.Services {
if aws.StringValue(service.ServiceName) == serviceName {
svc := Service(*service)
return &svc, nil
}
}
return nil, fmt.Errorf("cannot find service %s", serviceName)
}
func isRequestTimeoutErr(err error) bool {
if aerr, ok := err.(awserr.Error); ok {
return aerr.Code() == request.WaiterResourceNotReadyErrorCode
}
return false
}
| 453 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package ecs
import (
"errors"
"fmt"
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/service/ecs"
"github.com/aws/copilot-cli/internal/pkg/aws/ecs/mocks"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
func TestECS_TaskDefinition(t *testing.T) {
mockError := errors.New("error")
testCases := map[string]struct {
taskDefinitionName string
mockECSClient func(m *mocks.Mockapi)
wantErr error
wantTaskDef *TaskDefinition
}{
"should return wrapped error given error": {
taskDefinitionName: "task-def",
mockECSClient: func(m *mocks.Mockapi) {
m.EXPECT().DescribeTaskDefinition(&ecs.DescribeTaskDefinitionInput{
TaskDefinition: aws.String("task-def"),
}).Return(nil, mockError)
},
wantErr: fmt.Errorf("describe task definition %s: %w", "task-def", mockError),
},
"returns task definition given a task definition name": {
taskDefinitionName: "task-def",
mockECSClient: func(m *mocks.Mockapi) {
m.EXPECT().DescribeTaskDefinition(&ecs.DescribeTaskDefinitionInput{
TaskDefinition: aws.String("task-def"),
}).Return(&ecs.DescribeTaskDefinitionOutput{
TaskDefinition: &ecs.TaskDefinition{
ContainerDefinitions: []*ecs.ContainerDefinition{
{
Environment: []*ecs.KeyValuePair{
{
Name: aws.String("COPILOT_SERVICE_NAME"),
Value: aws.String("my-app"),
},
{
Name: aws.String("COPILOT_ENVIRONMENT_NAME"),
Value: aws.String("prod"),
},
},
},
},
},
}, nil)
},
wantTaskDef: &TaskDefinition{
ContainerDefinitions: []*ecs.ContainerDefinition{
{
Environment: []*ecs.KeyValuePair{
{
Name: aws.String("COPILOT_SERVICE_NAME"),
Value: aws.String("my-app"),
},
{
Name: aws.String("COPILOT_ENVIRONMENT_NAME"),
Value: aws.String("prod"),
},
},
},
},
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockECSClient := mocks.NewMockapi(ctrl)
tc.mockECSClient(mockECSClient)
service := ECS{
client: mockECSClient,
}
gotTaskDef, gotErr := service.TaskDefinition(tc.taskDefinitionName)
if gotErr != nil {
require.Equal(t, tc.wantErr, gotErr)
} else {
require.Equal(t, tc.wantTaskDef, gotTaskDef)
}
})
}
}
func TestECS_Service(t *testing.T) {
testCases := map[string]struct {
clusterName string
serviceName string
mockECSClient func(m *mocks.Mockapi)
wantErr error
wantSvc *Service
}{
"success": {
clusterName: "mockCluster",
serviceName: "mockService",
mockECSClient: func(m *mocks.Mockapi) {
m.EXPECT().DescribeServices(&ecs.DescribeServicesInput{
Cluster: aws.String("mockCluster"),
Services: aws.StringSlice([]string{"mockService"}),
}).Return(&ecs.DescribeServicesOutput{
Services: []*ecs.Service{
{
ServiceName: aws.String("mockService"),
},
},
}, nil)
},
wantSvc: &Service{
ServiceName: aws.String("mockService"),
},
},
"errors if failed to describe service": {
clusterName: "mockCluster",
serviceName: "mockService",
mockECSClient: func(m *mocks.Mockapi) {
m.EXPECT().DescribeServices(&ecs.DescribeServicesInput{
Cluster: aws.String("mockCluster"),
Services: aws.StringSlice([]string{"mockService"}),
}).Return(nil, errors.New("some error"))
},
wantErr: fmt.Errorf("describe service mockService: some error"),
},
"errors if failed to find the service": {
clusterName: "mockCluster",
serviceName: "mockService",
mockECSClient: func(m *mocks.Mockapi) {
m.EXPECT().DescribeServices(&ecs.DescribeServicesInput{
Cluster: aws.String("mockCluster"),
Services: aws.StringSlice([]string{"mockService"}),
}).Return(&ecs.DescribeServicesOutput{
Services: []*ecs.Service{
{
ServiceName: aws.String("badMockService"),
},
},
}, nil)
},
wantErr: fmt.Errorf("cannot find service mockService"),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockECSClient := mocks.NewMockapi(ctrl)
tc.mockECSClient(mockECSClient)
service := ECS{
client: mockECSClient,
}
gotSvc, gotErr := service.Service(tc.clusterName, tc.serviceName)
if gotErr != nil {
require.EqualError(t, tc.wantErr, gotErr.Error())
} else {
require.Equal(t, tc.wantSvc, gotSvc)
require.NoError(t, tc.wantErr)
}
})
}
}
func TestECS_UpdateService(t *testing.T) {
const (
clusterName = "mockCluster"
serviceName = "mockService"
)
testCases := map[string]struct {
forceUpdate bool
maxTryNum int
mockECSClient func(m *mocks.Mockapi)
wantErr error
wantSvc *Service
}{
"errors if failed to update service": {
mockECSClient: func(m *mocks.Mockapi) {
m.EXPECT().UpdateService(&ecs.UpdateServiceInput{
Cluster: aws.String(clusterName),
Service: aws.String(serviceName),
}).Return(nil, errors.New("some error"))
},
wantErr: fmt.Errorf("update service mockService from cluster mockCluster: some error"),
},
"errors if max retries exceeded": {
mockECSClient: func(m *mocks.Mockapi) {
m.EXPECT().UpdateService(&ecs.UpdateServiceInput{
Cluster: aws.String(clusterName),
Service: aws.String(serviceName),
}).Return(&ecs.UpdateServiceOutput{
Service: &ecs.Service{
Deployments: []*ecs.Deployment{{}, {}},
DesiredCount: aws.Int64(1),
RunningCount: aws.Int64(2),
ClusterArn: aws.String(clusterName),
ServiceName: aws.String(serviceName),
},
}, nil)
m.EXPECT().DescribeServices(&ecs.DescribeServicesInput{
Cluster: aws.String(clusterName),
Services: aws.StringSlice([]string{serviceName}),
}).Return(&ecs.DescribeServicesOutput{
Services: []*ecs.Service{
{
Deployments: []*ecs.Deployment{{}},
DesiredCount: aws.Int64(1),
RunningCount: aws.Int64(2),
ClusterArn: aws.String(clusterName),
ServiceName: aws.String(serviceName),
},
},
}, nil).Times(2)
},
wantErr: fmt.Errorf("wait until service mockService becomes stable: max retries 2 exceeded"),
},
"errors if failed to describe service": {
mockECSClient: func(m *mocks.Mockapi) {
m.EXPECT().UpdateService(&ecs.UpdateServiceInput{
Cluster: aws.String(clusterName),
Service: aws.String(serviceName),
}).Return(&ecs.UpdateServiceOutput{
Service: &ecs.Service{
Deployments: []*ecs.Deployment{{}, {}},
DesiredCount: aws.Int64(1),
RunningCount: aws.Int64(2),
ClusterArn: aws.String(clusterName),
ServiceName: aws.String(serviceName),
},
}, nil)
m.EXPECT().DescribeServices(&ecs.DescribeServicesInput{
Cluster: aws.String(clusterName),
Services: aws.StringSlice([]string{serviceName}),
}).Return(nil, errors.New("some error"))
},
wantErr: fmt.Errorf("wait until service mockService becomes stable: describe service mockService: some error"),
},
"success": {
forceUpdate: true,
mockECSClient: func(m *mocks.Mockapi) {
m.EXPECT().UpdateService(&ecs.UpdateServiceInput{
Cluster: aws.String(clusterName),
Service: aws.String(serviceName),
ForceNewDeployment: aws.Bool(true),
}).Return(&ecs.UpdateServiceOutput{
Service: &ecs.Service{
Deployments: []*ecs.Deployment{{}, {}},
DesiredCount: aws.Int64(1),
RunningCount: aws.Int64(2),
ClusterArn: aws.String(clusterName),
ServiceName: aws.String(serviceName),
},
}, nil)
m.EXPECT().DescribeServices(&ecs.DescribeServicesInput{
Cluster: aws.String(clusterName),
Services: aws.StringSlice([]string{serviceName}),
}).Return(&ecs.DescribeServicesOutput{
Services: []*ecs.Service{
{
Deployments: []*ecs.Deployment{{}},
DesiredCount: aws.Int64(1),
RunningCount: aws.Int64(2),
ClusterArn: aws.String(clusterName),
ServiceName: aws.String(serviceName),
},
},
}, nil)
m.EXPECT().DescribeServices(&ecs.DescribeServicesInput{
Cluster: aws.String(clusterName),
Services: aws.StringSlice([]string{serviceName}),
}).Return(&ecs.DescribeServicesOutput{
Services: []*ecs.Service{
{
Deployments: []*ecs.Deployment{{}},
DesiredCount: aws.Int64(1),
RunningCount: aws.Int64(1),
ClusterArn: aws.String(clusterName),
ServiceName: aws.String(serviceName),
},
},
}, nil)
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockECSClient := mocks.NewMockapi(ctrl)
tc.mockECSClient(mockECSClient)
service := ECS{
client: mockECSClient,
maxServiceStableTries: 2,
pollIntervalDuration: 0,
}
var opts []UpdateServiceOpts
if tc.forceUpdate {
opts = append(opts, WithForceUpdate())
}
gotErr := service.UpdateService(clusterName, serviceName, opts...)
if tc.wantErr != nil {
require.EqualError(t, tc.wantErr, gotErr.Error())
} else {
require.NoError(t, gotErr)
}
})
}
}
func TestECS_Tasks(t *testing.T) {
testCases := map[string]struct {
clusterName string
serviceName string
mockECSClient func(m *mocks.Mockapi)
wantErr error
wantTasks []*Task
}{
"errors if failed to list running tasks": {
clusterName: "mockCluster",
serviceName: "mockService",
mockECSClient: func(m *mocks.Mockapi) {
m.EXPECT().ListTasks(&ecs.ListTasksInput{
Cluster: aws.String("mockCluster"),
ServiceName: aws.String("mockService"),
DesiredStatus: aws.String("RUNNING"),
}).Return(nil, errors.New("some error"))
},
wantErr: fmt.Errorf("list running tasks: some error"),
},
"errors if failed to describe running tasks": {
clusterName: "mockCluster",
serviceName: "mockService",
mockECSClient: func(m *mocks.Mockapi) {
m.EXPECT().ListTasks(&ecs.ListTasksInput{
Cluster: aws.String("mockCluster"),
ServiceName: aws.String("mockService"),
DesiredStatus: aws.String("RUNNING"),
}).Return(&ecs.ListTasksOutput{
NextToken: nil,
TaskArns: aws.StringSlice([]string{"mockTaskArn"}),
}, nil)
m.EXPECT().DescribeTasks(&ecs.DescribeTasksInput{
Cluster: aws.String("mockCluster"),
Tasks: aws.StringSlice([]string{"mockTaskArn"}),
Include: aws.StringSlice([]string{ecs.TaskFieldTags}),
}).Return(nil, errors.New("some error"))
},
wantErr: fmt.Errorf("describe running tasks in cluster mockCluster: some error"),
},
"success": {
clusterName: "mockCluster",
serviceName: "mockService",
mockECSClient: func(m *mocks.Mockapi) {
m.EXPECT().ListTasks(&ecs.ListTasksInput{
Cluster: aws.String("mockCluster"),
ServiceName: aws.String("mockService"),
DesiredStatus: aws.String("RUNNING"),
}).Return(&ecs.ListTasksOutput{
NextToken: nil,
TaskArns: aws.StringSlice([]string{"mockTaskArn"}),
}, nil)
m.EXPECT().DescribeTasks(&ecs.DescribeTasksInput{
Cluster: aws.String("mockCluster"),
Tasks: aws.StringSlice([]string{"mockTaskArn"}),
Include: aws.StringSlice([]string{ecs.TaskFieldTags}),
}).Return(&ecs.DescribeTasksOutput{
Tasks: []*ecs.Task{
{
TaskArn: aws.String("mockTaskArn"),
},
},
}, nil)
},
wantTasks: []*Task{
{
TaskArn: aws.String("mockTaskArn"),
},
},
},
"success with pagination": {
clusterName: "mockCluster",
serviceName: "mockService",
mockECSClient: func(m *mocks.Mockapi) {
m.EXPECT().ListTasks(&ecs.ListTasksInput{
Cluster: aws.String("mockCluster"),
ServiceName: aws.String("mockService"),
DesiredStatus: aws.String("RUNNING"),
}).Return(&ecs.ListTasksOutput{
NextToken: aws.String("mockNextToken"),
TaskArns: aws.StringSlice([]string{"mockTaskArn1"}),
}, nil)
m.EXPECT().DescribeTasks(&ecs.DescribeTasksInput{
Cluster: aws.String("mockCluster"),
Tasks: aws.StringSlice([]string{"mockTaskArn1"}),
Include: aws.StringSlice([]string{ecs.TaskFieldTags}),
}).Return(&ecs.DescribeTasksOutput{
Tasks: []*ecs.Task{
{
TaskArn: aws.String("mockTaskArn1"),
},
},
}, nil)
m.EXPECT().ListTasks(&ecs.ListTasksInput{
Cluster: aws.String("mockCluster"),
ServiceName: aws.String("mockService"),
DesiredStatus: aws.String("RUNNING"),
NextToken: aws.String("mockNextToken"),
}).Return(&ecs.ListTasksOutput{
NextToken: nil,
TaskArns: aws.StringSlice([]string{"mockTaskArn2"}),
}, nil)
m.EXPECT().DescribeTasks(&ecs.DescribeTasksInput{
Cluster: aws.String("mockCluster"),
Tasks: aws.StringSlice([]string{"mockTaskArn2"}),
Include: aws.StringSlice([]string{ecs.TaskFieldTags}),
}).Return(&ecs.DescribeTasksOutput{
Tasks: []*ecs.Task{
{
TaskArn: aws.String("mockTaskArn2"),
},
},
}, nil)
},
wantTasks: []*Task{
{
TaskArn: aws.String("mockTaskArn1"),
},
{
TaskArn: aws.String("mockTaskArn2"),
},
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockECSClient := mocks.NewMockapi(ctrl)
tc.mockECSClient(mockECSClient)
service := ECS{
client: mockECSClient,
}
gotTasks, gotErr := service.ServiceRunningTasks(tc.clusterName, tc.serviceName)
if gotErr != nil {
require.EqualError(t, tc.wantErr, gotErr.Error())
} else {
require.Equal(t, tc.wantTasks, gotTasks)
}
})
}
}
func TestECS_StoppedServiceTasks(t *testing.T) {
testCases := map[string]struct {
clusterName string
serviceName string
mockECSClient func(m *mocks.Mockapi)
wantErr error
wantTasks []*Task
}{
"errors if failed to list stopped tasks": {
clusterName: "mockCluster",
serviceName: "mockService",
mockECSClient: func(m *mocks.Mockapi) {
m.EXPECT().ListTasks(&ecs.ListTasksInput{
Cluster: aws.String("mockCluster"),
ServiceName: aws.String("mockService"),
DesiredStatus: aws.String(ecs.DesiredStatusStopped),
}).Return(nil, errors.New("some error"))
},
wantErr: fmt.Errorf("list running tasks: some error"),
},
"errors if failed to describe stopped tasks": {
clusterName: "mockCluster",
serviceName: "mockService",
mockECSClient: func(m *mocks.Mockapi) {
m.EXPECT().ListTasks(&ecs.ListTasksInput{
Cluster: aws.String("mockCluster"),
ServiceName: aws.String("mockService"),
DesiredStatus: aws.String(ecs.DesiredStatusStopped),
}).Return(&ecs.ListTasksOutput{
NextToken: nil,
TaskArns: aws.StringSlice([]string{"mockTaskArn"}),
}, nil)
m.EXPECT().DescribeTasks(&ecs.DescribeTasksInput{
Cluster: aws.String("mockCluster"),
Tasks: aws.StringSlice([]string{"mockTaskArn"}),
Include: aws.StringSlice([]string{ecs.TaskFieldTags}),
}).Return(nil, errors.New("some error"))
},
wantErr: fmt.Errorf("describe running tasks in cluster mockCluster: some error"),
},
"success": {
clusterName: "mockCluster",
serviceName: "mockService",
mockECSClient: func(m *mocks.Mockapi) {
m.EXPECT().ListTasks(&ecs.ListTasksInput{
Cluster: aws.String("mockCluster"),
ServiceName: aws.String("mockService"),
DesiredStatus: aws.String(ecs.DesiredStatusStopped),
}).Return(&ecs.ListTasksOutput{
NextToken: nil,
TaskArns: aws.StringSlice([]string{"mockTaskArn"}),
}, nil)
m.EXPECT().DescribeTasks(&ecs.DescribeTasksInput{
Cluster: aws.String("mockCluster"),
Tasks: aws.StringSlice([]string{"mockTaskArn"}),
Include: aws.StringSlice([]string{ecs.TaskFieldTags}),
}).Return(&ecs.DescribeTasksOutput{
Tasks: []*ecs.Task{
{
TaskArn: aws.String("mockTaskArn"),
},
},
}, nil)
},
wantTasks: []*Task{
{
TaskArn: aws.String("mockTaskArn"),
},
},
},
"success with pagination": {
clusterName: "mockCluster",
serviceName: "mockService",
mockECSClient: func(m *mocks.Mockapi) {
m.EXPECT().ListTasks(&ecs.ListTasksInput{
Cluster: aws.String("mockCluster"),
ServiceName: aws.String("mockService"),
DesiredStatus: aws.String(ecs.DesiredStatusStopped),
}).Return(&ecs.ListTasksOutput{
NextToken: aws.String("mockNextToken"),
TaskArns: aws.StringSlice([]string{"mockTaskArn1"}),
}, nil)
m.EXPECT().DescribeTasks(&ecs.DescribeTasksInput{
Cluster: aws.String("mockCluster"),
Tasks: aws.StringSlice([]string{"mockTaskArn1"}),
Include: aws.StringSlice([]string{ecs.TaskFieldTags}),
}).Return(&ecs.DescribeTasksOutput{
Tasks: []*ecs.Task{
{
TaskArn: aws.String("mockTaskArn1"),
},
},
}, nil)
m.EXPECT().ListTasks(&ecs.ListTasksInput{
Cluster: aws.String("mockCluster"),
ServiceName: aws.String("mockService"),
DesiredStatus: aws.String(ecs.DesiredStatusStopped),
NextToken: aws.String("mockNextToken"),
}).Return(&ecs.ListTasksOutput{
NextToken: nil,
TaskArns: aws.StringSlice([]string{"mockTaskArn2"}),
}, nil)
m.EXPECT().DescribeTasks(&ecs.DescribeTasksInput{
Cluster: aws.String("mockCluster"),
Tasks: aws.StringSlice([]string{"mockTaskArn2"}),
Include: aws.StringSlice([]string{ecs.TaskFieldTags}),
}).Return(&ecs.DescribeTasksOutput{
Tasks: []*ecs.Task{
{
TaskArn: aws.String("mockTaskArn2"),
},
},
}, nil)
},
wantTasks: []*Task{
{
TaskArn: aws.String("mockTaskArn1"),
},
{
TaskArn: aws.String("mockTaskArn2"),
},
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockECSClient := mocks.NewMockapi(ctrl)
tc.mockECSClient(mockECSClient)
service := ECS{
client: mockECSClient,
}
gotTasks, gotErr := service.StoppedServiceTasks(tc.clusterName, tc.serviceName)
if gotErr != nil {
require.EqualError(t, tc.wantErr, gotErr.Error())
} else {
require.Equal(t, tc.wantTasks, gotTasks)
}
})
}
}
func TestECS_StopTasks(t *testing.T) {
mockTasks := []string{"mockTask1", "mockTask2"}
mockError := errors.New("some error")
testCases := map[string]struct {
cluster string
stopTasksReason string
tasks []string
mockECSClient func(m *mocks.Mockapi)
wantErr error
}{
"errors if failed to stop tasks in default cluster": {
tasks: mockTasks,
mockECSClient: func(m *mocks.Mockapi) {
m.EXPECT().StopTask(&ecs.StopTaskInput{
Task: aws.String("mockTask1"),
}).Return(&ecs.StopTaskOutput{}, nil)
m.EXPECT().StopTask(&ecs.StopTaskInput{
Task: aws.String("mockTask2"),
}).Return(&ecs.StopTaskOutput{}, mockError)
},
wantErr: fmt.Errorf("stop task mockTask2: some error"),
},
"success": {
tasks: mockTasks,
cluster: "mockCluster",
stopTasksReason: "some reason",
mockECSClient: func(m *mocks.Mockapi) {
m.EXPECT().StopTask(&ecs.StopTaskInput{
Cluster: aws.String("mockCluster"),
Reason: aws.String("some reason"),
Task: aws.String("mockTask1"),
}).Return(&ecs.StopTaskOutput{}, nil)
m.EXPECT().StopTask(&ecs.StopTaskInput{
Cluster: aws.String("mockCluster"),
Reason: aws.String("some reason"),
Task: aws.String("mockTask2"),
}).Return(&ecs.StopTaskOutput{}, nil)
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockECSClient := mocks.NewMockapi(ctrl)
tc.mockECSClient(mockECSClient)
service := ECS{
client: mockECSClient,
}
var opts []StopTasksOpts
if tc.cluster != "" {
opts = append(opts, WithStopTaskCluster(tc.cluster))
}
if tc.stopTasksReason != "" {
opts = append(opts, WithStopTaskReason(tc.stopTasksReason))
}
gotErr := service.StopTasks(tc.tasks, opts...)
if gotErr != nil {
require.EqualError(t, tc.wantErr, gotErr.Error())
} else {
require.NoError(t, tc.wantErr)
}
})
}
}
func TestECS_DefaultCluster(t *testing.T) {
testCases := map[string]struct {
mockECSClient func(m *mocks.Mockapi)
wantedError error
wantedClusters string
}{
"get default clusters success": {
mockECSClient: func(m *mocks.Mockapi) {
m.EXPECT().
DescribeClusters(&ecs.DescribeClustersInput{}).
Return(&ecs.DescribeClustersOutput{
Clusters: []*ecs.Cluster{
{
ClusterArn: aws.String("arn:aws:ecs:us-east-1:0123456:cluster/cluster1"),
ClusterName: aws.String("cluster1"),
Status: aws.String(clusterStatusActive),
},
{
ClusterArn: aws.String("arn:aws:ecs:us-east-1:0123456:cluster/cluster2"),
ClusterName: aws.String("cluster2"),
Status: aws.String(clusterStatusActive),
},
},
}, nil)
},
wantedClusters: "arn:aws:ecs:us-east-1:0123456:cluster/cluster1",
},
"ignore inactive cluster": {
mockECSClient: func(m *mocks.Mockapi) {
m.EXPECT().
DescribeClusters(&ecs.DescribeClustersInput{}).
Return(&ecs.DescribeClustersOutput{
Clusters: []*ecs.Cluster{
{
ClusterArn: aws.String("arn:aws:ecs:us-east-1:0123456:cluster/cluster1"),
ClusterName: aws.String("cluster1"),
Status: aws.String("INACTIVE"),
},
},
}, nil)
},
wantedError: fmt.Errorf("default cluster does not exist"),
},
"failed to get default clusters": {
mockECSClient: func(m *mocks.Mockapi) {
m.EXPECT().
DescribeClusters(&ecs.DescribeClustersInput{}).
Return(nil, errors.New("error"))
},
wantedError: fmt.Errorf("get default cluster: %s", "error"),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockECSClient := mocks.NewMockapi(ctrl)
tc.mockECSClient(mockECSClient)
ecs := ECS{
client: mockECSClient,
}
clusters, err := ecs.DefaultCluster()
if tc.wantedError != nil {
require.EqualError(t, tc.wantedError, err.Error())
} else {
require.Equal(t, tc.wantedClusters, clusters)
}
})
}
}
func TestECS_HasDefaultCluster(t *testing.T) {
testCases := map[string]struct {
mockECSClient func(m *mocks.Mockapi)
wantedHasDefaultCluster bool
wantedErr error
}{
"no default cluster": {
mockECSClient: func(m *mocks.Mockapi) {
m.EXPECT().DescribeClusters(&ecs.DescribeClustersInput{}).
Return(&ecs.DescribeClustersOutput{
Clusters: []*ecs.Cluster{},
}, nil)
},
wantedHasDefaultCluster: false,
},
"error getting default cluster": {
mockECSClient: func(m *mocks.Mockapi) {
m.EXPECT().DescribeClusters(&ecs.DescribeClustersInput{}).
Return(nil, errors.New("other error"))
},
wantedErr: fmt.Errorf("get default cluster: other error"),
},
"has default cluster": {
mockECSClient: func(m *mocks.Mockapi) {
m.EXPECT().DescribeClusters(&ecs.DescribeClustersInput{}).
Return(&ecs.DescribeClustersOutput{
Clusters: []*ecs.Cluster{
{
ClusterArn: aws.String("cluster"),
Status: aws.String(clusterStatusActive),
},
},
}, nil)
},
wantedHasDefaultCluster: true,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockECSClient := mocks.NewMockapi(ctrl)
tc.mockECSClient(mockECSClient)
ecs := ECS{
client: mockECSClient,
}
hasDefaultCluster, err := ecs.HasDefaultCluster()
if tc.wantedErr != nil {
require.EqualError(t, tc.wantedErr, err.Error())
} else {
require.NoError(t, err)
}
require.Equal(t, tc.wantedHasDefaultCluster, hasDefaultCluster)
})
}
}
func TestECS_RunTask(t *testing.T) {
type input struct {
cluster string
count int
subnets []string
securityGroups []string
taskFamilyName string
startedBy string
platformVersion string
enableExec bool
}
runTaskInput := input{
cluster: "my-cluster",
count: 3,
subnets: []string{"subnet-1", "subnet-2"},
securityGroups: []string{"sg-1", "sg-2"},
taskFamilyName: "my-task",
startedBy: "task",
platformVersion: "LATEST",
enableExec: true,
}
ecsTasks := []*ecs.Task{
{
TaskArn: aws.String("task-1"),
},
{
TaskArn: aws.String("task-2"),
},
{
TaskArn: aws.String("task-3"),
},
}
describeTasksInput := ecs.DescribeTasksInput{
Cluster: aws.String("my-cluster"),
Tasks: aws.StringSlice([]string{"task-1", "task-2", "task-3"}),
Include: aws.StringSlice([]string{ecs.TaskFieldTags}),
}
testCases := map[string]struct {
input
mockECSClient func(m *mocks.Mockapi)
wantedError error
wantedTasks []*Task
}{
"run task success": {
input: runTaskInput,
mockECSClient: func(m *mocks.Mockapi) {
m.EXPECT().RunTask(&ecs.RunTaskInput{
Cluster: aws.String("my-cluster"),
Count: aws.Int64(3),
LaunchType: aws.String(ecs.LaunchTypeFargate),
StartedBy: aws.String("task"),
TaskDefinition: aws.String("my-task"),
NetworkConfiguration: &ecs.NetworkConfiguration{
AwsvpcConfiguration: &ecs.AwsVpcConfiguration{
AssignPublicIp: aws.String(ecs.AssignPublicIpEnabled),
Subnets: aws.StringSlice([]string{"subnet-1", "subnet-2"}),
SecurityGroups: aws.StringSlice([]string{"sg-1", "sg-2"}),
},
},
EnableExecuteCommand: aws.Bool(true),
PlatformVersion: aws.String("LATEST"),
PropagateTags: aws.String(ecs.PropagateTagsTaskDefinition),
}).Return(&ecs.RunTaskOutput{
Tasks: ecsTasks,
}, nil)
m.EXPECT().WaitUntilTasksRunning(&describeTasksInput).Times(1)
m.EXPECT().DescribeTasks(&describeTasksInput).Return(&ecs.DescribeTasksOutput{
Tasks: ecsTasks,
}, nil)
},
wantedTasks: []*Task{
{
TaskArn: aws.String("task-1"),
},
{
TaskArn: aws.String("task-2"),
},
{
TaskArn: aws.String("task-3"),
},
},
},
"run task failed": {
input: runTaskInput,
mockECSClient: func(m *mocks.Mockapi) {
m.EXPECT().RunTask(&ecs.RunTaskInput{
Cluster: aws.String("my-cluster"),
Count: aws.Int64(3),
LaunchType: aws.String(ecs.LaunchTypeFargate),
StartedBy: aws.String("task"),
TaskDefinition: aws.String("my-task"),
NetworkConfiguration: &ecs.NetworkConfiguration{
AwsvpcConfiguration: &ecs.AwsVpcConfiguration{
AssignPublicIp: aws.String(ecs.AssignPublicIpEnabled),
Subnets: aws.StringSlice([]string{"subnet-1", "subnet-2"}),
SecurityGroups: aws.StringSlice([]string{"sg-1", "sg-2"}),
},
},
EnableExecuteCommand: aws.Bool(true),
PlatformVersion: aws.String("LATEST"),
PropagateTags: aws.String(ecs.PropagateTagsTaskDefinition),
}).
Return(&ecs.RunTaskOutput{}, errors.New("error"))
},
wantedError: errors.New("run task(s) my-task: error"),
},
"failed to call WaitUntilTasksRunning": {
input: runTaskInput,
mockECSClient: func(m *mocks.Mockapi) {
m.EXPECT().RunTask(&ecs.RunTaskInput{
Cluster: aws.String("my-cluster"),
Count: aws.Int64(3),
LaunchType: aws.String(ecs.LaunchTypeFargate),
StartedBy: aws.String("task"),
TaskDefinition: aws.String("my-task"),
NetworkConfiguration: &ecs.NetworkConfiguration{
AwsvpcConfiguration: &ecs.AwsVpcConfiguration{
AssignPublicIp: aws.String(ecs.AssignPublicIpEnabled),
Subnets: aws.StringSlice([]string{"subnet-1", "subnet-2"}),
SecurityGroups: aws.StringSlice([]string{"sg-1", "sg-2"}),
},
},
EnableExecuteCommand: aws.Bool(true),
PlatformVersion: aws.String("LATEST"),
PropagateTags: aws.String(ecs.PropagateTagsTaskDefinition),
}).
Return(&ecs.RunTaskOutput{
Tasks: ecsTasks,
}, nil)
m.EXPECT().WaitUntilTasksRunning(&describeTasksInput).Return(errors.New("some error"))
},
wantedError: errors.New("wait for tasks to be running: some error"),
},
"task failed to start": {
input: runTaskInput,
mockECSClient: func(m *mocks.Mockapi) {
m.EXPECT().RunTask(&ecs.RunTaskInput{
Cluster: aws.String("my-cluster"),
Count: aws.Int64(3),
LaunchType: aws.String(ecs.LaunchTypeFargate),
StartedBy: aws.String("task"),
TaskDefinition: aws.String("my-task"),
NetworkConfiguration: &ecs.NetworkConfiguration{
AwsvpcConfiguration: &ecs.AwsVpcConfiguration{
AssignPublicIp: aws.String(ecs.AssignPublicIpEnabled),
Subnets: aws.StringSlice([]string{"subnet-1", "subnet-2"}),
SecurityGroups: aws.StringSlice([]string{"sg-1", "sg-2"}),
},
},
EnableExecuteCommand: aws.Bool(true),
PlatformVersion: aws.String("LATEST"),
PropagateTags: aws.String(ecs.PropagateTagsTaskDefinition),
}).
Return(&ecs.RunTaskOutput{
Tasks: ecsTasks}, nil)
m.EXPECT().WaitUntilTasksRunning(&describeTasksInput).
Return(awserr.New(request.WaiterResourceNotReadyErrorCode, "some error", errors.New("some error")))
m.EXPECT().DescribeTasks(&describeTasksInput).Return(&ecs.DescribeTasksOutput{
Tasks: []*ecs.Task{
{
TaskArn: aws.String("task-1"),
},
{
TaskArn: aws.String("arn:aws:ecs:us-west-2:123456789:task/4082490ee6c245e09d2145010aa1ba8d"),
StoppedReason: aws.String("Task failed to start"),
LastStatus: aws.String("STOPPED"),
Containers: []*ecs.Container{
{
Reason: aws.String("CannotPullContainerError: inspect image has been retried 1 time(s)"),
LastStatus: aws.String("STOPPED"),
},
},
},
{
TaskArn: aws.String("task-3"),
},
},
}, nil)
},
wantedError: errors.New("task 4082490e: Task failed to start: CannotPullContainerError: inspect image has been retried 1 time(s)"),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockECSClient := mocks.NewMockapi(ctrl)
tc.mockECSClient(mockECSClient)
ecs := ECS{
client: mockECSClient,
}
tasks, err := ecs.RunTask(RunTaskInput{
Count: tc.count,
Cluster: tc.cluster,
TaskFamilyName: tc.taskFamilyName,
Subnets: tc.subnets,
SecurityGroups: tc.securityGroups,
StartedBy: tc.startedBy,
PlatformVersion: tc.platformVersion,
EnableExec: tc.enableExec,
})
if tc.wantedError != nil {
require.EqualError(t, tc.wantedError, err.Error())
} else {
require.Equal(t, tc.wantedTasks, tasks)
}
})
}
}
func TestECS_DescribeTasks(t *testing.T) {
inCluster := "my-cluster"
inTaskARNs := []string{"task-1", "task-2", "task-3"}
testCases := map[string]struct {
mockAPI func(m *mocks.Mockapi)
wantedError error
wantedTasks []*Task
}{
"error describing tasks": {
mockAPI: func(m *mocks.Mockapi) {
m.EXPECT().DescribeTasks(&ecs.DescribeTasksInput{
Cluster: aws.String(inCluster),
Tasks: aws.StringSlice(inTaskARNs),
Include: aws.StringSlice([]string{ecs.TaskFieldTags}),
}).Return(nil, errors.New("error describing tasks"))
},
wantedError: fmt.Errorf("describe tasks: %w", errors.New("error describing tasks")),
},
"successfully described tasks": {
mockAPI: func(m *mocks.Mockapi) {
m.EXPECT().DescribeTasks(&ecs.DescribeTasksInput{
Cluster: aws.String(inCluster),
Tasks: aws.StringSlice(inTaskARNs),
Include: aws.StringSlice([]string{ecs.TaskFieldTags}),
}).Return(&ecs.DescribeTasksOutput{
Tasks: []*ecs.Task{
{
TaskArn: aws.String("task-1"),
},
{
TaskArn: aws.String("task-2"),
},
{
TaskArn: aws.String("task-3"),
},
},
}, nil)
},
wantedTasks: []*Task{
{
TaskArn: aws.String("task-1"),
},
{
TaskArn: aws.String("task-2"),
},
{
TaskArn: aws.String("task-3"),
},
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockAPI := mocks.NewMockapi(ctrl)
tc.mockAPI(mockAPI)
ecs := ECS{
client: mockAPI,
}
tasks, err := ecs.DescribeTasks(inCluster, inTaskARNs)
if tc.wantedError != nil {
require.EqualError(t, tc.wantedError, err.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedTasks, tasks)
}
})
}
}
func TestECS_ExecuteCommand(t *testing.T) {
mockExecCmdIn := &ecs.ExecuteCommandInput{
Cluster: aws.String("mockCluster"),
Command: aws.String("mockCommand"),
Interactive: aws.Bool(true),
Container: aws.String("mockContainer"),
Task: aws.String("mockTask"),
}
mockSess := &ecs.Session{
SessionId: aws.String("mockSessID"),
}
mockErr := errors.New("some error")
testCases := map[string]struct {
mockAPI func(m *mocks.Mockapi)
mockSessStarter func(m *mocks.MockssmSessionStarter)
wantedError error
}{
"return error if fail to call ExecuteCommand": {
mockAPI: func(m *mocks.Mockapi) {
m.EXPECT().ExecuteCommand(mockExecCmdIn).Return(nil, mockErr)
},
mockSessStarter: func(m *mocks.MockssmSessionStarter) {},
wantedError: &ErrExecuteCommand{err: mockErr},
},
"return error if fail to start the session": {
mockAPI: func(m *mocks.Mockapi) {
m.EXPECT().ExecuteCommand(&ecs.ExecuteCommandInput{
Cluster: aws.String("mockCluster"),
Command: aws.String("mockCommand"),
Interactive: aws.Bool(true),
Container: aws.String("mockContainer"),
Task: aws.String("mockTask"),
}).Return(&ecs.ExecuteCommandOutput{
Session: mockSess,
}, nil)
},
mockSessStarter: func(m *mocks.MockssmSessionStarter) {
m.EXPECT().StartSession(mockSess).Return(mockErr)
},
wantedError: fmt.Errorf("start session mockSessID using ssm plugin: some error"),
},
"success": {
mockAPI: func(m *mocks.Mockapi) {
m.EXPECT().ExecuteCommand(mockExecCmdIn).Return(&ecs.ExecuteCommandOutput{
Session: mockSess,
}, nil)
},
mockSessStarter: func(m *mocks.MockssmSessionStarter) {
m.EXPECT().StartSession(mockSess).Return(nil)
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockAPI := mocks.NewMockapi(ctrl)
mockSessStarter := mocks.NewMockssmSessionStarter(ctrl)
tc.mockAPI(mockAPI)
tc.mockSessStarter(mockSessStarter)
ecs := ECS{
client: mockAPI,
newSessStarter: func() ssmSessionStarter {
return mockSessStarter
},
}
err := ecs.ExecuteCommand(ExecuteCommandInput{
Cluster: "mockCluster",
Command: "mockCommand",
Container: "mockContainer",
Task: "mockTask",
})
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
}
})
}
}
func TestECS_NetworkConfiguration(t *testing.T) {
testCases := map[string]struct {
mockAPI func(m *mocks.Mockapi)
wantedError error
wantedNetworkConfiguration *NetworkConfiguration
}{
"success": {
mockAPI: func(m *mocks.Mockapi) {
m.EXPECT().DescribeServices(&ecs.DescribeServicesInput{
Cluster: aws.String("crowded-cluster"),
Services: aws.StringSlice([]string{"cool-service"}),
}).Return(&ecs.DescribeServicesOutput{
Services: []*ecs.Service{
{
ServiceName: aws.String("cool-service"),
NetworkConfiguration: &ecs.NetworkConfiguration{
AwsvpcConfiguration: &ecs.AwsVpcConfiguration{
AssignPublicIp: aws.String("1.2.3.4"),
SecurityGroups: aws.StringSlice([]string{"sg-1", "sg-2"}),
Subnets: aws.StringSlice([]string{"sbn-1", "sbn-2"}),
},
},
},
},
}, nil)
},
wantedNetworkConfiguration: &NetworkConfiguration{
AssignPublicIp: "1.2.3.4",
SecurityGroups: []string{"sg-1", "sg-2"},
Subnets: []string{"sbn-1", "sbn-2"},
},
},
"fail to describe service": {
mockAPI: func(m *mocks.Mockapi) {
m.EXPECT().DescribeServices(&ecs.DescribeServicesInput{
Cluster: aws.String("crowded-cluster"),
Services: aws.StringSlice([]string{"cool-service"}),
}).Return(nil, errors.New("some error"))
},
wantedError: fmt.Errorf("describe service cool-service: some error"),
},
"fail to find awsvpc configuration": {
mockAPI: func(m *mocks.Mockapi) {
m.EXPECT().DescribeServices(&ecs.DescribeServicesInput{
Cluster: aws.String("crowded-cluster"),
Services: aws.StringSlice([]string{"cool-service"}),
}).Return(&ecs.DescribeServicesOutput{
Services: []*ecs.Service{
{
ServiceName: aws.String("cool-service"),
},
},
}, nil)
},
wantedError: errors.New("cannot find the awsvpc configuration for service cool-service"),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockAPI := mocks.NewMockapi(ctrl)
tc.mockAPI(mockAPI)
e := ECS{
client: mockAPI,
}
inCluster := "crowded-cluster"
inServiceName := "cool-service"
got, err := e.NetworkConfiguration(inCluster, inServiceName)
if tc.wantedError != nil {
require.EqualError(t, tc.wantedError, err.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedNetworkConfiguration, got)
}
})
}
}
| 1,322 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.