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 describe
import (
"bytes"
"encoding/json"
"fmt"
"strings"
"text/tabwriter"
"github.com/aws/copilot-cli/internal/pkg/aws/codepipeline"
"github.com/aws/copilot-cli/internal/pkg/aws/sessions"
"github.com/aws/copilot-cli/internal/pkg/config"
cfnstack "github.com/aws/copilot-cli/internal/pkg/deploy/cloudformation/stack"
"github.com/aws/copilot-cli/internal/pkg/describe/stack"
"github.com/aws/copilot-cli/internal/pkg/term/color"
"github.com/aws/copilot-cli/internal/pkg/version"
"golang.org/x/mod/semver"
"gopkg.in/yaml.v3"
)
// App contains serialized parameters for an application.
type App struct {
Name string `json:"name"`
Version string `json:"version"`
URI string `json:"uri"`
PermissionsBoundary string `json:"permissionsBoundary"`
Envs []*config.Environment `json:"environments"`
Services []*config.Workload `json:"services"`
Jobs []*config.Workload `json:"jobs"`
Pipelines []*codepipeline.Pipeline `json:"pipelines"`
WkldDeployedtoEnvs map[string][]string `json:"-"`
}
// JSONString returns the stringified App struct with json format.
func (a *App) JSONString() (string, error) {
b, err := json.Marshal(a)
if err != nil {
return "", fmt.Errorf("marshal application description: %w", err)
}
return fmt.Sprintf("%s\n", b), nil
}
// HumanString returns the stringified App struct with human readable format.
func (a *App) HumanString() string {
var b bytes.Buffer
writer := tabwriter.NewWriter(&b, minCellWidth, tabWidth, cellPaddingWidth, paddingChar, noAdditionalFormatting)
fmt.Fprint(writer, color.Bold.Sprint("About\n\n"))
writer.Flush()
fmt.Fprintf(writer, " %s\t%s\n", "Name", a.Name)
if a.URI == "" {
a.URI = "N/A"
}
if a.PermissionsBoundary == "" {
a.PermissionsBoundary = "N/A"
}
fmt.Fprintf(writer, " %s\t%s\n", "Version", a.Version)
fmt.Fprintf(writer, " %s\t%s\n", "URI", a.URI)
fmt.Fprintf(writer, " %s\t%s\n", "Permissions Boundary", a.PermissionsBoundary)
fmt.Fprint(writer, color.Bold.Sprint("\nEnvironments\n\n"))
writer.Flush()
headers := []string{"Name", "AccountID", "Region"}
fmt.Fprintf(writer, " %s\n", strings.Join(headers, "\t"))
fmt.Fprintf(writer, " %s\n", strings.Join(underline(headers), "\t"))
for _, env := range a.Envs {
fmt.Fprintf(writer, " %s\t%s\t%s\n", env.Name, env.AccountID, env.Region)
}
fmt.Fprint(writer, color.Bold.Sprint("\nWorkloads\n\n"))
writer.Flush()
headers = []string{"Name", "Type", "Environments"}
fmt.Fprintf(writer, " %s\n", strings.Join(headers, "\t"))
fmt.Fprintf(writer, " %s\n", strings.Join(underline(headers), "\t"))
for _, svc := range a.Services {
envs := "-"
if len(a.WkldDeployedtoEnvs[svc.Name]) > 0 {
envs = strings.Join(a.WkldDeployedtoEnvs[svc.Name], ", ")
}
fmt.Fprintf(writer, " %s\t%s\t%s\n", svc.Name, svc.Type, envs)
}
for _, job := range a.Jobs {
envs := "-"
if len(a.WkldDeployedtoEnvs[job.Name]) > 0 {
envs = strings.Join(a.WkldDeployedtoEnvs[job.Name], ", ")
}
fmt.Fprintf(writer, " %s\t%s\t%s\n", job.Name, job.Type, envs)
}
writer.Flush()
fmt.Fprint(writer, color.Bold.Sprint("\nPipelines\n\n"))
writer.Flush()
headers = []string{"Name"}
fmt.Fprintf(writer, " %s\n", strings.Join(headers, "\t"))
fmt.Fprintf(writer, " %s\n", strings.Join(underline(headers), "\t"))
for _, pipeline := range a.Pipelines {
fmt.Fprintf(writer, " %s\n", pipeline.Name)
}
writer.Flush()
return b.String()
}
// AppDescriber retrieves information about an application.
type AppDescriber struct {
app string
stackDescriber stackDescriber
stackSetDescriber stackDescriber
}
// NewAppDescriber instantiates an application describer.
func NewAppDescriber(appName string) (*AppDescriber, error) {
sess, err := sessions.ImmutableProvider().Default()
if err != nil {
return nil, fmt.Errorf("assume default role for app %s: %w", appName, err)
}
return &AppDescriber{
app: appName,
stackDescriber: stack.NewStackDescriber(cfnstack.NameForAppStack(appName), sess),
stackSetDescriber: stack.NewStackDescriber(cfnstack.NameForAppStackSet(appName), sess),
}, nil
}
// Version returns the app CloudFormation template version associated with
// the application by reading the Metadata.Version field from the template.
// Specifically it will get both app CFN stack template version and app StackSet template version,
// and return the minimum as the current app version.
//
// If the Version field does not exist, then it's a legacy template and it returns an deploy.LegacyAppTemplate and nil error.
func (d *AppDescriber) Version() (string, error) {
type metadata struct {
TemplateVersion string `yaml:"TemplateVersion"`
}
stackMetadata, stackSetMetadata := metadata{}, metadata{}
appStackMetadata, err := d.stackDescriber.StackMetadata()
if err != nil {
return "", err
}
if err := yaml.Unmarshal([]byte(appStackMetadata), &stackMetadata); err != nil {
return "", fmt.Errorf("unmarshal Metadata property from app %s stack: %w", d.app, err)
}
appStackVersion := stackMetadata.TemplateVersion
if appStackVersion == "" {
appStackVersion = version.LegacyAppTemplate
}
appStackSetMetadata, err := d.stackSetDescriber.StackSetMetadata()
if err != nil {
return "", err
}
if err := yaml.Unmarshal([]byte(appStackSetMetadata), &stackSetMetadata); err != nil {
return "", fmt.Errorf("unmarshal Metadata property for app %s stack set: %w", d.app, err)
}
appStackSetVersion := stackSetMetadata.TemplateVersion
if appStackSetVersion == "" {
appStackSetVersion = version.LegacyAppTemplate
}
minVersion := appStackVersion
if semver.Compare(appStackVersion, appStackSetVersion) > 0 {
minVersion = appStackSetVersion
}
return minVersion, nil
}
| 164 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package describe
import (
"errors"
"fmt"
"testing"
"github.com/aws/copilot-cli/internal/pkg/describe/mocks"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
func TestAppDescriber_Version(t *testing.T) {
testCases := map[string]struct {
given func(ctrl *gomock.Controller) *AppDescriber
wantedVersion string
wantedErr error
}{
"should return error if fail to get metadata": {
given: func(ctrl *gomock.Controller) *AppDescriber {
m := mocks.NewMockstackDescriber(ctrl)
m.EXPECT().StackMetadata().Return("", errors.New("some error"))
return &AppDescriber{
app: "phonetool",
stackDescriber: m,
stackSetDescriber: m,
}
},
wantedErr: fmt.Errorf("some error"),
},
"success": {
given: func(ctrl *gomock.Controller) *AppDescriber {
m := mocks.NewMockstackDescriber(ctrl)
m.EXPECT().StackMetadata().Return(`{"TemplateVersion":"v1.2.0"}`, nil)
m.EXPECT().StackSetMetadata().Return(`{"TemplateVersion":"v1.0.0"}`, nil)
return &AppDescriber{
app: "phonetool",
stackDescriber: m,
stackSetDescriber: m,
}
},
wantedVersion: "v1.0.0",
},
"success with legacy template": {
given: func(ctrl *gomock.Controller) *AppDescriber {
m := mocks.NewMockstackDescriber(ctrl)
m.EXPECT().StackMetadata().Return("", nil)
m.EXPECT().StackSetMetadata().Return(`{"TemplateVersion":"v1.0.0"}`, nil)
return &AppDescriber{
app: "phonetool",
stackDescriber: m,
stackSetDescriber: m,
}
},
wantedVersion: "v0.0.0",
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
d := tc.given(ctrl)
// WHEN
actual, err := d.Version()
// THEN
if tc.wantedErr != nil {
require.EqualError(t, err, tc.wantedErr.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedVersion, actual)
}
})
}
}
| 85 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package describe
import (
"bytes"
"encoding/json"
"fmt"
"strings"
"text/tabwriter"
"github.com/aws/copilot-cli/internal/pkg/aws/cloudwatch"
"github.com/aws/copilot-cli/internal/pkg/aws/elbv2"
"github.com/aws/copilot-cli/internal/pkg/aws/sessions"
"github.com/aws/copilot-cli/internal/pkg/docker/dockerengine"
"github.com/aws/copilot-cli/internal/pkg/manifest/manifestinfo"
"github.com/aws/copilot-cli/internal/pkg/template"
cfnstack "github.com/aws/copilot-cli/internal/pkg/deploy/cloudformation/stack"
"github.com/aws/copilot-cli/internal/pkg/describe/stack"
"github.com/aws/copilot-cli/internal/pkg/term/color"
)
const (
// BlankServiceDiscoveryURI is an empty URI to denote services
// that cannot be reached with Service Discovery.
BlankServiceDiscoveryURI = "-"
blankContainerPort = "-"
)
// BackendServiceDescriber retrieves information about a backend service.
type BackendServiceDescriber struct {
app string
svc string
enableResources bool
store DeployedEnvServicesLister
initECSServiceDescribers func(string) (ecsDescriber, error)
initEnvDescribers func(string) (envDescriber, error)
initLBDescriber func(string) (lbDescriber, error)
initCWDescriber func(string) (cwAlarmDescriber, error)
ecsServiceDescribers map[string]ecsDescriber
envStackDescriber map[string]envDescriber
cwAlarmDescribers map[string]cwAlarmDescriber
}
// NewBackendServiceDescriber instantiates a backend service describer.
func NewBackendServiceDescriber(opt NewServiceConfig) (*BackendServiceDescriber, error) {
describer := &BackendServiceDescriber{
app: opt.App,
svc: opt.Svc,
enableResources: opt.EnableResources,
store: opt.DeployStore,
ecsServiceDescribers: make(map[string]ecsDescriber),
envStackDescriber: make(map[string]envDescriber),
}
describer.initLBDescriber = func(envName string) (lbDescriber, error) {
env, err := opt.ConfigStore.GetEnvironment(opt.App, envName)
if err != nil {
return nil, fmt.Errorf("get environment %s: %w", envName, err)
}
sess, err := sessions.ImmutableProvider().FromRole(env.ManagerRoleARN, env.Region)
if err != nil {
return nil, err
}
return elbv2.New(sess), nil
}
describer.initECSServiceDescribers = func(env string) (ecsDescriber, error) {
if describer, ok := describer.ecsServiceDescribers[env]; ok {
return describer, nil
}
svcDescr, err := newECSServiceDescriber(NewServiceConfig{
App: opt.App,
Svc: opt.Svc,
ConfigStore: opt.ConfigStore,
}, env)
if err != nil {
return nil, err
}
describer.ecsServiceDescribers[env] = svcDescr
return svcDescr, nil
}
describer.initCWDescriber = func(envName string) (cwAlarmDescriber, error) {
if describer, ok := describer.cwAlarmDescribers[envName]; ok {
return describer, nil
}
env, err := opt.ConfigStore.GetEnvironment(opt.App, envName)
if err != nil {
return nil, fmt.Errorf("get environment %s: %w", envName, err)
}
sess, err := sessions.ImmutableProvider().FromRole(env.ManagerRoleARN, env.Region)
if err != nil {
return nil, err
}
return cloudwatch.New(sess), nil
}
describer.initEnvDescribers = func(env string) (envDescriber, error) {
if describer, ok := describer.envStackDescriber[env]; ok {
return describer, nil
}
envDescr, err := NewEnvDescriber(NewEnvDescriberConfig{
App: opt.App,
Env: env,
ConfigStore: opt.ConfigStore,
})
if err != nil {
return nil, err
}
describer.envStackDescriber[env] = envDescr
return envDescr, nil
}
return describer, nil
}
// Describe returns info of a backend service.
func (d *BackendServiceDescriber) Describe() (HumanJSONStringer, error) {
environments, err := d.store.ListEnvironmentsDeployedTo(d.app, d.svc)
if err != nil {
return nil, fmt.Errorf("list deployed environments for application %s: %w", d.app, err)
}
var routes []*WebServiceRoute
var configs []*ECSServiceConfig
sdEndpoints := make(serviceDiscoveries)
scEndpoints := make(serviceConnects)
var envVars []*containerEnvVar
var secrets []*secret
var alarmDescriptions []*cloudwatch.AlarmDescription
for _, env := range environments {
svcDescr, err := d.initECSServiceDescribers(env)
if err != nil {
return nil, err
}
uri, err := d.URI(env)
if err != nil {
return nil, fmt.Errorf("retrieve service URI: %w", err)
}
if uri.AccessType == URIAccessTypeInternal {
routes = append(routes, &WebServiceRoute{
Environment: env,
URL: uri.URI,
})
}
svcParams, err := svcDescr.Params()
if err != nil {
return nil, fmt.Errorf("get stack parameters for environment %s: %w", env, err)
}
envDescr, err := d.initEnvDescribers(env)
if err != nil {
return nil, err
}
port := blankContainerPort
if isReachableWithinVPC(svcParams) {
port = svcParams[cfnstack.WorkloadTargetPortParamKey]
if err := sdEndpoints.collectEndpoints(envDescr, d.svc, env, port); err != nil {
return nil, err
}
if err := scEndpoints.collectEndpoints(svcDescr, env); err != nil {
return nil, err
}
}
containerPlatform, err := svcDescr.Platform()
if err != nil {
return nil, fmt.Errorf("retrieve platform: %w", err)
}
configs = append(configs, &ECSServiceConfig{
ServiceConfig: &ServiceConfig{
Environment: env,
Port: port,
CPU: svcParams[cfnstack.WorkloadTaskCPUParamKey],
Memory: svcParams[cfnstack.WorkloadTaskMemoryParamKey],
Platform: dockerengine.PlatformString(containerPlatform.OperatingSystem, containerPlatform.Architecture),
},
Tasks: svcParams[cfnstack.WorkloadTaskCountParamKey],
})
alarmNames, err := svcDescr.RollbackAlarmNames()
if err != nil {
return nil, fmt.Errorf("retrieve rollback alarm names: %w", err)
}
if len(alarmNames) != 0 {
cwAlarmDescr, err := d.initCWDescriber(env)
if err != nil {
return nil, err
}
alarmDescs, err := cwAlarmDescr.AlarmDescriptions(alarmNames)
if err != nil {
return nil, fmt.Errorf("retrieve alarm descriptions: %w", err)
}
for _, alarm := range alarmDescs {
alarm.Environment = env
}
alarmDescriptions = append(alarmDescriptions, alarmDescs...)
}
backendSvcEnvVars, err := svcDescr.EnvVars()
if err != nil {
return nil, fmt.Errorf("retrieve environment variables: %w", err)
}
envVars = append(envVars, flattenContainerEnvVars(env, backendSvcEnvVars)...)
webSvcSecrets, err := svcDescr.Secrets()
if err != nil {
return nil, fmt.Errorf("retrieve secrets: %w", err)
}
secrets = append(secrets, flattenSecrets(env, webSvcSecrets)...)
}
resources := make(map[string][]*stack.Resource)
if d.enableResources {
for _, env := range environments {
svcDescr, err := d.initECSServiceDescribers(env)
if err != nil {
return nil, err
}
stackResources, err := svcDescr.StackResources()
if err != nil {
return nil, fmt.Errorf("retrieve service resources: %w", err)
}
resources[env] = stackResources
}
}
return &backendSvcDesc{
ecsSvcDesc: ecsSvcDesc{
Service: d.svc,
Type: manifestinfo.BackendServiceType,
App: d.app,
Configurations: configs,
AlarmDescriptions: alarmDescriptions,
Routes: routes,
ServiceDiscovery: sdEndpoints,
ServiceConnect: scEndpoints,
Variables: envVars,
Secrets: secrets,
Resources: resources,
environments: environments,
},
}, nil
}
// Manifest returns the contents of the manifest used to deploy a backend service stack.
// If the Manifest metadata doesn't exist in the stack template, then returns ErrManifestNotFoundInTemplate.
func (d *BackendServiceDescriber) Manifest(env string) ([]byte, error) {
cfn, err := d.initECSServiceDescribers(env)
if err != nil {
return nil, err
}
return cfn.Manifest()
}
// backendSvcDesc contains serialized parameters for a backend service.
type backendSvcDesc struct {
ecsSvcDesc
}
// JSONString returns the stringified backendService struct with json format.
func (w *backendSvcDesc) JSONString() (string, error) {
b, err := json.Marshal(w)
if err != nil {
return "", fmt.Errorf("marshal backend service description: %w", err)
}
return fmt.Sprintf("%s\n", b), nil
}
// HumanString returns the stringified backendService struct with human readable format.
func (w *backendSvcDesc) HumanString() string {
var b bytes.Buffer
writer := tabwriter.NewWriter(&b, minCellWidth, tabWidth, cellPaddingWidth, paddingChar, noAdditionalFormatting)
fmt.Fprint(writer, color.Bold.Sprint("About\n\n"))
writer.Flush()
fmt.Fprintf(writer, " %s\t%s\n", "Application", w.App)
fmt.Fprintf(writer, " %s\t%s\n", "Name", w.Service)
fmt.Fprintf(writer, " %s\t%s\n", "Type", w.Type)
fmt.Fprint(writer, color.Bold.Sprint("\nConfigurations\n\n"))
writer.Flush()
w.Configurations.humanString(writer)
if len(w.AlarmDescriptions) > 0 {
fmt.Fprint(writer, color.Bold.Sprint("\nRollback Alarms\n\n"))
writer.Flush()
rollbackAlarms(w.AlarmDescriptions).humanString(writer)
}
if len(w.Routes) > 0 {
fmt.Fprint(writer, color.Bold.Sprint("\nRoutes\n\n"))
writer.Flush()
headers := []string{"Environment", "URL"}
fmt.Fprintf(writer, " %s\n", strings.Join(headers, "\t"))
fmt.Fprintf(writer, " %s\n", strings.Join(underline(headers), "\t"))
for _, route := range w.Routes {
fmt.Fprintf(writer, " %s\t%s\n", route.Environment, route.URL)
}
}
if len(w.ServiceConnect) > 0 || len(w.ServiceDiscovery) > 0 {
fmt.Fprint(writer, color.Bold.Sprint("\nInternal Service Endpoint\n\n"))
writer.Flush()
endpoints := serviceEndpoints{
discoveries: w.ServiceDiscovery,
connects: w.ServiceConnect,
}
endpoints.humanString(writer)
}
fmt.Fprint(writer, color.Bold.Sprint("\nVariables\n\n"))
writer.Flush()
w.Variables.humanString(writer)
if len(w.Secrets) != 0 {
fmt.Fprint(writer, color.Bold.Sprint("\nSecrets\n\n"))
writer.Flush()
w.Secrets.humanString(writer)
}
if len(w.Resources) != 0 {
fmt.Fprint(writer, color.Bold.Sprint("\nResources\n"))
writer.Flush()
w.Resources.humanStringByEnv(writer, w.environments)
}
writer.Flush()
return b.String()
}
func isReachableWithinVPC(params map[string]string) bool {
return params[cfnstack.WorkloadTargetPortParamKey] != template.NoExposedContainerPort
}
| 322 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package describe
import (
"errors"
"fmt"
"testing"
"github.com/aws/copilot-cli/internal/pkg/aws/cloudwatch"
"github.com/aws/copilot-cli/internal/pkg/aws/ecs"
cfnstack "github.com/aws/copilot-cli/internal/pkg/deploy/cloudformation/stack"
"github.com/aws/copilot-cli/internal/pkg/describe/mocks"
"github.com/aws/copilot-cli/internal/pkg/describe/stack"
describeStack "github.com/aws/copilot-cli/internal/pkg/describe/stack"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
type backendSvcDescriberMocks struct {
storeSvc *mocks.MockDeployedEnvServicesLister
ecsDescriber *mocks.MockecsDescriber
cwDescriber *mocks.MockcwAlarmDescriber
envDescriber *mocks.MockenvDescriber
lbDescriber *mocks.MocklbDescriber
}
func TestBackendServiceDescriber_Describe(t *testing.T) {
const (
testApp = "phonetool"
testEnv = "test"
testSvc = "jobs"
prodEnv = "prod"
mockEnv = "mockEnv"
alarm1 = "alarm1"
alarm2 = "alarm2"
desc1 = "alarm description 1"
desc2 = "alarm description 2"
)
mockErr := errors.New("some error")
testCases := map[string]struct {
shouldOutputResources bool
setupMocks func(mocks backendSvcDescriberMocks)
wantedBackendSvc *backendSvcDesc
wantedError error
}{
"return error if fail to list environment": {
setupMocks: func(m backendSvcDescriberMocks) {
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return(nil, mockErr),
)
},
wantedError: fmt.Errorf("list deployed environments for application phonetool: some error"),
},
"return error if fail to retrieve service deployment configuration": {
setupMocks: func(m backendSvcDescriberMocks) {
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv}, nil),
m.ecsDescriber.EXPECT().StackResources().Return(nil, nil),
m.ecsDescriber.EXPECT().Params().Return(nil, mockErr),
)
},
wantedError: fmt.Errorf("retrieve service URI: get stack parameters for environment test: some error"),
},
"return error if fail to retrieve svc discovery endpoint": {
setupMocks: func(m backendSvcDescriberMocks) {
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv}, nil),
m.ecsDescriber.EXPECT().StackResources().Return(nil, nil),
m.ecsDescriber.EXPECT().Params().Return(map[string]string{
cfnstack.WorkloadTargetPortParamKey: "80",
cfnstack.WorkloadTaskCountParamKey: "1",
cfnstack.WorkloadTaskMemoryParamKey: "512",
cfnstack.WorkloadTaskCPUParamKey: "256",
}, nil),
m.ecsDescriber.EXPECT().ServiceConnectDNSNames().Return(nil, nil),
m.envDescriber.EXPECT().ServiceDiscoveryEndpoint().Return("", mockErr),
)
},
wantedError: fmt.Errorf("retrieve service URI: retrieve service discovery endpoint for environment test: some error"),
},
"return error if fail to retrieve service connect dns names": {
setupMocks: func(m backendSvcDescriberMocks) {
params := map[string]string{
cfnstack.WorkloadTargetPortParamKey: "5000",
cfnstack.WorkloadTaskCountParamKey: "1",
cfnstack.WorkloadTaskCPUParamKey: "256",
cfnstack.WorkloadTaskMemoryParamKey: "512",
}
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv}, nil),
m.ecsDescriber.EXPECT().StackResources().Return(nil, nil),
m.ecsDescriber.EXPECT().Params().Return(params, nil),
m.ecsDescriber.EXPECT().ServiceConnectDNSNames().Return(nil, nil),
m.envDescriber.EXPECT().ServiceDiscoveryEndpoint().Return("test.phonetool.local", nil),
m.ecsDescriber.EXPECT().Params().Return(params, nil),
m.envDescriber.EXPECT().ServiceDiscoveryEndpoint().Return("test.phonetool.local", nil),
m.ecsDescriber.EXPECT().ServiceConnectDNSNames().Return(nil, mockErr),
)
},
wantedError: fmt.Errorf("retrieve service connect DNS names: some error"),
},
"return error if fail to retrieve platform": {
setupMocks: func(m backendSvcDescriberMocks) {
params := map[string]string{
cfnstack.WorkloadTargetPortParamKey: "5000",
cfnstack.WorkloadTaskCountParamKey: "1",
cfnstack.WorkloadTaskCPUParamKey: "256",
cfnstack.WorkloadTaskMemoryParamKey: "512",
}
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv}, nil),
m.ecsDescriber.EXPECT().StackResources().Return(nil, nil),
m.ecsDescriber.EXPECT().Params().Return(params, nil),
m.ecsDescriber.EXPECT().ServiceConnectDNSNames().Return(nil, nil),
m.envDescriber.EXPECT().ServiceDiscoveryEndpoint().Return("test.phonetool.local", nil),
m.ecsDescriber.EXPECT().Params().Return(params, nil),
m.envDescriber.EXPECT().ServiceDiscoveryEndpoint().Return("test.phonetool.local", nil),
m.ecsDescriber.EXPECT().ServiceConnectDNSNames().Return(nil, nil),
m.ecsDescriber.EXPECT().Platform().Return(nil, mockErr),
)
},
wantedError: fmt.Errorf("retrieve platform: some error"),
},
"return error if fail to retrieve rollback alarm names": {
setupMocks: func(m backendSvcDescriberMocks) {
params := map[string]string{
cfnstack.WorkloadTargetPortParamKey: "5000",
cfnstack.WorkloadTaskCountParamKey: "1",
cfnstack.WorkloadTaskCPUParamKey: "256",
cfnstack.WorkloadTaskMemoryParamKey: "512",
}
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv}, nil),
m.ecsDescriber.EXPECT().StackResources().Return(nil, nil),
m.ecsDescriber.EXPECT().Params().Return(params, nil),
m.ecsDescriber.EXPECT().ServiceConnectDNSNames().Return(nil, nil),
m.envDescriber.EXPECT().ServiceDiscoveryEndpoint().Return("test.phonetool.local", nil),
m.ecsDescriber.EXPECT().Params().Return(params, nil),
m.envDescriber.EXPECT().ServiceDiscoveryEndpoint().Return("test.phonetool.local", nil),
m.ecsDescriber.EXPECT().ServiceConnectDNSNames().Return(nil, nil),
m.ecsDescriber.EXPECT().Platform().Return(&ecs.ContainerPlatform{
OperatingSystem: "LINUX",
Architecture: "X86_64",
}, nil),
m.ecsDescriber.EXPECT().RollbackAlarmNames().Return(nil, mockErr),
)
},
wantedError: fmt.Errorf("retrieve rollback alarm names: some error"),
},
"return error if fail to retrieve rollback alarm descriptions": {
setupMocks: func(m backendSvcDescriberMocks) {
params := map[string]string{
cfnstack.WorkloadTargetPortParamKey: "5000",
cfnstack.WorkloadTaskCountParamKey: "1",
cfnstack.WorkloadTaskCPUParamKey: "256",
cfnstack.WorkloadTaskMemoryParamKey: "512",
}
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv}, nil),
m.ecsDescriber.EXPECT().StackResources().Return(nil, nil),
m.ecsDescriber.EXPECT().Params().Return(params, nil),
m.ecsDescriber.EXPECT().ServiceConnectDNSNames().Return(nil, nil),
m.envDescriber.EXPECT().ServiceDiscoveryEndpoint().Return("test.phonetool.local", nil),
m.ecsDescriber.EXPECT().Params().Return(params, nil),
m.envDescriber.EXPECT().ServiceDiscoveryEndpoint().Return("test.phonetool.local", nil),
m.ecsDescriber.EXPECT().ServiceConnectDNSNames().Return(nil, nil),
m.ecsDescriber.EXPECT().Platform().Return(&ecs.ContainerPlatform{
OperatingSystem: "LINUX",
Architecture: "X86_64",
}, nil),
m.ecsDescriber.EXPECT().RollbackAlarmNames().Return([]string{alarm1, alarm2}, nil),
m.cwDescriber.EXPECT().AlarmDescriptions([]string{alarm1, alarm2}).Return(nil, errors.New("some error")),
)
},
wantedError: fmt.Errorf("retrieve alarm descriptions: some error"),
},
"return error if fail to retrieve environment variables": {
setupMocks: func(m backendSvcDescriberMocks) {
params := map[string]string{
cfnstack.WorkloadTargetPortParamKey: "5000",
cfnstack.WorkloadTaskCountParamKey: "1",
cfnstack.WorkloadTaskCPUParamKey: "256",
cfnstack.WorkloadTaskMemoryParamKey: "512",
}
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv}, nil),
m.ecsDescriber.EXPECT().StackResources().Return(nil, nil),
m.ecsDescriber.EXPECT().Params().Return(params, nil),
m.ecsDescriber.EXPECT().ServiceConnectDNSNames().Return(nil, nil),
m.envDescriber.EXPECT().ServiceDiscoveryEndpoint().Return("test.phonetool.local", nil),
m.ecsDescriber.EXPECT().Params().Return(params, nil),
m.envDescriber.EXPECT().ServiceDiscoveryEndpoint().Return("test.phonetool.local", nil),
m.ecsDescriber.EXPECT().ServiceConnectDNSNames().Return(nil, nil),
m.ecsDescriber.EXPECT().Platform().Return(&ecs.ContainerPlatform{
OperatingSystem: "LINUX",
Architecture: "X86_64",
}, nil),
m.ecsDescriber.EXPECT().RollbackAlarmNames().Return(nil, nil),
m.ecsDescriber.EXPECT().EnvVars().Return(nil, mockErr),
)
},
wantedError: fmt.Errorf("retrieve environment variables: some error"),
},
"return error if fail to retrieve secrets": {
setupMocks: func(m backendSvcDescriberMocks) {
params := map[string]string{
cfnstack.WorkloadTargetPortParamKey: "80",
cfnstack.WorkloadTaskCountParamKey: "1",
cfnstack.WorkloadTaskCPUParamKey: "256",
cfnstack.WorkloadTaskMemoryParamKey: "512",
}
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv}, nil),
m.ecsDescriber.EXPECT().StackResources().Return(nil, nil),
m.ecsDescriber.EXPECT().Params().Return(params, nil),
m.ecsDescriber.EXPECT().ServiceConnectDNSNames().Return(nil, nil),
m.envDescriber.EXPECT().ServiceDiscoveryEndpoint().Return("test.phonetool.local", nil),
m.ecsDescriber.EXPECT().Params().Return(params, nil),
m.envDescriber.EXPECT().ServiceDiscoveryEndpoint().Return("test.phonetool.local", nil),
m.ecsDescriber.EXPECT().ServiceConnectDNSNames().Return(nil, nil),
m.ecsDescriber.EXPECT().Platform().Return(&ecs.ContainerPlatform{
OperatingSystem: "LINUX",
Architecture: "X86_64",
}, nil),
m.ecsDescriber.EXPECT().RollbackAlarmNames().Return(nil, nil),
m.ecsDescriber.EXPECT().EnvVars().Return([]*ecs.ContainerEnvVar{
{
Name: "COPILOT_ENVIRONMENT_NAME",
Container: "container",
Value: "prod",
},
}, nil),
m.ecsDescriber.EXPECT().Secrets().Return(nil, mockErr),
)
},
wantedError: fmt.Errorf("retrieve secrets: some error"),
},
"should not fetch descriptions if no ROLLBACK alarms present": {
setupMocks: func(m backendSvcDescriberMocks) {
testParams := map[string]string{
cfnstack.WorkloadTargetPortParamKey: "5000",
cfnstack.WorkloadTaskCountParamKey: "1",
cfnstack.WorkloadTaskCPUParamKey: "256",
cfnstack.WorkloadTaskMemoryParamKey: "512",
}
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv}, nil),
m.ecsDescriber.EXPECT().StackResources().Return(nil, nil),
m.ecsDescriber.EXPECT().Params().Return(testParams, nil),
m.ecsDescriber.EXPECT().ServiceConnectDNSNames().Return(nil, nil),
m.envDescriber.EXPECT().ServiceDiscoveryEndpoint().Return("test.phonetool.local", nil),
m.ecsDescriber.EXPECT().Params().Return(testParams, nil),
m.envDescriber.EXPECT().ServiceDiscoveryEndpoint().Return("test.phonetool.local", nil),
m.ecsDescriber.EXPECT().ServiceConnectDNSNames().Return(nil, nil),
m.ecsDescriber.EXPECT().Platform().Return(&ecs.ContainerPlatform{
OperatingSystem: "LINUX",
Architecture: "X86_64",
}, nil),
m.ecsDescriber.EXPECT().RollbackAlarmNames().Return([]string{}, nil),
m.ecsDescriber.EXPECT().EnvVars().Return([]*ecs.ContainerEnvVar{}, nil),
m.ecsDescriber.EXPECT().Secrets().Return([]*ecs.ContainerSecret{}, nil))
},
wantedBackendSvc: &backendSvcDesc{
ecsSvcDesc: ecsSvcDesc{
Service: testSvc,
Type: "Backend Service",
App: testApp,
Configurations: []*ECSServiceConfig{
{
ServiceConfig: &ServiceConfig{
CPU: "256",
Environment: "test",
Memory: "512",
Platform: "LINUX/X86_64",
Port: "5000",
},
Tasks: "1",
},
},
ServiceDiscovery: serviceDiscoveries{
"jobs.test.phonetool.local:5000": []string{"test"},
},
ServiceConnect: serviceConnects{},
Resources: map[string][]*stack.Resource{},
environments: []string{"test"},
},
},
},
"success": {
shouldOutputResources: true,
setupMocks: func(m backendSvcDescriberMocks) {
testParams := map[string]string{
cfnstack.WorkloadTargetPortParamKey: "5000",
cfnstack.WorkloadTaskCountParamKey: "1",
cfnstack.WorkloadTaskCPUParamKey: "256",
cfnstack.WorkloadTaskMemoryParamKey: "512",
}
prodParams := map[string]string{
cfnstack.WorkloadTargetPortParamKey: "5000",
cfnstack.WorkloadTaskCountParamKey: "2",
cfnstack.WorkloadTaskCPUParamKey: "512",
cfnstack.WorkloadTaskMemoryParamKey: "1024",
}
mockParams := map[string]string{
cfnstack.WorkloadTargetPortParamKey: "-1",
cfnstack.WorkloadTaskCountParamKey: "2",
cfnstack.WorkloadTaskCPUParamKey: "512",
cfnstack.WorkloadTaskMemoryParamKey: "1024",
}
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv, prodEnv, mockEnv}, nil),
m.ecsDescriber.EXPECT().StackResources().Return(nil, nil),
m.ecsDescriber.EXPECT().Params().Return(testParams, nil),
m.ecsDescriber.EXPECT().ServiceConnectDNSNames().Return(nil, nil),
m.envDescriber.EXPECT().ServiceDiscoveryEndpoint().Return("test.phonetool.local", nil),
m.ecsDescriber.EXPECT().Params().Return(testParams, nil),
m.envDescriber.EXPECT().ServiceDiscoveryEndpoint().Return("test.phonetool.local", nil),
m.ecsDescriber.EXPECT().ServiceConnectDNSNames().Return(nil, nil),
m.ecsDescriber.EXPECT().Platform().Return(&ecs.ContainerPlatform{
OperatingSystem: "LINUX",
Architecture: "X86_64",
}, nil),
m.ecsDescriber.EXPECT().RollbackAlarmNames().Return(nil, nil),
m.ecsDescriber.EXPECT().EnvVars().Return([]*ecs.ContainerEnvVar{
{
Name: "COPILOT_ENVIRONMENT_NAME",
Container: "container",
Value: testEnv,
},
}, nil),
m.ecsDescriber.EXPECT().Secrets().Return([]*ecs.ContainerSecret{
{
Name: "GITHUB_WEBHOOK_SECRET",
Container: "container",
ValueFrom: "GH_WEBHOOK_SECRET",
},
}, nil),
m.ecsDescriber.EXPECT().StackResources().Return(nil, nil),
m.ecsDescriber.EXPECT().Params().Return(prodParams, nil),
m.ecsDescriber.EXPECT().ServiceConnectDNSNames().Return(nil, nil),
m.envDescriber.EXPECT().ServiceDiscoveryEndpoint().Return("prod.phonetool.local", nil),
m.ecsDescriber.EXPECT().Params().Return(prodParams, nil),
m.envDescriber.EXPECT().ServiceDiscoveryEndpoint().Return("prod.phonetool.local", nil),
m.ecsDescriber.EXPECT().ServiceConnectDNSNames().Return(nil, nil),
m.ecsDescriber.EXPECT().Platform().Return(&ecs.ContainerPlatform{
OperatingSystem: "LINUX",
Architecture: "ARM64",
}, nil),
m.ecsDescriber.EXPECT().RollbackAlarmNames().Return([]string{alarm1}, nil),
m.cwDescriber.EXPECT().AlarmDescriptions([]string{alarm1}).Return([]*cloudwatch.AlarmDescription{
{
Name: alarm1,
Description: desc1,
},
}, nil),
m.ecsDescriber.EXPECT().EnvVars().Return([]*ecs.ContainerEnvVar{
{
Name: "COPILOT_ENVIRONMENT_NAME",
Container: "container",
Value: prodEnv,
},
}, nil),
m.ecsDescriber.EXPECT().Secrets().Return([]*ecs.ContainerSecret{
{
Name: "SOME_OTHER_SECRET",
Container: "container",
ValueFrom: "SHHHHHHHH",
},
}, nil),
m.ecsDescriber.EXPECT().StackResources().Return(nil, nil),
m.ecsDescriber.EXPECT().Params().Return(mockParams, nil),
m.ecsDescriber.EXPECT().Params().Return(mockParams, nil),
m.ecsDescriber.EXPECT().Platform().Return(&ecs.ContainerPlatform{
OperatingSystem: "LINUX",
Architecture: "X86_64",
}, nil),
m.ecsDescriber.EXPECT().RollbackAlarmNames().Return([]string{alarm2}, nil),
m.cwDescriber.EXPECT().AlarmDescriptions([]string{alarm2}).Return([]*cloudwatch.AlarmDescription{
{
Name: alarm2,
Description: desc2,
},
}, nil),
m.ecsDescriber.EXPECT().EnvVars().Return([]*ecs.ContainerEnvVar{
{
Name: "COPILOT_ENVIRONMENT_NAME",
Container: "container",
Value: mockEnv,
},
}, nil),
m.ecsDescriber.EXPECT().Secrets().Return(
nil, nil),
m.ecsDescriber.EXPECT().StackResources().Return([]*stack.Resource{
{
Type: "AWS::EC2::SecurityGroupIngress",
PhysicalID: "ContainerSecurityGroupIngressFromPublicALB",
},
}, nil),
m.ecsDescriber.EXPECT().StackResources().Return([]*stack.Resource{
{
Type: "AWS::EC2::SecurityGroup",
PhysicalID: "sg-0758ed6b233743530",
},
}, nil),
m.ecsDescriber.EXPECT().StackResources().Return([]*stack.Resource{
{
Type: "AWS::EC2::SecurityGroup",
PhysicalID: "sg-2337435300758ed6b",
},
}, nil),
)
},
wantedBackendSvc: &backendSvcDesc{
ecsSvcDesc: ecsSvcDesc{
Service: testSvc,
Type: "Backend Service",
App: testApp,
Configurations: []*ECSServiceConfig{
{
ServiceConfig: &ServiceConfig{
CPU: "256",
Environment: "test",
Memory: "512",
Platform: "LINUX/X86_64",
Port: "5000",
},
Tasks: "1",
},
{
ServiceConfig: &ServiceConfig{
CPU: "512",
Environment: "prod",
Memory: "1024",
Platform: "LINUX/ARM64",
Port: "5000",
},
Tasks: "2",
},
{
ServiceConfig: &ServiceConfig{
CPU: "512",
Environment: "mockEnv",
Memory: "1024",
Platform: "LINUX/X86_64",
Port: "-",
},
Tasks: "2",
},
},
ServiceDiscovery: serviceDiscoveries{
"jobs.test.phonetool.local:5000": []string{"test"},
"jobs.prod.phonetool.local:5000": []string{"prod"},
},
ServiceConnect: serviceConnects{},
AlarmDescriptions: []*cloudwatch.AlarmDescription{
{
Name: alarm1,
Description: desc1,
Environment: prodEnv,
},
{
Name: alarm2,
Description: desc2,
Environment: mockEnv,
},
},
Variables: []*containerEnvVar{
{
envVar: &envVar{
Environment: "test",
Name: "COPILOT_ENVIRONMENT_NAME",
Value: "test",
},
Container: "container",
},
{
envVar: &envVar{
Environment: "prod",
Name: "COPILOT_ENVIRONMENT_NAME",
Value: "prod",
},
Container: "container",
},
{
envVar: &envVar{
Environment: "mockEnv",
Name: "COPILOT_ENVIRONMENT_NAME",
Value: "mockEnv",
},
Container: "container",
},
},
Secrets: []*secret{
{
Name: "GITHUB_WEBHOOK_SECRET",
Container: "container",
Environment: "test",
ValueFrom: "GH_WEBHOOK_SECRET",
},
{
Name: "SOME_OTHER_SECRET",
Container: "container",
Environment: "prod",
ValueFrom: "SHHHHHHHH",
},
},
Resources: map[string][]*stack.Resource{
"test": {
{
Type: "AWS::EC2::SecurityGroupIngress",
PhysicalID: "ContainerSecurityGroupIngressFromPublicALB",
},
},
"prod": {
{
Type: "AWS::EC2::SecurityGroup",
PhysicalID: "sg-0758ed6b233743530",
},
},
"mockEnv": {
{
Type: "AWS::EC2::SecurityGroup",
PhysicalID: "sg-2337435300758ed6b",
},
},
},
environments: []string{"test", "prod", "mockEnv"},
},
},
},
"internal alb success http": {
shouldOutputResources: true,
setupMocks: func(m backendSvcDescriberMocks) {
params := map[string]string{
cfnstack.WorkloadTargetPortParamKey: "5000",
cfnstack.WorkloadTaskCountParamKey: "1",
cfnstack.WorkloadTaskCPUParamKey: "256",
cfnstack.WorkloadTaskMemoryParamKey: "512",
cfnstack.WorkloadRulePathParamKey: "mySvc",
}
resources := []*describeStack.Resource{
{
Type: "AWS::ElasticLoadBalancingV2::TargetGroup",
LogicalID: svcStackResourceALBTargetGroupLogicalID,
PhysicalID: "targetGroupARN",
},
{
Type: svcStackResourceListenerRuleResourceType,
LogicalID: svcStackResourceHTTPListenerRuleLogicalID,
PhysicalID: "listenerRuleARN",
},
}
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv}, nil),
m.ecsDescriber.EXPECT().StackResources().Return(resources, nil),
m.ecsDescriber.EXPECT().Params().Return(params, nil),
m.ecsDescriber.EXPECT().StackResources().Return(resources, nil),
m.lbDescriber.EXPECT().ListenerRulesHostHeaders([]string{"listenerRuleARN"}).Return([]string{"jobs.test.phonetool.internal"}, nil),
m.ecsDescriber.EXPECT().Params().Return(params, nil),
m.envDescriber.EXPECT().ServiceDiscoveryEndpoint().Return("test.phonetool.local", nil),
m.ecsDescriber.EXPECT().ServiceConnectDNSNames().Return([]string{"jobs"}, nil),
m.ecsDescriber.EXPECT().Platform().Return(&ecs.ContainerPlatform{
OperatingSystem: "LINUX",
Architecture: "X86_64",
}, nil),
m.ecsDescriber.EXPECT().RollbackAlarmNames().Return(nil, nil),
m.ecsDescriber.EXPECT().EnvVars().Return([]*ecs.ContainerEnvVar{
{
Name: "COPILOT_ENVIRONMENT_NAME",
Container: "container",
Value: testEnv,
},
}, nil),
m.ecsDescriber.EXPECT().Secrets().Return([]*ecs.ContainerSecret{
{
Name: "GITHUB_WEBHOOK_SECRET",
Container: "container",
ValueFrom: "GH_WEBHOOK_SECRET",
},
}, nil),
m.ecsDescriber.EXPECT().StackResources().Return(resources, nil),
)
},
wantedBackendSvc: &backendSvcDesc{
ecsSvcDesc: ecsSvcDesc{
Service: testSvc,
Type: "Backend Service",
App: testApp,
Configurations: []*ECSServiceConfig{
{
ServiceConfig: &ServiceConfig{
CPU: "256",
Environment: "test",
Memory: "512",
Platform: "LINUX/X86_64",
Port: "5000",
},
Tasks: "1",
},
},
Routes: []*WebServiceRoute{
{
Environment: "test",
URL: "http://jobs.test.phonetool.internal/mySvc",
},
},
ServiceDiscovery: serviceDiscoveries{
"jobs.test.phonetool.local:5000": []string{"test"},
},
ServiceConnect: serviceConnects{
"jobs": []string{"test"},
},
Variables: []*containerEnvVar{
{
envVar: &envVar{
Environment: "test",
Name: "COPILOT_ENVIRONMENT_NAME",
Value: "test",
},
Container: "container",
},
},
Secrets: []*secret{
{
Name: "GITHUB_WEBHOOK_SECRET",
Container: "container",
Environment: "test",
ValueFrom: "GH_WEBHOOK_SECRET",
},
},
Resources: map[string][]*stack.Resource{
"test": {
{
Type: "AWS::ElasticLoadBalancingV2::TargetGroup",
LogicalID: svcStackResourceALBTargetGroupLogicalID,
PhysicalID: "targetGroupARN",
},
{
Type: svcStackResourceListenerRuleResourceType,
LogicalID: svcStackResourceHTTPListenerRuleLogicalID,
PhysicalID: "listenerRuleARN",
},
},
},
environments: []string{"test"},
},
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mocks := backendSvcDescriberMocks{
storeSvc: mocks.NewMockDeployedEnvServicesLister(ctrl),
ecsDescriber: mocks.NewMockecsDescriber(ctrl),
cwDescriber: mocks.NewMockcwAlarmDescriber(ctrl),
envDescriber: mocks.NewMockenvDescriber(ctrl),
lbDescriber: mocks.NewMocklbDescriber(ctrl),
}
tc.setupMocks(mocks)
d := &BackendServiceDescriber{
app: testApp,
svc: testSvc,
enableResources: tc.shouldOutputResources,
store: mocks.storeSvc,
initECSServiceDescribers: func(s string) (ecsDescriber, error) { return mocks.ecsDescriber, nil },
initCWDescriber: func(s string) (cwAlarmDescriber, error) { return mocks.cwDescriber, nil },
initEnvDescribers: func(s string) (envDescriber, error) { return mocks.envDescriber, nil },
initLBDescriber: func(s string) (lbDescriber, error) { return mocks.lbDescriber, nil },
}
// WHEN
backendsvc, err := d.Describe()
// THEN
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedBackendSvc, backendsvc, "expected output content match")
}
})
}
}
func TestBackendSvcDesc_String(t *testing.T) {
testCases := map[string]struct {
wantedHumanString string
wantedJSONString string
}{
"correct output": {
wantedHumanString: `About
Application my-app
Name my-svc
Type Backend Service
Configurations
Environment Tasks CPU (vCPU) Memory (MiB) Platform Port
----------- ----- ---------- ------------ -------- ----
test 1 0.25 512 LINUX/X86_64 80
prod 3 0.5 1024 LINUX/ARM64 5000
Rollback Alarms
Name Environment Description
---- ----------- -----------
alarmName1 test alarm description 1
alarmName2 prod alarm description 2
Internal Service Endpoint
Endpoint Environment Type
-------- ----------- ----
http://my-svc.prod.my-app.local:5000 prod Service Discovery
http://my-svc.test.my-app.local:5000 test Service Discovery
Variables
Name Container Environment Value
---- --------- ----------- -----
COPILOT_ENVIRONMENT_NAME container prod prod
" " test test
Secrets
Name Container Environment Value From
---- --------- ----------- ----------
GITHUB_WEBHOOK_SECRET container test parameter/GH_WEBHOOK_SECRET
SOME_OTHER_SECRET " prod parameter/SHHHHH
Resources
test
AWS::EC2::SecurityGroup sg-0758ed6b233743530
prod
AWS::EC2::SecurityGroupIngress ContainerSecurityGroupIngressFromPublicALB
`,
wantedJSONString: "{\"service\":\"my-svc\",\"type\":\"Backend Service\",\"application\":\"my-app\",\"configurations\":[{\"environment\":\"test\",\"port\":\"80\",\"cpu\":\"256\",\"memory\":\"512\",\"platform\":\"LINUX/X86_64\",\"tasks\":\"1\"},{\"environment\":\"prod\",\"port\":\"5000\",\"cpu\":\"512\",\"memory\":\"1024\",\"platform\":\"LINUX/ARM64\",\"tasks\":\"3\"}],\"rollbackAlarms\":[{\"name\":\"alarmName1\",\"description\":\"alarm description 1\",\"environment\":\"test\"},{\"name\":\"alarmName2\",\"description\":\"alarm description 2\",\"environment\":\"prod\"}],\"routes\":null,\"serviceDiscovery\":[{\"environment\":[\"prod\"],\"endpoint\":\"http://my-svc.prod.my-app.local:5000\"},{\"environment\":[\"test\"],\"endpoint\":\"http://my-svc.test.my-app.local:5000\"}],\"variables\":[{\"environment\":\"prod\",\"name\":\"COPILOT_ENVIRONMENT_NAME\",\"value\":\"prod\",\"container\":\"container\"},{\"environment\":\"test\",\"name\":\"COPILOT_ENVIRONMENT_NAME\",\"value\":\"test\",\"container\":\"container\"}],\"secrets\":[{\"name\":\"GITHUB_WEBHOOK_SECRET\",\"container\":\"container\",\"environment\":\"test\",\"valueFrom\":\"GH_WEBHOOK_SECRET\"},{\"name\":\"SOME_OTHER_SECRET\",\"container\":\"container\",\"environment\":\"prod\",\"valueFrom\":\"SHHHHH\"}],\"resources\":{\"prod\":[{\"type\":\"AWS::EC2::SecurityGroupIngress\",\"physicalID\":\"ContainerSecurityGroupIngressFromPublicALB\"}],\"test\":[{\"type\":\"AWS::EC2::SecurityGroup\",\"physicalID\":\"sg-0758ed6b233743530\"}]}}\n",
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
config := []*ECSServiceConfig{
{
ServiceConfig: &ServiceConfig{
CPU: "256",
Environment: "test",
Memory: "512",
Platform: "LINUX/X86_64",
Port: "80",
},
Tasks: "1",
},
{
ServiceConfig: &ServiceConfig{
CPU: "512",
Environment: "prod",
Memory: "1024",
Platform: "LINUX/ARM64",
Port: "5000",
},
Tasks: "3",
},
}
alarmDescs := []*cloudwatch.AlarmDescription{
{
Name: "alarmName1",
Description: "alarm description 1",
Environment: "test",
},
{
Name: "alarmName2",
Description: "alarm description 2",
Environment: "prod",
},
}
envVars := []*containerEnvVar{
{
envVar: &envVar{
Environment: "prod",
Name: "COPILOT_ENVIRONMENT_NAME",
Value: "prod",
},
Container: "container",
},
{
envVar: &envVar{
Environment: "test",
Name: "COPILOT_ENVIRONMENT_NAME",
Value: "test",
},
Container: "container",
},
}
secrets := []*secret{
{
Name: "GITHUB_WEBHOOK_SECRET",
Container: "container",
Environment: "test",
ValueFrom: "GH_WEBHOOK_SECRET",
},
{
Name: "SOME_OTHER_SECRET",
Container: "container",
Environment: "prod",
ValueFrom: "SHHHHH",
},
}
sds := serviceDiscoveries{
"http://my-svc.test.my-app.local:5000": []string{"test"},
"http://my-svc.prod.my-app.local:5000": []string{"prod"},
}
resources := map[string][]*stack.Resource{
"test": {
{
PhysicalID: "sg-0758ed6b233743530",
Type: "AWS::EC2::SecurityGroup",
},
},
"prod": {
{
Type: "AWS::EC2::SecurityGroupIngress",
PhysicalID: "ContainerSecurityGroupIngressFromPublicALB",
},
},
}
backendSvc := &backendSvcDesc{
ecsSvcDesc: ecsSvcDesc{
Service: "my-svc",
Type: "Backend Service",
Configurations: config,
App: "my-app",
AlarmDescriptions: alarmDescs,
Variables: envVars,
Secrets: secrets,
ServiceDiscovery: sds,
Resources: resources,
environments: []string{"test", "prod"},
},
}
human := backendSvc.HumanString()
json, _ := backendSvc.JSONString()
require.Equal(t, tc.wantedHumanString, human)
require.Equal(t, tc.wantedJSONString, json)
})
}
}
| 863 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package describe
import (
"fmt"
"io"
"strings"
"github.com/aws/copilot-cli/internal/pkg/aws/ecs"
"github.com/aws/copilot-cli/internal/pkg/describe/stack"
"github.com/dustin/go-humanize"
)
const (
// Display settings.
minCellWidth = 10 // minimum number of characters in a table's cell.
tabWidth = 4 // number of characters in between columns.
cellPaddingWidth = 2 // number of padding characters added by default to a cell.
paddingChar = ' ' // character in between columns.
dittoSymbol = ` "` // Symbol used while displaying values in human format.
noAdditionalFormatting = 0
statusMinCellWidth = 12 // minimum number of characters in a table's cell.
statusCellPaddingWidth = 2
)
// humanizeTime is overridden in tests so that its output is constant as time passes.
var humanizeTime = humanize.Time
// HumanJSONStringer contains methods that stringify app info for output.
type HumanJSONStringer interface {
HumanString() string
JSONString() (string, error)
}
type stackDescriber interface {
Describe() (stack.StackDescription, error)
Resources() ([]*stack.Resource, error)
StackMetadata() (string, error)
StackSetMetadata() (string, error)
}
type deployedSvcResources map[string][]*stack.Resource
func (c deployedSvcResources) humanStringByEnv(w io.Writer, envs []string) {
for _, env := range envs {
resources := c[env]
fmt.Fprintf(w, "\n %s\n", env)
for _, resource := range resources {
fmt.Fprintf(w, " %s\t%s\n", resource.Type, resource.PhysicalID)
}
}
}
func flattenContainerEnvVars(envName string, envVars []*ecs.ContainerEnvVar) []*containerEnvVar {
var out []*containerEnvVar
for _, v := range envVars {
out = append(out, &containerEnvVar{
envVar: &envVar{
Name: v.Name,
Environment: envName,
Value: v.Value,
},
Container: v.Container,
})
}
return out
}
func flattenSecrets(envName string, secrets []*ecs.ContainerSecret) []*secret {
var out []*secret
for _, s := range secrets {
out = append(out, &secret{
Name: s.Name,
Container: s.Container,
Environment: envName,
ValueFrom: s.ValueFrom,
})
}
return out
}
func printTable(w io.Writer, headers []string, rows [][]string) {
fmt.Fprintf(w, " %s\n", strings.Join(headers, "\t"))
fmt.Fprintf(w, " %s\n", strings.Join(underline(headers), "\t"))
if len(rows) > 0 {
fmt.Fprintf(w, " %s\n", strings.Join(rows[0], "\t"))
}
for prev, cur := 0, 1; cur < len(rows); prev, cur = prev+1, cur+1 {
cells := make([]string, len(rows[cur]))
copy(cells, rows[cur])
for i, v := range cells {
if v == rows[prev][i] {
cells[i] = dittoSymbol
}
}
fmt.Fprintf(w, " %s\n", strings.Join(cells, "\t"))
}
}
| 103 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package describe provides functionality to retrieve information about deployed applications, environments and workloads.
package describe
| 6 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package describe
import (
"bytes"
"encoding/json"
"fmt"
"sort"
"strings"
"text/tabwriter"
"github.com/aws/copilot-cli/internal/pkg/template"
"github.com/aws/copilot-cli/internal/pkg/version"
"gopkg.in/yaml.v3"
"github.com/aws/copilot-cli/internal/pkg/aws/ec2"
"github.com/aws/copilot-cli/internal/pkg/aws/sessions"
"github.com/aws/copilot-cli/internal/pkg/config"
cfnstack "github.com/aws/copilot-cli/internal/pkg/deploy/cloudformation/stack"
"github.com/aws/copilot-cli/internal/pkg/describe/stack"
"github.com/aws/copilot-cli/internal/pkg/manifest"
"github.com/aws/copilot-cli/internal/pkg/term/color"
)
var (
fmtLegacySvcDiscoveryEndpoint = "%s.local"
)
type vpcSubnetLister interface {
ListVPCSubnets(vpcID string) (*ec2.VPCSubnets, error)
}
// EnvDescription contains the information about an environment.
type EnvDescription struct {
Environment *config.Environment `json:"environment"`
Services []*config.Workload `json:"services"`
Jobs []*config.Workload `json:"jobs"`
Tags map[string]string `json:"tags,omitempty"`
Resources []*stack.Resource `json:"resources,omitempty"`
EnvironmentVPC EnvironmentVPC `json:"environmentVPC"`
}
// EnvironmentVPC holds the ID of the environment's VPC configuration.
type EnvironmentVPC struct {
ID string `json:"id"`
PublicSubnetIDs []string `json:"publicSubnetIDs"`
PrivateSubnetIDs []string `json:"privateSubnetIDs"`
}
// EnvDescriber retrieves information about an environment.
type EnvDescriber struct {
app string
env *config.Environment
enableResources bool
configStore ConfigStoreSvc
deployStore DeployedEnvServicesLister
cfn stackDescriber
subnetLister vpcSubnetLister
// Cached values for reuse.
description *EnvDescription
}
// NewEnvDescriberConfig contains fields that initiates EnvDescriber struct.
type NewEnvDescriberConfig struct {
App string
Env string
EnableResources bool
ConfigStore ConfigStoreSvc
DeployStore DeployedEnvServicesLister
}
// NewEnvDescriber instantiates an environment describer.
func NewEnvDescriber(opt NewEnvDescriberConfig) (*EnvDescriber, error) {
env, err := opt.ConfigStore.GetEnvironment(opt.App, opt.Env)
if err != nil {
return nil, fmt.Errorf("get environment: %w", err)
}
sess, err := sessions.ImmutableProvider().FromRole(env.ManagerRoleARN, env.Region)
if err != nil {
return nil, fmt.Errorf("assume role for environment %s: %w", env.ManagerRoleARN, err)
}
return &EnvDescriber{
app: opt.App,
env: env,
enableResources: opt.EnableResources,
configStore: opt.ConfigStore,
deployStore: opt.DeployStore,
cfn: stack.NewStackDescriber(cfnstack.NameForEnv(opt.App, opt.Env), sess),
subnetLister: ec2.New(sess),
}, nil
}
// Describe returns info about an application's environment.
func (d *EnvDescriber) Describe() (*EnvDescription, error) {
if d.description != nil {
return d.description, nil
}
svcs, err := d.filterDeployedSvcs()
if err != nil {
return nil, err
}
jobs, err := d.filterDeployedJobs()
if err != nil {
return nil, err
}
tags, environmentVPC, err := d.loadStackInfo()
if err != nil {
return nil, err
}
var stackResources []*stack.Resource
if d.enableResources {
stackResources, err = d.cfn.Resources()
if err != nil {
return nil, fmt.Errorf("retrieve environment resources: %w", err)
}
}
d.description = &EnvDescription{
Environment: d.env,
Services: svcs,
Jobs: jobs,
Tags: tags,
Resources: stackResources,
EnvironmentVPC: environmentVPC,
}
return d.description, nil
}
// Manifest returns the contents of the manifest used to deploy an environment stack.
func (d *EnvDescriber) Manifest() ([]byte, error) {
tpl, err := d.cfn.StackMetadata()
if err != nil {
return nil, err
}
metadata := struct {
Manifest string `yaml:"Manifest"`
}{}
if err := yaml.Unmarshal([]byte(tpl), &metadata); err != nil {
return nil, fmt.Errorf("unmarshal Metadata.Manifest in environment stack: %v", err)
}
if metadata.Manifest != "" {
return []byte(strings.TrimSpace(metadata.Manifest)), nil
}
// Otherwise, the Manifest wasn't written into the CloudFormation template, we'll convert the config in SSM.
mft := manifest.FromEnvConfig(d.env, template.New())
out, err := yaml.Marshal(mft)
if err != nil {
return nil, fmt.Errorf("marshal manifest generated from SSM: %v", err)
}
return []byte(strings.TrimSpace(string(out))), nil
}
// Params returns the parameters of the environment stack.
func (d *EnvDescriber) Params() (map[string]string, error) {
descr, err := d.cfn.Describe()
if err != nil {
return nil, err
}
return descr.Parameters, nil
}
// Outputs returns the outputs of the environment stack.
func (d *EnvDescriber) Outputs() (map[string]string, error) {
descr, err := d.cfn.Describe()
if err != nil {
return nil, err
}
return descr.Outputs, nil
}
// AvailableFeatures returns the available features of the environment stack.
func (d *EnvDescriber) AvailableFeatures() ([]string, error) {
params, err := d.Params()
if err != nil {
return nil, err
}
var availableFeatures []string
for _, f := range template.AvailableEnvFeatures() {
if _, ok := params[f]; ok {
availableFeatures = append(availableFeatures, f)
}
}
return availableFeatures, nil
}
// Version returns the CloudFormation template version associated with
// the environment by reading the Metadata.Version field from the template.
//
// If the Version field does not exist, then it's a legacy template and it returns an version.LegacyEnvTemplate and nil error.
func (d *EnvDescriber) Version() (string, error) {
raw, err := d.cfn.StackMetadata()
if err != nil {
return "", err
}
metadata := struct {
Version string `yaml:"Version"`
}{}
if err := yaml.Unmarshal([]byte(raw), &metadata); err != nil {
return "", fmt.Errorf("unmarshal Metadata property to read Version: %w", err)
}
if metadata.Version == "" {
return version.LegacyEnvTemplate, nil
}
return metadata.Version, nil
}
// ServiceDiscoveryEndpoint returns the endpoint the environment was initialized with, if any. Otherwise,
// it returns the legacy app.local endpoint.
func (d *EnvDescriber) ServiceDiscoveryEndpoint() (string, error) {
p, err := d.Params()
if err != nil {
return "", fmt.Errorf("get params of environment %s in app %s: %w", d.env.Name, d.env.App, err)
}
for k, v := range p {
// Ignore non-svc discovery params
if k != cfnstack.EnvParamServiceDiscoveryEndpoint {
continue
}
// Stacks upgraded from legacy environments will have `app.local` as the parameter value.
// Stacks created after 1.5.0 will use `env.app.local`.
if v != "" {
return v, nil
}
}
// If the param does not exist, the environment is legacy, has not been upgraded, and uses `app.local`.
return fmt.Sprintf(fmtLegacySvcDiscoveryEndpoint, d.app), nil
}
// PublicCIDRBlocks returns the public CIDR blocks of the public subnets in the environment VPC.
func (d *EnvDescriber) PublicCIDRBlocks() ([]string, error) {
_, envVPC, err := d.loadStackInfo()
if err != nil {
return nil, err
}
vpcID := envVPC.ID
subnets, err := d.subnetLister.ListVPCSubnets(vpcID)
if err != nil {
return nil, fmt.Errorf("list subnets of vpc %s in environment %s: %w", vpcID, d.env.Name, err)
}
var cidrBlocks []string
for _, subnet := range subnets.Public {
cidrBlocks = append(cidrBlocks, subnet.CIDRBlock)
}
return cidrBlocks, nil
}
func (d *EnvDescriber) loadStackInfo() (map[string]string, EnvironmentVPC, error) {
var environmentVPC EnvironmentVPC
envStack, err := d.cfn.Describe()
if err != nil {
return nil, environmentVPC, fmt.Errorf("retrieve environment stack: %w", err)
}
for k, v := range envStack.Outputs {
switch k {
case cfnstack.EnvOutputVPCID:
environmentVPC.ID = v
case cfnstack.EnvOutputPublicSubnets:
environmentVPC.PublicSubnetIDs = strings.Split(v, ",")
case cfnstack.EnvOutputPrivateSubnets:
environmentVPC.PrivateSubnetIDs = strings.Split(v, ",")
}
}
return envStack.Tags, environmentVPC, nil
}
func (d *EnvDescriber) filterDeployedSvcs() ([]*config.Workload, error) {
allSvcs, err := d.configStore.ListServices(d.app)
if err != nil {
return nil, fmt.Errorf("list services for app %s: %w", d.app, err)
}
svcs := make(map[string]*config.Workload)
for _, svc := range allSvcs {
svcs[svc.Name] = svc
}
deployedSvcNames, err := d.deployStore.ListDeployedServices(d.app, d.env.Name)
if err != nil {
return nil, fmt.Errorf("list deployed services in env %s: %w", d.env.Name, err)
}
var deployedSvcs []*config.Workload
for _, deployedSvcName := range deployedSvcNames {
deployedSvcs = append(deployedSvcs, svcs[deployedSvcName])
}
return deployedSvcs, nil
}
// filterDeployedJobs lists the jobs that are deployed on the given app and environment
func (d *EnvDescriber) filterDeployedJobs() ([]*config.Workload, error) {
allJobs, err := d.configStore.ListJobs(d.app)
if err != nil {
return nil, fmt.Errorf("list jobs for app %s: %w", d.app, err)
}
jobs := make(map[string]*config.Workload)
for _, job := range allJobs {
jobs[job.Name] = job
}
deployedJobNames, err := d.deployStore.ListDeployedJobs(d.app, d.env.Name)
if err != nil {
return nil, fmt.Errorf("list deployed jobs in env %s: %w", d.env.Name, err)
}
var deployedJobs []*config.Workload
for _, deployedJobName := range deployedJobNames {
deployedJobs = append(deployedJobs, jobs[deployedJobName])
}
return deployedJobs, nil
}
// ValidateCFServiceDomainAliases returns error if an environment using cdn is deployed without specifying http.alias for all load-balanced web services
func (d *EnvDescriber) ValidateCFServiceDomainAliases() error {
stackDescr, err := d.cfn.Describe()
if err != nil {
return fmt.Errorf("describe stack: %w", err)
}
servicesString, ok := stackDescr.Parameters[cfnstack.EnvParamALBWorkloadsKey]
if !ok || servicesString == "" {
return nil
}
services := strings.Split(servicesString, ",")
jsonOutput, ok := stackDescr.Parameters[cfnstack.EnvParamAliasesKey]
if !ok {
return fmt.Errorf("cannot find %s in env stack parameter set", cfnstack.EnvParamAliasesKey)
}
var aliases map[string][]string
if jsonOutput != "" {
err = json.Unmarshal([]byte(jsonOutput), &aliases)
if err != nil {
return fmt.Errorf("unmarshal %q: %w", jsonOutput, err)
}
}
var lbSvcsWithoutAlias []string
for _, service := range services {
if _, ok := aliases[service]; !ok {
lbSvcsWithoutAlias = append(lbSvcsWithoutAlias, service)
}
}
if len(lbSvcsWithoutAlias) != 0 {
return &errLBWebSvcsOnCFWithoutAlias{
services: lbSvcsWithoutAlias,
aliasField: "http.alias",
}
}
return nil
}
// JSONString returns the stringified EnvDescription struct with json format.
func (e *EnvDescription) JSONString() (string, error) {
b, err := json.Marshal(e)
if err != nil {
return "", fmt.Errorf("marshal environment description: %w", err)
}
return fmt.Sprintf("%s\n", b), nil
}
// HumanString returns the stringified EnvDescription struct with human readable format.
func (e *EnvDescription) HumanString() string {
var b bytes.Buffer
writer := tabwriter.NewWriter(&b, minCellWidth, tabWidth, cellPaddingWidth, paddingChar, noAdditionalFormatting)
fmt.Fprint(writer, color.Bold.Sprint("About\n\n"))
writer.Flush()
fmt.Fprintf(writer, " %s\t%s\n", "Name", e.Environment.Name)
fmt.Fprintf(writer, " %s\t%s\n", "Region", e.Environment.Region)
fmt.Fprintf(writer, " %s\t%s\n", "Account ID", e.Environment.AccountID)
fmt.Fprint(writer, color.Bold.Sprint("\nWorkloads\n\n"))
writer.Flush()
headers := []string{"Name", "Type"}
fmt.Fprintf(writer, " %s\n", strings.Join(headers, "\t"))
fmt.Fprintf(writer, " %s\n", strings.Join(underline(headers), "\t"))
for _, svc := range e.Services {
fmt.Fprintf(writer, " %s\t%s\n", svc.Name, svc.Type)
}
for _, job := range e.Jobs {
fmt.Fprintf(writer, " %s\t%s\n", job.Name, job.Type)
}
writer.Flush()
if len(e.Tags) != 0 {
fmt.Fprint(writer, color.Bold.Sprint("\nTags\n\n"))
writer.Flush()
headers := []string{"Key", "Value"}
fmt.Fprintf(writer, " %s\n", strings.Join(headers, "\t"))
fmt.Fprintf(writer, " %s\n", strings.Join(underline(headers), "\t"))
// sort Tags in alpha order by keys
keys := make([]string, 0, len(e.Tags))
for k := range e.Tags {
keys = append(keys, k)
}
sort.Strings(keys)
for _, key := range keys {
fmt.Fprintf(writer, " %s\t%s\n", key, e.Tags[key])
}
}
writer.Flush()
if len(e.Resources) != 0 {
fmt.Fprint(writer, color.Bold.Sprint("\nResources\n\n"))
writer.Flush()
for _, resource := range e.Resources {
fmt.Fprintf(writer, " %s\t%s\n", resource.Type, resource.PhysicalID)
}
}
writer.Flush()
return b.String()
}
| 419 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package describe
import (
"errors"
"fmt"
"testing"
"github.com/aws/copilot-cli/internal/pkg/aws/ec2"
"github.com/aws/copilot-cli/internal/pkg/config"
cfnstack "github.com/aws/copilot-cli/internal/pkg/deploy/cloudformation/stack"
"github.com/aws/copilot-cli/internal/pkg/describe/mocks"
"github.com/aws/copilot-cli/internal/pkg/describe/stack"
"github.com/aws/copilot-cli/internal/pkg/template"
"github.com/aws/copilot-cli/internal/pkg/version"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
type envDescriberMocks struct {
configStoreSvc *mocks.MockConfigStoreSvc
deployStoreSvc *mocks.MockDeployedEnvServicesLister
stackDescriber *mocks.MockstackDescriber
subnetLister *mocks.MockvpcSubnetLister
}
var wantedResources = []*stack.Resource{
{
Type: "AWS::IAM::Role",
PhysicalID: "testApp-testEnv-CFNExecutionRole",
},
{
Type: "testApp-testEnv-Cluster",
PhysicalID: "AWS::ECS::Cluster-jI63pYBWU6BZ",
},
}
func TestEnvDescriber_Describe(t *testing.T) {
testApp := "testApp"
testEnv := &config.Environment{
App: "testApp",
Name: "testEnv",
Region: "us-west-2",
AccountID: "123456789012",
RegistryURL: "",
ExecutionRoleARN: "",
ManagerRoleARN: "",
}
testSvc1 := &config.Workload{
App: "testApp",
Name: "testSvc1",
Type: "load-balanced",
}
testSvc2 := &config.Workload{
App: "testApp",
Name: "testSvc2",
Type: "load-balanced",
}
testSvc3 := &config.Workload{
App: "testApp",
Name: "testSvc3",
Type: "load-balanced",
}
testJob1 := &config.Workload{
App: "testApp",
Name: "testJob1",
Type: "Scheduled Job",
}
testJob2 := &config.Workload{
App: "testApp",
Name: "testJob2",
Type: "Scheduled Job",
}
stackTags := map[string]string{
"copilot-application": "testApp",
"copilot-environment": "testEnv",
}
stackOutputs := map[string]string{
"VpcId": "vpc-012abcd345",
"PublicSubnets": "subnet-0789ab,subnet-0123cd",
"PrivateSubnets": "subnet-023ff,subnet-04af",
}
mockResource1 := &stack.Resource{
PhysicalID: "testApp-testEnv-CFNExecutionRole",
Type: "AWS::IAM::Role",
}
mockResource2 := &stack.Resource{
PhysicalID: "AWS::ECS::Cluster-jI63pYBWU6BZ",
Type: "testApp-testEnv-Cluster",
}
envSvcs := []*config.Workload{testSvc1, testSvc2}
envJobs := []*config.Workload{testJob1, testJob2}
mockError := errors.New("some error")
testCases := map[string]struct {
shouldOutputResources bool
setupMocks func(mocks envDescriberMocks)
wantedEnv *EnvDescription
wantedSvcs []*config.Workload
wantedError error
}{
"error if fail to list all services": {
setupMocks: func(m envDescriberMocks) {
gomock.InOrder(
m.configStoreSvc.EXPECT().ListServices(testApp).Return(nil, mockError),
)
},
wantedError: fmt.Errorf("list services for app testApp: some error"),
},
"error if fail to list deployed services": {
setupMocks: func(m envDescriberMocks) {
gomock.InOrder(
m.configStoreSvc.EXPECT().ListServices(testApp).Return([]*config.Workload{
testSvc1, testSvc2, testSvc3,
}, nil),
m.deployStoreSvc.EXPECT().ListDeployedServices(testApp, testEnv.Name).
Return(nil, mockError),
)
},
wantedError: fmt.Errorf("list deployed services in env testEnv: some error"),
},
"error if fail to get env tags": {
setupMocks: func(m envDescriberMocks) {
gomock.InOrder(
m.configStoreSvc.EXPECT().ListServices(testApp).Return([]*config.Workload{
testSvc1, testSvc2, testSvc3,
}, nil),
m.deployStoreSvc.EXPECT().ListDeployedServices(testApp, testEnv.Name).
Return([]string{"testSvc1", "testSvc2"}, nil),
m.configStoreSvc.EXPECT().ListJobs(testApp).Return([]*config.Workload{
testJob1, testJob2,
}, nil),
m.deployStoreSvc.EXPECT().ListDeployedJobs(testApp, testEnv.Name).
Return([]string{"testJob1", "testJob2"}, nil),
m.stackDescriber.EXPECT().Describe().Return(stack.StackDescription{}, mockError),
)
},
wantedError: fmt.Errorf("retrieve environment stack: some error"),
},
"error if fail to get env resources": {
shouldOutputResources: true,
setupMocks: func(m envDescriberMocks) {
gomock.InOrder(
m.configStoreSvc.EXPECT().ListServices(testApp).Return([]*config.Workload{
testSvc1, testSvc2, testSvc3,
}, nil),
m.deployStoreSvc.EXPECT().ListDeployedServices(testApp, testEnv.Name).
Return([]string{"testSvc1", "testSvc2"}, nil),
m.configStoreSvc.EXPECT().ListJobs(testApp).Return([]*config.Workload{
testJob1, testJob2,
}, nil),
m.deployStoreSvc.EXPECT().ListDeployedJobs(testApp, testEnv.Name).
Return([]string{"testJob1", "testJob2"}, nil),
m.stackDescriber.EXPECT().Describe().Return(stack.StackDescription{
Tags: stackTags,
Outputs: stackOutputs,
}, nil),
m.stackDescriber.EXPECT().Resources().Return(nil, mockError),
)
},
wantedError: fmt.Errorf("retrieve environment resources: some error"),
},
"success without resources": {
shouldOutputResources: false,
setupMocks: func(m envDescriberMocks) {
gomock.InOrder(
m.configStoreSvc.EXPECT().ListServices(testApp).Return([]*config.Workload{
testSvc1, testSvc2, testSvc3,
}, nil),
m.deployStoreSvc.EXPECT().ListDeployedServices(testApp, testEnv.Name).
Return([]string{"testSvc1", "testSvc2"}, nil),
m.configStoreSvc.EXPECT().ListJobs(testApp).Return([]*config.Workload{
testJob1, testJob2,
}, nil),
m.deployStoreSvc.EXPECT().ListDeployedJobs(testApp, testEnv.Name).
Return([]string{"testJob1", "testJob2"}, nil),
m.stackDescriber.EXPECT().Describe().Return(stack.StackDescription{
Tags: stackTags,
Outputs: stackOutputs,
}, nil),
)
},
wantedEnv: &EnvDescription{
Environment: testEnv,
Services: envSvcs,
Jobs: envJobs,
Tags: map[string]string{"copilot-application": "testApp", "copilot-environment": "testEnv"},
EnvironmentVPC: EnvironmentVPC{
ID: "vpc-012abcd345",
PublicSubnetIDs: []string{"subnet-0789ab", "subnet-0123cd"},
PrivateSubnetIDs: []string{"subnet-023ff", "subnet-04af"},
},
},
},
"success with resources": {
shouldOutputResources: true,
setupMocks: func(m envDescriberMocks) {
gomock.InOrder(
m.configStoreSvc.EXPECT().ListServices(testApp).Return([]*config.Workload{
testSvc1, testSvc2, testSvc3,
}, nil),
m.deployStoreSvc.EXPECT().ListDeployedServices(testApp, testEnv.Name).
Return([]string{"testSvc1", "testSvc2"}, nil),
m.configStoreSvc.EXPECT().ListJobs(testApp).Return([]*config.Workload{
testJob1, testJob2,
}, nil),
m.deployStoreSvc.EXPECT().ListDeployedJobs(testApp, testEnv.Name).
Return([]string{"testJob1", "testJob2"}, nil),
m.stackDescriber.EXPECT().Describe().Return(stack.StackDescription{
Tags: stackTags,
Outputs: stackOutputs,
}, nil),
m.stackDescriber.EXPECT().Resources().Return([]*stack.Resource{
mockResource1,
mockResource2,
}, nil),
)
},
wantedEnv: &EnvDescription{
Environment: testEnv,
Services: envSvcs,
Jobs: envJobs,
Tags: map[string]string{"copilot-application": "testApp", "copilot-environment": "testEnv"},
Resources: wantedResources,
EnvironmentVPC: EnvironmentVPC{
ID: "vpc-012abcd345",
PublicSubnetIDs: []string{"subnet-0789ab", "subnet-0123cd"},
PrivateSubnetIDs: []string{"subnet-023ff", "subnet-04af"},
},
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockConfigStoreSvc := mocks.NewMockConfigStoreSvc(ctrl)
mockDeployedEnvServicesLister := mocks.NewMockDeployedEnvServicesLister(ctrl)
mockCFN := mocks.NewMockstackDescriber(ctrl)
mocks := envDescriberMocks{
configStoreSvc: mockConfigStoreSvc,
deployStoreSvc: mockDeployedEnvServicesLister,
stackDescriber: mockCFN,
}
tc.setupMocks(mocks)
d := &EnvDescriber{
env: testEnv,
app: testApp,
enableResources: tc.shouldOutputResources,
configStore: mockConfigStoreSvc,
deployStore: mockDeployedEnvServicesLister,
cfn: mockCFN,
}
// WHEN
actual, err := d.Describe()
// THEN
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedEnv, actual)
}
})
}
}
func TestEnvDescriber_Manifest(t *testing.T) {
testCases := map[string]struct {
given func(ctrl *gomock.Controller) *EnvDescriber
wantedManifest []byte
wantedErr error
}{
"should return an error when the template Metadata cannot be retrieved": {
given: func(ctrl *gomock.Controller) *EnvDescriber {
m := mocks.NewMockstackDescriber(ctrl)
m.EXPECT().StackMetadata().Return("", errors.New("some error"))
return &EnvDescriber{
cfn: m,
}
},
wantedErr: errors.New("some error"),
},
"should unmarshal from SSM when the stack template does not have any Metadata.Manifest": {
given: func(ctrl *gomock.Controller) *EnvDescriber {
m := mocks.NewMockstackDescriber(ctrl)
m.EXPECT().StackMetadata().Return(`
Metadata:
Version: 1.9.0
`, nil)
return &EnvDescriber{
env: &config.Environment{
Name: "test",
},
cfn: m,
}
},
wantedManifest: []byte(`name: test
type: Environment`),
},
"should prioritize stack template's Metadata over SSM": {
given: func(ctrl *gomock.Controller) *EnvDescriber {
m := mocks.NewMockstackDescriber(ctrl)
m.EXPECT().StackMetadata().Return(`{"Version":"1.9.0","Manifest":"\nname: prod\ntype: Environment"}`, nil)
return &EnvDescriber{
env: &config.Environment{
Name: "test",
},
cfn: m,
}
},
wantedManifest: []byte(`name: prod
type: Environment`),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
describer := tc.given(ctrl)
// WHEN
mft, err := describer.Manifest()
// THEN
if tc.wantedErr != nil {
require.EqualError(t, err, tc.wantedErr.Error())
} else {
require.NoError(t, err)
require.Equal(t, string(tc.wantedManifest), string(mft), "expected manifests to match")
}
})
}
}
func TestEnvDescriber_Version(t *testing.T) {
testCases := map[string]struct {
given func(ctrl *gomock.Controller) *EnvDescriber
wantedVersion string
wantedErr error
}{
"should return version.LegacyEnvTemplate version if legacy template": {
given: func(ctrl *gomock.Controller) *EnvDescriber {
m := mocks.NewMockstackDescriber(ctrl)
m.EXPECT().StackMetadata().Return("", nil)
return &EnvDescriber{
app: "phonetool",
env: &config.Environment{Name: "test"},
cfn: m,
}
},
wantedVersion: version.LegacyEnvTemplate,
},
"should read the version from the Metadata field": {
given: func(ctrl *gomock.Controller) *EnvDescriber {
m := mocks.NewMockstackDescriber(ctrl)
m.EXPECT().StackMetadata().Return(`{"Version":"1.0.0"}`, nil)
return &EnvDescriber{
app: "phonetool",
env: &config.Environment{Name: "test"},
cfn: m,
}
},
wantedVersion: "1.0.0",
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
d := tc.given(ctrl)
// WHEN
actual, err := d.Version()
// THEN
if tc.wantedErr != nil {
require.EqualError(t, err, tc.wantedErr.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedVersion, actual)
}
})
}
}
func TestEnvDescriber_ServiceDiscoveryEndpoint(t *testing.T) {
testCases := map[string]struct {
given func(ctrl *gomock.Controller) *EnvDescriber
wantedEndpoint string
wantedErr error
}{
"should return app.local if legacy, unupgraded environment": {
given: func(ctrl *gomock.Controller) *EnvDescriber {
m := mocks.NewMockstackDescriber(ctrl)
m.EXPECT().Describe().Return(stack.StackDescription{Parameters: map[string]string{}}, nil)
return &EnvDescriber{
app: "phonetool",
env: &config.Environment{Name: "test"},
cfn: m,
}
},
wantedEndpoint: "phonetool.local",
},
"should return the new env template if the parameter is set": {
given: func(ctrl *gomock.Controller) *EnvDescriber {
m := mocks.NewMockstackDescriber(ctrl)
m.EXPECT().Describe().Return(stack.StackDescription{
Parameters: map[string]string{
cfnstack.EnvParamServiceDiscoveryEndpoint: "test.phonetool.local",
}}, nil)
return &EnvDescriber{
app: "phonetool",
env: &config.Environment{Name: "test"},
cfn: m,
}
},
wantedEndpoint: "test.phonetool.local",
},
"should return the old env template if the parameter is empty": {
given: func(ctrl *gomock.Controller) *EnvDescriber {
m := mocks.NewMockstackDescriber(ctrl)
m.EXPECT().Describe().Return(stack.StackDescription{
Parameters: map[string]string{
cfnstack.EnvParamServiceDiscoveryEndpoint: "",
}}, nil)
return &EnvDescriber{
app: "phonetool",
env: &config.Environment{Name: "test"},
cfn: m,
}
},
wantedEndpoint: "phonetool.local",
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
d := tc.given(ctrl)
// WHEN
actual, err := d.ServiceDiscoveryEndpoint()
// THEN
if tc.wantedErr != nil {
require.EqualError(t, err, tc.wantedErr.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedEndpoint, actual)
}
})
}
}
func TestEnvDescriber_PublicCIDRBlocks(t *testing.T) {
testCases := map[string]struct {
setupMocks func(mocks envDescriberMocks)
wantedCIDRBlocks []string
wantedErr error
}{
"fail to describe the environment to get the VPC ID": {
setupMocks: func(m envDescriberMocks) {
gomock.InOrder(
m.stackDescriber.EXPECT().Describe().Return(stack.StackDescription{}, errors.New("some error")),
)
},
wantedErr: errors.New("retrieve environment stack: some error"),
},
"fail to get the subnets of the environment VPC": {
setupMocks: func(m envDescriberMocks) {
gomock.InOrder(
m.stackDescriber.EXPECT().Describe().Return(stack.StackDescription{
Outputs: map[string]string{
"VpcId": "mockVPCID",
},
}, nil),
m.subnetLister.EXPECT().ListVPCSubnets("mockVPCID").Return(nil, errors.New("some error")),
)
},
wantedErr: errors.New("list subnets of vpc mockVPCID in environment mockEnv: some error"),
},
"return the correct CIDR blocks": {
setupMocks: func(m envDescriberMocks) {
gomock.InOrder(
m.stackDescriber.EXPECT().Describe().Return(stack.StackDescription{
Outputs: map[string]string{
"VpcId": "mockVPCID",
},
}, nil),
m.subnetLister.EXPECT().ListVPCSubnets("mockVPCID").Return(&ec2.VPCSubnets{
Public: []ec2.Subnet{
{
CIDRBlock: "mockCIDRBlock1",
},
{
CIDRBlock: "mockCIDRBlock2",
},
},
}, nil),
)
},
wantedCIDRBlocks: []string{"mockCIDRBlock1", "mockCIDRBlock2"},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := envDescriberMocks{
configStoreSvc: mocks.NewMockConfigStoreSvc(ctrl),
deployStoreSvc: mocks.NewMockDeployedEnvServicesLister(ctrl),
stackDescriber: mocks.NewMockstackDescriber(ctrl),
subnetLister: mocks.NewMockvpcSubnetLister(ctrl),
}
tc.setupMocks(m)
d := &EnvDescriber{
env: &config.Environment{
Name: "mockEnv",
},
configStore: m.configStoreSvc,
deployStore: m.deployStoreSvc,
cfn: m.stackDescriber,
subnetLister: m.subnetLister,
}
// WHEN
actual, err := d.PublicCIDRBlocks()
// THEN
if tc.wantedErr != nil {
require.EqualError(t, err, tc.wantedErr.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedCIDRBlocks, actual)
}
})
}
}
func TestEnvDescriber_Features(t *testing.T) {
testCases := map[string]struct {
setupMock func(m *envDescriberMocks)
wanted []string
wantedErr error
}{
"error describing stack": {
setupMock: func(m *envDescriberMocks) {
m.stackDescriber.EXPECT().Describe().Return(stack.StackDescription{}, errors.New("some error"))
},
wantedErr: errors.New("some error"),
},
"return outdated features": {
setupMock: func(m *envDescriberMocks) {
m.stackDescriber.EXPECT().Describe().Return(stack.StackDescription{
Parameters: map[string]string{
"AppName": "mock-app",
"EnvironmentName": "mock-env",
"ToolsAccountPrincipalARN": "mock-arn",
"AppDNSName": "mock-dns",
"AppDNSDelegationRole": "mock-role",
template.ALBFeatureName: "workload1,workload2",
template.EFSFeatureName: "",
template.NATFeatureName: "",
template.AliasesFeatureName: "",
},
}, nil)
},
wanted: []string{template.ALBFeatureName, template.EFSFeatureName, template.NATFeatureName, template.AliasesFeatureName},
},
"return up-to-date features": {
setupMock: func(m *envDescriberMocks) {
mockParams := map[string]string{
"AppName": "mock-app",
"EnvironmentName": "mock-env",
"ToolsAccountPrincipalARN": "mock-arn",
"AppDNSName": "mock-dns",
"AppDNSDelegationRole": "mock-role",
}
for _, f := range template.AvailableEnvFeatures() {
mockParams[f] = ""
}
m.stackDescriber.EXPECT().Describe().Return(stack.StackDescription{
Parameters: mockParams,
}, nil)
},
wanted: template.AvailableEnvFeatures(),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := &envDescriberMocks{
stackDescriber: mocks.NewMockstackDescriber(ctrl),
}
tc.setupMock(m)
d := &EnvDescriber{
cfn: m.stackDescriber,
}
// WHEN
got, err := d.AvailableFeatures()
// THEN
if tc.wantedErr != nil {
require.EqualError(t, err, tc.wantedErr.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wanted, got, "expected features to match")
}
})
}
}
func TestEnvDescriber_ValidateCFServiceDomainAliases(t *testing.T) {
const (
mockAppName = "mock-app"
mockEnvName = "mock-env"
mockALBWorkloads = "svc-1,svc-2"
mockAliasesJsonString = `{"svc-1":["test.copilot.com"],"svc-2":["test.copilot.com"]}`
mockInvalidAliasesJsonString = `{"svc-1":["test.copilot.com"]}`
)
mockEnvConfig := config.Environment{
App: mockAppName,
Name: mockEnvName,
}
testCases := map[string]struct {
setupMock func(m *envDescriberMocks)
wantedErr error
}{
"error describing stack": {
setupMock: func(m *envDescriberMocks) {
m.stackDescriber.EXPECT().Describe().Return(stack.StackDescription{}, errors.New("some error"))
},
wantedErr: fmt.Errorf("describe stack: some error"),
},
"no load balanced services": {
setupMock: func(m *envDescriberMocks) {
mockParams := map[string]string{
"AppName": mockAppName,
"EnvironmentName": mockEnvName,
}
m.stackDescriber.EXPECT().Describe().Return(stack.StackDescription{
Parameters: mockParams,
}, nil)
},
},
"no load balanced services with empty value for the ALBWorkloads parameter": {
setupMock: func(m *envDescriberMocks) {
mockParams := map[string]string{
"AppName": mockAppName,
"EnvironmentName": mockEnvName,
"ALBWorkloads": "",
}
m.stackDescriber.EXPECT().Describe().Return(stack.StackDescription{
Parameters: mockParams,
}, nil)
},
},
"missing aliases parameter in env stack": {
setupMock: func(m *envDescriberMocks) {
mockParams := map[string]string{
"AppName": mockAppName,
"EnvironmentName": mockEnvName,
"ALBWorkloads": mockALBWorkloads,
}
m.stackDescriber.EXPECT().Describe().Return(stack.StackDescription{
Parameters: mockParams,
}, nil)
},
wantedErr: fmt.Errorf("cannot find %s in env stack parameter set", cfnstack.EnvParamAliasesKey),
},
"error unmarshalling json string": {
setupMock: func(m *envDescriberMocks) {
mockParams := map[string]string{
"AppName": mockAppName,
"EnvironmentName": mockEnvName,
"ALBWorkloads": mockALBWorkloads,
"Aliases": "mock-invalid-aliases",
}
m.stackDescriber.EXPECT().Describe().Return(stack.StackDescription{
Parameters: mockParams,
}, nil)
},
wantedErr: fmt.Errorf("unmarshal \"mock-invalid-aliases\": invalid character 'm' looking for beginning of value"),
},
"no alb workloads have aliases parameter": {
setupMock: func(m *envDescriberMocks) {
mockParams := map[string]string{
"AppName": mockAppName,
"EnvironmentName": mockEnvName,
"ALBWorkloads": mockALBWorkloads,
"Aliases": "",
}
m.stackDescriber.EXPECT().Describe().Return(stack.StackDescription{
Parameters: mockParams,
}, nil)
},
wantedErr: fmt.Errorf("services \"svc-1\" and \"svc-2\" must have \"http.alias\" specified when CloudFront is enabled"),
},
"not all valid services have an alias": {
setupMock: func(m *envDescriberMocks) {
mockParams := map[string]string{
"AppName": mockAppName,
"EnvironmentName": mockEnvName,
"ALBWorkloads": mockALBWorkloads,
"Aliases": mockInvalidAliasesJsonString,
}
m.stackDescriber.EXPECT().Describe().Return(stack.StackDescription{
Parameters: mockParams,
}, nil)
},
wantedErr: fmt.Errorf("service \"svc-2\" must have \"http.alias\" specified when CloudFront is enabled"),
},
"all valid services have an alias": {
setupMock: func(m *envDescriberMocks) {
mockParams := map[string]string{
"AppName": mockAppName,
"EnvironmentName": mockEnvName,
"ALBWorkloads": mockALBWorkloads,
"Aliases": mockAliasesJsonString,
}
m.stackDescriber.EXPECT().Describe().Return(stack.StackDescription{
Parameters: mockParams,
}, nil)
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := &envDescriberMocks{
stackDescriber: mocks.NewMockstackDescriber(ctrl),
}
tc.setupMock(m)
d := &EnvDescriber{
app: mockAppName,
env: &mockEnvConfig,
cfn: m.stackDescriber,
deployStore: m.deployStoreSvc,
}
// WHEN
err := d.ValidateCFServiceDomainAliases()
// THEN
if tc.wantedErr != nil {
require.EqualError(t, err, tc.wantedErr.Error())
} else {
require.NoError(t, err)
}
})
}
}
func TestEnvDescription_JSONString(t *testing.T) {
testApp := &config.Application{
Name: "testApp",
Tags: map[string]string{"key1": "value1", "key2": "value2"},
}
testEnv := &config.Environment{
App: "testApp",
Name: "testEnv",
Region: "us-west-2",
AccountID: "123456789012",
RegistryURL: "",
ExecutionRoleARN: "",
ManagerRoleARN: "",
CustomConfig: &config.CustomizeEnv{},
}
testSvc1 := &config.Workload{
App: "testApp",
Name: "testSvc1",
Type: "load-balanced",
}
testSvc2 := &config.Workload{
App: "testApp",
Name: "testSvc2",
Type: "load-balanced",
}
testSvc3 := &config.Workload{
App: "testApp",
Name: "testSvc3",
Type: "load-balanced",
}
testJob1 := &config.Workload{
App: "testApp",
Name: "testJob1",
Type: "Scheduled Job",
}
allSvcs := []*config.Workload{testSvc1, testSvc2, testSvc3}
allJobs := []*config.Workload{testJob1}
wantedContent := "{\"environment\":{\"app\":\"testApp\",\"name\":\"testEnv\",\"region\":\"us-west-2\",\"accountID\":\"123456789012\",\"registryURL\":\"\",\"executionRoleARN\":\"\",\"managerRoleARN\":\"\",\"customConfig\":{}},\"services\":[{\"app\":\"testApp\",\"name\":\"testSvc1\",\"type\":\"load-balanced\"},{\"app\":\"testApp\",\"name\":\"testSvc2\",\"type\":\"load-balanced\"},{\"app\":\"testApp\",\"name\":\"testSvc3\",\"type\":\"load-balanced\"}],\"jobs\":[{\"app\":\"testApp\",\"name\":\"testJob1\",\"type\":\"Scheduled Job\"}],\"tags\":{\"key1\":\"value1\",\"key2\":\"value2\"},\"resources\":[{\"type\":\"AWS::IAM::Role\",\"physicalID\":\"testApp-testEnv-CFNExecutionRole\"},{\"type\":\"testApp-testEnv-Cluster\",\"physicalID\":\"AWS::ECS::Cluster-jI63pYBWU6BZ\"}],\"environmentVPC\":{\"id\":\"\",\"publicSubnetIDs\":null,\"privateSubnetIDs\":null}}\n"
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
d := &EnvDescription{
Environment: testEnv,
EnvironmentVPC: EnvironmentVPC{},
Services: allSvcs,
Jobs: allJobs,
Tags: testApp.Tags,
Resources: wantedResources,
}
// WHEN
actual, _ := d.JSONString()
// THEN
require.Equal(t, wantedContent, actual)
}
func TestEnvDescription_HumanString(t *testing.T) {
testApp := &config.Application{
Name: "testApp",
Tags: map[string]string{"key1": "value1", "key2": "value2"},
}
testEnv := &config.Environment{
App: "testApp",
Name: "testEnv",
Region: "us-west-2",
AccountID: "123456789012",
RegistryURL: "",
ExecutionRoleARN: "",
ManagerRoleARN: "",
}
testSvc1 := &config.Workload{
App: "testApp",
Name: "testSvc1",
Type: "load-balanced",
}
testSvc2 := &config.Workload{
App: "testApp",
Name: "testSvc2",
Type: "load-balanced",
}
testSvc3 := &config.Workload{
App: "testApp",
Name: "testSvc3",
Type: "load-balanced",
}
testJob1 := &config.Workload{
App: "testApp",
Name: "testJob1",
Type: "Scheduled Job",
}
allSvcs := []*config.Workload{testSvc1, testSvc2, testSvc3}
allJobs := []*config.Workload{testJob1}
wantedContent := `About
Name testEnv
Region us-west-2
Account ID 123456789012
Workloads
Name Type
---- ----
testSvc1 load-balanced
testSvc2 load-balanced
testSvc3 load-balanced
testJob1 Scheduled Job
Tags
Key Value
--- -----
key1 value1
key2 value2
Resources
AWS::IAM::Role testApp-testEnv-CFNExecutionRole
testApp-testEnv-Cluster AWS::ECS::Cluster-jI63pYBWU6BZ
`
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
d := &EnvDescription{
Environment: testEnv,
Services: allSvcs,
Jobs: allJobs,
Tags: testApp.Tags,
Resources: wantedResources,
}
// WHEN
actual := d.HumanString()
// THEN
require.Equal(t, wantedContent, actual)
}
| 926 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package describe
import (
"errors"
"fmt"
"github.com/aws/copilot-cli/internal/pkg/template"
"github.com/dustin/go-humanize/english"
)
// ErrManifestNotFoundInTemplate is returned when a deployed CFN template
// is missing manifest data.
type ErrManifestNotFoundInTemplate struct {
app string
env string
name string
}
// Error implements the error interface.
func (err *ErrManifestNotFoundInTemplate) Error() string {
return fmt.Sprintf("manifest metadata not found in template of stack %s-%s-%s", err.app, err.env, err.name)
}
// ErrNonAccessibleServiceType is returned when a service type cannot be reached over the network.
type ErrNonAccessibleServiceType struct {
name string
svcType string
}
// Error implements the error interface.
func (err *ErrNonAccessibleServiceType) Error() string {
return fmt.Sprintf("service %s is of type %s which cannot be reached over the network", err.name, err.svcType)
}
type errLBWebSvcsOnCFWithoutAlias struct {
services []string
aliasField string
}
// Error implements the error interface.
func (err *errLBWebSvcsOnCFWithoutAlias) Error() string {
return fmt.Sprintf("%s %s must have %q specified when CloudFront is enabled", english.PluralWord(len(err.services), "service", "services"),
english.WordSeries(template.QuoteSliceFunc(err.services), "and"), err.aliasField)
}
var errVPCIngressConnectionNotFound = errors.New("no vpc ingress connection found")
| 50 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package describe
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestErrManifestNotFoundInTemplate_Error(t *testing.T) {
require.EqualError(t,
&ErrManifestNotFoundInTemplate{app: "phonetool", env: "test", name: "api"},
"manifest metadata not found in template of stack phonetool-test-api")
}
| 17 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package describe
import (
"strings"
"github.com/aws/copilot-cli/internal/pkg/aws/ecs"
"github.com/aws/copilot-cli/internal/pkg/aws/elbv2"
)
func isContainerHealthCheckEnabled(tasks []ecs.TaskStatus) bool {
// If all of the tasks container health is empty or UNKNOWN, then the container health check
// is *typically* NOT enabled.
for _, t := range tasks {
if t.Health != ecs.TaskContainerHealthStatusUnknown && t.Health != "" {
return true
}
}
return false
}
func isCapacityProvidersEnabled(tasks []ecs.TaskStatus) bool {
for _, task := range tasks {
if task.CapacityProvider != "" {
return true
}
}
return false
}
func anyTasksInAnyTargetGroup(tasks []ecs.TaskStatus, targetHealthDescriptions []taskTargetHealth) bool {
taskToHealth := summarizeHTTPHealthForTasks(targetHealthDescriptions)
for _, t := range tasks {
if _, ok := taskToHealth[t.ID]; ok {
return true
}
}
return false
}
func containerHealthBreakDownByCount(tasks []ecs.TaskStatus) (healthy int, unhealthy int, unknown int) {
for _, t := range tasks {
switch strings.ToUpper(t.Health) {
case ecs.TaskContainerHealthStatusHealthy:
healthy += 1
case ecs.TaskContainerHealthStatusUnhealthy:
unhealthy += 1
case ecs.TaskContainerHealthStatusUnknown:
unknown += 1
}
}
return
}
func countHealthyHTTPTasks(tasks []ecs.TaskStatus, targetHealthDescriptions []taskTargetHealth) int {
var count int
taskToHealth := summarizeHTTPHealthForTasks(targetHealthDescriptions)
for _, t := range tasks {
// A task is healthy if it has health states and all of its states are healthy
if _, ok := taskToHealth[t.ID]; !ok {
continue
}
healthy := true
for _, state := range taskToHealth[t.ID] {
if state != elbv2.TargetHealthStateHealthy {
healthy = false
}
}
if healthy {
count += 1
}
}
return count
}
func summarizeHTTPHealthForTasks(targetsHealth []taskTargetHealth) map[string][]string {
out := make(map[string][]string)
for _, th := range targetsHealth {
if th.TaskID == "" {
continue
}
out[th.TaskID] = append(out[th.TaskID], th.HealthStatus.HealthState)
}
return out
}
func runningCapacityProvidersBreakDownByCount(tasks []ecs.TaskStatus) (fargate, spot, empty int) {
for _, t := range tasks {
if t.LastStatus != ecs.TaskStatusRunning {
continue
}
switch strings.ToUpper(t.CapacityProvider) {
case ecs.TaskCapacityProviderFargate:
fargate += 1
case ecs.TaskCapacityProviderFargateSpot:
spot += 1
default:
empty += 1
}
}
return
}
func (s *ecsServiceStatus) tasksOfRevision(revision int) []ecs.TaskStatus {
var ret []ecs.TaskStatus
for _, t := range s.DesiredRunningTasks {
taskRevision, err := ecs.TaskDefinitionVersion(t.TaskDefinition)
if err != nil {
continue
}
if taskRevision == revision {
ret = append(ret, t)
}
}
return ret
}
| 119 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package describe
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"strconv"
"strings"
"text/tabwriter"
"github.com/aws/copilot-cli/internal/pkg/aws/cloudwatch"
"github.com/aws/copilot-cli/internal/pkg/docker/dockerengine"
"github.com/aws/copilot-cli/internal/pkg/manifest/manifestinfo"
"github.com/aws/copilot-cli/internal/pkg/aws/elbv2"
"github.com/aws/copilot-cli/internal/pkg/aws/sessions"
"github.com/aws/aws-sdk-go/aws/awserr"
cfnstack "github.com/aws/copilot-cli/internal/pkg/deploy/cloudformation/stack"
"github.com/aws/copilot-cli/internal/pkg/describe/stack"
"github.com/aws/copilot-cli/internal/pkg/term/color"
)
const (
envOutputPublicLoadBalancerDNSName = "PublicLoadBalancerDNSName"
envOutputInternalLoadBalancerDNSName = "InternalLoadBalancerDNSName"
envOutputSubdomain = "EnvironmentSubdomain"
envOutputCloudFrontDomainName = "CloudFrontDomainName"
envOutputPublicALBAccessible = "PublicALBAccessible"
svcStackResourceALBTargetGroupLogicalID = "TargetGroup"
svcStackResourceNLBTargetGroupLogicalID = "NLBTargetGroup"
svcStackResourceHTTPSListenerRuleLogicalID = "HTTPSListenerRule"
svcStackResourceHTTPListenerRuleLogicalID = "HTTPListenerRule"
svcStackResourceListenerRuleResourceType = "AWS::ElasticLoadBalancingV2::ListenerRule"
svcOutputPublicNLBDNSName = "PublicNetworkLoadBalancerDNSName"
)
type envDescriber interface {
ServiceDiscoveryEndpoint() (string, error)
Params() (map[string]string, error)
Outputs() (map[string]string, error)
}
type lbDescriber interface {
ListenerRulesHostHeaders(ruleARNs []string) ([]string, error)
}
// LBWebServiceDescriber retrieves information about a load balanced web service.
type LBWebServiceDescriber struct {
app string
svc string
enableResources bool
store DeployedEnvServicesLister
initECSServiceDescribers func(string) (ecsDescriber, error)
initEnvDescribers func(string) (envDescriber, error)
initLBDescriber func(string) (lbDescriber, error)
initCWDescriber func(string) (cwAlarmDescriber, error)
ecsServiceDescribers map[string]ecsDescriber
envDescriber map[string]envDescriber
cwAlarmDescribers map[string]cwAlarmDescriber
}
// NewLBWebServiceDescriber instantiates a load balanced service describer.
func NewLBWebServiceDescriber(opt NewServiceConfig) (*LBWebServiceDescriber, error) {
describer := &LBWebServiceDescriber{
app: opt.App,
svc: opt.Svc,
enableResources: opt.EnableResources,
store: opt.DeployStore,
ecsServiceDescribers: make(map[string]ecsDescriber),
envDescriber: make(map[string]envDescriber),
}
describer.initLBDescriber = func(envName string) (lbDescriber, error) {
env, err := opt.ConfigStore.GetEnvironment(opt.App, envName)
if err != nil {
return nil, fmt.Errorf("get environment %s: %w", envName, err)
}
sess, err := sessions.ImmutableProvider().FromRole(env.ManagerRoleARN, env.Region)
if err != nil {
return nil, err
}
return elbv2.New(sess), nil
}
describer.initECSServiceDescribers = func(env string) (ecsDescriber, error) {
if describer, ok := describer.ecsServiceDescribers[env]; ok {
return describer, nil
}
svcDescr, err := newECSServiceDescriber(NewServiceConfig{
App: opt.App,
Svc: opt.Svc,
ConfigStore: opt.ConfigStore,
}, env)
if err != nil {
return nil, err
}
describer.ecsServiceDescribers[env] = svcDescr
return svcDescr, nil
}
describer.initEnvDescribers = func(env string) (envDescriber, error) {
if describer, ok := describer.envDescriber[env]; ok {
return describer, nil
}
envDescr, err := NewEnvDescriber(NewEnvDescriberConfig{
App: opt.App,
Env: env,
ConfigStore: opt.ConfigStore,
})
if err != nil {
return nil, err
}
describer.envDescriber[env] = envDescr
return envDescr, nil
}
describer.initCWDescriber = func(envName string) (cwAlarmDescriber, error) {
if describer, ok := describer.cwAlarmDescribers[envName]; ok {
return describer, nil
}
env, err := opt.ConfigStore.GetEnvironment(opt.App, envName)
if err != nil {
return nil, fmt.Errorf("get environment %s: %w", envName, err)
}
sess, err := sessions.ImmutableProvider().FromRole(env.ManagerRoleARN, env.Region)
if err != nil {
return nil, err
}
return cloudwatch.New(sess), nil
}
return describer, nil
}
// Describe returns info of a web service.
func (d *LBWebServiceDescriber) Describe() (HumanJSONStringer, error) {
environments, err := d.store.ListEnvironmentsDeployedTo(d.app, d.svc)
if err != nil {
return nil, fmt.Errorf("list deployed environments for application %s: %w", d.app, err)
}
var routes []*WebServiceRoute
var configs []*ECSServiceConfig
svcDiscoveries := make(serviceDiscoveries)
svcConnects := make(serviceConnects)
var envVars []*containerEnvVar
var secrets []*secret
var alarmDescriptions []*cloudwatch.AlarmDescription
for _, env := range environments {
svcDescr, err := d.initECSServiceDescribers(env)
if err != nil {
return nil, err
}
uri, err := d.URI(env)
if err != nil {
return nil, fmt.Errorf("retrieve service URI: %w", err)
}
routes = append(routes, &WebServiceRoute{
Environment: env,
URL: uri.URI,
})
containerPlatform, err := svcDescr.Platform()
if err != nil {
return nil, fmt.Errorf("retrieve platform: %w", err)
}
webSvcEnvVars, err := svcDescr.EnvVars()
if err != nil {
return nil, fmt.Errorf("retrieve environment variables: %w", err)
}
svcParams, err := svcDescr.Params()
if err != nil {
return nil, fmt.Errorf("get stack parameters for service %s: %w", d.svc, err)
}
configs = append(configs, &ECSServiceConfig{
ServiceConfig: &ServiceConfig{
Environment: env,
Port: svcParams[cfnstack.WorkloadTargetPortParamKey],
CPU: svcParams[cfnstack.WorkloadTaskCPUParamKey],
Memory: svcParams[cfnstack.WorkloadTaskMemoryParamKey],
Platform: dockerengine.PlatformString(containerPlatform.OperatingSystem, containerPlatform.Architecture),
},
Tasks: svcParams[cfnstack.WorkloadTaskCountParamKey],
})
alarmNames, err := svcDescr.RollbackAlarmNames()
if err != nil {
return nil, fmt.Errorf("retrieve rollback alarm names: %w", err)
}
if len(alarmNames) != 0 {
cwAlarmDescr, err := d.initCWDescriber(env)
if err != nil {
return nil, err
}
alarms, err := cwAlarmDescr.AlarmDescriptions(alarmNames)
if err != nil {
return nil, fmt.Errorf("retrieve alarm descriptions: %w", err)
}
for _, alarm := range alarms {
alarm.Environment = env
}
alarmDescriptions = append(alarmDescriptions, alarms...)
}
envDescr, err := d.initEnvDescribers(env)
if err != nil {
return nil, err
}
if err := svcDiscoveries.collectEndpoints(
envDescr, d.svc, env, svcParams[cfnstack.WorkloadTargetPortParamKey]); err != nil {
return nil, err
}
if err := svcConnects.collectEndpoints(svcDescr, env); err != nil {
return nil, err
}
envVars = append(envVars, flattenContainerEnvVars(env, webSvcEnvVars)...)
webSvcSecrets, err := svcDescr.Secrets()
if err != nil {
return nil, fmt.Errorf("retrieve secrets: %w", err)
}
secrets = append(secrets, flattenSecrets(env, webSvcSecrets)...)
}
resources := make(map[string][]*stack.Resource)
if d.enableResources {
for _, env := range environments {
svcDescr, err := d.initECSServiceDescribers(env)
if err != nil {
return nil, err
}
stackResources, err := svcDescr.StackResources()
if err != nil {
return nil, fmt.Errorf("retrieve service resources: %w", err)
}
resources[env] = stackResources
}
}
return &webSvcDesc{
ecsSvcDesc: ecsSvcDesc{
Service: d.svc,
Type: manifestinfo.LoadBalancedWebServiceType,
App: d.app,
Configurations: configs,
AlarmDescriptions: alarmDescriptions,
Routes: routes,
ServiceDiscovery: svcDiscoveries,
ServiceConnect: svcConnects,
Variables: envVars,
Secrets: secrets,
Resources: resources,
environments: environments,
},
}, nil
}
// Manifest returns the contents of the manifest used to deploy a load balanced web service stack.
// If the Manifest metadata doesn't exist in the stack template, then returns ErrManifestNotFoundInTemplate.
func (d *LBWebServiceDescriber) Manifest(env string) ([]byte, error) {
cfn, err := d.initECSServiceDescribers(env)
if err != nil {
return nil, err
}
return cfn.Manifest()
}
// WebServiceRoute contains serialized route parameters for a web service.
type WebServiceRoute struct {
Environment string `json:"environment"`
URL string `json:"url"`
}
// webSvcDesc contains serialized parameters for a web service.
type webSvcDesc struct {
ecsSvcDesc
}
// JSONString returns the stringified webSvcDesc struct in json format.
func (w *webSvcDesc) JSONString() (string, error) {
b, err := json.Marshal(w)
if err != nil {
return "", fmt.Errorf("marshal web service description: %w", err)
}
return fmt.Sprintf("%s\n", b), nil
}
// HumanString returns the stringified webService struct in human readable format.
func (w *webSvcDesc) HumanString() string {
var b bytes.Buffer
writer := tabwriter.NewWriter(&b, minCellWidth, tabWidth, cellPaddingWidth, paddingChar, noAdditionalFormatting)
fmt.Fprint(writer, color.Bold.Sprint("About\n\n"))
writer.Flush()
fmt.Fprintf(writer, " %s\t%s\n", "Application", w.App)
fmt.Fprintf(writer, " %s\t%s\n", "Name", w.Service)
fmt.Fprintf(writer, " %s\t%s\n", "Type", w.Type)
fmt.Fprint(writer, color.Bold.Sprint("\nConfigurations\n\n"))
writer.Flush()
w.Configurations.humanString(writer)
if len(w.AlarmDescriptions) > 0 {
fmt.Fprint(writer, color.Bold.Sprint("\nRollback Alarms\n\n"))
writer.Flush()
rollbackAlarms(w.AlarmDescriptions).humanString(writer)
}
fmt.Fprint(writer, color.Bold.Sprint("\nRoutes\n\n"))
writer.Flush()
headers := []string{"Environment", "URL"}
fmt.Fprintf(writer, " %s\n", strings.Join(headers, "\t"))
fmt.Fprintf(writer, " %s\n", strings.Join(underline(headers), "\t"))
for _, route := range w.Routes {
fmt.Fprintf(writer, " %s\t%s\n", route.Environment, route.URL)
}
if len(w.ServiceConnect) > 0 || len(w.ServiceDiscovery) > 0 {
fmt.Fprint(writer, color.Bold.Sprint("\nInternal Service Endpoint\n\n"))
writer.Flush()
endpoints := serviceEndpoints{
discoveries: w.ServiceDiscovery,
connects: w.ServiceConnect,
}
endpoints.humanString(writer)
}
fmt.Fprint(writer, color.Bold.Sprint("\nVariables\n\n"))
writer.Flush()
w.Variables.humanString(writer)
if len(w.Secrets) != 0 {
fmt.Fprint(writer, color.Bold.Sprint("\nSecrets\n\n"))
writer.Flush()
w.Secrets.humanString(writer)
}
if len(w.Resources) != 0 {
fmt.Fprint(writer, color.Bold.Sprint("\nResources\n"))
writer.Flush()
w.Resources.humanStringByEnv(writer, w.environments)
}
writer.Flush()
return b.String()
}
func cpuToString(s string) string {
cpuInt, _ := strconv.Atoi(s)
cpuFloat := float64(cpuInt) / 1024
return fmt.Sprintf("%g", cpuFloat)
}
// IsStackNotExistsErr returns true if error type is stack not exist.
func IsStackNotExistsErr(err error) bool {
if err == nil {
return false
}
aerr, ok := err.(awserr.Error)
if !ok {
return IsStackNotExistsErr(errors.Unwrap(err))
}
if aerr.Code() != "ValidationError" {
return IsStackNotExistsErr(errors.Unwrap(err))
}
if !strings.Contains(aerr.Message(), "does not exist") {
return IsStackNotExistsErr(errors.Unwrap(err))
}
return true
}
| 361 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package describe
import (
"errors"
"fmt"
"testing"
"github.com/aws/copilot-cli/internal/pkg/aws/cloudwatch"
"github.com/aws/copilot-cli/internal/pkg/aws/ecs"
cfnstack "github.com/aws/copilot-cli/internal/pkg/deploy/cloudformation/stack"
"github.com/aws/copilot-cli/internal/pkg/describe/mocks"
"github.com/aws/copilot-cli/internal/pkg/describe/stack"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
type lbWebSvcDescriberMocks struct {
storeSvc *mocks.MockDeployedEnvServicesLister
ecsDescriber *mocks.MockecsDescriber
envDescriber *mocks.MockenvDescriber
lbDescriber *mocks.MocklbDescriber
cwDescriber *mocks.MockcwAlarmDescriber
}
func TestLBWebServiceDescriber_Describe(t *testing.T) {
const (
testApp = "phonetool"
testEnv = "test"
testSvc = "jobs"
testEnvLBDNSName = "abc.us-west-1.elb.amazonaws.com"
testSvcPath = "*"
testALBAccessible = "true"
prodEnv = "prod"
prodSvcPath = "*"
alarm1 = "alarm1"
alarm2 = "alarm2"
desc1 = "alarm description 1"
desc2 = "alarm description 2"
)
mockParams := map[string]string{
cfnstack.WorkloadTargetPortParamKey: "80",
cfnstack.WorkloadTaskCountParamKey: "1",
cfnstack.WorkloadTaskCPUParamKey: "256",
cfnstack.WorkloadTaskMemoryParamKey: "512",
cfnstack.WorkloadRulePathParamKey: testSvcPath,
}
mockProdParams := map[string]string{
cfnstack.WorkloadTargetPortParamKey: "5000",
cfnstack.WorkloadTaskCountParamKey: "2",
cfnstack.WorkloadTaskCPUParamKey: "512",
cfnstack.WorkloadTaskMemoryParamKey: "1024",
cfnstack.WorkloadRulePathParamKey: prodSvcPath,
}
mockErr := errors.New("some error")
testCases := map[string]struct {
shouldOutputResources bool
setupMocks func(mocks lbWebSvcDescriberMocks)
wantedWebSvc *webSvcDesc
wantedError error
}{
"return error if fail to list environment": {
setupMocks: func(m lbWebSvcDescriberMocks) {
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return(nil, mockErr),
)
},
wantedError: fmt.Errorf("list deployed environments for application phonetool: some error"),
},
"return error if fail to retrieve URI for ALB service": {
setupMocks: func(m lbWebSvcDescriberMocks) {
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv}, nil),
m.ecsDescriber.EXPECT().StackResources().Return([]*stack.Resource{
{
LogicalID: svcStackResourceALBTargetGroupLogicalID,
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(nil, mockErr),
)
},
wantedError: fmt.Errorf("retrieve service URI: get stack parameters for service jobs: some error"),
},
"return error if fail to retrieve service params": {
setupMocks: func(m lbWebSvcDescriberMocks) {
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv}, nil),
m.ecsDescriber.EXPECT().StackResources().Return([]*stack.Resource{
{
LogicalID: svcStackResourceALBTargetGroupLogicalID,
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(mockParams, nil),
m.envDescriber.EXPECT().Outputs().Return(map[string]string{
envOutputPublicLoadBalancerDNSName: testEnvLBDNSName,
}, nil),
m.ecsDescriber.EXPECT().Platform().Return(&ecs.ContainerPlatform{
OperatingSystem: "LINUX",
Architecture: "X86_64",
}, nil),
m.ecsDescriber.EXPECT().EnvVars().Return([]*ecs.ContainerEnvVar{
{
Name: "COPILOT_ENVIRONMENT_NAME",
Container: "container",
Value: "prod",
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(nil, mockErr),
)
},
wantedError: fmt.Errorf("get stack parameters for service jobs: some error"),
},
"return error if fail to retrieve service discovery endpoint": {
setupMocks: func(m lbWebSvcDescriberMocks) {
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv}, nil),
m.ecsDescriber.EXPECT().StackResources().Return([]*stack.Resource{
{
LogicalID: svcStackResourceALBTargetGroupLogicalID,
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(mockParams, nil),
m.envDescriber.EXPECT().Outputs().Return(map[string]string{
envOutputPublicLoadBalancerDNSName: testEnvLBDNSName,
}, nil),
m.ecsDescriber.EXPECT().Platform().Return(&ecs.ContainerPlatform{
OperatingSystem: "LINUX",
Architecture: "X86_64",
}, nil),
m.ecsDescriber.EXPECT().EnvVars().Return([]*ecs.ContainerEnvVar{
{
Name: "COPILOT_ENVIRONMENT_NAME",
Container: "container",
Value: "prod",
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(mockParams, nil),
m.ecsDescriber.EXPECT().RollbackAlarmNames().Return(nil, nil),
m.envDescriber.EXPECT().ServiceDiscoveryEndpoint().Return("", errors.New("some error")),
)
},
wantedError: fmt.Errorf("some error"),
},
"return error if fail to retrieve platform": {
setupMocks: func(m lbWebSvcDescriberMocks) {
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv}, nil),
m.ecsDescriber.EXPECT().StackResources().Return([]*stack.Resource{
{
LogicalID: svcStackResourceALBTargetGroupLogicalID,
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(mockParams, nil),
m.envDescriber.EXPECT().Outputs().Return(map[string]string{
envOutputPublicLoadBalancerDNSName: testEnvLBDNSName,
}, nil),
m.ecsDescriber.EXPECT().Platform().Return(nil, errors.New("some error")),
)
},
wantedError: fmt.Errorf("retrieve platform: some error"),
},
"return error if fail to retrieve environment variables": {
setupMocks: func(m lbWebSvcDescriberMocks) {
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv}, nil),
m.ecsDescriber.EXPECT().StackResources().Return([]*stack.Resource{
{
LogicalID: svcStackResourceALBTargetGroupLogicalID,
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(mockParams, nil),
m.envDescriber.EXPECT().Outputs().Return(map[string]string{
envOutputPublicLoadBalancerDNSName: testEnvLBDNSName,
}, nil),
m.ecsDescriber.EXPECT().Platform().Return(&ecs.ContainerPlatform{
OperatingSystem: "LINUX",
Architecture: "X86_64",
}, nil),
m.ecsDescriber.EXPECT().EnvVars().Return(nil, mockErr),
)
},
wantedError: fmt.Errorf("retrieve environment variables: some error"),
},
"return error if fail to retrieve rollback alarm names": {
setupMocks: func(m lbWebSvcDescriberMocks) {
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv}, nil),
m.ecsDescriber.EXPECT().StackResources().Return([]*stack.Resource{
{
LogicalID: svcStackResourceALBTargetGroupLogicalID,
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(mockParams, nil),
m.envDescriber.EXPECT().Outputs().Return(map[string]string{
envOutputPublicLoadBalancerDNSName: testEnvLBDNSName,
}, nil),
m.ecsDescriber.EXPECT().Platform().Return(&ecs.ContainerPlatform{
OperatingSystem: "LINUX",
Architecture: "X86_64",
}, nil),
m.ecsDescriber.EXPECT().EnvVars().Return([]*ecs.ContainerEnvVar{
{
Name: "COPILOT_ENVIRONMENT_NAME",
Container: "container",
Value: "prod",
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(mockParams, nil),
m.ecsDescriber.EXPECT().RollbackAlarmNames().Return(nil, errors.New("some error")),
)
},
wantedError: fmt.Errorf("retrieve rollback alarm names: some error"),
},
"return error if fail to retrieve alarm descriptions": {
setupMocks: func(m lbWebSvcDescriberMocks) {
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv}, nil),
m.ecsDescriber.EXPECT().StackResources().Return([]*stack.Resource{
{
LogicalID: svcStackResourceALBTargetGroupLogicalID,
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(mockParams, nil),
m.envDescriber.EXPECT().Outputs().Return(map[string]string{
envOutputPublicLoadBalancerDNSName: testEnvLBDNSName,
}, nil),
m.ecsDescriber.EXPECT().Platform().Return(&ecs.ContainerPlatform{
OperatingSystem: "LINUX",
Architecture: "X86_64",
}, nil),
m.ecsDescriber.EXPECT().EnvVars().Return([]*ecs.ContainerEnvVar{
{
Name: "COPILOT_ENVIRONMENT_NAME",
Container: "container",
Value: "prod",
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(mockParams, nil),
m.ecsDescriber.EXPECT().RollbackAlarmNames().Return([]string{alarm1, alarm2}, nil),
m.cwDescriber.EXPECT().AlarmDescriptions([]string{alarm1, alarm2}).Return(nil, errors.New("some error")),
)
},
wantedError: fmt.Errorf("retrieve alarm descriptions: some error"),
},
"return error if fail to retrieve service connect DNS names": {
setupMocks: func(m lbWebSvcDescriberMocks) {
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv}, nil),
m.ecsDescriber.EXPECT().StackResources().Return([]*stack.Resource{
{
LogicalID: svcStackResourceALBTargetGroupLogicalID,
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(mockParams, nil),
m.envDescriber.EXPECT().Outputs().Return(map[string]string{
envOutputPublicLoadBalancerDNSName: testEnvLBDNSName,
}, nil),
m.ecsDescriber.EXPECT().Platform().Return(&ecs.ContainerPlatform{
OperatingSystem: "LINUX",
Architecture: "X86_64",
}, nil),
m.ecsDescriber.EXPECT().EnvVars().Return([]*ecs.ContainerEnvVar{
{
Name: "COPILOT_ENVIRONMENT_NAME",
Container: "container",
Value: "prod",
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(mockParams, nil),
m.ecsDescriber.EXPECT().RollbackAlarmNames().Return(nil, nil),
m.envDescriber.EXPECT().ServiceDiscoveryEndpoint().Return("test.phonetool.local", nil),
m.ecsDescriber.EXPECT().ServiceConnectDNSNames().Return(nil, mockErr),
)
},
wantedError: fmt.Errorf("retrieve service connect DNS names: some error"),
},
"return error if fail to retrieve secrets": {
setupMocks: func(m lbWebSvcDescriberMocks) {
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv}, nil),
m.ecsDescriber.EXPECT().StackResources().Return([]*stack.Resource{
{
LogicalID: svcStackResourceALBTargetGroupLogicalID,
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(mockParams, nil),
m.envDescriber.EXPECT().Outputs().Return(map[string]string{
envOutputPublicLoadBalancerDNSName: testEnvLBDNSName,
}, nil),
m.ecsDescriber.EXPECT().Platform().Return(&ecs.ContainerPlatform{
OperatingSystem: "LINUX",
Architecture: "X86_64",
}, nil),
m.ecsDescriber.EXPECT().EnvVars().Return([]*ecs.ContainerEnvVar{
{
Name: "COPILOT_ENVIRONMENT_NAME",
Container: "container",
Value: "prod",
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(mockParams, nil),
m.ecsDescriber.EXPECT().RollbackAlarmNames().Return(nil, nil),
m.envDescriber.EXPECT().ServiceDiscoveryEndpoint().Return("test.phonetool.local", nil),
m.ecsDescriber.EXPECT().ServiceConnectDNSNames().Return(nil, nil),
m.ecsDescriber.EXPECT().Secrets().Return(nil, mockErr),
)
},
wantedError: fmt.Errorf("retrieve secrets: some error"),
},
"return error if fail to retrieve service resources for ALB service": {
shouldOutputResources: true,
setupMocks: func(m lbWebSvcDescriberMocks) {
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv}, nil),
m.ecsDescriber.EXPECT().StackResources().Return([]*stack.Resource{
{
LogicalID: svcStackResourceALBTargetGroupLogicalID,
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(mockParams, nil),
m.envDescriber.EXPECT().Outputs().Return(map[string]string{
envOutputPublicLoadBalancerDNSName: testEnvLBDNSName,
}, nil),
m.ecsDescriber.EXPECT().Platform().Return(&ecs.ContainerPlatform{
OperatingSystem: "LINUX",
Architecture: "X86_64",
}, nil),
m.ecsDescriber.EXPECT().EnvVars().Return([]*ecs.ContainerEnvVar{
{
Name: "COPILOT_ENVIRONMENT_NAME",
Container: "container",
Value: "test",
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(mockParams, nil),
m.ecsDescriber.EXPECT().RollbackAlarmNames().Return(nil, nil),
m.envDescriber.EXPECT().ServiceDiscoveryEndpoint().Return("test.phonetool.local", nil),
m.ecsDescriber.EXPECT().ServiceConnectDNSNames().Return(nil, nil),
m.ecsDescriber.EXPECT().Secrets().Return([]*ecs.ContainerSecret{
{
Name: "GITHUB_WEBHOOK_SECRET",
Container: "container",
ValueFrom: "GH_WEBHOOK_SECRET",
},
{
Name: "SOME_OTHER_SECRET",
Container: "container",
ValueFrom: "SHHHHHHHH",
},
}, nil),
m.ecsDescriber.EXPECT().StackResources().Return(nil, mockErr),
)
},
wantedError: fmt.Errorf("retrieve service resources: some error"),
},
"should not try to fetch descriptions if no ROLLBACK alarms present": {
setupMocks: func(m lbWebSvcDescriberMocks) {
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv}, nil),
m.ecsDescriber.EXPECT().StackResources().Return([]*stack.Resource{
{
LogicalID: svcStackResourceALBTargetGroupLogicalID,
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(mockParams, nil),
m.envDescriber.EXPECT().Outputs().Return(map[string]string{
envOutputPublicLoadBalancerDNSName: testEnvLBDNSName,
envOutputPublicALBAccessible: testALBAccessible,
}, nil),
m.ecsDescriber.EXPECT().Platform().Return(&ecs.ContainerPlatform{
OperatingSystem: "LINUX",
Architecture: "X86_64",
}, nil),
m.ecsDescriber.EXPECT().EnvVars().Return([]*ecs.ContainerEnvVar{}, nil),
m.ecsDescriber.EXPECT().Params().Return(mockParams, nil),
m.ecsDescriber.EXPECT().RollbackAlarmNames().Return([]string{}, nil),
m.envDescriber.EXPECT().ServiceDiscoveryEndpoint().Return("test.phonetool.local", nil),
m.ecsDescriber.EXPECT().ServiceConnectDNSNames().Return([]string{testSvc}, nil),
m.ecsDescriber.EXPECT().Secrets().Return([]*ecs.ContainerSecret{}, nil))
},
wantedWebSvc: &webSvcDesc{
ecsSvcDesc: ecsSvcDesc{
Service: testSvc,
Type: "Load Balanced Web Service",
App: testApp,
Configurations: []*ECSServiceConfig{
{
ServiceConfig: &ServiceConfig{
CPU: "256",
Environment: "test",
Memory: "512",
Platform: "LINUX/X86_64",
Port: "80",
},
Tasks: "1",
},
},
Routes: []*WebServiceRoute{
{
Environment: "test",
URL: "http://abc.us-west-1.elb.amazonaws.com/*",
},
},
ServiceDiscovery: serviceDiscoveries{
"jobs.test.phonetool.local:80": []string{"test"},
},
ServiceConnect: serviceConnects{
testSvc: []string{"test"},
},
Resources: map[string][]*stack.Resource{},
environments: []string{"test"},
},
},
},
"success for ALB service": {
shouldOutputResources: true,
setupMocks: func(m lbWebSvcDescriberMocks) {
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv, prodEnv}, nil),
m.ecsDescriber.EXPECT().StackResources().Return([]*stack.Resource{
{
LogicalID: svcStackResourceALBTargetGroupLogicalID,
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(mockParams, nil),
m.envDescriber.EXPECT().Outputs().Return(map[string]string{
envOutputPublicLoadBalancerDNSName: testEnvLBDNSName,
envOutputPublicALBAccessible: testALBAccessible,
}, nil),
m.ecsDescriber.EXPECT().Platform().Return(&ecs.ContainerPlatform{
OperatingSystem: "LINUX",
Architecture: "X86_64",
}, nil),
m.ecsDescriber.EXPECT().EnvVars().Return([]*ecs.ContainerEnvVar{
{
Name: "COPILOT_ENVIRONMENT_NAME",
Container: "container1",
Value: testEnv,
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(mockParams, nil),
m.ecsDescriber.EXPECT().RollbackAlarmNames().Return([]string{alarm1}, nil),
m.cwDescriber.EXPECT().AlarmDescriptions([]string{alarm1}).Return([]*cloudwatch.AlarmDescription{
{
Name: alarm1,
Description: desc1,
Environment: testEnv,
},
}, nil),
m.envDescriber.EXPECT().ServiceDiscoveryEndpoint().Return("test.phonetool.local", nil),
m.ecsDescriber.EXPECT().ServiceConnectDNSNames().Return([]string{testSvc}, nil),
m.ecsDescriber.EXPECT().Secrets().Return([]*ecs.ContainerSecret{
{
Name: "GITHUB_WEBHOOK_SECRET",
Container: "container",
ValueFrom: "GH_WEBHOOK_SECRET",
},
}, nil),
m.ecsDescriber.EXPECT().StackResources().Return([]*stack.Resource{
{
LogicalID: svcStackResourceALBTargetGroupLogicalID,
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(mockProdParams, nil),
m.envDescriber.EXPECT().Outputs().Return(map[string]string{
envOutputPublicLoadBalancerDNSName: testEnvLBDNSName,
envOutputPublicALBAccessible: testALBAccessible,
}, nil),
m.ecsDescriber.EXPECT().Platform().Return(&ecs.ContainerPlatform{
OperatingSystem: "LINUX",
Architecture: "ARM64",
}, nil),
m.ecsDescriber.EXPECT().EnvVars().Return([]*ecs.ContainerEnvVar{
{
Name: "COPILOT_ENVIRONMENT_NAME",
Container: "container2",
Value: prodEnv,
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(mockProdParams, nil),
m.ecsDescriber.EXPECT().RollbackAlarmNames().Return([]string{alarm2}, nil),
m.cwDescriber.EXPECT().AlarmDescriptions([]string{alarm2}).Return([]*cloudwatch.AlarmDescription{
{
Name: alarm2,
Description: desc2,
Environment: prodEnv,
},
}, nil),
m.envDescriber.EXPECT().ServiceDiscoveryEndpoint().Return("prod.phonetool.local", nil),
m.ecsDescriber.EXPECT().ServiceConnectDNSNames().
Return([]string{testSvc}, nil),
m.ecsDescriber.EXPECT().Secrets().Return([]*ecs.ContainerSecret{
{
Name: "SOME_OTHER_SECRET",
Container: "container",
ValueFrom: "SHHHHHHHH",
},
}, nil),
m.ecsDescriber.EXPECT().StackResources().Return([]*stack.Resource{
{
Type: "AWS::EC2::SecurityGroupIngress",
PhysicalID: "ContainerSecurityGroupIngressFromPublicALB",
},
}, nil),
m.ecsDescriber.EXPECT().StackResources().Return([]*stack.Resource{
{
Type: "AWS::EC2::SecurityGroup",
PhysicalID: "sg-0758ed6b233743530",
},
}, nil),
)
},
wantedWebSvc: &webSvcDesc{
ecsSvcDesc: ecsSvcDesc{
Service: testSvc,
Type: "Load Balanced Web Service",
App: testApp,
Configurations: []*ECSServiceConfig{
{
ServiceConfig: &ServiceConfig{
CPU: "256",
Environment: "test",
Memory: "512",
Platform: "LINUX/X86_64",
Port: "80",
},
Tasks: "1",
},
{
ServiceConfig: &ServiceConfig{
CPU: "512",
Environment: "prod",
Memory: "1024",
Platform: "LINUX/ARM64",
Port: "5000",
},
Tasks: "2",
},
},
Routes: []*WebServiceRoute{
{
Environment: "test",
URL: "http://abc.us-west-1.elb.amazonaws.com/*",
},
{
Environment: "prod",
URL: "http://abc.us-west-1.elb.amazonaws.com/*",
},
},
AlarmDescriptions: []*cloudwatch.AlarmDescription{
{
Name: alarm1,
Description: desc1,
Environment: testEnv,
},
{
Name: alarm2,
Description: desc2,
Environment: prodEnv,
},
},
ServiceDiscovery: serviceDiscoveries{
"jobs.test.phonetool.local:80": []string{"test"},
"jobs.prod.phonetool.local:5000": []string{"prod"},
},
ServiceConnect: serviceConnects{
testSvc: []string{"test", "prod"},
},
Variables: []*containerEnvVar{
{
envVar: &envVar{
Environment: "test",
Name: "COPILOT_ENVIRONMENT_NAME",
Value: "test",
},
Container: "container1",
},
{
envVar: &envVar{
Environment: "prod",
Name: "COPILOT_ENVIRONMENT_NAME",
Value: "prod",
},
Container: "container2",
},
},
Secrets: []*secret{
{
Name: "GITHUB_WEBHOOK_SECRET",
Container: "container",
Environment: "test",
ValueFrom: "GH_WEBHOOK_SECRET",
},
{
Name: "SOME_OTHER_SECRET",
Container: "container",
Environment: "prod",
ValueFrom: "SHHHHHHHH",
},
},
Resources: map[string][]*stack.Resource{
"test": {
{
Type: "AWS::EC2::SecurityGroupIngress",
PhysicalID: "ContainerSecurityGroupIngressFromPublicALB",
},
},
"prod": {
{
Type: "AWS::EC2::SecurityGroup",
PhysicalID: "sg-0758ed6b233743530",
},
},
},
environments: []string{"test", "prod"},
},
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockStore := mocks.NewMockDeployedEnvServicesLister(ctrl)
mockSvcStackDescriber := mocks.NewMockecsDescriber(ctrl)
mockEnvDescriber := mocks.NewMockenvDescriber(ctrl)
mockCwDescriber := mocks.NewMockcwAlarmDescriber(ctrl)
mocks := lbWebSvcDescriberMocks{
storeSvc: mockStore,
ecsDescriber: mockSvcStackDescriber,
envDescriber: mockEnvDescriber,
cwDescriber: mockCwDescriber,
}
tc.setupMocks(mocks)
d := &LBWebServiceDescriber{
app: testApp,
svc: testSvc,
enableResources: tc.shouldOutputResources,
store: mockStore,
initECSServiceDescribers: func(s string) (ecsDescriber, error) { return mockSvcStackDescriber, nil },
initCWDescriber: func(s string) (cwAlarmDescriber, error) { return mocks.cwDescriber, nil },
initEnvDescribers: func(s string) (envDescriber, error) { return mockEnvDescriber, nil },
}
// WHEN
websvc, err := d.Describe()
// THEN
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedWebSvc, websvc, "expected output content match")
}
})
}
}
func TestLBWebServiceDesc_String(t *testing.T) {
testCases := map[string]struct {
wantedHumanString string
wantedJSONString string
}{
"correct output including env vars and secrets sorted (name, container, env) and double-quotes for ditto": {
wantedHumanString: `About
Application my-app
Name my-svc
Type Load Balanced Web Service
Configurations
Environment Tasks CPU (vCPU) Memory (MiB) Platform Port
----------- ----- ---------- ------------ -------- ----
test 1 0.25 512 LINUX/X86_64 80
prod 3 0.5 1024 LINUX/ARM64 5000
Rollback Alarms
Name Environment Description
---- ----------- -----------
alarmName1 test alarm description 1
alarmName2 prod alarm description 2
Routes
Environment URL
----------- ---
test http://my-pr-Publi.us-west-2.elb.amazonaws.com/frontend
prod http://my-pr-Publi.us-west-2.elb.amazonaws.com/backend
Internal Service Endpoint
Endpoint Environment Type
-------- ----------- ----
my-svc test, prod Service Connect
http://my-svc.prod.my-app.local:5000 prod Service Discovery
http://my-svc.test.my-app.local:5000 test Service Discovery
Variables
Name Container Environment Value
---- --------- ----------- -----
COPILOT_ENVIRONMENT_NAME containerA test test
" containerB prod prod
DIFFERENT_ENV_VAR " " "
Secrets
Name Container Environment Value From
---- --------- ----------- ----------
GITHUB_WEBHOOK_SECRET containerA test parameter/GH_WEBHOOK_SECRET
SOME_OTHER_SECRET containerB prod parameter/SHHHHH
Resources
test
AWS::EC2::SecurityGroup sg-0758ed6b233743530
prod
AWS::EC2::SecurityGroupIngress ContainerSecurityGroupIngressFromPublicALB
`,
wantedJSONString: "{\"service\":\"my-svc\",\"type\":\"Load Balanced Web Service\",\"application\":\"my-app\",\"configurations\":[{\"environment\":\"test\",\"port\":\"80\",\"cpu\":\"256\",\"memory\":\"512\",\"platform\":\"LINUX/X86_64\",\"tasks\":\"1\"},{\"environment\":\"prod\",\"port\":\"5000\",\"cpu\":\"512\",\"memory\":\"1024\",\"platform\":\"LINUX/ARM64\",\"tasks\":\"3\"}],\"rollbackAlarms\":[{\"name\":\"alarmName1\",\"description\":\"alarm description 1\",\"environment\":\"test\"},{\"name\":\"alarmName2\",\"description\":\"alarm description 2\",\"environment\":\"prod\"}],\"routes\":[{\"environment\":\"test\",\"url\":\"http://my-pr-Publi.us-west-2.elb.amazonaws.com/frontend\"},{\"environment\":\"prod\",\"url\":\"http://my-pr-Publi.us-west-2.elb.amazonaws.com/backend\"}],\"serviceDiscovery\":[{\"environment\":[\"prod\"],\"endpoint\":\"http://my-svc.prod.my-app.local:5000\"},{\"environment\":[\"test\"],\"endpoint\":\"http://my-svc.test.my-app.local:5000\"}],\"serviceConnect\":[{\"environment\":[\"test\",\"prod\"],\"endpoint\":\"my-svc\"}],\"variables\":[{\"environment\":\"test\",\"name\":\"COPILOT_ENVIRONMENT_NAME\",\"value\":\"test\",\"container\":\"containerA\"},{\"environment\":\"prod\",\"name\":\"COPILOT_ENVIRONMENT_NAME\",\"value\":\"prod\",\"container\":\"containerB\"},{\"environment\":\"prod\",\"name\":\"DIFFERENT_ENV_VAR\",\"value\":\"prod\",\"container\":\"containerB\"}],\"secrets\":[{\"name\":\"GITHUB_WEBHOOK_SECRET\",\"container\":\"containerA\",\"environment\":\"test\",\"valueFrom\":\"GH_WEBHOOK_SECRET\"},{\"name\":\"SOME_OTHER_SECRET\",\"container\":\"containerB\",\"environment\":\"prod\",\"valueFrom\":\"SHHHHH\"}],\"resources\":{\"prod\":[{\"type\":\"AWS::EC2::SecurityGroupIngress\",\"physicalID\":\"ContainerSecurityGroupIngressFromPublicALB\"}],\"test\":[{\"type\":\"AWS::EC2::SecurityGroup\",\"physicalID\":\"sg-0758ed6b233743530\"}]}}\n",
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
config := []*ECSServiceConfig{
{
ServiceConfig: &ServiceConfig{
CPU: "256",
Environment: "test",
Memory: "512",
Platform: "LINUX/X86_64",
Port: "80",
},
Tasks: "1",
},
{
ServiceConfig: &ServiceConfig{
CPU: "512",
Environment: "prod",
Memory: "1024",
Platform: "LINUX/ARM64",
Port: "5000",
},
Tasks: "3",
},
}
envVars := []*containerEnvVar{
{
envVar: &envVar{
Environment: "prod",
Name: "COPILOT_ENVIRONMENT_NAME",
Value: "prod",
},
Container: "containerB",
},
{
envVar: &envVar{
Environment: "test",
Name: "COPILOT_ENVIRONMENT_NAME",
Value: "test",
},
Container: "containerA",
},
{
envVar: &envVar{
Environment: "prod",
Name: "DIFFERENT_ENV_VAR",
Value: "prod",
},
Container: "containerB",
},
}
alarmDescs := []*cloudwatch.AlarmDescription{
{
Name: "alarmName1",
Description: "alarm description 1",
Environment: "test",
},
{
Name: "alarmName2",
Description: "alarm description 2",
Environment: "prod",
},
}
secrets := []*secret{
{
Name: "GITHUB_WEBHOOK_SECRET",
Container: "containerA",
Environment: "test",
ValueFrom: "GH_WEBHOOK_SECRET",
},
{
Name: "SOME_OTHER_SECRET",
Container: "containerB",
Environment: "prod",
ValueFrom: "SHHHHH",
},
}
routes := []*WebServiceRoute{
{
Environment: "test",
URL: "http://my-pr-Publi.us-west-2.elb.amazonaws.com/frontend",
},
{
Environment: "prod",
URL: "http://my-pr-Publi.us-west-2.elb.amazonaws.com/backend",
},
}
sds := serviceDiscoveries{
"http://my-svc.test.my-app.local:5000": []string{"test"},
"http://my-svc.prod.my-app.local:5000": []string{"prod"},
}
scs := serviceConnects{
"my-svc": []string{"test", "prod"},
}
resources := map[string][]*stack.Resource{
"test": {
{
PhysicalID: "sg-0758ed6b233743530",
Type: "AWS::EC2::SecurityGroup",
},
},
"prod": {
{
Type: "AWS::EC2::SecurityGroupIngress",
PhysicalID: "ContainerSecurityGroupIngressFromPublicALB",
},
},
}
webSvc := &webSvcDesc{
ecsSvcDesc: ecsSvcDesc{
Service: "my-svc",
Type: "Load Balanced Web Service",
Configurations: config,
App: "my-app",
Variables: envVars,
AlarmDescriptions: alarmDescs,
Secrets: secrets,
Routes: routes,
ServiceDiscovery: sds,
ServiceConnect: scs,
Resources: resources,
environments: []string{"test", "prod"},
},
}
human := webSvc.HumanString()
json, _ := webSvc.JSONString()
require.Equal(t, tc.wantedHumanString, human)
require.Equal(t, tc.wantedJSONString, json)
})
}
}
| 867 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package describe
import (
"bytes"
"encoding/json"
"fmt"
"strings"
"text/tabwriter"
"github.com/aws/copilot-cli/internal/pkg/aws/sessions"
"github.com/aws/copilot-cli/internal/pkg/deploy"
"github.com/aws/copilot-cli/internal/pkg/deploy/cloudformation/stack"
describestack "github.com/aws/copilot-cli/internal/pkg/describe/stack"
// TODO refactor this into our own pkg
"github.com/aws/copilot-cli/internal/pkg/aws/codepipeline"
"github.com/aws/copilot-cli/internal/pkg/term/color"
)
type pipelineGetter interface {
GetPipeline(pipelineName string) (*codepipeline.Pipeline, error)
}
// Pipeline contains serialized parameters for a pipeline.
type Pipeline struct {
// Name is the user provided name for a pipeline
Name string `json:"name"`
codepipeline.Pipeline
Resources []*describestack.Resource `json:"resources,omitempty"`
}
// PipelineDescriber retrieves information about a deployed pipeline.
type PipelineDescriber struct {
pipeline deploy.Pipeline
showResources bool
pipelineSvc pipelineGetter
cfn stackDescriber
}
// NewPipelineDescriber instantiates a new pipeline describer
func NewPipelineDescriber(pipeline deploy.Pipeline, showResources bool) (*PipelineDescriber, error) {
sess, err := sessions.ImmutableProvider().Default()
if err != nil {
return nil, err
}
pipelineSvc := codepipeline.New(sess)
return &PipelineDescriber{
pipeline: pipeline,
pipelineSvc: pipelineSvc,
showResources: showResources,
cfn: describestack.NewStackDescriber(stack.NameForPipeline(pipeline.AppName, pipeline.Name, pipeline.IsLegacy), sess),
}, nil
}
// Describe returns description of a pipeline.
func (d *PipelineDescriber) Describe() (HumanJSONStringer, error) {
cp, err := d.pipelineSvc.GetPipeline(d.pipeline.ResourceName)
if err != nil {
return nil, fmt.Errorf("get pipeline: %w", err)
}
var resources []*describestack.Resource
if d.showResources {
stackResources, err := d.cfn.Resources()
if err != nil && !IsStackNotExistsErr(err) {
return nil, fmt.Errorf("retrieve pipeline resources: %w", err)
}
resources = stackResources
}
pipeline := &Pipeline{
Name: d.pipeline.Name,
Pipeline: *cp,
Resources: resources,
}
return pipeline, nil
}
// JSONString returns the stringified Pipeline struct with JSON format.
func (p *Pipeline) JSONString() (string, error) {
b, err := json.Marshal(p)
if err != nil {
return "", fmt.Errorf("marshal pipeline: %w", err)
}
return fmt.Sprintf("%s\n", b), nil
}
// HumanString returns the stringified Pipeline struct with human readable format.
func (p *Pipeline) HumanString() string {
var b bytes.Buffer
// TODO tweak the spacing
writer := tabwriter.NewWriter(&b, minCellWidth, tabWidth, cellPaddingWidth, paddingChar, noAdditionalFormatting)
fmt.Fprint(writer, color.Bold.Sprint("About\n\n"))
writer.Flush()
fmt.Fprintf(writer, " %s\t%s\n", "Name", p.Name)
fmt.Fprintf(writer, " %s\t%s\n", "Region", p.Pipeline.Region)
fmt.Fprintf(writer, " %s\t%s\n", "AccountID", p.Pipeline.AccountID)
fmt.Fprintf(writer, " %s\t%s\n", "Created At", humanizeTime(p.Pipeline.CreatedAt))
fmt.Fprintf(writer, " %s\t%s\n", "Updated At", humanizeTime(p.Pipeline.UpdatedAt))
writer.Flush()
fmt.Fprint(writer, color.Bold.Sprint("\nStages\n\n"))
writer.Flush()
headers := []string{"Name", "Category", "Provider", "Details"}
fmt.Fprintf(writer, " %s\n", strings.Join(headers, "\t"))
fmt.Fprintf(writer, " %s\n", strings.Join(underline(headers), "\t"))
for _, stage := range p.Pipeline.Stages {
fmt.Fprintf(writer, " %s", stage.HumanString())
}
writer.Flush()
if len(p.Resources) != 0 {
fmt.Fprint(writer, color.Bold.Sprint("\nResources\n"))
writer.Flush()
for _, r := range p.Resources {
fmt.Fprintf(writer, " %s", r.HumanString())
}
}
writer.Flush()
return b.String()
}
| 127 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package describe
import (
"errors"
"fmt"
"testing"
"time"
"github.com/aws/copilot-cli/internal/pkg/aws/codepipeline"
"github.com/aws/copilot-cli/internal/pkg/deploy"
"github.com/aws/copilot-cli/internal/pkg/describe/mocks"
"github.com/aws/copilot-cli/internal/pkg/describe/stack"
"github.com/dustin/go-humanize"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
type pipelineDescriberMocks struct {
cfn *mocks.MockstackDescriber
pipelineGetter *mocks.MockpipelineGetter
}
var pipelineResourceName = "pipeline-dinder-badgoose-repo-RANDOMSTRING"
var pipelineName = "pipeline-dinder-badgoose-repo"
var mockTime = func() time.Time {
t, _ := time.Parse(time.RFC3339, "2020-02-02T15:04:05+00:00")
return t
}
var mockPipeline = &codepipeline.Pipeline{
Name: pipelineResourceName,
Region: "us-west-2",
AccountID: "1234567890",
Stages: []*codepipeline.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(),
}
var expectedResources = []*stack.Resource{
{
PhysicalID: "pipeline-dinder-badgoose-repo-BuildProject",
Type: "AWS::CodeBuild::Project",
},
{
PhysicalID: "pipel-Buil-1PEASDDL44ID2",
Type: "AWS::IAM::Policy",
},
{
PhysicalID: "pipeline-dinder-badgoose-repo-BuildProjectRole-A4V6VSG1XIIJ",
Type: "AWS::IAM::Role",
},
{
PhysicalID: "pipeline-dinder-badgoose-repo",
Type: "AWS::CodePipeline::Pipeline",
},
{
PhysicalID: "pipeline-dinder-badgoose-repo-PipelineRole-100SEEQN6CU0F",
Type: "AWS::IAM::Role",
},
{
PhysicalID: "pipel-Pipe-EO4QGE10RJ8F",
Type: "AWS::IAM::Policy",
},
}
func TestPipelineDescriber_Describe(t *testing.T) {
mockResources := []*stack.Resource{
{
PhysicalID: "pipeline-dinder-badgoose-repo-BuildProject",
Type: "AWS::CodeBuild::Project",
},
{
PhysicalID: "pipel-Buil-1PEASDDL44ID2",
Type: "AWS::IAM::Policy",
},
{
PhysicalID: "pipeline-dinder-badgoose-repo-BuildProjectRole-A4V6VSG1XIIJ",
Type: "AWS::IAM::Role",
},
{
PhysicalID: "pipeline-dinder-badgoose-repo",
Type: "AWS::CodePipeline::Pipeline",
},
{
PhysicalID: "pipeline-dinder-badgoose-repo-PipelineRole-100SEEQN6CU0F",
Type: "AWS::IAM::Role",
},
{
PhysicalID: "pipel-Pipe-EO4QGE10RJ8F",
Type: "AWS::IAM::Policy",
},
}
mockError := errors.New("mockError")
testCases := map[string]struct {
callMocks func(m pipelineDescriberMocks)
inShowResource bool
expectedError error
expectedOutput *Pipeline
}{
"happy path with resources": {
callMocks: func(m pipelineDescriberMocks) {
m.pipelineGetter.EXPECT().GetPipeline(pipelineResourceName).Return(mockPipeline, nil)
m.cfn.EXPECT().Resources().Return(mockResources, nil)
},
inShowResource: true,
expectedError: nil,
expectedOutput: &Pipeline{
Name: pipelineName,
Pipeline: *mockPipeline,
Resources: expectedResources,
},
},
"happy path without resources": {
callMocks: func(m pipelineDescriberMocks) {
m.pipelineGetter.EXPECT().GetPipeline(pipelineResourceName).Return(mockPipeline, nil)
},
inShowResource: false,
expectedError: nil,
expectedOutput: &Pipeline{
Name: pipelineName,
Pipeline: *mockPipeline,
Resources: nil,
},
},
"wraps get pipeline error": {
callMocks: func(m pipelineDescriberMocks) {
m.pipelineGetter.EXPECT().GetPipeline(pipelineResourceName).Return(nil, mockError)
},
inShowResource: false,
expectedError: fmt.Errorf("get pipeline: %w", mockError),
expectedOutput: nil,
},
"wraps stack resources error": {
callMocks: func(m pipelineDescriberMocks) {
m.pipelineGetter.EXPECT().GetPipeline(pipelineResourceName).Return(mockPipeline, nil)
m.cfn.EXPECT().Resources().Return(nil, mockError)
},
inShowResource: true,
expectedError: fmt.Errorf("retrieve pipeline resources: %w", mockError),
expectedOutput: nil,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockCFN := mocks.NewMockstackDescriber(ctrl)
mockPipelineGetter := mocks.NewMockpipelineGetter(ctrl)
mocks := pipelineDescriberMocks{
cfn: mockCFN,
pipelineGetter: mockPipelineGetter,
}
tc.callMocks(mocks)
mockDeployedPipeline := deploy.Pipeline{
ResourceName: pipelineResourceName,
Name: pipelineName,
AppName: "mockAppName",
IsLegacy: false,
}
describer := &PipelineDescriber{
pipeline: mockDeployedPipeline,
showResources: tc.inShowResource,
pipelineSvc: mockPipelineGetter,
cfn: mockCFN,
}
// WHEN
pipeline, err := describer.Describe()
// THEN
if tc.expectedError != nil {
require.EqualError(t, err, tc.expectedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.expectedOutput, pipeline, "expected output content match")
}
})
}
}
func TestPipelineDescriber_String(t *testing.T) {
oldHumanize := humanizeTime
humanizeTime = func(then time.Time) string {
now, _ := time.Parse(time.RFC3339, "2020-06-19T00:00:00+00:00")
return humanize.RelTime(then, now, "ago", "from now")
}
defer func() {
humanizeTime = oldHumanize
}()
testCases := map[string]struct {
inPipeline *Pipeline
expectedHumanString string
expectedJSONString string
}{
"correct output with resources": {
inPipeline: &Pipeline{
Name: pipelineName,
Pipeline: *mockPipeline,
Resources: expectedResources,
},
expectedHumanString: `About
Name pipeline-dinder-badgoose-repo
Region us-west-2
AccountID 1234567890
Created At 4 months ago
Updated At 4 months ago
Stages
Name Category Provider Details
---- -------- -------- -------
Source Source GitHub Repository: badgoose/repo
Build Build CodeBuild BuildProject: pipeline-dinder-badgoose-repo-BuildProject
DeployTo-test Deploy CloudFormation StackName: dinder-test-test
Resources
AWS::CodeBuild::Project pipeline-dinder-badgoose-repo-BuildProject
AWS::IAM::Policy pipel-Buil-1PEASDDL44ID2
AWS::IAM::Role pipeline-dinder-badgoose-repo-BuildProjectRole-A4V6VSG1XIIJ
AWS::CodePipeline::Pipeline pipeline-dinder-badgoose-repo
AWS::IAM::Role pipeline-dinder-badgoose-repo-PipelineRole-100SEEQN6CU0F
AWS::IAM::Policy pipel-Pipe-EO4QGE10RJ8F
`,
expectedJSONString: "{\"name\":\"pipeline-dinder-badgoose-repo\",\"pipelineName\":\"pipeline-dinder-badgoose-repo-RANDOMSTRING\",\"region\":\"us-west-2\",\"accountId\":\"1234567890\",\"stages\":[{\"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\":\"2020-02-02T15:04:05Z\",\"updatedAt\":\"2020-02-02T15:04:05Z\",\"resources\":[{\"type\":\"AWS::CodeBuild::Project\",\"physicalID\":\"pipeline-dinder-badgoose-repo-BuildProject\"},{\"type\":\"AWS::IAM::Policy\",\"physicalID\":\"pipel-Buil-1PEASDDL44ID2\"},{\"type\":\"AWS::IAM::Role\",\"physicalID\":\"pipeline-dinder-badgoose-repo-BuildProjectRole-A4V6VSG1XIIJ\"},{\"type\":\"AWS::CodePipeline::Pipeline\",\"physicalID\":\"pipeline-dinder-badgoose-repo\"},{\"type\":\"AWS::IAM::Role\",\"physicalID\":\"pipeline-dinder-badgoose-repo-PipelineRole-100SEEQN6CU0F\"},{\"type\":\"AWS::IAM::Policy\",\"physicalID\":\"pipel-Pipe-EO4QGE10RJ8F\"}]}\n",
},
"correct output without resources": {
inPipeline: &Pipeline{
Name: pipelineName,
Pipeline: *mockPipeline,
Resources: nil,
},
expectedHumanString: `About
Name pipeline-dinder-badgoose-repo
Region us-west-2
AccountID 1234567890
Created At 4 months ago
Updated At 4 months ago
Stages
Name Category Provider Details
---- -------- -------- -------
Source Source GitHub Repository: badgoose/repo
Build Build CodeBuild BuildProject: pipeline-dinder-badgoose-repo-BuildProject
DeployTo-test Deploy CloudFormation StackName: dinder-test-test
`,
expectedJSONString: "{\"name\":\"pipeline-dinder-badgoose-repo\",\"pipelineName\":\"pipeline-dinder-badgoose-repo-RANDOMSTRING\",\"region\":\"us-west-2\",\"accountId\":\"1234567890\",\"stages\":[{\"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\":\"2020-02-02T15:04:05Z\",\"updatedAt\":\"2020-02-02T15:04:05Z\"}\n",
},
}
for _, tc := range testCases {
human := tc.inPipeline.HumanString()
json, _ := tc.inPipeline.JSONString()
require.Equal(t, tc.expectedHumanString, human, "expected human output to match")
require.Equal(t, tc.expectedJSONString, json, "expected JSON output to match")
}
}
| 286 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package describe
import (
"bytes"
"encoding/json"
"fmt"
"strings"
"text/tabwriter"
"github.com/aws/copilot-cli/internal/pkg/aws/codepipeline"
"github.com/aws/copilot-cli/internal/pkg/aws/sessions"
"github.com/aws/copilot-cli/internal/pkg/deploy"
"github.com/aws/copilot-cli/internal/pkg/term/color"
)
type pipelineStateGetter interface {
GetPipelineState(pipelineName string) (*codepipeline.PipelineState, error)
}
// PipelineStatusDescriber retrieves status of a deployed pipeline.
type PipelineStatusDescriber struct {
pipeline deploy.Pipeline
pipelineSvc pipelineStateGetter
}
// PipelineStatus contains the status for a pipeline.
type PipelineStatus struct {
Name string `json:"name"`
codepipeline.PipelineState
}
// NewPipelineStatusDescriber instantiates a new PipelineStatus struct.
func NewPipelineStatusDescriber(pipeline deploy.Pipeline) (*PipelineStatusDescriber, error) {
sess, err := sessions.ImmutableProvider().Default()
if err != nil {
return nil, err
}
pipelineSvc := codepipeline.New(sess)
return &PipelineStatusDescriber{
pipeline: pipeline,
pipelineSvc: pipelineSvc,
}, nil
}
// Describe returns status of a pipeline.
func (d *PipelineStatusDescriber) Describe() (HumanJSONStringer, error) {
ps, err := d.pipelineSvc.GetPipelineState(d.pipeline.ResourceName)
if err != nil {
return nil, fmt.Errorf("get pipeline status: %w", err)
}
pipelineStatus := &PipelineStatus{
Name: d.pipeline.Name,
PipelineState: *ps,
}
return pipelineStatus, nil
}
// JSONString returns stringified PipelineStatus struct with json format.
func (p PipelineStatus) JSONString() (string, error) {
b, err := json.Marshal(p)
if err != nil {
return "", fmt.Errorf("marshal pipeline status: %w", err)
}
return fmt.Sprintf("%s\n", b), nil
}
// HumanString returns stringified PipelineStatus struct with human readable format.
func (p PipelineStatus) HumanString() string {
var b bytes.Buffer
writer := tabwriter.NewWriter(&b, minCellWidth, tabWidth, cellPaddingWidth, paddingChar, noAdditionalFormatting)
fmt.Fprint(writer, color.Bold.Sprint("Pipeline Status\n\n"))
writer.Flush()
headers := []string{"Stage", "Transition", "Status"}
fmt.Fprintf(writer, "%s\n", strings.Join(headers, "\t"))
fmt.Fprintf(writer, "%s\n", strings.Join(underline(headers), "\t"))
for _, stage := range p.StageStates {
fmt.Fprint(writer, stage.HumanString())
}
writer.Flush()
fmt.Fprint(writer, color.Bold.Sprint("\nLast Deployment\n\n"))
fmt.Fprintf(writer, " %s\t%s\n", "Updated At", humanizeTime(p.UpdatedAt))
writer.Flush()
return b.String()
}
| 89 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package describe
import (
"errors"
"fmt"
"testing"
"time"
"github.com/dustin/go-humanize"
"github.com/aws/copilot-cli/internal/pkg/aws/codepipeline"
"github.com/aws/copilot-cli/internal/pkg/deploy"
"github.com/aws/copilot-cli/internal/pkg/describe/mocks"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
type pipelineStatusDescriberMocks struct {
pipelineStateGetter *mocks.MockpipelineStateGetter
}
var mockParsedTime = func() time.Time {
t, _ := time.Parse(time.RFC3339, "2020-02-02T15:04:05+00:00")
return t
}
var mockPipelineState = &codepipeline.PipelineState{
PipelineName: pipelineResourceName,
StageStates: []*codepipeline.StageState{
{
StageName: "Source",
},
{
StageName: "Build",
Actions: []codepipeline.StageAction{
{
Name: "action1",
Status: "Failed",
},
{
Name: "action2",
Status: "InProgress",
},
{
Name: "action3",
Status: "Succeeded",
},
},
Transition: "ENABLED",
},
{
StageName: "DeployTo-test",
Actions: []codepipeline.StageAction{
{
Name: "action1",
Status: "Succeeded",
},
},
Transition: "DISABLED",
},
{
StageName: "DeployTo-prod",
Actions: []codepipeline.StageAction{
{
Name: "action1",
Status: "Succeeded",
},
{
Name: "TestCommands",
Status: "Failed",
},
},
},
},
UpdatedAt: mockParsedTime(),
}
func TestPipelineStatusDescriber_Describe(t *testing.T) {
mockError := errors.New("some error")
testCases := map[string]struct {
setupMocks func(m pipelineStatusDescriberMocks)
expectedError error
expectedOutput *PipelineStatus
}{
"wraps GetPipelineState error": {
setupMocks: func(m pipelineStatusDescriberMocks) {
m.pipelineStateGetter.EXPECT().GetPipelineState(pipelineResourceName).Return(nil, mockError)
},
expectedError: fmt.Errorf("get pipeline status: %w", mockError),
expectedOutput: nil,
},
"success": {
setupMocks: func(m pipelineStatusDescriberMocks) {
m.pipelineStateGetter.EXPECT().GetPipelineState(pipelineResourceName).Return(mockPipelineState, nil)
},
expectedError: nil,
expectedOutput: &PipelineStatus{
Name: pipelineName,
PipelineState: *mockPipelineState,
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockPipelineStateGetter := mocks.NewMockpipelineStateGetter(ctrl)
mocks := pipelineStatusDescriberMocks{
pipelineStateGetter: mockPipelineStateGetter,
}
tc.setupMocks(mocks)
mockDeployedPipeline := deploy.Pipeline{
Name: pipelineName,
ResourceName: pipelineResourceName,
AppName: "mockApp",
IsLegacy: false,
}
describer := &PipelineStatusDescriber{
pipeline: mockDeployedPipeline,
pipelineSvc: mockPipelineStateGetter,
}
// WHEN
pipelineStatus, err := describer.Describe()
// THEN
if tc.expectedError != nil {
require.EqualError(t, err, tc.expectedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.expectedOutput, pipelineStatus, "expected output content match")
}
})
}
}
func TestPipelineStatusDescriber_String(t *testing.T) {
oldHumanize := humanizeTime
humanizeTime = func(then time.Time) string {
now, _ := time.Parse(time.RFC3339, "2020-06-19T00:00:00+00:00")
return humanize.RelTime(then, now, "ago", "from now")
}
defer func() {
humanizeTime = oldHumanize
}()
testCases := map[string]struct {
testPipelineStatus *PipelineStatus
expectedHumanString string
expectedJSONString string
}{
"correct output with correct aggregate statuses": {
testPipelineStatus: &PipelineStatus{
Name: pipelineName,
PipelineState: *mockPipelineState},
expectedHumanString: `Pipeline Status
Stage Transition Status
----- ---------- ------
Source - -
Build ENABLED InProgress
├── action1 Failed
├── action2 InProgress
└── action3 Succeeded
DeployTo-test DISABLED Succeeded
└── action1 Succeeded
DeployTo-prod - Failed
├── action1 Succeeded
└── TestCommands Failed
Last Deployment
Updated At 4 months ago
`,
expectedJSONString: "{\"name\":\"pipeline-dinder-badgoose-repo\",\"pipelineName\":\"pipeline-dinder-badgoose-repo-RANDOMSTRING\",\"stageStates\":[{\"stageName\":\"Source\",\"transition\":\"\"},{\"stageName\":\"Build\",\"actions\":[{\"name\":\"action1\",\"status\":\"Failed\"},{\"name\":\"action2\",\"status\":\"InProgress\"},{\"name\":\"action3\",\"status\":\"Succeeded\"}],\"transition\":\"ENABLED\"},{\"stageName\":\"DeployTo-test\",\"actions\":[{\"name\":\"action1\",\"status\":\"Succeeded\"}],\"transition\":\"DISABLED\"},{\"stageName\":\"DeployTo-prod\",\"actions\":[{\"name\":\"action1\",\"status\":\"Succeeded\"},{\"name\":\"TestCommands\",\"status\":\"Failed\"}],\"transition\":\"\"}],\"updatedAt\":\"2020-02-02T15:04:05Z\"}\n",
},
}
for _, tc := range testCases {
human := tc.testPipelineStatus.HumanString()
json, _ := tc.testPipelineStatus.JSONString()
require.Equal(t, tc.expectedHumanString, human, "expected human output to match")
require.Equal(t, tc.expectedJSONString, json, "expected JSON output to match")
}
}
| 193 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package describe
import (
"bytes"
"encoding/json"
"fmt"
"io"
"strings"
"text/tabwriter"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/copilot-cli/internal/pkg/aws/apprunner"
"github.com/aws/copilot-cli/internal/pkg/describe/stack"
"github.com/aws/copilot-cli/internal/pkg/manifest/manifestinfo"
"github.com/aws/copilot-cli/internal/pkg/term/color"
)
// RDWebServiceDescriber retrieves information about a request-driven web service.
type RDWebServiceDescriber struct {
app string
svc string
enableResources bool
store DeployedEnvServicesLister
initAppRunnerDescriber func(string) (apprunnerDescriber, error)
envSvcDescribers map[string]apprunnerDescriber
}
// NewRDWebServiceDescriber instantiates a request-driven service describer.
func NewRDWebServiceDescriber(opt NewServiceConfig) (*RDWebServiceDescriber, error) {
describer := &RDWebServiceDescriber{
app: opt.App,
svc: opt.Svc,
enableResources: opt.EnableResources,
store: opt.DeployStore,
envSvcDescribers: make(map[string]apprunnerDescriber),
}
describer.initAppRunnerDescriber = func(env string) (apprunnerDescriber, error) {
if describer, ok := describer.envSvcDescribers[env]; ok {
return describer, nil
}
d, err := newAppRunnerServiceDescriber(NewServiceConfig{
App: opt.App,
Svc: opt.Svc,
ConfigStore: opt.ConfigStore,
}, env)
if err != nil {
return nil, err
}
describer.envSvcDescribers[env] = d
return d, nil
}
return describer, nil
}
// ServiceARN retrieves the ARN of the app runner service.
func (d *RDWebServiceDescriber) ServiceARN(env string) (string, error) {
describer, err := d.initAppRunnerDescriber(env)
if err != nil {
return "", err
}
return describer.ServiceARN()
}
// Describe returns info for a request-driven web service.
func (d *RDWebServiceDescriber) Describe() (HumanJSONStringer, error) {
environments, err := d.store.ListEnvironmentsDeployedTo(d.app, d.svc)
if err != nil {
return nil, fmt.Errorf("list deployed environments for application %s: %w", d.app, err)
}
var observabilities []observabilityInEnv
var routes []*RDWSRoute
var configs []*ServiceConfig
var envVars envVars
var secrets []*rdwsSecret
resources := make(map[string][]*stack.Resource)
for _, env := range environments {
describer, err := d.initAppRunnerDescriber(env)
if err != nil {
return nil, err
}
service, err := describer.Service()
if err != nil {
return nil, fmt.Errorf("retrieve service configuration: %w", err)
}
url, err := describer.ServiceURL()
if err != nil {
return nil, fmt.Errorf("retrieve service url: %w", err)
}
private, err := describer.IsPrivate()
if err != nil {
return nil, fmt.Errorf("check if service is private: %w", err)
}
ingress := rdwsIngressInternet
if private {
ingress = rdwsIngressEnvironment
}
routes = append(routes, &RDWSRoute{
Environment: env,
URL: url,
Ingress: ingress,
})
configs = append(configs, &ServiceConfig{
Environment: env,
Port: service.Port,
CPU: service.CPU,
Memory: service.Memory,
})
for _, v := range service.EnvironmentVariables {
envVars = append(envVars, &envVar{
Environment: env,
Name: v.Name,
Value: v.Value,
})
}
for _, v := range service.EnvironmentSecrets {
secrets = append(secrets, &rdwsSecret{
Environment: env,
Name: v.Name,
ValueFrom: v.Value,
})
}
observabilities = append(observabilities, observabilityInEnv{
Environment: env,
Tracing: formatTracingConfiguration(service.Observability.TraceConfiguration),
})
if d.enableResources {
stackResources, err := describer.StackResources()
if err != nil {
return nil, fmt.Errorf("retrieve service resources: %w", err)
}
resources[env] = stackResources
}
}
if !observabilityPerEnv(observabilities).hasObservabilityConfiguration() {
observabilities = nil
}
return &rdWebSvcDesc{
Service: d.svc,
Type: manifestinfo.RequestDrivenWebServiceType,
App: d.app,
AppRunnerConfigurations: configs,
Routes: routes,
Variables: envVars,
Resources: resources,
Observability: observabilities,
Secrets: secrets,
environments: environments,
}, nil
}
// Manifest returns the contents of the manifest used to deploy a request-driven web service stack.
// If the Manifest metadata doesn't exist in the stack template, then returns ErrManifestNotFoundInTemplate.
func (d *RDWebServiceDescriber) Manifest(env string) ([]byte, error) {
cfn, err := d.initAppRunnerDescriber(env)
if err != nil {
return nil, err
}
return cfn.Manifest()
}
func formatTracingConfiguration(configuration *apprunner.TraceConfiguration) *tracing {
if configuration == nil {
return nil
}
return &tracing{
Vendor: aws.StringValue(configuration.Vendor),
}
}
type observabilityPerEnv []observabilityInEnv
func (obs observabilityPerEnv) hasObservabilityConfiguration() bool {
for _, envObservabilityConfig := range obs {
if !envObservabilityConfig.isEmpty() {
return true
}
}
return false
}
func (obs observabilityPerEnv) humanString(w io.Writer) {
headers := []string{"Environment", "Tracing"}
var rows [][]string
for _, ob := range obs {
tracingVendor := "None"
if ob.Tracing != nil && ob.Tracing.Vendor != "" {
tracingVendor = ob.Tracing.Vendor
}
rows = append(rows, []string{ob.Environment, tracingVendor})
}
printTable(w, headers, rows)
}
type observabilityInEnv struct {
Environment string `json:"environment"`
Tracing *tracing `json:"tracing,omitempty"`
}
func (o observabilityInEnv) isEmpty() bool {
return o.Tracing.isEmpty()
}
type tracing struct {
Vendor string `json:"vendor"`
}
func (t *tracing) isEmpty() bool {
return t == nil || t.Vendor == ""
}
type rdwsIngress string
const (
rdwsIngressEnvironment rdwsIngress = "environment"
rdwsIngressInternet rdwsIngress = "internet"
)
// RDWSRoute contains serialized route parameters for a Request-Driven Web Service.
type RDWSRoute struct {
Environment string `json:"environment"`
URL string `json:"url"`
Ingress rdwsIngress `json:"ingress"`
}
// rdWebSvcDesc contains serialized parameters for a web service.
type rdWebSvcDesc struct {
Service string `json:"service"`
Type string `json:"type"`
App string `json:"application"`
AppRunnerConfigurations appRunnerConfigurations `json:"configurations"`
Routes []*RDWSRoute `json:"routes"`
Variables envVars `json:"variables"`
Resources deployedSvcResources `json:"resources,omitempty"`
Observability observabilityPerEnv `json:"observability,omitempty"`
Secrets rdwsSecrets `json:"secrets,omitempty"`
environments []string `json:"-"`
}
// JSONString returns the stringified rdWebSvcDesc struct in json format.
func (w *rdWebSvcDesc) JSONString() (string, error) {
b, err := json.Marshal(w)
if err != nil {
return "", fmt.Errorf("marshal web service description: %w", err)
}
return fmt.Sprintf("%s\n", b), nil
}
// HumanString returns the stringified webService struct in human readable format.
func (w *rdWebSvcDesc) HumanString() string {
var b bytes.Buffer
writer := tabwriter.NewWriter(&b, minCellWidth, tabWidth, cellPaddingWidth, paddingChar, noAdditionalFormatting)
fmt.Fprint(writer, color.Bold.Sprint("About\n\n"))
writer.Flush()
fmt.Fprintf(writer, " %s\t%s\n", "Application", w.App)
fmt.Fprintf(writer, " %s\t%s\n", "Name", w.Service)
fmt.Fprintf(writer, " %s\t%s\n", "Type", w.Type)
fmt.Fprint(writer, color.Bold.Sprint("\nConfigurations\n\n"))
writer.Flush()
w.AppRunnerConfigurations.humanString(writer)
if w.Observability.hasObservabilityConfiguration() {
fmt.Fprint(writer, color.Bold.Sprint("\nObservability\n\n"))
writer.Flush()
w.Observability.humanString(writer)
}
fmt.Fprint(writer, color.Bold.Sprint("\nRoutes\n\n"))
writer.Flush()
headers := []string{"Environment", "Ingress", "URL"}
fmt.Fprintf(writer, " %s\n", strings.Join(headers, "\t"))
fmt.Fprintf(writer, " %s\n", strings.Join(underline(headers), "\t"))
for _, route := range w.Routes {
fmt.Fprintf(writer, " %s\t%s\t%s\n", route.Environment, route.Ingress, route.URL)
}
fmt.Fprint(writer, color.Bold.Sprint("\nVariables\n\n"))
writer.Flush()
w.Variables.humanString(writer)
if len(w.Secrets) != 0 {
fmt.Fprint(writer, color.Bold.Sprint("\nSecrets\n\n"))
writer.Flush()
w.Secrets.humanString(writer)
}
if len(w.Resources) != 0 {
fmt.Fprint(writer, color.Bold.Sprint("\nResources\n"))
writer.Flush()
w.Resources.humanStringByEnv(writer, w.environments)
}
writer.Flush()
return b.String()
}
| 304 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package describe
import (
"errors"
"fmt"
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/copilot-cli/internal/pkg/aws/apprunner"
"github.com/aws/copilot-cli/internal/pkg/describe/mocks"
"github.com/aws/copilot-cli/internal/pkg/describe/stack"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
const humanStringWithResources = `About
Application testapp
Name testsvc
Type Request-Driven Web Service
Configurations
Environment CPU (vCPU) Memory (MiB) Port
----------- ---------- ------------ ----
test 1 2048 80
prod 2 3072 "
Routes
Environment Ingress URL
----------- ------- ---
test environment https://6znxd4ra33.public.us-east-1.apprunner.amazonaws.com
prod internet https://tumkjmvjjf.public.us-east-1.apprunner.amazonaws.com
Variables
Name Environment Value
---- ----------- -----
COPILOT_ENVIRONMENT_NAME prod prod
" test test
Secrets
Name Environment Value
---- ----------- -----
my-ssm-secret prod prod
" test test
Resources
test
AWS::AppRunner::Service arn:aws:apprunner:us-east-1:111111111111:service/testapp-test-testsvc
prod
AWS::AppRunner::Service arn:aws:apprunner:us-east-1:111111111111:service/testapp-prod-testsvc
`
type apprunnerSvcDescriberMocks struct {
storeSvc *mocks.MockDeployedEnvServicesLister
ecsSvcDescriber *mocks.MockapprunnerDescriber
}
func TestRDWebServiceDescriber_Describe(t *testing.T) {
const (
testApp = "testapp"
testSvc = "testsvc"
testEnv = "test"
prodEnv = "prod"
)
mockErr := errors.New("some error")
testCases := map[string]struct {
shouldOutputResources bool
setupMocks func(mocks apprunnerSvcDescriberMocks)
wantedSvcDesc *rdWebSvcDesc
wantedError error
}{
"return error if fail to list environment": {
setupMocks: func(m apprunnerSvcDescriberMocks) {
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return(nil, mockErr),
)
},
wantedError: fmt.Errorf("list deployed environments for application testapp: some error"),
},
"return error if fail to retrieve service configuration": {
setupMocks: func(m apprunnerSvcDescriberMocks) {
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv}, nil),
m.ecsSvcDescriber.EXPECT().Service().Return(nil, mockErr),
)
},
wantedError: fmt.Errorf("retrieve service configuration: some error"),
},
"return error if fail to get service url": {
shouldOutputResources: true,
setupMocks: func(m apprunnerSvcDescriberMocks) {
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv}, nil),
m.ecsSvcDescriber.EXPECT().Service().Return(&apprunner.Service{}, nil),
m.ecsSvcDescriber.EXPECT().ServiceURL().Return("", mockErr),
)
},
wantedError: fmt.Errorf("retrieve service url: some error"),
},
"return error if fail to check if private": {
shouldOutputResources: true,
setupMocks: func(m apprunnerSvcDescriberMocks) {
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv}, nil),
m.ecsSvcDescriber.EXPECT().Service().Return(&apprunner.Service{}, nil),
m.ecsSvcDescriber.EXPECT().ServiceURL().Return("", nil),
m.ecsSvcDescriber.EXPECT().IsPrivate().Return(false, mockErr),
)
},
wantedError: fmt.Errorf("check if service is private: some error"),
},
"return error if fail to retrieve service resources": {
shouldOutputResources: true,
setupMocks: func(m apprunnerSvcDescriberMocks) {
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv}, nil),
m.ecsSvcDescriber.EXPECT().Service().Return(&apprunner.Service{}, nil),
m.ecsSvcDescriber.EXPECT().ServiceURL().Return("", nil),
m.ecsSvcDescriber.EXPECT().IsPrivate().Return(false, nil),
m.ecsSvcDescriber.EXPECT().StackResources().Return(nil, mockErr),
)
},
wantedError: fmt.Errorf("retrieve service resources: some error"),
},
"success": {
shouldOutputResources: true,
setupMocks: func(m apprunnerSvcDescriberMocks) {
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv, prodEnv}, nil),
m.ecsSvcDescriber.EXPECT().Service().Return(&apprunner.Service{
ServiceARN: "arn:aws:apprunner:us-east-1:111111111111:service/testapp-test-testsvc",
ServiceURL: "6znxd4ra33.public.us-east-1.apprunner.amazonaws.com",
CPU: "1024",
Memory: "2048",
Port: "80",
EnvironmentVariables: []*apprunner.EnvironmentVariable{
{
Name: "COPILOT_ENVIRONMENT_NAME",
Value: "test",
},
},
EnvironmentSecrets: []*apprunner.EnvironmentSecret{
{
Name: "SOME_OTHER_SECRET",
Value: "arn:aws:ssm:us-east-1:111111111111:parameter/SHHHHH",
},
},
}, nil),
m.ecsSvcDescriber.EXPECT().ServiceURL().Return("https://6znxd4ra33.public.us-east-1.apprunner.amazonaws.com", nil),
m.ecsSvcDescriber.EXPECT().IsPrivate().Return(true, nil),
m.ecsSvcDescriber.EXPECT().StackResources().Return([]*stack.Resource{
{
Type: "AWS::AppRunner::Service",
PhysicalID: "arn:aws:apprunner:us-east-1:111111111111:service/testapp-test-testsvc",
},
}, nil),
m.ecsSvcDescriber.EXPECT().Service().Return(&apprunner.Service{
ServiceARN: "arn:aws:apprunner:us-east-1:111111111111:service/testapp-prod-testsvc",
ServiceURL: "tumkjmvjjf.public.us-east-1.apprunner.amazonaws.com",
CPU: "2048",
Memory: "3072",
Port: "80",
EnvironmentVariables: []*apprunner.EnvironmentVariable{
{
Name: "COPILOT_ENVIRONMENT_NAME",
Value: "prod",
},
},
EnvironmentSecrets: []*apprunner.EnvironmentSecret{
{
Name: "my-ssm-secret",
Value: "arn:aws:ssm:us-east-1:111111111111:parameter/jan11ssm",
},
},
}, nil),
m.ecsSvcDescriber.EXPECT().ServiceURL().Return("https://tumkjmvjjf.public.us-east-1.apprunner.amazonaws.com", nil),
m.ecsSvcDescriber.EXPECT().IsPrivate().Return(false, nil),
m.ecsSvcDescriber.EXPECT().StackResources().Return([]*stack.Resource{
{
Type: "AWS::AppRunner::Service",
PhysicalID: "arn:aws:apprunner:us-east-1:111111111111:service/testapp-prod-testsvc",
},
}, nil),
)
},
wantedSvcDesc: &rdWebSvcDesc{
Service: testSvc,
Type: "Request-Driven Web Service",
App: testApp,
AppRunnerConfigurations: []*ServiceConfig{
{
CPU: "1024",
Environment: "test",
Memory: "2048",
Port: "80",
},
{
CPU: "2048",
Environment: "prod",
Memory: "3072",
Port: "80",
},
},
Routes: []*RDWSRoute{
{
Environment: "test",
URL: "https://6znxd4ra33.public.us-east-1.apprunner.amazonaws.com",
Ingress: rdwsIngressEnvironment,
},
{
Environment: "prod",
URL: "https://tumkjmvjjf.public.us-east-1.apprunner.amazonaws.com",
Ingress: rdwsIngressInternet,
},
},
Variables: []*envVar{
{
Environment: "test",
Name: "COPILOT_ENVIRONMENT_NAME",
Value: "test",
},
{
Environment: "prod",
Name: "COPILOT_ENVIRONMENT_NAME",
Value: "prod",
},
},
Secrets: []*rdwsSecret{
{
Environment: "test",
Name: "SOME_OTHER_SECRET",
ValueFrom: "arn:aws:ssm:us-east-1:111111111111:parameter/SHHHHH",
},
{
Environment: "prod",
Name: "my-ssm-secret",
ValueFrom: "arn:aws:ssm:us-east-1:111111111111:parameter/jan11ssm",
},
},
Resources: map[string][]*stack.Resource{
"test": {
{
Type: "AWS::AppRunner::Service",
PhysicalID: "arn:aws:apprunner:us-east-1:111111111111:service/testapp-test-testsvc",
},
},
"prod": {
{
Type: "AWS::AppRunner::Service",
PhysicalID: "arn:aws:apprunner:us-east-1:111111111111:service/testapp-prod-testsvc",
},
},
},
environments: []string{"test", "prod"},
},
},
"success with observability": {
shouldOutputResources: true,
setupMocks: func(m apprunnerSvcDescriberMocks) {
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv, prodEnv}, nil),
m.ecsSvcDescriber.EXPECT().Service().Return(&apprunner.Service{
ServiceARN: "arn:aws:apprunner:us-east-1:111111111111:service/testapp-test-testsvc",
ServiceURL: "6znxd4ra33.public.us-east-1.apprunner.amazonaws.com",
CPU: "1024",
Memory: "2048",
Port: "80",
EnvironmentVariables: []*apprunner.EnvironmentVariable{
{
Name: "COPILOT_ENVIRONMENT_NAME",
Value: "test",
},
},
EnvironmentSecrets: []*apprunner.EnvironmentSecret{
{
Name: "SOME_OTHER_SECRET",
Value: "arn:aws:ssm:us-east-1:111111111111:parameter/SHHHHH",
},
},
Observability: apprunner.ObservabilityConfiguration{
TraceConfiguration: &apprunner.TraceConfiguration{
Vendor: aws.String("mockVendor"),
},
},
}, nil),
m.ecsSvcDescriber.EXPECT().ServiceURL().Return("https://6znxd4ra33.public.us-east-1.apprunner.amazonaws.com", nil),
m.ecsSvcDescriber.EXPECT().IsPrivate().Return(true, nil),
m.ecsSvcDescriber.EXPECT().StackResources().Return([]*stack.Resource{
{
Type: "AWS::AppRunner::Service",
PhysicalID: "arn:aws:apprunner:us-east-1:111111111111:service/testapp-test-testsvc",
},
}, nil),
m.ecsSvcDescriber.EXPECT().Service().Return(&apprunner.Service{
ServiceARN: "arn:aws:apprunner:us-east-1:111111111111:service/testapp-prod-testsvc",
ServiceURL: "tumkjmvjjf.public.us-east-1.apprunner.amazonaws.com",
CPU: "2048",
Memory: "3072",
Port: "80",
EnvironmentVariables: []*apprunner.EnvironmentVariable{
{
Name: "COPILOT_ENVIRONMENT_NAME",
Value: "prod",
},
},
EnvironmentSecrets: []*apprunner.EnvironmentSecret{
{
Name: "my-ssm-secret",
Value: "arn:aws:ssm:us-east-1:111111111111:parameter/jan11ssm",
},
},
}, nil),
m.ecsSvcDescriber.EXPECT().ServiceURL().Return("https://tumkjmvjjf.public.us-east-1.apprunner.amazonaws.com", nil),
m.ecsSvcDescriber.EXPECT().IsPrivate().Return(false, nil),
m.ecsSvcDescriber.EXPECT().StackResources().Return([]*stack.Resource{
{
Type: "AWS::AppRunner::Service",
PhysicalID: "arn:aws:apprunner:us-east-1:111111111111:service/testapp-prod-testsvc",
},
}, nil),
)
},
wantedSvcDesc: &rdWebSvcDesc{
Service: testSvc,
Type: "Request-Driven Web Service",
App: testApp,
AppRunnerConfigurations: []*ServiceConfig{
{
CPU: "1024",
Environment: "test",
Memory: "2048",
Port: "80",
},
{
CPU: "2048",
Environment: "prod",
Memory: "3072",
Port: "80",
},
},
Routes: []*RDWSRoute{
{
Environment: "test",
URL: "https://6znxd4ra33.public.us-east-1.apprunner.amazonaws.com",
Ingress: rdwsIngressEnvironment,
},
{
Environment: "prod",
URL: "https://tumkjmvjjf.public.us-east-1.apprunner.amazonaws.com",
Ingress: rdwsIngressInternet,
},
},
Variables: []*envVar{
{
Environment: "test",
Name: "COPILOT_ENVIRONMENT_NAME",
Value: "test",
},
{
Environment: "prod",
Name: "COPILOT_ENVIRONMENT_NAME",
Value: "prod",
},
},
Secrets: []*rdwsSecret{
{
Environment: "test",
Name: "SOME_OTHER_SECRET",
ValueFrom: "arn:aws:ssm:us-east-1:111111111111:parameter/SHHHHH",
},
{
Environment: "prod",
Name: "my-ssm-secret",
ValueFrom: "arn:aws:ssm:us-east-1:111111111111:parameter/jan11ssm",
},
},
Observability: []observabilityInEnv{
{
Environment: "test",
Tracing: &tracing{
Vendor: "mockVendor",
},
},
{
Environment: "prod",
},
},
Resources: map[string][]*stack.Resource{
"test": {
{
Type: "AWS::AppRunner::Service",
PhysicalID: "arn:aws:apprunner:us-east-1:111111111111:service/testapp-test-testsvc",
},
},
"prod": {
{
Type: "AWS::AppRunner::Service",
PhysicalID: "arn:aws:apprunner:us-east-1:111111111111:service/testapp-prod-testsvc",
},
},
},
environments: []string{"test", "prod"},
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockStore := mocks.NewMockDeployedEnvServicesLister(ctrl)
mockSvcDescriber := mocks.NewMockapprunnerDescriber(ctrl)
mocks := apprunnerSvcDescriberMocks{
storeSvc: mockStore,
ecsSvcDescriber: mockSvcDescriber,
}
tc.setupMocks(mocks)
d := &RDWebServiceDescriber{
app: testApp,
svc: testSvc,
enableResources: tc.shouldOutputResources,
store: mockStore,
initAppRunnerDescriber: func(string) (apprunnerDescriber, error) { return mockSvcDescriber, nil },
}
// WHEN
svcDesc, err := d.Describe()
// THEN
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedSvcDesc, svcDesc, "expected output content match")
}
})
}
}
func TestRDWebServiceDesc_String(t *testing.T) {
t.Run("correct output including resources", func(t *testing.T) {
wantedHumanString := humanStringWithResources
wantedJSONString := "{\"service\":\"testsvc\",\"type\":\"Request-Driven Web Service\",\"application\":\"testapp\",\"configurations\":[{\"environment\":\"test\",\"port\":\"80\",\"cpu\":\"1024\",\"memory\":\"2048\"},{\"environment\":\"prod\",\"port\":\"80\",\"cpu\":\"2048\",\"memory\":\"3072\"}],\"routes\":[{\"environment\":\"test\",\"url\":\"https://6znxd4ra33.public.us-east-1.apprunner.amazonaws.com\",\"ingress\":\"environment\"},{\"environment\":\"prod\",\"url\":\"https://tumkjmvjjf.public.us-east-1.apprunner.amazonaws.com\",\"ingress\":\"internet\"}],\"variables\":[{\"environment\":\"prod\",\"name\":\"COPILOT_ENVIRONMENT_NAME\",\"value\":\"prod\"},{\"environment\":\"test\",\"name\":\"COPILOT_ENVIRONMENT_NAME\",\"value\":\"test\"}],\"resources\":{\"prod\":[{\"type\":\"AWS::AppRunner::Service\",\"physicalID\":\"arn:aws:apprunner:us-east-1:111111111111:service/testapp-prod-testsvc\"}],\"test\":[{\"type\":\"AWS::AppRunner::Service\",\"physicalID\":\"arn:aws:apprunner:us-east-1:111111111111:service/testapp-test-testsvc\"}]},\"secrets\":[{\"environment\":\"prod\",\"name\":\"my-ssm-secret\",\"value\":\"prod\"},{\"environment\":\"test\",\"name\":\"my-ssm-secret\",\"value\":\"test\"}]}\n"
svcDesc := &rdWebSvcDesc{
Service: "testsvc",
Type: "Request-Driven Web Service",
App: "testapp",
AppRunnerConfigurations: []*ServiceConfig{
{
CPU: "1024",
Environment: "test",
Memory: "2048",
Port: "80",
},
{
CPU: "2048",
Environment: "prod",
Memory: "3072",
Port: "80",
},
},
Routes: []*RDWSRoute{
{
Environment: "test",
URL: "https://6znxd4ra33.public.us-east-1.apprunner.amazonaws.com",
Ingress: rdwsIngressEnvironment,
},
{
Environment: "prod",
URL: "https://tumkjmvjjf.public.us-east-1.apprunner.amazonaws.com",
Ingress: rdwsIngressInternet,
},
},
Variables: []*envVar{
{
Environment: "test",
Name: "COPILOT_ENVIRONMENT_NAME",
Value: "test",
},
{
Environment: "prod",
Name: "COPILOT_ENVIRONMENT_NAME",
Value: "prod",
},
},
Secrets: []*rdwsSecret{
{
Environment: "prod",
Name: "my-ssm-secret",
ValueFrom: "prod",
},
{
Environment: "test",
Name: "my-ssm-secret",
ValueFrom: "test",
},
},
Resources: map[string][]*stack.Resource{
"test": {
{
Type: "AWS::AppRunner::Service",
PhysicalID: "arn:aws:apprunner:us-east-1:111111111111:service/testapp-test-testsvc",
},
},
"prod": {
{
Type: "AWS::AppRunner::Service",
PhysicalID: "arn:aws:apprunner:us-east-1:111111111111:service/testapp-prod-testsvc",
},
},
},
environments: []string{"test", "prod"},
}
human := svcDesc.HumanString()
json, _ := svcDesc.JSONString()
require.Equal(t, wantedHumanString, human)
require.Equal(t, wantedJSONString, json)
})
t.Run("correct output including resources with observability", func(t *testing.T) {
wantedHumanString := `About
Application testapp
Name testsvc
Type Request-Driven Web Service
Configurations
Environment CPU (vCPU) Memory (MiB) Port
----------- ---------- ------------ ----
test 1 2048 80
prod 2 3072 "
Observability
Environment Tracing
----------- -------
test mockVendor
prod None
Routes
Environment Ingress URL
----------- ------- ---
test environment https://6znxd4ra33.public.us-east-1.apprunner.amazonaws.com
prod internet https://tumkjmvjjf.public.us-east-1.apprunner.amazonaws.com
Variables
Name Environment Value
---- ----------- -----
COPILOT_ENVIRONMENT_NAME prod prod
" test test
Secrets
Name Environment Value
---- ----------- -----
my-ssm-secret prod prod
" test test
Resources
test
AWS::AppRunner::Service arn:aws:apprunner:us-east-1:111111111111:service/testapp-test-testsvc
prod
AWS::AppRunner::Service arn:aws:apprunner:us-east-1:111111111111:service/testapp-prod-testsvc
`
wantedJSONString := "{\"service\":\"testsvc\",\"type\":\"Request-Driven Web Service\",\"application\":\"testapp\",\"configurations\":[{\"environment\":\"test\",\"port\":\"80\",\"cpu\":\"1024\",\"memory\":\"2048\"},{\"environment\":\"prod\",\"port\":\"80\",\"cpu\":\"2048\",\"memory\":\"3072\"}],\"routes\":[{\"environment\":\"test\",\"url\":\"https://6znxd4ra33.public.us-east-1.apprunner.amazonaws.com\",\"ingress\":\"environment\"},{\"environment\":\"prod\",\"url\":\"https://tumkjmvjjf.public.us-east-1.apprunner.amazonaws.com\",\"ingress\":\"internet\"}],\"variables\":[{\"environment\":\"prod\",\"name\":\"COPILOT_ENVIRONMENT_NAME\",\"value\":\"prod\"},{\"environment\":\"test\",\"name\":\"COPILOT_ENVIRONMENT_NAME\",\"value\":\"test\"}],\"resources\":{\"prod\":[{\"type\":\"AWS::AppRunner::Service\",\"physicalID\":\"arn:aws:apprunner:us-east-1:111111111111:service/testapp-prod-testsvc\"}],\"test\":[{\"type\":\"AWS::AppRunner::Service\",\"physicalID\":\"arn:aws:apprunner:us-east-1:111111111111:service/testapp-test-testsvc\"}]},\"observability\":[{\"environment\":\"test\",\"tracing\":{\"vendor\":\"mockVendor\"}},{\"environment\":\"prod\"}],\"secrets\":[{\"environment\":\"prod\",\"name\":\"my-ssm-secret\",\"value\":\"prod\"},{\"environment\":\"test\",\"name\":\"my-ssm-secret\",\"value\":\"test\"}]}\n"
svcDesc := &rdWebSvcDesc{
Service: "testsvc",
Type: "Request-Driven Web Service",
App: "testapp",
AppRunnerConfigurations: []*ServiceConfig{
{
CPU: "1024",
Environment: "test",
Memory: "2048",
Port: "80",
},
{
CPU: "2048",
Environment: "prod",
Memory: "3072",
Port: "80",
},
},
Routes: []*RDWSRoute{
{
Environment: "test",
URL: "https://6znxd4ra33.public.us-east-1.apprunner.amazonaws.com",
Ingress: rdwsIngressEnvironment,
},
{
Environment: "prod",
URL: "https://tumkjmvjjf.public.us-east-1.apprunner.amazonaws.com",
Ingress: rdwsIngressInternet,
},
},
Variables: []*envVar{
{
Environment: "test",
Name: "COPILOT_ENVIRONMENT_NAME",
Value: "test",
},
{
Environment: "prod",
Name: "COPILOT_ENVIRONMENT_NAME",
Value: "prod",
},
},
Secrets: []*rdwsSecret{
{
Environment: "prod",
Name: "my-ssm-secret",
ValueFrom: "prod",
},
{
Environment: "test",
Name: "my-ssm-secret",
ValueFrom: "test",
},
},
Observability: []observabilityInEnv{
{
Environment: "test",
Tracing: &tracing{
Vendor: "mockVendor",
},
},
{
Environment: "prod",
},
},
Resources: map[string][]*stack.Resource{
"test": {
{
Type: "AWS::AppRunner::Service",
PhysicalID: "arn:aws:apprunner:us-east-1:111111111111:service/testapp-test-testsvc",
},
},
"prod": {
{
Type: "AWS::AppRunner::Service",
PhysicalID: "arn:aws:apprunner:us-east-1:111111111111:service/testapp-prod-testsvc",
},
},
},
environments: []string{"test", "prod"},
}
human := svcDesc.HumanString()
json, _ := svcDesc.JSONString()
require.Equal(t, wantedHumanString, human)
require.Equal(t, wantedJSONString, json)
})
}
| 674 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package describe
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/url"
"sort"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/arn"
"github.com/aws/copilot-cli/internal/pkg/aws/apprunner"
"github.com/aws/copilot-cli/internal/pkg/aws/cloudwatch"
awsecs "github.com/aws/copilot-cli/internal/pkg/aws/ecs"
"github.com/aws/copilot-cli/internal/pkg/config"
"github.com/aws/copilot-cli/internal/pkg/describe/stack"
"github.com/aws/copilot-cli/internal/pkg/ecs"
)
const (
// Ignored resources
rulePriorityFunction = "Custom::RulePriorityFunction"
waitCondition = "AWS::CloudFormation::WaitCondition"
waitConditionHandle = "AWS::CloudFormation::WaitConditionHandle"
)
const (
apprunnerServiceType = "AWS::AppRunner::Service"
apprunnerVPCIngressConnectionType = "AWS::AppRunner::VpcIngressConnection"
)
const maxAlarmShowColumnWidth = 40
// ConfigStoreSvc wraps methods of config store.
type ConfigStoreSvc interface {
GetEnvironment(appName string, environmentName string) (*config.Environment, error)
ListEnvironments(appName string) ([]*config.Environment, error)
ListServices(appName string) ([]*config.Workload, error)
GetWorkload(appName string, name string) (*config.Workload, error)
ListJobs(appName string) ([]*config.Workload, error)
}
// DeployedEnvServicesLister wraps methods of deploy store.
type DeployedEnvServicesLister interface {
ListEnvironmentsDeployedTo(appName string, svcName string) ([]string, error)
ListDeployedServices(appName string, envName string) ([]string, error)
ListDeployedJobs(appName string, envName string) ([]string, error)
}
type ecsClient interface {
TaskDefinition(app, env, svc string) (*awsecs.TaskDefinition, error)
Service(app, env, svc string) (*awsecs.Service, error)
}
type apprunnerClient interface {
DescribeService(svcARN string) (*apprunner.Service, error)
PrivateURL(vicARN string) (string, error)
}
type workloadDescriber interface {
Params() (map[string]string, error)
Outputs() (map[string]string, error)
StackResources() ([]*stack.Resource, error)
Manifest() ([]byte, error)
}
type ecsDescriber interface {
workloadDescriber
ServiceConnectDNSNames() ([]string, error)
Platform() (*awsecs.ContainerPlatform, error)
EnvVars() ([]*awsecs.ContainerEnvVar, error)
Secrets() ([]*awsecs.ContainerSecret, error)
RollbackAlarmNames() ([]string, error)
}
type apprunnerDescriber interface {
workloadDescriber
Service() (*apprunner.Service, error)
ServiceARN() (string, error)
ServiceURL() (string, error)
IsPrivate() (bool, error)
}
type cwAlarmDescriber interface {
AlarmDescriptions([]string) ([]*cloudwatch.AlarmDescription, error)
}
type bucketDescriber interface {
BucketTree(bucket string) (string, error)
}
type bucketDataGetter interface {
BucketSizeAndCount(bucket string) (string, int, error)
}
type bucketNameGetter interface {
BucketName(app, env, svc string) (string, error)
}
type ecsSvcDesc struct {
Service string `json:"service"`
Type string `json:"type"`
App string `json:"application"`
Configurations ecsConfigurations `json:"configurations"`
AlarmDescriptions []*cloudwatch.AlarmDescription `json:"rollbackAlarms,omitempty"`
Routes []*WebServiceRoute `json:"routes"`
ServiceDiscovery serviceDiscoveries `json:"serviceDiscovery"`
ServiceConnect serviceConnects `json:"serviceConnect,omitempty"`
Variables containerEnvVars `json:"variables"`
Secrets secrets `json:"secrets,omitempty"`
Resources deployedSvcResources `json:"resources,omitempty"`
environments []string `json:"-"`
}
type ecsServiceDescriber struct {
*workloadStackDescriber
ecsClient ecsClient
}
type appRunnerServiceDescriber struct {
*workloadStackDescriber
apprunnerClient apprunnerClient
}
// NewServiceConfig contains fields that initiates service describer struct.
type NewServiceConfig struct {
App string
Svc string
ConfigStore ConfigStoreSvc
EnableResources bool
DeployStore DeployedEnvServicesLister
}
func newECSServiceDescriber(opt NewServiceConfig, env string) (*ecsServiceDescriber, error) {
stackDescriber, err := newWorkloadStackDescriber(workloadConfig{
app: opt.App,
name: opt.Svc,
configStore: opt.ConfigStore,
}, env)
if err != nil {
return nil, err
}
return &ecsServiceDescriber{
workloadStackDescriber: stackDescriber,
ecsClient: ecs.New(stackDescriber.sess),
}, nil
}
func newAppRunnerServiceDescriber(opt NewServiceConfig, env string) (*appRunnerServiceDescriber, error) {
stackDescriber, err := newWorkloadStackDescriber(workloadConfig{
app: opt.App,
name: opt.Svc,
configStore: opt.ConfigStore,
}, env)
if err != nil {
return nil, err
}
return &appRunnerServiceDescriber{
workloadStackDescriber: stackDescriber,
apprunnerClient: apprunner.New(stackDescriber.sess),
}, nil
}
// EnvVars returns the environment variables of the task definition.
func (d *ecsServiceDescriber) EnvVars() ([]*awsecs.ContainerEnvVar, error) {
taskDefinition, err := d.ecsClient.TaskDefinition(d.app, d.env, d.name)
if err != nil {
return nil, fmt.Errorf("describe task definition for service %s: %w", d.name, err)
}
return taskDefinition.EnvironmentVariables(), nil
}
// Secrets returns the secrets of the task definition.
func (d *ecsServiceDescriber) Secrets() ([]*awsecs.ContainerSecret, error) {
taskDefinition, err := d.ecsClient.TaskDefinition(d.app, d.env, d.name)
if err != nil {
return nil, fmt.Errorf("describe task definition for service %s: %w", d.name, err)
}
return taskDefinition.Secrets(), nil
}
// Platform returns the platform of the task definition.
func (d *ecsServiceDescriber) Platform() (*awsecs.ContainerPlatform, error) {
taskDefinition, err := d.ecsClient.TaskDefinition(d.app, d.env, d.name)
if err != nil {
return nil, fmt.Errorf("describe task definition for service %s: %w", d.name, err)
}
platform := taskDefinition.Platform()
if platform == nil {
return &awsecs.ContainerPlatform{
OperatingSystem: "LINUX",
Architecture: "X86_64",
}, nil
}
return platform, nil
}
// ServiceConnectDNSNames returns the service connect dns names of a service.
func (d *ecsServiceDescriber) ServiceConnectDNSNames() ([]string, error) {
service, err := d.ecsClient.Service(d.app, d.env, d.name)
if err != nil {
return nil, fmt.Errorf("get service %s: %w", d.name, err)
}
return service.ServiceConnectAliases(), nil
}
// RollbackAlarmNames returns the rollback alarm names of a service.
func (d *ecsServiceDescriber) RollbackAlarmNames() ([]string, error) {
service, err := d.ecsClient.Service(d.app, d.env, d.name)
if err != nil {
return nil, fmt.Errorf("get service %s: %w", d.name, err)
}
if service.DeploymentConfiguration.Alarms == nil {
return nil, nil
}
return aws.StringValueSlice(service.DeploymentConfiguration.Alarms.AlarmNames), nil
}
// ServiceARN retrieves the ARN of the app runner service.
func (d *appRunnerServiceDescriber) ServiceARN() (string, error) {
StackResources, err := d.StackResources()
if err != nil {
return "", err
}
for _, resource := range StackResources {
arn := resource.PhysicalID
if resource.Type == apprunnerServiceType && arn != "" {
return arn, nil
}
}
return "", fmt.Errorf("no App Runner Service in service stack")
}
// vpcIngressConnectionARN returns the ARN of the VPC Ingress Connection
// for this service. If one does not exist, it returns errVPCIngressConnectionNotFound.
func (d *appRunnerServiceDescriber) vpcIngressConnectionARN() (string, error) {
StackResources, err := d.StackResources()
if err != nil {
return "", err
}
for _, resource := range StackResources {
arn := resource.PhysicalID
if resource.Type == apprunnerVPCIngressConnectionType && arn != "" {
return arn, nil
}
}
return "", errVPCIngressConnectionNotFound
}
// Service retrieves an app runner service.
func (d *appRunnerServiceDescriber) Service() (*apprunner.Service, error) {
serviceARN, err := d.ServiceARN()
if err != nil {
return nil, err
}
service, err := d.apprunnerClient.DescribeService(serviceARN)
if err != nil {
return nil, fmt.Errorf("describe service: %w", err)
}
return service, nil
}
// IsPrivate returns true if the service is configured as non-public.
func (d *appRunnerServiceDescriber) IsPrivate() (bool, error) {
_, err := d.vpcIngressConnectionARN()
if err != nil {
if errors.Is(err, errVPCIngressConnectionNotFound) {
return false, nil
}
return false, err
}
return true, nil
}
// ServiceURL retrieves the app runner service URL.
func (d *appRunnerServiceDescriber) ServiceURL() (string, error) {
vicARN, err := d.vpcIngressConnectionARN()
isVICNotFound := errors.Is(err, errVPCIngressConnectionNotFound)
if err != nil && !isVICNotFound {
return "", err
}
if !isVICNotFound {
url, err := d.apprunnerClient.PrivateURL(vicARN)
if err != nil {
return "", err
}
return formatAppRunnerURL(url), nil
}
service, err := d.Service()
if err != nil {
return "", err
}
return formatAppRunnerURL(service.ServiceURL), nil
}
func formatAppRunnerURL(serviceURL string) string {
svcUrl := &url.URL{
Host: serviceURL,
// App Runner defaults to https
Scheme: "https",
}
return svcUrl.String()
}
// ServiceConfig contains serialized configuration parameters for a service.
type ServiceConfig struct {
Environment string `json:"environment"`
Port string `json:"port"`
CPU string `json:"cpu"`
Memory string `json:"memory"`
Platform string `json:"platform,omitempty"`
}
// ECSServiceConfig contains info about how an ECS-based service is configured.
type ECSServiceConfig struct {
*ServiceConfig
Tasks string `json:"tasks"`
}
type appRunnerConfigurations []*ServiceConfig
type ecsConfigurations []*ECSServiceConfig
func (c ecsConfigurations) humanString(w io.Writer) {
headers := []string{"Environment", "Tasks", "CPU (vCPU)", "Memory (MiB)", "Platform", "Port"}
var rows [][]string
for _, config := range c {
rows = append(rows, []string{config.Environment, config.Tasks, cpuToString(config.CPU), config.Memory, config.Platform, config.Port})
}
printTable(w, headers, rows)
}
func (c appRunnerConfigurations) humanString(w io.Writer) {
headers := []string{"Environment", "CPU (vCPU)", "Memory (MiB)", "Port"}
var rows [][]string
for _, config := range c {
rows = append(rows, []string{config.Environment, cpuToString(config.CPU), config.Memory, config.Port})
}
printTable(w, headers, rows)
}
type rollbackAlarms []*cloudwatch.AlarmDescription
func (abr rollbackAlarms) humanString(w io.Writer) {
headers := []string{"Name", "Environment", "Description"}
fmt.Fprintf(w, " %s\n", strings.Join(headers, "\t"))
fmt.Fprintf(w, " %s\n", strings.Join(underline(headers), "\t"))
for _, alarm := range abr {
printWithMaxWidth(w, " %s\t%s\t%s\n", maxAlarmShowColumnWidth, alarm.Name, alarm.Environment, alarm.Description)
}
}
// envVar contains serialized environment variables for a service.
type envVar struct {
Environment string `json:"environment"`
Name string `json:"name"`
Value string `json:"value"`
}
type envVars []*envVar
func (e envVars) humanString(w io.Writer) {
headers := []string{"Name", "Environment", "Value"}
var rows [][]string
sort.SliceStable(e, func(i, j int) bool { return e[i].Environment < e[j].Environment })
sort.SliceStable(e, func(i, j int) bool { return e[i].Name < e[j].Name })
for _, v := range e {
rows = append(rows, []string{v.Name, v.Environment, v.Value})
}
printTable(w, headers, rows)
}
type containerEnvVar struct {
*envVar
Container string `json:"container"`
}
type containerEnvVars []*containerEnvVar
func (e containerEnvVars) humanString(w io.Writer) {
headers := []string{"Name", "Container", "Environment", "Value"}
var rows [][]string
sort.SliceStable(e, func(i, j int) bool { return e[i].Environment < e[j].Environment })
sort.SliceStable(e, func(i, j int) bool { return e[i].Container < e[j].Container })
sort.SliceStable(e, func(i, j int) bool { return e[i].Name < e[j].Name })
for _, v := range e {
rows = append(rows, []string{v.Name, v.Container, v.Environment, v.Value})
}
printTable(w, headers, rows)
}
// rdwsSecret contains secrets for an rdws service.
type rdwsSecret struct {
Environment string `json:"environment"`
Name string `json:"name"`
ValueFrom string `json:"value"`
}
type rdwsSecrets []*rdwsSecret
func (e rdwsSecrets) humanString(w io.Writer) {
headers := []string{"Name", "Environment", "Value"}
var rows [][]string
sort.SliceStable(e, func(i, j int) bool {
if e[i].Name == e[j].Name {
return e[i].Environment < e[j].Environment
}
return e[i].Name < e[j].Name
})
for _, v := range e {
rows = append(rows, []string{v.Name, v.Environment, v.ValueFrom})
}
printTable(w, headers, rows)
}
type secret struct {
Name string `json:"name"`
Container string `json:"container"`
Environment string `json:"environment"`
ValueFrom string `json:"valueFrom"`
}
type secrets []*secret
func (s secrets) humanString(w io.Writer) {
headers := []string{"Name", "Container", "Environment", "Value From"}
fmt.Fprintf(w, " %s\n", strings.Join(headers, "\t"))
fmt.Fprintf(w, " %s\n", strings.Join(underline(headers), "\t"))
sort.SliceStable(s, func(i, j int) bool { return s[i].Environment < s[j].Environment })
sort.SliceStable(s, func(i, j int) bool { return s[i].Container < s[j].Container })
sort.SliceStable(s, func(i, j int) bool { return s[i].Name < s[j].Name })
if len(s) > 0 {
valueFrom := s[0].ValueFrom
if _, err := arn.Parse(s[0].ValueFrom); err != nil {
// If the valueFrom is not an ARN, preface it with "parameter/"
valueFrom = fmt.Sprintf("parameter/%s", s[0].ValueFrom)
}
fmt.Fprintf(w, " %s\n", strings.Join([]string{s[0].Name, s[0].Container, s[0].Environment, valueFrom}, "\t"))
}
for prev, cur := 0, 1; cur < len(s); prev, cur = prev+1, cur+1 {
valueFrom := s[cur].ValueFrom
if _, err := arn.Parse(s[cur].ValueFrom); err != nil {
// If the valueFrom is not an ARN, preface it with "parameter/"
valueFrom = fmt.Sprintf("parameter/%s", s[cur].ValueFrom)
}
cols := []string{s[cur].Name, s[cur].Container, s[cur].Environment, valueFrom}
if s[prev].Name == s[cur].Name {
cols[0] = dittoSymbol
}
if s[prev].Container == s[cur].Container {
cols[1] = dittoSymbol
}
if s[prev].Environment == s[cur].Environment {
cols[2] = dittoSymbol
}
if s[prev].ValueFrom == s[cur].ValueFrom {
cols[3] = dittoSymbol
}
fmt.Fprintf(w, " %s\n", strings.Join(cols, "\t"))
}
}
func underline(headings []string) []string {
var lines []string
for _, heading := range headings {
line := strings.Repeat("-", len(heading))
lines = append(lines, line)
}
return lines
}
// endpointToEnvs is a mapping of endpoint to environments.
type endpointToEnvs map[string][]string
func (e *endpointToEnvs) marshalJSON() ([]byte, error) {
type internalEndpoint struct {
Environment []string `json:"environment"`
Endpoint string `json:"endpoint"`
}
var internalEndpoints []internalEndpoint
for endpoint := range *e {
internalEndpoints = append(internalEndpoints, internalEndpoint{
Environment: (*e)[endpoint],
Endpoint: endpoint,
})
}
sort.Slice(internalEndpoints, func(i, j int) bool { return internalEndpoints[i].Endpoint < internalEndpoints[j].Endpoint })
return json.Marshal(&internalEndpoints)
}
func (e endpointToEnvs) add(endpoint string, env string) {
e[endpoint] = append(e[endpoint], env)
}
type serviceDiscoveries endpointToEnvs
// MarshalJSON overrides the default JSON marshaling logic for the serviceDiscoveries
// struct, allowing it to perform more complex marshaling behavior.
func (sds *serviceDiscoveries) MarshalJSON() ([]byte, error) {
return (*endpointToEnvs)(sds).marshalJSON()
}
func (sds *serviceDiscoveries) collectEndpoints(descr envDescriber, svc, env, port string) error {
endpoint, err := descr.ServiceDiscoveryEndpoint()
if err != nil {
return err
}
sd := serviceDiscovery{
Service: svc,
Port: port,
Endpoint: endpoint,
}
(*endpointToEnvs)(sds).add(sd.String(), env)
return nil
}
type serviceConnects endpointToEnvs
// MarshalJSON overrides the default JSON marshaling logic for the serviceConnects
// struct, allowing it to perform more complex marshaling behavior.
func (scs *serviceConnects) MarshalJSON() ([]byte, error) {
return (*endpointToEnvs)(scs).marshalJSON()
}
func (scs *serviceConnects) collectEndpoints(descr ecsDescriber, env string) error {
scDNSNames, err := descr.ServiceConnectDNSNames()
if err != nil {
return fmt.Errorf("retrieve service connect DNS names: %w", err)
}
for _, dnsName := range scDNSNames {
(*endpointToEnvs)(scs).add(dnsName, env)
}
return nil
}
type serviceEndpoints struct {
discoveries serviceDiscoveries
connects serviceConnects
}
func (s serviceEndpoints) humanString(w io.Writer) {
headers := []string{"Endpoint", "Environment", "Type"}
fmt.Fprintf(w, " %s\n", strings.Join(headers, "\t"))
fmt.Fprintf(w, " %s\n", strings.Join(underline(headers), "\t"))
var scEndpoints []string
for endpoint := range s.connects {
scEndpoints = append(scEndpoints, endpoint)
}
sort.Slice(scEndpoints, func(i, j int) bool { return scEndpoints[i] < scEndpoints[j] })
for _, endpoint := range scEndpoints {
fmt.Fprintf(w, " %s\t%s\t%s\n", endpoint, strings.Join(s.connects[endpoint], ", "), "Service Connect")
}
var sdEndpoints []string
for endpoint := range s.discoveries {
sdEndpoints = append(sdEndpoints, endpoint)
}
sort.Slice(sdEndpoints, func(i, j int) bool { return sdEndpoints[i] < sdEndpoints[j] })
for _, endpoint := range sdEndpoints {
fmt.Fprintf(w, " %s\t%s\t%s\n", endpoint, strings.Join(s.discoveries[endpoint], ", "), "Service Discovery")
}
}
| 589 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package describe
import (
"errors"
"fmt"
"testing"
ecsapi "github.com/aws/aws-sdk-go/service/ecs"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/copilot-cli/internal/pkg/aws/apprunner"
"github.com/aws/copilot-cli/internal/pkg/aws/ecs"
awsecs "github.com/aws/copilot-cli/internal/pkg/aws/ecs"
"github.com/aws/copilot-cli/internal/pkg/describe/mocks"
"github.com/aws/copilot-cli/internal/pkg/describe/stack"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
type ecsSvcDescriberMocks struct {
mockCFN *mocks.MockstackDescriber
mockECSClient *mocks.MockecsClient
}
func TestECSServiceDescriber_EnvVars(t *testing.T) {
const (
testApp = "phonetool"
testSvc = "svc"
testEnv = "test"
)
testCases := map[string]struct {
setupMocks func(mocks ecsSvcDescriberMocks)
wantedEnvVars []*awsecs.ContainerEnvVar
wantedError error
}{
"returns error if fails to get task definition": {
setupMocks: func(m ecsSvcDescriberMocks) {
m.mockECSClient.EXPECT().TaskDefinition(testApp, testEnv, testSvc).Return(nil, errors.New("some error"))
},
wantedError: errors.New("describe task definition for service svc: some error"),
},
"get environment variables": {
setupMocks: func(m ecsSvcDescriberMocks) {
gomock.InOrder(
m.mockECSClient.EXPECT().TaskDefinition(testApp, testEnv, testSvc).Return(&ecs.TaskDefinition{
ContainerDefinitions: []*ecsapi.ContainerDefinition{
{
Name: aws.String("container"),
Environment: []*ecsapi.KeyValuePair{
{
Name: aws.String("COPILOT_SERVICE_NAME"),
Value: aws.String("my-svc"),
},
{
Name: aws.String("COPILOT_ENVIRONMENT_NAME"),
Value: aws.String("prod"),
},
},
},
},
}, nil),
)
},
wantedEnvVars: []*ecs.ContainerEnvVar{
{
Name: "COPILOT_SERVICE_NAME",
Container: "container",
Value: "my-svc",
},
{
Name: "COPILOT_ENVIRONMENT_NAME",
Container: "container",
Value: "prod",
},
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockecsClient := mocks.NewMockecsClient(ctrl)
mockCFN := mocks.NewMockstackDescriber(ctrl)
mocks := ecsSvcDescriberMocks{
mockECSClient: mockecsClient,
}
tc.setupMocks(mocks)
d := &ecsServiceDescriber{
workloadStackDescriber: &workloadStackDescriber{
app: testApp,
name: testSvc,
env: testEnv,
cfn: mockCFN,
},
ecsClient: mockecsClient,
}
// WHEN
actual, err := d.EnvVars()
// THEN
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedEnvVars, actual)
}
})
}
}
func TestECSServiceDescriber_RollbackAlarmNames(t *testing.T) {
const (
testApp = "phonetool"
testSvc = "svc"
testEnv = "test"
)
testCases := map[string]struct {
setupMocks func(mocks ecsSvcDescriberMocks)
wantedAlarmNames []string
wantedError error
}{
"returns error if fails to get service": {
setupMocks: func(m ecsSvcDescriberMocks) {
m.mockECSClient.EXPECT().Service(testApp, testEnv, testSvc).Return(&awsecs.Service{
DeploymentConfiguration: &ecsapi.DeploymentConfiguration{
Alarms: nil,
},
}, errors.New("some error"))
},
wantedError: errors.New("get service svc: some error"),
},
"returns nil if no alarms in the svc config": {
setupMocks: func(m ecsSvcDescriberMocks) {
gomock.InOrder(
m.mockECSClient.EXPECT().Service(testApp, testEnv, testSvc).Return(&awsecs.Service{
DeploymentConfiguration: &ecsapi.DeploymentConfiguration{
Alarms: nil,
},
}, nil),
)
},
},
"successfully returns alarm names": {
setupMocks: func(m ecsSvcDescriberMocks) {
gomock.InOrder(
m.mockECSClient.EXPECT().Service(testApp, testEnv, testSvc).Return(&awsecs.Service{
DeploymentConfiguration: &ecsapi.DeploymentConfiguration{
Alarms: &ecsapi.DeploymentAlarms{
AlarmNames: []*string{aws.String("alarm1"), aws.String("alarm2")},
Enable: aws.Bool(true),
Rollback: aws.Bool(true),
},
},
}, nil),
)
},
wantedAlarmNames: []string{"alarm1", "alarm2"},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockecsClient := mocks.NewMockecsClient(ctrl)
mocks := ecsSvcDescriberMocks{
mockECSClient: mockecsClient,
}
tc.setupMocks(mocks)
d := &ecsServiceDescriber{
workloadStackDescriber: &workloadStackDescriber{
app: testApp,
name: testSvc,
env: testEnv,
},
ecsClient: mockecsClient,
}
// WHEN
actual, err := d.RollbackAlarmNames()
// THEN
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedAlarmNames, actual)
}
})
}
}
func TestECSServiceDescriber_ServiceConnectDNSNames(t *testing.T) {
const (
testApp = "phonetool"
testSvc = "svc"
testEnv = "test"
)
testCases := map[string]struct {
setupMocks func(mocks ecsSvcDescriberMocks)
wantedDNSNames []string
wantedError error
}{
"returns error if fails to get ECS service": {
setupMocks: func(m ecsSvcDescriberMocks) {
m.mockECSClient.EXPECT().Service(testApp, testEnv, testSvc).Return(nil, errors.New("some error"))
},
wantedError: errors.New("get service svc: some error"),
},
"success": {
setupMocks: func(m ecsSvcDescriberMocks) {
m.mockECSClient.EXPECT().Service(testApp, testEnv, testSvc).Return(&awsecs.Service{
Deployments: []*ecsapi.Deployment{
{
ServiceConnectConfiguration: &ecsapi.ServiceConnectConfiguration{
Enabled: aws.Bool(true),
Namespace: aws.String("foobar.com"),
Services: []*ecsapi.ServiceConnectService{
{
PortName: aws.String("frontend"),
},
},
},
},
},
}, nil)
},
wantedDNSNames: []string{"frontend.foobar.com"},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockecsClient := mocks.NewMockecsClient(ctrl)
mocks := ecsSvcDescriberMocks{
mockECSClient: mockecsClient,
}
tc.setupMocks(mocks)
d := &ecsServiceDescriber{
workloadStackDescriber: &workloadStackDescriber{
app: testApp,
name: testSvc,
env: testEnv,
},
ecsClient: mockecsClient,
}
// WHEN
actual, err := d.ServiceConnectDNSNames()
// THEN
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
require.ElementsMatch(t, tc.wantedDNSNames, actual)
}
})
}
}
func TestECSServiceDescriber_Secrets(t *testing.T) {
const (
testApp = "phonetool"
testSvc = "svc"
testEnv = "test"
)
testCases := map[string]struct {
setupMocks func(mocks ecsSvcDescriberMocks)
wantedSecrets []*awsecs.ContainerSecret
wantedError error
}{
"returns error if fails to get task definition": {
setupMocks: func(m ecsSvcDescriberMocks) {
gomock.InOrder(
m.mockECSClient.EXPECT().TaskDefinition(testApp, testEnv, testSvc).Return(nil, errors.New("some error")),
)
},
wantedError: fmt.Errorf("describe task definition for service svc: some error"),
},
"successfully gets secrets": {
setupMocks: func(m ecsSvcDescriberMocks) {
gomock.InOrder(
m.mockECSClient.EXPECT().TaskDefinition(testApp, testEnv, testSvc).Return(&ecs.TaskDefinition{
ContainerDefinitions: []*ecsapi.ContainerDefinition{
{
Name: aws.String("container"),
Secrets: []*ecsapi.Secret{
{
Name: aws.String("GITHUB_WEBHOOK_SECRET"),
ValueFrom: aws.String("GH_WEBHOOK_SECRET"),
},
{
Name: aws.String("SOME_OTHER_SECRET"),
ValueFrom: aws.String("SHHHHHHHH"),
},
},
},
},
}, nil),
)
},
wantedSecrets: []*ecs.ContainerSecret{
{
Name: "GITHUB_WEBHOOK_SECRET",
Container: "container",
ValueFrom: "GH_WEBHOOK_SECRET",
},
{
Name: "SOME_OTHER_SECRET",
Container: "container",
ValueFrom: "SHHHHHHHH",
},
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockecsClient := mocks.NewMockecsClient(ctrl)
mocks := ecsSvcDescriberMocks{
mockECSClient: mockecsClient,
}
tc.setupMocks(mocks)
d := &ecsServiceDescriber{
workloadStackDescriber: &workloadStackDescriber{
app: testApp,
name: testSvc,
env: testEnv,
},
ecsClient: mockecsClient,
}
// WHEN
actual, err := d.Secrets()
// THEN
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedSecrets, actual)
}
})
}
}
func TestECSServiceDescriber_Platform(t *testing.T) {
const (
testApp = "phonetool"
testSvc = "svc"
testEnv = "test"
)
testCases := map[string]struct {
setupMocks func(mocks ecsSvcDescriberMocks)
wantedPlatform *awsecs.ContainerPlatform
wantedError error
}{
"returns error if fails to get task definition": {
setupMocks: func(m ecsSvcDescriberMocks) {
gomock.InOrder(
m.mockECSClient.EXPECT().TaskDefinition(testApp, testEnv, testSvc).Return(nil, errors.New("some error")),
)
},
wantedError: fmt.Errorf("describe task definition for service svc: some error"),
},
"successfully returns platform that's returned from api call": {
setupMocks: func(m ecsSvcDescriberMocks) {
gomock.InOrder(
m.mockECSClient.EXPECT().TaskDefinition(testApp, testEnv, testSvc).Return(&ecs.TaskDefinition{
RuntimePlatform: &ecsapi.RuntimePlatform{
CpuArchitecture: aws.String("ARM64"),
OperatingSystemFamily: aws.String("LINUX"),
},
}, nil))
},
wantedPlatform: &awsecs.ContainerPlatform{
OperatingSystem: "LINUX",
Architecture: "ARM64",
},
},
"successfully returns default platform when none returned from api call": {
setupMocks: func(m ecsSvcDescriberMocks) {
gomock.InOrder(
m.mockECSClient.EXPECT().TaskDefinition(testApp, testEnv, testSvc).Return(&ecs.TaskDefinition{}, nil))
},
wantedPlatform: &awsecs.ContainerPlatform{
OperatingSystem: "LINUX",
Architecture: "X86_64",
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockecsClient := mocks.NewMockecsClient(ctrl)
mocks := ecsSvcDescriberMocks{
mockECSClient: mockecsClient,
}
tc.setupMocks(mocks)
d := &ecsServiceDescriber{
workloadStackDescriber: &workloadStackDescriber{
app: testApp,
name: testSvc,
env: testEnv,
},
ecsClient: mockecsClient,
}
// WHEN
actual, err := d.Platform()
// THEN
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedPlatform, actual)
}
})
}
}
type apprunnerMocks struct {
apprunnerClient *mocks.MockapprunnerClient
stackDescriber *mocks.MockstackDescriber
}
func TestAppRunnerServiceDescriber_ServiceURL(t *testing.T) {
mockErr := errors.New("some error")
mockVICARN := "mockVICARN"
mockServiceARN := "mockServiceARN"
tests := map[string]struct {
setupMocks func(m apprunnerMocks)
expected string
expectedErr string
}{
"get ingress connection error": {
setupMocks: func(m apprunnerMocks) {
m.stackDescriber.EXPECT().Resources().Return(nil, mockErr)
},
expectedErr: "some error",
},
"get private url error": {
setupMocks: func(m apprunnerMocks) {
m.stackDescriber.EXPECT().Resources().Return([]*stack.Resource{
{
Type: apprunnerVPCIngressConnectionType,
PhysicalID: mockVICARN,
},
}, nil)
m.apprunnerClient.EXPECT().PrivateURL(mockVICARN).Return("", mockErr)
},
expectedErr: "some error",
},
"private service, success": {
setupMocks: func(m apprunnerMocks) {
m.stackDescriber.EXPECT().Resources().Return([]*stack.Resource{
{
Type: apprunnerVPCIngressConnectionType,
PhysicalID: mockVICARN,
},
}, nil)
m.apprunnerClient.EXPECT().PrivateURL(mockVICARN).Return("example.com", nil)
},
expected: "https://example.com",
},
"public service, resources fails": {
setupMocks: func(m apprunnerMocks) {
m.stackDescriber.EXPECT().Resources().Return(nil, nil)
m.stackDescriber.EXPECT().Resources().Return(nil, mockErr)
},
expectedErr: "some error",
},
"public service, no app runner resource": {
setupMocks: func(m apprunnerMocks) {
m.stackDescriber.EXPECT().Resources().Return([]*stack.Resource{
{
Type: "random",
PhysicalID: "random",
},
}, nil)
},
expectedErr: "no App Runner Service in service stack",
},
"public service, describe service fails": {
setupMocks: func(m apprunnerMocks) {
m.stackDescriber.EXPECT().Resources().Return([]*stack.Resource{
{
Type: apprunnerServiceType,
PhysicalID: mockServiceARN,
},
}, nil)
m.apprunnerClient.EXPECT().DescribeService(mockServiceARN).Return(nil, mockErr)
},
expectedErr: "describe service: some error",
},
"public service, success": {
setupMocks: func(m apprunnerMocks) {
m.stackDescriber.EXPECT().Resources().Return([]*stack.Resource{
{
Type: apprunnerServiceType,
PhysicalID: mockServiceARN,
},
}, nil)
m.apprunnerClient.EXPECT().DescribeService(mockServiceARN).Return(&apprunner.Service{
ServiceURL: "example.com",
}, nil)
},
expected: "https://example.com",
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := apprunnerMocks{
apprunnerClient: mocks.NewMockapprunnerClient(ctrl),
stackDescriber: mocks.NewMockstackDescriber(ctrl),
}
tc.setupMocks(m)
d := &appRunnerServiceDescriber{
workloadStackDescriber: &workloadStackDescriber{
cfn: m.stackDescriber,
},
apprunnerClient: m.apprunnerClient,
}
url, err := d.ServiceURL()
if tc.expectedErr != "" {
require.EqualError(t, err, tc.expectedErr)
} else {
require.NoError(t, err)
require.Equal(t, tc.expected, url)
}
})
}
}
func TestAppRunnerServiceDescriber_IsPrivate(t *testing.T) {
mockErr := errors.New("some error")
tests := map[string]struct {
setupMocks func(m apprunnerMocks)
expected bool
expectedErr string
}{
"get resources error": {
setupMocks: func(m apprunnerMocks) {
m.stackDescriber.EXPECT().Resources().Return(nil, mockErr)
},
expectedErr: "some error",
},
"is not private": {
setupMocks: func(m apprunnerMocks) {
m.stackDescriber.EXPECT().Resources().Return(nil, nil)
},
expected: false,
},
"is private": {
setupMocks: func(m apprunnerMocks) {
m.stackDescriber.EXPECT().Resources().Return([]*stack.Resource{
{
Type: apprunnerVPCIngressConnectionType,
PhysicalID: "arn",
},
}, nil)
},
expected: true,
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := apprunnerMocks{
stackDescriber: mocks.NewMockstackDescriber(ctrl),
}
tc.setupMocks(m)
d := &appRunnerServiceDescriber{
workloadStackDescriber: &workloadStackDescriber{
cfn: m.stackDescriber,
},
}
isPrivate, err := d.IsPrivate()
if tc.expectedErr != "" {
require.EqualError(t, err, tc.expectedErr)
} else {
require.NoError(t, err)
require.Equal(t, tc.expected, isPrivate)
}
})
}
}
| 644 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package describe
import (
"bytes"
"encoding/json"
"fmt"
awsS3 "github.com/aws/copilot-cli/internal/pkg/aws/s3"
"github.com/aws/copilot-cli/internal/pkg/aws/sessions"
s3 "github.com/aws/copilot-cli/internal/pkg/s3"
"strings"
"text/tabwriter"
"github.com/aws/copilot-cli/internal/pkg/describe/stack"
"github.com/aws/copilot-cli/internal/pkg/manifest/manifestinfo"
"github.com/aws/copilot-cli/internal/pkg/term/color"
"github.com/dustin/go-humanize/english"
)
const (
staticSiteOutputCFDomainName = "CloudFrontDistributionDomainName"
staticSiteOutputCFAltDomainName = "CloudFrontDistributionAlternativeDomainName"
)
// StaticSiteDescriber retrieves information about a static site service.
type StaticSiteDescriber struct {
app string
svc string
enableResources bool
store DeployedEnvServicesLister
initWkldStackDescriber func(string) (workloadDescriber, error)
wkldDescribers map[string]workloadDescriber
initS3Client func(string) (bucketDescriber, bucketNameGetter, error)
}
// NewStaticSiteDescriber instantiates a static site service describer.
func NewStaticSiteDescriber(opt NewServiceConfig) (*StaticSiteDescriber, error) {
describer := &StaticSiteDescriber{
app: opt.App,
svc: opt.Svc,
enableResources: opt.EnableResources,
store: opt.DeployStore,
wkldDescribers: make(map[string]workloadDescriber),
}
describer.initWkldStackDescriber = func(env string) (workloadDescriber, error) {
if describer, ok := describer.wkldDescribers[env]; ok {
return describer, nil
}
svcDescr, err := newWorkloadStackDescriber(workloadConfig{
app: opt.App,
name: opt.Svc,
configStore: opt.ConfigStore,
}, env)
if err != nil {
return nil, err
}
describer.wkldDescribers[env] = svcDescr
return svcDescr, nil
}
describer.initS3Client = func(env string) (bucketDescriber, bucketNameGetter, error) {
environment, err := opt.ConfigStore.GetEnvironment(opt.App, env)
if err != nil {
return nil, nil, fmt.Errorf("get environment %s: %w", env, err)
}
sess, err := sessions.ImmutableProvider().FromRole(environment.ManagerRoleARN, environment.Region)
if err != nil {
return nil, nil, err
}
return awsS3.New(sess), s3.New(sess), nil
}
return describer, nil
}
// URI returns the public accessible URI of a static site service.
func (d *StaticSiteDescriber) URI(envName string) (URI, error) {
wkldDescr, err := d.initWkldStackDescriber(envName)
if err != nil {
return URI{}, err
}
outputs, err := wkldDescr.Outputs()
if err != nil {
return URI{}, fmt.Errorf("get stack output for service %q: %w", d.svc, err)
}
uri := accessURI{
HTTPS: true,
DNSNames: []string{outputs[staticSiteOutputCFDomainName]},
}
if outputs[staticSiteOutputCFAltDomainName] != "" {
uri.DNSNames = append(uri.DNSNames, outputs[staticSiteOutputCFAltDomainName])
}
return URI{
URI: english.OxfordWordSeries(uri.strings(), "or"),
AccessType: URIAccessTypeInternet,
}, nil
}
// Describe returns info of a static site.
func (d *StaticSiteDescriber) Describe() (HumanJSONStringer, error) {
environments, err := d.store.ListEnvironmentsDeployedTo(d.app, d.svc)
if err != nil {
return nil, fmt.Errorf("list deployed environments for service %q: %w", d.svc, err)
}
var routes []*WebServiceRoute
var objects []*S3ObjectTree
for _, env := range environments {
bucketDescriber, bucketNameDescriber, err := d.initS3Client(env)
if err != nil {
return nil, err
}
uri, err := d.URI(env)
if err != nil {
return nil, fmt.Errorf("retrieve service URI: %w", err)
}
if uri.AccessType == URIAccessTypeInternet {
routes = append(routes, &WebServiceRoute{
Environment: env,
URL: uri.URI,
})
}
bucketName, err := bucketNameDescriber.BucketName(d.app, env, d.svc)
if err != nil {
return nil, fmt.Errorf("get bucket name for %q env: %w", env, err)
}
tree, err := bucketDescriber.BucketTree(bucketName)
if err != nil {
return nil, fmt.Errorf("get tree representation of bucket contents: %w", err)
}
if tree != "" {
objects = append(objects, &S3ObjectTree{
Environment: env,
Tree: tree,
})
}
}
resources := make(map[string][]*stack.Resource)
if d.enableResources {
for _, env := range environments {
svcDescr, err := d.initWkldStackDescriber(env)
if err != nil {
return nil, err
}
stackResources, err := svcDescr.StackResources()
if err != nil {
return nil, fmt.Errorf("retrieve service resources: %w", err)
}
resources[env] = stackResources
}
}
return &staticSiteDesc{
Service: d.svc,
Type: manifestinfo.StaticSiteType,
App: d.app,
Routes: routes,
Resources: resources,
Objects: objects,
environments: environments,
}, nil
}
// Manifest returns the contents of the manifest used to deploy a static site stack.
// If the Manifest metadata doesn't exist in the stack template, then returns ErrManifestNotFoundInTemplate.
func (d *StaticSiteDescriber) Manifest(env string) ([]byte, error) {
cfn, err := d.initWkldStackDescriber(env)
if err != nil {
return nil, err
}
return cfn.Manifest()
}
// S3ObjectTree contains serialized parameters for an S3 object tree.
type S3ObjectTree struct {
Environment string
Tree string
}
// staticSiteDesc contains serialized parameters for a static site.
type staticSiteDesc struct {
Service string `json:"service"`
Type string `json:"type"`
App string `json:"application"`
Routes []*WebServiceRoute `json:"routes"`
Objects []*S3ObjectTree `json:"objects,omitempty"`
Resources deployedSvcResources `json:"resources,omitempty"`
environments []string `json:"-"`
}
// JSONString returns the stringified backendService struct with json format.
func (w *staticSiteDesc) JSONString() (string, error) {
b, err := json.Marshal(w)
if err != nil {
return "", fmt.Errorf("marshal static site description: %w", err)
}
return fmt.Sprintf("%s\n", b), nil
}
// HumanString returns the stringified backendService struct with human readable format.
func (w *staticSiteDesc) HumanString() string {
var b bytes.Buffer
writer := tabwriter.NewWriter(&b, minCellWidth, tabWidth, cellPaddingWidth, paddingChar, noAdditionalFormatting)
fmt.Fprint(writer, color.Bold.Sprint("About\n\n"))
writer.Flush()
fmt.Fprintf(writer, " %s\t%s\n", "Application", w.App)
fmt.Fprintf(writer, " %s\t%s\n", "Name", w.Service)
fmt.Fprintf(writer, " %s\t%s\n", "Type", w.Type)
if len(w.Routes) > 0 {
fmt.Fprint(writer, color.Bold.Sprint("\nRoutes\n\n"))
writer.Flush()
headers := []string{"Environment", "URL"}
fmt.Fprintf(writer, " %s\n", strings.Join(headers, "\t"))
fmt.Fprintf(writer, " %s\n", strings.Join(underline(headers), "\t"))
for _, route := range w.Routes {
fmt.Fprintf(writer, " %s\t%s\n", route.Environment, route.URL)
}
}
if len(w.Objects) != 0 {
fmt.Fprint(writer, color.Bold.Sprint("\nS3 Bucket Objects\n"))
writer.Flush()
for _, object := range w.Objects {
fmt.Fprintf(writer, "\n %s\t%s\n", "Environment", object.Environment)
fmt.Fprintf(writer, object.Tree)
}
writer.Flush()
}
if len(w.Resources) != 0 {
fmt.Fprint(writer, color.Bold.Sprint("\nResources\n"))
writer.Flush()
w.Resources.humanStringByEnv(writer, w.environments)
}
writer.Flush()
return b.String()
}
| 239 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package describe
import (
"errors"
"fmt"
"testing"
"github.com/aws/copilot-cli/internal/pkg/describe/mocks"
"github.com/aws/copilot-cli/internal/pkg/describe/stack"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
type staticSiteDescriberMocks struct {
wkldDescriber *mocks.MockworkloadDescriber
store *mocks.MockDeployedEnvServicesLister
awsS3Client *mocks.MockbucketDescriber
s3Client *mocks.MockbucketNameGetter
}
func TestStaticSiteDescriber_URI(t *testing.T) {
const (
mockApp = "phonetool"
mockEnv = "test"
mockSvc = "static"
)
mockErr := errors.New("some error")
testCases := map[string]struct {
setupMocks func(mocks staticSiteDescriberMocks)
wantedURI URI
wantedError error
}{
"return error if fail to get stack output": {
setupMocks: func(m staticSiteDescriberMocks) {
gomock.InOrder(
m.wkldDescriber.EXPECT().Outputs().Return(nil, mockErr),
)
},
wantedError: fmt.Errorf(`get stack output for service "static": some error`),
},
"success without alt domain name": {
setupMocks: func(m staticSiteDescriberMocks) {
gomock.InOrder(
m.wkldDescriber.EXPECT().Outputs().Return(map[string]string{
"CloudFrontDistributionDomainName": "dut843shvcmvn.cloudfront.net",
}, nil),
)
},
wantedURI: URI{
URI: "https://dut843shvcmvn.cloudfront.net/",
AccessType: URIAccessTypeInternet,
},
},
"success": {
setupMocks: func(m staticSiteDescriberMocks) {
gomock.InOrder(
m.wkldDescriber.EXPECT().Outputs().Return(map[string]string{
"CloudFrontDistributionDomainName": "dut843shvcmvn.cloudfront.net",
"CloudFrontDistributionAlternativeDomainName": "example.com",
}, nil),
)
},
wantedURI: URI{
URI: "https://dut843shvcmvn.cloudfront.net/ or https://example.com/",
AccessType: URIAccessTypeInternet,
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mocks := staticSiteDescriberMocks{
wkldDescriber: mocks.NewMockworkloadDescriber(ctrl),
}
tc.setupMocks(mocks)
d := &StaticSiteDescriber{
app: mockApp,
svc: mockSvc,
initWkldStackDescriber: func(string) (workloadDescriber, error) { return mocks.wkldDescriber, nil },
wkldDescribers: make(map[string]workloadDescriber),
}
// WHEN
gotURI, err := d.URI(mockEnv)
// THEN
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedURI, gotURI)
}
})
}
}
func TestStaticSiteDescriber_Describe(t *testing.T) {
const (
mockApp = "phonetool"
mockEnv = "test"
mockSvc = "static"
)
mockErr := errors.New("some error")
mockBucket := "bucketName"
testCases := map[string]struct {
shouldOutputResources bool
setupMocks func(mocks staticSiteDescriberMocks)
wantedHuman string
wantedJSON string
wantedError error
}{
"return error if fail to list environments": {
setupMocks: func(m staticSiteDescriberMocks) {
gomock.InOrder(
m.store.EXPECT().ListEnvironmentsDeployedTo(mockApp, mockSvc).Return(nil, mockErr),
)
},
wantedError: fmt.Errorf(`list deployed environments for service "static": some error`),
},
"success without resources flag or objects in bucket": {
setupMocks: func(m staticSiteDescriberMocks) {
gomock.InOrder(
m.store.EXPECT().ListEnvironmentsDeployedTo(mockApp, mockSvc).Return([]string{"test"}, nil),
m.wkldDescriber.EXPECT().Outputs().Return(map[string]string{
"CloudFrontDistributionDomainName": "dut843shvcmvn.cloudfront.net",
}, nil),
m.s3Client.EXPECT().BucketName(mockApp, mockEnv, mockSvc).Return(mockBucket, nil),
m.awsS3Client.EXPECT().BucketTree(mockBucket).Return("", nil),
)
},
wantedHuman: `About
Application phonetool
Name static
Type Static Site
Routes
Environment URL
----------- ---
test https://dut843shvcmvn.cloudfront.net/
`,
wantedJSON: "{\"service\":\"static\",\"type\":\"Static Site\",\"application\":\"phonetool\",\"routes\":[{\"environment\":\"test\",\"url\":\"https://dut843shvcmvn.cloudfront.net/\"}]}\n",
},
"return an error if failed to get stack resources": {
shouldOutputResources: true,
setupMocks: func(m staticSiteDescriberMocks) {
gomock.InOrder(
m.store.EXPECT().ListEnvironmentsDeployedTo(mockApp, mockSvc).Return([]string{"test"}, nil),
m.wkldDescriber.EXPECT().Outputs().Return(map[string]string{
"CloudFrontDistributionDomainName": "dut843shvcmvn.cloudfront.net",
}, nil),
m.s3Client.EXPECT().BucketName(mockApp, mockEnv, mockSvc).Return(mockBucket, nil),
m.awsS3Client.EXPECT().BucketTree(mockBucket).Return("", nil),
m.wkldDescriber.EXPECT().StackResources().Return(nil, mockErr),
)
},
wantedError: fmt.Errorf("retrieve service resources: some error"),
},
"success with resources flag and objects in bucket": {
shouldOutputResources: true,
setupMocks: func(m staticSiteDescriberMocks) {
gomock.InOrder(
m.store.EXPECT().ListEnvironmentsDeployedTo(mockApp, mockSvc).Return([]string{"test"}, nil),
m.wkldDescriber.EXPECT().Outputs().Return(map[string]string{
"CloudFrontDistributionDomainName": "dut843shvcmvn.cloudfront.net",
}, nil),
m.s3Client.EXPECT().BucketName(mockApp, mockEnv, mockSvc).Return(mockBucket, nil),
m.awsS3Client.EXPECT().BucketTree(mockBucket).Return(`.
├── README.md
├── error.html
├── index.html
├── Images
│ ├── firstImage.PNG
│ └── secondImage.PNG
├── css
│ ├── Style.css
│ └── bootstrap.min.css
└── top
└── middle
└── bottom.html
`, nil),
m.wkldDescriber.EXPECT().StackResources().Return([]*stack.Resource{
{
Type: "AWS::S3::Bucket",
PhysicalID: "demo-test-mystatic-bucket-h69vu7y72ga9",
LogicalID: "Bucket",
},
{
Type: "AWS::S3::BucketPolicy",
PhysicalID: "demo-test-mystatic-BucketPolicyForCloudFront-8AITX9Q7K13R",
LogicalID: "BucketPolicy",
},
}, nil),
)
},
wantedHuman: `About
Application phonetool
Name static
Type Static Site
Routes
Environment URL
----------- ---
test https://dut843shvcmvn.cloudfront.net/
S3 Bucket Objects
Environment test
.
├── README.md
├── error.html
├── index.html
├── Images
│ ├── firstImage.PNG
│ └── secondImage.PNG
├── css
│ ├── Style.css
│ └── bootstrap.min.css
└── top
└── middle
└── bottom.html
Resources
test
AWS::S3::Bucket demo-test-mystatic-bucket-h69vu7y72ga9
AWS::S3::BucketPolicy demo-test-mystatic-BucketPolicyForCloudFront-8AITX9Q7K13R
`,
wantedJSON: "{\"service\":\"static\",\"type\":\"Static Site\",\"application\":\"phonetool\",\"routes\":[{\"environment\":\"test\",\"url\":\"https://dut843shvcmvn.cloudfront.net/\"}],\"objects\":[{\"Environment\":\"test\",\"Tree\":\".\\n├── README.md\\n├── error.html\\n├── index.html\\n├── Images\\n│ ├── firstImage.PNG\\n│ └── secondImage.PNG\\n├── css\\n│ ├── Style.css\\n│ └── bootstrap.min.css\\n└── top\\n └── middle\\n └── bottom.html\\n\"}],\"resources\":{\"test\":[{\"type\":\"AWS::S3::Bucket\",\"physicalID\":\"demo-test-mystatic-bucket-h69vu7y72ga9\",\"logicalID\":\"Bucket\"},{\"type\":\"AWS::S3::BucketPolicy\",\"physicalID\":\"demo-test-mystatic-BucketPolicyForCloudFront-8AITX9Q7K13R\",\"logicalID\":\"BucketPolicy\"}]}}\n",
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mocks := staticSiteDescriberMocks{
store: mocks.NewMockDeployedEnvServicesLister(ctrl),
wkldDescriber: mocks.NewMockworkloadDescriber(ctrl),
awsS3Client: mocks.NewMockbucketDescriber(ctrl),
s3Client: mocks.NewMockbucketNameGetter(ctrl),
}
tc.setupMocks(mocks)
d := &StaticSiteDescriber{
app: mockApp,
svc: mockSvc,
enableResources: tc.shouldOutputResources,
store: mocks.store,
initWkldStackDescriber: func(string) (workloadDescriber, error) { return mocks.wkldDescriber, nil },
wkldDescribers: make(map[string]workloadDescriber),
initS3Client: func(string) (bucketDescriber, bucketNameGetter, error) { return mocks.awsS3Client, mocks.s3Client, nil },
}
// WHEN
got, err := d.Describe()
// THEN
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedHuman, got.HumanString())
gotJSON, _ := got.JSONString()
require.Equal(t, tc.wantedJSON, gotJSON)
}
})
}
}
| 284 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package describe
import (
"bytes"
"encoding/json"
"fmt"
"io"
"math"
"strconv"
"strings"
"text/tabwriter"
"time"
"github.com/aws/copilot-cli/internal/pkg/term/progress/summarybar"
"github.com/aws/copilot-cli/internal/pkg/aws/apprunner"
"github.com/aws/copilot-cli/internal/pkg/aws/cloudwatch"
"github.com/aws/copilot-cli/internal/pkg/aws/cloudwatchlogs"
awsecs "github.com/aws/copilot-cli/internal/pkg/aws/ecs"
"github.com/aws/copilot-cli/internal/pkg/aws/elbv2"
"github.com/aws/copilot-cli/internal/pkg/term/color"
fcolor "github.com/fatih/color"
)
const (
maxAlarmStatusColumnWidth = 30
defaultServiceLogsLimit = 10
shortTaskIDLength = 8
summaryBarWidth = 10
emptyRep = "â–‘"
)
var (
summaryBarWidthConfig = summarybar.WithWidth(summaryBarWidth)
summaryBarEmptyRepConfig = summarybar.WithEmptyRep(emptyRep)
)
// ecsServiceStatus contains the status for an ECS service.
type ecsServiceStatus struct {
Service awsecs.ServiceStatus
DesiredRunningTasks []awsecs.TaskStatus `json:"tasks"`
Alarms []cloudwatch.AlarmStatus `json:"alarms"`
StoppedTasks []awsecs.TaskStatus `json:"stoppedTasks"`
TargetHealthDescriptions []taskTargetHealth `json:"targetHealthDescriptions"`
}
// appRunnerServiceStatus contains the status for an App Runner service.
type appRunnerServiceStatus struct {
Service apprunner.Service
LogEvents []*cloudwatchlogs.Event
}
// staticSiteServiceStatus contains the status for a Static Site service.
type staticSiteServiceStatus struct {
BucketName string `json:"bucketName"`
Size string `json:"totalSize"`
Count int `json:"totalObjects"`
}
type taskTargetHealth struct {
HealthStatus elbv2.HealthStatus `json:"healthStatus"`
TaskID string `json:"taskID"` // TaskID is empty if the target cannot be traced to a task.
TargetGroupARN string `json:"targetGroup"`
}
// JSONString returns the stringified ecsServiceStatus struct with json format.
func (s *ecsServiceStatus) JSONString() (string, error) {
b, err := json.Marshal(s)
if err != nil {
return "", fmt.Errorf("marshal services: %w", err)
}
return fmt.Sprintf("%s\n", b), nil
}
// JSONString returns the stringified appRunnerServiceStatus struct with json format.
func (a *appRunnerServiceStatus) JSONString() (string, error) {
data := struct {
ARN string `json:"arn"`
Status string `json:"status"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
Source struct {
ImageID string `json:"imageId"`
} `json:"source"`
}{
ARN: a.Service.ServiceARN,
Status: a.Service.Status,
CreatedAt: a.Service.DateCreated,
UpdatedAt: a.Service.DateUpdated,
Source: struct {
ImageID string `json:"imageId"`
}{
ImageID: a.Service.ImageID,
},
}
b, err := json.Marshal(data)
if err != nil {
return "", fmt.Errorf("marshal services: %w", err)
}
return fmt.Sprintf("%s\n", b), nil
}
// JSONString returns the stringified staticSiteServiceStatus struct with json format.
func (s *staticSiteServiceStatus) JSONString() (string, error) {
b, err := json.Marshal(s)
if err != nil {
return "", fmt.Errorf("marshal services: %w", err)
}
return fmt.Sprintf("%s\n", b), nil
}
// HumanString returns the stringified ecsServiceStatus struct in human-readable format.
func (s *ecsServiceStatus) HumanString() string {
var b bytes.Buffer
writer := tabwriter.NewWriter(&b, statusMinCellWidth, tabWidth, statusCellPaddingWidth, paddingChar, noAdditionalFormatting)
fmt.Fprint(writer, color.Bold.Sprint("Task Summary\n\n"))
writer.Flush()
s.writeTaskSummary(writer)
writer.Flush()
if len(s.StoppedTasks) > 0 {
fmt.Fprint(writer, color.Bold.Sprint("\nStopped Tasks\n\n"))
writer.Flush()
s.writeStoppedTasks(writer)
writer.Flush()
}
if len(s.DesiredRunningTasks) > 0 {
fmt.Fprint(writer, color.Bold.Sprint("\nTasks\n\n"))
writer.Flush()
s.writeRunningTasks(writer)
writer.Flush()
}
if len(s.Alarms) > 0 {
fmt.Fprint(writer, color.Bold.Sprint("\nAlarms\n\n"))
writer.Flush()
s.writeAlarms(writer)
writer.Flush()
}
return b.String()
}
// HumanString returns the stringified appRunnerServiceStatus struct in human-readable format.
func (a *appRunnerServiceStatus) HumanString() string {
var b bytes.Buffer
writer := tabwriter.NewWriter(&b, minCellWidth, tabWidth, statusCellPaddingWidth, paddingChar, noAdditionalFormatting)
fmt.Fprint(writer, color.Bold.Sprint("Service Status\n\n"))
writer.Flush()
fmt.Fprintf(writer, " Status %s \n", statusColor(a.Service.Status))
fmt.Fprint(writer, color.Bold.Sprint("\nLast deployment\n\n"))
writer.Flush()
fmt.Fprintf(writer, " %s\t%s\n", "Updated At", humanizeTime(a.Service.DateUpdated))
serviceID := fmt.Sprintf("%s/%s", a.Service.Name, a.Service.ID)
fmt.Fprintf(writer, " %s\t%s\n", "Service ID", serviceID)
imageID := a.Service.ImageID
if strings.Contains(a.Service.ImageID, "/") {
imageID = strings.SplitAfterN(imageID, "/", 2)[1] // strip the registry.
}
fmt.Fprintf(writer, " %s\t%s\n", "Source", imageID)
writer.Flush()
fmt.Fprint(writer, color.Bold.Sprint("\nSystem Logs\n\n"))
writer.Flush()
lo, _ := time.LoadLocation("UTC")
for _, event := range a.LogEvents {
timestamp := time.Unix(event.Timestamp/1000, 0).In(lo)
fmt.Fprintf(writer, " %v\t%s\n", timestamp.Format(time.RFC3339), event.Message)
}
writer.Flush()
return b.String()
}
// HumanString returns the stringified staticSiteServiceStatus struct in human-readable format.
func (s *staticSiteServiceStatus) HumanString() string {
var b bytes.Buffer
writer := tabwriter.NewWriter(&b, minCellWidth, tabWidth, statusCellPaddingWidth, paddingChar, noAdditionalFormatting)
fmt.Fprint(writer, color.Bold.Sprint("Bucket Summary\n\n"))
writer.Flush()
fmt.Fprintf(writer, " Bucket Name %s\n", s.BucketName)
fmt.Fprintf(writer, " Total Objects %s\n", strconv.Itoa(s.Count))
fmt.Fprintf(writer, " Total Size %s\n", s.Size)
writer.Flush()
return b.String()
}
func (s *ecsServiceStatus) writeTaskSummary(writer io.Writer) {
// NOTE: all the `bar` need to be fully colored. Observe how all the second parameter for all `summaryBar` function
// is a list of strings that are colored (e.g. `[]string{color.Green.Sprint("â– "), color.Grey.Sprint("â–¡")}`)
// This is because if the some of the bar is partially colored, tab writer will behave unexpectedly.
var primaryDeployment awsecs.Deployment
var activeDeployments []awsecs.Deployment
for _, d := range s.Service.Deployments {
switch d.Status {
case awsecs.ServiceDeploymentStatusPrimary:
primaryDeployment = d // There is at most one primary deployment
case awsecs.ServiceDeploymentStatusActive:
activeDeployments = append(activeDeployments, d)
}
}
s.writeRunningTasksSummary(writer, primaryDeployment, activeDeployments)
s.writeDeploymentsSummary(writer, primaryDeployment, activeDeployments)
s.writeHealthSummary(writer, primaryDeployment, activeDeployments)
s.writeCapacityProvidersSummary(writer)
}
func (s *ecsServiceStatus) writeRunningTasksSummary(writer io.Writer, primaryDeployment awsecs.Deployment, activeDeployments []awsecs.Deployment) {
// By default, we want to show the primary running task vs. primary desired tasks.
data := []summarybar.Datum{
{
Value: (int)(s.Service.RunningCount),
Representation: color.Green.Sprint("â–ˆ"),
},
{
Value: (int)(s.Service.DesiredCount) - (int)(s.Service.RunningCount),
Representation: color.Green.Sprint("â–‘"),
},
}
// If there is one or more active deployments, show the primary running tasks vs. active running tasks instead.
if len(activeDeployments) > 0 {
var runningPrimary, runningActive int
for _, d := range activeDeployments {
runningActive += (int)(d.RunningCount)
}
runningPrimary = (int)(primaryDeployment.RunningCount)
data = []summarybar.Datum{
{
Value: runningPrimary,
Representation: color.Green.Sprint("â–ˆ"),
},
{
Value: runningActive,
Representation: color.Blue.Sprint("â–ˆ"),
},
}
}
renderer := summarybar.New(data, summaryBarWidthConfig, summaryBarEmptyRepConfig)
fmt.Fprintf(writer, " %s\t", "Running")
_, _ = renderer.Render(writer)
stringSummary := fmt.Sprintf("%d/%d desired tasks are running", s.Service.RunningCount, s.Service.DesiredCount)
fmt.Fprintf(writer, "\t%s\n", stringSummary)
}
func (s *ecsServiceStatus) writeDeploymentsSummary(writer io.Writer, primaryDeployment awsecs.Deployment, activeDeployments []awsecs.Deployment) {
if len(activeDeployments) <= 0 {
return
}
// Show "Deployments" section only if there are "ACTIVE" deployments in addition to the "PRIMARY" deployment.
// This is because if there aren't any "ACTIVE" deployment, then this section would have been showing the same
// information as the "Running" section.
header := "Deployments"
fmt.Fprintf(writer, " %s\t", header)
s.writeDeployment(writer, primaryDeployment, color.Green)
for _, deployment := range activeDeployments {
fmt.Fprint(writer, " \t")
s.writeDeployment(writer, deployment, color.Blue)
}
}
func (s *ecsServiceStatus) writeDeployment(writer io.Writer, deployment awsecs.Deployment, repColor *fcolor.Color) {
var revisionInfo string
revision, err := awsecs.TaskDefinitionVersion(deployment.TaskDefinition)
if err == nil {
revisionInfo = fmt.Sprintf(" (rev %d)", revision)
}
data := []summarybar.Datum{
{
Value: (int)(deployment.RunningCount),
Representation: repColor.Sprint("â–ˆ"),
},
{
Value: (int)(deployment.DesiredCount) - (int)(deployment.RunningCount),
Representation: repColor.Sprint("â–‘"),
},
}
renderer := summarybar.New(data, summaryBarWidthConfig, summaryBarEmptyRepConfig)
_, _ = renderer.Render(writer)
stringSummary := fmt.Sprintf("%d/%d running tasks for %s%s",
deployment.RunningCount,
deployment.DesiredCount,
strings.ToLower(deployment.Status),
revisionInfo)
fmt.Fprintf(writer, "\t%s\n", stringSummary)
}
func (s *ecsServiceStatus) writeHealthSummary(writer io.Writer, primaryDeployment awsecs.Deployment, activeDeployments []awsecs.Deployment) {
revision, _ := awsecs.TaskDefinitionVersion(primaryDeployment.TaskDefinition)
primaryTasks := s.tasksOfRevision(revision)
shouldShowHTTPHealth := anyTasksInAnyTargetGroup(primaryTasks, s.TargetHealthDescriptions)
shouldShowContainerHealth := isContainerHealthCheckEnabled(primaryTasks)
if !shouldShowHTTPHealth && !shouldShowContainerHealth {
return
}
var revisionInfo string
if len(activeDeployments) > 0 {
revisionInfo = fmt.Sprintf(" (rev %d)", revision)
}
header := "Health"
if shouldShowHTTPHealth {
healthyCount := countHealthyHTTPTasks(primaryTasks, s.TargetHealthDescriptions)
data := []summarybar.Datum{
{
Value: healthyCount,
Representation: color.Green.Sprint("â–ˆ"),
},
{
Value: (int)(primaryDeployment.DesiredCount) - healthyCount,
Representation: color.Green.Sprint("â–‘"),
},
}
renderer := summarybar.New(data, summaryBarWidthConfig, summaryBarEmptyRepConfig)
fmt.Fprintf(writer, " %s\t", "Health")
_, _ = renderer.Render(writer)
stringSummary := fmt.Sprintf("%d/%d passes HTTP health checks%s", healthyCount, primaryDeployment.DesiredCount, revisionInfo)
fmt.Fprintf(writer, "\t%s\n", stringSummary)
header = ""
}
if shouldShowContainerHealth {
healthyCount, _, _ := containerHealthBreakDownByCount(primaryTasks)
data := []summarybar.Datum{
{
Value: healthyCount,
Representation: color.Green.Sprint("â–ˆ"),
},
{
Value: (int)(primaryDeployment.DesiredCount) - healthyCount,
Representation: color.Green.Sprint("â–‘"),
},
}
renderer := summarybar.New(data, summaryBarWidthConfig, summaryBarEmptyRepConfig)
fmt.Fprintf(writer, " %s\t", header)
_, _ = renderer.Render(writer)
stringSummary := fmt.Sprintf("%d/%d passes container health checks%s", healthyCount, primaryDeployment.DesiredCount, revisionInfo)
fmt.Fprintf(writer, "\t%s\n", stringSummary)
}
}
func (s *ecsServiceStatus) writeCapacityProvidersSummary(writer io.Writer) {
if !isCapacityProvidersEnabled(s.DesiredRunningTasks) {
return
}
fargate, spot, empty := runningCapacityProvidersBreakDownByCount(s.DesiredRunningTasks)
data := []summarybar.Datum{
{
Value: fargate + empty,
Representation: color.Grey.Sprintf("â–’"),
},
{
Value: spot,
Representation: color.Grey.Sprintf("â–“"),
},
}
renderer := summarybar.New(data, summaryBarWidthConfig, summaryBarEmptyRepConfig)
fmt.Fprintf(writer, " %s\t", "Capacity Provider")
_, _ = renderer.Render(writer)
var cpSummaries []string
if fargate+empty != 0 {
// We consider those with empty capacity provider field as "FARGATE"
cpSummaries = append(cpSummaries, fmt.Sprintf("%d/%d on Fargate", fargate+empty, s.Service.RunningCount))
}
if spot != 0 {
cpSummaries = append(cpSummaries, fmt.Sprintf("%d/%d on Fargate Spot", spot, s.Service.RunningCount))
}
fmt.Fprintf(writer, "\t%s\n", strings.Join(cpSummaries, ", "))
}
func (s *ecsServiceStatus) writeStoppedTasks(writer io.Writer) {
headers := []string{"Reason", "Task Count", "Sample Task IDs"}
fmt.Fprintf(writer, " %s\n", strings.Join(headers, "\t"))
fmt.Fprintf(writer, " %s\n", strings.Join(underline(headers), "\t"))
reasonToTasks := make(map[string][]string)
for _, task := range s.StoppedTasks {
reasonToTasks[task.StoppedReason] = append(reasonToTasks[task.StoppedReason], shortTaskID(task.ID))
}
for reason, ids := range reasonToTasks {
sampleIDs := ids
if len(sampleIDs) > 5 {
sampleIDs = sampleIDs[:5]
}
printWithMaxWidth(writer, " %s\t%s\t%s\n", 30, reason, strconv.Itoa(len(ids)), strings.Join(sampleIDs, ","))
}
}
func (s *ecsServiceStatus) writeRunningTasks(writer io.Writer) {
shouldShowHTTPHealth := anyTasksInAnyTargetGroup(s.DesiredRunningTasks, s.TargetHealthDescriptions)
shouldShowCapacityProvider := isCapacityProvidersEnabled(s.DesiredRunningTasks)
shouldShowContainerHealth := isContainerHealthCheckEnabled(s.DesiredRunningTasks)
taskToHealth := summarizeHTTPHealthForTasks(s.TargetHealthDescriptions)
headers := []string{"ID", "Status", "Revision", "Started At"}
var opts []ecsTaskStatusConfigOpts
if shouldShowCapacityProvider {
opts = append(opts, withCapProviderShown)
headers = append(headers, "Capacity")
}
if shouldShowContainerHealth {
opts = append(opts, withContainerHealthShow)
headers = append(headers, "Cont. Health")
}
if shouldShowHTTPHealth {
headers = append(headers, "HTTP Health")
}
fmt.Fprintf(writer, " %s\n", strings.Join(headers, "\t"))
fmt.Fprintf(writer, " %s\n", strings.Join(underline(headers), "\t"))
for _, task := range s.DesiredRunningTasks {
taskStatus := fmt.Sprint((ecsTaskStatus)(task).humanString(opts...))
if shouldShowHTTPHealth {
var httpHealthState string
if states, ok := taskToHealth[task.ID]; !ok || len(states) == 0 {
httpHealthState = "-"
} else {
// sometimes a task can have multiple target health states (although rare)
httpHealthState = strings.Join(states, ",")
}
taskStatus = fmt.Sprintf("%s\t%s", taskStatus, strings.ToUpper(httpHealthState))
}
fmt.Fprintf(writer, " %s\n", taskStatus)
}
}
func (s *ecsServiceStatus) writeAlarms(writer io.Writer) {
headers := []string{"Name", "Type", "Condition", "Last Updated", "Health"}
fmt.Fprintf(writer, " %s\n", strings.Join(headers, "\t"))
fmt.Fprintf(writer, " %s\n", strings.Join(underline(headers), "\t"))
for _, alarm := range s.Alarms {
updatedTimeSince := humanizeTime(alarm.UpdatedTimes)
printWithMaxWidth(writer, " %s\t%s\t%s\t%s\t%s\n", maxAlarmStatusColumnWidth, alarm.Name, alarm.Type, alarm.Condition, updatedTimeSince, alarmHealthColor(alarm.Status))
fmt.Fprintf(writer, " %s\t%s\t%s\t%s\t%s\n", "", "", "", "", "")
}
}
type ecsTaskStatus awsecs.TaskStatus
// Example output:
//
// 6ca7a60d RUNNING 42 19 hours ago - UNKNOWN
func (ts ecsTaskStatus) humanString(opts ...ecsTaskStatusConfigOpts) string {
config := &ecsTaskStatusConfig{}
for _, opt := range opts {
opt(config)
}
var statusString string
shortID := "-"
if ts.ID != "" {
shortID = shortTaskID(ts.ID)
}
statusString += fmt.Sprint(shortID)
statusString += fmt.Sprintf("\t%s", ts.LastStatus)
revision := "-"
v, err := awsecs.TaskDefinitionVersion(ts.TaskDefinition)
if err == nil {
revision = strconv.Itoa(v)
}
statusString += fmt.Sprintf("\t%s", revision)
startedSince := "-"
if !ts.StartedAt.IsZero() {
startedSince = humanizeTime(ts.StartedAt)
}
statusString += fmt.Sprintf("\t%s", startedSince)
if config.shouldShowCapProvider {
cp := "FARGATE (Launch type)"
if ts.CapacityProvider != "" {
cp = ts.CapacityProvider
}
statusString += fmt.Sprintf("\t%s", cp)
}
if config.shouldShowContainerHealth {
ch := "-"
if ts.Health != "" {
ch = ts.Health
}
statusString += fmt.Sprintf("\t%s", ch)
}
return statusString
}
type ecsTaskStatusConfigOpts func(config *ecsTaskStatusConfig)
type ecsTaskStatusConfig struct {
shouldShowCapProvider bool
shouldShowContainerHealth bool
}
func withCapProviderShown(config *ecsTaskStatusConfig) {
config.shouldShowCapProvider = true
}
func withContainerHealthShow(config *ecsTaskStatusConfig) {
config.shouldShowContainerHealth = true
}
func shortTaskID(id string) string {
if len(id) >= shortTaskIDLength {
return id[:shortTaskIDLength]
}
return id
}
func printWithMaxWidth(w io.Writer, format string, width int, members ...string) {
columns := make([][]string, len(members))
maxNumOfLinesPerCol := 0
for ind, member := range members {
var column []string
builder := new(strings.Builder)
// https://stackoverflow.com/questions/25686109/split-string-by-length-in-golang
for i, r := range []rune(member) {
builder.WriteRune(r)
if i > 0 && (i+1)%width == 0 {
column = append(column, builder.String())
builder.Reset()
}
}
if builder.String() != "" {
column = append(column, builder.String())
}
maxNumOfLinesPerCol = int(math.Max(float64(len(column)), float64(maxNumOfLinesPerCol)))
columns[ind] = column
}
for i := 0; i < maxNumOfLinesPerCol; i++ {
args := make([]interface{}, len(columns))
for ind, memberSlice := range columns {
if i >= len(memberSlice) {
args[ind] = ""
continue
}
args[ind] = memberSlice[i]
}
fmt.Fprintf(w, format, args...)
}
}
func alarmHealthColor(status string) string {
switch status {
case "OK":
return color.Green.Sprint(status)
case "ALARM":
return color.Red.Sprint(status)
case "INSUFFICIENT_DATA":
return color.Yellow.Sprint(status)
default:
return status
}
}
func statusColor(status string) string {
switch status {
case "ACTIVE":
return color.Green.Sprint(status)
case "DRAINING":
return color.Yellow.Sprint(status)
case "RUNNING":
return color.Green.Sprint(status)
case "UPDATING":
return color.Yellow.Sprint(status)
default:
return color.Red.Sprint(status)
}
}
| 588 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package describe
import (
"fmt"
awsS3 "github.com/aws/copilot-cli/internal/pkg/aws/s3"
"github.com/aws/copilot-cli/internal/pkg/s3"
"sort"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/copilot-cli/internal/pkg/aws/aas"
"github.com/aws/copilot-cli/internal/pkg/aws/cloudwatch"
"github.com/aws/copilot-cli/internal/pkg/aws/cloudwatchlogs"
awsecs "github.com/aws/copilot-cli/internal/pkg/aws/ecs"
"github.com/aws/copilot-cli/internal/pkg/aws/elbv2"
"github.com/aws/copilot-cli/internal/pkg/aws/sessions"
"github.com/aws/copilot-cli/internal/pkg/deploy"
"github.com/aws/copilot-cli/internal/pkg/ecs"
)
const (
fmtAppRunnerSvcLogGroupName = "/aws/apprunner/%s/%s/service"
autoscalingAlarmType = "Auto Scaling"
rollbackAlarmType = "Rollback"
)
type targetHealthGetter interface {
TargetsHealth(targetGroupARN string) ([]*elbv2.TargetHealth, error)
}
type alarmStatusGetter interface {
AlarmsWithTags(tags map[string]string) ([]cloudwatch.AlarmStatus, error)
AlarmStatuses(...cloudwatch.DescribeAlarmOpts) ([]cloudwatch.AlarmStatus, error)
}
type logGetter interface {
LogEvents(opts cloudwatchlogs.LogEventsOpts) (*cloudwatchlogs.LogEventsOutput, error)
}
type ecsServiceGetter interface {
ServiceRunningTasks(clusterName, serviceName string) ([]*awsecs.Task, error)
Service(clusterName, serviceName string) (*awsecs.Service, error)
}
type serviceDescriber interface {
DescribeService(app, env, svc string) (*ecs.ServiceDesc, error)
}
type autoscalingAlarmNamesGetter interface {
ECSServiceAlarmNames(cluster, service string) ([]string, error)
}
type ecsStatusDescriber struct {
app string
env string
svc string
svcDescriber serviceDescriber
ecsSvcGetter ecsServiceGetter
cwSvcGetter alarmStatusGetter
aasSvcGetter autoscalingAlarmNamesGetter
targetHealthGetter targetHealthGetter
}
type appRunnerStatusDescriber struct {
app string
env string
svc string
svcDescriber apprunnerDescriber
eventsGetter logGetter
}
type staticSiteStatusDescriber struct {
app string
env string
svc string
initS3Client func(string) (bucketDataGetter, bucketNameGetter, error)
}
// NewServiceStatusConfig contains fields that initiates ServiceStatus struct.
type NewServiceStatusConfig struct {
App string
Env string
Svc string
ConfigStore ConfigStoreSvc
}
// NewECSStatusDescriber instantiates a new ecsStatusDescriber struct.
func NewECSStatusDescriber(opt *NewServiceStatusConfig) (*ecsStatusDescriber, error) {
env, err := opt.ConfigStore.GetEnvironment(opt.App, opt.Env)
if err != nil {
return nil, fmt.Errorf("get environment %s: %w", opt.Env, err)
}
sess, err := sessions.ImmutableProvider().FromRole(env.ManagerRoleARN, env.Region)
if err != nil {
return nil, fmt.Errorf("session for role %s and region %s: %w", env.ManagerRoleARN, env.Region, err)
}
return &ecsStatusDescriber{
app: opt.App,
env: opt.Env,
svc: opt.Svc,
svcDescriber: ecs.New(sess),
cwSvcGetter: cloudwatch.New(sess),
ecsSvcGetter: awsecs.New(sess),
aasSvcGetter: aas.New(sess),
targetHealthGetter: elbv2.New(sess),
}, nil
}
// NewAppRunnerStatusDescriber instantiates a new appRunnerStatusDescriber struct.
func NewAppRunnerStatusDescriber(opt *NewServiceStatusConfig) (*appRunnerStatusDescriber, error) {
appRunnerSvcDescriber, err := newAppRunnerServiceDescriber(NewServiceConfig{
App: opt.App,
Svc: opt.Svc,
ConfigStore: opt.ConfigStore,
}, opt.Env)
if err != nil {
return nil, err
}
return &appRunnerStatusDescriber{
app: opt.App,
env: opt.Env,
svc: opt.Svc,
svcDescriber: appRunnerSvcDescriber,
eventsGetter: cloudwatchlogs.New(appRunnerSvcDescriber.sess),
}, nil
}
// NewStaticSiteStatusDescriber instantiates a new staticSiteStatusDescriber struct.
func NewStaticSiteStatusDescriber(opt *NewServiceStatusConfig) (*staticSiteStatusDescriber, error) {
describer := &staticSiteStatusDescriber{
app: opt.App,
env: opt.Env,
svc: opt.Svc,
}
describer.initS3Client = func(env string) (bucketDataGetter, bucketNameGetter, error) {
environment, err := opt.ConfigStore.GetEnvironment(opt.App, env)
if err != nil {
return nil, nil, fmt.Errorf("get environment %s: %w", env, err)
}
sess, err := sessions.ImmutableProvider().FromRole(environment.ManagerRoleARN, environment.Region)
if err != nil {
return nil, nil, err
}
return awsS3.New(sess), s3.New(sess), nil
}
return describer, nil
}
// Describe returns the status of an ECS service.
func (s *ecsStatusDescriber) Describe() (HumanJSONStringer, error) {
svcDesc, err := s.svcDescriber.DescribeService(s.app, s.env, s.svc)
if err != nil {
return nil, fmt.Errorf("get ECS service description for %s: %w", s.svc, err)
}
service, err := s.ecsSvcGetter.Service(svcDesc.ClusterName, svcDesc.Name)
if err != nil {
return nil, fmt.Errorf("get service %s: %w", svcDesc.Name, err)
}
var taskStatus []awsecs.TaskStatus
for _, task := range svcDesc.Tasks {
status, err := task.TaskStatus()
if err != nil {
return nil, fmt.Errorf("get status for task %s: %w", aws.StringValue(task.TaskArn), err)
}
taskStatus = append(taskStatus, *status)
}
var stoppedTaskStatus []awsecs.TaskStatus
for _, task := range svcDesc.StoppedTasks {
status, err := task.TaskStatus()
if err != nil {
return nil, fmt.Errorf("get status for stopped task %s: %w", aws.StringValue(task.TaskArn), err)
}
stoppedTaskStatus = append(stoppedTaskStatus, *status)
}
// Using a map then converting it to a slice to avoid duplication.
alarms := make(map[string]cloudwatch.AlarmStatus)
taggedAlarms, err := s.cwSvcGetter.AlarmsWithTags(map[string]string{
deploy.AppTagKey: s.app,
deploy.EnvTagKey: s.env,
deploy.ServiceTagKey: s.svc,
})
if err != nil {
return nil, fmt.Errorf("get tagged CloudWatch alarms: %w", err)
}
for _, alarm := range taggedAlarms {
alarms[alarm.Name] = alarm
}
autoscalingAlarms, err := s.ecsServiceAutoscalingAlarms(svcDesc.ClusterName, svcDesc.Name)
if err != nil {
return nil, err
}
for _, alarm := range autoscalingAlarms {
alarms[alarm.Name] = alarm
}
rollbackAlarms, err := s.ecsServiceRollbackAlarms(s.app, s.env, s.svc)
if err != nil {
return nil, err
}
for _, alarm := range rollbackAlarms {
alarms[alarm.Name] = alarm
}
alarmList := make([]cloudwatch.AlarmStatus, len(alarms))
var i int
for _, v := range alarms {
alarmList[i] = v
i++
}
// Sort by alarm type, then alarm name within type categories.
sort.SliceStable(alarmList, func(i, j int) bool { return alarmList[i].Name < alarmList[j].Name })
sort.SliceStable(alarmList, func(i, j int) bool { return alarmList[i].Type < alarmList[j].Type })
var tasksTargetHealth []taskTargetHealth
targetGroupsARN := service.TargetGroups()
for _, groupARN := range targetGroupsARN {
targetsHealth, err := s.targetHealthGetter.TargetsHealth(groupARN)
if err != nil {
continue
}
tasksTargetHealth = append(tasksTargetHealth, targetHealthForTasks(targetsHealth, svcDesc.Tasks, groupARN)...)
}
sort.SliceStable(tasksTargetHealth, func(i, j int) bool {
if tasksTargetHealth[i].TargetGroupARN == tasksTargetHealth[j].TargetGroupARN {
return tasksTargetHealth[i].TaskID < tasksTargetHealth[j].TaskID
}
return tasksTargetHealth[i].TargetGroupARN < tasksTargetHealth[j].TargetGroupARN
})
return &ecsServiceStatus{
Service: service.ServiceStatus(),
DesiredRunningTasks: taskStatus,
Alarms: alarmList,
StoppedTasks: stoppedTaskStatus,
TargetHealthDescriptions: tasksTargetHealth,
}, nil
}
// Describe returns the status of an AppRunner service.
func (a *appRunnerStatusDescriber) Describe() (HumanJSONStringer, error) {
svc, err := a.svcDescriber.Service()
if err != nil {
return nil, fmt.Errorf("get App Runner service description for App Runner service %s in environment %s: %w", a.svc, a.env, err)
}
logGroupName := fmt.Sprintf(fmtAppRunnerSvcLogGroupName, svc.Name, svc.ID)
logEventsOpts := cloudwatchlogs.LogEventsOpts{
LogGroup: logGroupName,
Limit: aws.Int64(defaultServiceLogsLimit),
}
logEventsOutput, err := a.eventsGetter.LogEvents(logEventsOpts)
if err != nil {
return nil, fmt.Errorf("get log events for log group %s: %w", logGroupName, err)
}
return &appRunnerServiceStatus{
Service: *svc,
LogEvents: logEventsOutput.Events,
}, nil
}
// Describe returns the status of a Static Site service.
func (d *staticSiteStatusDescriber) Describe() (HumanJSONStringer, error) {
dataGetter, nameGetter, err := d.initS3Client(d.env)
if err != nil {
return nil, err
}
bucketName, err := nameGetter.BucketName(d.app, d.env, d.svc)
if err != nil {
return nil, fmt.Errorf("get bucket name for %q Static Site service in %q environment: %w", d.svc, d.env, err)
}
size, count, err := dataGetter.BucketSizeAndCount(bucketName)
if err != nil {
return nil, fmt.Errorf("get size and count data for %q S3 bucket: %w", bucketName, err)
}
return &staticSiteServiceStatus{
BucketName: bucketName,
Size: size,
Count: count,
}, nil
}
func (s *ecsStatusDescriber) ecsServiceAutoscalingAlarms(cluster, service string) ([]cloudwatch.AlarmStatus, error) {
alarmNames, err := s.aasSvcGetter.ECSServiceAlarmNames(cluster, service)
if err != nil {
return nil, fmt.Errorf("retrieve auto scaling alarm names for ECS service %s/%s: %w", cluster, service, err)
}
if len(alarmNames) == 0 {
return nil, nil
}
alarms, err := s.cwSvcGetter.AlarmStatuses(cloudwatch.WithNames(alarmNames))
if err != nil {
return nil, fmt.Errorf("get auto scaling CloudWatch alarms: %w", err)
}
for i := range alarms {
alarms[i].Type = autoscalingAlarmType
}
return alarms, nil
}
func (s *ecsStatusDescriber) ecsServiceRollbackAlarms(app, env, svc string) ([]cloudwatch.AlarmStatus, error) {
// This will not fetch imported alarms, as we filter by the Copilot-generated prefix of alarm names. This will also not fetch Copilot-generated alarms with names exceeding 255 characters, due to the balanced truncating of `TruncateAlarmName`.
alarms, err := s.cwSvcGetter.AlarmStatuses(cloudwatch.WithPrefix(fmt.Sprintf("%s-%s-%s-CopilotRollback", app, env, svc)))
if err != nil {
return nil, fmt.Errorf("get Copilot-created CloudWatch alarms: %w", err)
}
for i := range alarms {
alarms[i].Type = rollbackAlarmType
}
return alarms, nil
}
// targetHealthForTasks finds the corresponding task, if any, for each target health in a target group.
func targetHealthForTasks(targetsHealth []*elbv2.TargetHealth, tasks []*awsecs.Task, targetGroupARN string) []taskTargetHealth {
var out []taskTargetHealth
// Create a map from task's private IP address to task's ID to be matched against target's ID.
ipToTaskID := make(map[string]string)
for _, task := range tasks {
ip, err := task.PrivateIP()
if err != nil {
continue
}
taskID, err := awsecs.TaskID(aws.StringValue(task.TaskArn))
if err != nil {
continue
}
ipToTaskID[ip] = taskID
}
// For each target, check if its health check is actually checking against one of the tasks.
// If the target is an IP target, then its ID is the IP address.
// If a task is running on that IP address, then effectively the target's health check is checking against that task.
for _, th := range targetsHealth {
targetID := th.TargetID()
taskID, ok := ipToTaskID[targetID]
if !ok {
taskID = ""
}
out = append(out, taskTargetHealth{
HealthStatus: *th.HealthStatus(),
TargetGroupARN: targetGroupARN,
TaskID: taskID,
})
}
return out
}
| 354 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package describe
import (
"errors"
"fmt"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
ecsapi "github.com/aws/aws-sdk-go/service/ecs"
elbv2api "github.com/aws/aws-sdk-go/service/elbv2"
"github.com/aws/copilot-cli/internal/pkg/aws/apprunner"
"github.com/aws/copilot-cli/internal/pkg/aws/cloudwatch"
"github.com/aws/copilot-cli/internal/pkg/aws/cloudwatchlogs"
awsecs "github.com/aws/copilot-cli/internal/pkg/aws/ecs"
"github.com/aws/copilot-cli/internal/pkg/aws/elbv2"
"github.com/aws/copilot-cli/internal/pkg/describe/mocks"
"github.com/aws/copilot-cli/internal/pkg/ecs"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
type serviceStatusDescriberMocks struct {
appRunnerSvcDescriber *mocks.MockapprunnerDescriber
ecsServiceGetter *mocks.MockecsServiceGetter
alarmStatusGetter *mocks.MockalarmStatusGetter
serviceDescriber *mocks.MockserviceDescriber
aas *mocks.MockautoscalingAlarmNamesGetter
logGetter *mocks.MocklogGetter
targetHealthGetter *mocks.MocktargetHealthGetter
s3Client *mocks.MockbucketNameGetter
bucketDataGetter *mocks.MockbucketDataGetter
}
func TestServiceStatus_Describe(t *testing.T) {
const (
mockCluster = "mockCluster"
mockService = "mockService"
)
startTime, _ := time.Parse(time.RFC3339, "2006-01-02T15:04:05+00:00")
stopTime, _ := time.Parse(time.RFC3339, "2006-01-02T16:04:05+00:00")
updateTime, _ := time.Parse(time.RFC3339, "2020-03-13T19:50:30+00:00")
mockServiceDesc := &ecs.ServiceDesc{
ClusterName: mockCluster,
Name: mockService,
Tasks: []*awsecs.Task{
{
TaskArn: aws.String("arn:aws:ecs:us-west-2:123456789012:task/mockCluster/1234567890123456789"),
StartedAt: &startTime,
},
},
}
mockError := errors.New("some error")
testCases := map[string]struct {
setupMocks func(mocks serviceStatusDescriberMocks)
wantedError error
wantedContent *ecsServiceStatus
}{
"errors if failed to describe a service": {
setupMocks: func(m serviceStatusDescriberMocks) {
gomock.InOrder(
m.serviceDescriber.EXPECT().DescribeService("mockApp", "mockEnv", "mockSvc").Return(nil, mockError),
)
},
wantedError: fmt.Errorf("get ECS service description for mockSvc: some error"),
},
"errors if failed to get the ECS service": {
setupMocks: func(m serviceStatusDescriberMocks) {
gomock.InOrder(
m.serviceDescriber.EXPECT().DescribeService("mockApp", "mockEnv", "mockSvc").Return(mockServiceDesc, nil),
m.ecsServiceGetter.EXPECT().Service(mockCluster, mockService).Return(nil, mockError),
)
},
wantedError: fmt.Errorf("get service mockService: some error"),
},
"errors if failed to get running tasks status": {
setupMocks: func(m serviceStatusDescriberMocks) {
gomock.InOrder(
m.serviceDescriber.EXPECT().DescribeService("mockApp", "mockEnv", "mockSvc").Return(&ecs.ServiceDesc{
ClusterName: mockCluster,
Name: mockService,
Tasks: []*awsecs.Task{
{
TaskArn: aws.String("badMockTaskArn"),
},
},
}, nil),
m.ecsServiceGetter.EXPECT().Service(mockCluster, mockService).Return(&awsecs.Service{}, nil),
)
},
wantedError: fmt.Errorf("get status for task badMockTaskArn: parse ECS task ARN: arn: invalid prefix"),
},
"errors if failed to get stopped task status": {
setupMocks: func(m serviceStatusDescriberMocks) {
gomock.InOrder(
m.serviceDescriber.EXPECT().DescribeService("mockApp", "mockEnv", "mockSvc").Return(&ecs.ServiceDesc{
ClusterName: mockCluster,
Name: mockService,
Tasks: []*awsecs.Task{
{
TaskArn: aws.String("arn:aws:ecs:us-west-2:123456789012:task/mockCluster/1234567890123456789"),
},
},
StoppedTasks: []*awsecs.Task{
{
TaskArn: aws.String("badMockTaskArn"),
},
},
}, nil),
m.ecsServiceGetter.EXPECT().Service(mockCluster, mockService).Return(&awsecs.Service{}, nil),
)
},
wantedError: fmt.Errorf("get status for stopped task badMockTaskArn: parse ECS task ARN: arn: invalid prefix"),
},
"errors if failed to get tagged CloudWatch alarms": {
setupMocks: func(m serviceStatusDescriberMocks) {
gomock.InOrder(
m.serviceDescriber.EXPECT().DescribeService("mockApp", "mockEnv", "mockSvc").Return(mockServiceDesc, nil),
m.ecsServiceGetter.EXPECT().Service(mockCluster, mockService).Return(&awsecs.Service{}, nil),
m.alarmStatusGetter.EXPECT().AlarmsWithTags(gomock.Any()).Return(nil, mockError),
)
},
wantedError: fmt.Errorf("get tagged CloudWatch alarms: some error"),
},
"errors if failed to get auto scaling CloudWatch alarm names": {
setupMocks: func(m serviceStatusDescriberMocks) {
gomock.InOrder(
m.serviceDescriber.EXPECT().DescribeService("mockApp", "mockEnv", "mockSvc").Return(mockServiceDesc, nil),
m.ecsServiceGetter.EXPECT().Service(mockCluster, mockService).Return(&awsecs.Service{}, nil),
m.alarmStatusGetter.EXPECT().AlarmsWithTags(gomock.Any()).Return([]cloudwatch.AlarmStatus{}, nil),
m.aas.EXPECT().ECSServiceAlarmNames(mockCluster, mockService).Return(nil, mockError),
)
},
wantedError: fmt.Errorf("retrieve auto scaling alarm names for ECS service mockCluster/mockService: some error"),
},
"errors if failed to get auto scaling CloudWatch alarm status": {
setupMocks: func(m serviceStatusDescriberMocks) {
gomock.InOrder(
m.serviceDescriber.EXPECT().DescribeService("mockApp", "mockEnv", "mockSvc").Return(mockServiceDesc, nil),
m.ecsServiceGetter.EXPECT().Service(mockCluster, mockService).Return(&awsecs.Service{}, nil),
m.alarmStatusGetter.EXPECT().AlarmsWithTags(gomock.Any()).Return([]cloudwatch.AlarmStatus{}, nil),
m.aas.EXPECT().ECSServiceAlarmNames(mockCluster, mockService).Return([]string{"mockAlarmName"}, nil),
m.alarmStatusGetter.EXPECT().AlarmStatuses(gomock.Any()).Return(nil, mockError),
)
},
wantedError: fmt.Errorf("get auto scaling CloudWatch alarms: some error"),
},
"errors if failed to get Copilot-created CloudWatch rollback alarm status": {
setupMocks: func(m serviceStatusDescriberMocks) {
gomock.InOrder(
m.serviceDescriber.EXPECT().DescribeService("mockApp", "mockEnv", "mockSvc").Return(mockServiceDesc, nil),
m.ecsServiceGetter.EXPECT().Service(mockCluster, mockService).Return(&awsecs.Service{}, nil),
m.alarmStatusGetter.EXPECT().AlarmsWithTags(gomock.Any()).Return([]cloudwatch.AlarmStatus{}, nil),
m.aas.EXPECT().ECSServiceAlarmNames(mockCluster, mockService).Return([]string{"mockAlarmName"}, nil),
m.alarmStatusGetter.EXPECT().AlarmStatuses(gomock.Any()).Return(nil, nil),
m.alarmStatusGetter.EXPECT().AlarmStatuses(gomock.Any()).Return(nil, mockError),
)
},
wantedError: fmt.Errorf("get Copilot-created CloudWatch alarms: some error"),
},
"do not get status of extraneous alarms": {
setupMocks: func(m serviceStatusDescriberMocks) {
gomock.InOrder(
m.serviceDescriber.EXPECT().DescribeService("mockApp", "mockEnv", "mockSvc").Return(&ecs.ServiceDesc{
ClusterName: mockCluster,
Name: mockService,
Tasks: []*awsecs.Task{
{
TaskArn: aws.String("arn:aws:ecs:us-west-2:123456789012:task/mockCluster/1234567890123456789"),
StartedAt: &startTime,
HealthStatus: aws.String("HEALTHY"),
LastStatus: aws.String("RUNNING"),
Containers: []*ecsapi.Container{
{
Image: aws.String("mockImageID1"),
ImageDigest: aws.String("69671a968e8ec3648e2697417750e"),
},
},
StoppedAt: &stopTime,
StoppedReason: aws.String("some reason"),
},
},
}, nil),
m.ecsServiceGetter.EXPECT().Service(mockCluster, mockService).Return(&awsecs.Service{
Status: aws.String("ACTIVE"),
DesiredCount: aws.Int64(1),
RunningCount: aws.Int64(1),
Deployments: []*ecsapi.Deployment{
{
UpdatedAt: &startTime,
TaskDefinition: aws.String("mockTaskDefinition"),
},
},
}, nil),
m.alarmStatusGetter.EXPECT().AlarmsWithTags(map[string]string{
"copilot-application": "mockApp",
"copilot-environment": "mockEnv",
"copilot-service": "mockSvc",
}).Return(nil, nil),
m.aas.EXPECT().ECSServiceAlarmNames(mockCluster, mockService).Return(nil, nil),
m.alarmStatusGetter.EXPECT().AlarmStatuses(gomock.Any()).Return(nil, nil),
)
},
wantedContent: &ecsServiceStatus{
Service: awsecs.ServiceStatus{
DesiredCount: 1,
RunningCount: 1,
Status: "ACTIVE",
Deployments: []awsecs.Deployment{
{
UpdatedAt: startTime,
TaskDefinition: "mockTaskDefinition",
},
},
LastDeploymentAt: startTime,
TaskDefinition: "mockTaskDefinition",
},
Alarms: []cloudwatch.AlarmStatus{},
DesiredRunningTasks: []awsecs.TaskStatus{
{
Health: "HEALTHY",
LastStatus: "RUNNING",
ID: "1234567890123456789",
Images: []awsecs.Image{
{
Digest: "69671a968e8ec3648e2697417750e",
ID: "mockImageID1",
},
},
StartedAt: startTime,
StoppedAt: stopTime,
StoppedReason: "some reason",
},
},
},
},
"do not error out if failed to get a service's target group health": {
setupMocks: func(m serviceStatusDescriberMocks) {
gomock.InOrder(
m.serviceDescriber.EXPECT().DescribeService("mockApp", "mockEnv", "mockSvc").Return(mockServiceDesc, nil),
m.ecsServiceGetter.EXPECT().Service(mockCluster, mockService).Return(&awsecs.Service{
Deployments: []*ecsapi.Deployment{
{
UpdatedAt: aws.Time(startTime),
},
},
LoadBalancers: []*ecsapi.LoadBalancer{
{
TargetGroupArn: aws.String("group-1"),
},
},
}, nil),
m.alarmStatusGetter.EXPECT().AlarmsWithTags(gomock.Any()).Return([]cloudwatch.AlarmStatus{}, nil),
m.aas.EXPECT().ECSServiceAlarmNames(gomock.Any(), gomock.Any()).Return([]string{}, nil),
m.alarmStatusGetter.EXPECT().AlarmStatuses(gomock.Any()).Return(nil, nil),
m.targetHealthGetter.EXPECT().TargetsHealth("group-1").Return(nil, errors.New("some error")),
)
},
wantedContent: &ecsServiceStatus{
Service: awsecs.ServiceStatus{
Deployments: []awsecs.Deployment{
{
UpdatedAt: startTime,
},
},
LastDeploymentAt: startTime,
},
Alarms: []cloudwatch.AlarmStatus{},
DesiredRunningTasks: []awsecs.TaskStatus{
{
ID: "1234567890123456789",
StartedAt: startTime,
},
},
StoppedTasks: nil,
TargetHealthDescriptions: nil,
},
},
"retrieve all target health information in service": {
setupMocks: func(m serviceStatusDescriberMocks) {
gomock.InOrder(
m.serviceDescriber.EXPECT().DescribeService("mockApp", "mockEnv", "mockSvc").Return(&ecs.ServiceDesc{
ClusterName: mockCluster,
Name: mockService,
Tasks: []*awsecs.Task{
{
TaskArn: aws.String("arn:aws:ecs:us-west-2:123456789012:task/mockCluster/task-with-private-ip-being-target"),
Attachments: []*ecsapi.Attachment{
{
Type: aws.String("ElasticNetworkInterface"),
Details: []*ecsapi.KeyValuePair{
{
Name: aws.String("privateIPv4Address"),
Value: aws.String("1.2.3.4"),
},
},
},
},
},
{
TaskArn: aws.String("arn:aws:ecs:us-west-2:123456789012:task/mockCluster/task-with-private-ip-not-a-target"),
Attachments: []*ecsapi.Attachment{
{
Type: aws.String("ElasticNetworkInterface"),
Details: []*ecsapi.KeyValuePair{
{
Name: aws.String("privateIPv4Address"),
Value: aws.String("5.6.7.8"),
},
},
},
},
},
},
}, nil),
m.ecsServiceGetter.EXPECT().Service(mockCluster, mockService).Return(&awsecs.Service{
Status: aws.String("ACTIVE"),
DesiredCount: aws.Int64(1),
RunningCount: aws.Int64(1),
Deployments: []*ecsapi.Deployment{
{
UpdatedAt: &startTime,
TaskDefinition: aws.String("mockTaskDefinition"),
},
},
LoadBalancers: []*ecsapi.LoadBalancer{
{
TargetGroupArn: aws.String("group-1"),
},
{
TargetGroupArn: aws.String("group-2"),
},
},
}, nil),
m.alarmStatusGetter.EXPECT().AlarmsWithTags(map[string]string{
"copilot-application": "mockApp",
"copilot-environment": "mockEnv",
"copilot-service": "mockSvc",
}).Return([]cloudwatch.AlarmStatus{}, nil),
m.aas.EXPECT().ECSServiceAlarmNames(mockCluster, mockService).Return([]string{}, nil),
m.alarmStatusGetter.EXPECT().AlarmStatuses(gomock.Any()).Return(nil, nil),
m.targetHealthGetter.EXPECT().TargetsHealth("group-1").Return([]*elbv2.TargetHealth{
{
Target: &elbv2api.TargetDescription{
Id: aws.String("1.2.3.4"),
},
TargetHealth: &elbv2api.TargetHealth{
State: aws.String("unhealthy"),
Reason: aws.String("Target.ResponseCodeMismatch"),
},
},
{
Target: &elbv2api.TargetDescription{
Id: aws.String("4.3.2.1"),
},
TargetHealth: &elbv2api.TargetHealth{
State: aws.String("healthy"),
},
},
}, nil),
m.targetHealthGetter.EXPECT().TargetsHealth("group-2").Return([]*elbv2.TargetHealth{
{
Target: &elbv2api.TargetDescription{
Id: aws.String("1.2.3.4"),
},
TargetHealth: &elbv2api.TargetHealth{
State: aws.String("healthy"),
},
},
{
Target: &elbv2api.TargetDescription{
Id: aws.String("4.3.2.1"),
},
TargetHealth: &elbv2api.TargetHealth{
State: aws.String("healthy"),
},
},
}, nil),
)
},
wantedContent: &ecsServiceStatus{
Service: awsecs.ServiceStatus{
DesiredCount: 1,
RunningCount: 1,
Status: "ACTIVE",
Deployments: []awsecs.Deployment{
{
UpdatedAt: startTime,
TaskDefinition: "mockTaskDefinition",
},
},
LastDeploymentAt: startTime,
TaskDefinition: "mockTaskDefinition",
},
Alarms: []cloudwatch.AlarmStatus{},
DesiredRunningTasks: []awsecs.TaskStatus{
{
ID: "task-with-private-ip-being-target",
},
{
ID: "task-with-private-ip-not-a-target",
},
},
TargetHealthDescriptions: []taskTargetHealth{
{
HealthStatus: elbv2.HealthStatus{
TargetID: "4.3.2.1",
HealthState: "healthy",
},
TaskID: "",
TargetGroupARN: "group-1",
},
{
HealthStatus: elbv2.HealthStatus{
TargetID: "1.2.3.4",
HealthState: "unhealthy",
HealthReason: "Target.ResponseCodeMismatch",
},
TaskID: "task-with-private-ip-being-target",
TargetGroupARN: "group-1",
},
{
HealthStatus: elbv2.HealthStatus{
TargetID: "4.3.2.1",
HealthState: "healthy",
},
TaskID: "",
TargetGroupARN: "group-2",
},
{
HealthStatus: elbv2.HealthStatus{
TargetID: "1.2.3.4",
HealthState: "healthy",
},
TaskID: "task-with-private-ip-being-target",
TargetGroupARN: "group-2",
},
},
//rendererConfigurer: &barRendererConfigurer{},
},
},
"success": {
setupMocks: func(m serviceStatusDescriberMocks) {
gomock.InOrder(
m.serviceDescriber.EXPECT().DescribeService("mockApp", "mockEnv", "mockSvc").Return(&ecs.ServiceDesc{
ClusterName: mockCluster,
Name: mockService,
Tasks: []*awsecs.Task{
{
TaskArn: aws.String("arn:aws:ecs:us-west-2:123456789012:task/mockCluster/1234567890123456789"),
StartedAt: &startTime,
HealthStatus: aws.String("HEALTHY"),
LastStatus: aws.String("RUNNING"),
Containers: []*ecsapi.Container{
{
Image: aws.String("mockImageID1"),
ImageDigest: aws.String("69671a968e8ec3648e2697417750e"),
},
{
Image: aws.String("mockImageID2"),
ImageDigest: aws.String("ca27a44e25ce17fea7b07940ad793"),
},
},
StoppedAt: &stopTime,
StoppedReason: aws.String("some reason"),
},
},
}, nil),
m.ecsServiceGetter.EXPECT().Service(mockCluster, mockService).Return(&awsecs.Service{
Status: aws.String("ACTIVE"),
DesiredCount: aws.Int64(1),
RunningCount: aws.Int64(1),
Deployments: []*ecsapi.Deployment{
{
UpdatedAt: &startTime,
TaskDefinition: aws.String("mockTaskDefinition"),
},
},
}, nil),
m.alarmStatusGetter.EXPECT().AlarmsWithTags(map[string]string{
"copilot-application": "mockApp",
"copilot-environment": "mockEnv",
"copilot-service": "mockSvc",
}).Return([]cloudwatch.AlarmStatus{
{
Arn: "mockAlarmArn1",
Name: "AMetricAlarm",
Condition: "mockCondition",
Status: "OK",
Type: "Metric",
UpdatedTimes: updateTime,
},
{
Arn: "mockAlarmArn11",
Name: "BMetricAlarm",
Condition: "mockCondition",
Status: "OK",
Type: "Metric",
UpdatedTimes: updateTime,
},
}, nil),
m.aas.EXPECT().ECSServiceAlarmNames(mockCluster, mockService).Return([]string{"mockAlarm2"}, nil),
m.alarmStatusGetter.EXPECT().AlarmStatuses(gomock.Any()).Return([]cloudwatch.AlarmStatus{
{
Arn: "mockAlarmArn22",
Name: "BAutoScalingAlarm",
Condition: "mockCondition",
Status: "OK",
Type: "Metric",
UpdatedTimes: updateTime,
},
{
Arn: "mockAlarmArn2",
Name: "AAutoScalingAlarm",
Condition: "mockCondition",
Status: "OK",
Type: "Metric",
UpdatedTimes: updateTime,
},
}, nil),
m.alarmStatusGetter.EXPECT().AlarmStatuses(gomock.Any()).Return(
[]cloudwatch.AlarmStatus{
{
Arn: "mockAlarmArn33",
Name: "BmockApp-mockEnv-mockSvc-CopilotRollbackAlarm",
Condition: "mockCondition",
Status: "OK",
Type: "Metric",
UpdatedTimes: updateTime,
},
{
Arn: "mockAlarmArn3",
Name: "AmockApp-mockEnv-mockSvc-CopilotRollbackAlarm",
Condition: "mockCondition",
Status: "OK",
Type: "Metric",
UpdatedTimes: updateTime,
},
}, nil),
)
},
wantedContent: &ecsServiceStatus{
Service: awsecs.ServiceStatus{
DesiredCount: 1,
RunningCount: 1,
Status: "ACTIVE",
Deployments: []awsecs.Deployment{
{
UpdatedAt: startTime,
TaskDefinition: "mockTaskDefinition",
},
},
LastDeploymentAt: startTime,
TaskDefinition: "mockTaskDefinition",
},
Alarms: []cloudwatch.AlarmStatus{
{
Arn: "mockAlarmArn2",
Condition: "mockCondition",
Name: "AAutoScalingAlarm",
Status: "OK",
Type: "Auto Scaling",
UpdatedTimes: updateTime,
},
{
Arn: "mockAlarmArn22",
Name: "BAutoScalingAlarm",
Condition: "mockCondition",
Status: "OK",
Type: "Auto Scaling",
UpdatedTimes: updateTime,
},
{
Arn: "mockAlarmArn1",
Name: "AMetricAlarm",
Condition: "mockCondition",
Status: "OK",
Type: "Metric",
UpdatedTimes: updateTime,
},
{
Arn: "mockAlarmArn11",
Name: "BMetricAlarm",
Condition: "mockCondition",
Status: "OK",
Type: "Metric",
UpdatedTimes: updateTime,
},
{
Arn: "mockAlarmArn3",
Name: "AmockApp-mockEnv-mockSvc-CopilotRollbackAlarm",
Condition: "mockCondition",
Status: "OK",
Type: "Rollback",
UpdatedTimes: updateTime,
},
{
Arn: "mockAlarmArn33",
Name: "BmockApp-mockEnv-mockSvc-CopilotRollbackAlarm",
Condition: "mockCondition",
Status: "OK",
Type: "Rollback",
UpdatedTimes: updateTime,
},
},
DesiredRunningTasks: []awsecs.TaskStatus{
{
Health: "HEALTHY",
LastStatus: "RUNNING",
ID: "1234567890123456789",
Images: []awsecs.Image{
{
Digest: "69671a968e8ec3648e2697417750e",
ID: "mockImageID1",
},
{
ID: "mockImageID2",
Digest: "ca27a44e25ce17fea7b07940ad793",
},
},
StartedAt: startTime,
StoppedAt: stopTime,
StoppedReason: "some reason",
},
},
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockecsSvc := mocks.NewMockecsServiceGetter(ctrl)
mockcwSvc := mocks.NewMockalarmStatusGetter(ctrl)
mockSvcDescriber := mocks.NewMockserviceDescriber(ctrl)
mockaasClient := mocks.NewMockautoscalingAlarmNamesGetter(ctrl)
mockTargetHealthGetter := mocks.NewMocktargetHealthGetter(ctrl)
mocks := serviceStatusDescriberMocks{
ecsServiceGetter: mockecsSvc,
alarmStatusGetter: mockcwSvc,
serviceDescriber: mockSvcDescriber,
aas: mockaasClient,
targetHealthGetter: mockTargetHealthGetter,
}
tc.setupMocks(mocks)
svcStatus := &ecsStatusDescriber{
svc: "mockSvc",
env: "mockEnv",
app: "mockApp",
cwSvcGetter: mockcwSvc,
ecsSvcGetter: mockecsSvc,
svcDescriber: mockSvcDescriber,
aasSvcGetter: mockaasClient,
targetHealthGetter: mockTargetHealthGetter,
}
// WHEN
statusDesc, err := svcStatus.Describe()
// THEN
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedContent, statusDesc, "expected output content match")
}
})
}
}
func TestAppRunnerStatusDescriber_Describe(t *testing.T) {
appName := "testapp"
envName := "test"
svcName := "frontend"
updateTime := time.Unix(int64(1613145765), 0)
mockError := errors.New("some error")
mockAppRunnerService := apprunner.Service{
ServiceARN: "arn:aws:apprunner:us-west-2:1234567890:service/testapp-test-frontend/fc1098ac269245959ba78fd58bdd4bf",
Name: "testapp-test-frontend",
ID: "fc1098ac269245959ba78fd58bdd4bf",
Status: "RUNNING",
DateUpdated: updateTime,
}
logEvents := []*cloudwatchlogs.Event{
{
LogStreamName: "events",
Message: `[AppRunner] Service creation started.`,
},
}
testCases := map[string]struct {
setupMocks func(mocks serviceStatusDescriberMocks)
desc *appRunnerServiceStatus
wantedError error
wantedContent *appRunnerServiceStatus
}{
"errors if failed to describe a service": {
setupMocks: func(m serviceStatusDescriberMocks) {
gomock.InOrder(
m.appRunnerSvcDescriber.EXPECT().Service().Return(nil, mockError),
)
},
wantedError: fmt.Errorf("get App Runner service description for App Runner service frontend in environment test: some error"),
},
"success": {
setupMocks: func(m serviceStatusDescriberMocks) {
m.appRunnerSvcDescriber.EXPECT().Service().Return(&mockAppRunnerService, nil)
m.logGetter.EXPECT().LogEvents(cloudwatchlogs.LogEventsOpts{LogGroup: "/aws/apprunner/testapp-test-frontend/fc1098ac269245959ba78fd58bdd4bf/service", Limit: aws.Int64(10)}).Return(&cloudwatchlogs.LogEventsOutput{
Events: logEvents,
}, nil)
},
wantedContent: &appRunnerServiceStatus{
Service: mockAppRunnerService,
LogEvents: logEvents,
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockSvcDesc := mocks.NewMockapprunnerDescriber(ctrl)
mockLogsSvc := mocks.NewMocklogGetter(ctrl)
mocks := serviceStatusDescriberMocks{
appRunnerSvcDescriber: mockSvcDesc,
logGetter: mockLogsSvc,
}
tc.setupMocks(mocks)
svcStatus := &appRunnerStatusDescriber{
app: appName,
env: envName,
svc: svcName,
svcDescriber: mockSvcDesc,
eventsGetter: mockLogsSvc,
}
statusDesc, err := svcStatus.Describe()
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedContent, statusDesc, "expected output content match")
}
})
}
}
func TestStaticSiteStatusDescriber_Describe(t *testing.T) {
appName := "testapp"
envName := "test"
svcName := "frontend"
mockBucket := "jimmyBuckets"
mockError := errors.New("some error")
testCases := map[string]struct {
setupMocks func(mocks serviceStatusDescriberMocks)
desc *staticSiteServiceStatus
wantedError error
wantedContent *staticSiteServiceStatus
}{
"success": {
setupMocks: func(m serviceStatusDescriberMocks) {
m.s3Client.EXPECT().BucketName(appName, envName, svcName).Return(mockBucket, nil)
m.bucketDataGetter.EXPECT().BucketSizeAndCount(mockBucket).Return("mockSize", 123, nil)
},
wantedContent: &staticSiteServiceStatus{
BucketName: mockBucket,
Size: "mockSize",
Count: 123,
},
},
"error getting bucket name": {
setupMocks: func(m serviceStatusDescriberMocks) {
m.s3Client.EXPECT().BucketName(appName, envName, svcName).Return("", mockError)
},
wantedError: fmt.Errorf(`get bucket name for "frontend" Static Site service in "test" environment: %w`, mockError),
},
"error getting bucket size and count": {
setupMocks: func(m serviceStatusDescriberMocks) {
m.s3Client.EXPECT().BucketName(appName, envName, svcName).Return(mockBucket, nil)
m.bucketDataGetter.EXPECT().BucketSizeAndCount(mockBucket).Return("", 0, mockError)
},
wantedError: fmt.Errorf(`get size and count data for "jimmyBuckets" S3 bucket: %w`, mockError),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
//mockSvcDesc := mocks.NewMockstaticSiteDescriber(ctrl)
mocks := serviceStatusDescriberMocks{
s3Client: mocks.NewMockbucketNameGetter(ctrl),
bucketDataGetter: mocks.NewMockbucketDataGetter(ctrl),
}
tc.setupMocks(mocks)
d := &staticSiteStatusDescriber{
app: appName,
env: envName,
svc: svcName,
initS3Client: func(string) (bucketDataGetter, bucketNameGetter, error) {
return mocks.bucketDataGetter, mocks.s3Client, nil
},
}
statusDesc, err := d.Describe()
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedContent, statusDesc, "expected output content match")
}
})
}
}
func Test_targetHealthForTasks(t *testing.T) {
testCases := map[string]struct {
inTargetsHealth []*elbv2.TargetHealth
inTasks []*awsecs.Task
inTargetGroupARN string
wanted []taskTargetHealth
}{
"include target health in output even if it's not matchable to a task": {
inTargetsHealth: []*elbv2.TargetHealth{
{
Target: &elbv2api.TargetDescription{
Id: aws.String("42.42.42.42"),
},
TargetHealth: &elbv2api.TargetHealth{},
},
{
Target: &elbv2api.TargetDescription{
Id: aws.String("24.24.24.24"),
},
TargetHealth: &elbv2api.TargetHealth{},
},
},
inTasks: []*awsecs.Task{
{
TaskArn: aws.String("arn:aws:ecs:us-west-2:123456789012:task/mockCluster/task-with-private-ip-being-target"),
Attachments: []*ecsapi.Attachment{
{
Type: aws.String("ElasticNetworkInterface"),
Details: []*ecsapi.KeyValuePair{
{
Name: aws.String("privateIPv4Address"),
Value: aws.String("1.2.3.4"),
},
},
},
},
},
{
TaskArn: aws.String("arn:aws:ecs:us-west-2:123456789012:task/mockCluster/task-with-private-ip-being-target"),
Attachments: []*ecsapi.Attachment{
{
Type: aws.String("ElasticNetworkInterface"),
Details: []*ecsapi.KeyValuePair{
{
Name: aws.String("privateIPv4Address"),
Value: aws.String("4.3.2.1"),
},
},
},
},
},
},
inTargetGroupARN: "group-1",
wanted: []taskTargetHealth{
{
HealthStatus: elbv2.HealthStatus{
TargetID: "42.42.42.42",
},
TargetGroupARN: "group-1",
},
{
HealthStatus: elbv2.HealthStatus{
TargetID: "24.24.24.24",
},
TargetGroupARN: "group-1",
},
},
},
"target health should be matched to a task if applicable": {
inTargetsHealth: []*elbv2.TargetHealth{
{
Target: &elbv2api.TargetDescription{
Id: aws.String("42.42.42.42"),
},
TargetHealth: &elbv2api.TargetHealth{
Description: aws.String("unhealthy because this and that"),
State: aws.String("unhealthy"),
Reason: aws.String("Target.Timeout"),
},
},
{
Target: &elbv2api.TargetDescription{
Id: aws.String("24.24.24.24"),
},
TargetHealth: &elbv2api.TargetHealth{
State: aws.String("healthy"),
},
},
},
inTasks: []*awsecs.Task{
{
TaskArn: aws.String("arn:aws:ecs:us-west-2:123456789012:task/mockCluster/task-with-private-ip-being-target"),
Attachments: []*ecsapi.Attachment{
{
Type: aws.String("ElasticNetworkInterface"),
Details: []*ecsapi.KeyValuePair{
{
Name: aws.String("privateIPv4Address"),
Value: aws.String("42.42.42.42"),
},
},
},
},
},
{
TaskArn: aws.String("arn:aws:ecs:us-west-2:123456789012:task/mockCluster/not-target"),
Attachments: []*ecsapi.Attachment{
{
Type: aws.String("ElasticNetworkInterface"),
Details: []*ecsapi.KeyValuePair{
{
Name: aws.String("privateIPv4Address"),
Value: aws.String("4.3.2.1"),
},
},
},
},
},
},
inTargetGroupARN: "group-1",
wanted: []taskTargetHealth{
{
TaskID: "task-with-private-ip-being-target",
HealthStatus: elbv2.HealthStatus{
TargetID: "42.42.42.42",
HealthReason: "Target.Timeout",
HealthState: "unhealthy",
HealthDescription: "unhealthy because this and that",
},
TargetGroupARN: "group-1",
},
{
TaskID: "",
HealthStatus: elbv2.HealthStatus{
TargetID: "24.24.24.24",
HealthState: "healthy",
},
TargetGroupARN: "group-1",
},
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
got := targetHealthForTasks(tc.inTargetsHealth, tc.inTasks, tc.inTargetGroupARN)
require.Equal(t, tc.wanted, got)
})
}
}
| 995 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package describe
import (
"testing"
"time"
"github.com/aws/copilot-cli/internal/pkg/aws/apprunner"
"github.com/aws/copilot-cli/internal/pkg/aws/cloudwatch"
"github.com/aws/copilot-cli/internal/pkg/aws/cloudwatchlogs"
awsecs "github.com/aws/copilot-cli/internal/pkg/aws/ecs"
"github.com/aws/copilot-cli/internal/pkg/aws/elbv2"
"github.com/aws/copilot-cli/internal/pkg/term/progress"
"github.com/dustin/go-humanize"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
func TestServiceStatusDesc_String(t *testing.T) {
// from the function changes (ex: from "1 month ago" to "2 months ago"). To make our tests stable,
oldHumanize := humanizeTime
humanizeTime = func(then time.Time) string {
now, _ := time.Parse(time.RFC3339, "2020-01-01T00:00:00+00:00")
return humanize.RelTime(then, now, "ago", "from now")
}
defer func() {
humanizeTime = oldHumanize
}()
updateTime, _ := time.Parse(time.RFC3339, "2020-03-13T19:50:30+00:00")
stoppedTime, _ := time.Parse(time.RFC3339, "2020-03-13T20:00:30+00:00")
testCases := map[string]struct {
desc *ecsServiceStatus
setUpMockBarRenderer func(length int, data []int, representations []string, emptyRepresentation string) (progress.Renderer, error)
human string
json string
}{
"while provisioning (some primary, some active)": {
desc: &ecsServiceStatus{
Service: awsecs.ServiceStatus{
DesiredCount: 10,
RunningCount: 3,
Status: "ACTIVE",
Deployments: []awsecs.Deployment{
{
Id: "active-1",
DesiredCount: 1,
RunningCount: 1,
Status: "ACTIVE",
TaskDefinition: "arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:5",
},
{
Id: "active-2",
DesiredCount: 2,
RunningCount: 1,
Status: "ACTIVE",
TaskDefinition: "arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:4",
},
{
Id: "id-4",
DesiredCount: 10,
RunningCount: 1,
Status: "PRIMARY",
TaskDefinition: "arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:6",
},
{
Id: "id-5",
Status: "INACTIVE",
},
},
},
Alarms: []cloudwatch.AlarmStatus{
{
Arn: "mockAlarmArn1",
Name: "mySupercalifragilisticexpialidociousAlarm",
Condition: "RequestCount > 100.00 for 3 datapoints within 25 minutes",
Status: "OK",
Type: "Auto Scaling",
UpdatedTimes: updateTime,
},
{
Arn: "mockAlarmArn2",
Name: "Um-dittle-ittl-um-dittle-I-Alarm",
Condition: "CPUUtilization > 70.00 for 3 datapoints within 3 minutes",
Status: "OK",
Type: "Rollback",
UpdatedTimes: updateTime,
},
},
DesiredRunningTasks: []awsecs.TaskStatus{
{
Health: "HEALTHY",
LastStatus: "RUNNING",
ID: "111111111111111",
TaskDefinition: "arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:5",
},
{
Health: "UNKNOWN",
LastStatus: "RUNNING",
ID: "111111111111111",
TaskDefinition: "arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:4",
},
{
Health: "HEALTHY",
LastStatus: "PROVISIONING",
ID: "1234567890123456789",
TaskDefinition: "arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:6",
},
},
},
human: `Task Summary
Running ██████████ 3/10 desired tasks are running
Deployments █░░░░░░░░░ 1/10 running tasks for primary (rev 6)
██████████ 1/1 running tasks for active (rev 5)
█████░░░░░ 1/2 running tasks for active (rev 4)
Health █░░░░░░░░░ 1/10 passes container health checks (rev 6)
Tasks
ID Status Revision Started At Cont. Health
-- ------ -------- ---------- ------------
11111111 RUNNING 5 - HEALTHY
11111111 RUNNING 4 - UNKNOWN
12345678 PROVISIONING 6 - HEALTHY
Alarms
Name Type Condition Last Updated Health
---- ---- --------- ------------ ------
mySupercalifragilisticexpialid Auto Scaling RequestCount > 100.00 for 3 da 2 months from now OK
ociousAlarm tapoints within 25 minutes
Um-dittle-ittl-um-dittle-I-Ala Rollback CPUUtilization > 70.00 for 3 d 2 months from now OK
rm atapoints within 3 minutes
`,
json: `{"Service":{"desiredCount":10,"runningCount":3,"status":"ACTIVE","deployments":[{"id":"active-1","desiredCount":1,"runningCount":1,"updatedAt":"0001-01-01T00:00:00Z","launchType":"","taskDefinition":"arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:5","status":"ACTIVE"},{"id":"active-2","desiredCount":2,"runningCount":1,"updatedAt":"0001-01-01T00:00:00Z","launchType":"","taskDefinition":"arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:4","status":"ACTIVE"},{"id":"id-4","desiredCount":10,"runningCount":1,"updatedAt":"0001-01-01T00:00:00Z","launchType":"","taskDefinition":"arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:6","status":"PRIMARY"},{"id":"id-5","desiredCount":0,"runningCount":0,"updatedAt":"0001-01-01T00:00:00Z","launchType":"","taskDefinition":"","status":"INACTIVE"}],"lastDeploymentAt":"0001-01-01T00:00:00Z","taskDefinition":""},"tasks":[{"health":"HEALTHY","id":"111111111111111","images":null,"lastStatus":"RUNNING","startedAt":"0001-01-01T00:00:00Z","stoppedAt":"0001-01-01T00:00:00Z","stoppedReason":"","capacityProvider":"","taskDefinitionARN":"arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:5"},{"health":"UNKNOWN","id":"111111111111111","images":null,"lastStatus":"RUNNING","startedAt":"0001-01-01T00:00:00Z","stoppedAt":"0001-01-01T00:00:00Z","stoppedReason":"","capacityProvider":"","taskDefinitionARN":"arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:4"},{"health":"HEALTHY","id":"1234567890123456789","images":null,"lastStatus":"PROVISIONING","startedAt":"0001-01-01T00:00:00Z","stoppedAt":"0001-01-01T00:00:00Z","stoppedReason":"","capacityProvider":"","taskDefinitionARN":"arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:6"}],"alarms":[{"arn":"mockAlarmArn1","name":"mySupercalifragilisticexpialidociousAlarm","condition":"RequestCount \u003e 100.00 for 3 datapoints within 25 minutes","status":"OK","type":"Auto Scaling","updatedTimes":"2020-03-13T19:50:30Z"},{"arn":"mockAlarmArn2","name":"Um-dittle-ittl-um-dittle-I-Alarm","condition":"CPUUtilization \u003e 70.00 for 3 datapoints within 3 minutes","status":"OK","type":"Rollback","updatedTimes":"2020-03-13T19:50:30Z"}],"stoppedTasks":null,"targetHealthDescriptions":null}
`,
},
"while running with both health check (all primary)": {
desc: &ecsServiceStatus{
Service: awsecs.ServiceStatus{
DesiredCount: 3,
RunningCount: 3,
Status: "ACTIVE",
Deployments: []awsecs.Deployment{
{
Status: "PRIMARY",
TaskDefinition: "arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:6",
DesiredCount: 3,
RunningCount: 3,
},
},
},
DesiredRunningTasks: []awsecs.TaskStatus{
{
Health: "HEALTHY",
LastStatus: "RUNNING",
ID: "111111111111111",
TaskDefinition: "arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:6",
},
{
Health: "UNHEALTHY",
LastStatus: "RUNNING",
ID: "2222222222222222",
TaskDefinition: "arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:6",
},
{
Health: "HEALTHY",
LastStatus: "PROVISIONING",
ID: "3333333333333333",
TaskDefinition: "arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:6",
},
},
TargetHealthDescriptions: []taskTargetHealth{
{
HealthStatus: elbv2.HealthStatus{
TargetID: "1.1.1.1",
HealthState: "unhealthy",
HealthReason: "some reason",
},
TaskID: "111111111111111",
TargetGroupARN: "group-1",
},
{
HealthStatus: elbv2.HealthStatus{
TargetID: "2.2.2.2",
HealthState: "healthy",
},
TaskID: "2222222222222222",
TargetGroupARN: "group-1",
},
{
HealthStatus: elbv2.HealthStatus{
TargetID: "3.3.3.3",
HealthState: "healthy",
},
TaskID: "3333333333333333",
TargetGroupARN: "group-1",
},
{
HealthStatus: elbv2.HealthStatus{
TargetID: "4.4.4.4",
HealthState: "healthy",
},
TaskID: "",
TargetGroupARN: "group-1",
},
},
},
human: `Task Summary
Running ██████████ 3/3 desired tasks are running
Health ███████░░░ 2/3 passes HTTP health checks
███████░░░ 2/3 passes container health checks
Tasks
ID Status Revision Started At Cont. Health HTTP Health
-- ------ -------- ---------- ------------ -----------
11111111 RUNNING 6 - HEALTHY UNHEALTHY
22222222 RUNNING 6 - UNHEALTHY HEALTHY
33333333 PROVISIONING 6 - HEALTHY HEALTHY
`,
json: `{"Service":{"desiredCount":3,"runningCount":3,"status":"ACTIVE","deployments":[{"id":"","desiredCount":3,"runningCount":3,"updatedAt":"0001-01-01T00:00:00Z","launchType":"","taskDefinition":"arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:6","status":"PRIMARY"}],"lastDeploymentAt":"0001-01-01T00:00:00Z","taskDefinition":""},"tasks":[{"health":"HEALTHY","id":"111111111111111","images":null,"lastStatus":"RUNNING","startedAt":"0001-01-01T00:00:00Z","stoppedAt":"0001-01-01T00:00:00Z","stoppedReason":"","capacityProvider":"","taskDefinitionARN":"arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:6"},{"health":"UNHEALTHY","id":"2222222222222222","images":null,"lastStatus":"RUNNING","startedAt":"0001-01-01T00:00:00Z","stoppedAt":"0001-01-01T00:00:00Z","stoppedReason":"","capacityProvider":"","taskDefinitionARN":"arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:6"},{"health":"HEALTHY","id":"3333333333333333","images":null,"lastStatus":"PROVISIONING","startedAt":"0001-01-01T00:00:00Z","stoppedAt":"0001-01-01T00:00:00Z","stoppedReason":"","capacityProvider":"","taskDefinitionARN":"arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:6"}],"alarms":null,"stoppedTasks":null,"targetHealthDescriptions":[{"healthStatus":{"targetID":"1.1.1.1","description":"","state":"unhealthy","reason":"some reason"},"taskID":"111111111111111","targetGroup":"group-1"},{"healthStatus":{"targetID":"2.2.2.2","description":"","state":"healthy","reason":""},"taskID":"2222222222222222","targetGroup":"group-1"},{"healthStatus":{"targetID":"3.3.3.3","description":"","state":"healthy","reason":""},"taskID":"3333333333333333","targetGroup":"group-1"},{"healthStatus":{"targetID":"4.4.4.4","description":"","state":"healthy","reason":""},"taskID":"","targetGroup":"group-1"}]}
`,
},
"while some tasks are stopping": {
desc: &ecsServiceStatus{
Service: awsecs.ServiceStatus{
DesiredCount: 5,
RunningCount: 3,
Status: "ACTIVE",
Deployments: []awsecs.Deployment{
{
Status: "PRIMARY",
TaskDefinition: "arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:6",
DesiredCount: 5,
RunningCount: 3,
},
},
},
DesiredRunningTasks: []awsecs.TaskStatus{
{
Health: "HEALTHY",
LastStatus: "RUNNING",
ID: "111111111111111",
TaskDefinition: "arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:6",
},
{
Health: "UNHEALTHY",
LastStatus: "RUNNING",
ID: "2222222222222222",
TaskDefinition: "arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:6",
},
{
Health: "HEALTHY",
LastStatus: "PROVISIONING",
ID: "3333333333333333",
TaskDefinition: "arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:6",
},
},
StoppedTasks: []awsecs.TaskStatus{
{
LastStatus: "DEPROVISIONING",
ID: "S111111111111",
StoppedAt: stoppedTime,
Images: []awsecs.Image{},
StoppedReason: "April-is-the-cruellest-month-breeding-Lilacs-out-of-the-dead-land-m",
},
{
LastStatus: "DEPROVISIONING",
ID: "S2222222222222",
StoppedAt: stoppedTime,
Images: []awsecs.Image{},
StoppedReason: "April-is-the-cruellest-month-breeding-Lilacs-out-of-the-dead-land-m",
},
{
LastStatus: "DEPROVISIONING",
ID: "S333333333333333",
StoppedAt: stoppedTime,
Images: []awsecs.Image{},
StoppedReason: "April-is-the-cruellest-month-breeding-Lilacs-out-of-the-dead-land-m",
},
{
LastStatus: "DEPROVISIONING",
ID: "S44444444444",
StoppedAt: stoppedTime,
Images: []awsecs.Image{},
StoppedReason: "April-is-the-cruellest-month-breeding-Lilacs-out-of-the-dead-land-m",
},
{
LastStatus: "DEPROVISIONING",
ID: "S55555555555555",
StoppedAt: stoppedTime,
Images: []awsecs.Image{},
StoppedReason: "April-is-the-cruellest-month-breeding-Lilacs-out-of-the-dead-land-m",
},
{
LastStatus: "DEPROVISIONING",
ID: "S66666666666666",
StoppedAt: stoppedTime,
Images: []awsecs.Image{},
StoppedReason: "April-is-the-cruellest-month-breeding-Lilacs-out-of-the-dead-land-m",
},
},
},
human: `Task Summary
Running ██████░░░░ 3/5 desired tasks are running
Health ████░░░░░░ 2/5 passes container health checks
Stopped Tasks
Reason Task Count Sample Task IDs
------ ---------- ---------------
April-is-the-cruellest-month-b 6 S1111111,S2222222,S3333333,S44
reeding-Lilacs-out-of-the-dead 44444,S5555555
-land-m
Tasks
ID Status Revision Started At Cont. Health
-- ------ -------- ---------- ------------
11111111 RUNNING 6 - HEALTHY
22222222 RUNNING 6 - UNHEALTHY
33333333 PROVISIONING 6 - HEALTHY
`,
json: `{"Service":{"desiredCount":5,"runningCount":3,"status":"ACTIVE","deployments":[{"id":"","desiredCount":5,"runningCount":3,"updatedAt":"0001-01-01T00:00:00Z","launchType":"","taskDefinition":"arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:6","status":"PRIMARY"}],"lastDeploymentAt":"0001-01-01T00:00:00Z","taskDefinition":""},"tasks":[{"health":"HEALTHY","id":"111111111111111","images":null,"lastStatus":"RUNNING","startedAt":"0001-01-01T00:00:00Z","stoppedAt":"0001-01-01T00:00:00Z","stoppedReason":"","capacityProvider":"","taskDefinitionARN":"arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:6"},{"health":"UNHEALTHY","id":"2222222222222222","images":null,"lastStatus":"RUNNING","startedAt":"0001-01-01T00:00:00Z","stoppedAt":"0001-01-01T00:00:00Z","stoppedReason":"","capacityProvider":"","taskDefinitionARN":"arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:6"},{"health":"HEALTHY","id":"3333333333333333","images":null,"lastStatus":"PROVISIONING","startedAt":"0001-01-01T00:00:00Z","stoppedAt":"0001-01-01T00:00:00Z","stoppedReason":"","capacityProvider":"","taskDefinitionARN":"arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:6"}],"alarms":null,"stoppedTasks":[{"health":"","id":"S111111111111","images":[],"lastStatus":"DEPROVISIONING","startedAt":"0001-01-01T00:00:00Z","stoppedAt":"2020-03-13T20:00:30Z","stoppedReason":"April-is-the-cruellest-month-breeding-Lilacs-out-of-the-dead-land-m","capacityProvider":"","taskDefinitionARN":""},{"health":"","id":"S2222222222222","images":[],"lastStatus":"DEPROVISIONING","startedAt":"0001-01-01T00:00:00Z","stoppedAt":"2020-03-13T20:00:30Z","stoppedReason":"April-is-the-cruellest-month-breeding-Lilacs-out-of-the-dead-land-m","capacityProvider":"","taskDefinitionARN":""},{"health":"","id":"S333333333333333","images":[],"lastStatus":"DEPROVISIONING","startedAt":"0001-01-01T00:00:00Z","stoppedAt":"2020-03-13T20:00:30Z","stoppedReason":"April-is-the-cruellest-month-breeding-Lilacs-out-of-the-dead-land-m","capacityProvider":"","taskDefinitionARN":""},{"health":"","id":"S44444444444","images":[],"lastStatus":"DEPROVISIONING","startedAt":"0001-01-01T00:00:00Z","stoppedAt":"2020-03-13T20:00:30Z","stoppedReason":"April-is-the-cruellest-month-breeding-Lilacs-out-of-the-dead-land-m","capacityProvider":"","taskDefinitionARN":""},{"health":"","id":"S55555555555555","images":[],"lastStatus":"DEPROVISIONING","startedAt":"0001-01-01T00:00:00Z","stoppedAt":"2020-03-13T20:00:30Z","stoppedReason":"April-is-the-cruellest-month-breeding-Lilacs-out-of-the-dead-land-m","capacityProvider":"","taskDefinitionARN":""},{"health":"","id":"S66666666666666","images":[],"lastStatus":"DEPROVISIONING","startedAt":"0001-01-01T00:00:00Z","stoppedAt":"2020-03-13T20:00:30Z","stoppedReason":"April-is-the-cruellest-month-breeding-Lilacs-out-of-the-dead-land-m","capacityProvider":"","taskDefinitionARN":""}],"targetHealthDescriptions":null}
`,
},
"while running without health check": {
desc: &ecsServiceStatus{
Service: awsecs.ServiceStatus{
DesiredCount: 3,
RunningCount: 2,
Status: "ACTIVE",
},
DesiredRunningTasks: []awsecs.TaskStatus{
{
Health: "UNKNOWN",
LastStatus: "RUNNING",
ID: "1111111111111111",
},
{
Health: "UNKNOWN",
LastStatus: "RUNNING",
ID: "2222222222222222",
},
},
},
human: `Task Summary
Running ███████░░░ 2/3 desired tasks are running
Tasks
ID Status Revision Started At
-- ------ -------- ----------
11111111 RUNNING - -
22222222 RUNNING - -
`,
json: `{"Service":{"desiredCount":3,"runningCount":2,"status":"ACTIVE","deployments":null,"lastDeploymentAt":"0001-01-01T00:00:00Z","taskDefinition":""},"tasks":[{"health":"UNKNOWN","id":"1111111111111111","images":null,"lastStatus":"RUNNING","startedAt":"0001-01-01T00:00:00Z","stoppedAt":"0001-01-01T00:00:00Z","stoppedReason":"","capacityProvider":"","taskDefinitionARN":""},{"health":"UNKNOWN","id":"2222222222222222","images":null,"lastStatus":"RUNNING","startedAt":"0001-01-01T00:00:00Z","stoppedAt":"0001-01-01T00:00:00Z","stoppedReason":"","capacityProvider":"","taskDefinitionARN":""}],"alarms":null,"stoppedTasks":null,"targetHealthDescriptions":null}
`,
},
"should hide HTTP health from summary if no primary task has HTTP check": {
desc: &ecsServiceStatus{
Service: awsecs.ServiceStatus{
DesiredCount: 10,
RunningCount: 3,
Status: "ACTIVE",
Deployments: []awsecs.Deployment{
{
Id: "active-1",
DesiredCount: 1,
RunningCount: 1,
Status: "ACTIVE",
TaskDefinition: "arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:5",
},
{
Id: "active-2",
DesiredCount: 2,
RunningCount: 1,
Status: "ACTIVE",
TaskDefinition: "arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:4",
},
{
Id: "primary",
DesiredCount: 10,
RunningCount: 1,
Status: "PRIMARY",
TaskDefinition: "arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:6",
},
},
},
DesiredRunningTasks: []awsecs.TaskStatus{
{
Health: "HEALTHY",
LastStatus: "RUNNING",
ID: "111111111111111",
TaskDefinition: "arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:5",
},
{
Health: "UNKNOWN",
LastStatus: "RUNNING",
ID: "22222222222222",
TaskDefinition: "arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:4",
},
{
Health: "HEALTHY",
LastStatus: "PROVISIONING",
ID: "3333333333333",
TaskDefinition: "arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:6",
},
},
TargetHealthDescriptions: []taskTargetHealth{
{
HealthStatus: elbv2.HealthStatus{
TargetID: "1.1.1.1",
HealthState: "unhealthy",
HealthReason: "some reason",
},
TaskID: "111111111111111",
TargetGroupARN: "health check for active",
},
{
HealthStatus: elbv2.HealthStatus{
TargetID: "2.2.2.2",
HealthState: "healthy",
},
TaskID: "22222222222222",
TargetGroupARN: "health check for active",
},
},
},
human: `Task Summary
Running ██████████ 3/10 desired tasks are running
Deployments █░░░░░░░░░ 1/10 running tasks for primary (rev 6)
██████████ 1/1 running tasks for active (rev 5)
█████░░░░░ 1/2 running tasks for active (rev 4)
Health █░░░░░░░░░ 1/10 passes container health checks (rev 6)
Tasks
ID Status Revision Started At Cont. Health HTTP Health
-- ------ -------- ---------- ------------ -----------
11111111 RUNNING 5 - HEALTHY UNHEALTHY
22222222 RUNNING 4 - UNKNOWN HEALTHY
33333333 PROVISIONING 6 - HEALTHY -
`,
json: `{"Service":{"desiredCount":10,"runningCount":3,"status":"ACTIVE","deployments":[{"id":"active-1","desiredCount":1,"runningCount":1,"updatedAt":"0001-01-01T00:00:00Z","launchType":"","taskDefinition":"arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:5","status":"ACTIVE"},{"id":"active-2","desiredCount":2,"runningCount":1,"updatedAt":"0001-01-01T00:00:00Z","launchType":"","taskDefinition":"arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:4","status":"ACTIVE"},{"id":"primary","desiredCount":10,"runningCount":1,"updatedAt":"0001-01-01T00:00:00Z","launchType":"","taskDefinition":"arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:6","status":"PRIMARY"}],"lastDeploymentAt":"0001-01-01T00:00:00Z","taskDefinition":""},"tasks":[{"health":"HEALTHY","id":"111111111111111","images":null,"lastStatus":"RUNNING","startedAt":"0001-01-01T00:00:00Z","stoppedAt":"0001-01-01T00:00:00Z","stoppedReason":"","capacityProvider":"","taskDefinitionARN":"arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:5"},{"health":"UNKNOWN","id":"22222222222222","images":null,"lastStatus":"RUNNING","startedAt":"0001-01-01T00:00:00Z","stoppedAt":"0001-01-01T00:00:00Z","stoppedReason":"","capacityProvider":"","taskDefinitionARN":"arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:4"},{"health":"HEALTHY","id":"3333333333333","images":null,"lastStatus":"PROVISIONING","startedAt":"0001-01-01T00:00:00Z","stoppedAt":"0001-01-01T00:00:00Z","stoppedReason":"","capacityProvider":"","taskDefinitionARN":"arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:6"}],"alarms":null,"stoppedTasks":null,"targetHealthDescriptions":[{"healthStatus":{"targetID":"1.1.1.1","description":"","state":"unhealthy","reason":"some reason"},"taskID":"111111111111111","targetGroup":"health check for active"},{"healthStatus":{"targetID":"2.2.2.2","description":"","state":"healthy","reason":""},"taskID":"22222222222222","targetGroup":"health check for active"}]}
`,
},
"while running with capacity providers": {
desc: &ecsServiceStatus{
Service: awsecs.ServiceStatus{
DesiredCount: 4,
RunningCount: 3,
Status: "ACTIVE",
},
DesiredRunningTasks: []awsecs.TaskStatus{
{
Health: "UNKNOWN",
LastStatus: "RUNNING",
ID: "11111111111111111",
Images: []awsecs.Image{},
CapacityProvider: "FARGATE_SPOT",
},
{
Health: "UNKNOWN",
LastStatus: "RUNNING",
ID: "22222222222222",
Images: []awsecs.Image{},
CapacityProvider: "FARGATE",
},
{
Health: "UNKNOWN",
LastStatus: "RUNNING",
ID: "333333333333",
Images: []awsecs.Image{},
CapacityProvider: "",
},
{
Health: "UNKNOWN",
LastStatus: "ACTIVATING",
ID: "444444444444",
Images: []awsecs.Image{},
CapacityProvider: "",
},
},
},
human: `Task Summary
Running ████████░░ 3/4 desired tasks are running
Capacity Provider â–’â–’â–’â–’â–’â–’â–’â–“â–“â–“ 2/3 on Fargate, 1/3 on Fargate Spot
Tasks
ID Status Revision Started At Capacity
-- ------ -------- ---------- --------
11111111 RUNNING - - FARGATE_SPOT
22222222 RUNNING - - FARGATE
33333333 RUNNING - - FARGATE (Launch type)
44444444 ACTIVATING - - FARGATE (Launch type)
`,
json: `{"Service":{"desiredCount":4,"runningCount":3,"status":"ACTIVE","deployments":null,"lastDeploymentAt":"0001-01-01T00:00:00Z","taskDefinition":""},"tasks":[{"health":"UNKNOWN","id":"11111111111111111","images":[],"lastStatus":"RUNNING","startedAt":"0001-01-01T00:00:00Z","stoppedAt":"0001-01-01T00:00:00Z","stoppedReason":"","capacityProvider":"FARGATE_SPOT","taskDefinitionARN":""},{"health":"UNKNOWN","id":"22222222222222","images":[],"lastStatus":"RUNNING","startedAt":"0001-01-01T00:00:00Z","stoppedAt":"0001-01-01T00:00:00Z","stoppedReason":"","capacityProvider":"FARGATE","taskDefinitionARN":""},{"health":"UNKNOWN","id":"333333333333","images":[],"lastStatus":"RUNNING","startedAt":"0001-01-01T00:00:00Z","stoppedAt":"0001-01-01T00:00:00Z","stoppedReason":"","capacityProvider":"","taskDefinitionARN":""},{"health":"UNKNOWN","id":"444444444444","images":[],"lastStatus":"ACTIVATING","startedAt":"0001-01-01T00:00:00Z","stoppedAt":"0001-01-01T00:00:00Z","stoppedReason":"","capacityProvider":"","taskDefinitionARN":""}],"alarms":null,"stoppedTasks":null,"targetHealthDescriptions":null}
`,
},
"hide tasks section if there is no desired running task": {
desc: &ecsServiceStatus{
Service: awsecs.ServiceStatus{
DesiredCount: 0,
RunningCount: 0,
Status: "ACTIVE",
Deployments: []awsecs.Deployment{
{
Id: "id-4",
DesiredCount: 0,
RunningCount: 0,
Status: "PRIMARY",
TaskDefinition: "arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:6",
},
},
},
DesiredRunningTasks: []awsecs.TaskStatus{},
},
human: `Task Summary
Running â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘ 0/0 desired tasks are running
`,
json: `{"Service":{"desiredCount":0,"runningCount":0,"status":"ACTIVE","deployments":[{"id":"id-4","desiredCount":0,"runningCount":0,"updatedAt":"0001-01-01T00:00:00Z","launchType":"","taskDefinition":"arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:6","status":"PRIMARY"}],"lastDeploymentAt":"0001-01-01T00:00:00Z","taskDefinition":""},"tasks":[],"alarms":null,"stoppedTasks":null,"targetHealthDescriptions":null}
`,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
json, err := tc.desc.JSONString()
require.NoError(t, err)
require.Equal(t, tc.json, json)
human := tc.desc.HumanString()
require.Equal(t, tc.human, human)
})
}
}
func TestServiceStatusDesc_AppRunnerServiceString(t *testing.T) {
oldHumanize := humanizeTime
humanizeTime = func(then time.Time) string {
now, _ := time.Parse(time.RFC3339, "2020-01-01T00:00:00+00:00")
return humanize.RelTime(then, now, "from now", "ago")
}
defer func() {
humanizeTime = oldHumanize
}()
createTime, _ := time.Parse(time.RFC3339, "2020-01-01T00:00:00+00:00")
updateTime, _ := time.Parse(time.RFC3339, "2020-03-01T00:00:00+00:00")
logEvents := []*cloudwatchlogs.Event{
{
LogStreamName: "events",
Message: `[AppRunner] Service creation started.`,
Timestamp: 1621365985294,
},
}
testCases := map[string]struct {
desc *appRunnerServiceStatus
human string
json string
}{
"RUNNING": {
desc: &appRunnerServiceStatus{
Service: apprunner.Service{
Name: "frontend",
ID: "8a2b343f658144d885e47d10adb4845e",
ServiceARN: "arn:aws:apprunner:us-east-1:1111:service/frontend/8a2b343f658144d885e47d10adb4845e",
Status: "RUNNING",
DateCreated: createTime,
DateUpdated: updateTime,
ImageID: "hello",
},
LogEvents: logEvents,
},
human: `Service Status
Status RUNNING
Last deployment
Updated At 2 months ago
Service ID frontend/8a2b343f658144d885e47d10adb4845e
Source hello
System Logs
2021-05-18T19:26:25Z [AppRunner] Service creation started.
`,
json: `{"arn":"arn:aws:apprunner:us-east-1:1111:service/frontend/8a2b343f658144d885e47d10adb4845e","status":"RUNNING","createdAt":"2020-01-01T00:00:00Z","updatedAt":"2020-03-01T00:00:00Z","source":{"imageId":"hello"}}` + "\n",
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
json, err := tc.desc.JSONString()
require.NoError(t, err)
require.Equal(t, tc.human, tc.desc.HumanString())
require.Equal(t, tc.json, json)
})
}
}
func TestServiceStatusDesc_StaticSiteServiceString(t *testing.T) {
testCases := map[string]struct {
desc *staticSiteServiceStatus
human string
json string
}{
"success": {
desc: &staticSiteServiceStatus{
BucketName: "Jimmy Buckets",
Size: "999 MB",
Count: 22,
},
human: `Bucket Summary
Bucket Name Jimmy Buckets
Total Objects 22
Total Size 999 MB
`,
json: `{"bucketName":"Jimmy Buckets","totalSize":"999 MB","totalObjects":22}` + "\n",
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
json, err := tc.desc.JSONString()
require.NoError(t, err)
require.Equal(t, tc.human, tc.desc.HumanString())
require.Equal(t, tc.json, json)
})
}
}
func TestECSTaskStatus_humanString(t *testing.T) {
// from the function changes (ex: from "1 month ago" to "2 months ago"). To make our tests stable,
oldHumanize := humanizeTime
humanizeTime = func(then time.Time) string {
now, _ := time.Parse(time.RFC3339, "2020-01-01T00:00:00+00:00")
return humanize.RelTime(then, now, "ago", "from now")
}
defer func() {
humanizeTime = oldHumanize
}()
startTime, _ := time.Parse(time.RFC3339, "2006-01-02T15:04:05+00:00")
stopTime, _ := time.Parse(time.RFC3339, "2006-01-02T16:04:05+00:00")
mockImageDigest := "18f7eb6cff6e63e5f5273fb53f672975fe6044580f66c354f55d2de8dd28aec7"
testCases := map[string]struct {
id string
health string
lastStatus string
imageDigest string
startedAt time.Time
stoppedAt time.Time
capacityProvider string
taskDefinition string
inConfigs []ecsTaskStatusConfigOpts
wantTaskStatus string
}{
"show only basic fields": {
health: "HEALTHY",
id: "aslhfnqo39j8qomimvoiqm89349",
lastStatus: "RUNNING",
startedAt: startTime,
stoppedAt: stopTime,
imageDigest: mockImageDigest,
capacityProvider: "FARGATE",
taskDefinition: "arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:42",
wantTaskStatus: "aslhfnqo\tRUNNING\t42\t14 years ago",
},
"show all": {
health: "HEALTHY",
id: "aslhfnqo39j8qomimvoiqm89349",
lastStatus: "RUNNING",
startedAt: startTime,
stoppedAt: stopTime,
imageDigest: mockImageDigest,
capacityProvider: "FARGATE",
taskDefinition: "arn:aws:ecs:us-east-1:000000000000:task-definition/some-task-def:42",
inConfigs: []ecsTaskStatusConfigOpts{
withCapProviderShown,
withContainerHealthShow,
},
wantTaskStatus: "aslhfnqo\tRUNNING\t42\t14 years ago\tFARGATE\tHEALTHY",
},
"show all while having missing params": {
health: "HEALTHY",
lastStatus: "RUNNING",
inConfigs: []ecsTaskStatusConfigOpts{
withCapProviderShown,
withContainerHealthShow,
},
wantTaskStatus: "-\tRUNNING\t-\t-\tFARGATE (Launch type)\tHEALTHY",
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
task := ecsTaskStatus{
Health: tc.health,
ID: tc.id,
Images: []awsecs.Image{
{
Digest: tc.imageDigest,
},
},
LastStatus: tc.lastStatus,
StartedAt: tc.startedAt,
StoppedAt: tc.stoppedAt,
CapacityProvider: tc.capacityProvider,
TaskDefinition: tc.taskDefinition,
}
gotTaskStatus := task.humanString(tc.inConfigs...)
require.Equal(t, tc.wantTaskStatus, gotTaskStatus)
})
}
}
| 748 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package describe
import (
"fmt"
"strings"
"github.com/aws/copilot-cli/internal/pkg/term/color"
"github.com/dustin/go-humanize/english"
"github.com/aws/copilot-cli/internal/pkg/deploy/cloudformation/stack"
"github.com/aws/copilot-cli/internal/pkg/manifest/manifestinfo"
)
// URIAccessType represents how a URI can be accessed.
type URIAccessType int
// Supported URI Access Types.
const (
URIAccessTypeNone URIAccessType = iota
URIAccessTypeInternet
URIAccessTypeInternal
URIAccessTypeServiceDiscovery
URIAccessTypeServiceConnect
)
var (
fmtSvcDiscoveryEndpointWithPort = "%s.%s:%s" // Format string of the form {svc}.{endpoint}:{port}
)
// URI represents a uri and how it can be accessed.
type URI struct {
URI string
AccessType URIAccessType
}
// ReachableService represents a service describer that has an endpoint.
type ReachableService interface {
URI(env string) (URI, error)
}
// NewReachableService returns a ReachableService based on the type of the service.
func NewReachableService(app, svc string, store ConfigStoreSvc) (ReachableService, error) {
cfg, err := store.GetWorkload(app, svc)
if err != nil {
return nil, err
}
in := NewServiceConfig{
App: app,
Svc: svc,
ConfigStore: store,
}
switch cfg.Type {
case manifestinfo.LoadBalancedWebServiceType:
return NewLBWebServiceDescriber(in)
case manifestinfo.RequestDrivenWebServiceType:
return NewRDWebServiceDescriber(in)
case manifestinfo.BackendServiceType:
return NewBackendServiceDescriber(in)
case manifestinfo.StaticSiteType:
return NewStaticSiteDescriber(in)
default:
return nil, &ErrNonAccessibleServiceType{
name: svc,
svcType: cfg.Type,
}
}
}
// URI returns the LBWebServiceURI to identify this service uniquely given an environment name.
func (d *LBWebServiceDescriber) URI(envName string) (URI, error) {
svcDescr, err := d.initECSServiceDescribers(envName)
if err != nil {
return URI{}, err
}
envDescr, err := d.initEnvDescribers(envName)
if err != nil {
return URI{}, err
}
var albEnabled, nlbEnabled bool
resources, err := svcDescr.StackResources()
if err != nil {
return URI{}, fmt.Errorf("get stack resources for service %s: %w", d.svc, err)
}
for _, resource := range resources {
if strings.HasPrefix(resource.LogicalID, svcStackResourceALBTargetGroupLogicalID) {
albEnabled = true
}
if strings.HasPrefix(resource.LogicalID, svcStackResourceNLBTargetGroupLogicalID) {
nlbEnabled = true
}
}
var uri LBWebServiceURI
if albEnabled {
uriDescr := &uriDescriber{
svc: d.svc,
env: envName,
svcDescriber: svcDescr,
envDescriber: envDescr,
initLBDescriber: d.initLBDescriber,
albCFNOutputName: envOutputPublicLoadBalancerDNSName,
}
publicURI, err := uriDescr.uri()
if err != nil {
return URI{}, err
}
uri.access = publicURI
}
if nlbEnabled {
nlbURI, err := d.nlbURI(envName, svcDescr, envDescr)
if err != nil {
return URI{}, err
}
uri.nlbURI = nlbURI
}
return URI{
URI: uri.String(),
AccessType: URIAccessTypeInternet,
}, nil
}
func (d *LBWebServiceDescriber) nlbURI(envName string, svcDescr ecsDescriber, envDescr envDescriber) (nlbURI, error) {
svcParams, err := svcDescr.Params()
if err != nil {
return nlbURI{}, fmt.Errorf("get stack parameters for service %s: %w", d.svc, err)
}
port, ok := svcParams[stack.LBWebServiceNLBPortParamKey]
if !ok {
return nlbURI{}, nil
}
uri := nlbURI{
Port: port,
}
dnsDelegated, ok := svcParams[stack.LBWebServiceDNSDelegatedParamKey]
if !ok || dnsDelegated != "true" {
svcOutputs, err := svcDescr.Outputs()
if err != nil {
return nlbURI{}, fmt.Errorf("get stack outputs for service %s: %w", d.svc, err)
}
uri.DNSNames = []string{svcOutputs[svcOutputPublicNLBDNSName]}
return uri, nil
}
aliases, ok := svcParams[stack.LBWebServiceNLBAliasesParamKey]
if ok && aliases != "" {
uri.DNSNames = strings.Split(aliases, ",")
return uri, nil
}
envOutputs, err := envDescr.Outputs()
if err != nil {
return nlbURI{}, fmt.Errorf("get stack outputs for environment %s: %w", envName, err)
}
uri.DNSNames = []string{fmt.Sprintf("%s-nlb.%s", d.svc, envOutputs[envOutputSubdomain])}
return uri, nil
}
// URI returns the service discovery namespace and is used to make
// BackendServiceDescriber have the same signature as WebServiceDescriber.
func (d *BackendServiceDescriber) URI(envName string) (URI, error) {
svcDescr, err := d.initECSServiceDescribers(envName)
if err != nil {
return URI{}, err
}
envDescr, err := d.initEnvDescribers(envName)
if err != nil {
return URI{}, err
}
resources, err := svcDescr.StackResources()
if err != nil {
return URI{}, fmt.Errorf("get stack resources for service %s: %w", d.svc, err)
}
for _, res := range resources {
if res.LogicalID == svcStackResourceALBTargetGroupLogicalID {
uriDescr := &uriDescriber{
svc: d.svc,
env: envName,
svcDescriber: svcDescr,
envDescriber: envDescr,
initLBDescriber: d.initLBDescriber,
albCFNOutputName: envOutputInternalLoadBalancerDNSName,
}
privateURI, err := uriDescr.uri()
if err != nil {
return URI{}, err
}
if !privateURI.HTTPS && len(privateURI.DNSNames) > 1 {
privateURI = uriDescr.bestEffortRemoveALBDNSName(privateURI)
}
return URI{
URI: english.OxfordWordSeries(privateURI.strings(), "or"),
AccessType: URIAccessTypeInternal,
}, nil
}
}
svcStackParams, err := svcDescr.Params()
if err != nil {
return URI{}, fmt.Errorf("get stack parameters for environment %s: %w", envName, err)
}
if !isReachableWithinVPC(svcStackParams) {
return URI{
URI: BlankServiceDiscoveryURI,
AccessType: URIAccessTypeNone,
}, nil
}
scDNSNames, err := svcDescr.ServiceConnectDNSNames()
if err != nil {
return URI{}, fmt.Errorf("retrieve service connect DNS names: %w", err)
}
if len(scDNSNames) > 0 {
return URI{
URI: english.OxfordWordSeries(scDNSNames, "or"),
AccessType: URIAccessTypeServiceConnect,
}, nil
}
endpoint, err := envDescr.ServiceDiscoveryEndpoint()
if err != nil {
return URI{}, fmt.Errorf("retrieve service discovery endpoint for environment %s: %w", envName, err)
}
s := serviceDiscovery{
Service: d.svc,
Port: svcStackParams[stack.WorkloadTargetPortParamKey],
Endpoint: endpoint,
}
return URI{
URI: s.String(),
AccessType: URIAccessTypeServiceDiscovery,
}, nil
}
type uriDescriber struct {
svc string
env string
svcDescriber ecsDescriber
envDescriber envDescriber
initLBDescriber func(string) (lbDescriber, error)
albCFNOutputName string // The DNS name for the public or private ALB.
}
func (d *uriDescriber) envDNSName(path string) (accessURI, error) {
var dnsNames []string
envOutputs, err := d.envDescriber.Outputs()
if err != nil {
return accessURI{}, fmt.Errorf("get stack outputs for environment %s: %w", d.env, err)
}
// Backward compatibility concern since envOutputPublicALBAccessible didn't exist before,
// and public ALB DNS name previously was always accessible until the introduction of envOutputPublicALBAccessible.
if accessible, ok := envOutputs[envOutputPublicALBAccessible]; !ok || accessible == "true" {
dnsNames = append(dnsNames, envOutputs[d.albCFNOutputName])
}
if cfDNS, ok := envOutputs[envOutputCloudFrontDomainName]; ok {
dnsNames = append(dnsNames, cfDNS)
}
return accessURI{
DNSNames: dnsNames,
Path: path,
}, nil
}
func (d *uriDescriber) uri() (accessURI, error) {
svcParams, err := d.svcDescriber.Params()
if err != nil {
return accessURI{}, fmt.Errorf("get stack parameters for service %s: %w", d.svc, err)
}
path := svcParams[stack.WorkloadRulePathParamKey]
httpsEnabled := svcParams[stack.WorkloadHTTPSParamKey] == "true"
// public load balancers use the env DNS name if https is not enabled
if d.albCFNOutputName == envOutputPublicLoadBalancerDNSName && !httpsEnabled {
return d.envDNSName(path)
}
svcResources, err := d.svcDescriber.StackResources()
if err != nil {
return accessURI{}, fmt.Errorf("get stack resources for service %s: %w", d.svc, err)
}
var ruleARNs []string
for _, resource := range svcResources {
if resource.Type == svcStackResourceListenerRuleResourceType &&
((httpsEnabled && strings.HasPrefix(resource.LogicalID, svcStackResourceHTTPSListenerRuleLogicalID)) ||
(!httpsEnabled && strings.HasPrefix(resource.LogicalID, svcStackResourceHTTPListenerRuleLogicalID))) {
ruleARNs = append(ruleARNs, resource.PhysicalID)
}
}
lbDescr, err := d.initLBDescriber(d.env)
if err != nil {
return accessURI{}, nil
}
dnsNames, err := lbDescr.ListenerRulesHostHeaders(ruleARNs)
if err != nil {
return accessURI{}, fmt.Errorf("get host headers for listener rules %s: %w", strings.Join(ruleARNs, ","), err)
}
if len(dnsNames) == 0 {
return d.envDNSName(path)
}
return accessURI{
HTTPS: httpsEnabled,
DNSNames: dnsNames,
Path: path,
}, nil
}
func (d *uriDescriber) bestEffortRemoveALBDNSName(accessURI accessURI) accessURI {
envOutputs, err := d.envDescriber.Outputs()
if err != nil {
return accessURI
}
lbDNSName := envOutputs[d.albCFNOutputName]
for i := range accessURI.DNSNames {
if accessURI.DNSNames[i] == lbDNSName {
accessURI.DNSNames = append(accessURI.DNSNames[:i], accessURI.DNSNames[i+1:]...)
break
}
}
return accessURI
}
// URI returns the WebServiceURI to identify this service uniquely given an environment name.
func (d *RDWebServiceDescriber) URI(envName string) (URI, error) {
describer, err := d.initAppRunnerDescriber(envName)
if err != nil {
return URI{}, err
}
serviceURL, err := describer.ServiceURL()
if err != nil {
return URI{}, fmt.Errorf("get outputs for service %q: %w", d.svc, err)
}
isPrivate, err := describer.IsPrivate()
if err != nil {
return URI{}, fmt.Errorf("check if service %q is private: %w", d.svc, err)
}
accessType := URIAccessTypeInternet
if isPrivate {
accessType = URIAccessTypeInternal
}
return URI{
URI: serviceURL,
AccessType: accessType,
}, nil
}
// LBWebServiceURI represents the unique identifier to access a load balanced web service.
type LBWebServiceURI struct {
access accessURI
nlbURI nlbURI
}
type accessURI struct {
HTTPS bool
DNSNames []string // The environment's subdomain if the service is served on HTTPS. Otherwise, the public application load balancer's access point.
Path string // Empty if the service is served on HTTPS. Otherwise, the pattern used to match the service.
}
type nlbURI struct {
DNSNames []string
Port string
}
func (u *LBWebServiceURI) String() string {
uris := u.access.strings()
for _, dnsName := range u.nlbURI.DNSNames {
uris = append(uris, color.HighlightResource(fmt.Sprintf("%s:%s", dnsName, u.nlbURI.Port)))
}
return english.OxfordWordSeries(uris, "or")
}
func (u *accessURI) strings() []string {
var uris []string
for _, dnsName := range u.DNSNames {
protocol := "http://"
if u.HTTPS {
protocol = "https://"
}
path := ""
if u.Path != "/" {
path = fmt.Sprintf("/%s", u.Path)
}
uris = append(uris, color.HighlightResource(protocol+dnsName+path))
}
return uris
}
type serviceDiscovery struct {
Service string
Endpoint string
Port string
}
func (s *serviceDiscovery) String() string {
return fmt.Sprintf(fmtSvcDiscoveryEndpointWithPort, s.Service, s.Endpoint, s.Port)
}
| 406 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package describe
import (
"errors"
"fmt"
"testing"
"github.com/aws/copilot-cli/internal/pkg/deploy/cloudformation/stack"
"github.com/aws/copilot-cli/internal/pkg/describe/mocks"
"github.com/aws/copilot-cli/internal/pkg/template"
describeStack "github.com/aws/copilot-cli/internal/pkg/describe/stack"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
func TestLBWebServiceDescriber_URI(t *testing.T) {
const (
testApp = "phonetool"
testEnv = "test"
testSvc = "jobs"
testEnvSubdomain = "test.phonetool.com"
testEnvLBDNSName = "abc.us-west-1.elb.amazonaws.com"
testSvcPath = "/"
testALBAccessible = "true"
testALBInaccessible = "false"
testCloudFrontDomainName = "test.cloudfront.com"
testNLBDNSName = "def.us-west-2.elb.amazonaws.com"
)
mockErr := errors.New("some error")
testCases := map[string]struct {
setupMocks func(mocks lbWebSvcDescriberMocks)
wantedURI string
wantedError error
}{
"fail to get stack resources of service stack": {
setupMocks: func(m lbWebSvcDescriberMocks) {
gomock.InOrder(
m.ecsDescriber.EXPECT().StackResources().Return(nil, mockErr),
)
},
wantedError: fmt.Errorf("get stack resources for service jobs: some error"),
},
"fail to get params of the service stack when fetching ALB uris": {
setupMocks: func(m lbWebSvcDescriberMocks) {
gomock.InOrder(
m.ecsDescriber.EXPECT().StackResources().Return([]*describeStack.Resource{
{
LogicalID: svcStackResourceALBTargetGroupLogicalID,
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(nil, mockErr),
)
},
wantedError: fmt.Errorf("get stack parameters for service jobs: some error"),
},
"fail to get outputs of environment stack when fetching ALB uris": {
setupMocks: func(m lbWebSvcDescriberMocks) {
gomock.InOrder(
m.ecsDescriber.EXPECT().StackResources().Return([]*describeStack.Resource{
{
LogicalID: svcStackResourceALBTargetGroupLogicalID,
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(map[string]string{
stack.WorkloadRulePathParamKey: testSvcPath,
}, nil),
m.envDescriber.EXPECT().Outputs().Return(nil, mockErr),
)
},
wantedError: fmt.Errorf("get stack outputs for environment test: some error"),
},
"fail to get listener rule host-header": {
setupMocks: func(m lbWebSvcDescriberMocks) {
gomock.InOrder(
m.ecsDescriber.EXPECT().StackResources().Return([]*describeStack.Resource{
{
LogicalID: svcStackResourceALBTargetGroupLogicalID,
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(map[string]string{
stack.WorkloadRulePathParamKey: testSvcPath,
stack.WorkloadHTTPSParamKey: "true",
}, nil),
m.ecsDescriber.EXPECT().StackResources().Return([]*describeStack.Resource{
{
LogicalID: svcStackResourceHTTPSListenerRuleLogicalID,
Type: svcStackResourceListenerRuleResourceType,
PhysicalID: "mockRuleARN",
},
}, nil),
m.lbDescriber.EXPECT().ListenerRulesHostHeaders([]string{"mockRuleARN"}).
Return(nil, mockErr),
)
},
wantedError: fmt.Errorf("get host headers for listener rules mockRuleARN: some error"),
},
"https web service": {
setupMocks: func(m lbWebSvcDescriberMocks) {
gomock.InOrder(
m.ecsDescriber.EXPECT().StackResources().Return([]*describeStack.Resource{
{
LogicalID: svcStackResourceALBTargetGroupLogicalID,
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(map[string]string{
stack.WorkloadRulePathParamKey: testSvcPath,
stack.WorkloadHTTPSParamKey: "true",
}, nil),
m.ecsDescriber.EXPECT().StackResources().Return([]*describeStack.Resource{
{
LogicalID: "HTTPSListenerRule",
Type: svcStackResourceListenerRuleResourceType,
PhysicalID: "mockRuleARN1",
},
{
LogicalID: "HTTPSListenerRule1",
Type: svcStackResourceListenerRuleResourceType,
PhysicalID: "mockRuleARN2",
},
}, nil),
m.lbDescriber.EXPECT().ListenerRulesHostHeaders([]string{"mockRuleARN1", "mockRuleARN2"}).
Return([]string{"jobs.test.phonetool.com", "phonetool.com", "v1.phonetool.com"}, nil),
)
},
wantedURI: "https://jobs.test.phonetool.com, https://phonetool.com, or https://v1.phonetool.com",
},
"http web service": {
setupMocks: func(m lbWebSvcDescriberMocks) {
gomock.InOrder(
m.ecsDescriber.EXPECT().StackResources().Return([]*describeStack.Resource{
{
LogicalID: svcStackResourceALBTargetGroupLogicalID,
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(map[string]string{
stack.WorkloadRulePathParamKey: "mySvc",
}, nil),
m.envDescriber.EXPECT().Outputs().Return(map[string]string{
envOutputPublicLoadBalancerDNSName: testEnvLBDNSName,
}, nil),
)
},
wantedURI: "http://abc.us-west-1.elb.amazonaws.com/mySvc",
},
"http web service with cloudfront": {
setupMocks: func(m lbWebSvcDescriberMocks) {
gomock.InOrder(
m.ecsDescriber.EXPECT().StackResources().Return([]*describeStack.Resource{
{
LogicalID: svcStackResourceALBTargetGroupLogicalID,
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(map[string]string{
stack.WorkloadRulePathParamKey: "mySvc",
}, nil),
m.envDescriber.EXPECT().Outputs().Return(map[string]string{
envOutputPublicLoadBalancerDNSName: testEnvLBDNSName,
envOutputPublicALBAccessible: testALBAccessible,
envOutputCloudFrontDomainName: testCloudFrontDomainName,
}, nil),
)
},
wantedURI: "http://abc.us-west-1.elb.amazonaws.com/mySvc or http://test.cloudfront.com/mySvc",
},
"http web service with cloudfront and alb disabled": {
setupMocks: func(m lbWebSvcDescriberMocks) {
gomock.InOrder(
m.ecsDescriber.EXPECT().StackResources().Return([]*describeStack.Resource{
{
LogicalID: svcStackResourceALBTargetGroupLogicalID,
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(map[string]string{
stack.WorkloadRulePathParamKey: "mySvc",
}, nil),
m.envDescriber.EXPECT().Outputs().Return(map[string]string{
envOutputPublicLoadBalancerDNSName: testEnvLBDNSName,
envOutputPublicALBAccessible: testALBInaccessible,
envOutputCloudFrontDomainName: testCloudFrontDomainName,
}, nil),
)
},
wantedURI: "http://test.cloudfront.com/mySvc",
},
"fail to get parameters of service stack when fetching NLB uris": {
setupMocks: func(m lbWebSvcDescriberMocks) {
m.ecsDescriber.EXPECT().StackResources().Return([]*describeStack.Resource{
{
LogicalID: svcStackResourceNLBTargetGroupLogicalID,
},
}, nil)
m.ecsDescriber.EXPECT().Params().Return(nil, mockErr)
},
wantedError: fmt.Errorf("get stack parameters for service jobs: some error"),
},
"fail to get outputs of service stack when fetching NLB uris": {
setupMocks: func(m lbWebSvcDescriberMocks) {
m.ecsDescriber.EXPECT().StackResources().Return([]*describeStack.Resource{
{
LogicalID: svcStackResourceNLBTargetGroupLogicalID,
},
}, nil)
m.ecsDescriber.EXPECT().Params().Return(map[string]string{
stack.LBWebServiceNLBPortParamKey: "443",
stack.LBWebServiceDNSDelegatedParamKey: "false",
}, nil)
m.ecsDescriber.EXPECT().Outputs().Return(nil, mockErr)
},
wantedError: fmt.Errorf("get stack outputs for service jobs: some error"),
},
"fail to get outputs of environment stack when fetching NLB uris": {
setupMocks: func(m lbWebSvcDescriberMocks) {
m.ecsDescriber.EXPECT().StackResources().Return([]*describeStack.Resource{
{
LogicalID: svcStackResourceNLBTargetGroupLogicalID,
},
}, nil)
m.ecsDescriber.EXPECT().Params().Return(map[string]string{
stack.LBWebServiceNLBPortParamKey: "443",
stack.LBWebServiceDNSDelegatedParamKey: "true",
}, nil)
m.envDescriber.EXPECT().Outputs().Return(nil, mockErr)
},
wantedError: fmt.Errorf("get stack outputs for environment test: some error"),
},
"nlb web service": {
setupMocks: func(m lbWebSvcDescriberMocks) {
gomock.InOrder(
m.ecsDescriber.EXPECT().StackResources().Return([]*describeStack.Resource{
{
LogicalID: svcStackResourceNLBTargetGroupLogicalID,
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(map[string]string{
stack.LBWebServiceNLBPortParamKey: "443",
stack.LBWebServiceDNSDelegatedParamKey: "false",
}, nil),
m.ecsDescriber.EXPECT().Outputs().Return(map[string]string{
svcOutputPublicNLBDNSName: testNLBDNSName,
}, nil),
)
},
wantedURI: "def.us-west-2.elb.amazonaws.com:443",
},
"nlb web service with default DNS name": {
setupMocks: func(m lbWebSvcDescriberMocks) {
gomock.InOrder(
m.ecsDescriber.EXPECT().StackResources().Return([]*describeStack.Resource{
{
LogicalID: svcStackResourceNLBTargetGroupLogicalID,
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(map[string]string{
stack.LBWebServiceNLBPortParamKey: "443",
stack.LBWebServiceDNSDelegatedParamKey: "true",
}, nil),
m.envDescriber.EXPECT().Outputs().Return(map[string]string{
envOutputSubdomain: testEnvSubdomain,
}, nil),
)
},
wantedURI: "jobs-nlb.test.phonetool.com:443",
},
"nlb web service with alias": {
setupMocks: func(m lbWebSvcDescriberMocks) {
gomock.InOrder(
m.ecsDescriber.EXPECT().StackResources().Return([]*describeStack.Resource{
{
LogicalID: svcStackResourceNLBTargetGroupLogicalID,
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(map[string]string{
stack.LBWebServiceNLBPortParamKey: "443",
stack.LBWebServiceDNSDelegatedParamKey: "true",
stack.LBWebServiceNLBAliasesParamKey: "alias1.phonetool.com,alias2.phonetool.com",
}, nil),
)
},
wantedURI: "alias1.phonetool.com:443 or alias2.phonetool.com:443",
},
"both http and nlb with alias": {
setupMocks: func(m lbWebSvcDescriberMocks) {
gomock.InOrder(
m.ecsDescriber.EXPECT().StackResources().Return([]*describeStack.Resource{
{
LogicalID: svcStackResourceNLBTargetGroupLogicalID,
},
{
LogicalID: svcStackResourceALBTargetGroupLogicalID,
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(map[string]string{
stack.WorkloadRulePathParamKey: testSvcPath,
stack.WorkloadHTTPSParamKey: "true",
}, nil),
m.ecsDescriber.EXPECT().StackResources().Return([]*describeStack.Resource{
{
LogicalID: svcStackResourceHTTPSListenerRuleLogicalID,
Type: svcStackResourceListenerRuleResourceType,
PhysicalID: "mockRuleARN",
},
}, nil),
m.lbDescriber.EXPECT().ListenerRulesHostHeaders([]string{"mockRuleARN"}).
Return([]string{"example.com", "v1.example.com"}, nil),
m.ecsDescriber.EXPECT().Params().Return(map[string]string{
stack.LBWebServiceNLBPortParamKey: "443",
stack.LBWebServiceDNSDelegatedParamKey: "true",
stack.LBWebServiceNLBAliasesParamKey: "alias1.phonetool.com,alias2.phonetool.com",
}, nil),
)
},
wantedURI: "https://example.com, https://v1.example.com, alias1.phonetool.com:443, or alias2.phonetool.com:443",
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockSvcDescriber := mocks.NewMockecsDescriber(ctrl)
mockEnvDescriber := mocks.NewMockenvDescriber(ctrl)
mockLBDescriber := mocks.NewMocklbDescriber(ctrl)
mocks := lbWebSvcDescriberMocks{
ecsDescriber: mockSvcDescriber,
envDescriber: mockEnvDescriber,
lbDescriber: mockLBDescriber,
}
tc.setupMocks(mocks)
d := &LBWebServiceDescriber{
app: testApp,
svc: testSvc,
initECSServiceDescribers: func(s string) (ecsDescriber, error) { return mockSvcDescriber, nil },
initEnvDescribers: func(s string) (envDescriber, error) { return mockEnvDescriber, nil },
initLBDescriber: func(s string) (lbDescriber, error) { return mockLBDescriber, nil },
}
// WHEN
actual, err := d.URI(testEnv)
// THEN
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedURI, actual.URI)
}
})
}
}
func TestBackendServiceDescriber_URI(t *testing.T) {
const (
testApp = "phonetool"
testEnv = "test"
testSvc = "my-svc"
testEnvInternalDNSName = "abc.us-west-1.elb.amazonaws.internal"
)
testCases := map[string]struct {
setupMocks func(mocks lbWebSvcDescriberMocks)
wantedURI string
wantedError error
}{
"should return a blank service discovery URI if there is no port exposed": {
setupMocks: func(m lbWebSvcDescriberMocks) {
m.ecsDescriber.EXPECT().StackResources().Return(nil, nil)
m.ecsDescriber.EXPECT().Params().Return(map[string]string{
stack.WorkloadTargetPortParamKey: template.NoExposedContainerPort, // No port is set for the backend service.
}, nil)
},
wantedURI: BlankServiceDiscoveryURI,
},
"should return service connect endpoint if port is exposed": {
setupMocks: func(m lbWebSvcDescriberMocks) {
m.ecsDescriber.EXPECT().StackResources().Return(nil, nil)
m.ecsDescriber.EXPECT().Params().Return(map[string]string{
stack.WorkloadTargetPortParamKey: "8080",
}, nil)
m.ecsDescriber.EXPECT().ServiceConnectDNSNames().Return([]string{"my-svc:8080"}, nil)
},
wantedURI: "my-svc:8080",
},
"should return service discovery endpoint if port is exposed": {
setupMocks: func(m lbWebSvcDescriberMocks) {
m.ecsDescriber.EXPECT().StackResources().Return(nil, nil)
m.ecsDescriber.EXPECT().Params().Return(map[string]string{
stack.WorkloadTargetPortParamKey: "8080",
}, nil)
m.ecsDescriber.EXPECT().ServiceConnectDNSNames().Return(nil, nil)
m.envDescriber.EXPECT().ServiceDiscoveryEndpoint().Return("test.app.local", nil)
},
wantedURI: "my-svc.test.app.local:8080",
},
"internal url http": {
setupMocks: func(m lbWebSvcDescriberMocks) {
resources := []*describeStack.Resource{
{
Type: "AWS::ElasticLoadBalancingV2::TargetGroup",
LogicalID: svcStackResourceALBTargetGroupLogicalID,
PhysicalID: "targetGroupARN",
},
{
Type: svcStackResourceListenerRuleResourceType,
LogicalID: svcStackResourceHTTPListenerRuleLogicalID,
PhysicalID: "mockRuleARN",
},
}
gomock.InOrder(
m.ecsDescriber.EXPECT().StackResources().Return(resources, nil),
m.ecsDescriber.EXPECT().Params().Return(map[string]string{
stack.WorkloadRulePathParamKey: "mySvc",
}, nil),
m.ecsDescriber.EXPECT().StackResources().Return(resources, nil),
m.lbDescriber.EXPECT().ListenerRulesHostHeaders([]string{"mockRuleARN"}).
Return([]string{"jobs.test.phonetool.internal", "1234.us-west-2.internal.aws.com"}, nil),
m.envDescriber.EXPECT().Outputs().Return(map[string]string{
envOutputInternalLoadBalancerDNSName: "1234.us-west-2.internal.aws.com",
}, nil),
)
},
wantedURI: "http://jobs.test.phonetool.internal/mySvc",
},
"internal url https": {
setupMocks: func(m lbWebSvcDescriberMocks) {
gomock.InOrder(
m.ecsDescriber.EXPECT().StackResources().Return([]*describeStack.Resource{
{
LogicalID: svcStackResourceALBTargetGroupLogicalID,
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(map[string]string{
stack.WorkloadRulePathParamKey: "/",
stack.WorkloadHTTPSParamKey: "true",
}, nil),
m.ecsDescriber.EXPECT().StackResources().Return([]*describeStack.Resource{
{
LogicalID: "HTTPSListenerRuleGroup0",
Type: svcStackResourceListenerRuleResourceType,
PhysicalID: "mockRuleARN1",
},
{
LogicalID: "HTTPSListenerRuleGroup1",
Type: svcStackResourceListenerRuleResourceType,
PhysicalID: "mockRuleARN2",
},
}, nil),
m.lbDescriber.EXPECT().ListenerRulesHostHeaders([]string{"mockRuleARN1", "mockRuleARN2"}).
Return([]string{"jobs.test.phonetool.com", "phonetool.com", "v1.phonetool.com"}, nil),
)
},
wantedURI: "https://jobs.test.phonetool.com, https://phonetool.com, or https://v1.phonetool.com",
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockSvcDescriber := mocks.NewMockecsDescriber(ctrl)
mockEnvDescriber := mocks.NewMockenvDescriber(ctrl)
mockLBDescriber := mocks.NewMocklbDescriber(ctrl)
mocks := lbWebSvcDescriberMocks{
ecsDescriber: mockSvcDescriber,
envDescriber: mockEnvDescriber,
lbDescriber: mockLBDescriber,
}
tc.setupMocks(mocks)
d := &BackendServiceDescriber{
app: testApp,
svc: testSvc,
initECSServiceDescribers: func(s string) (ecsDescriber, error) { return mockSvcDescriber, nil },
initEnvDescribers: func(s string) (envDescriber, error) { return mockEnvDescriber, nil },
initLBDescriber: func(s string) (lbDescriber, error) { return mockLBDescriber, nil },
}
// WHEN
actual, err := d.URI(testEnv)
// THEN
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedURI, actual.URI)
}
})
}
}
func TestRDWebServiceDescriber_URI(t *testing.T) {
const (
testApp = "phonetool"
testEnv = "test"
testSvc = "frontend"
testSvcURL = "https://6znxd4ra33.public.us-east-1.apprunner.amazonaws.com"
)
mockErr := errors.New("some error")
testCases := map[string]struct {
setupMocks func(mocks apprunnerSvcDescriberMocks)
wantedURI URI
wantedError error
}{
"fail to get outputs of service stack": {
setupMocks: func(m apprunnerSvcDescriberMocks) {
gomock.InOrder(
m.ecsSvcDescriber.EXPECT().ServiceURL().Return("", mockErr),
)
},
wantedError: fmt.Errorf(`get outputs for service "frontend": some error`),
},
"fail to check if private": {
setupMocks: func(m apprunnerSvcDescriberMocks) {
gomock.InOrder(
m.ecsSvcDescriber.EXPECT().ServiceURL().Return(testSvcURL, nil),
m.ecsSvcDescriber.EXPECT().IsPrivate().Return(false, mockErr),
)
},
wantedError: fmt.Errorf(`check if service "frontend" is private: some error`),
},
"succeed in getting public service uri": {
setupMocks: func(m apprunnerSvcDescriberMocks) {
gomock.InOrder(
m.ecsSvcDescriber.EXPECT().ServiceURL().Return(testSvcURL, nil),
m.ecsSvcDescriber.EXPECT().IsPrivate().Return(false, nil),
)
},
wantedURI: URI{
URI: "https://6znxd4ra33.public.us-east-1.apprunner.amazonaws.com",
AccessType: URIAccessTypeInternet,
},
},
"succeed in getting private service uri": {
setupMocks: func(m apprunnerSvcDescriberMocks) {
gomock.InOrder(
m.ecsSvcDescriber.EXPECT().ServiceURL().Return(testSvcURL, nil),
m.ecsSvcDescriber.EXPECT().IsPrivate().Return(true, nil),
)
},
wantedURI: URI{
URI: "https://6znxd4ra33.public.us-east-1.apprunner.amazonaws.com",
AccessType: URIAccessTypeInternal,
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockSvcDescriber := mocks.NewMockapprunnerDescriber(ctrl)
mocks := apprunnerSvcDescriberMocks{
ecsSvcDescriber: mockSvcDescriber,
}
tc.setupMocks(mocks)
d := &RDWebServiceDescriber{
app: testApp,
svc: testSvc,
initAppRunnerDescriber: func(string) (apprunnerDescriber, error) { return mockSvcDescriber, nil },
}
// WHEN
actual, err := d.URI(testEnv)
// THEN
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedURI, actual)
}
})
}
}
func TestLBWebServiceURI_String(t *testing.T) {
testCases := map[string]struct {
accessDNSNames []string
accessPath string
accessHTTPS bool
wanted string
}{
"http": {
accessDNSNames: []string{"abc.us-west-1.elb.amazonaws.com"},
accessPath: "svc",
wanted: "http://abc.us-west-1.elb.amazonaws.com/svc",
},
"http with / path": {
accessDNSNames: []string{"jobs.test.phonetool.com"},
accessPath: "/",
wanted: "http://jobs.test.phonetool.com",
},
"cloudfront": {
accessDNSNames: []string{"abc.cloudfront.net"},
accessPath: "svc",
wanted: "http://abc.cloudfront.net/svc",
},
"cloudfront with https": {
accessDNSNames: []string{"abc.cloudfront.net"},
accessPath: "svc",
accessHTTPS: true,
wanted: "https://abc.cloudfront.net/svc",
},
"https": {
accessDNSNames: []string{"jobs.test.phonetool.com"},
accessPath: "svc",
accessHTTPS: true,
wanted: "https://jobs.test.phonetool.com/svc",
},
"https with / path": {
accessDNSNames: []string{"jobs.test.phonetool.com"},
accessPath: "/",
accessHTTPS: true,
wanted: "https://jobs.test.phonetool.com",
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
uri := &LBWebServiceURI{
access: accessURI{
DNSNames: tc.accessDNSNames,
Path: tc.accessPath,
HTTPS: tc.accessHTTPS,
},
}
require.Equal(t, tc.wanted, uri.String())
})
}
}
| 659 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package describe
import (
"bytes"
"encoding/json"
"fmt"
"text/tabwriter"
"github.com/aws/copilot-cli/internal/pkg/aws/cloudwatch"
"github.com/aws/copilot-cli/internal/pkg/aws/sessions"
"github.com/aws/copilot-cli/internal/pkg/docker/dockerengine"
"github.com/aws/copilot-cli/internal/pkg/manifest/manifestinfo"
cfnstack "github.com/aws/copilot-cli/internal/pkg/deploy/cloudformation/stack"
"github.com/aws/copilot-cli/internal/pkg/describe/stack"
"github.com/aws/copilot-cli/internal/pkg/term/color"
)
// WorkerServiceDescriber retrieves information about a worker service.
type WorkerServiceDescriber struct {
app string
svc string
enableResources bool
store DeployedEnvServicesLister
initECSDescriber func(string) (ecsDescriber, error)
initCWDescriber func(string) (cwAlarmDescriber, error)
svcStackDescriber map[string]ecsDescriber
cwAlarmDescribers map[string]cwAlarmDescriber
}
// NewWorkerServiceDescriber instantiates a worker service describer.
func NewWorkerServiceDescriber(opt NewServiceConfig) (*WorkerServiceDescriber, error) {
describer := &WorkerServiceDescriber{
app: opt.App,
svc: opt.Svc,
enableResources: opt.EnableResources,
store: opt.DeployStore,
svcStackDescriber: make(map[string]ecsDescriber),
}
describer.initECSDescriber = func(env string) (ecsDescriber, error) {
if describer, ok := describer.svcStackDescriber[env]; ok {
return describer, nil
}
d, err := newECSServiceDescriber(NewServiceConfig{
App: opt.App,
Svc: opt.Svc,
ConfigStore: opt.ConfigStore,
}, env)
if err != nil {
return nil, err
}
describer.svcStackDescriber[env] = d
return d, nil
}
describer.initCWDescriber = func(envName string) (cwAlarmDescriber, error) {
if describer, ok := describer.cwAlarmDescribers[envName]; ok {
return describer, nil
}
env, err := opt.ConfigStore.GetEnvironment(opt.App, envName)
if err != nil {
return nil, fmt.Errorf("get environment %s: %w", envName, err)
}
sess, err := sessions.ImmutableProvider().FromRole(env.ManagerRoleARN, env.Region)
if err != nil {
return nil, err
}
return cloudwatch.New(sess), nil
}
return describer, nil
}
// Describe returns info of a worker service.
func (d *WorkerServiceDescriber) Describe() (HumanJSONStringer, error) {
environments, err := d.store.ListEnvironmentsDeployedTo(d.app, d.svc)
if err != nil {
return nil, fmt.Errorf("list deployed environments for application %s: %w", d.app, err)
}
var configs []*ECSServiceConfig
var envVars []*containerEnvVar
var secrets []*secret
var alarmDescriptions []*cloudwatch.AlarmDescription
for _, env := range environments {
svcDescr, err := d.initECSDescriber(env)
if err != nil {
return nil, err
}
svcParams, err := svcDescr.Params()
if err != nil {
return nil, fmt.Errorf("get stack parameters for environment %s: %w", env, err)
}
containerPlatform, err := svcDescr.Platform()
if err != nil {
return nil, fmt.Errorf("retrieve platform: %w", err)
}
configs = append(configs, &ECSServiceConfig{
ServiceConfig: &ServiceConfig{
Environment: env,
Port: blankContainerPort,
CPU: svcParams[cfnstack.WorkloadTaskCPUParamKey],
Memory: svcParams[cfnstack.WorkloadTaskMemoryParamKey],
Platform: dockerengine.PlatformString(containerPlatform.OperatingSystem, containerPlatform.Architecture),
},
Tasks: svcParams[cfnstack.WorkloadTaskCountParamKey],
})
alarmNames, err := svcDescr.RollbackAlarmNames()
if err != nil {
return nil, fmt.Errorf("retrieve rollback alarm names: %w", err)
}
if len(alarmNames) != 0 {
cwAlarmDescr, err := d.initCWDescriber(env)
if err != nil {
return nil, err
}
alarmDescs, err := cwAlarmDescr.AlarmDescriptions(alarmNames)
if err != nil {
return nil, fmt.Errorf("retrieve alarm descriptions: %w", err)
}
for _, alarm := range alarmDescs {
alarm.Environment = env
}
alarmDescriptions = append(alarmDescriptions, alarmDescs...)
}
workerSvcEnvVars, err := svcDescr.EnvVars()
if err != nil {
return nil, fmt.Errorf("retrieve environment variables: %w", err)
}
envVars = append(envVars, flattenContainerEnvVars(env, workerSvcEnvVars)...)
webSvcSecrets, err := svcDescr.Secrets()
if err != nil {
return nil, fmt.Errorf("retrieve secrets: %w", err)
}
secrets = append(secrets, flattenSecrets(env, webSvcSecrets)...)
}
resources := make(map[string][]*stack.Resource)
if d.enableResources {
for _, env := range environments {
svcDescr, err := d.initECSDescriber(env)
if err != nil {
return nil, err
}
stackResources, err := svcDescr.StackResources()
if err != nil {
return nil, fmt.Errorf("retrieve service resources: %w", err)
}
resources[env] = stackResources
}
}
return &workerSvcDesc{
Service: d.svc,
Type: manifestinfo.WorkerServiceType,
App: d.app,
Configurations: configs,
AlarmDescriptions: alarmDescriptions,
Variables: envVars,
Secrets: secrets,
Resources: resources,
environments: environments,
}, nil
}
// Manifest returns the contents of the manifest used to deploy a worker service stack.
// If the Manifest metadata doesn't exist in the stack template, then returns ErrManifestNotFoundInTemplate.
func (d *WorkerServiceDescriber) Manifest(env string) ([]byte, error) {
cfn, err := d.initECSDescriber(env)
if err != nil {
return nil, err
}
return cfn.Manifest()
}
// workerSvcDesc contains serialized parameters for a worker service.
type workerSvcDesc struct {
Service string `json:"service"`
Type string `json:"type"`
App string `json:"application"`
Configurations ecsConfigurations `json:"configurations"`
AlarmDescriptions []*cloudwatch.AlarmDescription `json:"rollbackAlarms,omitempty"`
Variables containerEnvVars `json:"variables"`
Secrets secrets `json:"secrets,omitempty"`
Resources deployedSvcResources `json:"resources,omitempty"`
environments []string `json:"-"`
}
// JSONString returns the stringified workerService struct with json format.
func (w *workerSvcDesc) JSONString() (string, error) {
b, err := json.Marshal(w)
if err != nil {
return "", fmt.Errorf("marshal worker service description: %w", err)
}
return fmt.Sprintf("%s\n", b), nil
}
// HumanString returns the stringified workerService struct with human readable format.
func (w *workerSvcDesc) HumanString() string {
var b bytes.Buffer
writer := tabwriter.NewWriter(&b, minCellWidth, tabWidth, cellPaddingWidth, paddingChar, noAdditionalFormatting)
fmt.Fprint(writer, color.Bold.Sprint("About\n\n"))
writer.Flush()
fmt.Fprintf(writer, " %s\t%s\n", "Application", w.App)
fmt.Fprintf(writer, " %s\t%s\n", "Name", w.Service)
fmt.Fprintf(writer, " %s\t%s\n", "Type", w.Type)
fmt.Fprint(writer, color.Bold.Sprint("\nConfigurations\n\n"))
writer.Flush()
w.Configurations.humanString(writer)
if len(w.AlarmDescriptions) > 0 {
fmt.Fprint(writer, color.Bold.Sprint("\nRollback Alarms\n\n"))
writer.Flush()
rollbackAlarms(w.AlarmDescriptions).humanString(writer)
}
fmt.Fprint(writer, color.Bold.Sprint("\nVariables\n\n"))
writer.Flush()
w.Variables.humanString(writer)
if len(w.Secrets) != 0 {
fmt.Fprint(writer, color.Bold.Sprint("\nSecrets\n\n"))
writer.Flush()
w.Secrets.humanString(writer)
}
if len(w.Resources) != 0 {
fmt.Fprint(writer, color.Bold.Sprint("\nResources\n"))
writer.Flush()
w.Resources.humanStringByEnv(writer, w.environments)
}
writer.Flush()
return b.String()
}
| 237 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package describe
import (
"errors"
"fmt"
"github.com/aws/copilot-cli/internal/pkg/aws/cloudwatch"
"testing"
"github.com/aws/copilot-cli/internal/pkg/aws/ecs"
cfnstack "github.com/aws/copilot-cli/internal/pkg/deploy/cloudformation/stack"
"github.com/aws/copilot-cli/internal/pkg/describe/mocks"
"github.com/aws/copilot-cli/internal/pkg/describe/stack"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
type workerSvcDescriberMocks struct {
storeSvc *mocks.MockDeployedEnvServicesLister
ecsDescriber *mocks.MockecsDescriber
cwDescriber *mocks.MockcwAlarmDescriber
}
func TestWorkerServiceDescriber_Describe(t *testing.T) {
const (
testApp = "phonetool"
testEnv = "test"
testSvc = "jobs"
prodEnv = "prod"
mockEnv = "mockEnv"
alarm1 = "alarm1"
alarm2 = "alarm2"
desc1 = "alarm description 1"
desc2 = "alarm description 2"
)
mockErr := errors.New("some error")
testCases := map[string]struct {
shouldOutputResources bool
setupMocks func(mocks workerSvcDescriberMocks)
wantedWorkerSvc *workerSvcDesc
wantedError error
}{
"return error if fail to list environment": {
setupMocks: func(m workerSvcDescriberMocks) {
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return(nil, mockErr),
)
},
wantedError: fmt.Errorf("list deployed environments for application phonetool: some error"),
},
"return error if fail to retrieve service deployment configuration": {
setupMocks: func(m workerSvcDescriberMocks) {
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv}, nil),
m.ecsDescriber.EXPECT().Params().Return(nil, mockErr),
)
},
wantedError: fmt.Errorf("get stack parameters for environment test: some error"),
},
"return error if fail to retrieve platform": {
setupMocks: func(m workerSvcDescriberMocks) {
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv}, nil),
m.ecsDescriber.EXPECT().Params().Return(map[string]string{
cfnstack.WorkloadTaskCountParamKey: "1",
cfnstack.WorkloadTaskCPUParamKey: "256",
cfnstack.WorkloadTaskMemoryParamKey: "512",
}, nil),
m.ecsDescriber.EXPECT().Platform().Return(nil, errors.New("some error")),
)
},
wantedError: fmt.Errorf("retrieve platform: some error"),
},
"return error if fail to retrieve rollback alarm names": {
setupMocks: func(m workerSvcDescriberMocks) {
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv}, nil),
m.ecsDescriber.EXPECT().Params().Return(map[string]string{
cfnstack.WorkloadTaskCountParamKey: "1",
cfnstack.WorkloadTaskCPUParamKey: "256",
cfnstack.WorkloadTaskMemoryParamKey: "512",
}, nil),
m.ecsDescriber.EXPECT().Platform().Return(&ecs.ContainerPlatform{
OperatingSystem: "LINUX",
Architecture: "X86_64",
}, nil),
m.ecsDescriber.EXPECT().RollbackAlarmNames().Return(nil, errors.New("some error")),
)
},
wantedError: fmt.Errorf("retrieve rollback alarm names: some error"),
},
"return error if fail to retrieve alarm descriptions": {
setupMocks: func(m workerSvcDescriberMocks) {
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv}, nil),
m.ecsDescriber.EXPECT().Params().Return(map[string]string{
cfnstack.WorkloadTaskCountParamKey: "1",
cfnstack.WorkloadTaskCPUParamKey: "256",
cfnstack.WorkloadTaskMemoryParamKey: "512",
}, nil),
m.ecsDescriber.EXPECT().Platform().Return(&ecs.ContainerPlatform{
OperatingSystem: "LINUX",
Architecture: "X86_64",
}, nil),
m.ecsDescriber.EXPECT().RollbackAlarmNames().Return([]string{alarm1}, nil),
m.cwDescriber.EXPECT().AlarmDescriptions([]string{alarm1}).Return(nil, errors.New("some error")),
)
},
wantedError: fmt.Errorf("retrieve alarm descriptions: some error"),
},
"return error if fail to retrieve environment variables": {
setupMocks: func(m workerSvcDescriberMocks) {
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv}, nil),
m.ecsDescriber.EXPECT().Params().Return(map[string]string{
cfnstack.WorkloadTaskCountParamKey: "1",
cfnstack.WorkloadTaskMemoryParamKey: "512",
cfnstack.WorkloadTaskCPUParamKey: "256",
}, nil),
m.ecsDescriber.EXPECT().Platform().Return(&ecs.ContainerPlatform{
OperatingSystem: "LINUX",
Architecture: "X86_64",
}, nil),
m.ecsDescriber.EXPECT().RollbackAlarmNames().Return(nil, nil),
m.ecsDescriber.EXPECT().EnvVars().Return(nil, mockErr),
)
},
wantedError: fmt.Errorf("retrieve environment variables: some error"),
},
"return error if fail to retrieve secrets": {
setupMocks: func(m workerSvcDescriberMocks) {
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv}, nil),
m.ecsDescriber.EXPECT().Params().Return(map[string]string{
cfnstack.WorkloadTaskCountParamKey: "1",
cfnstack.WorkloadTaskCPUParamKey: "256",
cfnstack.WorkloadTaskMemoryParamKey: "512",
}, nil),
m.ecsDescriber.EXPECT().Platform().Return(&ecs.ContainerPlatform{
OperatingSystem: "LINUX",
Architecture: "X86_64",
}, nil),
m.ecsDescriber.EXPECT().RollbackAlarmNames().Return(nil, nil),
m.ecsDescriber.EXPECT().EnvVars().Return([]*ecs.ContainerEnvVar{
{
Name: "COPILOT_ENVIRONMENT_NAME",
Container: "container",
Value: "prod",
},
}, nil),
m.ecsDescriber.EXPECT().Secrets().Return(nil, mockErr),
)
},
wantedError: fmt.Errorf("retrieve secrets: some error"),
},
"should not fetch descriptions if no ROLLBACK alarms present": {
setupMocks: func(m workerSvcDescriberMocks) {
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv}, nil),
m.ecsDescriber.EXPECT().Params().Return(map[string]string{
cfnstack.WorkloadTaskCountParamKey: "1",
cfnstack.WorkloadTaskCPUParamKey: "256",
cfnstack.WorkloadTaskMemoryParamKey: "512",
}, nil),
m.ecsDescriber.EXPECT().Platform().Return(&ecs.ContainerPlatform{
OperatingSystem: "LINUX",
Architecture: "X86_64",
}, nil),
m.ecsDescriber.EXPECT().RollbackAlarmNames().Return([]string{}, nil),
m.ecsDescriber.EXPECT().EnvVars().Return([]*ecs.ContainerEnvVar{}, nil),
m.ecsDescriber.EXPECT().Secrets().Return([]*ecs.ContainerSecret{}, nil),
)
},
wantedWorkerSvc: &workerSvcDesc{
Service: testSvc,
Type: "Worker Service",
App: testApp,
Configurations: []*ECSServiceConfig{
{
ServiceConfig: &ServiceConfig{
CPU: "256",
Environment: "test",
Memory: "512",
Platform: "LINUX/X86_64",
Port: "-",
},
Tasks: "1",
},
},
Resources: map[string][]*stack.Resource{},
environments: []string{"test"},
},
},
"success": {
shouldOutputResources: true,
setupMocks: func(m workerSvcDescriberMocks) {
gomock.InOrder(
m.storeSvc.EXPECT().ListEnvironmentsDeployedTo(testApp, testSvc).Return([]string{testEnv, prodEnv, mockEnv}, nil),
m.ecsDescriber.EXPECT().Params().Return(map[string]string{
cfnstack.WorkloadTaskCountParamKey: "1",
cfnstack.WorkloadTaskCPUParamKey: "256",
cfnstack.WorkloadTaskMemoryParamKey: "512",
}, nil),
m.ecsDescriber.EXPECT().Platform().Return(&ecs.ContainerPlatform{
OperatingSystem: "LINUX",
Architecture: "X86_64",
}, nil),
m.ecsDescriber.EXPECT().RollbackAlarmNames().Return([]string{alarm1}, nil),
m.cwDescriber.EXPECT().AlarmDescriptions([]string{alarm1}).Return([]*cloudwatch.AlarmDescription{
{
Name: alarm1,
Description: desc1,
},
}, nil),
m.ecsDescriber.EXPECT().EnvVars().Return([]*ecs.ContainerEnvVar{
{
Name: "COPILOT_ENVIRONMENT_NAME",
Container: "container",
Value: testEnv,
},
}, nil),
m.ecsDescriber.EXPECT().Secrets().Return([]*ecs.ContainerSecret{
{
Name: "GITHUB_WEBHOOK_SECRET",
Container: "container",
ValueFrom: "GH_WEBHOOK_SECRET",
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(map[string]string{
cfnstack.WorkloadTaskCountParamKey: "2",
cfnstack.WorkloadTaskCPUParamKey: "512",
cfnstack.WorkloadTaskMemoryParamKey: "1024",
}, nil),
m.ecsDescriber.EXPECT().Platform().Return(&ecs.ContainerPlatform{
OperatingSystem: "LINUX",
Architecture: "ARM64",
}, nil),
m.ecsDescriber.EXPECT().RollbackAlarmNames().Return([]string{alarm2}, nil),
m.cwDescriber.EXPECT().AlarmDescriptions([]string{alarm2}).Return([]*cloudwatch.AlarmDescription{
{
Name: alarm2,
Description: desc2,
},
}, nil),
m.ecsDescriber.EXPECT().EnvVars().Return([]*ecs.ContainerEnvVar{
{
Name: "COPILOT_ENVIRONMENT_NAME",
Container: "container",
Value: prodEnv,
},
}, nil),
m.ecsDescriber.EXPECT().Secrets().Return([]*ecs.ContainerSecret{
{
Name: "A_SECRET",
Container: "container",
ValueFrom: "SECRET",
},
}, nil),
m.ecsDescriber.EXPECT().Params().Return(map[string]string{
cfnstack.WorkloadTaskCountParamKey: "2",
cfnstack.WorkloadTaskCPUParamKey: "512",
cfnstack.WorkloadTaskMemoryParamKey: "1024",
}, nil),
m.ecsDescriber.EXPECT().Platform().Return(&ecs.ContainerPlatform{
OperatingSystem: "LINUX",
Architecture: "X86_64",
}, nil),
m.ecsDescriber.EXPECT().RollbackAlarmNames().Return(nil, nil),
m.ecsDescriber.EXPECT().EnvVars().Return([]*ecs.ContainerEnvVar{
{
Name: "COPILOT_ENVIRONMENT_NAME",
Container: "container",
Value: mockEnv,
},
}, nil),
m.ecsDescriber.EXPECT().Secrets().Return(
nil, nil),
m.ecsDescriber.EXPECT().StackResources().Return([]*stack.Resource{
{
Type: "AWS::EC2::SecurityGroupIngress",
PhysicalID: "ContainerSecurityGroupIngressFromPublicALB",
},
}, nil),
m.ecsDescriber.EXPECT().StackResources().Return([]*stack.Resource{
{
Type: "AWS::EC2::SecurityGroup",
PhysicalID: "sg-0758ed6b233743530",
},
}, nil),
m.ecsDescriber.EXPECT().StackResources().Return([]*stack.Resource{
{
Type: "AWS::EC2::SecurityGroup",
PhysicalID: "sg-2337435300758ed6b",
},
}, nil),
)
},
wantedWorkerSvc: &workerSvcDesc{
Service: testSvc,
Type: "Worker Service",
App: testApp,
Configurations: []*ECSServiceConfig{
{
ServiceConfig: &ServiceConfig{
CPU: "256",
Environment: "test",
Memory: "512",
Platform: "LINUX/X86_64",
Port: "-",
},
Tasks: "1",
},
{
ServiceConfig: &ServiceConfig{
CPU: "512",
Environment: "prod",
Memory: "1024",
Platform: "LINUX/ARM64",
Port: "-",
},
Tasks: "2",
},
{
ServiceConfig: &ServiceConfig{
CPU: "512",
Environment: "mockEnv",
Memory: "1024",
Platform: "LINUX/X86_64",
Port: "-",
},
Tasks: "2",
},
},
AlarmDescriptions: []*cloudwatch.AlarmDescription{
{
Name: alarm1,
Description: desc1,
Environment: testEnv,
},
{
Name: alarm2,
Description: desc2,
Environment: prodEnv,
},
},
Variables: []*containerEnvVar{
{
envVar: &envVar{
Environment: "test",
Name: "COPILOT_ENVIRONMENT_NAME",
Value: "test",
},
Container: "container",
},
{
envVar: &envVar{
Environment: "prod",
Name: "COPILOT_ENVIRONMENT_NAME",
Value: "prod",
},
Container: "container",
},
{
envVar: &envVar{
Environment: "mockEnv",
Name: "COPILOT_ENVIRONMENT_NAME",
Value: "mockEnv",
},
Container: "container",
},
},
Secrets: []*secret{
{
Name: "GITHUB_WEBHOOK_SECRET",
Container: "container",
Environment: "test",
ValueFrom: "GH_WEBHOOK_SECRET",
},
{
Name: "A_SECRET",
Container: "container",
Environment: "prod",
ValueFrom: "SECRET",
},
},
Resources: map[string][]*stack.Resource{
"test": {
{
Type: "AWS::EC2::SecurityGroupIngress",
PhysicalID: "ContainerSecurityGroupIngressFromPublicALB",
},
},
"prod": {
{
Type: "AWS::EC2::SecurityGroup",
PhysicalID: "sg-0758ed6b233743530",
},
},
"mockEnv": {
{
Type: "AWS::EC2::SecurityGroup",
PhysicalID: "sg-2337435300758ed6b",
},
},
},
environments: []string{"test", "prod", "mockEnv"},
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockStore := mocks.NewMockDeployedEnvServicesLister(ctrl)
mockSvcDescriber := mocks.NewMockecsDescriber(ctrl)
mockCwDescriber := mocks.NewMockcwAlarmDescriber(ctrl)
mocks := workerSvcDescriberMocks{
storeSvc: mockStore,
ecsDescriber: mockSvcDescriber,
cwDescriber: mockCwDescriber,
}
tc.setupMocks(mocks)
d := &WorkerServiceDescriber{
app: testApp,
svc: testSvc,
enableResources: tc.shouldOutputResources,
store: mockStore,
initECSDescriber: func(s string) (ecsDescriber, error) { return mockSvcDescriber, nil },
initCWDescriber: func(s string) (cwAlarmDescriber, error) { return mockCwDescriber, nil },
}
// WHEN
workersvc, err := d.Describe()
// THEN
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedWorkerSvc, workersvc, "expected output content match")
}
})
}
}
func TestWorkerSvcDesc_String(t *testing.T) {
testCases := map[string]struct {
wantedHumanString string
wantedJSONString string
}{
"correct output": {
wantedHumanString: `About
Application my-app
Name my-svc
Type Worker Service
Configurations
Environment Tasks CPU (vCPU) Memory (MiB) Platform Port
----------- ----- ---------- ------------ -------- ----
test 1 0.25 512 LINUX/X86_64 -
prod 3 0.5 1024 LINUX/ARM64 "
Rollback Alarms
Name Environment Description
---- ----------- -----------
alarmName1 test alarm description 1
alarmName2 prod alarm description 2
Variables
Name Container Environment Value
---- --------- ----------- -----
COPILOT_ENVIRONMENT_NAME container prod prod
" " test test
Secrets
Name Container Environment Value From
---- --------- ----------- ----------
A_SECRET container prod parameter/SECRET
GITHUB_WEBHOOK_SECRET " test parameter/GH_WEBHOOK_SECRET
Resources
test
AWS::EC2::SecurityGroup sg-0758ed6b233743530
prod
AWS::EC2::SecurityGroupIngress ContainerSecurityGroupIngressFromPublicALB
`,
wantedJSONString: "{\"service\":\"my-svc\",\"type\":\"Worker Service\",\"application\":\"my-app\",\"configurations\":[{\"environment\":\"test\",\"port\":\"-\",\"cpu\":\"256\",\"memory\":\"512\",\"platform\":\"LINUX/X86_64\",\"tasks\":\"1\"},{\"environment\":\"prod\",\"port\":\"-\",\"cpu\":\"512\",\"memory\":\"1024\",\"platform\":\"LINUX/ARM64\",\"tasks\":\"3\"}],\"rollbackAlarms\":[{\"name\":\"alarmName1\",\"description\":\"alarm description 1\",\"environment\":\"test\"},{\"name\":\"alarmName2\",\"description\":\"alarm description 2\",\"environment\":\"prod\"}],\"variables\":[{\"environment\":\"prod\",\"name\":\"COPILOT_ENVIRONMENT_NAME\",\"value\":\"prod\",\"container\":\"container\"},{\"environment\":\"test\",\"name\":\"COPILOT_ENVIRONMENT_NAME\",\"value\":\"test\",\"container\":\"container\"}],\"secrets\":[{\"name\":\"A_SECRET\",\"container\":\"container\",\"environment\":\"prod\",\"valueFrom\":\"SECRET\"},{\"name\":\"GITHUB_WEBHOOK_SECRET\",\"container\":\"container\",\"environment\":\"test\",\"valueFrom\":\"GH_WEBHOOK_SECRET\"}],\"resources\":{\"prod\":[{\"type\":\"AWS::EC2::SecurityGroupIngress\",\"physicalID\":\"ContainerSecurityGroupIngressFromPublicALB\"}],\"test\":[{\"type\":\"AWS::EC2::SecurityGroup\",\"physicalID\":\"sg-0758ed6b233743530\"}]}}\n",
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
config := []*ECSServiceConfig{
{
ServiceConfig: &ServiceConfig{
CPU: "256",
Environment: "test",
Memory: "512",
Platform: "LINUX/X86_64",
Port: "-",
},
Tasks: "1",
},
{
ServiceConfig: &ServiceConfig{
CPU: "512",
Environment: "prod",
Memory: "1024",
Platform: "LINUX/ARM64",
Port: "-",
},
Tasks: "3",
},
}
envVars := []*containerEnvVar{
{
envVar: &envVar{
Environment: "prod",
Name: "COPILOT_ENVIRONMENT_NAME",
Value: "prod",
},
Container: "container",
},
{
envVar: &envVar{
Environment: "test",
Name: "COPILOT_ENVIRONMENT_NAME",
Value: "test",
},
Container: "container",
},
}
alarmDescs := []*cloudwatch.AlarmDescription{
{
Name: "alarmName1",
Description: "alarm description 1",
Environment: "test",
},
{
Name: "alarmName2",
Description: "alarm description 2",
Environment: "prod",
},
}
secrets := []*secret{
{
Name: "GITHUB_WEBHOOK_SECRET",
Container: "container",
Environment: "test",
ValueFrom: "GH_WEBHOOK_SECRET",
},
{
Name: "A_SECRET",
Container: "container",
Environment: "prod",
ValueFrom: "SECRET",
},
}
resources := map[string][]*stack.Resource{
"test": {
{
PhysicalID: "sg-0758ed6b233743530",
Type: "AWS::EC2::SecurityGroup",
},
},
"prod": {
{
Type: "AWS::EC2::SecurityGroupIngress",
PhysicalID: "ContainerSecurityGroupIngressFromPublicALB",
},
},
}
workerSvc := &workerSvcDesc{
Service: "my-svc",
Type: "Worker Service",
Configurations: config,
AlarmDescriptions: alarmDescs,
App: "my-app",
Variables: envVars,
Secrets: secrets,
Resources: resources,
environments: []string{"test", "prod"},
}
human := workerSvc.HumanString()
json, _ := workerSvc.JSONString()
require.Equal(t, tc.wantedHumanString, human)
require.Equal(t, tc.wantedJSONString, json)
})
}
}
| 611 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package describe
import (
"fmt"
"strings"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/copilot-cli/internal/pkg/aws/sessions"
cfnstack "github.com/aws/copilot-cli/internal/pkg/deploy/cloudformation/stack"
"github.com/aws/copilot-cli/internal/pkg/describe/stack"
"gopkg.in/yaml.v3"
)
// workloadStackDescriber provides base functionality for retrieving info about a workload stack.
type workloadStackDescriber struct {
app string
name string
env string
cfn stackDescriber
sess *session.Session
// Cache variables.
params map[string]string
outputs map[string]string
stackResources []*stack.Resource
}
type workloadConfig struct {
app string
name string
configStore ConfigStoreSvc
}
// newWorkloadStackDescriber instantiates the core elements of a new workload.
func newWorkloadStackDescriber(opt workloadConfig, env string) (*workloadStackDescriber, error) {
environment, err := opt.configStore.GetEnvironment(opt.app, env)
if err != nil {
return nil, fmt.Errorf("get environment %s: %w", env, err)
}
sess, err := sessions.ImmutableProvider().FromRole(environment.ManagerRoleARN, environment.Region)
if err != nil {
return nil, err
}
return &workloadStackDescriber{
app: opt.app,
name: opt.name,
env: env,
cfn: stack.NewStackDescriber(cfnstack.NameForWorkload(opt.app, env, opt.name), sess),
sess: sess,
}, nil
}
// Params returns the parameters of the workload stack.
func (d *workloadStackDescriber) Params() (map[string]string, error) {
if d.params != nil {
return d.params, nil
}
descr, err := d.cfn.Describe()
if err != nil {
return nil, err
}
d.params = descr.Parameters
return descr.Parameters, nil
}
// Outputs returns the outputs of the service stack.
func (d *workloadStackDescriber) Outputs() (map[string]string, error) {
if d.outputs != nil {
return d.outputs, nil
}
descr, err := d.cfn.Describe()
if err != nil {
return nil, err
}
d.outputs = descr.Outputs
return descr.Outputs, nil
}
// StackResources returns the workload stack resources created by CloudFormation.
func (d *workloadStackDescriber) StackResources() ([]*stack.Resource, error) {
if len(d.stackResources) != 0 {
return d.stackResources, nil
}
svcResources, err := d.cfn.Resources()
if err != nil {
return nil, err
}
var resources []*stack.Resource
ignored := struct{}{}
ignoredResources := map[string]struct{}{
rulePriorityFunction: ignored,
waitCondition: ignored,
waitConditionHandle: ignored,
}
for _, svcResource := range svcResources {
if _, ok := ignoredResources[svcResource.Type]; !ok {
resources = append(resources, svcResource)
}
}
d.stackResources = resources
return resources, nil
}
// Manifest returns the contents of the manifest used to deploy a workload stack.
// If the Manifest metadata doesn't exist in the stack template, then returns ErrManifestNotFoundInTemplate.
func (d *workloadStackDescriber) Manifest() ([]byte, error) {
tpl, err := d.cfn.StackMetadata()
if err != nil {
return nil, fmt.Errorf("retrieve stack metadata for %s-%s-%s: %w", d.app, d.env, d.name, err)
}
metadata := struct {
Manifest string `yaml:"Manifest"`
}{}
if err := yaml.Unmarshal([]byte(tpl), &metadata); err != nil {
return nil, fmt.Errorf("unmarshal Metadata.Manifest in stack %s-%s-%s: %v", d.app, d.env, d.name, err)
}
if len(strings.TrimSpace(metadata.Manifest)) == 0 {
return nil, &ErrManifestNotFoundInTemplate{
app: d.app,
env: d.env,
name: d.name,
}
}
return []byte(metadata.Manifest), nil
}
| 132 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package describe
import (
"errors"
"fmt"
"testing"
"github.com/aws/copilot-cli/internal/pkg/describe/mocks"
"github.com/aws/copilot-cli/internal/pkg/describe/stack"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
func TestServiceStackDescriber_Manifest(t *testing.T) {
testApp, testEnv, testWorkload := "phonetool", "test", "api"
testCases := map[string]struct {
mockCFN func(ctrl *gomock.Controller) *mocks.MockstackDescriber
wantedMft []byte
wantedErr error
}{
"should return wrapped error if Metadata cannot be retrieved from stack": {
mockCFN: func(ctrl *gomock.Controller) *mocks.MockstackDescriber {
cfn := mocks.NewMockstackDescriber(ctrl)
cfn.EXPECT().StackMetadata().Return("", errors.New("some error"))
return cfn
},
wantedErr: errors.New("retrieve stack metadata for phonetool-test-api: some error"),
},
"should return ErrManifestNotFoundInTemplate if Metadata.Manifest is empty": {
mockCFN: func(ctrl *gomock.Controller) *mocks.MockstackDescriber {
cfn := mocks.NewMockstackDescriber(ctrl)
cfn.EXPECT().StackMetadata().Return("", nil)
return cfn
},
wantedErr: &ErrManifestNotFoundInTemplate{app: testApp, env: testEnv, name: testWorkload},
},
"should return content of Metadata.Manifest if it exists": {
mockCFN: func(ctrl *gomock.Controller) *mocks.MockstackDescriber {
cfn := mocks.NewMockstackDescriber(ctrl)
cfn.EXPECT().StackMetadata().Return(`
Manifest: |
hello`, nil)
return cfn
},
wantedMft: []byte("hello"),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
describer := workloadStackDescriber{
app: testApp,
env: testEnv,
name: testWorkload,
cfn: tc.mockCFN(ctrl),
}
// WHEN
actualMft, actualErr := describer.Manifest()
// THEN
if tc.wantedErr != nil {
require.EqualError(t, actualErr, tc.wantedErr.Error())
} else {
require.NoError(t, actualErr)
require.Equal(t, tc.wantedMft, actualMft)
}
})
}
}
func Test_WorkloadManifest(t *testing.T) {
testApp, testService := "phonetool", "api"
testCases := map[string]struct {
inEnv string
mockDescriber func(ctrl *gomock.Controller) interface{ Manifest(string) ([]byte, error) }
wantedMft []byte
wantedErr error
}{
"should return the error as is from the mock ecs client for LBWSDescriber": {
inEnv: "test",
mockDescriber: func(ctrl *gomock.Controller) interface{ Manifest(string) ([]byte, error) } {
m := mocks.NewMockecsDescriber(ctrl)
m.EXPECT().Manifest().Return(nil, errors.New("some error"))
return &LBWebServiceDescriber{
app: testApp,
svc: testService,
initECSServiceDescribers: func(s string) (ecsDescriber, error) {
return m, nil
},
}
},
wantedErr: errors.New("some error"),
},
"should return the error as is from the mock ecs client for BackendServiceDescriber": {
inEnv: "test",
mockDescriber: func(ctrl *gomock.Controller) interface{ Manifest(string) ([]byte, error) } {
m := mocks.NewMockecsDescriber(ctrl)
m.EXPECT().Manifest().Return(nil, errors.New("some error"))
return &BackendServiceDescriber{
app: testApp,
svc: testService,
initECSServiceDescribers: func(s string) (ecsDescriber, error) {
return m, nil
},
}
},
wantedErr: errors.New("some error"),
},
"should return the error as is from the mock app runner client for RDWebServiceDescriber": {
inEnv: "test",
mockDescriber: func(ctrl *gomock.Controller) interface{ Manifest(string) ([]byte, error) } {
m := mocks.NewMockapprunnerDescriber(ctrl)
m.EXPECT().Manifest().Return(nil, errors.New("some error"))
return &RDWebServiceDescriber{
app: testApp,
svc: testService,
initAppRunnerDescriber: func(s string) (apprunnerDescriber, error) {
return m, nil
},
}
},
wantedErr: errors.New("some error"),
},
"should return the error as is from the mock app runner client for WorkerServiceDescriber": {
inEnv: "test",
mockDescriber: func(ctrl *gomock.Controller) interface{ Manifest(string) ([]byte, error) } {
m := mocks.NewMockecsDescriber(ctrl)
m.EXPECT().Manifest().Return(nil, errors.New("some error"))
return &WorkerServiceDescriber{
app: testApp,
svc: testService,
initECSDescriber: func(s string) (ecsDescriber, error) {
return m, nil
},
}
},
wantedErr: errors.New("some error"),
},
"should return the manifest content on success for LBWSDescriber": {
inEnv: "test",
mockDescriber: func(ctrl *gomock.Controller) interface{ Manifest(string) ([]byte, error) } {
m := mocks.NewMockecsDescriber(ctrl)
m.EXPECT().Manifest().Return([]byte("hello"), nil)
return &LBWebServiceDescriber{
app: testApp,
svc: testService,
initECSServiceDescribers: func(s string) (ecsDescriber, error) {
return m, nil
},
}
},
wantedMft: []byte("hello"),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
describer := tc.mockDescriber(ctrl)
// WHEN
actualMft, actualErr := describer.Manifest(tc.inEnv)
// THEN
if tc.wantedErr != nil {
require.EqualError(t, actualErr, tc.wantedErr.Error())
} else {
require.NoError(t, actualErr)
require.Equal(t, tc.wantedMft, actualMft)
}
})
}
}
func TestServiceDescriber_StackResources(t *testing.T) {
const (
testApp = "phonetool"
testEnv = "test"
testWkld = "jobs"
)
testdeployedSvcResources := []*stack.Resource{
{
Type: "AWS::EC2::SecurityGroup",
PhysicalID: "sg-0758ed6b233743530",
},
}
testCases := map[string]struct {
setupMocks func(mocks ecsSvcDescriberMocks)
wantedResources []*stack.Resource
wantedError error
}{
"returns error when fail to describe stack resources": {
setupMocks: func(m ecsSvcDescriberMocks) {
gomock.InOrder(
m.mockCFN.EXPECT().Resources().Return(nil, errors.New("some error")),
)
},
wantedError: fmt.Errorf("some error"),
},
"ignores dummy stack resources": {
setupMocks: func(m ecsSvcDescriberMocks) {
gomock.InOrder(
m.mockCFN.EXPECT().Resources().Return([]*stack.Resource{
{
Type: "AWS::EC2::SecurityGroup",
PhysicalID: "sg-0758ed6b233743530",
},
{
Type: "AWS::CloudFormation::WaitConditionHandle",
PhysicalID: "https://cloudformation-waitcondition-us-west-2.s3-us-west-2.amazonaws.com/",
},
{
Type: "Custom::RulePriorityFunction",
PhysicalID: "alb-rule-priority-HTTPRulePriorityAction",
},
{
Type: "AWS::CloudFormation::WaitCondition",
PhysicalID: "arn:aws:cloudformation:us-west-2:1234567890",
},
}, nil),
)
},
wantedResources: testdeployedSvcResources,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockCFN := mocks.NewMockstackDescriber(ctrl)
mocks := ecsSvcDescriberMocks{
mockCFN: mockCFN,
}
tc.setupMocks(mocks)
d := &workloadStackDescriber{
app: testApp,
name: testWkld,
env: testEnv,
cfn: mockCFN,
}
// WHEN
actual, err := d.StackResources()
// THEN
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
require.ElementsMatch(t, tc.wantedResources, actual)
}
})
}
}
| 275 |
copilot-cli | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: ./internal/pkg/describe/backend_service.go
// Package mocks is a generated GoMock package.
package mocks
| 6 |
copilot-cli | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: ./internal/pkg/describe/describe.go
// Package mocks is a generated GoMock package.
package mocks
import (
reflect "reflect"
stack "github.com/aws/copilot-cli/internal/pkg/describe/stack"
gomock "github.com/golang/mock/gomock"
)
// MockHumanJSONStringer is a mock of HumanJSONStringer interface.
type MockHumanJSONStringer struct {
ctrl *gomock.Controller
recorder *MockHumanJSONStringerMockRecorder
}
// MockHumanJSONStringerMockRecorder is the mock recorder for MockHumanJSONStringer.
type MockHumanJSONStringerMockRecorder struct {
mock *MockHumanJSONStringer
}
// NewMockHumanJSONStringer creates a new mock instance.
func NewMockHumanJSONStringer(ctrl *gomock.Controller) *MockHumanJSONStringer {
mock := &MockHumanJSONStringer{ctrl: ctrl}
mock.recorder = &MockHumanJSONStringerMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockHumanJSONStringer) EXPECT() *MockHumanJSONStringerMockRecorder {
return m.recorder
}
// HumanString mocks base method.
func (m *MockHumanJSONStringer) HumanString() string {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "HumanString")
ret0, _ := ret[0].(string)
return ret0
}
// HumanString indicates an expected call of HumanString.
func (mr *MockHumanJSONStringerMockRecorder) HumanString() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HumanString", reflect.TypeOf((*MockHumanJSONStringer)(nil).HumanString))
}
// JSONString mocks base method.
func (m *MockHumanJSONStringer) JSONString() (string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "JSONString")
ret0, _ := ret[0].(string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// JSONString indicates an expected call of JSONString.
func (mr *MockHumanJSONStringerMockRecorder) JSONString() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "JSONString", reflect.TypeOf((*MockHumanJSONStringer)(nil).JSONString))
}
// MockstackDescriber is a mock of stackDescriber interface.
type MockstackDescriber struct {
ctrl *gomock.Controller
recorder *MockstackDescriberMockRecorder
}
// MockstackDescriberMockRecorder is the mock recorder for MockstackDescriber.
type MockstackDescriberMockRecorder struct {
mock *MockstackDescriber
}
// NewMockstackDescriber creates a new mock instance.
func NewMockstackDescriber(ctrl *gomock.Controller) *MockstackDescriber {
mock := &MockstackDescriber{ctrl: ctrl}
mock.recorder = &MockstackDescriberMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockstackDescriber) EXPECT() *MockstackDescriberMockRecorder {
return m.recorder
}
// Describe mocks base method.
func (m *MockstackDescriber) Describe() (stack.StackDescription, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Describe")
ret0, _ := ret[0].(stack.StackDescription)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Describe indicates an expected call of Describe.
func (mr *MockstackDescriberMockRecorder) Describe() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Describe", reflect.TypeOf((*MockstackDescriber)(nil).Describe))
}
// Resources mocks base method.
func (m *MockstackDescriber) Resources() ([]*stack.Resource, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Resources")
ret0, _ := ret[0].([]*stack.Resource)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Resources indicates an expected call of Resources.
func (mr *MockstackDescriberMockRecorder) Resources() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Resources", reflect.TypeOf((*MockstackDescriber)(nil).Resources))
}
// StackMetadata mocks base method.
func (m *MockstackDescriber) StackMetadata() (string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "StackMetadata")
ret0, _ := ret[0].(string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// StackMetadata indicates an expected call of StackMetadata.
func (mr *MockstackDescriberMockRecorder) StackMetadata() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StackMetadata", reflect.TypeOf((*MockstackDescriber)(nil).StackMetadata))
}
// StackSetMetadata mocks base method.
func (m *MockstackDescriber) StackSetMetadata() (string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "StackSetMetadata")
ret0, _ := ret[0].(string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// StackSetMetadata indicates an expected call of StackSetMetadata.
func (mr *MockstackDescriberMockRecorder) StackSetMetadata() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StackSetMetadata", reflect.TypeOf((*MockstackDescriber)(nil).StackSetMetadata))
}
| 148 |
copilot-cli | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: ./internal/pkg/describe/env.go
// Package mocks is a generated GoMock package.
package mocks
import (
reflect "reflect"
ec2 "github.com/aws/copilot-cli/internal/pkg/aws/ec2"
gomock "github.com/golang/mock/gomock"
)
// MockvpcSubnetLister is a mock of vpcSubnetLister interface.
type MockvpcSubnetLister struct {
ctrl *gomock.Controller
recorder *MockvpcSubnetListerMockRecorder
}
// MockvpcSubnetListerMockRecorder is the mock recorder for MockvpcSubnetLister.
type MockvpcSubnetListerMockRecorder struct {
mock *MockvpcSubnetLister
}
// NewMockvpcSubnetLister creates a new mock instance.
func NewMockvpcSubnetLister(ctrl *gomock.Controller) *MockvpcSubnetLister {
mock := &MockvpcSubnetLister{ctrl: ctrl}
mock.recorder = &MockvpcSubnetListerMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockvpcSubnetLister) EXPECT() *MockvpcSubnetListerMockRecorder {
return m.recorder
}
// ListVPCSubnets mocks base method.
func (m *MockvpcSubnetLister) ListVPCSubnets(vpcID string) (*ec2.VPCSubnets, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListVPCSubnets", vpcID)
ret0, _ := ret[0].(*ec2.VPCSubnets)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ListVPCSubnets indicates an expected call of ListVPCSubnets.
func (mr *MockvpcSubnetListerMockRecorder) ListVPCSubnets(vpcID interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListVPCSubnets", reflect.TypeOf((*MockvpcSubnetLister)(nil).ListVPCSubnets), vpcID)
}
| 51 |
copilot-cli | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: ./internal/pkg/describe/lb_web_service.go
// Package mocks is a generated GoMock package.
package mocks
import (
reflect "reflect"
gomock "github.com/golang/mock/gomock"
)
// MockenvDescriber is a mock of envDescriber interface.
type MockenvDescriber struct {
ctrl *gomock.Controller
recorder *MockenvDescriberMockRecorder
}
// MockenvDescriberMockRecorder is the mock recorder for MockenvDescriber.
type MockenvDescriberMockRecorder struct {
mock *MockenvDescriber
}
// NewMockenvDescriber creates a new mock instance.
func NewMockenvDescriber(ctrl *gomock.Controller) *MockenvDescriber {
mock := &MockenvDescriber{ctrl: ctrl}
mock.recorder = &MockenvDescriberMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockenvDescriber) EXPECT() *MockenvDescriberMockRecorder {
return m.recorder
}
// Outputs mocks base method.
func (m *MockenvDescriber) Outputs() (map[string]string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Outputs")
ret0, _ := ret[0].(map[string]string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Outputs indicates an expected call of Outputs.
func (mr *MockenvDescriberMockRecorder) Outputs() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Outputs", reflect.TypeOf((*MockenvDescriber)(nil).Outputs))
}
// Params mocks base method.
func (m *MockenvDescriber) Params() (map[string]string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Params")
ret0, _ := ret[0].(map[string]string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Params indicates an expected call of Params.
func (mr *MockenvDescriberMockRecorder) Params() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Params", reflect.TypeOf((*MockenvDescriber)(nil).Params))
}
// ServiceDiscoveryEndpoint mocks base method.
func (m *MockenvDescriber) ServiceDiscoveryEndpoint() (string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ServiceDiscoveryEndpoint")
ret0, _ := ret[0].(string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ServiceDiscoveryEndpoint indicates an expected call of ServiceDiscoveryEndpoint.
func (mr *MockenvDescriberMockRecorder) ServiceDiscoveryEndpoint() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceDiscoveryEndpoint", reflect.TypeOf((*MockenvDescriber)(nil).ServiceDiscoveryEndpoint))
}
// MocklbDescriber is a mock of lbDescriber interface.
type MocklbDescriber struct {
ctrl *gomock.Controller
recorder *MocklbDescriberMockRecorder
}
// MocklbDescriberMockRecorder is the mock recorder for MocklbDescriber.
type MocklbDescriberMockRecorder struct {
mock *MocklbDescriber
}
// NewMocklbDescriber creates a new mock instance.
func NewMocklbDescriber(ctrl *gomock.Controller) *MocklbDescriber {
mock := &MocklbDescriber{ctrl: ctrl}
mock.recorder = &MocklbDescriberMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MocklbDescriber) EXPECT() *MocklbDescriberMockRecorder {
return m.recorder
}
// ListenerRulesHostHeaders mocks base method.
func (m *MocklbDescriber) ListenerRulesHostHeaders(ruleARNs []string) ([]string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListenerRulesHostHeaders", ruleARNs)
ret0, _ := ret[0].([]string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ListenerRulesHostHeaders indicates an expected call of ListenerRulesHostHeaders.
func (mr *MocklbDescriberMockRecorder) ListenerRulesHostHeaders(ruleARNs interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListenerRulesHostHeaders", reflect.TypeOf((*MocklbDescriber)(nil).ListenerRulesHostHeaders), ruleARNs)
}
| 118 |
copilot-cli | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: ./internal/pkg/describe/pipeline_show.go
// Package mocks is a generated GoMock package.
package mocks
import (
reflect "reflect"
codepipeline "github.com/aws/copilot-cli/internal/pkg/aws/codepipeline"
gomock "github.com/golang/mock/gomock"
)
// MockpipelineGetter is a mock of pipelineGetter interface.
type MockpipelineGetter struct {
ctrl *gomock.Controller
recorder *MockpipelineGetterMockRecorder
}
// MockpipelineGetterMockRecorder is the mock recorder for MockpipelineGetter.
type MockpipelineGetterMockRecorder struct {
mock *MockpipelineGetter
}
// NewMockpipelineGetter creates a new mock instance.
func NewMockpipelineGetter(ctrl *gomock.Controller) *MockpipelineGetter {
mock := &MockpipelineGetter{ctrl: ctrl}
mock.recorder = &MockpipelineGetterMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockpipelineGetter) EXPECT() *MockpipelineGetterMockRecorder {
return m.recorder
}
// GetPipeline mocks base method.
func (m *MockpipelineGetter) GetPipeline(pipelineName string) (*codepipeline.Pipeline, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetPipeline", pipelineName)
ret0, _ := ret[0].(*codepipeline.Pipeline)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetPipeline indicates an expected call of GetPipeline.
func (mr *MockpipelineGetterMockRecorder) GetPipeline(pipelineName interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPipeline", reflect.TypeOf((*MockpipelineGetter)(nil).GetPipeline), pipelineName)
}
| 51 |
copilot-cli | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: ./internal/pkg/describe/pipeline_status.go
// Package mocks is a generated GoMock package.
package mocks
import (
reflect "reflect"
codepipeline "github.com/aws/copilot-cli/internal/pkg/aws/codepipeline"
gomock "github.com/golang/mock/gomock"
)
// MockpipelineStateGetter is a mock of pipelineStateGetter interface.
type MockpipelineStateGetter struct {
ctrl *gomock.Controller
recorder *MockpipelineStateGetterMockRecorder
}
// MockpipelineStateGetterMockRecorder is the mock recorder for MockpipelineStateGetter.
type MockpipelineStateGetterMockRecorder struct {
mock *MockpipelineStateGetter
}
// NewMockpipelineStateGetter creates a new mock instance.
func NewMockpipelineStateGetter(ctrl *gomock.Controller) *MockpipelineStateGetter {
mock := &MockpipelineStateGetter{ctrl: ctrl}
mock.recorder = &MockpipelineStateGetterMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockpipelineStateGetter) EXPECT() *MockpipelineStateGetterMockRecorder {
return m.recorder
}
// GetPipelineState mocks base method.
func (m *MockpipelineStateGetter) GetPipelineState(pipelineName string) (*codepipeline.PipelineState, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetPipelineState", pipelineName)
ret0, _ := ret[0].(*codepipeline.PipelineState)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetPipelineState indicates an expected call of GetPipelineState.
func (mr *MockpipelineStateGetterMockRecorder) GetPipelineState(pipelineName interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPipelineState", reflect.TypeOf((*MockpipelineStateGetter)(nil).GetPipelineState), pipelineName)
}
| 51 |
copilot-cli | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: ./internal/pkg/describe/rd_web_service.go
// Package mocks is a generated GoMock package.
package mocks
| 6 |
copilot-cli | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: ./internal/pkg/describe/service.go
// Package mocks is a generated GoMock package.
package mocks
import (
reflect "reflect"
apprunner "github.com/aws/copilot-cli/internal/pkg/aws/apprunner"
cloudwatch "github.com/aws/copilot-cli/internal/pkg/aws/cloudwatch"
ecs "github.com/aws/copilot-cli/internal/pkg/aws/ecs"
config "github.com/aws/copilot-cli/internal/pkg/config"
stack "github.com/aws/copilot-cli/internal/pkg/describe/stack"
gomock "github.com/golang/mock/gomock"
)
// MockConfigStoreSvc is a mock of ConfigStoreSvc interface.
type MockConfigStoreSvc struct {
ctrl *gomock.Controller
recorder *MockConfigStoreSvcMockRecorder
}
// MockConfigStoreSvcMockRecorder is the mock recorder for MockConfigStoreSvc.
type MockConfigStoreSvcMockRecorder struct {
mock *MockConfigStoreSvc
}
// NewMockConfigStoreSvc creates a new mock instance.
func NewMockConfigStoreSvc(ctrl *gomock.Controller) *MockConfigStoreSvc {
mock := &MockConfigStoreSvc{ctrl: ctrl}
mock.recorder = &MockConfigStoreSvcMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockConfigStoreSvc) EXPECT() *MockConfigStoreSvcMockRecorder {
return m.recorder
}
// GetEnvironment mocks base method.
func (m *MockConfigStoreSvc) GetEnvironment(appName, environmentName string) (*config.Environment, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetEnvironment", appName, environmentName)
ret0, _ := ret[0].(*config.Environment)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetEnvironment indicates an expected call of GetEnvironment.
func (mr *MockConfigStoreSvcMockRecorder) GetEnvironment(appName, environmentName interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetEnvironment", reflect.TypeOf((*MockConfigStoreSvc)(nil).GetEnvironment), appName, environmentName)
}
// GetWorkload mocks base method.
func (m *MockConfigStoreSvc) GetWorkload(appName, name string) (*config.Workload, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetWorkload", appName, name)
ret0, _ := ret[0].(*config.Workload)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetWorkload indicates an expected call of GetWorkload.
func (mr *MockConfigStoreSvcMockRecorder) GetWorkload(appName, name interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetWorkload", reflect.TypeOf((*MockConfigStoreSvc)(nil).GetWorkload), appName, name)
}
// ListEnvironments mocks base method.
func (m *MockConfigStoreSvc) ListEnvironments(appName string) ([]*config.Environment, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListEnvironments", appName)
ret0, _ := ret[0].([]*config.Environment)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ListEnvironments indicates an expected call of ListEnvironments.
func (mr *MockConfigStoreSvcMockRecorder) ListEnvironments(appName interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListEnvironments", reflect.TypeOf((*MockConfigStoreSvc)(nil).ListEnvironments), appName)
}
// ListJobs mocks base method.
func (m *MockConfigStoreSvc) ListJobs(appName string) ([]*config.Workload, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListJobs", appName)
ret0, _ := ret[0].([]*config.Workload)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ListJobs indicates an expected call of ListJobs.
func (mr *MockConfigStoreSvcMockRecorder) ListJobs(appName interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListJobs", reflect.TypeOf((*MockConfigStoreSvc)(nil).ListJobs), appName)
}
// ListServices mocks base method.
func (m *MockConfigStoreSvc) ListServices(appName string) ([]*config.Workload, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListServices", appName)
ret0, _ := ret[0].([]*config.Workload)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ListServices indicates an expected call of ListServices.
func (mr *MockConfigStoreSvcMockRecorder) ListServices(appName interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListServices", reflect.TypeOf((*MockConfigStoreSvc)(nil).ListServices), appName)
}
// MockDeployedEnvServicesLister is a mock of DeployedEnvServicesLister interface.
type MockDeployedEnvServicesLister struct {
ctrl *gomock.Controller
recorder *MockDeployedEnvServicesListerMockRecorder
}
// MockDeployedEnvServicesListerMockRecorder is the mock recorder for MockDeployedEnvServicesLister.
type MockDeployedEnvServicesListerMockRecorder struct {
mock *MockDeployedEnvServicesLister
}
// NewMockDeployedEnvServicesLister creates a new mock instance.
func NewMockDeployedEnvServicesLister(ctrl *gomock.Controller) *MockDeployedEnvServicesLister {
mock := &MockDeployedEnvServicesLister{ctrl: ctrl}
mock.recorder = &MockDeployedEnvServicesListerMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockDeployedEnvServicesLister) EXPECT() *MockDeployedEnvServicesListerMockRecorder {
return m.recorder
}
// ListDeployedJobs mocks base method.
func (m *MockDeployedEnvServicesLister) ListDeployedJobs(appName, envName string) ([]string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListDeployedJobs", appName, envName)
ret0, _ := ret[0].([]string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ListDeployedJobs indicates an expected call of ListDeployedJobs.
func (mr *MockDeployedEnvServicesListerMockRecorder) ListDeployedJobs(appName, envName interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListDeployedJobs", reflect.TypeOf((*MockDeployedEnvServicesLister)(nil).ListDeployedJobs), appName, envName)
}
// ListDeployedServices mocks base method.
func (m *MockDeployedEnvServicesLister) ListDeployedServices(appName, envName string) ([]string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListDeployedServices", appName, envName)
ret0, _ := ret[0].([]string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ListDeployedServices indicates an expected call of ListDeployedServices.
func (mr *MockDeployedEnvServicesListerMockRecorder) ListDeployedServices(appName, envName interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListDeployedServices", reflect.TypeOf((*MockDeployedEnvServicesLister)(nil).ListDeployedServices), appName, envName)
}
// ListEnvironmentsDeployedTo mocks base method.
func (m *MockDeployedEnvServicesLister) ListEnvironmentsDeployedTo(appName, svcName string) ([]string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListEnvironmentsDeployedTo", appName, svcName)
ret0, _ := ret[0].([]string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ListEnvironmentsDeployedTo indicates an expected call of ListEnvironmentsDeployedTo.
func (mr *MockDeployedEnvServicesListerMockRecorder) ListEnvironmentsDeployedTo(appName, svcName interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListEnvironmentsDeployedTo", reflect.TypeOf((*MockDeployedEnvServicesLister)(nil).ListEnvironmentsDeployedTo), appName, svcName)
}
// MockecsClient is a mock of ecsClient interface.
type MockecsClient struct {
ctrl *gomock.Controller
recorder *MockecsClientMockRecorder
}
// MockecsClientMockRecorder is the mock recorder for MockecsClient.
type MockecsClientMockRecorder struct {
mock *MockecsClient
}
// NewMockecsClient creates a new mock instance.
func NewMockecsClient(ctrl *gomock.Controller) *MockecsClient {
mock := &MockecsClient{ctrl: ctrl}
mock.recorder = &MockecsClientMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockecsClient) EXPECT() *MockecsClientMockRecorder {
return m.recorder
}
// Service mocks base method.
func (m *MockecsClient) Service(app, env, svc string) (*ecs.Service, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Service", app, env, svc)
ret0, _ := ret[0].(*ecs.Service)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Service indicates an expected call of Service.
func (mr *MockecsClientMockRecorder) Service(app, env, svc interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Service", reflect.TypeOf((*MockecsClient)(nil).Service), app, env, svc)
}
// TaskDefinition mocks base method.
func (m *MockecsClient) TaskDefinition(app, env, svc string) (*ecs.TaskDefinition, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "TaskDefinition", app, env, svc)
ret0, _ := ret[0].(*ecs.TaskDefinition)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// TaskDefinition indicates an expected call of TaskDefinition.
func (mr *MockecsClientMockRecorder) TaskDefinition(app, env, svc interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TaskDefinition", reflect.TypeOf((*MockecsClient)(nil).TaskDefinition), app, env, svc)
}
// 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
}
// DescribeService mocks base method.
func (m *MockapprunnerClient) DescribeService(svcARN string) (*apprunner.Service, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DescribeService", svcARN)
ret0, _ := ret[0].(*apprunner.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)
}
// PrivateURL mocks base method.
func (m *MockapprunnerClient) PrivateURL(vicARN string) (string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "PrivateURL", vicARN)
ret0, _ := ret[0].(string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// PrivateURL indicates an expected call of PrivateURL.
func (mr *MockapprunnerClientMockRecorder) PrivateURL(vicARN interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PrivateURL", reflect.TypeOf((*MockapprunnerClient)(nil).PrivateURL), vicARN)
}
// MockworkloadDescriber is a mock of workloadDescriber interface.
type MockworkloadDescriber struct {
ctrl *gomock.Controller
recorder *MockworkloadDescriberMockRecorder
}
// MockworkloadDescriberMockRecorder is the mock recorder for MockworkloadDescriber.
type MockworkloadDescriberMockRecorder struct {
mock *MockworkloadDescriber
}
// NewMockworkloadDescriber creates a new mock instance.
func NewMockworkloadDescriber(ctrl *gomock.Controller) *MockworkloadDescriber {
mock := &MockworkloadDescriber{ctrl: ctrl}
mock.recorder = &MockworkloadDescriberMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockworkloadDescriber) EXPECT() *MockworkloadDescriberMockRecorder {
return m.recorder
}
// Manifest mocks base method.
func (m *MockworkloadDescriber) Manifest() ([]byte, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Manifest")
ret0, _ := ret[0].([]byte)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Manifest indicates an expected call of Manifest.
func (mr *MockworkloadDescriberMockRecorder) Manifest() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Manifest", reflect.TypeOf((*MockworkloadDescriber)(nil).Manifest))
}
// Outputs mocks base method.
func (m *MockworkloadDescriber) Outputs() (map[string]string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Outputs")
ret0, _ := ret[0].(map[string]string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Outputs indicates an expected call of Outputs.
func (mr *MockworkloadDescriberMockRecorder) Outputs() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Outputs", reflect.TypeOf((*MockworkloadDescriber)(nil).Outputs))
}
// Params mocks base method.
func (m *MockworkloadDescriber) Params() (map[string]string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Params")
ret0, _ := ret[0].(map[string]string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Params indicates an expected call of Params.
func (mr *MockworkloadDescriberMockRecorder) Params() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Params", reflect.TypeOf((*MockworkloadDescriber)(nil).Params))
}
// StackResources mocks base method.
func (m *MockworkloadDescriber) StackResources() ([]*stack.Resource, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "StackResources")
ret0, _ := ret[0].([]*stack.Resource)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// StackResources indicates an expected call of StackResources.
func (mr *MockworkloadDescriberMockRecorder) StackResources() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StackResources", reflect.TypeOf((*MockworkloadDescriber)(nil).StackResources))
}
// MockecsDescriber is a mock of ecsDescriber interface.
type MockecsDescriber struct {
ctrl *gomock.Controller
recorder *MockecsDescriberMockRecorder
}
// MockecsDescriberMockRecorder is the mock recorder for MockecsDescriber.
type MockecsDescriberMockRecorder struct {
mock *MockecsDescriber
}
// NewMockecsDescriber creates a new mock instance.
func NewMockecsDescriber(ctrl *gomock.Controller) *MockecsDescriber {
mock := &MockecsDescriber{ctrl: ctrl}
mock.recorder = &MockecsDescriberMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockecsDescriber) EXPECT() *MockecsDescriberMockRecorder {
return m.recorder
}
// EnvVars mocks base method.
func (m *MockecsDescriber) EnvVars() ([]*ecs.ContainerEnvVar, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "EnvVars")
ret0, _ := ret[0].([]*ecs.ContainerEnvVar)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// EnvVars indicates an expected call of EnvVars.
func (mr *MockecsDescriberMockRecorder) EnvVars() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EnvVars", reflect.TypeOf((*MockecsDescriber)(nil).EnvVars))
}
// Manifest mocks base method.
func (m *MockecsDescriber) Manifest() ([]byte, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Manifest")
ret0, _ := ret[0].([]byte)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Manifest indicates an expected call of Manifest.
func (mr *MockecsDescriberMockRecorder) Manifest() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Manifest", reflect.TypeOf((*MockecsDescriber)(nil).Manifest))
}
// Outputs mocks base method.
func (m *MockecsDescriber) Outputs() (map[string]string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Outputs")
ret0, _ := ret[0].(map[string]string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Outputs indicates an expected call of Outputs.
func (mr *MockecsDescriberMockRecorder) Outputs() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Outputs", reflect.TypeOf((*MockecsDescriber)(nil).Outputs))
}
// Params mocks base method.
func (m *MockecsDescriber) Params() (map[string]string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Params")
ret0, _ := ret[0].(map[string]string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Params indicates an expected call of Params.
func (mr *MockecsDescriberMockRecorder) Params() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Params", reflect.TypeOf((*MockecsDescriber)(nil).Params))
}
// Platform mocks base method.
func (m *MockecsDescriber) Platform() (*ecs.ContainerPlatform, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Platform")
ret0, _ := ret[0].(*ecs.ContainerPlatform)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Platform indicates an expected call of Platform.
func (mr *MockecsDescriberMockRecorder) Platform() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Platform", reflect.TypeOf((*MockecsDescriber)(nil).Platform))
}
// RollbackAlarmNames mocks base method.
func (m *MockecsDescriber) RollbackAlarmNames() ([]string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RollbackAlarmNames")
ret0, _ := ret[0].([]string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// RollbackAlarmNames indicates an expected call of RollbackAlarmNames.
func (mr *MockecsDescriberMockRecorder) RollbackAlarmNames() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RollbackAlarmNames", reflect.TypeOf((*MockecsDescriber)(nil).RollbackAlarmNames))
}
// Secrets mocks base method.
func (m *MockecsDescriber) Secrets() ([]*ecs.ContainerSecret, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Secrets")
ret0, _ := ret[0].([]*ecs.ContainerSecret)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Secrets indicates an expected call of Secrets.
func (mr *MockecsDescriberMockRecorder) Secrets() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Secrets", reflect.TypeOf((*MockecsDescriber)(nil).Secrets))
}
// ServiceConnectDNSNames mocks base method.
func (m *MockecsDescriber) ServiceConnectDNSNames() ([]string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ServiceConnectDNSNames")
ret0, _ := ret[0].([]string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ServiceConnectDNSNames indicates an expected call of ServiceConnectDNSNames.
func (mr *MockecsDescriberMockRecorder) ServiceConnectDNSNames() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceConnectDNSNames", reflect.TypeOf((*MockecsDescriber)(nil).ServiceConnectDNSNames))
}
// StackResources mocks base method.
func (m *MockecsDescriber) StackResources() ([]*stack.Resource, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "StackResources")
ret0, _ := ret[0].([]*stack.Resource)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// StackResources indicates an expected call of StackResources.
func (mr *MockecsDescriberMockRecorder) StackResources() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StackResources", reflect.TypeOf((*MockecsDescriber)(nil).StackResources))
}
// MockapprunnerDescriber is a mock of apprunnerDescriber interface.
type MockapprunnerDescriber struct {
ctrl *gomock.Controller
recorder *MockapprunnerDescriberMockRecorder
}
// MockapprunnerDescriberMockRecorder is the mock recorder for MockapprunnerDescriber.
type MockapprunnerDescriberMockRecorder struct {
mock *MockapprunnerDescriber
}
// NewMockapprunnerDescriber creates a new mock instance.
func NewMockapprunnerDescriber(ctrl *gomock.Controller) *MockapprunnerDescriber {
mock := &MockapprunnerDescriber{ctrl: ctrl}
mock.recorder = &MockapprunnerDescriberMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockapprunnerDescriber) EXPECT() *MockapprunnerDescriberMockRecorder {
return m.recorder
}
// IsPrivate mocks base method.
func (m *MockapprunnerDescriber) IsPrivate() (bool, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "IsPrivate")
ret0, _ := ret[0].(bool)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// IsPrivate indicates an expected call of IsPrivate.
func (mr *MockapprunnerDescriberMockRecorder) IsPrivate() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsPrivate", reflect.TypeOf((*MockapprunnerDescriber)(nil).IsPrivate))
}
// Manifest mocks base method.
func (m *MockapprunnerDescriber) Manifest() ([]byte, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Manifest")
ret0, _ := ret[0].([]byte)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Manifest indicates an expected call of Manifest.
func (mr *MockapprunnerDescriberMockRecorder) Manifest() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Manifest", reflect.TypeOf((*MockapprunnerDescriber)(nil).Manifest))
}
// Outputs mocks base method.
func (m *MockapprunnerDescriber) Outputs() (map[string]string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Outputs")
ret0, _ := ret[0].(map[string]string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Outputs indicates an expected call of Outputs.
func (mr *MockapprunnerDescriberMockRecorder) Outputs() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Outputs", reflect.TypeOf((*MockapprunnerDescriber)(nil).Outputs))
}
// Params mocks base method.
func (m *MockapprunnerDescriber) Params() (map[string]string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Params")
ret0, _ := ret[0].(map[string]string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Params indicates an expected call of Params.
func (mr *MockapprunnerDescriberMockRecorder) Params() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Params", reflect.TypeOf((*MockapprunnerDescriber)(nil).Params))
}
// Service mocks base method.
func (m *MockapprunnerDescriber) Service() (*apprunner.Service, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Service")
ret0, _ := ret[0].(*apprunner.Service)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Service indicates an expected call of Service.
func (mr *MockapprunnerDescriberMockRecorder) Service() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Service", reflect.TypeOf((*MockapprunnerDescriber)(nil).Service))
}
// ServiceARN mocks base method.
func (m *MockapprunnerDescriber) ServiceARN() (string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ServiceARN")
ret0, _ := ret[0].(string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ServiceARN indicates an expected call of ServiceARN.
func (mr *MockapprunnerDescriberMockRecorder) ServiceARN() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceARN", reflect.TypeOf((*MockapprunnerDescriber)(nil).ServiceARN))
}
// ServiceURL mocks base method.
func (m *MockapprunnerDescriber) ServiceURL() (string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ServiceURL")
ret0, _ := ret[0].(string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ServiceURL indicates an expected call of ServiceURL.
func (mr *MockapprunnerDescriberMockRecorder) ServiceURL() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceURL", reflect.TypeOf((*MockapprunnerDescriber)(nil).ServiceURL))
}
// StackResources mocks base method.
func (m *MockapprunnerDescriber) StackResources() ([]*stack.Resource, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "StackResources")
ret0, _ := ret[0].([]*stack.Resource)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// StackResources indicates an expected call of StackResources.
func (mr *MockapprunnerDescriberMockRecorder) StackResources() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StackResources", reflect.TypeOf((*MockapprunnerDescriber)(nil).StackResources))
}
// MockcwAlarmDescriber is a mock of cwAlarmDescriber interface.
type MockcwAlarmDescriber struct {
ctrl *gomock.Controller
recorder *MockcwAlarmDescriberMockRecorder
}
// MockcwAlarmDescriberMockRecorder is the mock recorder for MockcwAlarmDescriber.
type MockcwAlarmDescriberMockRecorder struct {
mock *MockcwAlarmDescriber
}
// NewMockcwAlarmDescriber creates a new mock instance.
func NewMockcwAlarmDescriber(ctrl *gomock.Controller) *MockcwAlarmDescriber {
mock := &MockcwAlarmDescriber{ctrl: ctrl}
mock.recorder = &MockcwAlarmDescriberMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockcwAlarmDescriber) EXPECT() *MockcwAlarmDescriberMockRecorder {
return m.recorder
}
// AlarmDescriptions mocks base method.
func (m *MockcwAlarmDescriber) AlarmDescriptions(arg0 []string) ([]*cloudwatch.AlarmDescription, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "AlarmDescriptions", arg0)
ret0, _ := ret[0].([]*cloudwatch.AlarmDescription)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// AlarmDescriptions indicates an expected call of AlarmDescriptions.
func (mr *MockcwAlarmDescriberMockRecorder) AlarmDescriptions(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AlarmDescriptions", reflect.TypeOf((*MockcwAlarmDescriber)(nil).AlarmDescriptions), arg0)
}
// MockbucketDescriber is a mock of bucketDescriber interface.
type MockbucketDescriber struct {
ctrl *gomock.Controller
recorder *MockbucketDescriberMockRecorder
}
// MockbucketDescriberMockRecorder is the mock recorder for MockbucketDescriber.
type MockbucketDescriberMockRecorder struct {
mock *MockbucketDescriber
}
// NewMockbucketDescriber creates a new mock instance.
func NewMockbucketDescriber(ctrl *gomock.Controller) *MockbucketDescriber {
mock := &MockbucketDescriber{ctrl: ctrl}
mock.recorder = &MockbucketDescriberMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockbucketDescriber) EXPECT() *MockbucketDescriberMockRecorder {
return m.recorder
}
// BucketTree mocks base method.
func (m *MockbucketDescriber) BucketTree(bucket string) (string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "BucketTree", bucket)
ret0, _ := ret[0].(string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// BucketTree indicates an expected call of BucketTree.
func (mr *MockbucketDescriberMockRecorder) BucketTree(bucket interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BucketTree", reflect.TypeOf((*MockbucketDescriber)(nil).BucketTree), bucket)
}
// MockbucketDataGetter is a mock of bucketDataGetter interface.
type MockbucketDataGetter struct {
ctrl *gomock.Controller
recorder *MockbucketDataGetterMockRecorder
}
// MockbucketDataGetterMockRecorder is the mock recorder for MockbucketDataGetter.
type MockbucketDataGetterMockRecorder struct {
mock *MockbucketDataGetter
}
// NewMockbucketDataGetter creates a new mock instance.
func NewMockbucketDataGetter(ctrl *gomock.Controller) *MockbucketDataGetter {
mock := &MockbucketDataGetter{ctrl: ctrl}
mock.recorder = &MockbucketDataGetterMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockbucketDataGetter) EXPECT() *MockbucketDataGetterMockRecorder {
return m.recorder
}
// BucketSizeAndCount mocks base method.
func (m *MockbucketDataGetter) BucketSizeAndCount(bucket string) (string, int, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "BucketSizeAndCount", bucket)
ret0, _ := ret[0].(string)
ret1, _ := ret[1].(int)
ret2, _ := ret[2].(error)
return ret0, ret1, ret2
}
// BucketSizeAndCount indicates an expected call of BucketSizeAndCount.
func (mr *MockbucketDataGetterMockRecorder) BucketSizeAndCount(bucket interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BucketSizeAndCount", reflect.TypeOf((*MockbucketDataGetter)(nil).BucketSizeAndCount), bucket)
}
// MockbucketNameGetter is a mock of bucketNameGetter interface.
type MockbucketNameGetter struct {
ctrl *gomock.Controller
recorder *MockbucketNameGetterMockRecorder
}
// MockbucketNameGetterMockRecorder is the mock recorder for MockbucketNameGetter.
type MockbucketNameGetterMockRecorder struct {
mock *MockbucketNameGetter
}
// NewMockbucketNameGetter creates a new mock instance.
func NewMockbucketNameGetter(ctrl *gomock.Controller) *MockbucketNameGetter {
mock := &MockbucketNameGetter{ctrl: ctrl}
mock.recorder = &MockbucketNameGetterMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockbucketNameGetter) EXPECT() *MockbucketNameGetterMockRecorder {
return m.recorder
}
// BucketName mocks base method.
func (m *MockbucketNameGetter) BucketName(app, env, svc string) (string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "BucketName", app, env, svc)
ret0, _ := ret[0].(string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// BucketName indicates an expected call of BucketName.
func (mr *MockbucketNameGetterMockRecorder) BucketName(app, env, svc interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BucketName", reflect.TypeOf((*MockbucketNameGetter)(nil).BucketName), app, env, svc)
}
| 826 |
copilot-cli | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: ./internal/pkg/describe/status.go
// Package mocks is a generated GoMock package.
package mocks
| 6 |
copilot-cli | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: ./internal/pkg/describe/status_describe.go
// Package mocks is a generated GoMock package.
package mocks
import (
reflect "reflect"
cloudwatch "github.com/aws/copilot-cli/internal/pkg/aws/cloudwatch"
cloudwatchlogs "github.com/aws/copilot-cli/internal/pkg/aws/cloudwatchlogs"
ecs "github.com/aws/copilot-cli/internal/pkg/aws/ecs"
elbv2 "github.com/aws/copilot-cli/internal/pkg/aws/elbv2"
ecs0 "github.com/aws/copilot-cli/internal/pkg/ecs"
gomock "github.com/golang/mock/gomock"
)
// MocktargetHealthGetter is a mock of targetHealthGetter interface.
type MocktargetHealthGetter struct {
ctrl *gomock.Controller
recorder *MocktargetHealthGetterMockRecorder
}
// MocktargetHealthGetterMockRecorder is the mock recorder for MocktargetHealthGetter.
type MocktargetHealthGetterMockRecorder struct {
mock *MocktargetHealthGetter
}
// NewMocktargetHealthGetter creates a new mock instance.
func NewMocktargetHealthGetter(ctrl *gomock.Controller) *MocktargetHealthGetter {
mock := &MocktargetHealthGetter{ctrl: ctrl}
mock.recorder = &MocktargetHealthGetterMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MocktargetHealthGetter) EXPECT() *MocktargetHealthGetterMockRecorder {
return m.recorder
}
// TargetsHealth mocks base method.
func (m *MocktargetHealthGetter) TargetsHealth(targetGroupARN string) ([]*elbv2.TargetHealth, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "TargetsHealth", targetGroupARN)
ret0, _ := ret[0].([]*elbv2.TargetHealth)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// TargetsHealth indicates an expected call of TargetsHealth.
func (mr *MocktargetHealthGetterMockRecorder) TargetsHealth(targetGroupARN interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TargetsHealth", reflect.TypeOf((*MocktargetHealthGetter)(nil).TargetsHealth), targetGroupARN)
}
// MockalarmStatusGetter is a mock of alarmStatusGetter interface.
type MockalarmStatusGetter struct {
ctrl *gomock.Controller
recorder *MockalarmStatusGetterMockRecorder
}
// MockalarmStatusGetterMockRecorder is the mock recorder for MockalarmStatusGetter.
type MockalarmStatusGetterMockRecorder struct {
mock *MockalarmStatusGetter
}
// NewMockalarmStatusGetter creates a new mock instance.
func NewMockalarmStatusGetter(ctrl *gomock.Controller) *MockalarmStatusGetter {
mock := &MockalarmStatusGetter{ctrl: ctrl}
mock.recorder = &MockalarmStatusGetterMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockalarmStatusGetter) EXPECT() *MockalarmStatusGetterMockRecorder {
return m.recorder
}
// AlarmStatuses mocks base method.
func (m *MockalarmStatusGetter) AlarmStatuses(arg0 ...cloudwatch.DescribeAlarmOpts) ([]cloudwatch.AlarmStatus, error) {
m.ctrl.T.Helper()
varargs := []interface{}{}
for _, a := range arg0 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "AlarmStatuses", varargs...)
ret0, _ := ret[0].([]cloudwatch.AlarmStatus)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// AlarmStatuses indicates an expected call of AlarmStatuses.
func (mr *MockalarmStatusGetterMockRecorder) AlarmStatuses(arg0 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AlarmStatuses", reflect.TypeOf((*MockalarmStatusGetter)(nil).AlarmStatuses), arg0...)
}
// AlarmsWithTags mocks base method.
func (m *MockalarmStatusGetter) AlarmsWithTags(tags map[string]string) ([]cloudwatch.AlarmStatus, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "AlarmsWithTags", tags)
ret0, _ := ret[0].([]cloudwatch.AlarmStatus)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// AlarmsWithTags indicates an expected call of AlarmsWithTags.
func (mr *MockalarmStatusGetterMockRecorder) AlarmsWithTags(tags interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AlarmsWithTags", reflect.TypeOf((*MockalarmStatusGetter)(nil).AlarmsWithTags), tags)
}
// MocklogGetter is a mock of logGetter interface.
type MocklogGetter struct {
ctrl *gomock.Controller
recorder *MocklogGetterMockRecorder
}
// MocklogGetterMockRecorder is the mock recorder for MocklogGetter.
type MocklogGetterMockRecorder struct {
mock *MocklogGetter
}
// NewMocklogGetter creates a new mock instance.
func NewMocklogGetter(ctrl *gomock.Controller) *MocklogGetter {
mock := &MocklogGetter{ctrl: ctrl}
mock.recorder = &MocklogGetterMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MocklogGetter) EXPECT() *MocklogGetterMockRecorder {
return m.recorder
}
// LogEvents mocks base method.
func (m *MocklogGetter) LogEvents(opts cloudwatchlogs.LogEventsOpts) (*cloudwatchlogs.LogEventsOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "LogEvents", opts)
ret0, _ := ret[0].(*cloudwatchlogs.LogEventsOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// LogEvents indicates an expected call of LogEvents.
func (mr *MocklogGetterMockRecorder) LogEvents(opts interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LogEvents", reflect.TypeOf((*MocklogGetter)(nil).LogEvents), opts)
}
// MockecsServiceGetter is a mock of ecsServiceGetter interface.
type MockecsServiceGetter struct {
ctrl *gomock.Controller
recorder *MockecsServiceGetterMockRecorder
}
// MockecsServiceGetterMockRecorder is the mock recorder for MockecsServiceGetter.
type MockecsServiceGetterMockRecorder struct {
mock *MockecsServiceGetter
}
// NewMockecsServiceGetter creates a new mock instance.
func NewMockecsServiceGetter(ctrl *gomock.Controller) *MockecsServiceGetter {
mock := &MockecsServiceGetter{ctrl: ctrl}
mock.recorder = &MockecsServiceGetterMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockecsServiceGetter) EXPECT() *MockecsServiceGetterMockRecorder {
return m.recorder
}
// Service mocks base method.
func (m *MockecsServiceGetter) Service(clusterName, serviceName string) (*ecs.Service, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Service", clusterName, serviceName)
ret0, _ := ret[0].(*ecs.Service)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Service indicates an expected call of Service.
func (mr *MockecsServiceGetterMockRecorder) Service(clusterName, serviceName interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Service", reflect.TypeOf((*MockecsServiceGetter)(nil).Service), clusterName, serviceName)
}
// ServiceRunningTasks mocks base method.
func (m *MockecsServiceGetter) ServiceRunningTasks(clusterName, serviceName string) ([]*ecs.Task, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ServiceRunningTasks", clusterName, serviceName)
ret0, _ := ret[0].([]*ecs.Task)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ServiceRunningTasks indicates an expected call of ServiceRunningTasks.
func (mr *MockecsServiceGetterMockRecorder) ServiceRunningTasks(clusterName, serviceName interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceRunningTasks", reflect.TypeOf((*MockecsServiceGetter)(nil).ServiceRunningTasks), clusterName, serviceName)
}
// MockserviceDescriber is a mock of serviceDescriber interface.
type MockserviceDescriber struct {
ctrl *gomock.Controller
recorder *MockserviceDescriberMockRecorder
}
// MockserviceDescriberMockRecorder is the mock recorder for MockserviceDescriber.
type MockserviceDescriberMockRecorder struct {
mock *MockserviceDescriber
}
// NewMockserviceDescriber creates a new mock instance.
func NewMockserviceDescriber(ctrl *gomock.Controller) *MockserviceDescriber {
mock := &MockserviceDescriber{ctrl: ctrl}
mock.recorder = &MockserviceDescriberMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockserviceDescriber) EXPECT() *MockserviceDescriberMockRecorder {
return m.recorder
}
// DescribeService mocks base method.
func (m *MockserviceDescriber) DescribeService(app, env, svc string) (*ecs0.ServiceDesc, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DescribeService", app, env, svc)
ret0, _ := ret[0].(*ecs0.ServiceDesc)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DescribeService indicates an expected call of DescribeService.
func (mr *MockserviceDescriberMockRecorder) DescribeService(app, env, svc interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeService", reflect.TypeOf((*MockserviceDescriber)(nil).DescribeService), app, env, svc)
}
// MockautoscalingAlarmNamesGetter is a mock of autoscalingAlarmNamesGetter interface.
type MockautoscalingAlarmNamesGetter struct {
ctrl *gomock.Controller
recorder *MockautoscalingAlarmNamesGetterMockRecorder
}
// MockautoscalingAlarmNamesGetterMockRecorder is the mock recorder for MockautoscalingAlarmNamesGetter.
type MockautoscalingAlarmNamesGetterMockRecorder struct {
mock *MockautoscalingAlarmNamesGetter
}
// NewMockautoscalingAlarmNamesGetter creates a new mock instance.
func NewMockautoscalingAlarmNamesGetter(ctrl *gomock.Controller) *MockautoscalingAlarmNamesGetter {
mock := &MockautoscalingAlarmNamesGetter{ctrl: ctrl}
mock.recorder = &MockautoscalingAlarmNamesGetterMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockautoscalingAlarmNamesGetter) EXPECT() *MockautoscalingAlarmNamesGetterMockRecorder {
return m.recorder
}
// ECSServiceAlarmNames mocks base method.
func (m *MockautoscalingAlarmNamesGetter) ECSServiceAlarmNames(cluster, service string) ([]string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ECSServiceAlarmNames", cluster, service)
ret0, _ := ret[0].([]string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ECSServiceAlarmNames indicates an expected call of ECSServiceAlarmNames.
func (mr *MockautoscalingAlarmNamesGetterMockRecorder) ECSServiceAlarmNames(cluster, service interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ECSServiceAlarmNames", reflect.TypeOf((*MockautoscalingAlarmNamesGetter)(nil).ECSServiceAlarmNames), cluster, service)
}
| 279 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package stack
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/copilot-cli/internal/pkg/aws/cloudformation"
)
type cfn interface {
Describe(name string) (*cloudformation.StackDescription, error)
StackResources(name string) ([]*cloudformation.StackResource, error)
Metadata(opt cloudformation.MetadataOpts) (string, error)
}
// StackDescription is the description of a cloudformation stack.
type StackDescription struct {
Parameters map[string]string
Tags map[string]string
Outputs map[string]string
}
// Resource contains cloudformation stack resource info.
type Resource struct {
Type string `json:"type"`
PhysicalID string `json:"physicalID"`
LogicalID string `json:"logicalID,omitempty"`
}
// HumanString returns the stringified Resource struct with human readable format.
func (c Resource) HumanString() string {
return fmt.Sprintf("%s\t%s\n", c.Type, c.PhysicalID)
}
// StackDescriber retrieves information about a stack.
type StackDescriber struct {
name string
cfn cfn
}
// NewStackDescriber instantiates a new StackDescriber.
func NewStackDescriber(stackName string, sess *session.Session) *StackDescriber {
return &StackDescriber{
name: stackName,
cfn: cloudformation.New(sess),
}
}
// Describe retrieves information about a cloudformation stack.
func (d *StackDescriber) Describe() (StackDescription, error) {
descr, err := d.cfn.Describe(d.name)
if err != nil {
return StackDescription{}, fmt.Errorf("describe stack %s: %w", d.name, err)
}
params := make(map[string]string)
for _, param := range descr.Parameters {
params[aws.StringValue(param.ParameterKey)] = aws.StringValue(param.ParameterValue)
}
outputs := make(map[string]string)
for _, out := range descr.Outputs {
outputs[aws.StringValue(out.OutputKey)] = aws.StringValue(out.OutputValue)
}
tags := make(map[string]string)
for _, tag := range descr.Tags {
tags[aws.StringValue(tag.Key)] = aws.StringValue(tag.Value)
}
return StackDescription{
Parameters: params,
Tags: tags,
Outputs: outputs,
}, nil
}
// Resources retrieves the information about a stack's resources.
func (d *StackDescriber) Resources() ([]*Resource, error) {
resources, err := d.cfn.StackResources(d.name)
if err != nil {
return nil, fmt.Errorf("retrieve resources for stack %s: %w", d.name, err)
}
return flattenResources(resources), nil
}
// StackMetadata returns the metadata of the stack.
func (d *StackDescriber) StackMetadata() (string, error) {
metadata, err := d.cfn.Metadata(cloudformation.MetadataWithStackName(d.name))
if err != nil {
return "", fmt.Errorf("get metadata for stack %s: %w", d.name, err)
}
return metadata, nil
}
// StackSetMetadata returns the metadata of the stackset.
func (d *StackDescriber) StackSetMetadata() (string, error) {
metadata, err := d.cfn.Metadata(cloudformation.MetadataWithStackSetName(d.name))
if err != nil {
return "", fmt.Errorf("get metadata for stack set %s: %w", d.name, err)
}
return metadata, nil
}
func flattenResources(stackResources []*cloudformation.StackResource) []*Resource {
var resources []*Resource
for _, stackResource := range stackResources {
resources = append(resources, &Resource{
Type: aws.StringValue(stackResource.ResourceType),
PhysicalID: aws.StringValue(stackResource.PhysicalResourceId),
LogicalID: aws.StringValue(stackResource.LogicalResourceId),
})
}
return resources
}
| 116 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package stack
import (
"errors"
"fmt"
"testing"
"github.com/aws/aws-sdk-go/aws"
sdkcfn "github.com/aws/aws-sdk-go/service/cloudformation"
"github.com/aws/copilot-cli/internal/pkg/aws/cloudformation"
"github.com/aws/copilot-cli/internal/pkg/describe/stack/mocks"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
type stackDescriberMocks struct {
cfn *mocks.Mockcfn
}
func TestStackDescriber_Describe(t *testing.T) {
const mockStackName = "phonetool"
mockErr := errors.New("some error")
testCases := map[string]struct {
setupMocks func(mocks stackDescriberMocks)
wantedDescription StackDescription
wantedError error
}{
"return error if fail to describe stack": {
setupMocks: func(m stackDescriberMocks) {
gomock.InOrder(
m.cfn.EXPECT().Describe(mockStackName).Return(nil, mockErr),
)
},
wantedError: fmt.Errorf("describe stack phonetool: some error"),
},
"success": {
setupMocks: func(m stackDescriberMocks) {
gomock.InOrder(
m.cfn.EXPECT().Describe(mockStackName).Return(&cloudformation.StackDescription{
Parameters: []*sdkcfn.Parameter{
{
ParameterKey: aws.String("mockParamKey"),
ParameterValue: aws.String("mockParamVal"),
},
},
Outputs: []*sdkcfn.Output{
{
OutputKey: aws.String("mockOutputKey"),
OutputValue: aws.String("mockOutputVal"),
},
},
Tags: []*sdkcfn.Tag{
{
Key: aws.String("mockTagKey"),
Value: aws.String("mockTagVal"),
},
},
}, nil),
)
},
wantedDescription: StackDescription{
Parameters: map[string]string{"mockParamKey": "mockParamVal"},
Tags: map[string]string{"mockTagKey": "mockTagVal"},
Outputs: map[string]string{"mockOutputKey": "mockOutputVal"},
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockcfn := mocks.NewMockcfn(ctrl)
mocks := stackDescriberMocks{
cfn: mockcfn,
}
tc.setupMocks(mocks)
d := &StackDescriber{
name: mockStackName,
cfn: mockcfn,
}
// WHEN
actual, err := d.Describe()
// THEN
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedDescription, actual)
}
})
}
}
func TestStackDescriber_Resources(t *testing.T) {
const mockStackName = "phonetool"
mockErr := errors.New("some error")
testCases := map[string]struct {
setupMocks func(mocks stackDescriberMocks)
wantedResources []*Resource
wantedError error
}{
"return error if fail to get stack resources": {
setupMocks: func(m stackDescriberMocks) {
gomock.InOrder(
m.cfn.EXPECT().StackResources(mockStackName).Return(nil, mockErr),
)
},
wantedError: fmt.Errorf("retrieve resources for stack phonetool: some error"),
},
"success": {
setupMocks: func(m stackDescriberMocks) {
gomock.InOrder(
m.cfn.EXPECT().StackResources(mockStackName).Return([]*cloudformation.StackResource{
{
ResourceType: aws.String("mockResourceType"),
PhysicalResourceId: aws.String("mockPhysicalID"),
LogicalResourceId: aws.String("mockLogicalID"),
},
}, nil),
)
},
wantedResources: []*Resource{
{
Type: "mockResourceType",
PhysicalID: "mockPhysicalID",
LogicalID: "mockLogicalID",
},
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockcfn := mocks.NewMockcfn(ctrl)
mocks := stackDescriberMocks{
cfn: mockcfn,
}
tc.setupMocks(mocks)
d := &StackDescriber{
name: mockStackName,
cfn: mockcfn,
}
// WHEN
actual, err := d.Resources()
// THEN
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
require.ElementsMatch(t, tc.wantedResources, actual)
}
})
}
}
func TestStackDescriber_Metadata(t *testing.T) {
const mockStackName = "phonetool"
mockErr := errors.New("some error")
testCases := map[string]struct {
setupMocks func(mocks stackDescriberMocks)
wantedMetadata string
wantedError error
}{
"return error if fail to get stack metadata": {
setupMocks: func(m stackDescriberMocks) {
gomock.InOrder(
m.cfn.EXPECT().Metadata(gomock.Any()).Return("", mockErr),
)
},
wantedError: fmt.Errorf("get metadata for stack phonetool: some error"),
},
"success": {
setupMocks: func(m stackDescriberMocks) {
gomock.InOrder(
m.cfn.EXPECT().Metadata(gomock.Any()).Return("mockMetadata", nil),
)
},
wantedMetadata: "mockMetadata",
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockcfn := mocks.NewMockcfn(ctrl)
mocks := stackDescriberMocks{
cfn: mockcfn,
}
tc.setupMocks(mocks)
d := &StackDescriber{
name: mockStackName,
cfn: mockcfn,
}
// WHEN
actual, err := d.StackMetadata()
// THEN
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedMetadata, actual)
}
})
}
}
| 231 |
copilot-cli | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: ./internal/pkg/describe/stack/stack.go
// Package mocks is a generated GoMock package.
package mocks
import (
reflect "reflect"
cloudformation "github.com/aws/copilot-cli/internal/pkg/aws/cloudformation"
gomock "github.com/golang/mock/gomock"
)
// Mockcfn is a mock of cfn interface.
type Mockcfn struct {
ctrl *gomock.Controller
recorder *MockcfnMockRecorder
}
// MockcfnMockRecorder is the mock recorder for Mockcfn.
type MockcfnMockRecorder struct {
mock *Mockcfn
}
// NewMockcfn creates a new mock instance.
func NewMockcfn(ctrl *gomock.Controller) *Mockcfn {
mock := &Mockcfn{ctrl: ctrl}
mock.recorder = &MockcfnMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *Mockcfn) EXPECT() *MockcfnMockRecorder {
return m.recorder
}
// Describe mocks base method.
func (m *Mockcfn) Describe(name string) (*cloudformation.StackDescription, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Describe", name)
ret0, _ := ret[0].(*cloudformation.StackDescription)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Describe indicates an expected call of Describe.
func (mr *MockcfnMockRecorder) Describe(name interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Describe", reflect.TypeOf((*Mockcfn)(nil).Describe), name)
}
// Metadata mocks base method.
func (m *Mockcfn) Metadata(opt cloudformation.MetadataOpts) (string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Metadata", opt)
ret0, _ := ret[0].(string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Metadata indicates an expected call of Metadata.
func (mr *MockcfnMockRecorder) Metadata(opt interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Metadata", reflect.TypeOf((*Mockcfn)(nil).Metadata), opt)
}
// StackResources mocks base method.
func (m *Mockcfn) StackResources(name string) ([]*cloudformation.StackResource, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "StackResources", name)
ret0, _ := ret[0].([]*cloudformation.StackResource)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// StackResources indicates an expected call of StackResources.
func (mr *MockcfnMockRecorder) StackResources(name interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StackResources", reflect.TypeOf((*Mockcfn)(nil).StackResources), name)
}
| 81 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package dockerengine provides functionality to interact with the Docker server.
package dockerengine
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"os"
osexec "os/exec"
"path/filepath"
"sort"
"strings"
"github.com/aws/copilot-cli/internal/pkg/exec"
)
// Cmd is the interface implemented by external commands.
type Cmd interface {
Run(name string, args []string, options ...exec.CmdOption) error
RunWithContext(ctx context.Context, name string, args []string, opts ...exec.CmdOption) error
}
// Operating systems and architectures supported by docker.
const (
OSLinux = "linux"
OSWindows = "windows"
ArchAMD64 = "amd64"
ArchX86 = "x86_64"
ArchARM = "arm"
ArchARM64 = "arm64"
)
const (
credStoreECRLogin = "ecr-login" // set on `credStore` attribute in docker configuration file
)
// DockerCmdClient represents the docker client to interact with the server via external commands.
type DockerCmdClient struct {
runner Cmd
// Override in unit tests.
buf *bytes.Buffer
homePath string
lookupEnv func(string) (string, bool)
}
// New returns CmdClient to make requests against the Docker daemon via external commands.
func New(cmd Cmd) DockerCmdClient {
return DockerCmdClient{
runner: cmd,
homePath: userHomeDirectory(),
lookupEnv: os.LookupEnv,
}
}
// BuildArguments holds the arguments that can be passed while building a container.
type BuildArguments struct {
URI string // Required. Location of ECR Repo. Used to generate image name in conjunction with tag.
Tags []string // Required. List of tags to apply to the image.
Dockerfile string // Required. Dockerfile to pass to `docker build` via --file flag.
Context string // Optional. Build context directory to pass to `docker build`.
Target string // Optional. The target build stage to pass to `docker build`.
CacheFrom []string // Optional. Images to consider as cache sources to pass to `docker build`
Platform string // Optional. OS/Arch to pass to `docker build`.
Args map[string]string // Optional. Build args to pass via `--build-arg` flags. Equivalent to ARG directives in dockerfile.
Labels map[string]string // Required. Set metadata for an image.
}
// GenerateDockerBuildArgs returns command line arguments to be passed to the Docker build command based on the provided BuildArguments.
// Returns an error if no tags are provided for building an image.
func (in *BuildArguments) GenerateDockerBuildArgs(c DockerCmdClient) ([]string, error) {
// Tags must not be empty to build an docker image.
if len(in.Tags) == 0 {
return nil, &errEmptyImageTags{
uri: in.URI,
}
}
dfDir := in.Context
// Context wasn't specified use the Dockerfile's directory as context.
if dfDir == "" {
dfDir = filepath.Dir(in.Dockerfile)
}
args := []string{"build"}
// Add additional image tags to the docker build call.
for _, tag := range in.Tags {
args = append(args, "-t", imageName(in.URI, tag))
}
// Add cache from options.
for _, imageFrom := range in.CacheFrom {
args = append(args, "--cache-from", imageFrom)
}
// Add target option.
if in.Target != "" {
args = append(args, "--target", in.Target)
}
// Add platform option.
if in.Platform != "" {
args = append(args, "--platform", in.Platform)
}
// Plain display if we're in a CI environment.
if ci, _ := c.lookupEnv("CI"); ci == "true" {
args = append(args, "--progress", "plain")
}
// Add the "args:" override section from manifest to the docker build call.
// Collect the keys in a slice to sort for test stability.
var keys []string
for k := range in.Args {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
args = append(args, "--build-arg", fmt.Sprintf("%s=%s", k, in.Args[k]))
}
// Add Labels to docker build call.
// Collect the keys in a slice to sort for test stability.
var labelKeys []string
for k := range in.Labels {
labelKeys = append(labelKeys, k)
}
sort.Strings(labelKeys)
for _, k := range labelKeys {
args = append(args, "--label", fmt.Sprintf("%s=%s", k, in.Labels[k]))
}
args = append(args, dfDir, "-f", in.Dockerfile)
return args, nil
}
type dockerConfig struct {
CredsStore string `json:"credsStore,omitempty"`
CredHelpers map[string]string `json:"credHelpers,omitempty"`
}
// Build will run a `docker build` command for the given ecr repo URI and build arguments.
func (c DockerCmdClient) Build(ctx context.Context, in *BuildArguments, w io.Writer) error {
args, err := in.GenerateDockerBuildArgs(c)
if err != nil {
return fmt.Errorf("generate docker build args: %w", err)
}
if err := c.runner.RunWithContext(ctx, "docker", args, exec.Stdout(w), exec.Stderr(w)); err != nil {
return fmt.Errorf("building image: %w", err)
}
return nil
}
// Login will run a `docker login` command against the Service repository URI with the input uri and auth data.
func (c DockerCmdClient) Login(uri, username, password string) error {
err := c.runner.Run("docker",
[]string{"login", "-u", username, "--password-stdin", uri},
exec.Stdin(strings.NewReader(password)))
if err != nil {
return fmt.Errorf("authenticate to ECR: %w", err)
}
return nil
}
// Push pushes the images with the specified tags and ecr repository URI, and returns the image digest on success.
func (c DockerCmdClient) Push(ctx context.Context, uri string, w io.Writer, tags ...string) (digest string, err error) {
images := []string{}
for _, tag := range tags {
images = append(images, imageName(uri, tag))
}
var args []string
if ci, _ := c.lookupEnv("CI"); ci == "true" {
args = append(args, "--quiet")
}
for _, img := range images {
if err := c.runner.RunWithContext(ctx, "docker", append([]string{"push", img}, args...), exec.Stdout(w), exec.Stderr(w)); err != nil {
return "", fmt.Errorf("docker push %s: %w", img, err)
}
}
buf := new(strings.Builder)
// The container image will have the same digest regardless of the associated tag.
// Pick the first tag and get the image's digest.
// For Main container we call docker inspect --format '{{json (index .RepoDigests 0)}}' uri:latest
// For Sidecar container images we call docker inspect --format '{{json (index .RepoDigests 0)}}' uri:<sidecarname>-latest
if err := c.runner.RunWithContext(ctx, "docker", []string{"inspect", "--format", "'{{json (index .RepoDigests 0)}}'", imageName(uri, tags[0])}, exec.Stdout(buf)); err != nil {
return "", fmt.Errorf("inspect image digest for %s: %w", uri, err)
}
repoDigest := strings.Trim(strings.TrimSpace(buf.String()), `"'`) // remove new lines and quotes from output
parts := strings.SplitAfter(repoDigest, "@")
if len(parts) != 2 {
return "", fmt.Errorf("parse the digest from the repo digest '%s'", repoDigest)
}
return parts[1], nil
}
// CheckDockerEngineRunning will run `docker info` command to check if the docker engine is running.
func (c DockerCmdClient) CheckDockerEngineRunning() error {
if _, err := osexec.LookPath("docker"); err != nil {
return ErrDockerCommandNotFound
}
buf := &bytes.Buffer{}
err := c.runner.Run("docker", []string{"info", "-f", "'{{json .}}'"}, exec.Stdout(buf))
if err != nil {
return fmt.Errorf("get docker info: %w", err)
}
// Trim redundant prefix and suffix. For example: '{"ServerErrors":["Cannot connect...}'\n returns
// {"ServerErrors":["Cannot connect...}
out := strings.TrimSuffix(strings.TrimPrefix(strings.TrimSpace(buf.String()), "'"), "'")
type dockerEngineNotRunningMsg struct {
ServerErrors []string `json:"ServerErrors"`
}
var msg dockerEngineNotRunningMsg
if err := json.Unmarshal([]byte(out), &msg); err != nil {
return fmt.Errorf("unmarshal docker info message: %w", err)
}
if len(msg.ServerErrors) == 0 {
return nil
}
return &ErrDockerDaemonNotResponsive{
msg: strings.Join(msg.ServerErrors, "\n"),
}
}
// GetPlatform will run the `docker version` command to get the OS/Arch.
func (c DockerCmdClient) GetPlatform() (os, arch string, err error) {
if _, err := osexec.LookPath("docker"); err != nil {
return "", "", ErrDockerCommandNotFound
}
buf := &bytes.Buffer{}
err = c.runner.Run("docker", []string{"version", "-f", "'{{json .Server}}'"}, exec.Stdout(buf))
if err != nil {
return "", "", fmt.Errorf("run docker version: %w", err)
}
out := strings.TrimSuffix(strings.TrimPrefix(strings.TrimSpace(buf.String()), "'"), "'")
type dockerServer struct {
OS string `json:"Os"`
Arch string `json:"Arch"`
}
var platform dockerServer
if err := json.Unmarshal([]byte(out), &platform); err != nil {
return "", "", fmt.Errorf("unmarshal docker platform: %w", err)
}
return platform.OS, platform.Arch, nil
}
func imageName(uri, tag string) string {
return fmt.Sprintf("%s:%s", uri, tag)
}
// IsEcrCredentialHelperEnabled return true if ecr-login is enabled either globally or registry level
func (c DockerCmdClient) IsEcrCredentialHelperEnabled(uri string) bool {
// Make sure the program is able to obtain the home directory
splits := strings.Split(uri, "/")
if c.homePath == "" || len(splits) == 0 {
return false
}
// Look into the default locations
pathsToTry := []string{filepath.Join(".docker", "config.json"), ".dockercfg"}
for _, path := range pathsToTry {
content, err := os.ReadFile(filepath.Join(c.homePath, path))
if err != nil {
// if we can't read the file keep going
continue
}
config, err := parseCredFromDockerConfig(content)
if err != nil {
continue
}
if config.CredsStore == credStoreECRLogin || config.CredHelpers[splits[0]] == credStoreECRLogin {
return true
}
}
return false
}
// PlatformString returns a specified of the format <os>/<arch>.
func PlatformString(os, arch string) string {
return fmt.Sprintf("%s/%s", os, arch)
}
func parseCredFromDockerConfig(config []byte) (*dockerConfig, error) {
/*
Sample docker config file
{
"credsStore" : "ecr-login",
"credHelpers": {
"dummyaccountId.dkr.ecr.region.amazonaws.com": "ecr-login"
}
}
*/
cred := dockerConfig{}
err := json.Unmarshal(config, &cred)
if err != nil {
return nil, err
}
return &cred, nil
}
func userHomeDirectory() string {
home, err := os.UserHomeDir()
if err != nil {
return ""
}
return home
}
type errEmptyImageTags struct {
uri string
}
func (e *errEmptyImageTags) Error() string {
return fmt.Sprintf("tags to reference an image should not be empty for building and pushing into the ECR repository %s", e.uri)
}
| 330 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package dockerengine
import (
"bytes"
"context"
"errors"
"fmt"
osexec "os/exec"
"path/filepath"
"strings"
"testing"
"github.com/aws/copilot-cli/internal/pkg/exec"
"github.com/golang/mock/gomock"
"github.com/spf13/afero"
"github.com/stretchr/testify/require"
)
func TestDockerCommand_Build(t *testing.T) {
mockError := errors.New("mockError")
mockURI := "mockURI"
mockPath := "mockPath/to/mockDockerfile"
mockContext := "mockPath"
mockTag1 := "tag1"
mockTag2 := "tag2"
mockTag3 := "tag3"
mockContainerName := "mockWkld"
ctx := context.Background()
var mockCmd *MockCmd
tests := map[string]struct {
path string
context string
tags []string
args map[string]string
target string
cacheFrom []string
envVars map[string]string
labels map[string]string
setupMocks func(controller *gomock.Controller)
wantedError error
}{
"should error tags are not specified": {
path: mockPath,
context: "",
setupMocks: func(controller *gomock.Controller) {
mockCmd = NewMockCmd(controller)
},
wantedError: fmt.Errorf("generate docker build args: tags to reference an image should not be empty for building and pushing into the ECR repository %s", mockURI),
},
"should error if the docker build command fails": {
path: mockPath,
context: "",
tags: []string{mockTag1},
setupMocks: func(controller *gomock.Controller) {
mockCmd = NewMockCmd(controller)
mockCmd.EXPECT().RunWithContext(ctx, "docker", []string{"build",
"-t", mockURI + ":" + mockTag1,
filepath.FromSlash("mockPath/to"),
"-f", "mockPath/to/mockDockerfile"}, gomock.Any(), gomock.Any()).Return(mockError)
},
wantedError: fmt.Errorf("building image: %w", mockError),
},
"should succeed in simple case with no context": {
path: mockPath,
context: "",
tags: []string{mockTag1},
setupMocks: func(controller *gomock.Controller) {
mockCmd = NewMockCmd(controller)
mockCmd.EXPECT().RunWithContext(ctx, "docker", []string{"build",
"-t", "mockURI:tag1", filepath.FromSlash("mockPath/to"),
"-f", "mockPath/to/mockDockerfile"}, gomock.Any(), gomock.Any()).Return(nil)
},
},
"should display quiet progress updates when in a CI environment": {
path: mockPath,
tags: []string{mockTag1},
context: "",
envVars: map[string]string{
"CI": "true",
},
setupMocks: func(controller *gomock.Controller) {
mockCmd = NewMockCmd(controller)
mockCmd.EXPECT().RunWithContext(ctx, "docker", []string{"build",
"-t", fmt.Sprintf("%s:%s", mockURI, mockTag1),
"--progress", "plain",
filepath.FromSlash("mockPath/to"), "-f", "mockPath/to/mockDockerfile"}, gomock.Any(), gomock.Any()).
Return(nil)
},
},
"context differs from path": {
path: mockPath,
tags: []string{mockTag1},
context: mockContext,
setupMocks: func(controller *gomock.Controller) {
mockCmd = NewMockCmd(controller)
mockCmd.EXPECT().RunWithContext(ctx, "docker", []string{"build",
"-t", fmt.Sprintf("%s:%s", mockURI, mockTag1),
"mockPath",
"-f", "mockPath/to/mockDockerfile"}, gomock.Any(), gomock.Any()).Return(nil)
},
},
"behaves the same if context is DF dir": {
path: mockPath,
context: "mockPath/to",
tags: []string{mockTag1},
setupMocks: func(controller *gomock.Controller) {
mockCmd = NewMockCmd(controller)
mockCmd.EXPECT().RunWithContext(ctx, "docker", []string{"build",
"-t", mockURI + ":" + mockTag1,
"mockPath/to",
"-f", "mockPath/to/mockDockerfile"}, gomock.Any(), gomock.Any()).Return(nil)
},
},
"success with additional tags": {
path: mockPath,
tags: []string{mockTag1, mockTag2, mockTag3},
setupMocks: func(controller *gomock.Controller) {
mockCmd = NewMockCmd(controller)
mockCmd.EXPECT().RunWithContext(ctx, "docker", []string{"build",
"-t", mockURI + ":" + mockTag1,
"-t", mockURI + ":" + mockTag2,
"-t", mockURI + ":" + mockTag3,
filepath.FromSlash("mockPath/to"),
"-f", "mockPath/to/mockDockerfile"}, gomock.Any(), gomock.Any()).Return(nil)
},
},
"success with build args": {
path: mockPath,
tags: []string{"latest"},
args: map[string]string{
"GOPROXY": "direct",
"key": "value",
"abc": "def",
},
setupMocks: func(c *gomock.Controller) {
mockCmd = NewMockCmd(c)
mockCmd.EXPECT().RunWithContext(ctx, "docker", []string{"build",
"-t", fmt.Sprintf("%s:%s", mockURI, "latest"),
"--build-arg", "GOPROXY=direct",
"--build-arg", "abc=def",
"--build-arg", "key=value",
filepath.FromSlash("mockPath/to"),
"-f", "mockPath/to/mockDockerfile"}, gomock.Any(), gomock.Any()).Return(nil)
},
},
"success with labels": {
path: mockPath,
tags: []string{"latest"},
labels: map[string]string{
"com.aws.copilot.image.version": "v1.26.0",
"com.aws.copilot.image.builder": "copilot-cli",
"com.aws.copilot.image.container.name": mockContainerName,
},
setupMocks: func(c *gomock.Controller) {
mockCmd = NewMockCmd(c)
mockCmd.EXPECT().RunWithContext(ctx, "docker", []string{"build",
"-t", fmt.Sprintf("%s:%s", mockURI, "latest"),
"--label", "com.aws.copilot.image.builder=copilot-cli",
"--label", "com.aws.copilot.image.container.name=mockWkld",
"--label", "com.aws.copilot.image.version=v1.26.0",
filepath.FromSlash("mockPath/to"),
"-f", "mockPath/to/mockDockerfile"}, gomock.Any(), gomock.Any()).Return(nil)
},
},
"runs with cache_from and target fields": {
path: mockPath,
tags: []string{"latest"},
target: "foobar",
cacheFrom: []string{"foo/bar:latest", "foo/bar/baz:1.2.3"},
setupMocks: func(c *gomock.Controller) {
mockCmd = NewMockCmd(c)
mockCmd.EXPECT().RunWithContext(ctx, "docker", []string{"build",
"-t", fmt.Sprintf("%s:%s", mockURI, "latest"),
"--cache-from", "foo/bar:latest",
"--cache-from", "foo/bar/baz:1.2.3",
"--target", "foobar",
filepath.FromSlash("mockPath/to"),
"-f", "mockPath/to/mockDockerfile"}, gomock.Any(), gomock.Any()).Return(nil)
},
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
controller := gomock.NewController(t)
tc.setupMocks(controller)
s := DockerCmdClient{
runner: mockCmd,
lookupEnv: func(key string) (string, bool) {
if val, ok := tc.envVars[key]; ok {
return val, true
}
return "", false
},
}
buildInput := BuildArguments{
Context: tc.context,
Dockerfile: tc.path,
URI: mockURI,
Args: tc.args,
Target: tc.target,
CacheFrom: tc.cacheFrom,
Tags: tc.tags,
Labels: tc.labels,
}
buf := new(strings.Builder)
got := s.Build(ctx, &buildInput, buf)
if tc.wantedError != nil {
require.EqualError(t, tc.wantedError, got.Error())
} else {
require.Nil(t, got)
}
})
}
}
func TestDockerCommand_Login(t *testing.T) {
mockError := errors.New("mockError")
mockURI := "mockURI"
mockUsername := "mockUsername"
mockPassword := "mockPassword"
var mockCmd *MockCmd
tests := map[string]struct {
setupMocks func(controller *gomock.Controller)
want error
}{
"wrap error returned from Run()": {
setupMocks: func(controller *gomock.Controller) {
mockCmd = NewMockCmd(controller)
mockCmd.EXPECT().Run("docker", []string{"login", "-u", mockUsername, "--password-stdin", mockURI}, gomock.Any()).Return(mockError)
},
want: fmt.Errorf("authenticate to ECR: %w", mockError),
},
"happy path": {
setupMocks: func(controller *gomock.Controller) {
mockCmd = NewMockCmd(controller)
mockCmd.EXPECT().Run("docker", []string{"login", "-u", mockUsername, "--password-stdin", mockURI}, gomock.Any()).Return(nil)
},
want: nil,
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
controller := gomock.NewController(t)
test.setupMocks(controller)
s := DockerCmdClient{
runner: mockCmd,
}
got := s.Login(mockURI, mockUsername, mockPassword)
require.Equal(t, test.want, got)
})
}
}
func TestDockerCommand_Push(t *testing.T) {
emptyLookupEnv := func(key string) (string, bool) {
return "", false
}
ctx := context.Background()
t.Run("pushes an image with multiple tags and returns its digest", func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := NewMockCmd(ctrl)
m.EXPECT().RunWithContext(ctx, "docker", []string{"push", "aws_account_id.dkr.ecr.region.amazonaws.com/my-web-app:latest"}, gomock.Any(), gomock.Any()).Return(nil)
m.EXPECT().RunWithContext(ctx, "docker", []string{"push", "aws_account_id.dkr.ecr.region.amazonaws.com/my-web-app:g123bfc"}, gomock.Any(), gomock.Any()).Return(nil)
m.EXPECT().RunWithContext(ctx, "docker", []string{"inspect", "--format", "'{{json (index .RepoDigests 0)}}'", "aws_account_id.dkr.ecr.region.amazonaws.com/my-web-app:latest"}, gomock.Any()).
Do(func(ctx context.Context, _ string, _ []string, opt exec.CmdOption) {
cmd := &osexec.Cmd{}
opt(cmd)
_, _ = cmd.Stdout.Write([]byte("\"aws_account_id.dkr.ecr.region.amazonaws.com/my-web-app@sha256:f1d4ae3f7261a72e98c6ebefe9985cf10a0ea5bd762585a43e0700ed99863807\"\n"))
}).Return(nil)
// WHEN
cmd := DockerCmdClient{
runner: m,
lookupEnv: emptyLookupEnv,
}
buf := new(strings.Builder)
digest, err := cmd.Push(ctx, "aws_account_id.dkr.ecr.region.amazonaws.com/my-web-app", buf, "latest", "g123bfc")
// THEN
require.NoError(t, err)
require.Equal(t, "sha256:f1d4ae3f7261a72e98c6ebefe9985cf10a0ea5bd762585a43e0700ed99863807", digest)
})
t.Run("should display quiet progress updates when in a CI environment", func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := NewMockCmd(ctrl)
m.EXPECT().RunWithContext(ctx, "docker", []string{"push", "aws_account_id.dkr.ecr.region.amazonaws.com/my-web-app:latest", "--quiet"}, gomock.Any(), gomock.Any()).Return(nil)
m.EXPECT().RunWithContext(ctx, "docker", []string{"inspect", "--format", "'{{json (index .RepoDigests 0)}}'", "aws_account_id.dkr.ecr.region.amazonaws.com/my-web-app:latest"}, gomock.Any()).
Do(func(ctx context.Context, _ string, _ []string, opt exec.CmdOption) {
cmd := &osexec.Cmd{}
opt(cmd)
_, _ = cmd.Stdout.Write([]byte("\"aws_account_id.dkr.ecr.region.amazonaws.com/my-web-app@sha256:f1d4ae3f7261a72e98c6ebefe9985cf10a0ea5bd762585a43e0700ed99863807\"\n"))
}).Return(nil)
// WHEN
cmd := DockerCmdClient{
runner: m,
lookupEnv: func(key string) (string, bool) {
if key == "CI" {
return "true", true
}
return "", false
},
}
buf := new(strings.Builder)
digest, err := cmd.Push(context.Background(), "aws_account_id.dkr.ecr.region.amazonaws.com/my-web-app", buf, "latest")
// THEN
require.NoError(t, err)
require.Equal(t, "sha256:f1d4ae3f7261a72e98c6ebefe9985cf10a0ea5bd762585a43e0700ed99863807", digest)
})
t.Run("returns a wrapped error on failed push to ecr", func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := NewMockCmd(ctrl)
m.EXPECT().RunWithContext(ctx, gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(errors.New("some error"))
// WHEN
cmd := DockerCmdClient{
runner: m,
lookupEnv: emptyLookupEnv,
}
buf := new(strings.Builder)
_, err := cmd.Push(ctx, "uri", buf, "latest")
// THEN
require.EqualError(t, err, "docker push uri:latest: some error")
})
t.Run("returns a wrapped error on failure to retrieve image digest", func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := NewMockCmd(ctrl)
m.EXPECT().RunWithContext(ctx, "docker", []string{"push", "uri:latest"}, gomock.Any(), gomock.Any()).Return(nil)
m.EXPECT().RunWithContext(ctx, "docker", []string{"inspect", "--format", "'{{json (index .RepoDigests 0)}}'", "uri:latest"}, gomock.Any()).Return(errors.New("some error"))
// WHEN
cmd := DockerCmdClient{
runner: m,
lookupEnv: emptyLookupEnv,
}
buf := new(strings.Builder)
_, err := cmd.Push(ctx, "uri", buf, "latest")
// THEN
require.EqualError(t, err, "inspect image digest for uri: some error")
})
t.Run("returns an error if the repo digest cannot be parsed for the pushed image", func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := NewMockCmd(ctrl)
m.EXPECT().RunWithContext(ctx, "docker", []string{"push", "aws_account_id.dkr.ecr.region.amazonaws.com/my-web-app:latest"}, gomock.Any(), gomock.Any()).Return(nil)
m.EXPECT().RunWithContext(ctx, "docker", []string{"push", "aws_account_id.dkr.ecr.region.amazonaws.com/my-web-app:g123bfc"}, gomock.Any(), gomock.Any()).Return(nil)
m.EXPECT().RunWithContext(ctx, "docker", []string{"inspect", "--format", "'{{json (index .RepoDigests 0)}}'", "aws_account_id.dkr.ecr.region.amazonaws.com/my-web-app:latest"}, gomock.Any()).
Do(func(ctx context.Context, _ string, _ []string, opt exec.CmdOption) {
cmd := &osexec.Cmd{}
opt(cmd)
_, _ = cmd.Stdout.Write([]byte(""))
}).Return(nil)
// WHEN
cmd := DockerCmdClient{
runner: m,
lookupEnv: emptyLookupEnv,
}
buf := new(strings.Builder)
_, err := cmd.Push(ctx, "aws_account_id.dkr.ecr.region.amazonaws.com/my-web-app", buf, "latest", "g123bfc")
// THEN
require.EqualError(t, err, "parse the digest from the repo digest ''")
})
}
func TestDockerCommand_CheckDockerEngineRunning(t *testing.T) {
mockError := errors.New("some error")
var mockCmd *MockCmd
tests := map[string]struct {
setupMocks func(controller *gomock.Controller)
wantedErr error
}{
"error running docker info": {
setupMocks: func(controller *gomock.Controller) {
mockCmd = NewMockCmd(controller)
mockCmd.EXPECT().Run("docker", []string{"info", "-f", "'{{json .}}'"}, gomock.Any()).Return(mockError)
},
wantedErr: fmt.Errorf("get docker info: some error"),
},
"return when docker engine is not started": {
setupMocks: func(controller *gomock.Controller) {
mockCmd = NewMockCmd(controller)
mockCmd.EXPECT().Run("docker", []string{"info", "-f", "'{{json .}}'"}, gomock.Any()).
Do(func(_ string, _ []string, opt exec.CmdOption) {
cmd := &osexec.Cmd{}
opt(cmd)
_, _ = cmd.Stdout.Write([]byte(`'{"ServerErrors":["Cannot connect to the Docker daemon at unix:///var/run/docker.sock.", "Is the docker daemon running?"]}'`))
}).Return(nil)
},
wantedErr: &ErrDockerDaemonNotResponsive{
msg: "Cannot connect to the Docker daemon at unix:///var/run/docker.sock.\nIs the docker daemon running?",
},
},
"success": {
setupMocks: func(controller *gomock.Controller) {
mockCmd = NewMockCmd(controller)
mockCmd.EXPECT().Run("docker", []string{"info", "-f", "'{{json .}}'"}, gomock.Any()).
Do(func(_ string, _ []string, opt exec.CmdOption) {
cmd := &osexec.Cmd{}
opt(cmd)
_, _ = cmd.Stdout.Write([]byte(`'{"ID":"A2VY:4WTA:HDKK:UR76:SD2I:EQYZ:GCED:H4GT:6O7X:P72W:LCUP:ZQJD","Containers":15}'
`))
}).Return(nil)
},
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
controller := gomock.NewController(t)
tc.setupMocks(controller)
s := DockerCmdClient{
runner: mockCmd,
}
err := s.CheckDockerEngineRunning()
if tc.wantedErr == nil {
require.NoError(t, err)
} else {
require.EqualError(t, err, tc.wantedErr.Error())
}
})
}
}
func TestDockerCommand_GetPlatform(t *testing.T) {
mockError := errors.New("some error")
var mockCmd *MockCmd
tests := map[string]struct {
setupMocks func(controller *gomock.Controller)
wantedOS string
wantedArch string
wantedErr error
}{
"error running 'docker version'": {
setupMocks: func(controller *gomock.Controller) {
mockCmd = NewMockCmd(controller)
mockCmd.EXPECT().Run("docker", []string{"version", "-f", "'{{json .Server}}'"}, gomock.Any()).Return(mockError)
},
wantedOS: "",
wantedArch: "",
wantedErr: fmt.Errorf("run docker version: some error"),
},
"successfully returns os and arch": {
setupMocks: func(controller *gomock.Controller) {
mockCmd = NewMockCmd(controller)
mockCmd.EXPECT().Run("docker", []string{"version", "-f", "'{{json .Server}}'"}, gomock.Any()).
Do(func(_ string, _ []string, opt exec.CmdOption) {
cmd := &osexec.Cmd{}
opt(cmd)
_, _ = cmd.Stdout.Write([]byte("{\"Platform\":{\"Name\":\"Docker DockerCmdClient - Community\"},\"Components\":[{\"Name\":\"DockerCmdClient\",\"Version\":\"20.10.6\",\"Details\":{\"ApiVersion\":\"1.41\",\"Arch\":\"amd64\",\"BuildTime\":\"Fri Apr 9 22:44:56 2021\",\"Experimental\":\"false\",\"GitCommit\":\"8728dd2\",\"GoVersion\":\"go1.13.15\",\"KernelVersion\":\"5.10.25-linuxkit\",\"MinAPIVersion\":\"1.12\",\"Os\":\"linux\"}},{\"Name\":\"containerd\",\"Version\":\"1.4.4\",\"Details\":{\"GitCommit\":\"05f951a3781f4f2c1911b05e61c16e\"}},{\"Name\":\"runc\",\"Version\":\"1.0.0-rc93\",\"Details\":{\"GitCommit\":\"12644e614e25b05da6fd00cfe1903fdec\"}},{\"Name\":\"docker-init\",\"Version\":\"0.19.0\",\"Details\":{\"GitCommit\":\"de40ad0\"}}],\"Version\":\"20.10.6\",\"ApiVersion\":\"1.41\",\"MinAPIVersion\":\"1.12\",\"GitCommit\":\"8728dd2\",\"GoVersion\":\"go1.13.15\",\"Os\":\"linux\",\"Arch\":\"amd64\",\"KernelVersion\":\"5.10.25-linuxkit\",\"BuildTime\":\"2021-04-09T22:44:56.000000000+00:00\"}\n"))
}).Return(nil)
},
wantedOS: "linux",
wantedArch: "amd64",
wantedErr: nil,
},
"successfully returns 'windows/amd64' if that's what's detected": {
setupMocks: func(controller *gomock.Controller) {
mockCmd = NewMockCmd(controller)
mockCmd.EXPECT().Run("docker", []string{"version", "-f", "'{{json .Server}}'"}, gomock.Any()).
Do(func(_ string, _ []string, opt exec.CmdOption) {
cmd := &osexec.Cmd{}
opt(cmd)
_, _ = cmd.Stdout.Write([]byte("{\"Platform\":{\"Name\":\"Docker DockerCmdClient - Community\"},\"Components\":[{\"Name\":\"DockerCmdClient\",\"Version\":\"20.10.6\",\"Details\":{\"ApiVersion\":\"1.41\",\"Arch\":\"amd64\",\"BuildTime\":\"Fri Apr 9 22:44:56 2021\",\"Experimental\":\"false\",\"GitCommit\":\"8728dd2\",\"GoVersion\":\"go1.13.15\",\"KernelVersion\":\"5.10.25-linuxkit\",\"MinAPIVersion\":\"1.12\",\"Os\":\"linux\"}},{\"Name\":\"containerd\",\"Version\":\"1.4.4\",\"Details\":{\"GitCommit\":\"05f951a3781f4f2c1911b05e61c16e\"}},{\"Name\":\"runc\",\"Version\":\"1.0.0-rc93\",\"Details\":{\"GitCommit\":\"12644e614e25b05da6fd00cfe1903fdec\"}},{\"Name\":\"docker-init\",\"Version\":\"0.19.0\",\"Details\":{\"GitCommit\":\"de40ad0\"}}],\"Version\":\"20.10.6\",\"ApiVersion\":\"1.41\",\"MinAPIVersion\":\"1.12\",\"GitCommit\":\"8728dd2\",\"GoVersion\":\"go1.13.15\",\"Os\":\"windows\",\"Arch\":\"amd64\",\"KernelVersion\":\"5.10.25-linuxkit\",\"BuildTime\":\"2021-04-09T22:44:56.000000000+00:00\"}\n"))
}).Return(nil)
},
wantedOS: "windows",
wantedArch: "amd64",
wantedErr: nil,
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
controller := gomock.NewController(t)
tc.setupMocks(controller)
s := DockerCmdClient{
runner: mockCmd,
}
os, arch, err := s.GetPlatform()
if tc.wantedErr != nil {
require.EqualError(t, err, tc.wantedErr.Error())
} else {
require.Equal(t, tc.wantedOS, os)
require.Equal(t, tc.wantedArch, arch)
require.NoError(t, err)
}
})
}
}
func TestIsEcrCredentialHelperEnabled(t *testing.T) {
var mockCmd *MockCmd
workspace := "test/copilot/.docker"
registry := "dummyaccountid.dkr.ecr.region.amazonaws.com"
uri := fmt.Sprintf("%s/ui/app", registry)
testCases := map[string]struct {
setupMocks func(controller *gomock.Controller)
inBuffer *bytes.Buffer
mockFileSystem func(fs afero.Fs)
postExec func(fs afero.Fs)
isEcrRepo bool
}{
"ecr-login check global level": {
mockFileSystem: func(fs afero.Fs) {
fs.MkdirAll(workspace, 0755)
afero.WriteFile(fs, filepath.Join(workspace, "config.json"), []byte(fmt.Sprintf("{\"credsStore\":\"%s\"}", credStoreECRLogin)), 0644)
},
setupMocks: func(c *gomock.Controller) {
mockCmd = NewMockCmd(c)
},
postExec: func(fs afero.Fs) {
fs.RemoveAll(workspace)
},
isEcrRepo: true,
},
"ecr-login check registry level": {
mockFileSystem: func(fs afero.Fs) {
fs.MkdirAll(workspace, 0755)
afero.WriteFile(fs, filepath.Join(workspace, "config.json"), []byte(fmt.Sprintf("{\"credhelpers\":{\"%s\": \"%s\"}}", registry, credStoreECRLogin)), 0644)
},
setupMocks: func(c *gomock.Controller) {
mockCmd = NewMockCmd(c)
},
postExec: func(fs afero.Fs) {
fs.RemoveAll(workspace)
},
isEcrRepo: true,
},
"default login check registry level": {
mockFileSystem: func(fs afero.Fs) {
fs.MkdirAll(workspace, 0755)
afero.WriteFile(fs, filepath.Join(workspace, "config.json"), []byte(fmt.Sprintf("{\"credhelpers\":{\"%s\": \"%s\"}}", registry, "desktop")), 0644)
},
setupMocks: func(c *gomock.Controller) {
mockCmd = NewMockCmd(c)
},
postExec: func(fs afero.Fs) {
fs.RemoveAll(workspace)
},
isEcrRepo: false,
},
"no file check": {
mockFileSystem: func(fs afero.Fs) {
fs.MkdirAll(workspace, 0755)
},
setupMocks: func(c *gomock.Controller) {
mockCmd = NewMockCmd(c)
},
postExec: func(fs afero.Fs) {
fs.RemoveAll(workspace)
},
isEcrRepo: false,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// Create an empty FileSystem
fs := afero.NewOsFs()
controller := gomock.NewController(t)
tc.setupMocks(controller)
tc.mockFileSystem(fs)
s := DockerCmdClient{
runner: mockCmd,
buf: tc.inBuffer,
homePath: "test/copilot",
}
credStore := s.IsEcrCredentialHelperEnabled(uri)
tc.postExec(fs)
require.Equal(t, tc.isEcrRepo, credStore)
})
}
}
| 626 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package dockerengine
import (
"errors"
"fmt"
)
// ErrDockerCommandNotFound means the docker command is not found.
var ErrDockerCommandNotFound = errors.New("docker: command not found")
// ErrDockerDaemonNotResponsive means the docker daemon is not responsive.
type ErrDockerDaemonNotResponsive struct {
msg string
}
func (e ErrDockerDaemonNotResponsive) Error() string {
return fmt.Sprintf("docker daemon is not responsive: %s", e.msg)
}
| 22 |
copilot-cli | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: ./internal/pkg/docker/dockerengine/dockerengine.go
// Package dockerengine is a generated GoMock package.
package dockerengine
import (
context "context"
reflect "reflect"
exec "github.com/aws/copilot-cli/internal/pkg/exec"
gomock "github.com/golang/mock/gomock"
)
// MockCmd is a mock of Cmd interface.
type MockCmd struct {
ctrl *gomock.Controller
recorder *MockCmdMockRecorder
}
// MockCmdMockRecorder is the mock recorder for MockCmd.
type MockCmdMockRecorder struct {
mock *MockCmd
}
// NewMockCmd creates a new mock instance.
func NewMockCmd(ctrl *gomock.Controller) *MockCmd {
mock := &MockCmd{ctrl: ctrl}
mock.recorder = &MockCmdMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockCmd) EXPECT() *MockCmdMockRecorder {
return m.recorder
}
// Run mocks base method.
func (m *MockCmd) Run(name string, args []string, options ...exec.CmdOption) error {
m.ctrl.T.Helper()
varargs := []interface{}{name, args}
for _, a := range options {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "Run", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// Run indicates an expected call of Run.
func (mr *MockCmdMockRecorder) Run(name, args interface{}, options ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{name, args}, options...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Run", reflect.TypeOf((*MockCmd)(nil).Run), varargs...)
}
// RunWithContext mocks base method.
func (m *MockCmd) RunWithContext(ctx context.Context, name string, args []string, opts ...exec.CmdOption) error {
m.ctrl.T.Helper()
varargs := []interface{}{ctx, name, args}
for _, a := range opts {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "RunWithContext", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// RunWithContext indicates an expected call of RunWithContext.
func (mr *MockCmdMockRecorder) RunWithContext(ctx, name, args interface{}, opts ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{ctx, name, args}, opts...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RunWithContext", reflect.TypeOf((*MockCmd)(nil).RunWithContext), varargs...)
}
| 75 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package dockerfile provides functionality to parse a Dockerfile.
package dockerfile
import (
"encoding/json"
"errors"
"flag"
"fmt"
"regexp"
"strconv"
"strings"
"time"
"github.com/spf13/afero"
)
var exposeRegexPattern = regexp.MustCompile(`(?P<port>\d+)(\/(?P<protocol>\w+))?`) // port and optional protocol, at least 1 time on a line
const (
exposeRegexpWholeMatch = 0
exposeRegexpPort = 1
exposeRegexpProtocol = 3
)
const reFindAllMatches = -1 // regexp package uses this as shorthand for "find all matches in string"
const (
intervalFlag = "interval"
intervalDefault = 10 * time.Second
timeoutFlag = "timeout"
timeoutDefault = 5 * time.Second
startPeriodFlag = "start-period"
startPeriodDefault = 0
hcRetriesFlag = "retries"
retriesDefault = 2
cmdInstructionPrefix = "CMD "
cmdShell = "CMD-SHELL"
)
// Port represents an exposed port in a Dockerfile.
type Port struct {
Port uint16
Protocol string
RawString string
err error
}
// String implements the fmt.Stringer interface.
func (p *Port) String() string {
return p.RawString
}
// HealthCheck represents container health check options in a Dockerfile.
type HealthCheck struct {
Interval time.Duration
Timeout time.Duration
StartPeriod time.Duration
Retries int
Cmd []string
}
// Dockerfile represents a parsed Dockerfile.
type Dockerfile struct {
exposedPorts []Port
healthCheck *HealthCheck
parsed bool
path string
fs afero.Fs
}
// New returns an empty Dockerfile.
func New(fs afero.Fs, path string) *Dockerfile {
return &Dockerfile{
exposedPorts: []Port{},
healthCheck: nil,
fs: fs,
path: path,
}
}
// GetExposedPorts returns a uint16 slice of exposed ports found in the Dockerfile.
func (df *Dockerfile) GetExposedPorts() ([]Port, error) {
if !df.parsed {
if err := df.parse(); err != nil {
return nil, err
}
}
if len(df.exposedPorts) == 0 {
return nil, ErrNoExpose{
Dockerfile: df.path,
}
}
var portsWithoutErrs []Port
for _, port := range df.exposedPorts {
// ensure we register that there is an error (will only be ErrNoExpose) if
// any ports were unparseable or invalid
if port.err != nil {
return nil, port.err
}
portsWithoutErrs = append(portsWithoutErrs, port)
}
return portsWithoutErrs, nil
}
// GetHealthCheck parses the HEALTHCHECK instruction from the Dockerfile and returns it.
// If the HEALTHCHECK is NONE or there is no instruction, returns nil.
func (df *Dockerfile) GetHealthCheck() (*HealthCheck, error) {
if !df.parsed {
if err := df.parse(); err != nil {
return nil, err
}
}
return df.healthCheck, nil
}
// parse takes a Dockerfile and fills in struct members based on methods like parseExpose and parseHealthcheck.
func (df *Dockerfile) parse() error {
if df.parsed {
return nil
}
file, err := df.fs.Open(df.path)
if err != nil {
return fmt.Errorf("open Dockerfile: %w", err)
}
defer file.Close()
f, err := afero.ReadFile(df.fs, file.Name())
if err != nil {
return fmt.Errorf("read Dockerfile %s error: %w", f, err)
}
parsedDockerfile, err := parse(file.Name(), string(f))
if err != nil {
return err
}
df.exposedPorts = parsedDockerfile.exposedPorts
df.healthCheck = parsedDockerfile.healthCheck
df.parsed = true
return nil
}
// parse parses the contents of a Dockerfile into a Dockerfile struct.
func parse(name, content string) (*Dockerfile, error) {
var df Dockerfile
df.exposedPorts = []Port{}
lexer := lex(strings.NewReader(content))
for {
instr := lexer.next()
switch instr.name {
case instrErr:
return nil, fmt.Errorf("scan Dockerfile %s: %s", name, instr.args)
case instrEOF:
return &df, nil
case instrExpose:
currentPorts := parseExpose(instr.args)
df.exposedPorts = append(df.exposedPorts, currentPorts...)
case instrHealthCheck:
hc, err := parseHealthCheck(instr.args)
if err != nil {
return nil, err
}
df.healthCheck = hc
}
}
}
func parseExpose(line string) []Port {
// group 0: whole match
// group 1: port
// group 2: /protocol
// group 3: protocol
// matches strings of form <digits>(/<string>)?
// for any number of digits and optional protocol string
// separated by forward slash
matches := exposeRegexPattern.FindAllStringSubmatch(line, reFindAllMatches)
// check that there are matches, if not return port with only raw data
// there will only ever be length 0 or 4 arrays
// TODO implement arg parser regex
// https://github.com/aws/copilot-cli/issues/827
if len(matches) == 0 {
return []Port{
{
RawString: line,
err: ErrInvalidPort{
Match: line,
},
},
}
}
var ports []Port
for _, match := range matches {
var err error
// convert the matched port to int and validate
// We don't use the validate func in the cli package to avoid a circular dependency
extractedPort, err := strconv.Atoi(match[exposeRegexpPort])
if err != nil {
ports = append(ports, Port{
err: ErrInvalidPort{
Match: match[0],
},
})
continue
}
var extractedPortUint uint16
if extractedPort >= 1 && extractedPort <= 65535 {
extractedPortUint = uint16(extractedPort)
} else {
err = ErrInvalidPort{Match: match[0]}
}
ports = append(ports, Port{
RawString: match[exposeRegexpWholeMatch],
Protocol: match[exposeRegexpProtocol],
Port: extractedPortUint,
err: err,
})
}
return ports
}
// parseHealthCheck takes a HEALTHCHECK directives and turns into a healthCheck struct.
func parseHealthCheck(content string) (*HealthCheck, error) {
if strings.ToUpper(strings.TrimSpace(content)) == "NONE" {
return nil, nil
}
if !strings.Contains(content, "CMD") {
return nil, errors.New("parse HEALTHCHECK: instruction must contain either CMD or NONE")
}
var retries int
var interval, timeout, startPeriod time.Duration
fs := flag.NewFlagSet("flags", flag.ContinueOnError)
fs.DurationVar(&interval, intervalFlag, intervalDefault, "")
fs.DurationVar(&timeout, timeoutFlag, timeoutDefault, "")
fs.DurationVar(&startPeriod, startPeriodFlag, startPeriodDefault, "")
fs.IntVar(&retries, hcRetriesFlag, retriesDefault, "")
var instrArgs []string
for _, arg := range strings.Split(content, " ") {
if arg == "" {
continue
}
instrArgs = append(instrArgs, strings.TrimSpace(arg))
}
if err := fs.Parse(instrArgs); err != nil {
return nil, fmt.Errorf("parse HEALTHCHECK: %w", err)
}
// if HEALTHCHECK instruction is not "NONE", there must be a "CMD" instruction otherwise will error out.
// The CMD instruction can either be in a shell command format: `HEALTHCHECK CMD /bin/check-running`
// Or, it can also be an exec array: HEALTHCHECK CMD ["/bin/check-running"]
cmdIndex := strings.Index(content, cmdInstructionPrefix)
cmdArgs := strings.TrimSpace(content[cmdIndex+len(cmdInstructionPrefix):])
cmdExecutor := "CMD"
var args []string
if err := json.Unmarshal([]byte(cmdArgs), &args); err != nil {
cmdExecutor = cmdShell // In string form, use CMD-SHELL.
args = []string{cmdArgs}
}
return &HealthCheck{
Interval: interval,
Timeout: timeout,
StartPeriod: startPeriod,
Retries: retries,
Cmd: append([]string{cmdExecutor}, args...),
}, nil
}
| 282 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package dockerfile
import (
"bytes"
"errors"
"fmt"
"testing"
"time"
"github.com/moby/buildkit/frontend/dockerfile/instructions"
"github.com/moby/buildkit/frontend/dockerfile/parser"
"github.com/spf13/afero"
"github.com/stretchr/testify/require"
)
func TestDockerfile_GetExposedPort(t *testing.T) {
wantedPath := "./Dockerfile"
testCases := map[string]struct {
dockerfilePath string
dockerfile []byte
wantedPorts []Port
wantedErr error
}{
"no exposed ports": {
dockerfilePath: wantedPath,
dockerfile: []byte(`
FROM nginx
ARG arg=80`),
wantedPorts: []Port{},
wantedErr: ErrNoExpose{Dockerfile: wantedPath},
},
"one exposed port": {
dockerfilePath: wantedPath,
dockerfile: []byte(`
FROM nginx
EXPOSE 8080
`),
wantedPorts: []Port{
{
Port: 8080,
RawString: "8080",
},
},
},
"two exposed ports": {
dockerfilePath: wantedPath,
dockerfile: []byte(`
FROM nginx
EXPOSE 8080
EXPOSE 80`),
wantedPorts: []Port{
{
Port: 8080,
RawString: "8080",
},
{
Port: 80,
RawString: "80",
},
},
},
"two exposed ports one line": {
dockerfilePath: wantedPath,
dockerfile: []byte(`
FROM nginx
EXPOSE 80/tcp 3000`),
wantedPorts: []Port{
{
Port: 80,
Protocol: "tcp",
RawString: "80/tcp",
},
{
Port: 3000,
RawString: "3000",
},
},
},
"bad expose token single port": {
dockerfilePath: wantedPath,
dockerfile: []byte(`
FROM nginx
EXPOSE $arg
`),
wantedPorts: nil,
wantedErr: ErrInvalidPort{Match: "$arg"},
},
"bad expose token multiple ports": {
dockerfilePath: wantedPath,
dockerfile: []byte(`
FROM nginx
EXPOSE 80
EXPOSE $arg
EXPOSE 8080/tcp 5000`),
wantedPorts: nil,
wantedErr: ErrInvalidPort{Match: "$arg"},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
fs := afero.Afero{Fs: afero.NewMemMapFs()}
err := fs.WriteFile("./Dockerfile", tc.dockerfile, 0644)
if err != nil {
t.FailNow()
}
// Ensure the dockerfile is parse-able by Docker.
dat, err := fs.ReadFile("./Dockerfile")
require.NoError(t, err)
ast, err := parser.Parse(bytes.NewReader(dat))
require.NoError(t, err)
stages, _, _ := instructions.Parse(ast.AST)
ports, err := New(fs, "./Dockerfile").GetExposedPorts()
if tc.wantedErr != nil {
require.EqualError(t, err, tc.wantedErr.Error())
require.Nil(t, ports)
} else {
require.NoError(t, err)
require.ElementsMatch(t, tc.wantedPorts, ports, "expected ports do not match")
// Compare our parsing against Docker's.
var portsFromDocker []string
for _, cmd := range stages[0].Commands {
switch v := cmd.(type) {
case *instructions.ExposeCommand:
portsFromDocker = append(portsFromDocker, v.Ports...)
}
}
require.ElementsMatch(t, portsFromDocker, stringifyPorts(ports), "ports from Docker do not match")
}
})
}
}
func TestDockerfile_GetHealthCheck(t *testing.T) {
testCases := map[string]struct {
dockerfilePath string
dockerfile []byte
wantedConfig *HealthCheck
wantedErr error
}{
"correctly parses healthcheck with default values": {
dockerfile: []byte(`
FROM nginx
HEALTHCHECK CMD curl -f http://localhost/ || exit 1
`),
wantedErr: nil,
wantedConfig: &HealthCheck{
Interval: 10 * time.Second,
Timeout: 5 * time.Second,
StartPeriod: 0,
Retries: 2,
Cmd: []string{cmdShell, "curl -f http://localhost/ || exit 1"},
},
},
"correctly parses multiline healthcheck": {
dockerfile: []byte(`
FROM nginx
HEALTHCHECK --interval=5m\
--timeout=3s --start-period=2s --retries=3 \
CMD curl -f http://localhost/ || exit 1 `),
wantedErr: nil,
wantedConfig: &HealthCheck{
Interval: 300 * time.Second,
Timeout: 3 * time.Second,
StartPeriod: 2 * time.Second,
Retries: 3,
Cmd: []string{cmdShell, "curl -f http://localhost/ || exit 1"},
},
},
"correctly parses healthcheck with user's values": {
dockerfile: []byte(`
FROM nginx
HEALTHCHECK --interval=5m --timeout=3s --start-period=2s --retries=3 \
CMD curl -f http://localhost/ || exit 1`),
wantedErr: nil,
wantedConfig: &HealthCheck{
Interval: 300 * time.Second,
Timeout: 3 * time.Second,
StartPeriod: 2 * time.Second,
Retries: 3,
Cmd: []string{cmdShell, "curl -f http://localhost/ || exit 1"},
},
},
"correctly parses healthcheck with NONE": {
dockerfile: []byte(`
FROM nginx
HEALTHCHECK NONE
`),
wantedErr: nil,
wantedConfig: nil,
},
"correctly parses no healthchecks": {
dockerfile: []byte(`FROM nginx`),
wantedErr: nil,
wantedConfig: nil,
},
"correctly parses HEALTHCHECK instruction with awkward spacing": {
dockerfile: []byte(`
FROM nginx
HEALTHCHECK CMD a b
`),
wantedErr: nil,
wantedConfig: &HealthCheck{
Interval: 10 * time.Second,
Timeout: 5 * time.Second,
Retries: 2,
Cmd: []string{cmdShell, "a b"},
},
},
"correctly parses HEALTHCHECK instruction with exec array format": {
dockerfile: []byte(`
FROM nginx
EXPOSE 80
HEALTHCHECK CMD ["a", "b"]
`),
wantedErr: nil,
wantedConfig: &HealthCheck{
Interval: 10 * time.Second,
Timeout: 5 * time.Second,
Retries: 2,
Cmd: []string{"CMD", "a", "b"},
},
},
"healthcheck contains an invalid flag": {
dockerfile: []byte(`HEALTHCHECK --interval=5m --randomFlag=4s CMD curl -f http://localhost/ || exit 1`),
wantedErr: fmt.Errorf("parse HEALTHCHECK: flag provided but not defined: -randomFlag"),
},
"healthcheck does not contain CMD": {
dockerfile: []byte(`HEALTHCHECK --interval=5m curl -f http://localhost/ || exit 1`),
wantedErr: errors.New("parse HEALTHCHECK: instruction must contain either CMD or NONE"),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
fs := afero.Afero{Fs: afero.NewMemMapFs()}
err := fs.WriteFile("./Dockerfile", tc.dockerfile, 0644)
if err != nil {
t.FailNow()
}
// Ensure the dockerfile is parse-able by Docker.
dat, err := fs.ReadFile("./Dockerfile")
require.NoError(t, err)
ast, err := parser.Parse(bytes.NewReader(dat))
require.NoError(t, err)
stages, _, _ := instructions.Parse(ast.AST)
hc, err := New(fs, "./Dockerfile").GetHealthCheck()
if tc.wantedErr != nil {
require.EqualError(t, err, tc.wantedErr.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedConfig, hc, "healthcheck configs do not match")
for _, cmd := range stages[0].Commands {
switch v := cmd.(type) {
case *instructions.HealthCheckCommand:
if tc.wantedConfig == nil {
require.Equal(t, []string{"NONE"}, v.Health.Test, "expected NONE from Docker healthcheck")
} else {
require.Equal(t, tc.wantedConfig.Cmd, v.Health.Test, "Docker CMD instructions do not match")
}
}
}
}
})
}
}
func stringifyPorts(ports []Port) []string {
var arr []string
for _, p := range ports {
if p.err != nil {
continue
}
arr = append(arr, p.String())
}
return arr
}
| 290 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package dockerfile
import "fmt"
// ErrInvalidPort means that while there was a port provided, it was out of bounds or unparseable
type ErrInvalidPort struct {
Match string
}
func (e ErrInvalidPort) Error() string {
return fmt.Sprintf("parse EXPOSE: port represented at %s is invalid or unparseable", e.Match)
}
// ErrNoExpose means there were no documented EXPOSE statements in the given dockerfile.
type ErrNoExpose struct {
Dockerfile string
}
func (e ErrNoExpose) Error() string {
return fmt.Sprintf("parse EXPOSE: no EXPOSE statements in Dockerfile %s", e.Dockerfile)
}
| 25 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package dockerfile
import (
"bufio"
"fmt"
"io"
"strings"
"unicode"
)
// instructionName identifies the name of the instruction.
type instructionName int
const (
instrErr instructionName = iota // an error occurred while scanning.
instrHealthCheck // a HEALTHCHECK instruction.
instrExpose // an EXPOSE instruction.
instrEOF // done scanning.
)
const (
markerExposeInstr = "expose " // start of an EXPOSE instruction.
markerHealthCheckInstr = "healthcheck " // start of a HEALTHCHECK instruction.
)
var (
lineContinuationMarkers = []string{"`", "\\"} // denotes that the instruction continues to the next line.
instrMarkers = map[instructionName]string{ // lookup table for how an instruction starts.
instrExpose: markerExposeInstr,
instrHealthCheck: markerHealthCheckInstr,
}
)
// An instruction part of a Dockerfile.
// Dockerfiles are of the following format:
// ```
// # Comment
// INSTRUCTION arguments
// ```
type instruction struct {
name instructionName // the type of the instruction.
args string // the arguments of an instruction.
line int // line number at the start of this instruction.
}
// lexer holds the state of the scanner.
type lexer struct {
scanner *bufio.Scanner // line-by-line scanner of the contents of the Dockerfile.
curLineCount int // line number scanned so far.
curLine string // current line scanned.
curArgs *strings.Builder // accumulated arguments for an instruction.
instructions chan instruction //channel of discovered instructions.
}
// lex returns a running lexer that scans the Dockerfile.
// The lexing logic is heavily inspired by:
// https://cs.opensource.google/go/go/+/refs/tags/go1.17.1:src/text/template/parse/lex.go
func lex(reader io.Reader) *lexer {
l := &lexer{
scanner: bufio.NewScanner(reader),
curArgs: new(strings.Builder),
instructions: make(chan instruction),
}
go l.run()
return l
}
// next returns the next scanned instruction.
func (lex *lexer) next() instruction {
return <-lex.instructions
}
// readLine loads the next line in the Dockerfile.
// If we reached the end of the file, then isEOF is set to true.
// If any unexpected error occurs during scanning, then err is not nil.
func (lex *lexer) readLine() (isEOF bool, err error) {
if ok := lex.scanner.Scan(); !ok {
if err := lex.scanner.Err(); err != nil {
return false, err
}
return true, nil
}
lex.curLineCount++
lex.curLine = lex.scanner.Text()
return false, nil
}
// emit passes an instruction back to the client.
func (lex *lexer) emit(name instructionName) {
defer lex.curArgs.Reset()
lex.instructions <- instruction{
name: name,
args: lex.curArgs.String(),
line: lex.curLineCount,
}
}
// emitErr notifies clients that an error occurred during scanning.
func (lex *lexer) emitErr(err error) {
lex.instructions <- instruction{
name: instrErr,
args: err.Error(),
line: lex.curLineCount,
}
}
// consumeInstr keeps calling readLine and storing the arguments in the lexer until there is no more
// continuation marker and then emits the instruction.
func (lex *lexer) consumeInstr(name instructionName) stateFn {
isEOF, err := lex.readLine()
if err != nil {
lex.emitErr(err)
return nil
}
if isEOF {
lex.emitErr(fmt.Errorf("unexpected EOF while reading Dockerfile at line %d", lex.curLineCount))
return nil
}
// For example a healthcheck instruction like:
// ```
// HEALTHCHECK --interval=5m --timeout=3s --start-period=2s\
// --retries=3 \
// CMD curl -f http://localhost/ || exit 1`
// ```
// will be stored as:
// curArgs = "--interval=5m --timeout=3s --start-period=2s --retries=3 CMD curl -f http://localhost/ || exit 1"
clean := trimContinuationLineMarker(trimLeadingWhitespaces(lex.curLine))
_, err = lex.curArgs.WriteString(fmt.Sprintf(" %s", clean)) // separate each new line with a space character.
if err != nil {
lex.emitErr(fmt.Errorf("write '%s' to arguments buffer: %w", clean, err))
return nil
}
if hasLineContinuationMarker(lex.curLine) {
return lex.consumeInstr(name)
}
lex.emit(name)
return lexContent
}
// run walks through the state machine for the lexer.
func (lex *lexer) run() {
for state := lexContent; state != nil; {
state = state(lex)
}
close(lex.instructions)
}
// stateFn represents a state machine transition of the scanner going from one INSTRUCTION to the next.
type stateFn func(*lexer) stateFn
// lexContent scans until we reach the end of the Dockerfile.
func lexContent(l *lexer) stateFn {
isEOF, err := l.readLine()
if err != nil {
l.emitErr(err)
return nil
}
if isEOF {
l.emit(instrEOF)
return nil
}
line := strings.ToLower(strings.TrimLeftFunc(l.curLine, unicode.IsSpace))
switch {
case strings.HasPrefix(line, markerExposeInstr):
return lexExpose
case strings.HasPrefix(line, markerHealthCheckInstr):
return lexHealthCheck
default:
return lexContent // Ignore all the other instructions, consume the line without emitting any instructions.
}
}
// lexExpose collects the arguments for an EXPOSE instruction and then emits it.
func lexExpose(l *lexer) stateFn {
return lexInstruction(l, instrExpose)
}
// lexHealthCheck collects the arguments for a HEALTHCHECK instruction and then emits it.
func lexHealthCheck(l *lexer) stateFn {
return lexInstruction(l, instrHealthCheck)
}
// lexInstruction collects all the arguments for the named instruction and then emits it.
func lexInstruction(l *lexer, name instructionName) stateFn {
args := trimContinuationLineMarker(trimInstruction(l.curLine, instrMarkers[name]))
_, err := l.curArgs.WriteString(args)
if err != nil {
l.emitErr(fmt.Errorf("write '%s' to arguments buffer: %w", args, err))
return nil
}
if hasLineContinuationMarker(l.curLine) {
return l.consumeInstr(name)
}
l.emit(name)
return lexContent
}
// hasLineContinuationMarker returns true if the line wraps to the next line.
func hasLineContinuationMarker(line string) bool {
for _, marker := range lineContinuationMarkers {
if strings.HasSuffix(line, marker) {
return true
}
}
return false
}
// trimInstruction trims the instrMarker prefix from line and returns it.
func trimInstruction(line, instrMarker string) string {
normalized := strings.ToLower(line)
if !strings.Contains(normalized, instrMarker) {
return line
}
idx := strings.Index(normalized, instrMarker) + len(instrMarker)
return line[idx:]
}
// trimContinuationLineMarker returns the line without any continuation line markers.
// If the line doesn't have a continuation marker, then returns it as is.
func trimContinuationLineMarker(line string) string {
for _, marker := range lineContinuationMarkers {
if strings.HasSuffix(line, marker) {
return strings.TrimSuffix(line, marker)
}
}
return line
}
// trimLeadingWhitespaces removes any leading space characters.
func trimLeadingWhitespaces(line string) string {
return strings.TrimLeftFunc(line, unicode.IsSpace)
}
| 243 |
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 retrieve Copilot ECS information.
package ecs
import (
"encoding/json"
"fmt"
"sort"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws/arn"
"github.com/aws/copilot-cli/internal/pkg/aws/stepfunctions"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/copilot-cli/internal/pkg/aws/ecs"
"github.com/aws/copilot-cli/internal/pkg/aws/resourcegroups"
"github.com/aws/copilot-cli/internal/pkg/deploy"
)
const (
fmtWorkloadTaskDefinitionFamily = "%s-%s-%s"
fmtTaskTaskDefinitionFamily = "copilot-%s"
clusterResourceType = "ecs:cluster"
serviceResourceType = "ecs:service"
taskStopReason = "Task stopped because the underlying CloudFormation stack was deleted."
)
type resourceGetter interface {
GetResourcesByTags(resourceType string, tags map[string]string) ([]*resourcegroups.Resource, error)
}
type ecsClient interface {
DefaultCluster() (string, error)
Service(clusterName, serviceName string) (*ecs.Service, error)
NetworkConfiguration(cluster, serviceName string) (*ecs.NetworkConfiguration, error)
RunningTasks(cluster string) ([]*ecs.Task, error)
RunningTasksInFamily(cluster, family string) ([]*ecs.Task, error)
ServiceRunningTasks(clusterName, serviceName string) ([]*ecs.Task, error)
StoppedServiceTasks(cluster, service string) ([]*ecs.Task, error)
StopTasks(tasks []string, opts ...ecs.StopTasksOpts) error
TaskDefinition(taskDefName string) (*ecs.TaskDefinition, error)
UpdateService(clusterName, serviceName string, opts ...ecs.UpdateServiceOpts) error
DescribeTasks(cluster string, taskARNs []string) ([]*ecs.Task, error)
}
type stepFunctionsClient interface {
StateMachineDefinition(stateMachineARN string) (string, error)
}
// ServiceDesc contains the description of an ECS service.
type ServiceDesc struct {
Name string
ClusterName string
Tasks []*ecs.Task // Tasks is a list of tasks with DesiredStatus being RUNNING.
StoppedTasks []*ecs.Task
}
// Client retrieves Copilot information from ECS endpoint.
type Client struct {
rgGetter resourceGetter
ecsClient ecsClient
StepFuncClient stepFunctionsClient
}
// New inits a new Client.
func New(sess *session.Session) *Client {
return &Client{
rgGetter: resourcegroups.New(sess),
ecsClient: ecs.New(sess),
StepFuncClient: stepfunctions.New(sess),
}
}
// ClusterARN returns the ARN of the cluster in an environment.
func (c Client) ClusterARN(app, env string) (string, error) {
return c.clusterARN(app, env)
}
// ForceUpdateService forces a new update for an ECS service given Copilot service info.
func (c Client) ForceUpdateService(app, env, svc string) error {
clusterName, serviceName, err := c.fetchAndParseServiceARN(app, env, svc)
if err != nil {
return err
}
return c.ecsClient.UpdateService(clusterName, serviceName, ecs.WithForceUpdate())
}
// DescribeService returns the description of an ECS service given Copilot service info.
func (c Client) DescribeService(app, env, svc string) (*ServiceDesc, error) {
clusterName, serviceName, err := c.fetchAndParseServiceARN(app, env, svc)
if err != nil {
return nil, err
}
tasks, err := c.ecsClient.ServiceRunningTasks(clusterName, serviceName)
if err != nil {
return nil, fmt.Errorf("get tasks for service %s: %w", serviceName, err)
}
stoppedTasks, err := c.ecsClient.StoppedServiceTasks(clusterName, serviceName)
if err != nil {
return nil, fmt.Errorf("get stopped tasks for service %s: %w", serviceName, err)
}
return &ServiceDesc{
ClusterName: clusterName,
Name: serviceName,
Tasks: tasks,
StoppedTasks: stoppedTasks,
}, nil
}
// Service returns an ECS service given Copilot service info.
func (c Client) Service(app, env, svc string) (*ecs.Service, error) {
clusterName, serviceName, err := c.fetchAndParseServiceARN(app, env, svc)
if err != nil {
return nil, err
}
service, err := c.ecsClient.Service(clusterName, serviceName)
if err != nil {
return nil, fmt.Errorf("get ECS service %s: %w", serviceName, err)
}
return service, nil
}
// LastUpdatedAt returns the last updated time of the ECS service.
func (c Client) LastUpdatedAt(app, env, svc string) (time.Time, error) {
detail, err := c.Service(app, env, svc)
if err != nil {
return time.Time{}, err
}
return detail.LastUpdatedAt(), nil
}
// ListActiveAppEnvTasksOpts contains the parameters for ListActiveAppEnvTasks.
type ListActiveAppEnvTasksOpts struct {
App string
Env string
ListTasksFilter
}
// ListTasksFilter contains the filtering parameters for listing Copilot tasks.
type ListTasksFilter struct {
TaskGroup string // Returns only tasks with the given TaskGroup name.
TaskID string // Returns only tasks with the given ID.
CopilotOnly bool // Returns only tasks with the `copilot-task` tag.
}
type listActiveCopilotTasksOpts struct {
Cluster string
ListTasksFilter
}
// ListActiveAppEnvTasks returns the active Copilot tasks in the environment of an application.
func (c Client) ListActiveAppEnvTasks(opts ListActiveAppEnvTasksOpts) ([]*ecs.Task, error) {
clusterARN, err := c.ClusterARN(opts.App, opts.Env)
if err != nil {
return nil, err
}
return c.listActiveCopilotTasks(listActiveCopilotTasksOpts{
Cluster: clusterARN,
ListTasksFilter: opts.ListTasksFilter,
})
}
// ListActiveDefaultClusterTasks returns the active Copilot tasks in the default cluster.
func (c Client) ListActiveDefaultClusterTasks(filter ListTasksFilter) ([]*ecs.Task, error) {
defaultCluster, err := c.ecsClient.DefaultCluster()
if err != nil {
return nil, fmt.Errorf("get default cluster: %w", err)
}
return c.listActiveCopilotTasks(listActiveCopilotTasksOpts{
Cluster: defaultCluster,
ListTasksFilter: filter,
})
}
// StopWorkloadTasks stops all tasks in the given application, enviornment, and workload.
func (c Client) StopWorkloadTasks(app, env, workload string) error {
return c.stopTasks(app, env, ListTasksFilter{
TaskGroup: fmt.Sprintf(fmtWorkloadTaskDefinitionFamily, app, env, workload),
})
}
// StopOneOffTasks stops all one-off tasks in the given application and environment with the family name.
func (c Client) StopOneOffTasks(app, env, family string) error {
return c.stopTasks(app, env, ListTasksFilter{
TaskGroup: fmt.Sprintf(fmtTaskTaskDefinitionFamily, family),
CopilotOnly: true,
})
}
// stopTasks stops all tasks in the given application and environment in the given family.
func (c Client) stopTasks(app, env string, filter ListTasksFilter) error {
tasks, err := c.ListActiveAppEnvTasks(ListActiveAppEnvTasksOpts{
App: app,
Env: env,
ListTasksFilter: filter,
})
if err != nil {
return err
}
taskIDs := make([]string, len(tasks))
for n, task := range tasks {
taskIDs[n] = aws.StringValue(task.TaskArn)
}
clusterARN, err := c.ClusterARN(app, env)
if err != nil {
return fmt.Errorf("get cluster for env %s: %w", env, err)
}
return c.ecsClient.StopTasks(taskIDs, ecs.WithStopTaskCluster(clusterARN), ecs.WithStopTaskReason(taskStopReason))
}
// StopDefaultClusterTasks stops all copilot tasks from the given family in the default cluster.
func (c Client) StopDefaultClusterTasks(familyName string) error {
tdFamily := fmt.Sprintf(fmtTaskTaskDefinitionFamily, familyName)
tasks, err := c.ListActiveDefaultClusterTasks(ListTasksFilter{
TaskGroup: tdFamily,
CopilotOnly: true,
})
if err != nil {
return err
}
taskIDs := make([]string, len(tasks))
for n, task := range tasks {
taskIDs[n] = aws.StringValue(task.TaskArn)
}
return c.ecsClient.StopTasks(taskIDs, ecs.WithStopTaskReason(taskStopReason))
}
// TaskDefinition returns the task definition of the service.
func (c Client) TaskDefinition(app, env, svc string) (*ecs.TaskDefinition, error) {
taskDefName := fmt.Sprintf("%s-%s-%s", app, env, svc)
taskDefinition, err := c.ecsClient.TaskDefinition(taskDefName)
if err != nil {
return nil, fmt.Errorf("get task definition %s of service %s: %w", taskDefName, svc, err)
}
return taskDefinition, nil
}
// NetworkConfiguration returns the network configuration of the service.
func (c Client) NetworkConfiguration(app, env, svc string) (*ecs.NetworkConfiguration, error) {
clusterARN, err := c.clusterARN(app, env)
if err != nil {
return nil, err
}
arn, err := c.serviceARN(app, env, svc)
if err != nil {
return nil, err
}
svcName, err := arn.ServiceName()
if err != nil {
return nil, fmt.Errorf("extract service name from arn %s: %w", *arn, err)
}
return c.ecsClient.NetworkConfiguration(clusterARN, svcName)
}
// NetworkConfigurationForJob returns the network configuration of the job.
func (c Client) NetworkConfigurationForJob(app, env, job string) (*ecs.NetworkConfiguration, error) {
jobARN, err := c.stateMachineARN(app, env, job)
if err != nil {
return nil, err
}
raw, err := c.StepFuncClient.StateMachineDefinition(jobARN)
if err != nil {
return nil, fmt.Errorf("get state machine definition for job %s: %w", job, err)
}
var config NetworkConfiguration
err = json.Unmarshal([]byte(raw), &config)
if err != nil {
return nil, fmt.Errorf("unmarshal state machine definition: %w", err)
}
return (*ecs.NetworkConfiguration)(&config), nil
}
// NetworkConfiguration wraps an ecs.NetworkConfiguration struct.
type NetworkConfiguration ecs.NetworkConfiguration
// UnmarshalJSON implements custom logic to unmarshal only the network configuration from a state machine definition.
// Example state machine definition:
//
// "Version": "1.0",
// "Comment": "Run AWS Fargate task",
// "StartAt": "Run Fargate Task",
// "States": {
// "Run Fargate Task": {
// "Type": "Task",
// "Resource": "arn:aws:states:::ecs:runTask.sync",
// "Parameters": {
// "LaunchType": "FARGATE",
// "PlatformVersion": "1.4.0",
// "Cluster": "cluster",
// "TaskDefinition": "def",
// "PropagateTags": "TASK_DEFINITION",
// "Group.$": "$$.Execution.Name",
// "NetworkConfiguration": {
// "AwsvpcConfiguration": {
// "Subnets": ["sbn-1", "sbn-2"],
// "AssignPublicIp": "ENABLED",
// "SecurityGroups": ["sg-1", "sg-2"]
// }
// }
// },
// "End": true
// }
func (n *NetworkConfiguration) UnmarshalJSON(b []byte) error {
var f interface{}
err := json.Unmarshal(b, &f)
if err != nil {
return err
}
states := f.(map[string]interface{})["States"].(map[string]interface{})
parameters := states["Run Fargate Task"].(map[string]interface{})["Parameters"].(map[string]interface{})
networkConfig := parameters["NetworkConfiguration"].(map[string]interface{})["AwsvpcConfiguration"].(map[string]interface{})
var subnets []string
for _, subnet := range networkConfig["Subnets"].([]interface{}) {
subnets = append(subnets, subnet.(string))
}
var securityGroups []string
for _, sg := range networkConfig["SecurityGroups"].([]interface{}) {
securityGroups = append(securityGroups, sg.(string))
}
n.Subnets = subnets
n.SecurityGroups = securityGroups
n.AssignPublicIp = networkConfig["AssignPublicIp"].(string)
return nil
}
func (c Client) listActiveCopilotTasks(opts listActiveCopilotTasksOpts) ([]*ecs.Task, error) {
var tasks []*ecs.Task
if opts.TaskGroup != "" {
resp, err := c.ecsClient.RunningTasksInFamily(opts.Cluster, opts.TaskGroup)
if err != nil {
return nil, fmt.Errorf("list running tasks in family %s and cluster %s: %w", opts.TaskGroup, opts.Cluster, err)
}
tasks = resp
} else {
resp, err := c.ecsClient.RunningTasks(opts.Cluster)
if err != nil {
return nil, fmt.Errorf("list running tasks in cluster %s: %w", opts.Cluster, err)
}
tasks = resp
}
if opts.CopilotOnly {
return filterCopilotTasks(tasks, opts.TaskID), nil
}
return filterTasksByID(tasks, opts.TaskID), nil
}
func filterTasksByID(tasks []*ecs.Task, taskID string) []*ecs.Task {
var filteredTasks []*ecs.Task
for _, task := range tasks {
id, _ := ecs.TaskID(aws.StringValue(task.TaskArn))
if strings.Contains(id, taskID) {
filteredTasks = append(filteredTasks, task)
}
}
return filteredTasks
}
func filterCopilotTasks(tasks []*ecs.Task, taskID string) []*ecs.Task {
var filteredTasks []*ecs.Task
for _, task := range filterTasksByID(tasks, taskID) {
var copilotTask bool
for _, tag := range task.Tags {
if aws.StringValue(tag.Key) == deploy.TaskTagKey {
copilotTask = true
break
}
}
if copilotTask {
filteredTasks = append(filteredTasks, task)
}
}
return filteredTasks
}
func (c Client) clusterARN(app, env string) (string, error) {
tags := tags(map[string]string{
deploy.AppTagKey: app,
deploy.EnvTagKey: env,
})
clusters, err := c.rgGetter.GetResourcesByTags(clusterResourceType, tags)
if err != nil {
return "", fmt.Errorf("get ECS cluster with tags %s: %w", tags.String(), err)
}
if len(clusters) == 0 {
return "", fmt.Errorf("no ECS cluster found with tags %s", tags.String())
}
// NOTE: only one cluster is associated with an application and an environment.
if len(clusters) > 1 {
return "", fmt.Errorf("more than one ECS cluster are found with tags %s", tags.String())
}
return clusters[0].ARN, nil
}
func (c Client) fetchAndParseServiceARN(app, env, svc string) (cluster, service string, err error) {
svcARN, err := c.serviceARN(app, env, svc)
if err != nil {
return "", "", err
}
clusterName, err := svcARN.ClusterName()
if err != nil {
return "", "", fmt.Errorf("get cluster name: %w", err)
}
serviceName, err := svcARN.ServiceName()
if err != nil {
return "", "", fmt.Errorf("get service name: %w", err)
}
return clusterName, serviceName, nil
}
func (c Client) serviceARN(app, env, svc string) (*ecs.ServiceArn, error) {
tags := tags(map[string]string{
deploy.AppTagKey: app,
deploy.EnvTagKey: env,
deploy.ServiceTagKey: svc,
})
services, err := c.rgGetter.GetResourcesByTags(serviceResourceType, tags)
if err != nil {
return nil, fmt.Errorf("get ECS service with tags %s: %w", tags.String(), err)
}
if len(services) == 0 {
return nil, fmt.Errorf("no ECS service found with tags %s", tags.String())
}
if len(services) > 1 {
return nil, fmt.Errorf("more than one ECS service with tags %s", tags.String())
}
serviceArn := ecs.ServiceArn(services[0].ARN)
return &serviceArn, nil
}
type tags map[string]string
func (tags tags) String() string {
serialized := make([]string, len(tags))
var i = 0
for k, v := range tags {
serialized[i] = fmt.Sprintf("%q=%q", k, v)
i += 1
}
sort.SliceStable(serialized, func(i, j int) bool { return serialized[i] < serialized[j] })
return strings.Join(serialized, ",")
}
func (c Client) stateMachineARN(app, env, job string) (string, error) {
tags := tags(map[string]string{
deploy.AppTagKey: app,
deploy.EnvTagKey: env,
deploy.ServiceTagKey: job,
})
resources, err := c.rgGetter.GetResourcesByTags(resourcegroups.ResourceTypeStateMachine, tags)
if err != nil {
return "", fmt.Errorf("get state machine resource with tags %s: %w", tags.String(), err)
}
var stateMachineARN string
targetName := fmt.Sprintf(fmtStateMachineName, app, env, job)
for _, r := range resources {
parsedARN, err := arn.Parse(r.ARN)
if err != nil {
continue
}
parts := strings.Split(parsedARN.Resource, ":")
if len(parts) != 2 {
continue
}
if parts[1] == targetName {
stateMachineARN = r.ARN
break
}
}
if stateMachineARN == "" {
return "", fmt.Errorf("state machine for job %s not found", job)
}
return stateMachineARN, nil
}
// HasNonZeroExitCode returns an error if at least one of the tasks exited with a non-zero exit code. It assumes that all tasks are built on the same task definition.
func (c Client) HasNonZeroExitCode(taskARNs []string, cluster string) error {
tasks, err := c.ecsClient.DescribeTasks(cluster, taskARNs)
if err != nil {
return fmt.Errorf("describe tasks %s: %w", taskARNs, err)
}
if len(tasks) == 0 {
return fmt.Errorf("cannot find tasks %s", strings.Join(taskARNs, ", "))
}
taskDefinitonARN := aws.StringValue(tasks[0].TaskDefinitionArn)
taskDefinition, err := c.ecsClient.TaskDefinition(taskDefinitonARN)
if err != nil {
return fmt.Errorf("get task definition %s: %w", taskDefinitonARN, err)
}
isContainerEssential := make(map[string]bool)
for _, container := range taskDefinition.ContainerDefinitions {
isContainerEssential[aws.StringValue(container.Name)] = aws.BoolValue(container.Essential)
}
for _, describedTask := range tasks {
for _, container := range describedTask.Containers {
if isContainerEssential[aws.StringValue(container.Name)] && aws.Int64Value(container.ExitCode) != 0 {
taskID, err := ecs.TaskID(aws.StringValue(describedTask.TaskArn))
if err != nil {
return err
}
return &ErrExitCode{aws.StringValue(container.Name),
taskID,
int(aws.Int64Value(container.ExitCode))}
}
}
}
return nil
}
| 534 |
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"
"time"
"github.com/aws/aws-sdk-go/aws"
awsecs "github.com/aws/aws-sdk-go/service/ecs"
"github.com/aws/copilot-cli/internal/pkg/aws/ecs"
"github.com/aws/copilot-cli/internal/pkg/aws/resourcegroups"
"github.com/aws/copilot-cli/internal/pkg/deploy"
"github.com/aws/copilot-cli/internal/pkg/ecs/mocks"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
type clientMocks struct {
resourceGetter *mocks.MockresourceGetter
ecsClient *mocks.MockecsClient
StepFuncClient *mocks.MockstepFunctionsClient
}
func TestClient_ClusterARN(t *testing.T) {
const (
mockApp = "mockApp"
mockEnv = "mockEnv"
)
getRgInput := map[string]string{
deploy.AppTagKey: mockApp,
deploy.EnvTagKey: mockEnv,
}
testError := errors.New("some error")
tests := map[string]struct {
setupMocks func(mocks clientMocks)
wantedError error
wantedCluster string
}{
"errors if fail to get resources by tags": {
setupMocks: func(m clientMocks) {
gomock.InOrder(
m.resourceGetter.EXPECT().GetResourcesByTags(clusterResourceType, getRgInput).
Return(nil, testError),
)
},
wantedError: fmt.Errorf(`get ECS cluster with tags "copilot-application"="mockApp","copilot-environment"="mockEnv": some error`),
},
"errors if no cluster found": {
setupMocks: func(m clientMocks) {
gomock.InOrder(
m.resourceGetter.EXPECT().GetResourcesByTags(clusterResourceType, getRgInput).
Return([]*resourcegroups.Resource{}, nil),
)
},
wantedError: fmt.Errorf(`no ECS cluster found with tags "copilot-application"="mockApp","copilot-environment"="mockEnv"`),
},
"errors if more than one cluster found": {
setupMocks: func(m clientMocks) {
gomock.InOrder(
m.resourceGetter.EXPECT().GetResourcesByTags(clusterResourceType, getRgInput).
Return([]*resourcegroups.Resource{
{ARN: "mockARN1"}, {ARN: "mockARN2"},
}, nil),
)
},
wantedError: fmt.Errorf(`more than one ECS cluster are found with tags "copilot-application"="mockApp","copilot-environment"="mockEnv"`),
},
"success": {
setupMocks: func(m clientMocks) {
gomock.InOrder(
m.resourceGetter.EXPECT().GetResourcesByTags(clusterResourceType, getRgInput).
Return([]*resourcegroups.Resource{
{ARN: "mockARN"},
}, nil),
)
},
wantedCluster: "mockARN",
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
// GIVEN
mockRgGetter := mocks.NewMockresourceGetter(ctrl)
mocks := clientMocks{
resourceGetter: mockRgGetter,
}
test.setupMocks(mocks)
client := Client{
rgGetter: mockRgGetter,
}
// WHEN
get, err := client.ClusterARN(mockApp, mockEnv)
// THEN
if test.wantedError != nil {
require.EqualError(t, err, test.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, get, test.wantedCluster)
}
})
}
}
func TestClient_serviceARN(t *testing.T) {
const (
mockApp = "mockApp"
mockEnv = "mockEnv"
mockSvc = "mockSvc"
)
getRgInput := map[string]string{
deploy.AppTagKey: mockApp,
deploy.EnvTagKey: mockEnv,
deploy.ServiceTagKey: mockSvc,
}
testError := errors.New("some error")
tests := map[string]struct {
setupMocks func(mocks clientMocks)
wantedError error
wantedService string
}{
"errors if fail to get resources by tags": {
setupMocks: func(m clientMocks) {
gomock.InOrder(
m.resourceGetter.EXPECT().GetResourcesByTags(serviceResourceType, getRgInput).
Return(nil, testError),
)
},
wantedError: fmt.Errorf(`get ECS service with tags "copilot-application"="mockApp","copilot-environment"="mockEnv","copilot-service"="mockSvc": some error`),
},
"errors if no service found": {
setupMocks: func(m clientMocks) {
gomock.InOrder(
m.resourceGetter.EXPECT().GetResourcesByTags(serviceResourceType, getRgInput).
Return([]*resourcegroups.Resource{}, nil),
)
},
wantedError: fmt.Errorf(`no ECS service found with tags "copilot-application"="mockApp","copilot-environment"="mockEnv","copilot-service"="mockSvc"`),
},
"errors if more than one service found": {
setupMocks: func(m clientMocks) {
gomock.InOrder(
m.resourceGetter.EXPECT().GetResourcesByTags(serviceResourceType, getRgInput).
Return([]*resourcegroups.Resource{
{ARN: "mockARN1"}, {ARN: "mockARN2"},
}, nil),
)
},
wantedError: fmt.Errorf(`more than one ECS service with tags "copilot-application"="mockApp","copilot-environment"="mockEnv","copilot-service"="mockSvc"`),
},
"success": {
setupMocks: func(m clientMocks) {
gomock.InOrder(
m.resourceGetter.EXPECT().GetResourcesByTags(serviceResourceType, getRgInput).
Return([]*resourcegroups.Resource{
{ARN: "mockARN"},
}, nil),
)
},
wantedService: "mockARN",
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
// GIVEN
mockRgGetter := mocks.NewMockresourceGetter(ctrl)
mocks := clientMocks{
resourceGetter: mockRgGetter,
}
test.setupMocks(mocks)
client := Client{
rgGetter: mockRgGetter,
}
// WHEN
get, err := client.serviceARN(mockApp, mockEnv, mockSvc)
// THEN
if test.wantedError != nil {
require.EqualError(t, err, test.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, string(*get), test.wantedService)
}
})
}
}
func TestClient_DescribeService(t *testing.T) {
const (
mockApp = "mockApp"
mockEnv = "mockEnv"
mockSvc = "mockSvc"
badSvcARN = "badMockArn"
mockSvcARN = "arn:aws:ecs:us-west-2:1234567890:service/mockCluster/mockService"
mockCluster = "mockCluster"
mockService = "mockService"
)
getRgInput := map[string]string{
deploy.AppTagKey: mockApp,
deploy.EnvTagKey: mockEnv,
deploy.ServiceTagKey: mockSvc,
}
tests := map[string]struct {
setupMocks func(mocks clientMocks)
wantedError error
wanted *ServiceDesc
}{
"return error if failed to get cluster name": {
setupMocks: func(m clientMocks) {
gomock.InOrder(
m.resourceGetter.EXPECT().GetResourcesByTags(serviceResourceType, getRgInput).
Return([]*resourcegroups.Resource{
{ARN: badSvcARN},
}, nil),
)
},
wantedError: fmt.Errorf("get cluster name: arn: invalid prefix"),
},
"return error if failed to get service tasks": {
setupMocks: func(m clientMocks) {
gomock.InOrder(
m.resourceGetter.EXPECT().GetResourcesByTags(serviceResourceType, getRgInput).
Return([]*resourcegroups.Resource{
{ARN: mockSvcARN},
}, nil),
m.ecsClient.EXPECT().ServiceRunningTasks(mockCluster, mockService).Return(nil, errors.New("some error")),
)
},
wantedError: fmt.Errorf("get tasks for service mockService: some error"),
},
"return error if failed to get stopped service tasks": {
setupMocks: func(m clientMocks) {
gomock.InOrder(
m.resourceGetter.EXPECT().GetResourcesByTags(serviceResourceType, getRgInput).
Return([]*resourcegroups.Resource{
{ARN: mockSvcARN},
}, nil),
m.ecsClient.EXPECT().ServiceRunningTasks(mockCluster, mockService).Return([]*ecs.Task{
{TaskArn: aws.String("mockTaskARN")},
}, nil),
m.ecsClient.EXPECT().StoppedServiceTasks(mockCluster, mockService).Return(nil, errors.New("some error")),
)
},
wantedError: errors.New("get stopped tasks for service mockService: some error"),
},
"success": {
setupMocks: func(m clientMocks) {
gomock.InOrder(
m.resourceGetter.EXPECT().GetResourcesByTags(serviceResourceType, getRgInput).
Return([]*resourcegroups.Resource{
{ARN: mockSvcARN},
}, nil),
m.ecsClient.EXPECT().ServiceRunningTasks(mockCluster, mockService).Return([]*ecs.Task{
{TaskArn: aws.String("mockTaskARN")},
}, nil),
m.ecsClient.EXPECT().StoppedServiceTasks(mockCluster, mockService).Return([]*ecs.Task{
{TaskArn: aws.String("mockStoppedTaskARN")},
}, nil),
)
},
wanted: &ServiceDesc{
ClusterName: mockCluster,
Name: mockService,
Tasks: []*ecs.Task{
{TaskArn: aws.String("mockTaskARN")},
},
StoppedTasks: []*ecs.Task{
{TaskArn: aws.String("mockStoppedTaskARN")},
},
},
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
// GIVEN
mockRgGetter := mocks.NewMockresourceGetter(ctrl)
mockECSClient := mocks.NewMockecsClient(ctrl)
mocks := clientMocks{
resourceGetter: mockRgGetter,
ecsClient: mockECSClient,
}
test.setupMocks(mocks)
client := Client{
rgGetter: mockRgGetter,
ecsClient: mockECSClient,
}
// WHEN
get, err := client.DescribeService(mockApp, mockEnv, mockSvc)
// THEN
if test.wantedError != nil {
require.EqualError(t, err, test.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, get, test.wanted)
}
})
}
}
func TestClient_Service(t *testing.T) {
const (
mockApp = "mockApp"
mockEnv = "mockEnv"
mockSvc = "mockSvc"
mockSvcARN = "arn:aws:ecs:us-west-2:1234567890:service/mockCluster/mockService"
mockCluster = "mockCluster"
mockService = "mockService"
)
mockError := errors.New("some error")
getRgInput := map[string]string{
deploy.AppTagKey: mockApp,
deploy.EnvTagKey: mockEnv,
deploy.ServiceTagKey: mockSvc,
}
tests := map[string]struct {
setupMocks func(mocks clientMocks)
wantedError error
wanted *ecs.Service
}{
"error if fail to describe ECS service": {
setupMocks: func(m clientMocks) {
gomock.InOrder(
m.resourceGetter.EXPECT().GetResourcesByTags(serviceResourceType, getRgInput).
Return([]*resourcegroups.Resource{
{ARN: mockSvcARN},
}, nil),
m.ecsClient.EXPECT().Service(mockCluster, mockService).Return(nil, mockError),
)
},
wantedError: fmt.Errorf("get ECS service mockService: some error"),
},
"err if failed to get the ECS service": {
setupMocks: func(m clientMocks) {
gomock.InOrder(
m.resourceGetter.EXPECT().GetResourcesByTags(serviceResourceType, getRgInput).
Return([]*resourcegroups.Resource{
{ARN: mockSvcARN},
}, nil),
m.ecsClient.EXPECT().Service(mockCluster, mockService).Return(nil, mockError),
)
},
wantedError: fmt.Errorf("get ECS service mockService: some error"),
},
"success": {
setupMocks: func(m clientMocks) {
gomock.InOrder(
m.resourceGetter.EXPECT().GetResourcesByTags(serviceResourceType, getRgInput).
Return([]*resourcegroups.Resource{
{ARN: mockSvcARN},
}, nil),
m.ecsClient.EXPECT().Service(mockCluster, mockService).Return(&ecs.Service{}, nil),
)
},
wanted: &ecs.Service{},
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
// GIVEN
mockRgGetter := mocks.NewMockresourceGetter(ctrl)
mockECSClient := mocks.NewMockecsClient(ctrl)
mocks := clientMocks{
resourceGetter: mockRgGetter,
ecsClient: mockECSClient,
}
test.setupMocks(mocks)
client := Client{
rgGetter: mockRgGetter,
ecsClient: mockECSClient,
}
// WHEN
get, err := client.Service(mockApp, mockEnv, mockSvc)
// THEN
if test.wantedError != nil {
require.EqualError(t, err, test.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, get, test.wanted)
}
})
}
}
func TestClient_LastUpdatedAt(t *testing.T) {
const (
mockApp = "mockApp"
mockEnv = "mockEnv"
mockSvc = "mockSvc"
mockSvcARN = "arn:aws:ecs:us-west-2:1234567890:service/mockCluster/mockService"
mockCluster = "mockCluster"
mockService = "mockService"
)
mockTime := time.Unix(1494505756, 0)
mockBeforeTime := time.Unix(1494505750, 0)
getRgInput := map[string]string{
deploy.AppTagKey: mockApp,
deploy.EnvTagKey: mockEnv,
deploy.ServiceTagKey: mockSvc,
}
tests := map[string]struct {
setupMocks func(mocks clientMocks)
wantedError error
wanted time.Time
}{
"succeed": {
setupMocks: func(m clientMocks) {
gomock.InOrder(
m.resourceGetter.EXPECT().GetResourcesByTags(serviceResourceType, getRgInput).
Return([]*resourcegroups.Resource{
{ARN: mockSvcARN},
}, nil),
m.ecsClient.EXPECT().Service(mockCluster, mockService).Return(&ecs.Service{
Deployments: []*awsecs.Deployment{
{
UpdatedAt: &mockTime,
},
{
UpdatedAt: &mockBeforeTime,
},
},
}, nil),
)
},
wanted: mockTime,
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
// GIVEN
mockRgGetter := mocks.NewMockresourceGetter(ctrl)
mockECSClient := mocks.NewMockecsClient(ctrl)
mocks := clientMocks{
resourceGetter: mockRgGetter,
ecsClient: mockECSClient,
}
test.setupMocks(mocks)
client := Client{
rgGetter: mockRgGetter,
ecsClient: mockECSClient,
}
// WHEN
get, err := client.LastUpdatedAt(mockApp, mockEnv, mockSvc)
// THEN
if test.wantedError != nil {
require.EqualError(t, err, test.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, get, test.wanted)
}
})
}
}
func TestClient_ForceUpdateService(t *testing.T) {
const (
mockApp = "mockApp"
mockEnv = "mockEnv"
mockSvc = "mockSvc"
mockSvcARN = "arn:aws:ecs:us-west-2:1234567890:service/mockCluster/mockService"
mockCluster = "mockCluster"
mockService = "mockService"
)
getRgInput := map[string]string{
deploy.AppTagKey: mockApp,
deploy.EnvTagKey: mockEnv,
deploy.ServiceTagKey: mockSvc,
}
tests := map[string]struct {
setupMocks func(mocks clientMocks)
wantedError error
}{
"return error if failed to update service": {
setupMocks: func(m clientMocks) {
gomock.InOrder(
m.resourceGetter.EXPECT().GetResourcesByTags(serviceResourceType, getRgInput).
Return([]*resourcegroups.Resource{
{ARN: mockSvcARN},
}, nil),
m.ecsClient.EXPECT().UpdateService(mockCluster, mockService, gomock.Any()).Return(errors.New("some error")),
)
},
wantedError: fmt.Errorf("some error"),
},
"success": {
setupMocks: func(m clientMocks) {
gomock.InOrder(
m.resourceGetter.EXPECT().GetResourcesByTags(serviceResourceType, getRgInput).
Return([]*resourcegroups.Resource{
{ARN: mockSvcARN},
}, nil),
m.ecsClient.EXPECT().UpdateService(mockCluster, mockService, gomock.Any()).Return(nil),
)
},
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
// GIVEN
mockRgGetter := mocks.NewMockresourceGetter(ctrl)
mockECSClient := mocks.NewMockecsClient(ctrl)
mocks := clientMocks{
resourceGetter: mockRgGetter,
ecsClient: mockECSClient,
}
test.setupMocks(mocks)
client := Client{
rgGetter: mockRgGetter,
ecsClient: mockECSClient,
}
// WHEN
err := client.ForceUpdateService(mockApp, mockEnv, mockSvc)
// THEN
if test.wantedError != nil {
require.EqualError(t, err, test.wantedError.Error())
} else {
require.NoError(t, err)
}
})
}
}
func TestClient_listActiveCopilotTasks(t *testing.T) {
const (
mockCluster = "mockCluster"
mockTaskGroup = "mockTaskGroup"
)
testError := errors.New("some error")
tests := map[string]struct {
inTaskGroup string
inTaskID string
inOneOff bool
setupMocks func(mocks clientMocks)
wantedError error
wanted []*ecs.Task
}{
"errors if fail to list running tasks in a family": {
inTaskGroup: mockTaskGroup,
setupMocks: func(m clientMocks) {
gomock.InOrder(
m.ecsClient.EXPECT().RunningTasksInFamily(mockCluster, "mockTaskGroup").
Return(nil, testError),
)
},
wantedError: fmt.Errorf("list running tasks in family mockTaskGroup and cluster mockCluster: some error"),
},
"errors if fail to list running tasks": {
setupMocks: func(m clientMocks) {
gomock.InOrder(
m.ecsClient.EXPECT().RunningTasks(mockCluster).
Return(nil, testError),
)
},
wantedError: fmt.Errorf("list running tasks in cluster mockCluster: some error"),
},
"success": {
inTaskID: "123456",
inOneOff: true,
setupMocks: func(m clientMocks) {
gomock.InOrder(
m.ecsClient.EXPECT().RunningTasks(mockCluster).
Return([]*ecs.Task{
{
TaskArn: aws.String("arn:aws:ecs:us-west-2:123456789:task/123456789"),
Tags: []*awsecs.Tag{
{Key: aws.String("copilot-task")},
},
},
{
TaskArn: aws.String("arn:aws:ecs:us-west-2:123456789:task/123456789"),
Tags: []*awsecs.Tag{
{Key: aws.String("copilot-application")},
},
},
{
TaskArn: aws.String("arn:aws:ecs:us-west-2:123456789:task/123456788"),
},
{
TaskArn: aws.String("arn:aws:ecs:us-west-2:123456789:task/987765654"),
Tags: []*awsecs.Tag{
{Key: aws.String("copilot-task")},
},
},
}, nil),
)
},
wanted: []*ecs.Task{
{
TaskArn: aws.String("arn:aws:ecs:us-west-2:123456789:task/123456789"),
Tags: []*awsecs.Tag{
{Key: aws.String("copilot-task")},
},
},
},
},
"success with oneOff disabled": {
inTaskID: "123456",
inOneOff: false,
setupMocks: func(m clientMocks) {
gomock.InOrder(
m.ecsClient.EXPECT().RunningTasks(mockCluster).
Return([]*ecs.Task{
{
TaskArn: aws.String("arn:aws:ecs:us-west-2:123456789:task/123456789"),
Tags: []*awsecs.Tag{
{Key: aws.String("copilot-task")},
},
},
{
TaskArn: aws.String("arn:aws:ecs:us-west-2:123456789:task/123456789"),
Tags: []*awsecs.Tag{
{Key: aws.String("copilot-application")},
},
},
}, nil),
)
},
wanted: []*ecs.Task{
{
TaskArn: aws.String("arn:aws:ecs:us-west-2:123456789:task/123456789"),
Tags: []*awsecs.Tag{
{Key: aws.String("copilot-task")},
},
},
{
TaskArn: aws.String("arn:aws:ecs:us-west-2:123456789:task/123456789"),
Tags: []*awsecs.Tag{
{Key: aws.String("copilot-application")},
},
},
},
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
// GIVEN
mockECSTasksGetter := mocks.NewMockecsClient(ctrl)
mocks := clientMocks{
ecsClient: mockECSTasksGetter,
}
test.setupMocks(mocks)
client := Client{
ecsClient: mockECSTasksGetter,
}
// WHEN
got, err := client.listActiveCopilotTasks(listActiveCopilotTasksOpts{
Cluster: mockCluster,
ListTasksFilter: ListTasksFilter{
TaskGroup: test.inTaskGroup,
TaskID: test.inTaskID,
CopilotOnly: test.inOneOff,
},
})
// THEN
if test.wantedError != nil {
require.EqualError(t, err, test.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, got, test.wanted)
}
})
}
}
func TestClient_StopWorkloadTasks(t *testing.T) {
mockCluster := "arn:aws::ecs:cluster/abcd1234"
mockResource := resourcegroups.Resource{
ARN: mockCluster,
}
mockECSTask := []*ecs.Task{
{
TaskArn: aws.String("deadbeef"),
Tags: []*awsecs.Tag{
{
Key: aws.String("copilot-service"),
},
},
},
{
TaskArn: aws.String("abcd"),
Tags: []*awsecs.Tag{
{
Key: aws.String("copilot-service"),
},
},
},
}
testCases := map[string]struct {
inApp string
inEnv string
inTask string
mockECS func(m *mocks.MockecsClient)
mockrg func(m *mocks.MockresourceGetter)
wantErr error
}{
"success": {
inApp: "phonetool",
inEnv: "pdx",
inTask: "service",
mockECS: func(m *mocks.MockecsClient) {
m.EXPECT().RunningTasksInFamily(mockCluster, "phonetool-pdx-service").Return(mockECSTask, nil)
m.EXPECT().StopTasks([]string{"deadbeef", "abcd"}, gomock.Any()).Return(nil)
},
mockrg: func(m *mocks.MockresourceGetter) {
m.EXPECT().GetResourcesByTags(clusterResourceType, map[string]string{
"copilot-application": "phonetool",
"copilot-environment": "pdx",
}).Return([]*resourcegroups.Resource{&mockResource}, nil).Times(2)
},
},
"no tasks": {
inApp: "phonetool",
inEnv: "pdx",
inTask: "service",
mockECS: func(m *mocks.MockecsClient) {
m.EXPECT().RunningTasksInFamily(mockCluster, "phonetool-pdx-service").Return([]*ecs.Task{}, nil)
m.EXPECT().StopTasks([]string{}, gomock.Any()).Return(nil)
},
mockrg: func(m *mocks.MockresourceGetter) {
m.EXPECT().GetResourcesByTags(clusterResourceType, map[string]string{
"copilot-application": "phonetool",
"copilot-environment": "pdx",
}).Return([]*resourcegroups.Resource{&mockResource}, nil).Times(2)
},
},
"failure getting resources": {
inApp: "phonetool",
inEnv: "pdx",
inTask: "service",
mockECS: func(m *mocks.MockecsClient) {},
mockrg: func(m *mocks.MockresourceGetter) {
m.EXPECT().GetResourcesByTags(clusterResourceType, map[string]string{
"copilot-application": "phonetool",
"copilot-environment": "pdx",
}).Return(nil, errors.New("some error"))
},
wantErr: errors.New(`get ECS cluster with tags "copilot-application"="phonetool","copilot-environment"="pdx": some error`),
},
"failure stopping tasks": {
inApp: "phonetool",
inEnv: "pdx",
inTask: "service",
mockECS: func(m *mocks.MockecsClient) {
m.EXPECT().RunningTasksInFamily(mockCluster, "phonetool-pdx-service").Return(mockECSTask, nil)
m.EXPECT().StopTasks([]string{"deadbeef", "abcd"}, gomock.Any()).Return(errors.New("some error"))
},
mockrg: func(m *mocks.MockresourceGetter) {
m.EXPECT().GetResourcesByTags(clusterResourceType, map[string]string{
"copilot-application": "phonetool",
"copilot-environment": "pdx",
}).Return([]*resourcegroups.Resource{&mockResource}, nil).Times(2)
},
wantErr: errors.New("some error"),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockECS := mocks.NewMockecsClient(ctrl)
mockrg := mocks.NewMockresourceGetter(ctrl)
tc.mockECS(mockECS)
tc.mockrg(mockrg)
c := Client{
ecsClient: mockECS,
rgGetter: mockrg,
}
// WHEN
err := c.StopWorkloadTasks(tc.inApp, tc.inEnv, tc.inTask)
// THEN
if tc.wantErr != nil {
require.EqualError(t, err, tc.wantErr.Error())
} else {
require.NoError(t, err)
}
})
}
}
func TestClient_StopOneOffTasks(t *testing.T) {
mockCluster := "arn:aws::ecs:cluster/abcd1234"
mockResource := resourcegroups.Resource{
ARN: mockCluster,
}
mockECSTask := []*ecs.Task{
{
TaskArn: aws.String("deadbeef"),
Tags: []*awsecs.Tag{
{
Key: aws.String("copilot-task"),
},
},
},
}
testCases := map[string]struct {
inApp string
inEnv string
inTask string
mockECS func(m *mocks.MockecsClient)
mockrg func(m *mocks.MockresourceGetter)
wantErr error
}{
"success": {
inApp: "phonetool",
inEnv: "pdx",
inTask: "cooltask",
mockECS: func(m *mocks.MockecsClient) {
m.EXPECT().RunningTasksInFamily(mockCluster, "copilot-cooltask").Return(mockECSTask, nil)
m.EXPECT().StopTasks([]string{"deadbeef"}, gomock.Any()).Return(nil)
},
mockrg: func(m *mocks.MockresourceGetter) {
m.EXPECT().GetResourcesByTags(clusterResourceType, map[string]string{
"copilot-application": "phonetool",
"copilot-environment": "pdx",
}).Return([]*resourcegroups.Resource{&mockResource}, nil).Times(2)
},
},
"no tasks": {
inApp: "phonetool",
inEnv: "pdx",
inTask: "cooltask",
mockECS: func(m *mocks.MockecsClient) {
m.EXPECT().RunningTasksInFamily(mockCluster, "copilot-cooltask").Return([]*ecs.Task{}, nil)
m.EXPECT().StopTasks([]string{}, gomock.Any()).Return(nil)
},
mockrg: func(m *mocks.MockresourceGetter) {
m.EXPECT().GetResourcesByTags(clusterResourceType, map[string]string{
"copilot-application": "phonetool",
"copilot-environment": "pdx",
}).Return([]*resourcegroups.Resource{&mockResource}, nil).Times(2)
},
},
"failure getting resources": {
inApp: "phonetool",
inEnv: "pdx",
inTask: "cooltask",
mockECS: func(m *mocks.MockecsClient) {},
mockrg: func(m *mocks.MockresourceGetter) {
m.EXPECT().GetResourcesByTags(clusterResourceType, map[string]string{
"copilot-application": "phonetool",
"copilot-environment": "pdx",
}).Return(nil, errors.New("some error"))
},
wantErr: errors.New(`get ECS cluster with tags "copilot-application"="phonetool","copilot-environment"="pdx": some error`),
},
"failure stopping tasks": {
inApp: "phonetool",
inEnv: "pdx",
inTask: "cooltask",
mockECS: func(m *mocks.MockecsClient) {
m.EXPECT().RunningTasksInFamily(mockCluster, "copilot-cooltask").Return(mockECSTask, nil)
m.EXPECT().StopTasks([]string{"deadbeef"}, gomock.Any()).Return(errors.New("some error"))
},
mockrg: func(m *mocks.MockresourceGetter) {
m.EXPECT().GetResourcesByTags(clusterResourceType, map[string]string{
"copilot-application": "phonetool",
"copilot-environment": "pdx",
}).Return([]*resourcegroups.Resource{&mockResource}, nil).Times(2)
},
wantErr: errors.New("some error"),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockECS := mocks.NewMockecsClient(ctrl)
mockrg := mocks.NewMockresourceGetter(ctrl)
tc.mockECS(mockECS)
tc.mockrg(mockrg)
c := Client{
ecsClient: mockECS,
rgGetter: mockrg,
}
// WHEN
err := c.StopOneOffTasks(tc.inApp, tc.inEnv, tc.inTask)
// THEN
if tc.wantErr != nil {
require.EqualError(t, err, tc.wantErr.Error())
} else {
require.NoError(t, err)
}
})
}
}
func Test_StopDefaultClusterTasks(t *testing.T) {
mockECSTask := []*ecs.Task{
{
TaskArn: aws.String("deadbeef"),
Tags: []*awsecs.Tag{
{
Key: aws.String("copilot-task"),
},
},
},
{
TaskArn: aws.String("deadbeef"),
Tags: []*awsecs.Tag{
{
Key: aws.String("copilot-service"),
},
},
},
}
testCases := map[string]struct {
inTask string
mockECS func(m *mocks.MockecsClient)
wantErr error
}{
"success": {
inTask: "cooltask",
mockECS: func(m *mocks.MockecsClient) {
m.EXPECT().DefaultCluster().Return("cluster", nil)
m.EXPECT().RunningTasksInFamily(gomock.Any(), "copilot-cooltask").Return(mockECSTask, nil)
m.EXPECT().StopTasks([]string{"deadbeef"}, gomock.Any()).Return(nil)
},
},
"failure stopping tasks": {
inTask: "cooltask",
mockECS: func(m *mocks.MockecsClient) {
m.EXPECT().DefaultCluster().Return("cluster", nil)
m.EXPECT().RunningTasksInFamily(gomock.Any(), "copilot-cooltask").Return(mockECSTask, nil)
m.EXPECT().StopTasks([]string{"deadbeef"}, gomock.Any()).Return(errors.New("some error"))
},
wantErr: errors.New("some error"),
},
"failure getting cluster": {
mockECS: func(m *mocks.MockecsClient) {
m.EXPECT().DefaultCluster().Return("", errors.New("some error"))
},
wantErr: errors.New("get default cluster: some error"),
},
"failure listing tasks": {
inTask: "cooltask",
mockECS: func(m *mocks.MockecsClient) {
m.EXPECT().DefaultCluster().Return("cluster", nil)
m.EXPECT().RunningTasksInFamily(gomock.Any(), "copilot-cooltask").Return(nil, errors.New("some error"))
},
wantErr: errors.New("list running tasks in family copilot-cooltask and cluster cluster: some error"),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockECS := mocks.NewMockecsClient(ctrl)
tc.mockECS(mockECS)
c := Client{
ecsClient: mockECS,
}
// WHEN
err := c.StopDefaultClusterTasks(tc.inTask)
// THEN
if tc.wantErr != nil {
require.EqualError(t, err, tc.wantErr.Error())
} else {
require.NoError(t, err)
}
})
}
}
func TestServiceDescriber_TaskDefinition(t *testing.T) {
const (
testApp = "phonetool"
testSvc = "svc"
testEnv = "test"
)
testCases := map[string]struct {
setupMocks func(m *mocks.MockecsClient)
wantedTaskDefinition *ecs.TaskDefinition
wantedError error
}{
"unable to retrieve task definition": {
setupMocks: func(m *mocks.MockecsClient) {
m.EXPECT().TaskDefinition("phonetool-test-svc").Return(nil, errors.New("some error"))
},
wantedError: errors.New("get task definition phonetool-test-svc of service svc: some error"),
},
"successfully return task definition information": {
setupMocks: func(m *mocks.MockecsClient) {
m.EXPECT().TaskDefinition("phonetool-test-svc").Return(&ecs.TaskDefinition{
ExecutionRoleArn: aws.String("execution-role"),
TaskRoleArn: aws.String("task-role"),
ContainerDefinitions: []*awsecs.ContainerDefinition{
{
Name: aws.String("the-container"),
Image: aws.String("beautiful-image"),
Environment: []*awsecs.KeyValuePair{
{
Name: aws.String("weather"),
Value: aws.String("snowy"),
},
{
Name: aws.String("temperature"),
Value: aws.String("low"),
},
},
Secrets: []*awsecs.Secret{
{
Name: aws.String("secret-1"),
ValueFrom: aws.String("first walk to Hokkaido"),
},
{
Name: aws.String("secret-2"),
ValueFrom: aws.String("then get on the HAYABUSA"),
},
},
EntryPoint: aws.StringSlice([]string{"do", "not", "enter"}),
Command: aws.StringSlice([]string{"--force", "--verbose"}),
},
},
}, nil)
},
wantedTaskDefinition: &ecs.TaskDefinition{
ExecutionRoleArn: aws.String("execution-role"),
TaskRoleArn: aws.String("task-role"),
ContainerDefinitions: []*awsecs.ContainerDefinition{
{
Name: aws.String("the-container"),
Image: aws.String("beautiful-image"),
Environment: []*awsecs.KeyValuePair{
{
Name: aws.String("weather"),
Value: aws.String("snowy"),
},
{
Name: aws.String("temperature"),
Value: aws.String("low"),
},
},
Secrets: []*awsecs.Secret{
{
Name: aws.String("secret-1"),
ValueFrom: aws.String("first walk to Hokkaido"),
},
{
Name: aws.String("secret-2"),
ValueFrom: aws.String("then get on the HAYABUSA"),
},
},
EntryPoint: aws.StringSlice([]string{"do", "not", "enter"}),
Command: aws.StringSlice([]string{"--force", "--verbose"}),
},
},
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockECS := mocks.NewMockecsClient(ctrl)
tc.setupMocks(mockECS)
c := Client{
ecsClient: mockECS,
}
// WHEN
got, err := c.TaskDefinition(testApp, testEnv, testSvc)
// THEN
if tc.wantedError != nil {
require.EqualError(t, tc.wantedError, err.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedTaskDefinition, got)
}
})
}
}
func Test_NetworkConfiguration(t *testing.T) {
const (
testApp = "phonetool"
testSvc = "svc"
testEnv = "test"
)
getRgInput := map[string]string{
deploy.AppTagKey: testApp,
deploy.EnvTagKey: testEnv,
}
testCases := map[string]struct {
setupMocks func(m clientMocks)
wantedNetworkConfig *ecs.NetworkConfiguration
wantedError error
}{
"errors if fail to get resources by tags": {
setupMocks: func(m clientMocks) {
gomock.InOrder(
m.resourceGetter.EXPECT().GetResourcesByTags(clusterResourceType, getRgInput).
Return(nil, errors.New("some error")),
)
},
wantedError: fmt.Errorf(`get ECS cluster with tags "copilot-application"="phonetool","copilot-environment"="test": some error`),
},
"errors if no cluster found": {
setupMocks: func(m clientMocks) {
gomock.InOrder(
m.resourceGetter.EXPECT().GetResourcesByTags(clusterResourceType, getRgInput).
Return([]*resourcegroups.Resource{}, nil),
)
},
wantedError: fmt.Errorf(`no ECS cluster found with tags "copilot-application"="phonetool","copilot-environment"="test"`),
},
"errors if more than one cluster found": {
setupMocks: func(m clientMocks) {
gomock.InOrder(
m.resourceGetter.EXPECT().GetResourcesByTags(clusterResourceType, getRgInput).
Return([]*resourcegroups.Resource{
{ARN: "mockARN1"}, {ARN: "mockARN2"},
}, nil),
)
},
wantedError: fmt.Errorf(`more than one ECS cluster are found with tags "copilot-application"="phonetool","copilot-environment"="test"`),
},
"successfully retrieve network configuration": {
setupMocks: func(m clientMocks) {
gomock.InOrder(
m.resourceGetter.EXPECT().GetResourcesByTags(clusterResourceType, getRgInput).
Return([]*resourcegroups.Resource{
{ARN: "cluster-1"},
}, nil),
m.resourceGetter.EXPECT().GetResourcesByTags(serviceResourceType, map[string]string{
deploy.AppTagKey: testApp,
deploy.EnvTagKey: testEnv,
deploy.ServiceTagKey: testSvc,
}).Return([]*resourcegroups.Resource{
{ARN: "arn:aws:ecs:us-west-2:1234567890:service/my-project-test-Cluster-9F7Y0RLP60R7/my-project-test-myService-JSOH5GYBFAIB"},
}, nil),
m.ecsClient.EXPECT().NetworkConfiguration("cluster-1", "my-project-test-myService-JSOH5GYBFAIB").Return(&ecs.NetworkConfiguration{
AssignPublicIp: "1.2.3.4",
SecurityGroups: []string{"sg-1", "sg-2"},
Subnets: []string{"sn-1", "sn-2"},
}, nil),
)
},
wantedNetworkConfig: &ecs.NetworkConfiguration{
AssignPublicIp: "1.2.3.4",
SecurityGroups: []string{"sg-1", "sg-2"},
Subnets: []string{"sn-1", "sn-2"},
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
// GIVEN
m := clientMocks{
resourceGetter: mocks.NewMockresourceGetter(ctrl),
ecsClient: mocks.NewMockecsClient(ctrl),
}
tc.setupMocks(m)
client := Client{
rgGetter: m.resourceGetter,
ecsClient: m.ecsClient,
}
// WHEN
get, err := client.NetworkConfiguration(testApp, testEnv, testSvc)
// THEN
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, get, tc.wantedNetworkConfig)
}
})
}
}
func Test_NetworkConfigurationForJob(t *testing.T) {
const (
testApp = "testApp"
testEnv = "testEnv"
testJob = "testJob"
testARN = "arn:aws:states:us-east-1:1234456789012:stateMachine:testApp-testEnv-testJob"
testStateMachineDefinition = `{
"Version": "1.0",
"Comment": "Run AWS Fargate task",
"StartAt": "Run Fargate Task",
"States": {
"Run Fargate Task": {
"Type": "Task",
"Resource": "arn:aws:states:::ecs:runTask.sync",
"Parameters": {
"LaunchType": "FARGATE",
"PlatformVersion": "LATEST",
"Cluster": "cluster",
"TaskDefinition": "def",
"PropagateTags": "TASK_DEFINITION",
"Group.$": "$$.Execution.Name",
"NetworkConfiguration": {
"AwsvpcConfiguration": {
"Subnets": ["sbn-1", "sbn-2"],
"AssignPublicIp": "ENABLED",
"SecurityGroups": ["sg-1", "sg-2"]
}
}
},
"End": true
}
}
}`
)
testCases := map[string]struct {
setupMocks func(m clientMocks)
wantedConfig *ecs.NetworkConfiguration
wantedError error
}{
"success": {
setupMocks: func(m clientMocks) {
m.resourceGetter.EXPECT().GetResourcesByTags(resourcegroups.ResourceTypeStateMachine, map[string]string{
deploy.AppTagKey: testApp,
deploy.EnvTagKey: testEnv,
deploy.ServiceTagKey: testJob,
}).Return([]*resourcegroups.Resource{
{
ARN: "random-arn-doesn't matter",
},
{
ARN: testARN,
},
}, nil)
m.StepFuncClient.EXPECT().StateMachineDefinition(testARN).Return(testStateMachineDefinition, nil)
},
wantedConfig: &ecs.NetworkConfiguration{
Subnets: []string{"sbn-1", "sbn-2"},
SecurityGroups: []string{"sg-1", "sg-2"},
AssignPublicIp: "ENABLED",
},
},
"fail to get resources by tags": {
setupMocks: func(m clientMocks) {
m.resourceGetter.EXPECT().GetResourcesByTags(resourcegroups.ResourceTypeStateMachine, map[string]string{
deploy.AppTagKey: testApp,
deploy.EnvTagKey: testEnv,
deploy.ServiceTagKey: testJob,
}).Return(nil, errors.New("some error"))
},
wantedError: errors.New(`get state machine resource with tags "copilot-application"="testApp","copilot-environment"="testEnv","copilot-service"="testJob": some error`),
},
"state machine resource not found": {
setupMocks: func(m clientMocks) {
m.resourceGetter.EXPECT().GetResourcesByTags(resourcegroups.ResourceTypeStateMachine, map[string]string{
deploy.AppTagKey: testApp,
deploy.EnvTagKey: testEnv,
deploy.ServiceTagKey: testJob,
}).Return([]*resourcegroups.Resource{
{
ARN: "rabbit",
},
{
ARN: "cabbage",
},
}, nil)
},
wantedError: errors.New("state machine for job testJob not found"),
},
"fail to get state machine definition": {
setupMocks: func(m clientMocks) {
m.resourceGetter.EXPECT().GetResourcesByTags(resourcegroups.ResourceTypeStateMachine, map[string]string{
deploy.AppTagKey: testApp,
deploy.EnvTagKey: testEnv,
deploy.ServiceTagKey: testJob,
}).Return([]*resourcegroups.Resource{
{
ARN: "random-arn-doesn't matter",
},
{
ARN: testARN,
},
}, nil)
m.StepFuncClient.EXPECT().StateMachineDefinition(testARN).Return("", errors.New("some error"))
},
wantedError: errors.New("get state machine definition for job testJob: some error"),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
// GIVEN
m := clientMocks{
StepFuncClient: mocks.NewMockstepFunctionsClient(ctrl),
resourceGetter: mocks.NewMockresourceGetter(ctrl),
}
tc.setupMocks(m)
client := Client{
rgGetter: m.resourceGetter,
StepFuncClient: m.StepFuncClient,
}
// WHEN
get, err := client.NetworkConfigurationForJob(testApp, testEnv, testJob)
// THEN
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, get, tc.wantedConfig)
}
})
}
}
func Test_HasNonZeroExitCode(t *testing.T) {
testCases := map[string]struct {
inTaskARNs []string
inGroupName string
inCluster string
setupMocks func(m clientMocks)
wantedError error
}{
"returns the non zero exit code of the essential container": {
inCluster: "cluster-1",
inTaskARNs: []string{"mockTask1"},
setupMocks: func(m clientMocks) {
gomock.InOrder(
m.ecsClient.EXPECT().DescribeTasks("cluster-1", []string{"mockTask1"}).Return([]*ecs.Task{
{
TaskArn: aws.String("arn:aws:ecs:us-west-2:123456789:task/4082490ee6c245e09d2145010aa1ba8d"),
TaskDefinitionArn: aws.String("arn:aws:ecs:us-west-2:1233454566:task-definition/CdkExampleStacknametaskdefinitionCA96DCAA:1"),
StoppedReason: aws.String("Task failed to start"),
LastStatus: aws.String("STOPPED"),
Containers: []*awsecs.Container{
{
Name: aws.String("the-one-and-only-one-container"),
ExitCode: aws.Int64(1),
},
},
},
}, nil),
m.ecsClient.EXPECT().TaskDefinition("arn:aws:ecs:us-west-2:1233454566:task-definition/CdkExampleStacknametaskdefinitionCA96DCAA:1").Return(&ecs.TaskDefinition{
ExecutionRoleArn: aws.String("execution-role"),
TaskRoleArn: aws.String("task-role"),
ContainerDefinitions: []*awsecs.ContainerDefinition{
{
Name: aws.String("the-one-and-only-one-container"),
Image: aws.String("beautiful-image"),
EntryPoint: aws.StringSlice([]string{"enter", "here"}),
Command: aws.StringSlice([]string{"do", "not", "enter", "here"}),
Essential: aws.Bool(true),
Environment: []*awsecs.KeyValuePair{
{
Name: aws.String("enter"),
Value: aws.String("no"),
},
{
Name: aws.String("kidding"),
Value: aws.String("yes"),
},
},
Secrets: []*awsecs.Secret{
{
Name: aws.String("truth"),
ValueFrom: aws.String("go-ask-the-wise"),
},
},
},
},
}, nil),
)
},
wantedError: fmt.Errorf("container the-one-and-only-one-container in task 4082490ee6c245e09d2145010aa1ba8d exited with status code 1"),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
// GIVEN
m := clientMocks{
ecsClient: mocks.NewMockecsClient(ctrl),
}
tc.setupMocks(m)
client := Client{
ecsClient: m.ecsClient,
}
// WHEN
err := client.HasNonZeroExitCode(tc.inTaskARNs, tc.inCluster)
// THEN
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
}
})
}
}
| 1,531 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package ecs
import "fmt"
// ErrMultipleContainersInTaskDef is returned when multiple containers are configured in a task definition.
type ErrMultipleContainersInTaskDef struct {
taskDefIdentifier string
}
func (e *ErrMultipleContainersInTaskDef) Error() string {
return fmt.Sprintf("found more than one container in task definition: %s", e.taskDefIdentifier)
}
// ErrExitCode builds custom non-zero exit code error
type ErrExitCode struct {
containerName string
taskId string
exitCode int
}
func (e *ErrExitCode) Error() string {
return fmt.Sprintf("container %s in task %s exited with status code %d", e.containerName, e.taskId, e.exitCode)
}
// ExitCode returns the OS exit code configured for this error.
func (e *ErrExitCode) ExitCode() int {
return e.exitCode
}
| 32 |
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 retrieve Copilot ECS information.
package ecs
import (
"encoding/csv"
"fmt"
"sort"
"strings"
"github.com/aws/aws-sdk-go/aws"
awsecs "github.com/aws/copilot-cli/internal/pkg/aws/ecs"
)
const (
fmtStateMachineName = "%s-%s-%s" // refer to workload's state-machine partial template.
)
// ECSServiceDescriber provides information on an ECS service.
type ECSServiceDescriber interface {
Service(clusterName, serviceName string) (*awsecs.Service, error)
TaskDefinition(taskDefName string) (*awsecs.TaskDefinition, error)
NetworkConfiguration(cluster, serviceName string) (*awsecs.NetworkConfiguration, error)
}
// ServiceDescriber provides information on a Copilot service.
type ServiceDescriber interface {
TaskDefinition(app, env, svc string) (*awsecs.TaskDefinition, error)
NetworkConfiguration(app, env, svc string) (*awsecs.NetworkConfiguration, error)
ClusterARN(app, env string) (string, error)
}
// JobDescriber provides information on a Copilot job.
type JobDescriber interface {
TaskDefinition(app, env, job string) (*awsecs.TaskDefinition, error)
NetworkConfigurationForJob(app, env, job string) (*awsecs.NetworkConfiguration, error)
ClusterARN(app, env string) (string, error)
}
// RunTaskRequest contains information to generate a task run command.
type RunTaskRequest struct {
networkConfiguration awsecs.NetworkConfiguration
executionRole string
taskRole string
appName string
envName string
cluster string
containerInfo
}
type containerInfo struct {
image string
entryPoint []string
command []string
envVars map[string]string
secrets map[string]string
}
// RunTaskRequestFromECSService populates a RunTaskRequest with information from an ECS service.
func RunTaskRequestFromECSService(client ECSServiceDescriber, cluster, service string) (*RunTaskRequest, error) {
networkConfig, err := client.NetworkConfiguration(cluster, service)
if err != nil {
return nil, fmt.Errorf("retrieve network configuration for service %s in cluster %s: %w", service, cluster, err)
}
svc, err := client.Service(cluster, service)
if err != nil {
return nil, fmt.Errorf("retrieve service %s in cluster %s: %w", service, cluster, err)
}
taskDefNameOrARN := aws.StringValue(svc.TaskDefinition)
taskDef, err := client.TaskDefinition(taskDefNameOrARN)
if err != nil {
return nil, fmt.Errorf("retrieve task definition %s: %w", taskDefNameOrARN, err)
}
if len(taskDef.ContainerDefinitions) > 1 {
return nil, &ErrMultipleContainersInTaskDef{
taskDefIdentifier: taskDefNameOrARN,
}
}
containerName := aws.StringValue(taskDef.ContainerDefinitions[0].Name)
containerInfo, err := containerInformation(taskDef, containerName)
if err != nil {
return nil, err
}
return &RunTaskRequest{
networkConfiguration: *networkConfig,
executionRole: aws.StringValue(taskDef.ExecutionRoleArn),
taskRole: aws.StringValue(taskDef.TaskRoleArn),
containerInfo: *containerInfo,
cluster: cluster,
}, nil
}
// RunTaskRequestFromService populates a RunTaskRequest with information from a Copilot service.
func RunTaskRequestFromService(client ServiceDescriber, app, env, svc string) (*RunTaskRequest, error) {
networkConfig, err := client.NetworkConfiguration(app, env, svc)
if err != nil {
return nil, fmt.Errorf("retrieve network configuration for service %s: %w", svc, err)
}
// --subnets flag isn't supported when passing --app/--env, instead the subnet config
// will be read and applied during run.
if networkConfig != nil {
networkConfig.Subnets = nil
}
taskDef, err := client.TaskDefinition(app, env, svc)
if err != nil {
return nil, fmt.Errorf("retrieve task definition for service %s: %w", svc, err)
}
containerName := svc // NOTE: refer to workload's CloudFormation template. The container name is set to be the workload's name.
containerInfo, err := containerInformation(taskDef, containerName)
if err != nil {
return nil, err
}
return &RunTaskRequest{
networkConfiguration: *networkConfig,
executionRole: aws.StringValue(taskDef.ExecutionRoleArn),
taskRole: aws.StringValue(taskDef.TaskRoleArn),
containerInfo: *containerInfo,
appName: app,
envName: env,
}, nil
}
// RunTaskRequestFromJob populates a RunTaskRequest with information from a Copilot job.
func RunTaskRequestFromJob(client JobDescriber, app, env, job string) (*RunTaskRequest, error) {
config, err := client.NetworkConfigurationForJob(app, env, job)
if err != nil {
return nil, fmt.Errorf("retrieve network configuration for job %s: %w", job, err)
}
// --subnets flag isn't supported when passing --app/--env, instead the subnet config
// will be read and applied during run.
if config != nil {
config.Subnets = nil
}
taskDef, err := client.TaskDefinition(app, env, job)
if err != nil {
return nil, fmt.Errorf("retrieve task definition for job %s: %w", job, err)
}
containerName := job // NOTE: refer to workload's CloudFormation template. The container name is set to be the workload's name.
containerInfo, err := containerInformation(taskDef, containerName)
if err != nil {
return nil, err
}
return &RunTaskRequest{
networkConfiguration: *config,
executionRole: aws.StringValue(taskDef.ExecutionRoleArn),
taskRole: aws.StringValue(taskDef.TaskRoleArn),
containerInfo: *containerInfo,
appName: app,
envName: env,
}, nil
}
// CLIString stringifies a RunTaskRequest.
func (r RunTaskRequest) CLIString() (string, error) {
output := []string{"copilot task run"}
if r.executionRole != "" {
output = append(output, fmt.Sprintf("--execution-role %s", r.executionRole))
}
if r.taskRole != "" {
output = append(output, fmt.Sprintf("--task-role %s", r.taskRole))
}
if r.image != "" {
output = append(output, fmt.Sprintf("--image %s", r.image))
}
if r.entryPoint != nil {
output = append(output, fmt.Sprintf("--entrypoint %s", fmt.Sprintf("\"%s\"", strings.Join(r.entryPoint, " "))))
}
if r.command != nil {
output = append(output, fmt.Sprintf("--command %s", fmt.Sprintf("\"%s\"", strings.Join(r.command, " "))))
}
if r.envVars != nil && len(r.envVars) != 0 {
vars, err := fmtStringMapToString(r.envVars)
if err != nil {
return "", err
}
output = append(output, fmt.Sprintf("--env-vars %s", vars))
}
if r.secrets != nil && len(r.secrets) != 0 {
secrets, err := fmtStringMapToString(r.secrets)
if err != nil {
return "", err
}
output = append(output, fmt.Sprintf("--secrets %s", secrets))
}
if r.networkConfiguration.Subnets != nil && len(r.networkConfiguration.Subnets) != 0 {
output = append(output, fmt.Sprintf("--subnets %s", strings.Join(r.networkConfiguration.Subnets, ",")))
}
if r.networkConfiguration.SecurityGroups != nil && len(r.networkConfiguration.SecurityGroups) != 0 {
output = append(output, fmt.Sprintf("--security-groups %s", strings.Join(r.networkConfiguration.SecurityGroups, ",")))
}
if r.appName != "" {
output = append(output, fmt.Sprintf("--app %s", r.appName))
}
if r.envName != "" {
output = append(output, fmt.Sprintf("--env %s", r.envName))
}
if r.cluster != "" {
output = append(output, fmt.Sprintf("--cluster %s", r.cluster))
}
return strings.Join(output, " \\\n"), nil
}
func containerInformation(taskDef *awsecs.TaskDefinition, containerName string) (*containerInfo, error) {
image, err := taskDef.Image(containerName)
if err != nil {
return nil, err
}
entrypoint, err := taskDef.EntryPoint(containerName)
if err != nil {
return nil, err
}
command, err := taskDef.Command(containerName)
if err != nil {
return nil, err
}
envVars := make(map[string]string)
for _, envVar := range taskDef.EnvironmentVariables() {
if envVar.Container == containerName {
envVars[envVar.Name] = envVar.Value
}
}
secrets := make(map[string]string)
for _, secret := range taskDef.Secrets() {
if secret.Container == containerName {
secrets[secret.Name] = secret.ValueFrom
}
}
return &containerInfo{
image: image,
entryPoint: entrypoint,
command: command,
envVars: envVars,
secrets: secrets,
}, nil
}
// This function will format a map to a string as "key1=value1,key2=value2,key3=value3".
// Much of the complexity here comes from the two levels of escaping going on:
// 1. we are outputting a command to be copied and pasted into a shell, so we need to shell-escape the output.
// 2. the pflag library parses StringToString args as csv, so we csv escape the individual key/value pairs.
func fmtStringMapToString(m map[string]string) (string, error) {
// Sort the map so that the output is consistent and the unit test won't be flaky.
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
// write the key=value pairs as csv fields, which is what
// pflag expects to read in.
// This will escape internal double quotes and commas.
// We then need to trim the trailing newline that the csv writer adds.
var output []string
for _, k := range keys {
output = append(output, fmt.Sprintf("%s=%s", k, m[k]))
}
buf := new(strings.Builder)
w := csv.NewWriter(buf)
err := w.Write(output)
if err != nil {
return "", err
}
w.Flush()
final := strings.TrimSuffix(buf.String(), "\n")
// Then for shell escaping, wrap the entire argument in single quotes
// and escape any internal single quotes.
return shellQuote(final), nil
}
func shellQuote(s string) string {
return `'` + strings.ReplaceAll(s, `'`, `'\''`) + `'`
}
| 308 |
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"
"strings"
"testing"
"github.com/aws/copilot-cli/internal/pkg/ecs/mocks"
"github.com/aws/aws-sdk-go/aws"
awsecs "github.com/aws/aws-sdk-go/service/ecs"
"github.com/aws/copilot-cli/internal/pkg/aws/ecs"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
func Test_RunTaskRequestFromECSService(t *testing.T) {
var (
testCluster = "crowded-cluster"
testService = "good-service"
)
testCases := map[string]struct {
setUpMock func(m *mocks.MockECSServiceDescriber)
wantedRunTaskRequest *RunTaskRequest
wantedError error
}{
"success": {
setUpMock: func(m *mocks.MockECSServiceDescriber) {
m.EXPECT().Service(testCluster, testService).Return(&ecs.Service{
TaskDefinition: aws.String("task-def"),
}, nil)
m.EXPECT().TaskDefinition("task-def").Return(&ecs.TaskDefinition{
ExecutionRoleArn: aws.String("execution-role"),
TaskRoleArn: aws.String("task-role"),
ContainerDefinitions: []*awsecs.ContainerDefinition{
{
Name: aws.String("the-one-and-only-one-container"),
Image: aws.String("beautiful-image"),
EntryPoint: aws.StringSlice([]string{"enter", "here"}),
Command: aws.StringSlice([]string{"do", "not", "enter", "here"}),
Environment: []*awsecs.KeyValuePair{
{
Name: aws.String("enter"),
Value: aws.String("no"),
},
{
Name: aws.String("kidding"),
Value: aws.String("yes"),
},
},
Secrets: []*awsecs.Secret{
{
Name: aws.String("truth"),
ValueFrom: aws.String("go-ask-the-wise"),
},
},
},
},
}, nil)
m.EXPECT().NetworkConfiguration(testCluster, testService).Return(&ecs.NetworkConfiguration{
AssignPublicIp: "1.2.3.4",
Subnets: []string{"sbn-1", "sbn-2"},
SecurityGroups: []string{"sg-1", "sg-2"},
}, nil)
},
wantedRunTaskRequest: &RunTaskRequest{
networkConfiguration: ecs.NetworkConfiguration{
AssignPublicIp: "1.2.3.4",
Subnets: []string{"sbn-1", "sbn-2"},
SecurityGroups: []string{"sg-1", "sg-2"},
},
executionRole: "execution-role",
taskRole: "task-role",
containerInfo: containerInfo{
image: "beautiful-image",
entryPoint: []string{"enter", "here"},
command: []string{"do", "not", "enter", "here"},
envVars: map[string]string{
"enter": "no",
"kidding": "yes",
},
secrets: map[string]string{
"truth": "go-ask-the-wise",
},
},
cluster: testCluster,
},
},
"unable to retrieve service": {
setUpMock: func(m *mocks.MockECSServiceDescriber) {
m.EXPECT().Service(testCluster, testService).Return(nil, errors.New("some error"))
m.EXPECT().NetworkConfiguration(gomock.Any(), gomock.Any()).AnyTimes()
},
wantedError: errors.New("retrieve service good-service in cluster crowded-cluster: some error"),
},
"unable to retrieve task definition": {
setUpMock: func(m *mocks.MockECSServiceDescriber) {
m.EXPECT().Service(testCluster, testService).Return(&ecs.Service{
TaskDefinition: aws.String("task-def"),
}, nil)
m.EXPECT().TaskDefinition("task-def").Return(nil, errors.New("some error"))
m.EXPECT().NetworkConfiguration(gomock.Any(), gomock.Any()).AnyTimes()
},
wantedError: errors.New("retrieve task definition task-def: some error"),
},
"unable to retrieve network configuration": {
setUpMock: func(m *mocks.MockECSServiceDescriber) {
m.EXPECT().Service(gomock.Any(), gomock.Any()).AnyTimes()
m.EXPECT().TaskDefinition(gomock.Any()).AnyTimes()
m.EXPECT().NetworkConfiguration(testCluster, testService).Return(nil, errors.New("some error"))
},
wantedError: errors.New("retrieve network configuration for service good-service in cluster crowded-cluster: some error"),
},
"error if found more than one container": {
setUpMock: func(m *mocks.MockECSServiceDescriber) {
m.EXPECT().Service(testCluster, testService).Return(&ecs.Service{
TaskDefinition: aws.String("task-def"),
}, nil)
m.EXPECT().TaskDefinition("task-def").Return(&ecs.TaskDefinition{
ExecutionRoleArn: aws.String("execution-role"),
TaskRoleArn: aws.String("task-role"),
ContainerDefinitions: []*awsecs.ContainerDefinition{
{
Name: aws.String("the-first-container"),
},
{
Name: aws.String("sad-container"),
},
},
}, nil)
m.EXPECT().NetworkConfiguration(gomock.Any(), gomock.Any()).AnyTimes()
},
wantedError: errors.New("found more than one container in task definition: task-def"),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := mocks.NewMockECSServiceDescriber(ctrl)
tc.setUpMock(m)
got, err := RunTaskRequestFromECSService(m, testCluster, testService)
if tc.wantedError != nil {
require.EqualError(t, tc.wantedError, err.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedRunTaskRequest, got)
}
})
}
}
func Test_RunTaskRequestFromService(t *testing.T) {
var (
testApp = "app"
testEnv = "env"
testSvc = "svc"
)
testCases := map[string]struct {
setUpMock func(m *mocks.MockServiceDescriber)
wantedRunTaskRequest *RunTaskRequest
wantedError error
}{
"returns RunTaskRequest with service's main container": {
setUpMock: func(m *mocks.MockServiceDescriber) {
m.EXPECT().TaskDefinition(testApp, testEnv, testSvc).Return(&ecs.TaskDefinition{
ExecutionRoleArn: aws.String("execution-role"),
TaskRoleArn: aws.String("task-role"),
ContainerDefinitions: []*awsecs.ContainerDefinition{
{
Name: aws.String(testSvc),
Image: aws.String("beautiful-image"),
EntryPoint: aws.StringSlice([]string{"enter", "here"}),
Command: aws.StringSlice([]string{"do", "not", "enter", "here"}),
Environment: []*awsecs.KeyValuePair{
{
Name: aws.String("enter"),
Value: aws.String("no"),
},
{
Name: aws.String("kidding"),
Value: aws.String("yes"),
},
},
Secrets: []*awsecs.Secret{
{
Name: aws.String("truth"),
ValueFrom: aws.String("go-ask-the-wise"),
},
},
},
{
Name: aws.String("random-container-that-we-do-not-care"),
},
},
}, nil)
m.EXPECT().NetworkConfiguration(testApp, testEnv, testSvc).Return(&ecs.NetworkConfiguration{
AssignPublicIp: "1.2.3.4",
Subnets: []string{"sbn-1", "sbn-2"},
SecurityGroups: []string{"sg-1", "sg-2"},
}, nil)
},
wantedRunTaskRequest: &RunTaskRequest{
networkConfiguration: ecs.NetworkConfiguration{
AssignPublicIp: "1.2.3.4",
SecurityGroups: []string{"sg-1", "sg-2"},
},
executionRole: "execution-role",
taskRole: "task-role",
appName: testApp,
envName: testEnv,
containerInfo: containerInfo{
image: "beautiful-image",
entryPoint: []string{"enter", "here"},
command: []string{"do", "not", "enter", "here"},
envVars: map[string]string{
"enter": "no",
"kidding": "yes",
},
secrets: map[string]string{
"truth": "go-ask-the-wise",
},
},
},
},
"unable to retrieve task definition": {
setUpMock: func(m *mocks.MockServiceDescriber) {
m.EXPECT().TaskDefinition(testApp, testEnv, testSvc).Return(nil, errors.New("some error"))
m.EXPECT().NetworkConfiguration(gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes()
m.EXPECT().ClusterARN(gomock.Any(), gomock.Any()).AnyTimes()
},
wantedError: errors.New("retrieve task definition for service svc: some error"),
},
"unable to retrieve network configuration": {
setUpMock: func(m *mocks.MockServiceDescriber) {
m.EXPECT().TaskDefinition(gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes()
m.EXPECT().NetworkConfiguration(testApp, testEnv, testSvc).Return(nil, errors.New("some error"))
m.EXPECT().ClusterARN(gomock.Any(), gomock.Any()).AnyTimes()
},
wantedError: errors.New("retrieve network configuration for service svc: some error"),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := mocks.NewMockServiceDescriber(ctrl)
tc.setUpMock(m)
got, err := RunTaskRequestFromService(m, testApp, testEnv, testSvc)
if tc.wantedError != nil {
require.EqualError(t, tc.wantedError, err.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedRunTaskRequest, got)
}
})
}
}
func Test_RunTaskRequestFromJob(t *testing.T) {
var (
testApp = "test-app"
testEnv = "test-env"
testJob = "test-job"
)
testCases := map[string]struct {
setUpMock func(m *mocks.MockJobDescriber)
wantedRunTaskRequest *RunTaskRequest
wantedError error
}{
"returns RunTaskRequest with job's main container": {
setUpMock: func(m *mocks.MockJobDescriber) {
m.EXPECT().TaskDefinition(testApp, testEnv, testJob).Return(&ecs.TaskDefinition{
ExecutionRoleArn: aws.String("execution-role"),
TaskRoleArn: aws.String("task-role"),
ContainerDefinitions: []*awsecs.ContainerDefinition{
{
Name: aws.String(testJob),
Image: aws.String("beautiful-image"),
EntryPoint: aws.StringSlice([]string{"enter", "here"}),
Command: aws.StringSlice([]string{"do", "not", "enter", "here"}),
Environment: []*awsecs.KeyValuePair{
{
Name: aws.String("enter"),
Value: aws.String("no"),
},
{
Name: aws.String("kidding"),
Value: aws.String("yes"),
},
},
Secrets: []*awsecs.Secret{
{
Name: aws.String("truth"),
ValueFrom: aws.String("go-ask-the-wise"),
},
},
},
{
Name: aws.String("random-container-that-we-do-not-care"),
},
},
}, nil)
m.EXPECT().NetworkConfigurationForJob(testApp, testEnv, testJob).Return(&ecs.NetworkConfiguration{
AssignPublicIp: "1.2.3.4",
Subnets: []string{"sbn-1", "sbn-2"},
SecurityGroups: []string{"sg-1", "sg-2"},
}, nil)
},
wantedRunTaskRequest: &RunTaskRequest{
networkConfiguration: ecs.NetworkConfiguration{
AssignPublicIp: "1.2.3.4",
SecurityGroups: []string{"sg-1", "sg-2"},
},
executionRole: "execution-role",
taskRole: "task-role",
appName: testApp,
envName: testEnv,
containerInfo: containerInfo{
image: "beautiful-image",
entryPoint: []string{"enter", "here"},
command: []string{"do", "not", "enter", "here"},
envVars: map[string]string{
"enter": "no",
"kidding": "yes",
},
secrets: map[string]string{
"truth": "go-ask-the-wise",
},
},
},
},
"unable to retrieve task definition": {
setUpMock: func(m *mocks.MockJobDescriber) {
m.EXPECT().TaskDefinition(testApp, testEnv, testJob).Return(nil, errors.New("some error"))
m.EXPECT().NetworkConfigurationForJob(gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes()
m.EXPECT().ClusterARN(gomock.Any(), gomock.Any()).AnyTimes()
},
wantedError: errors.New("retrieve task definition for job test-job: some error"),
},
"unable to retrieve network configuration": {
setUpMock: func(m *mocks.MockJobDescriber) {
m.EXPECT().TaskDefinition(gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes()
m.EXPECT().NetworkConfigurationForJob(testApp, testEnv, testJob).Return(nil, errors.New("some error"))
m.EXPECT().ClusterARN(gomock.Any(), gomock.Any()).AnyTimes()
},
wantedError: errors.New("retrieve network configuration for job test-job: some error"),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := mocks.NewMockJobDescriber(ctrl)
tc.setUpMock(m)
got, err := RunTaskRequestFromJob(m, testApp, testEnv, testJob)
if tc.wantedError != nil {
require.EqualError(t, tc.wantedError, err.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedRunTaskRequest, got)
}
})
}
}
func TestRunTaskRequest_CLIString(t *testing.T) {
var (
testApp = "test-app"
testEnv = "test-env"
)
testCases := map[string]struct {
in RunTaskRequest
wanted string
}{
"generates copilot service cmd with --app and --env and --security-groups": {
in: RunTaskRequest{
networkConfiguration: ecs.NetworkConfiguration{
AssignPublicIp: "1.2.3.4",
SecurityGroups: []string{"sg-1", "sg-2"},
},
executionRole: "execution-role",
taskRole: "task-role",
appName: testApp,
envName: testEnv,
containerInfo: containerInfo{
image: "beautiful-image",
entryPoint: []string{"enter", "here"},
command: []string{"do", "not", "enter", "here"},
envVars: map[string]string{
"enter": "no",
"kidding": "yes",
},
secrets: map[string]string{
"truth": "go-ask-the-wise",
},
},
},
wanted: strings.Join([]string{
"copilot task run",
"--execution-role execution-role",
"--task-role task-role",
"--image beautiful-image",
"--entrypoint \"enter here\"",
"--command \"do not enter here\"",
`--env-vars 'enter=no,kidding=yes'`,
`--secrets 'truth=go-ask-the-wise'`,
"--security-groups sg-1,sg-2",
fmt.Sprintf("--app %s", testApp),
fmt.Sprintf("--env %s", testEnv),
}, " \\\n"),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
got, err := tc.in.CLIString()
require.Nil(t, err)
require.Equal(t, tc.wanted, got)
})
}
}
func TestRunTaskRequest_fmtStringMapToString(t *testing.T) {
testCases := map[string]struct {
in map[string]string
wanted string
}{
"with internal commas": {
in: map[string]string{"a": "1,2,3", "b": "2"},
wanted: `'"a=1,2,3",b=2'`,
},
"with internal quotes": {
in: map[string]string{"name": `john "nickname" doe`, "single": "single 'quote'"},
wanted: `'"name=john ""nickname"" doe",single=single '\''quote'\'''`,
},
"with internal equals sign": {
in: map[string]string{"a": "4=2+2=4", "b": "b"},
wanted: `'a=4=2+2=4,b=b'`,
},
"with a json env var": {
in: map[string]string{"myval": `{"key1":"val1","key2":5}`},
wanted: `'"myval={""key1"":""val1"",""key2"":5}"'`,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
got, err := fmtStringMapToString(tc.in)
require.Nil(t, err)
require.Equal(t, tc.wanted, got)
})
}
}
| 483 |
copilot-cli | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: ./internal/pkg/ecs/ecs.go
// Package mocks is a generated GoMock package.
package mocks
import (
reflect "reflect"
ecs "github.com/aws/copilot-cli/internal/pkg/aws/ecs"
resourcegroups "github.com/aws/copilot-cli/internal/pkg/aws/resourcegroups"
gomock "github.com/golang/mock/gomock"
)
// 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)
}
// MockecsClient is a mock of ecsClient interface.
type MockecsClient struct {
ctrl *gomock.Controller
recorder *MockecsClientMockRecorder
}
// MockecsClientMockRecorder is the mock recorder for MockecsClient.
type MockecsClientMockRecorder struct {
mock *MockecsClient
}
// NewMockecsClient creates a new mock instance.
func NewMockecsClient(ctrl *gomock.Controller) *MockecsClient {
mock := &MockecsClient{ctrl: ctrl}
mock.recorder = &MockecsClientMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockecsClient) EXPECT() *MockecsClientMockRecorder {
return m.recorder
}
// DefaultCluster mocks base method.
func (m *MockecsClient) DefaultCluster() (string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DefaultCluster")
ret0, _ := ret[0].(string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DefaultCluster indicates an expected call of DefaultCluster.
func (mr *MockecsClientMockRecorder) DefaultCluster() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DefaultCluster", reflect.TypeOf((*MockecsClient)(nil).DefaultCluster))
}
// DescribeTasks mocks base method.
func (m *MockecsClient) DescribeTasks(cluster string, taskARNs []string) ([]*ecs.Task, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DescribeTasks", cluster, taskARNs)
ret0, _ := ret[0].([]*ecs.Task)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DescribeTasks indicates an expected call of DescribeTasks.
func (mr *MockecsClientMockRecorder) DescribeTasks(cluster, taskARNs interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeTasks", reflect.TypeOf((*MockecsClient)(nil).DescribeTasks), cluster, taskARNs)
}
// NetworkConfiguration mocks base method.
func (m *MockecsClient) NetworkConfiguration(cluster, serviceName string) (*ecs.NetworkConfiguration, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "NetworkConfiguration", cluster, serviceName)
ret0, _ := ret[0].(*ecs.NetworkConfiguration)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// NetworkConfiguration indicates an expected call of NetworkConfiguration.
func (mr *MockecsClientMockRecorder) NetworkConfiguration(cluster, serviceName interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NetworkConfiguration", reflect.TypeOf((*MockecsClient)(nil).NetworkConfiguration), cluster, serviceName)
}
// RunningTasks mocks base method.
func (m *MockecsClient) RunningTasks(cluster string) ([]*ecs.Task, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RunningTasks", cluster)
ret0, _ := ret[0].([]*ecs.Task)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// RunningTasks indicates an expected call of RunningTasks.
func (mr *MockecsClientMockRecorder) RunningTasks(cluster interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RunningTasks", reflect.TypeOf((*MockecsClient)(nil).RunningTasks), cluster)
}
// RunningTasksInFamily mocks base method.
func (m *MockecsClient) RunningTasksInFamily(cluster, family string) ([]*ecs.Task, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RunningTasksInFamily", cluster, family)
ret0, _ := ret[0].([]*ecs.Task)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// RunningTasksInFamily indicates an expected call of RunningTasksInFamily.
func (mr *MockecsClientMockRecorder) RunningTasksInFamily(cluster, family interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RunningTasksInFamily", reflect.TypeOf((*MockecsClient)(nil).RunningTasksInFamily), cluster, family)
}
// Service mocks base method.
func (m *MockecsClient) Service(clusterName, serviceName string) (*ecs.Service, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Service", clusterName, serviceName)
ret0, _ := ret[0].(*ecs.Service)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Service indicates an expected call of Service.
func (mr *MockecsClientMockRecorder) Service(clusterName, serviceName interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Service", reflect.TypeOf((*MockecsClient)(nil).Service), clusterName, serviceName)
}
// ServiceRunningTasks mocks base method.
func (m *MockecsClient) ServiceRunningTasks(clusterName, serviceName string) ([]*ecs.Task, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ServiceRunningTasks", clusterName, serviceName)
ret0, _ := ret[0].([]*ecs.Task)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ServiceRunningTasks indicates an expected call of ServiceRunningTasks.
func (mr *MockecsClientMockRecorder) ServiceRunningTasks(clusterName, serviceName interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceRunningTasks", reflect.TypeOf((*MockecsClient)(nil).ServiceRunningTasks), clusterName, serviceName)
}
// StopTasks mocks base method.
func (m *MockecsClient) StopTasks(tasks []string, opts ...ecs.StopTasksOpts) error {
m.ctrl.T.Helper()
varargs := []interface{}{tasks}
for _, a := range opts {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "StopTasks", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// StopTasks indicates an expected call of StopTasks.
func (mr *MockecsClientMockRecorder) StopTasks(tasks interface{}, opts ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{tasks}, opts...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StopTasks", reflect.TypeOf((*MockecsClient)(nil).StopTasks), varargs...)
}
// StoppedServiceTasks mocks base method.
func (m *MockecsClient) StoppedServiceTasks(cluster, service string) ([]*ecs.Task, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "StoppedServiceTasks", cluster, service)
ret0, _ := ret[0].([]*ecs.Task)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// StoppedServiceTasks indicates an expected call of StoppedServiceTasks.
func (mr *MockecsClientMockRecorder) StoppedServiceTasks(cluster, service interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StoppedServiceTasks", reflect.TypeOf((*MockecsClient)(nil).StoppedServiceTasks), cluster, service)
}
// TaskDefinition mocks base method.
func (m *MockecsClient) TaskDefinition(taskDefName string) (*ecs.TaskDefinition, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "TaskDefinition", taskDefName)
ret0, _ := ret[0].(*ecs.TaskDefinition)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// TaskDefinition indicates an expected call of TaskDefinition.
func (mr *MockecsClientMockRecorder) TaskDefinition(taskDefName interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TaskDefinition", reflect.TypeOf((*MockecsClient)(nil).TaskDefinition), taskDefName)
}
// UpdateService mocks base method.
func (m *MockecsClient) UpdateService(clusterName, serviceName string, opts ...ecs.UpdateServiceOpts) error {
m.ctrl.T.Helper()
varargs := []interface{}{clusterName, serviceName}
for _, a := range opts {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "UpdateService", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// UpdateService indicates an expected call of UpdateService.
func (mr *MockecsClientMockRecorder) UpdateService(clusterName, serviceName interface{}, opts ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{clusterName, serviceName}, opts...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateService", reflect.TypeOf((*MockecsClient)(nil).UpdateService), varargs...)
}
// MockstepFunctionsClient is a mock of stepFunctionsClient interface.
type MockstepFunctionsClient struct {
ctrl *gomock.Controller
recorder *MockstepFunctionsClientMockRecorder
}
// MockstepFunctionsClientMockRecorder is the mock recorder for MockstepFunctionsClient.
type MockstepFunctionsClientMockRecorder struct {
mock *MockstepFunctionsClient
}
// NewMockstepFunctionsClient creates a new mock instance.
func NewMockstepFunctionsClient(ctrl *gomock.Controller) *MockstepFunctionsClient {
mock := &MockstepFunctionsClient{ctrl: ctrl}
mock.recorder = &MockstepFunctionsClientMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockstepFunctionsClient) EXPECT() *MockstepFunctionsClientMockRecorder {
return m.recorder
}
// StateMachineDefinition mocks base method.
func (m *MockstepFunctionsClient) StateMachineDefinition(stateMachineARN string) (string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "StateMachineDefinition", stateMachineARN)
ret0, _ := ret[0].(string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// StateMachineDefinition indicates an expected call of StateMachineDefinition.
func (mr *MockstepFunctionsClientMockRecorder) StateMachineDefinition(stateMachineARN interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StateMachineDefinition", reflect.TypeOf((*MockstepFunctionsClient)(nil).StateMachineDefinition), stateMachineARN)
}
| 286 |
copilot-cli | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: ./internal/pkg/ecs/run_task_request.go
// Package mocks is a generated GoMock package.
package mocks
import (
reflect "reflect"
ecs "github.com/aws/copilot-cli/internal/pkg/aws/ecs"
gomock "github.com/golang/mock/gomock"
)
// MockECSServiceDescriber is a mock of ECSServiceDescriber interface.
type MockECSServiceDescriber struct {
ctrl *gomock.Controller
recorder *MockECSServiceDescriberMockRecorder
}
// MockECSServiceDescriberMockRecorder is the mock recorder for MockECSServiceDescriber.
type MockECSServiceDescriberMockRecorder struct {
mock *MockECSServiceDescriber
}
// NewMockECSServiceDescriber creates a new mock instance.
func NewMockECSServiceDescriber(ctrl *gomock.Controller) *MockECSServiceDescriber {
mock := &MockECSServiceDescriber{ctrl: ctrl}
mock.recorder = &MockECSServiceDescriberMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockECSServiceDescriber) EXPECT() *MockECSServiceDescriberMockRecorder {
return m.recorder
}
// NetworkConfiguration mocks base method.
func (m *MockECSServiceDescriber) NetworkConfiguration(cluster, serviceName string) (*ecs.NetworkConfiguration, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "NetworkConfiguration", cluster, serviceName)
ret0, _ := ret[0].(*ecs.NetworkConfiguration)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// NetworkConfiguration indicates an expected call of NetworkConfiguration.
func (mr *MockECSServiceDescriberMockRecorder) NetworkConfiguration(cluster, serviceName interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NetworkConfiguration", reflect.TypeOf((*MockECSServiceDescriber)(nil).NetworkConfiguration), cluster, serviceName)
}
// Service mocks base method.
func (m *MockECSServiceDescriber) Service(clusterName, serviceName string) (*ecs.Service, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Service", clusterName, serviceName)
ret0, _ := ret[0].(*ecs.Service)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Service indicates an expected call of Service.
func (mr *MockECSServiceDescriberMockRecorder) Service(clusterName, serviceName interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Service", reflect.TypeOf((*MockECSServiceDescriber)(nil).Service), clusterName, serviceName)
}
// TaskDefinition mocks base method.
func (m *MockECSServiceDescriber) TaskDefinition(taskDefName string) (*ecs.TaskDefinition, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "TaskDefinition", taskDefName)
ret0, _ := ret[0].(*ecs.TaskDefinition)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// TaskDefinition indicates an expected call of TaskDefinition.
func (mr *MockECSServiceDescriberMockRecorder) TaskDefinition(taskDefName interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TaskDefinition", reflect.TypeOf((*MockECSServiceDescriber)(nil).TaskDefinition), taskDefName)
}
// MockServiceDescriber is a mock of ServiceDescriber interface.
type MockServiceDescriber struct {
ctrl *gomock.Controller
recorder *MockServiceDescriberMockRecorder
}
// MockServiceDescriberMockRecorder is the mock recorder for MockServiceDescriber.
type MockServiceDescriberMockRecorder struct {
mock *MockServiceDescriber
}
// NewMockServiceDescriber creates a new mock instance.
func NewMockServiceDescriber(ctrl *gomock.Controller) *MockServiceDescriber {
mock := &MockServiceDescriber{ctrl: ctrl}
mock.recorder = &MockServiceDescriberMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockServiceDescriber) EXPECT() *MockServiceDescriberMockRecorder {
return m.recorder
}
// ClusterARN mocks base method.
func (m *MockServiceDescriber) ClusterARN(app, env string) (string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ClusterARN", app, env)
ret0, _ := ret[0].(string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ClusterARN indicates an expected call of ClusterARN.
func (mr *MockServiceDescriberMockRecorder) ClusterARN(app, env interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ClusterARN", reflect.TypeOf((*MockServiceDescriber)(nil).ClusterARN), app, env)
}
// NetworkConfiguration mocks base method.
func (m *MockServiceDescriber) NetworkConfiguration(app, env, svc string) (*ecs.NetworkConfiguration, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "NetworkConfiguration", app, env, svc)
ret0, _ := ret[0].(*ecs.NetworkConfiguration)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// NetworkConfiguration indicates an expected call of NetworkConfiguration.
func (mr *MockServiceDescriberMockRecorder) NetworkConfiguration(app, env, svc interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NetworkConfiguration", reflect.TypeOf((*MockServiceDescriber)(nil).NetworkConfiguration), app, env, svc)
}
// TaskDefinition mocks base method.
func (m *MockServiceDescriber) TaskDefinition(app, env, svc string) (*ecs.TaskDefinition, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "TaskDefinition", app, env, svc)
ret0, _ := ret[0].(*ecs.TaskDefinition)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// TaskDefinition indicates an expected call of TaskDefinition.
func (mr *MockServiceDescriberMockRecorder) TaskDefinition(app, env, svc interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TaskDefinition", reflect.TypeOf((*MockServiceDescriber)(nil).TaskDefinition), app, env, svc)
}
// MockJobDescriber is a mock of JobDescriber interface.
type MockJobDescriber struct {
ctrl *gomock.Controller
recorder *MockJobDescriberMockRecorder
}
// MockJobDescriberMockRecorder is the mock recorder for MockJobDescriber.
type MockJobDescriberMockRecorder struct {
mock *MockJobDescriber
}
// NewMockJobDescriber creates a new mock instance.
func NewMockJobDescriber(ctrl *gomock.Controller) *MockJobDescriber {
mock := &MockJobDescriber{ctrl: ctrl}
mock.recorder = &MockJobDescriberMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockJobDescriber) EXPECT() *MockJobDescriberMockRecorder {
return m.recorder
}
// ClusterARN mocks base method.
func (m *MockJobDescriber) ClusterARN(app, env string) (string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ClusterARN", app, env)
ret0, _ := ret[0].(string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ClusterARN indicates an expected call of ClusterARN.
func (mr *MockJobDescriberMockRecorder) ClusterARN(app, env interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ClusterARN", reflect.TypeOf((*MockJobDescriber)(nil).ClusterARN), app, env)
}
// NetworkConfigurationForJob mocks base method.
func (m *MockJobDescriber) NetworkConfigurationForJob(app, env, job string) (*ecs.NetworkConfiguration, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "NetworkConfigurationForJob", app, env, job)
ret0, _ := ret[0].(*ecs.NetworkConfiguration)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// NetworkConfigurationForJob indicates an expected call of NetworkConfigurationForJob.
func (mr *MockJobDescriberMockRecorder) NetworkConfigurationForJob(app, env, job interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NetworkConfigurationForJob", reflect.TypeOf((*MockJobDescriber)(nil).NetworkConfigurationForJob), app, env, job)
}
// TaskDefinition mocks base method.
func (m *MockJobDescriber) TaskDefinition(app, env, job string) (*ecs.TaskDefinition, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "TaskDefinition", app, env, job)
ret0, _ := ret[0].(*ecs.TaskDefinition)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// TaskDefinition indicates an expected call of TaskDefinition.
func (mr *MockJobDescriberMockRecorder) TaskDefinition(app, env, job interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TaskDefinition", reflect.TypeOf((*MockJobDescriber)(nil).TaskDefinition), app, env, job)
}
| 217 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package exec
// ErrSSMPluginNotExist means the ssm plugin is not installed.
type ErrSSMPluginNotExist struct{}
func (e ErrSSMPluginNotExist) Error() string {
return "Session Manager plugin does not exist"
}
// ErrOutdatedSSMPlugin means the ssm plugin is not up-to-date.
type ErrOutdatedSSMPlugin struct {
CurrentVersion string
LatestVersion string
}
func (e ErrOutdatedSSMPlugin) Error() string {
return "Session Manager plugin is not up-to-date"
}
| 22 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package exec provides an interface to execute certain commands.
package exec
import (
"context"
"io"
"net/http"
"os"
"os/exec"
)
type httpClient interface {
Get(url string) (resp *http.Response, err error)
}
type runner interface {
Run(name string, args []string, options ...CmdOption) error
InteractiveRun(name string, args []string) error
}
type cmdRunner interface {
Run() error
}
// Cmd runs external commands, it wraps the exec.CommandContext function from the stdlib so that
// running external commands can be unit tested.
type Cmd struct {
command func(ctx context.Context, name string, args []string, opts ...CmdOption) cmdRunner
}
// CmdOption is a type alias to configure a command.
type CmdOption func(cmd *exec.Cmd)
// NewCmd returns a Cmd that can run external commands.
// By default the output of the commands is piped to stderr.
func NewCmd() *Cmd {
return &Cmd{
command: func(ctx context.Context, name string, args []string, opts ...CmdOption) cmdRunner {
cmd := exec.CommandContext(ctx, name, args...)
cmd.Stdout = os.Stderr
cmd.Stderr = os.Stderr
for _, opt := range opts {
opt(cmd)
}
return cmd
},
}
}
// Stdin sets the internal *exec.Cmd's Stdin field.
func Stdin(r io.Reader) CmdOption {
return func(c *exec.Cmd) {
c.Stdin = r
}
}
// Stdout sets the internal *exec.Cmd's Stdout field.
func Stdout(writer io.Writer) CmdOption {
return func(c *exec.Cmd) {
c.Stdout = writer
}
}
// Stderr sets the internal *exec.Cmd's Stderr field.
func Stderr(writer io.Writer) CmdOption {
return func(c *exec.Cmd) {
c.Stderr = writer
}
}
// Run starts the named command and waits until it finishes.
func (c *Cmd) Run(name string, args []string, opts ...CmdOption) error {
cmd := c.command(context.Background(), name, args, opts...)
return cmd.Run()
}
// RunWithContext starts the named command with the given context.
// Command execution process will be killed if the context becomes done before the command completes on its own.
func (c *Cmd) RunWithContext(ctx context.Context, name string, args []string, opts ...CmdOption) error {
cmd := c.command(ctx, name, args, opts...)
return cmd.Run()
}
| 86 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package exec
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/golang/mock/gomock"
)
func TestCmd_Run(t *testing.T) {
t.Run("should delegate to exec and call Run", func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
cmd := &Cmd{
command: func(ctx context.Context, name string, args []string, opts ...CmdOption) cmdRunner {
require.Equal(t, "ls", name)
m := NewMockcmdRunner(ctrl)
m.EXPECT().Run().Return(nil)
return m
},
}
// WHEN
err := cmd.Run("ls", nil)
// THEN
require.NoError(t, err)
})
}
func TestCmd_RunWithContext(t *testing.T) {
t.Run("should delegate to exec and call Run", func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
cmd := &Cmd{
command: func(ctx context.Context, name string, args []string, opts ...CmdOption) cmdRunner {
require.Equal(t, "ls", name)
m := NewMockcmdRunner(ctrl)
m.EXPECT().Run().Return(nil)
return m
},
}
// WHEN
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
err := cmd.RunWithContext(ctx, "ls", nil)
// THEN
require.NoError(t, err)
})
}
| 61 |
copilot-cli | aws | Go | //go:build !windows
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package exec
import (
"context"
"os"
"os/signal"
)
// InteractiveRun runs the input command that starts a child process.
func (c *Cmd) InteractiveRun(name string, args []string) error {
// Ignore interrupt signal otherwise the program exits.
signal.Ignore(os.Interrupt)
defer signal.Reset(os.Interrupt)
cmd := c.command(context.Background(), name, args, Stdout(os.Stdout), Stdin(os.Stdin), Stderr(os.Stderr))
return cmd.Run()
}
| 22 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package exec
import (
"context"
"os"
"os/exec"
"testing"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
func TestCmd_InteractiveRun(t *testing.T) {
t.Run("should enable default stdin, stdout, and stderr before running the command", func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
cmd := &Cmd{
command: func(ctx context.Context, name string, args []string, opts ...CmdOption) cmdRunner {
// Ensure that the options applied match what we expect.
cmd := &exec.Cmd{}
for _, opt := range opts {
opt(cmd)
}
require.Equal(t, os.Stdin, cmd.Stdin)
require.Equal(t, os.Stdout, cmd.Stdout)
require.Equal(t, os.Stderr, cmd.Stderr)
m := NewMockcmdRunner(ctrl)
m.EXPECT().Run().Return(nil)
return m
},
}
// WHEN
err := cmd.InteractiveRun("hello", nil)
// THEN
require.NoError(t, err)
})
}
| 45 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package exec
import (
"context"
"os"
"os/signal"
)
// InteractiveRun runs the input command that starts a child process.
func (c *Cmd) InteractiveRun(name string, args []string) error {
sig := make(chan os.Signal, 1)
// See https://golang.org/pkg/os/signal/#hdr-Windows
signal.Notify(sig, os.Interrupt)
defer signal.Reset(os.Interrupt)
cmd := c.command(context.Background(), name, args, Stdout(os.Stdout), Stdin(os.Stdin), Stderr(os.Stderr))
return cmd.Run()
}
| 21 |
copilot-cli | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: ./internal/pkg/exec/exec.go
// Package exec is a generated GoMock package.
package exec
import (
http "net/http"
reflect "reflect"
gomock "github.com/golang/mock/gomock"
)
// MockhttpClient is a mock of httpClient interface.
type MockhttpClient struct {
ctrl *gomock.Controller
recorder *MockhttpClientMockRecorder
}
// MockhttpClientMockRecorder is the mock recorder for MockhttpClient.
type MockhttpClientMockRecorder struct {
mock *MockhttpClient
}
// NewMockhttpClient creates a new mock instance.
func NewMockhttpClient(ctrl *gomock.Controller) *MockhttpClient {
mock := &MockhttpClient{ctrl: ctrl}
mock.recorder = &MockhttpClientMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockhttpClient) EXPECT() *MockhttpClientMockRecorder {
return m.recorder
}
// Get mocks base method.
func (m *MockhttpClient) Get(url string) (*http.Response, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Get", url)
ret0, _ := ret[0].(*http.Response)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Get indicates an expected call of Get.
func (mr *MockhttpClientMockRecorder) Get(url interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockhttpClient)(nil).Get), url)
}
// Mockrunner is a mock of runner interface.
type Mockrunner struct {
ctrl *gomock.Controller
recorder *MockrunnerMockRecorder
}
// MockrunnerMockRecorder is the mock recorder for Mockrunner.
type MockrunnerMockRecorder struct {
mock *Mockrunner
}
// NewMockrunner creates a new mock instance.
func NewMockrunner(ctrl *gomock.Controller) *Mockrunner {
mock := &Mockrunner{ctrl: ctrl}
mock.recorder = &MockrunnerMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *Mockrunner) EXPECT() *MockrunnerMockRecorder {
return m.recorder
}
// InteractiveRun mocks base method.
func (m *Mockrunner) InteractiveRun(name string, args []string) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "InteractiveRun", name, args)
ret0, _ := ret[0].(error)
return ret0
}
// InteractiveRun indicates an expected call of InteractiveRun.
func (mr *MockrunnerMockRecorder) InteractiveRun(name, args interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InteractiveRun", reflect.TypeOf((*Mockrunner)(nil).InteractiveRun), name, args)
}
// Run mocks base method.
func (m *Mockrunner) Run(name string, args []string, options ...CmdOption) error {
m.ctrl.T.Helper()
varargs := []interface{}{name, args}
for _, a := range options {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "Run", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// Run indicates an expected call of Run.
func (mr *MockrunnerMockRecorder) Run(name, args interface{}, options ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{name, args}, options...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Run", reflect.TypeOf((*Mockrunner)(nil).Run), varargs...)
}
// MockcmdRunner is a mock of cmdRunner interface.
type MockcmdRunner struct {
ctrl *gomock.Controller
recorder *MockcmdRunnerMockRecorder
}
// MockcmdRunnerMockRecorder is the mock recorder for MockcmdRunner.
type MockcmdRunnerMockRecorder struct {
mock *MockcmdRunner
}
// NewMockcmdRunner creates a new mock instance.
func NewMockcmdRunner(ctrl *gomock.Controller) *MockcmdRunner {
mock := &MockcmdRunner{ctrl: ctrl}
mock.recorder = &MockcmdRunnerMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockcmdRunner) EXPECT() *MockcmdRunnerMockRecorder {
return m.recorder
}
// Run mocks base method.
func (m *MockcmdRunner) Run() error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Run")
ret0, _ := ret[0].(error)
return ret0
}
// Run indicates an expected call of Run.
func (mr *MockcmdRunnerMockRecorder) Run() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Run", reflect.TypeOf((*MockcmdRunner)(nil).Run))
}
| 144 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package exec provides an interface to execute certain commands.
package exec
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ecs"
)
const (
ssmPluginBinaryName = "session-manager-plugin"
startSessionAction = "StartSession"
executableNotExistErrMessage = "executable file not found"
ssmPluginBinaryLatestVersionURL = "https://s3.amazonaws.com/session-manager-downloads/plugin/latest/VERSION"
)
// SSMPluginCommand represents commands that can be run to trigger the ssm plugin.
type SSMPluginCommand struct {
sess *session.Session
runner
http httpClient
// facilitate unit test.
latestVersionBuffer bytes.Buffer
currentVersionBuffer bytes.Buffer
linuxDistVersionBuffer bytes.Buffer
tempDir string
}
// NewSSMPluginCommand returns a SSMPluginCommand.
func NewSSMPluginCommand(s *session.Session) SSMPluginCommand {
return SSMPluginCommand{
runner: NewCmd(),
sess: s,
http: http.DefaultClient,
}
}
// StartSession starts a session using the ssm plugin.
func (s SSMPluginCommand) StartSession(ssmSess *ecs.Session) error {
response, err := json.Marshal(ssmSess)
if err != nil {
return fmt.Errorf("marshal session response: %w", err)
}
if err := s.runner.InteractiveRun(ssmPluginBinaryName,
[]string{string(response), aws.StringValue(s.sess.Config.Region), startSessionAction}); err != nil {
return fmt.Errorf("start session: %w", err)
}
return nil
}
func download(client httpClient, filepath string, url string) error {
resp, err := client.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
out, err := os.Create(filepath)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, resp.Body)
return err
}
| 76 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package exec provides an interface to execute certain commands.
package exec
import (
"fmt"
"os"
"path/filepath"
)
// InstallLatestBinary installs the latest ssm plugin.
func (s SSMPluginCommand) InstallLatestBinary() error {
if s.tempDir == "" {
dir, err := os.MkdirTemp("", "ssmplugin")
if err != nil {
return fmt.Errorf("create a temporary directory: %w", err)
}
defer os.RemoveAll(dir)
s.tempDir = dir
}
if err := download(s.http, filepath.Join(s.tempDir, "sessionmanager-bundle.zip"), ssmPluginBinaryURL); err != nil {
return fmt.Errorf("download ssm plugin: %w", err)
}
if err := s.runner.Run("unzip", []string{"-o", filepath.Join(s.tempDir, "sessionmanager-bundle.zip"),
"-d", s.tempDir}); err != nil {
return err
}
if err := s.runner.Run("sudo", []string{filepath.Join(s.tempDir, "sessionmanager-bundle", "install"), "-i",
"/usr/local/sessionmanagerplugin", "-b",
"/usr/local/bin/session-manager-plugin"}); err != nil {
return err
}
return nil
}
| 37 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package exec
const (
ssmPluginBinaryURL = "https://s3.amazonaws.com/session-manager-downloads/plugin/latest/mac/sessionmanager-bundle.zip"
)
| 9 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package exec
const (
ssmPluginBinaryURL = "https://s3.amazonaws.com/session-manager-downloads/plugin/latest/mac_arm64/sessionmanager-bundle.zip"
)
| 9 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package exec
import (
"errors"
"fmt"
"os"
"path/filepath"
"testing"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
func TestSSMPluginCommand_InstallLatestBinary_darwin(t *testing.T) {
var mockDir string
var mockRunner *Mockrunner
mockError := errors.New("some error")
tests := map[string]struct {
setupMocks func(controller *gomock.Controller)
wantedError error
}{
"return error if fail to unzip binary": {
setupMocks: func(controller *gomock.Controller) {
mockRunner = NewMockrunner(controller)
mockRunner.EXPECT().Run("unzip", []string{"-o", filepath.Join(mockDir, "sessionmanager-bundle.zip"),
"-d", mockDir}).
Return(mockError)
},
wantedError: fmt.Errorf("some error"),
},
"return error if fail to install binary": {
setupMocks: func(controller *gomock.Controller) {
mockRunner = NewMockrunner(controller)
mockRunner.EXPECT().Run("unzip", []string{"-o", filepath.Join(mockDir, "sessionmanager-bundle.zip"),
"-d", mockDir}).
Return(nil)
mockRunner.EXPECT().Run("sudo", []string{filepath.Join(mockDir, "sessionmanager-bundle", "install"), "-i",
"/usr/local/sessionmanagerplugin", "-b",
"/usr/local/bin/session-manager-plugin"}).
Return(mockError)
},
wantedError: fmt.Errorf("some error"),
},
"success": {
setupMocks: func(controller *gomock.Controller) {
mockRunner = NewMockrunner(controller)
mockRunner.EXPECT().Run("unzip", []string{"-o", filepath.Join(mockDir, "sessionmanager-bundle.zip"),
"-d", mockDir}).
Return(nil)
mockRunner.EXPECT().Run("sudo", []string{filepath.Join(mockDir, "sessionmanager-bundle", "install"), "-i",
"/usr/local/sessionmanagerplugin", "-b",
"/usr/local/bin/session-manager-plugin"}).
Return(nil)
},
},
}
for name, tc := range tests {
mockDir, _ = os.MkdirTemp("", "temp")
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
tc.setupMocks(ctrl)
s := SSMPluginCommand{
runner: mockRunner,
tempDir: mockDir,
http: &fakeHTTPClient{
content: []byte("hello"),
},
}
err := s.InstallLatestBinary()
if tc.wantedError != nil {
require.EqualError(t, tc.wantedError, err.Error())
} else {
require.NoError(t, err)
}
})
os.RemoveAll(mockDir)
}
}
| 82 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package exec provides an interface to execute certain commands.
package exec
import (
"fmt"
"os"
"path/filepath"
"strings"
)
// InstallLatestBinary installs the latest ssm plugin.
func (s SSMPluginCommand) InstallLatestBinary() error {
if s.tempDir == "" {
dir, err := os.MkdirTemp("", "ssmplugin")
if err != nil {
return fmt.Errorf("create a temporary directory: %w", err)
}
defer os.RemoveAll(dir)
s.tempDir = dir
}
isUbuntu, err := s.isUbuntu()
if err != nil {
return err
}
if isUbuntu {
return s.installUbuntuBinary()
}
return s.installLinuxBinary()
}
func (s SSMPluginCommand) isUbuntu() (bool, error) {
if err := s.runner.Run("uname", []string{"-a"}, Stdout(&s.linuxDistVersionBuffer)); err != nil {
return false, fmt.Errorf("get linux distribution version: %w", err)
}
return strings.Contains(s.linuxDistVersionBuffer.String(), "Ubuntu"), nil
}
func (s SSMPluginCommand) installLinuxBinary() error {
if err := download(s.http, filepath.Join(s.tempDir, "session-manager-plugin.rpm"), linuxSSMPluginBinaryURL); err != nil {
return fmt.Errorf("download ssm plugin: %w", err)
}
if err := s.runner.Run("sudo", []string{"yum", "install", "-y",
filepath.Join(s.tempDir, "session-manager-plugin.rpm")}); err != nil {
return err
}
return nil
}
func (s SSMPluginCommand) installUbuntuBinary() error {
if err := download(s.http, filepath.Join(s.tempDir, "session-manager-plugin.deb"), ubuntuSSMPluginBinaryURL); err != nil {
return fmt.Errorf("download ssm plugin: %w", err)
}
if err := s.runner.Run("sudo", []string{"dpkg", "-i",
filepath.Join(s.tempDir, "session-manager-plugin.deb")}); err != nil {
return err
}
return nil
}
| 62 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package exec
const (
linuxSSMPluginBinaryURL = "https://s3.amazonaws.com/session-manager-downloads/plugin/latest/linux_64bit/session-manager-plugin.rpm"
ubuntuSSMPluginBinaryURL = "https://s3.amazonaws.com/session-manager-downloads/plugin/latest/ubuntu_64bit/session-manager-plugin.deb"
)
| 10 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package exec
const (
linuxSSMPluginBinaryURL = "https://s3.amazonaws.com/session-manager-downloads/plugin/latest/linux_arm64/session-manager-plugin.rpm"
ubuntuSSMPluginBinaryURL = "https://s3.amazonaws.com/session-manager-downloads/plugin/latest/ubuntu_arm64/session-manager-plugin.deb"
)
| 10 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package exec
import (
"bytes"
"errors"
"fmt"
"os"
"path/filepath"
"testing"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
func TestSSMPluginCommand_InstallLatestBinary_linux(t *testing.T) {
var mockDir string
var mockRunner *Mockrunner
mockError := errors.New("some error")
tests := map[string]struct {
setupMocks func(controller *gomock.Controller)
linuxVersion string
wantedError error
}{
"return error if fail to check linux distribution": {
setupMocks: func(controller *gomock.Controller) {
mockRunner = NewMockrunner(controller)
mockRunner.EXPECT().Run("uname", []string{"-a"}, gomock.Any()).
Return(mockError)
},
wantedError: fmt.Errorf("get linux distribution version: some error"),
},
"return error if fail to install binary on linux": {
linuxVersion: "Linux ip-172-31-35-135.us-west-2.compute.internal 4.14.203-156.332.amzn2.x86_64 #1 SMP Fri Oct 30 19:19:33 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux",
setupMocks: func(controller *gomock.Controller) {
mockRunner = NewMockrunner(controller)
mockRunner.EXPECT().Run("uname", []string{"-a"}, gomock.Any()).Return(nil)
mockRunner.EXPECT().Run("sudo", []string{"yum", "install", "-y",
filepath.Join(mockDir, "session-manager-plugin.rpm")}).
Return(mockError)
},
wantedError: fmt.Errorf("some error"),
},
"return error if fail to install binary on ubuntu": {
linuxVersion: "Linux ip-172-31-0-242 5.4.0-1029-aws #30-Ubuntu SMP Tue Oct 20 10:06:38 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux",
setupMocks: func(controller *gomock.Controller) {
mockRunner = NewMockrunner(controller)
mockRunner.EXPECT().Run("uname", []string{"-a"}, gomock.Any()).Return(nil)
mockRunner.EXPECT().Run("sudo", []string{"dpkg", "-i",
filepath.Join(mockDir, "session-manager-plugin.deb")}).
Return(mockError)
},
wantedError: fmt.Errorf("some error"),
},
"success on linux": {
linuxVersion: "Linux ip-172-31-35-135.us-west-2.compute.internal 4.14.203-156.332.amzn2.x86_64 #1 SMP Fri Oct 30 19:19:33 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux",
setupMocks: func(controller *gomock.Controller) {
mockRunner = NewMockrunner(controller)
mockRunner.EXPECT().Run("uname", []string{"-a"}, gomock.Any()).Return(nil)
mockRunner.EXPECT().Run("sudo", []string{"yum", "install", "-y",
filepath.Join(mockDir, "session-manager-plugin.rpm")}).
Return(nil)
},
},
"success on ubuntu": {
linuxVersion: "Linux ip-172-31-0-242 5.4.0-1029-aws #30-Ubuntu SMP Tue Oct 20 10:06:38 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux",
setupMocks: func(controller *gomock.Controller) {
mockRunner = NewMockrunner(controller)
mockRunner.EXPECT().Run("uname", []string{"-a"}, gomock.Any()).Return(nil)
mockRunner.EXPECT().Run("sudo", []string{"dpkg", "-i",
filepath.Join(mockDir, "session-manager-plugin.deb")}).
Return(nil)
},
},
}
for name, tc := range tests {
mockDir, _ = os.MkdirTemp("", "temp")
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
tc.setupMocks(ctrl)
s := SSMPluginCommand{
runner: mockRunner,
tempDir: mockDir,
linuxDistVersionBuffer: *bytes.NewBufferString(tc.linuxVersion),
http: &fakeHTTPClient{
content: []byte("hello"),
},
}
err := s.InstallLatestBinary()
if tc.wantedError != nil {
require.EqualError(t, tc.wantedError, err.Error())
} else {
require.NoError(t, err)
}
})
os.RemoveAll(mockDir)
}
}
| 101 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package exec provides an interface to execute certain commands.
package exec
// InstallLatestBinary returns nil and ssm plugin needs to be installed manually.
func (s SSMPluginCommand) InstallLatestBinary() error {
return nil
}
| 11 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package exec
import (
"errors"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"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/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
type fakeHTTPClient struct {
content []byte
err error
}
func (c *fakeHTTPClient) Get(url string) (resp *http.Response, err error) {
if c.err != nil {
return nil, c.err
}
r := httptest.NewRecorder()
_, _ = r.Write(c.content)
return r.Result(), nil
}
func TestSSMPluginCommand_StartSession(t *testing.T) {
mockSession := &ecs.Session{
SessionId: aws.String("mockSessionID"),
StreamUrl: aws.String("mockStreamURL"),
TokenValue: aws.String("mockTokenValue"),
}
var mockRunner *Mockrunner
mockError := errors.New("some error")
tests := map[string]struct {
inSession *ecs.Session
setupMocks func(controller *gomock.Controller)
wantedError error
}{
"return error if fail to start session": {
inSession: mockSession,
setupMocks: func(controller *gomock.Controller) {
mockRunner = NewMockrunner(controller)
mockRunner.EXPECT().InteractiveRun(ssmPluginBinaryName,
[]string{`{"SessionId":"mockSessionID","StreamUrl":"mockStreamURL","TokenValue":"mockTokenValue"}`, "us-west-2", "StartSession"}).Return(mockError)
},
wantedError: fmt.Errorf("start session: some error"),
},
"success with no update and no install": {
inSession: mockSession,
setupMocks: func(controller *gomock.Controller) {
mockRunner = NewMockrunner(controller)
mockRunner.EXPECT().InteractiveRun(ssmPluginBinaryName,
[]string{`{"SessionId":"mockSessionID","StreamUrl":"mockStreamURL","TokenValue":"mockTokenValue"}`, "us-west-2", "StartSession"}).Return(nil)
},
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
tc.setupMocks(ctrl)
s := SSMPluginCommand{
runner: mockRunner,
sess: &session.Session{
Config: &aws.Config{
Region: aws.String("us-west-2"),
},
},
}
err := s.StartSession(tc.inSession)
if tc.wantedError != nil {
require.EqualError(t, tc.wantedError, err.Error())
} else {
require.NoError(t, err)
}
})
}
}
| 86 |
copilot-cli | aws | Go | //go:build !windows
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package exec provides an interface to execute certain commands.
package exec
import (
"fmt"
"strings"
)
// ValidateBinary validates if the ssm plugin exists and needs update.
func (s SSMPluginCommand) ValidateBinary() error {
var latestVersion, currentVersion string
if err := s.runner.Run("curl", []string{"-s", ssmPluginBinaryLatestVersionURL}, Stdout(&s.latestVersionBuffer)); err != nil {
return fmt.Errorf("get ssm plugin latest version: %w", err)
}
latestVersion = strings.TrimSpace(s.latestVersionBuffer.String())
if err := s.runner.Run(ssmPluginBinaryName, []string{"--version"}, Stdout(&s.currentVersionBuffer)); err != nil {
if !strings.Contains(err.Error(), executableNotExistErrMessage) {
return fmt.Errorf("get local ssm plugin version: %w", err)
}
return &ErrSSMPluginNotExist{}
}
currentVersion = strings.TrimSpace(s.currentVersionBuffer.String())
if currentVersion != latestVersion {
return &ErrOutdatedSSMPlugin{
CurrentVersion: currentVersion,
LatestVersion: latestVersion,
}
}
return nil
}
| 36 |
copilot-cli | aws | Go | //go:build !windows
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package exec
import (
"bytes"
"errors"
"fmt"
"testing"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
func TestSSMPluginCommand_ValidateBinary(t *testing.T) {
const (
mockLatestVersion = "1.2.30.0"
mockCurrentVersion = "1.2.7.0"
)
var mockRunner *Mockrunner
mockError := errors.New("some error")
tests := map[string]struct {
inLatestVersion string
inCurrentVersion string
setupMocks func(controller *gomock.Controller)
wantedError error
}{
"return error if fail to get the latest version": {
setupMocks: func(controller *gomock.Controller) {
mockRunner = NewMockrunner(controller)
mockRunner.EXPECT().Run("curl", []string{"-s", ssmPluginBinaryLatestVersionURL}, gomock.Any()).
Return(mockError)
},
wantedError: fmt.Errorf("get ssm plugin latest version: some error"),
},
"return error if fail to get the current version": {
inLatestVersion: mockLatestVersion,
setupMocks: func(controller *gomock.Controller) {
mockRunner = NewMockrunner(controller)
mockRunner.EXPECT().Run("curl", []string{"-s", ssmPluginBinaryLatestVersionURL}, gomock.Any()).
Return(nil)
mockRunner.EXPECT().Run(ssmPluginBinaryName, []string{"--version"}, gomock.Any()).
Return(mockError)
},
wantedError: fmt.Errorf("get local ssm plugin version: some error"),
},
"return ErrSSMPluginNotExist if plugin doesn't exist": {
inLatestVersion: mockLatestVersion,
setupMocks: func(controller *gomock.Controller) {
mockRunner = NewMockrunner(controller)
mockRunner.EXPECT().Run("curl", []string{"-s", ssmPluginBinaryLatestVersionURL}, gomock.Any()).
Return(nil)
mockRunner.EXPECT().Run(ssmPluginBinaryName, []string{"--version"}, gomock.Any()).
Return(errors.New("executable file not found in $PATH"))
},
wantedError: fmt.Errorf("Session Manager plugin does not exist"),
},
"return ErrOutdatedSSMPlugin if plugin needs update": {
inLatestVersion: mockLatestVersion,
inCurrentVersion: mockCurrentVersion,
setupMocks: func(controller *gomock.Controller) {
mockRunner = NewMockrunner(controller)
mockRunner.EXPECT().Run("curl", []string{"-s", ssmPluginBinaryLatestVersionURL}, gomock.Any()).
Return(nil)
mockRunner.EXPECT().Run(ssmPluginBinaryName, []string{"--version"}, gomock.Any()).
Return(nil)
},
wantedError: fmt.Errorf("Session Manager plugin is not up-to-date"),
},
"return nil if no update needed": {
inLatestVersion: mockLatestVersion,
inCurrentVersion: mockLatestVersion,
setupMocks: func(controller *gomock.Controller) {
mockRunner = NewMockrunner(controller)
mockRunner.EXPECT().Run("curl", []string{"-s", ssmPluginBinaryLatestVersionURL}, gomock.Any()).
Return(nil)
mockRunner.EXPECT().Run(ssmPluginBinaryName, []string{"--version"}, gomock.Any()).
Return(nil)
},
wantedError: nil,
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
tc.setupMocks(ctrl)
s := SSMPluginCommand{
runner: mockRunner,
currentVersionBuffer: *bytes.NewBufferString(tc.inCurrentVersion),
latestVersionBuffer: *bytes.NewBufferString(tc.inLatestVersion),
}
err := s.ValidateBinary()
if tc.wantedError != nil {
require.EqualError(t, tc.wantedError, err.Error())
} else {
require.NoError(t, err)
}
})
}
}
| 104 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package exec provides an interface to execute certain commands.
package exec
import (
"bytes"
)
// ValidateBinary validates if the ssm plugin exists.
func (s SSMPluginCommand) ValidateBinary() error {
// Hinder output on the screen.
var b bytes.Buffer
return s.runner.Run(ssmPluginBinaryName, []string{}, Stdout(&b))
}
| 17 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package graph
import (
"fmt"
"strings"
)
type errCycle[V comparable] struct {
vertices []V
}
func (e *errCycle[V]) Error() string {
ss := make([]string, len(e.vertices))
for i, v := range e.vertices {
ss[i] = fmt.Sprintf("%v", v)
}
return fmt.Sprintf("graph contains a cycle: %s", strings.Join(ss, ", "))
}
| 22 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package graph provides functionality for directed graphs.
package graph
// vertexStatus denotes the visiting status of a vertex when running DFS in a graph.
type vertexStatus int
const (
unvisited vertexStatus = iota + 1
visiting
visited
)
// Graph represents a directed graph.
type Graph[V comparable] struct {
vertices map[V]neighbors[V] // Adjacency list for each vertex.
inDegrees map[V]int // Number of incoming edges for each vertex.
}
// Edge represents one edge of a directed graph.
type Edge[V comparable] struct {
From V
To V
}
type neighbors[V comparable] map[V]bool
// New initiates a new Graph.
func New[V comparable](vertices ...V) *Graph[V] {
adj := make(map[V]neighbors[V])
inDegrees := make(map[V]int)
for _, vertex := range vertices {
adj[vertex] = make(neighbors[V])
inDegrees[vertex] = 0
}
return &Graph[V]{
vertices: adj,
inDegrees: inDegrees,
}
}
// Neighbors returns the list of connected vertices from vtx.
func (g *Graph[V]) Neighbors(vtx V) []V {
neighbors, ok := g.vertices[vtx]
if !ok {
return nil
}
arr := make([]V, len(neighbors))
i := 0
for neighbor := range neighbors {
arr[i] = neighbor
i += 1
}
return arr
}
// Add adds a connection between two vertices.
func (g *Graph[V]) Add(edge Edge[V]) {
from, to := edge.From, edge.To
if _, ok := g.vertices[from]; !ok {
g.vertices[from] = make(neighbors[V])
}
if _, ok := g.vertices[to]; !ok {
g.vertices[to] = make(neighbors[V])
}
if _, ok := g.inDegrees[from]; !ok {
g.inDegrees[from] = 0
}
if _, ok := g.inDegrees[to]; !ok {
g.inDegrees[to] = 0
}
g.vertices[from][to] = true
g.inDegrees[to] += 1
}
// InDegree returns the number of incoming edges to vtx.
func (g *Graph[V]) InDegree(vtx V) int {
return g.inDegrees[vtx]
}
// Remove deletes a connection between two vertices.
func (g *Graph[V]) Remove(edge Edge[V]) {
if _, ok := g.vertices[edge.From][edge.To]; !ok {
return
}
delete(g.vertices[edge.From], edge.To)
g.inDegrees[edge.To] -= 1
}
type findCycleTempVars[V comparable] struct {
status map[V]vertexStatus
parents map[V]V
cycleStart V
cycleEnd V
}
// IsAcyclic checks if the graph is acyclic. If not, return the first detected cycle.
func (g *Graph[V]) IsAcyclic() ([]V, bool) {
var cycle []V
status := make(map[V]vertexStatus)
for vertex := range g.vertices {
status[vertex] = unvisited
}
temp := findCycleTempVars[V]{
status: status,
parents: make(map[V]V),
}
// We will run a series of DFS in the graph. Initially all vertices are marked unvisited.
// From each unvisited vertex, start the DFS, mark it visiting while entering and mark it visited on exit.
// If DFS moves to a visiting vertex, then we have found a cycle. The cycle itself can be reconstructed using parent map.
// See https://cp-algorithms.com/graph/finding-cycle.html
for vertex := range g.vertices {
if status[vertex] == unvisited && g.hasCycles(&temp, vertex) {
for n := temp.cycleStart; n != temp.cycleEnd; n = temp.parents[n] {
cycle = append(cycle, n)
}
cycle = append(cycle, temp.cycleEnd)
return cycle, false
}
}
return nil, true
}
// Roots returns a slice of vertices with no incoming edges.
func (g *Graph[V]) Roots() []V {
var roots []V
for vtx, degree := range g.inDegrees {
if degree == 0 {
roots = append(roots, vtx)
}
}
return roots
}
func (g *Graph[V]) hasCycles(temp *findCycleTempVars[V], currVertex V) bool {
temp.status[currVertex] = visiting
for vertex := range g.vertices[currVertex] {
if temp.status[vertex] == unvisited {
temp.parents[vertex] = currVertex
if g.hasCycles(temp, vertex) {
return true
}
} else if temp.status[vertex] == visiting {
temp.cycleStart = currVertex
temp.cycleEnd = vertex
return true
}
}
temp.status[currVertex] = visited
return false
}
// TopologicalSorter ranks vertices using Kahn's algorithm: https://en.wikipedia.org/wiki/Topological_sorting#Kahn's_algorithm
// However, if two vertices can be scheduled in parallel then the same rank is returned.
type TopologicalSorter[V comparable] struct {
ranks map[V]int
}
// Rank returns the order of the vertex. The smallest order starts at 0.
// The second boolean return value is used to indicate whether the vertex exists in the graph.
func (alg *TopologicalSorter[V]) Rank(vtx V) (int, bool) {
r, ok := alg.ranks[vtx]
return r, ok
}
func (alg *TopologicalSorter[V]) traverse(g *Graph[V]) {
roots := g.Roots()
for _, root := range roots {
alg.ranks[root] = 0 // Explicitly set to 0 so that `_, ok := alg.ranks[vtx]` returns true instead of false.
}
for len(roots) > 0 {
var vtx V
vtx, roots = roots[0], roots[1:]
for _, neighbor := range g.Neighbors(vtx) {
if new, old := alg.ranks[vtx]+1, alg.ranks[neighbor]; new > old {
alg.ranks[neighbor] = new
}
g.Remove(Edge[V]{vtx, neighbor})
if g.InDegree(neighbor) == 0 {
roots = append(roots, neighbor)
}
}
}
}
// TopologicalOrder determines whether the directed graph is acyclic, and if so then
// finds a topological-order, or a linear order, of the vertices.
// Note that this function will modify the original graph.
//
// If there is an edge from vertex V to U, then V must happen before U and results in rank of V < rank of U.
// When there are ties (two vertices can be scheduled in parallel), the vertices are given the same rank.
// If the digraph contains a cycle, then an error is returned.
//
// An example graph and their ranks is shown below to illustrate:
// .
//├── a rank: 0
//│ ├── c rank: 1
//│ │ └── f rank: 2
//│ └── d rank: 1
//└── b rank: 0
// └── e rank: 1
func TopologicalOrder[V comparable](digraph *Graph[V]) (*TopologicalSorter[V], error) {
if vertices, isAcyclic := digraph.IsAcyclic(); !isAcyclic {
return nil, &errCycle[V]{
vertices,
}
}
topo := &TopologicalSorter[V]{
ranks: make(map[V]int),
}
topo.traverse(digraph)
return topo, nil
}
| 218 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package graph
import (
"strings"
"testing"
"github.com/stretchr/testify/require"
)
func TestGraph_Add(t *testing.T) {
t.Run("success", func(t *testing.T) {
// GIVEN
graph := New[string]()
// WHEN
// A <-> B
// -> C
graph.Add(Edge[string]{
From: "A",
To: "B",
})
graph.Add(Edge[string]{
From: "B",
To: "A",
})
graph.Add(Edge[string]{
From: "A",
To: "C",
})
// THEN
require.ElementsMatch(t, []string{"B", "C"}, graph.Neighbors("A"))
require.ElementsMatch(t, []string{"A"}, graph.Neighbors("B"))
})
}
func TestGraph_InDegree(t *testing.T) {
testCases := map[string]struct {
graph *Graph[rune]
wanted map[rune]int
}{
"should return 0 for nodes that don't exist in the graph": {
graph: New[rune](),
wanted: map[rune]int{
'a': 0,
},
},
"should return number of incoming edges for complex graph": {
graph: func() *Graph[rune] {
g := New[rune]()
g.Add(Edge[rune]{'a', 'b'})
g.Add(Edge[rune]{'b', 'a'})
g.Add(Edge[rune]{'a', 'c'})
g.Add(Edge[rune]{'b', 'c'})
g.Add(Edge[rune]{'d', 'e'})
return g
}(),
wanted: map[rune]int{
'a': 1,
'b': 1,
'c': 2,
'd': 0,
'e': 1,
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
for vtx, wanted := range tc.wanted {
require.Equal(t, wanted, tc.graph.InDegree(vtx), "indegree for vertex %v does not match", vtx)
}
})
}
}
func TestGraph_Remove(t *testing.T) {
testCases := map[string]struct {
graph *Graph[rune]
wantedNeighbors map[rune][]rune
wantedIndegrees map[rune]int
}{
"edge deletion should be idempotent": {
graph: func() *Graph[rune] {
g := New[rune]()
g.Add(Edge[rune]{'a', 'b'})
g.Add(Edge[rune]{'z', 'b'})
g.Remove(Edge[rune]{'a', 'b'})
g.Remove(Edge[rune]{'a', 'b'}) // Remove a second time.
return g
}(),
wantedNeighbors: map[rune][]rune{
'a': nil,
'b': nil,
'z': {'b'},
},
wantedIndegrees: map[rune]int{
'a': 0,
'z': 0,
'b': 1,
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
for vtx, wanted := range tc.wantedNeighbors {
require.ElementsMatch(t, wanted, tc.graph.Neighbors(vtx), "neighbors for vertex %v do not match", vtx)
}
for vtx, wanted := range tc.wantedIndegrees {
require.Equal(t, wanted, tc.graph.InDegree(vtx), "indegree for vertex %v does not match")
}
})
}
}
func TestGraph_IsAcyclic(t *testing.T) {
testCases := map[string]struct {
graph Graph[string]
isAcyclic bool
cycle []string
}{
"small non acyclic graph": {
graph: Graph[string]{
vertices: map[string]neighbors[string]{
"A": {"B": true, "C": true},
"B": {"A": true},
},
},
isAcyclic: false,
cycle: []string{"A", "B"},
},
"non acyclic": {
graph: Graph[string]{
vertices: map[string]neighbors[string]{
"K": {"F": true},
"A": {"B": true, "C": true},
"B": {"D": true, "E": true},
"E": {"G": true},
"F": {"G": true},
"G": {"A": true},
},
},
isAcyclic: false,
cycle: []string{"A", "G", "E", "B"},
},
"acyclic": {
graph: Graph[string]{
vertices: map[string]neighbors[string]{
"A": {"B": true, "C": true},
"B": {"D": true},
"E": {"G": true},
"F": {"G": true},
},
},
isAcyclic: true,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// WHEN
gotCycle, gotAcyclic := tc.graph.IsAcyclic()
// THEN
require.Equal(t, tc.isAcyclic, gotAcyclic)
require.ElementsMatch(t, tc.cycle, gotCycle)
})
}
}
func TestGraph_Roots(t *testing.T) {
testCases := map[string]struct {
graph *Graph[int]
wantedRoots []int
}{
"should return nil if the graph is empty": {
graph: New[int](),
},
"should return all the vertices if there are no edges in the graph": {
graph: New[int](1, 2, 3, 4, 5),
wantedRoots: []int{1, 2, 3, 4, 5},
},
"should return only vertices with no in degrees": {
graph: func() *Graph[int] {
g := New[int]()
g.Add(Edge[int]{
From: 1,
To: 3,
})
g.Add(Edge[int]{
From: 2,
To: 3,
})
g.Add(Edge[int]{
From: 3,
To: 4,
})
return g
}(),
wantedRoots: []int{1, 2},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
require.ElementsMatch(t, tc.wantedRoots, tc.graph.Roots())
})
}
}
func TestTopologicalOrder(t *testing.T) {
testCases := map[string]struct {
graph *Graph[string]
wantedRanks map[string]int
wantedErrPrefix string
}{
"should return an error when a cycle is detected": {
// frontend <-> backend
graph: func() *Graph[string] {
g := New("frontend", "backend")
g.Add(Edge[string]{
From: "frontend",
To: "backend",
})
g.Add(Edge[string]{
From: "backend",
To: "frontend",
})
return g
}(),
wantedErrPrefix: "graph contains a cycle: ", // the cycle can appear in any order as map traversals are not deterministic, so only check the prefix.
},
"should return the ranks for a graph that looks like a bus": {
// vpc -> lb -> api
graph: func() *Graph[string] {
g := New[string]()
g.Add(Edge[string]{
From: "vpc",
To: "lb",
})
g.Add(Edge[string]{
From: "lb",
To: "api",
})
return g
}(),
wantedRanks: map[string]int{
"api": 2,
"lb": 1,
"vpc": 0,
},
},
"should return the ranks for a graph that looks like a tree": {
graph: func() *Graph[string] {
// vpc -> rds -> backend
// -> s3 -> api
// -> frontend
g := New[string]()
g.Add(Edge[string]{
From: "vpc",
To: "rds",
})
g.Add(Edge[string]{
From: "vpc",
To: "s3",
})
g.Add(Edge[string]{
From: "rds",
To: "backend",
})
g.Add(Edge[string]{
From: "s3",
To: "api",
})
g.Add(Edge[string]{
From: "s3",
To: "frontend",
})
return g
}(),
wantedRanks: map[string]int{
"api": 2,
"frontend": 2,
"backend": 2,
"s3": 1,
"rds": 1,
"vpc": 0,
},
},
"should return the ranks for a graph with multiple root nodes": {
graph: func() *Graph[string] {
// warehouse -> orders -> frontend
// payments ->
g := New[string]()
g.Add(Edge[string]{
From: "payments",
To: "frontend",
})
g.Add(Edge[string]{
From: "warehouse",
To: "orders",
})
g.Add(Edge[string]{
From: "orders",
To: "frontend",
})
return g
}(),
wantedRanks: map[string]int{
"frontend": 2,
"orders": 1,
"warehouse": 0,
"payments": 0,
},
},
"should find the longest path to a node": {
graph: func() *Graph[string] {
// a -> b -> c -> d -> f
// a -> e -> f
g := New[string]()
for _, edge := range []Edge[string]{{"a", "b"}, {"b", "c"}, {"c", "d"}, {"d", "f"}, {"a", "e"}, {"e", "f"}} {
g.Add(edge)
}
return g
}(),
wantedRanks: map[string]int{
"a": 0,
"b": 1,
"e": 1,
"c": 2,
"d": 3,
"f": 4,
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
topo, err := TopologicalOrder(tc.graph)
if tc.wantedErrPrefix != "" {
require.Error(t, err)
require.True(t, strings.HasPrefix(err.Error(), tc.wantedErrPrefix))
} else {
require.NoError(t, err)
for vtx, wantedRank := range tc.wantedRanks {
rank, _ := topo.Rank(vtx)
require.Equal(t, wantedRank, rank, "expected rank for vertex %s does not match", vtx)
}
}
})
}
}
| 372 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package ini provides functionality to parse and read properties from INI files.
package ini
import (
"fmt"
"gopkg.in/ini.v1"
)
type sectionsParser interface {
Sections() []*ini.Section
}
// INI represents a parsed INI file in memory.
type INI struct {
cfg sectionsParser
}
// New returns an INI file given a path to the file.
// An error is returned if the file can't be parsed.
func New(path string) (*INI, error) {
cfg, err := ini.Load(path)
if err != nil {
return nil, fmt.Errorf("load ini file %s: %w", path, err)
}
return &INI{
cfg: cfg,
}, nil
}
// Sections returns the names of **non-empty** sections in the file.
//
// For example, the method returns ["paths", "servers"] if the file's content is:
// app_mode = development
// [paths]
// data = /home/git/grafana
// [server]
// protocol = http
// http_port = 9999
func (i *INI) Sections() []string {
var names []string
for _, section := range i.cfg.Sections() {
if len(section.Keys()) == 0 {
continue
}
names = append(names, section.Name())
}
return names
}
| 53 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package ini
import (
"testing"
"github.com/stretchr/testify/require"
"gopkg.in/ini.v1"
)
func TestINI_Sections(t *testing.T) {
// GIVEN
content := `[paths]
data = /home/git/grafana
[server]
protocol = http
`
cfg, _ := ini.Load([]byte(content))
ini := &INI{cfg: cfg}
// WHEN
actualNames := ini.Sections()
// THEN
require.Equal(t, []string{"paths", "server"}, actualNames)
}
| 31 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package initialize contains methods and structs needed to initialize jobs and services.
package initialize
import (
"encoding"
"fmt"
"os"
"path/filepath"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/copilot-cli/internal/pkg/config"
"github.com/aws/copilot-cli/internal/pkg/deploy/cloudformation"
"github.com/aws/copilot-cli/internal/pkg/manifest"
"github.com/aws/copilot-cli/internal/pkg/manifest/manifestinfo"
"github.com/aws/copilot-cli/internal/pkg/term/color"
"github.com/aws/copilot-cli/internal/pkg/term/log"
"github.com/aws/copilot-cli/internal/pkg/workspace"
)
const (
jobWlType = "job"
svcWlType = "service"
)
var fmtErrUnrecognizedWlType = "unrecognized workload type %s"
// Store represents the methods needed to add workloads to the SSM parameter store.
type Store interface {
GetApplication(appName string) (*config.Application, error)
CreateService(service *config.Workload) error
CreateJob(job *config.Workload) error
ListServices(appName string) ([]*config.Workload, error)
ListJobs(appName string) ([]*config.Workload, error)
}
// WorkloadAdder contains the methods needed to add jobs and services to an existing application.
type WorkloadAdder interface {
AddJobToApp(app *config.Application, jobName string, opts ...cloudformation.AddWorkloadToAppOpt) error
AddServiceToApp(app *config.Application, serviceName string, opts ...cloudformation.AddWorkloadToAppOpt) error
}
// Workspace contains the methods needed to manipulate a Copilot workspace.
type Workspace interface {
Rel(path string) (string, error)
WriteJobManifest(marshaler encoding.BinaryMarshaler, jobName string) (string, error)
WriteServiceManifest(marshaler encoding.BinaryMarshaler, serviceName string) (string, error)
}
// Prog contains the methods needed to render multi-stage operations.
type Prog interface {
Start(label string)
Stop(label string)
}
// WorkloadProps contains the information needed to represent a Workload (job or service).
type WorkloadProps struct {
App string
Type string
Name string
DockerfilePath string
Image string
Platform manifest.PlatformArgsOrString
Topics []manifest.TopicSubscription
Queue manifest.SQSQueue
PrivateOnlyEnvironments []string
}
// JobProps contains the information needed to represent a Job.
type JobProps struct {
WorkloadProps
Schedule string
HealthCheck manifest.ContainerHealthCheck
Timeout string
Retries int
}
// ServiceProps contains the information needed to represent a Service (port, HealthCheck, and workload common props).
type ServiceProps struct {
WorkloadProps
Port uint16
HealthCheck manifest.ContainerHealthCheck
Private bool
appDomain *string
FileUploads []manifest.FileUpload
}
// WorkloadInitializer holds the clients necessary to initialize either a
// service or job in an existing application.
type WorkloadInitializer struct {
Store Store
Deployer WorkloadAdder
Ws Workspace
Prog Prog
}
// Service writes the service manifest, creates an ECR repository, and adds the service to SSM.
func (w *WorkloadInitializer) Service(i *ServiceProps) (string, error) {
return w.initService(i)
}
// Job writes the job manifest, creates an ECR repository, and adds the job to SSM.
func (w *WorkloadInitializer) Job(i *JobProps) (string, error) {
return w.initJob(i)
}
func (w *WorkloadInitializer) addWlToApp(app *config.Application, props WorkloadProps, wlType string) error {
switch wlType {
case svcWlType:
if props.Type == manifestinfo.StaticSiteType {
return w.Deployer.AddServiceToApp(app, props.Name, cloudformation.AddWorkloadToAppOptWithoutECR)
}
return w.Deployer.AddServiceToApp(app, props.Name)
case jobWlType:
return w.Deployer.AddJobToApp(app, props.Name)
default:
return fmt.Errorf(fmtErrUnrecognizedWlType, wlType)
}
}
func (w *WorkloadInitializer) addWlToStore(wl *config.Workload, wlType string) error {
switch wlType {
case svcWlType:
return w.Store.CreateService(wl)
case jobWlType:
return w.Store.CreateJob(wl)
default:
return fmt.Errorf(fmtErrUnrecognizedWlType, wlType)
}
}
func (w *WorkloadInitializer) initJob(props *JobProps) (string, error) {
if props.DockerfilePath != "" {
path, err := w.Ws.Rel(props.DockerfilePath)
if err != nil {
return "", err
}
props.DockerfilePath = path
}
var manifestExists bool
mf, err := newJobManifest(props)
if err != nil {
return "", err
}
manifestPath, err := w.Ws.WriteJobManifest(mf, props.Name)
if err != nil {
e, ok := err.(*workspace.ErrFileExists)
if !ok {
return "", fmt.Errorf("write %s manifest: %w", jobWlType, err)
}
manifestExists = true
manifestPath = e.FileName
}
manifestMsgFmt := "Wrote the manifest for %s %s at %s\n"
if manifestExists {
manifestMsgFmt = "Manifest file for %s %s already exists at %s, skipping writing it.\n"
}
path := displayPath(manifestPath)
log.Successf(manifestMsgFmt, jobWlType, color.HighlightUserInput(props.Name), color.HighlightResource(path))
var sched = props.Schedule
if props.Schedule == "" {
sched = "None"
}
helpText := fmt.Sprintf("Your manifest contains configurations like your container size and job schedule (%s).", sched)
log.Infoln(color.Help(helpText))
log.Infoln()
app, err := w.Store.GetApplication(props.App)
if err != nil {
return "", fmt.Errorf("get application %s: %w", props.App, err)
}
err = w.addJobToAppAndSSM(app, props.WorkloadProps)
if err != nil {
return "", err
}
path, err = w.Ws.Rel(manifestPath)
if err != nil {
return "", err
}
return path, nil
}
func (w *WorkloadInitializer) initService(props *ServiceProps) (string, error) {
if props.DockerfilePath != "" {
path, err := w.Ws.Rel(props.DockerfilePath)
if err != nil {
return "", err
}
props.DockerfilePath = path
}
app, err := w.Store.GetApplication(props.App)
if err != nil {
return "", fmt.Errorf("get application %s: %w", props.App, err)
}
if app.Domain != "" {
props.appDomain = aws.String(app.Domain)
}
var manifestExists bool
mf, err := w.newServiceManifest(props)
if err != nil {
return "", err
}
manifestPath, err := w.Ws.WriteServiceManifest(mf, props.Name)
if err != nil {
e, ok := err.(*workspace.ErrFileExists)
if !ok {
return "", fmt.Errorf("write %s manifest: %w", svcWlType, err)
}
manifestExists = true
manifestPath = e.FileName
}
manifestMsgFmt := "Wrote the manifest for %s %s at %s\n"
if manifestExists {
manifestMsgFmt = "Manifest file for %s %s already exists at %s, skipping writing it.\n"
}
path := displayPath(manifestPath)
log.Successf(manifestMsgFmt, svcWlType, color.HighlightUserInput(props.Name), color.HighlightResource(path))
helpText := "Your manifest contains configurations like your container size and port."
log.Infoln(color.Help(helpText))
log.Infoln()
err = w.addSvcToAppAndSSM(app, props.WorkloadProps)
if err != nil {
return "", err
}
path, err = w.Ws.Rel(manifestPath)
if err != nil {
return "", err
}
return path, nil
}
func (w *WorkloadInitializer) addSvcToAppAndSSM(app *config.Application, props WorkloadProps) error {
return w.addWlToAppAndSSM(app, props, svcWlType)
}
func (w *WorkloadInitializer) addJobToAppAndSSM(app *config.Application, props WorkloadProps) error {
return w.addWlToAppAndSSM(app, props, jobWlType)
}
func (w *WorkloadInitializer) addWlToAppAndSSM(app *config.Application, props WorkloadProps, wlType string) error {
if err := w.addWlToApp(app, props, wlType); err != nil {
return fmt.Errorf("add %s %s to application %s: %w", wlType, props.Name, props.App, err)
}
if err := w.addWlToStore(&config.Workload{
App: props.App,
Name: props.Name,
Type: props.Type,
}, wlType); err != nil {
return fmt.Errorf("saving %s %s: %w", wlType, props.Name, err)
}
return nil
}
func newJobManifest(i *JobProps) (encoding.BinaryMarshaler, error) {
switch i.Type {
case manifestinfo.ScheduledJobType:
return manifest.NewScheduledJob(&manifest.ScheduledJobProps{
WorkloadProps: &manifest.WorkloadProps{
Name: i.Name,
Dockerfile: i.DockerfilePath,
Image: i.Image,
PrivateOnlyEnvironments: i.PrivateOnlyEnvironments,
},
HealthCheck: i.HealthCheck,
Platform: i.Platform,
Schedule: i.Schedule,
Timeout: i.Timeout,
Retries: i.Retries,
}), nil
default:
return nil, fmt.Errorf("job type %s doesn't have a manifest", i.Type)
}
}
func (w *WorkloadInitializer) newServiceManifest(i *ServiceProps) (encoding.BinaryMarshaler, error) {
switch i.Type {
case manifestinfo.LoadBalancedWebServiceType:
return w.newLoadBalancedWebServiceManifest(i)
case manifestinfo.RequestDrivenWebServiceType:
return newRequestDrivenWebServiceManifest(i), nil
case manifestinfo.BackendServiceType:
return w.newBackendServiceManifest(i)
case manifestinfo.WorkerServiceType:
return newWorkerServiceManifest(i)
case manifestinfo.StaticSiteType:
return newStaticSiteServiceManifest(i)
default:
return nil, fmt.Errorf("service type %s doesn't have a manifest", i.Type)
}
}
func (w *WorkloadInitializer) newLoadBalancedWebServiceManifest(inProps *ServiceProps) (*manifest.LoadBalancedWebService, error) {
outProps := &manifest.LoadBalancedWebServiceProps{
WorkloadProps: &manifest.WorkloadProps{
Name: inProps.Name,
Dockerfile: inProps.DockerfilePath,
Image: inProps.Image,
PrivateOnlyEnvironments: inProps.PrivateOnlyEnvironments,
},
Path: "/",
Port: inProps.Port,
HealthCheck: inProps.HealthCheck,
Platform: inProps.Platform,
}
existingSvcs, err := w.Store.ListServices(inProps.App)
if err != nil {
return nil, err
}
// We default to "/" for the first service or if the application is initialized with a domain, but if there's another
// Load Balanced Web Service, we use the svc name as the default, instead.
if aws.StringValue(inProps.appDomain) == "" {
for _, existingSvc := range existingSvcs {
if existingSvc.Type == manifestinfo.LoadBalancedWebServiceType && existingSvc.Name != inProps.Name {
outProps.Path = inProps.Name
break
}
}
}
return manifest.NewLoadBalancedWebService(outProps), nil
}
func newRequestDrivenWebServiceManifest(i *ServiceProps) *manifest.RequestDrivenWebService {
props := &manifest.RequestDrivenWebServiceProps{
WorkloadProps: &manifest.WorkloadProps{
Name: i.Name,
Dockerfile: i.DockerfilePath,
Image: i.Image,
},
Port: i.Port,
Platform: i.Platform,
Private: i.Private,
}
return manifest.NewRequestDrivenWebService(props)
}
func (w *WorkloadInitializer) newBackendServiceManifest(i *ServiceProps) (*manifest.BackendService, error) {
outProps := manifest.BackendServiceProps{
WorkloadProps: manifest.WorkloadProps{
Name: i.Name,
Dockerfile: i.DockerfilePath,
Image: i.Image,
PrivateOnlyEnvironments: i.PrivateOnlyEnvironments,
},
Port: i.Port,
HealthCheck: i.HealthCheck,
Platform: i.Platform,
}
return manifest.NewBackendService(outProps), nil
}
func newWorkerServiceManifest(i *ServiceProps) (*manifest.WorkerService, error) {
return manifest.NewWorkerService(manifest.WorkerServiceProps{
WorkloadProps: manifest.WorkloadProps{
Name: i.Name,
Dockerfile: i.DockerfilePath,
Image: i.Image,
PrivateOnlyEnvironments: i.PrivateOnlyEnvironments,
},
HealthCheck: i.HealthCheck,
Platform: i.Platform,
Topics: i.Topics,
Queue: i.Queue,
}), nil
}
func newStaticSiteServiceManifest(i *ServiceProps) (*manifest.StaticSite, error) {
return manifest.NewStaticSite(manifest.StaticSiteProps{
Name: i.Name,
StaticSiteConfig: manifest.StaticSiteConfig{
FileUploads: i.FileUploads,
},
}), nil
}
// Copy of cli.displayPath
func displayPath(target string) string {
if !filepath.IsAbs(target) {
return filepath.Clean(target)
}
base, err := os.Getwd()
if err != nil {
return filepath.Clean(target)
}
rel, err := filepath.Rel(base, target)
if err != nil {
// No path from base to target available, return target as is.
return filepath.Clean(target)
}
return rel
}
| 409 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package initialize
import (
"errors"
"fmt"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/copilot-cli/internal/pkg/config"
"github.com/aws/copilot-cli/internal/pkg/initialize/mocks"
"github.com/aws/copilot-cli/internal/pkg/manifest"
"github.com/aws/copilot-cli/internal/pkg/manifest/manifestinfo"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
func TestWorkloadInitializer_Job(t *testing.T) {
testCases := map[string]struct {
inJobType string
inJobName string
inDockerfilePath string
inImage string
inAppName string
inPlatform manifest.PlatformArgsOrString
inSchedule string
inRetries int
inTimeout string
mockWriter func(m *mocks.MockWorkspace)
mockstore func(m *mocks.MockStore)
mockappDeployer func(m *mocks.MockWorkloadAdder)
wantedErr error
}{
"writes Scheduled Job manifest, and creates repositories successfully": {
inJobType: manifestinfo.ScheduledJobType,
inAppName: "app",
inJobName: "resizer",
inDockerfilePath: "resizer/Dockerfile",
inSchedule: "@hourly",
mockWriter: func(m *mocks.MockWorkspace) {
// workspace root: "/resizer/copilot"
gomock.InOrder(
m.EXPECT().Rel("resizer/Dockerfile").Return("../Dockerfile", nil),
m.EXPECT().Rel("/resizer/copilot/manifest.yml").Return("manifest.yml", nil))
m.EXPECT().WriteJobManifest(gomock.Any(), "resizer").Return("/resizer/copilot/manifest.yml", nil)
},
mockstore: func(m *mocks.MockStore) {
m.EXPECT().CreateJob(gomock.Any()).
Do(func(app *config.Workload) {
require.Equal(t, &config.Workload{
Name: "resizer",
App: "app",
Type: manifestinfo.ScheduledJobType,
}, app)
}).
Return(nil)
m.EXPECT().GetApplication("app").Return(&config.Application{
Name: "app",
AccountID: "1234",
}, nil)
},
mockappDeployer: func(m *mocks.MockWorkloadAdder) {
m.EXPECT().AddJobToApp(&config.Application{
Name: "app",
AccountID: "1234",
}, "resizer")
},
},
"using existing image": {
inJobType: manifestinfo.ScheduledJobType,
inAppName: "app",
inJobName: "resizer",
inImage: "mockImage",
inSchedule: "@hourly",
mockWriter: func(m *mocks.MockWorkspace) {
m.EXPECT().Rel("/resizer/manifest.yml").Return("manifest.yml", nil)
m.EXPECT().WriteJobManifest(gomock.Any(), "resizer").Do(func(m *manifest.ScheduledJob, _ string) {
require.Equal(t, *m.Workload.Type, manifestinfo.ScheduledJobType)
require.Equal(t, *m.ImageConfig.Image.Location, "mockImage")
}).Return("/resizer/manifest.yml", nil)
},
mockstore: func(m *mocks.MockStore) {
m.EXPECT().CreateJob(gomock.Any()).
Do(func(app *config.Workload) {
require.Equal(t, &config.Workload{
Name: "resizer",
App: "app",
Type: manifestinfo.ScheduledJobType,
}, app)
}).
Return(nil)
m.EXPECT().GetApplication("app").Return(&config.Application{
Name: "app",
AccountID: "1234",
}, nil)
},
mockappDeployer: func(m *mocks.MockWorkloadAdder) {
m.EXPECT().AddJobToApp(&config.Application{
Name: "app",
AccountID: "1234",
}, "resizer")
},
},
"write manifest error": {
inJobType: manifestinfo.ScheduledJobType,
inAppName: "app",
inJobName: "resizer",
inDockerfilePath: "resizer/Dockerfile",
inSchedule: "@hourly",
mockWriter: func(m *mocks.MockWorkspace) {
m.EXPECT().Rel("resizer/Dockerfile").Return("Dockerfile", nil)
m.EXPECT().WriteJobManifest(gomock.Any(), "resizer").Return("/resizer/manifest.yml", errors.New("some error"))
},
mockstore: func(m *mocks.MockStore) {},
wantedErr: errors.New("write job manifest: some error"),
},
"app error": {
inJobType: manifestinfo.ScheduledJobType,
inAppName: "app",
inJobName: "resizer",
inDockerfilePath: "resizer/Dockerfile",
inSchedule: "@hourly",
mockWriter: func(m *mocks.MockWorkspace) {
// workspace root: "/copilot"
m.EXPECT().Rel("resizer/Dockerfile").Return("resizer/Dockerfile", nil)
m.EXPECT().WriteJobManifest(gomock.Any(), "resizer").Return("/copilot/resizer/manifest.yml", nil)
},
mockstore: func(m *mocks.MockStore) {
m.EXPECT().GetApplication(gomock.Any()).Return(nil, errors.New("some error"))
},
wantedErr: errors.New("get application app: some error"),
},
"add job to app fails": {
inJobType: manifestinfo.ScheduledJobType,
inAppName: "app",
inJobName: "resizer",
inDockerfilePath: "frontend/Dockerfile",
inSchedule: "@hourly",
mockWriter: func(m *mocks.MockWorkspace) {
m.EXPECT().Rel("frontend/Dockerfile").Return("frontend/Dockerfile", nil)
m.EXPECT().WriteJobManifest(gomock.Any(), "resizer").Return("/resizer/manifest.yml", nil)
},
mockstore: func(m *mocks.MockStore) {
m.EXPECT().GetApplication(gomock.Any()).Return(&config.Application{
Name: "app",
AccountID: "1234",
}, nil)
},
mockappDeployer: func(m *mocks.MockWorkloadAdder) {
m.EXPECT().AddJobToApp(gomock.Any(), gomock.Any(), gomock.Any()).Return(errors.New("some error"))
},
wantedErr: errors.New("add job resizer to application app: some error"),
},
"error saving app": {
inJobType: manifestinfo.ScheduledJobType,
inAppName: "app",
inJobName: "resizer",
inDockerfilePath: "resizer/Dockerfile",
inSchedule: "@hourly",
mockWriter: func(m *mocks.MockWorkspace) {
m.EXPECT().Rel("resizer/Dockerfile").Return("Dockerfile", nil)
m.EXPECT().WriteJobManifest(gomock.Any(), "resizer").Return("/resizer/manifest.yml", nil)
},
mockstore: func(m *mocks.MockStore) {
m.EXPECT().CreateJob(gomock.Any()).
Return(fmt.Errorf("oops"))
m.EXPECT().GetApplication(gomock.Any()).Return(&config.Application{}, nil)
},
mockappDeployer: func(m *mocks.MockWorkloadAdder) {
m.EXPECT().AddJobToApp(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil)
},
wantedErr: fmt.Errorf("saving job resizer: oops"),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockWriter := mocks.NewMockWorkspace(ctrl)
mockstore := mocks.NewMockStore(ctrl)
mockappDeployer := mocks.NewMockWorkloadAdder(ctrl)
if tc.mockWriter != nil {
tc.mockWriter(mockWriter)
}
if tc.mockstore != nil {
tc.mockstore(mockstore)
}
if tc.mockappDeployer != nil {
tc.mockappDeployer(mockappDeployer)
}
initializer := &WorkloadInitializer{
Store: mockstore,
Ws: mockWriter,
Deployer: mockappDeployer,
}
initJobProps := &JobProps{
WorkloadProps: WorkloadProps{
App: tc.inAppName,
Name: tc.inJobName,
DockerfilePath: tc.inDockerfilePath,
Image: tc.inImage,
Type: tc.inJobType,
Platform: tc.inPlatform,
},
Schedule: tc.inSchedule,
Retries: tc.inRetries,
Timeout: tc.inTimeout,
}
// WHEN
_, err := initializer.Job(initJobProps)
// THEN
if tc.wantedErr != nil {
require.EqualError(t, err, tc.wantedErr.Error())
} else {
require.NoError(t, err)
}
})
}
}
func TestAppInitOpts_createLoadBalancedAppManifest(t *testing.T) {
testCases := map[string]struct {
inSvcPort uint16
inSvcName string
inDockerfilePath string
inAppName string
inAppDomain string
mockstore func(m *mocks.MockStore)
wantedErr error
wantedPath string
}{
"creates manifest with / as the path when there are no other apps": {
inAppName: "app",
inSvcName: "frontend",
inSvcPort: 80,
inDockerfilePath: "/Dockerfile",
mockstore: func(m *mocks.MockStore) {
m.EXPECT().ListServices("app").Return([]*config.Workload{}, nil)
},
wantedPath: "/",
},
"creates manifest with / as the path when it's the only app": {
inAppName: "app",
inSvcName: "frontend",
inSvcPort: 80,
inDockerfilePath: "/Dockerfile",
mockstore: func(m *mocks.MockStore) {
m.EXPECT().ListServices("app").Return([]*config.Workload{
{
Name: "frontend",
Type: manifestinfo.LoadBalancedWebServiceType,
},
}, nil)
},
wantedPath: "/",
},
"creates manifest with / as the path when it's the only LBWebService": {
inAppName: "app",
inSvcName: "frontend",
inSvcPort: 80,
inDockerfilePath: "/Dockerfile",
mockstore: func(m *mocks.MockStore) {
m.EXPECT().ListServices("app").Return([]*config.Workload{
{
Name: "another-app",
Type: "backend",
},
}, nil)
},
wantedPath: "/",
},
"creates manifest with {service name} as the path if there's another LBWebService": {
inAppName: "app",
inSvcName: "frontend",
inSvcPort: 80,
inDockerfilePath: "/Dockerfile",
mockstore: func(m *mocks.MockStore) {
m.EXPECT().ListServices("app").Return([]*config.Workload{
{
Name: "admin",
Type: manifestinfo.LoadBalancedWebServiceType,
},
}, nil)
},
wantedPath: "frontend",
},
"creates manifest with root path if the application is initialized with a domain": {
inAppName: "app",
inSvcName: "frontend",
inSvcPort: 80,
inDockerfilePath: "/Dockerfile",
inAppDomain: "example.com",
mockstore: func(m *mocks.MockStore) {
m.EXPECT().ListServices("app").Return([]*config.Workload{
{
Name: "admin",
Type: manifestinfo.LoadBalancedWebServiceType,
},
}, nil)
},
wantedPath: "/",
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockstore := mocks.NewMockStore(ctrl)
if tc.mockstore != nil {
tc.mockstore(mockstore)
}
props := ServiceProps{
WorkloadProps: WorkloadProps{
Name: tc.inSvcName,
App: tc.inAppName,
DockerfilePath: tc.inDockerfilePath,
},
Port: tc.inSvcPort,
appDomain: &tc.inAppDomain,
}
initter := &WorkloadInitializer{
Store: mockstore,
}
// WHEN
manifest, err := initter.newLoadBalancedWebServiceManifest(&props)
// THEN
if tc.wantedErr == nil {
require.NoError(t, err)
require.Equal(t, tc.inSvcName, aws.StringValue(manifest.Workload.Name))
require.Equal(t, tc.inSvcPort, aws.Uint16Value(manifest.ImageConfig.Port))
require.Contains(t, tc.inDockerfilePath, aws.StringValue(manifest.ImageConfig.Image.Build.BuildArgs.Dockerfile))
require.Equal(t, tc.wantedPath, aws.StringValue(manifest.HTTPOrBool.Main.Path))
} else {
require.EqualError(t, err, tc.wantedErr.Error())
}
})
}
}
func TestAppInitOpts_createRequestDrivenWebServiceManifest(t *testing.T) {
testCases := map[string]struct {
inSvcPort uint16
inSvcName string
inDockerfilePath string
inImage string
inAppName string
wantedErr error
}{
"creates manifest with dockerfile path": {
inAppName: "app",
inSvcName: "frontend",
inSvcPort: 80,
inDockerfilePath: "/Dockerfile",
},
"creates manifest with container image": {
inAppName: "app",
inSvcName: "frontend",
inSvcPort: 80,
inImage: "111111111111.dkr.ecr.us-east-1.amazonaws.com/app/frontend",
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
props := ServiceProps{
WorkloadProps: WorkloadProps{
Name: tc.inSvcName,
App: tc.inAppName,
DockerfilePath: tc.inDockerfilePath,
Image: tc.inImage,
},
Port: tc.inSvcPort,
}
// WHEN
manifest := newRequestDrivenWebServiceManifest(&props)
// THEN
require.Equal(t, tc.inSvcName, *manifest.Name)
require.Equal(t, tc.inSvcPort, *manifest.ImageConfig.Port)
if tc.inImage != "" {
require.Equal(t, tc.inImage, *manifest.ImageConfig.Image.Location)
}
if tc.inDockerfilePath != "" {
require.Equal(t, tc.inDockerfilePath, *manifest.ImageConfig.Image.Build.BuildArgs.Dockerfile)
}
})
}
}
func TestWorkloadInitializer_Service(t *testing.T) {
var (
testInterval = 10 * time.Second
testRetries = 2
testTimeout = 5 * time.Second
testStartPeriod = 0 * time.Second
)
testCases := map[string]struct {
inSvcPort uint16
inSvcType string
inSvcName string
inDockerfilePath string
inAppName string
inImage string
inHealthCheck manifest.ContainerHealthCheck
inTopics []manifest.TopicSubscription
mockWriter func(m *mocks.MockWorkspace)
mockstore func(m *mocks.MockStore)
mockappDeployer func(m *mocks.MockWorkloadAdder)
wantedErr error
}{
"writes Load Balanced Web Service manifest, and creates repositories successfully": {
inSvcType: manifestinfo.LoadBalancedWebServiceType,
inAppName: "app",
inSvcName: "frontend",
inDockerfilePath: "frontend/Dockerfile",
inSvcPort: 80,
mockWriter: func(m *mocks.MockWorkspace) {
// workspace root: "/frontend"
gomock.InOrder(
m.EXPECT().Rel("frontend/Dockerfile").Return("Dockerfile", nil),
m.EXPECT().Rel("/frontend/manifest.yml").Return("manifest.yml", nil))
m.EXPECT().WriteServiceManifest(gomock.Any(), "frontend").Return("/frontend/manifest.yml", nil)
},
mockstore: func(m *mocks.MockStore) {
m.EXPECT().ListServices("app").Return([]*config.Workload{}, nil)
m.EXPECT().CreateService(gomock.Any()).
Do(func(app *config.Workload) {
require.Equal(t, &config.Workload{
Name: "frontend",
App: "app",
Type: manifestinfo.LoadBalancedWebServiceType,
}, app)
}).
Return(nil)
m.EXPECT().GetApplication("app").Return(&config.Application{
Name: "app",
AccountID: "1234",
}, nil)
},
mockappDeployer: func(m *mocks.MockWorkloadAdder) {
m.EXPECT().AddServiceToApp(&config.Application{
Name: "app",
AccountID: "1234",
}, "frontend")
},
},
"writes Static Site manifest": {
inSvcType: manifestinfo.StaticSiteType,
inAppName: "app",
inSvcName: "static",
mockWriter: func(m *mocks.MockWorkspace) {
// workspace root: "/static"
gomock.InOrder(
m.EXPECT().Rel("/static/manifest.yml").Return("manifest.yml", nil))
m.EXPECT().WriteServiceManifest(gomock.Any(), "static").Return("/static/manifest.yml", nil)
},
mockstore: func(m *mocks.MockStore) {
m.EXPECT().CreateService(gomock.Any()).
Do(func(app *config.Workload) {
require.Equal(t, &config.Workload{
Name: "static",
App: "app",
Type: manifestinfo.StaticSiteType,
}, app)
}).
Return(nil)
m.EXPECT().GetApplication("app").Return(&config.Application{
Name: "app",
AccountID: "1234",
}, nil)
},
mockappDeployer: func(m *mocks.MockWorkloadAdder) {
m.EXPECT().AddServiceToApp(&config.Application{
Name: "app",
AccountID: "1234",
}, "static", gomock.Any())
},
},
"app error": {
inSvcType: manifestinfo.LoadBalancedWebServiceType,
inAppName: "app",
inSvcName: "frontend",
inSvcPort: 80,
inDockerfilePath: "frontend/Dockerfile",
mockWriter: func(m *mocks.MockWorkspace) {
// workspace root: "/frontend"
m.EXPECT().Rel("frontend/Dockerfile").Return("Dockerfile", nil)
},
mockstore: func(m *mocks.MockStore) {
m.EXPECT().GetApplication("app").Return(nil, errors.New("some error"))
},
wantedErr: errors.New("get application app: some error"),
},
"write manifest error": {
inSvcType: manifestinfo.LoadBalancedWebServiceType,
inAppName: "app",
inSvcName: "frontend",
inDockerfilePath: "frontend/Dockerfile",
inSvcPort: 80,
mockWriter: func(m *mocks.MockWorkspace) {
// workspace root: "/frontend"
m.EXPECT().Rel("frontend/Dockerfile").Return("Dockerfile", nil)
m.EXPECT().WriteServiceManifest(gomock.Any(), "frontend").Return("/frontend/manifest.yml", errors.New("some error"))
},
mockstore: func(m *mocks.MockStore) {
m.EXPECT().ListServices("app")
m.EXPECT().GetApplication("app").Return(&config.Application{
Name: "app",
AccountID: "1234",
}, nil)
},
wantedErr: errors.New("write service manifest: some error"),
},
"add service to app fails": {
inSvcType: manifestinfo.LoadBalancedWebServiceType,
inAppName: "app",
inSvcName: "frontend",
inSvcPort: 80,
inDockerfilePath: "frontend/Dockerfile",
mockWriter: func(m *mocks.MockWorkspace) {
// workspace root: "/frontend"
m.EXPECT().Rel("frontend/Dockerfile").Return("Dockerfile", nil)
m.EXPECT().WriteServiceManifest(gomock.Any(), "frontend").Return("/frontend/manifest.yml", nil)
},
mockstore: func(m *mocks.MockStore) {
m.EXPECT().ListServices("app").Return([]*config.Workload{}, nil)
m.EXPECT().GetApplication(gomock.Any()).Return(&config.Application{
Name: "app",
AccountID: "1234",
}, nil)
},
mockappDeployer: func(m *mocks.MockWorkloadAdder) {
m.EXPECT().AddServiceToApp(gomock.Any(), gomock.Any(), gomock.Any()).Return(errors.New("some error"))
},
wantedErr: errors.New("add service frontend to application app: some error"),
},
"error saving app": {
inSvcType: manifestinfo.LoadBalancedWebServiceType,
inAppName: "app",
inSvcName: "frontend",
inDockerfilePath: "frontend/Dockerfile",
mockWriter: func(m *mocks.MockWorkspace) {
// workspace root: "/frontend"
m.EXPECT().Rel("frontend/Dockerfile").Return("Dockerfile", nil)
m.EXPECT().WriteServiceManifest(gomock.Any(), "frontend").Return("/frontend/manifest.yml", nil)
},
mockstore: func(m *mocks.MockStore) {
m.EXPECT().ListServices("app").Return([]*config.Workload{}, nil)
m.EXPECT().CreateService(gomock.Any()).
Return(fmt.Errorf("oops"))
m.EXPECT().GetApplication(gomock.Any()).Return(&config.Application{}, nil)
},
mockappDeployer: func(m *mocks.MockWorkloadAdder) {
m.EXPECT().AddServiceToApp(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil)
},
wantedErr: fmt.Errorf("saving service frontend: oops"),
},
"using existing image": {
inSvcType: manifestinfo.BackendServiceType,
inAppName: "app",
inSvcName: "backend",
inImage: "mockImage",
inSvcPort: 80,
mockWriter: func(m *mocks.MockWorkspace) {
// workspace root: "/backend"
m.EXPECT().Rel("/backend/manifest.yml").Return("manifest.yml", nil)
m.EXPECT().WriteServiceManifest(gomock.Any(), "backend").
Do(func(m *manifest.BackendService, _ string) {
require.Equal(t, *m.Workload.Type, manifestinfo.BackendServiceType)
require.Equal(t, *m.ImageConfig.Image.Location, "mockImage")
require.Empty(t, m.ImageConfig.HealthCheck)
}).Return("/backend/manifest.yml", nil)
},
mockstore: func(m *mocks.MockStore) {
m.EXPECT().CreateService(gomock.Any()).
Do(func(app *config.Workload) {
require.Equal(t, &config.Workload{
Name: "backend",
App: "app",
Type: manifestinfo.BackendServiceType,
}, app)
}).
Return(nil)
m.EXPECT().GetApplication("app").Return(&config.Application{
Name: "app",
AccountID: "1234",
}, nil)
},
mockappDeployer: func(m *mocks.MockWorkloadAdder) {
m.EXPECT().AddServiceToApp(&config.Application{
Name: "app",
AccountID: "1234",
}, "backend")
},
},
"no healthcheck options": {
inSvcType: manifestinfo.BackendServiceType,
inAppName: "app",
inSvcName: "backend",
inDockerfilePath: "backend/Dockerfile",
inSvcPort: 80,
mockWriter: func(m *mocks.MockWorkspace) {
// workspace root: "/backend"
gomock.InOrder(
m.EXPECT().Rel("backend/Dockerfile").Return("Dockerfile", nil),
m.EXPECT().Rel("/backend/manifest.yml").Return("manifest.yml", nil))
m.EXPECT().WriteServiceManifest(gomock.Any(), "backend").
Do(func(m *manifest.BackendService, _ string) {
require.Equal(t, *m.Workload.Type, manifestinfo.BackendServiceType)
require.Empty(t, m.ImageConfig.HealthCheck)
}).Return("/backend/manifest.yml", nil)
},
mockstore: func(m *mocks.MockStore) {
m.EXPECT().CreateService(gomock.Any()).
Do(func(app *config.Workload) {
require.Equal(t, &config.Workload{
Name: "backend",
App: "app",
Type: manifestinfo.BackendServiceType,
}, app)
}).
Return(nil)
m.EXPECT().GetApplication("app").Return(&config.Application{
Name: "app",
AccountID: "1234",
}, nil)
},
mockappDeployer: func(m *mocks.MockWorkloadAdder) {
m.EXPECT().AddServiceToApp(&config.Application{
Name: "app",
AccountID: "1234",
}, "backend")
},
},
"default healthcheck options": {
inSvcType: manifestinfo.BackendServiceType,
inAppName: "app",
inSvcName: "backend",
inDockerfilePath: "backend/Dockerfile",
inSvcPort: 80,
inHealthCheck: manifest.ContainerHealthCheck{
Interval: &testInterval,
Retries: &testRetries,
Timeout: &testTimeout,
StartPeriod: &testStartPeriod,
Command: []string{"CMD curl -f http://localhost/ || exit 1"},
},
mockWriter: func(m *mocks.MockWorkspace) {
// workspace root: "/backend"
gomock.InOrder(
m.EXPECT().Rel("backend/Dockerfile").Return("Dockerfile", nil),
m.EXPECT().Rel("/backend/manifest.yml").Return("manifest.yml", nil))
m.EXPECT().WriteServiceManifest(gomock.Any(), "backend").
Do(func(m *manifest.BackendService, _ string) {
require.Equal(t, *m.Workload.Type, manifestinfo.BackendServiceType)
require.Equal(t, m.ImageConfig.HealthCheck, manifest.ContainerHealthCheck{
Interval: &testInterval,
Retries: &testRetries,
Timeout: &testTimeout,
StartPeriod: &testStartPeriod,
Command: []string{"CMD curl -f http://localhost/ || exit 1"}})
}).Return("/backend/manifest.yml", nil)
},
mockstore: func(m *mocks.MockStore) {
m.EXPECT().CreateService(gomock.Any()).
Do(func(app *config.Workload) {
require.Equal(t, &config.Workload{
Name: "backend",
App: "app",
Type: manifestinfo.BackendServiceType,
}, app)
}).
Return(nil)
m.EXPECT().GetApplication("app").Return(&config.Application{
Name: "app",
AccountID: "1234",
}, nil)
},
mockappDeployer: func(m *mocks.MockWorkloadAdder) {
m.EXPECT().AddServiceToApp(&config.Application{
Name: "app",
AccountID: "1234",
}, "backend")
},
},
"topic subscriptions enabled": {
inSvcType: manifestinfo.WorkerServiceType,
inAppName: "app",
inSvcName: "worker",
inDockerfilePath: "worker/Dockerfile",
inSvcPort: 80,
inTopics: []manifest.TopicSubscription{
{
Name: aws.String("theTopic"),
Service: aws.String("publisher"),
},
},
mockWriter: func(m *mocks.MockWorkspace) {
// workspace root: "/worker"
gomock.InOrder(
m.EXPECT().Rel("worker/Dockerfile").Return("Dockerfile", nil),
m.EXPECT().Rel("/worker/manifest.yml").Return("manifest.yml", nil))
m.EXPECT().WriteServiceManifest(gomock.Any(), "worker").
Do(func(m *manifest.WorkerService, _ string) {
require.Equal(t, *m.Workload.Type, manifestinfo.WorkerServiceType)
require.Empty(t, m.ImageConfig.HealthCheck)
}).Return("/worker/manifest.yml", nil)
},
mockstore: func(m *mocks.MockStore) {
m.EXPECT().CreateService(gomock.Any()).
Do(func(app *config.Workload) {
require.Equal(t, &config.Workload{
Name: "worker",
App: "app",
Type: manifestinfo.WorkerServiceType,
}, app)
}).
Return(nil)
m.EXPECT().GetApplication("app").Return(&config.Application{
Name: "app",
AccountID: "1234",
}, nil)
},
mockappDeployer: func(m *mocks.MockWorkloadAdder) {
m.EXPECT().AddServiceToApp(&config.Application{
Name: "app",
AccountID: "1234",
}, "worker")
},
},
"topic subscriptions enabled with default fifo queue": {
inSvcType: manifestinfo.WorkerServiceType,
inAppName: "app",
inSvcName: "worker",
inDockerfilePath: "worker/Dockerfile",
inSvcPort: 80,
inTopics: []manifest.TopicSubscription{
{
Name: aws.String("theTopic.fifo"),
Service: aws.String("publisher"),
},
},
mockWriter: func(m *mocks.MockWorkspace) {
// workspace root: "/worker"
gomock.InOrder(
m.EXPECT().Rel("worker/Dockerfile").Return("Dockerfile", nil),
m.EXPECT().Rel("/worker/manifest.yml").Return("manifest.yml", nil))
m.EXPECT().WriteServiceManifest(gomock.Any(), "worker").
Do(func(m *manifest.WorkerService, _ string) {
require.Equal(t, *m.Workload.Type, manifestinfo.WorkerServiceType)
require.Equal(t, *m.Subscribe.Queue.FIFO.Enable, true)
require.Empty(t, m.ImageConfig.HealthCheck)
}).Return("/worker/manifest.yml", nil)
},
mockstore: func(m *mocks.MockStore) {
m.EXPECT().CreateService(gomock.Any()).
Do(func(app *config.Workload) {
require.Equal(t, &config.Workload{
Name: "worker",
App: "app",
Type: manifestinfo.WorkerServiceType,
}, app)
}).
Return(nil)
m.EXPECT().GetApplication("app").Return(&config.Application{
Name: "app",
AccountID: "1234",
}, nil)
},
mockappDeployer: func(m *mocks.MockWorkloadAdder) {
m.EXPECT().AddServiceToApp(&config.Application{
Name: "app",
AccountID: "1234",
}, "worker")
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockWriter := mocks.NewMockWorkspace(ctrl)
mockstore := mocks.NewMockStore(ctrl)
mockappDeployer := mocks.NewMockWorkloadAdder(ctrl)
mockProg := mocks.NewMockProg(ctrl)
if tc.mockWriter != nil {
tc.mockWriter(mockWriter)
}
if tc.mockstore != nil {
tc.mockstore(mockstore)
}
if tc.mockappDeployer != nil {
tc.mockappDeployer(mockappDeployer)
}
initializer := &WorkloadInitializer{
Store: mockstore,
Ws: mockWriter,
Prog: mockProg,
Deployer: mockappDeployer,
}
// WHEN
_, err := initializer.Service(&ServiceProps{
WorkloadProps: WorkloadProps{
App: tc.inAppName,
Name: tc.inSvcName,
Type: tc.inSvcType,
DockerfilePath: tc.inDockerfilePath,
Image: tc.inImage,
Topics: tc.inTopics,
},
Port: tc.inSvcPort,
HealthCheck: tc.inHealthCheck,
})
// THEN
if tc.wantedErr != nil {
require.EqualError(t, err, tc.wantedErr.Error())
} else {
require.NoError(t, err)
}
})
}
}
| 891 |
copilot-cli | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: ./internal/pkg/initialize/workload.go
// Package mocks is a generated GoMock package.
package mocks
import (
encoding "encoding"
reflect "reflect"
config "github.com/aws/copilot-cli/internal/pkg/config"
cloudformation "github.com/aws/copilot-cli/internal/pkg/deploy/cloudformation"
gomock "github.com/golang/mock/gomock"
)
// MockStore is a mock of Store interface.
type MockStore struct {
ctrl *gomock.Controller
recorder *MockStoreMockRecorder
}
// MockStoreMockRecorder is the mock recorder for MockStore.
type MockStoreMockRecorder struct {
mock *MockStore
}
// NewMockStore creates a new mock instance.
func NewMockStore(ctrl *gomock.Controller) *MockStore {
mock := &MockStore{ctrl: ctrl}
mock.recorder = &MockStoreMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockStore) EXPECT() *MockStoreMockRecorder {
return m.recorder
}
// CreateJob mocks base method.
func (m *MockStore) CreateJob(job *config.Workload) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CreateJob", job)
ret0, _ := ret[0].(error)
return ret0
}
// CreateJob indicates an expected call of CreateJob.
func (mr *MockStoreMockRecorder) CreateJob(job interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateJob", reflect.TypeOf((*MockStore)(nil).CreateJob), job)
}
// CreateService mocks base method.
func (m *MockStore) CreateService(service *config.Workload) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CreateService", service)
ret0, _ := ret[0].(error)
return ret0
}
// CreateService indicates an expected call of CreateService.
func (mr *MockStoreMockRecorder) CreateService(service interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateService", reflect.TypeOf((*MockStore)(nil).CreateService), service)
}
// GetApplication mocks base method.
func (m *MockStore) GetApplication(appName string) (*config.Application, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetApplication", appName)
ret0, _ := ret[0].(*config.Application)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetApplication indicates an expected call of GetApplication.
func (mr *MockStoreMockRecorder) GetApplication(appName interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetApplication", reflect.TypeOf((*MockStore)(nil).GetApplication), appName)
}
// ListJobs mocks base method.
func (m *MockStore) ListJobs(appName string) ([]*config.Workload, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListJobs", appName)
ret0, _ := ret[0].([]*config.Workload)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ListJobs indicates an expected call of ListJobs.
func (mr *MockStoreMockRecorder) ListJobs(appName interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListJobs", reflect.TypeOf((*MockStore)(nil).ListJobs), appName)
}
// ListServices mocks base method.
func (m *MockStore) ListServices(appName string) ([]*config.Workload, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListServices", appName)
ret0, _ := ret[0].([]*config.Workload)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ListServices indicates an expected call of ListServices.
func (mr *MockStoreMockRecorder) ListServices(appName interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListServices", reflect.TypeOf((*MockStore)(nil).ListServices), appName)
}
// MockWorkloadAdder is a mock of WorkloadAdder interface.
type MockWorkloadAdder struct {
ctrl *gomock.Controller
recorder *MockWorkloadAdderMockRecorder
}
// MockWorkloadAdderMockRecorder is the mock recorder for MockWorkloadAdder.
type MockWorkloadAdderMockRecorder struct {
mock *MockWorkloadAdder
}
// NewMockWorkloadAdder creates a new mock instance.
func NewMockWorkloadAdder(ctrl *gomock.Controller) *MockWorkloadAdder {
mock := &MockWorkloadAdder{ctrl: ctrl}
mock.recorder = &MockWorkloadAdderMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockWorkloadAdder) EXPECT() *MockWorkloadAdderMockRecorder {
return m.recorder
}
// AddJobToApp mocks base method.
func (m *MockWorkloadAdder) AddJobToApp(app *config.Application, jobName string, opts ...cloudformation.AddWorkloadToAppOpt) error {
m.ctrl.T.Helper()
varargs := []interface{}{app, jobName}
for _, a := range opts {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "AddJobToApp", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// AddJobToApp indicates an expected call of AddJobToApp.
func (mr *MockWorkloadAdderMockRecorder) AddJobToApp(app, jobName interface{}, opts ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{app, jobName}, opts...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddJobToApp", reflect.TypeOf((*MockWorkloadAdder)(nil).AddJobToApp), varargs...)
}
// AddServiceToApp mocks base method.
func (m *MockWorkloadAdder) AddServiceToApp(app *config.Application, serviceName string, opts ...cloudformation.AddWorkloadToAppOpt) error {
m.ctrl.T.Helper()
varargs := []interface{}{app, serviceName}
for _, a := range opts {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "AddServiceToApp", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// AddServiceToApp indicates an expected call of AddServiceToApp.
func (mr *MockWorkloadAdderMockRecorder) AddServiceToApp(app, serviceName interface{}, opts ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{app, serviceName}, opts...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddServiceToApp", reflect.TypeOf((*MockWorkloadAdder)(nil).AddServiceToApp), varargs...)
}
// MockWorkspace is a mock of Workspace interface.
type MockWorkspace struct {
ctrl *gomock.Controller
recorder *MockWorkspaceMockRecorder
}
// MockWorkspaceMockRecorder is the mock recorder for MockWorkspace.
type MockWorkspaceMockRecorder struct {
mock *MockWorkspace
}
// NewMockWorkspace creates a new mock instance.
func NewMockWorkspace(ctrl *gomock.Controller) *MockWorkspace {
mock := &MockWorkspace{ctrl: ctrl}
mock.recorder = &MockWorkspaceMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockWorkspace) EXPECT() *MockWorkspaceMockRecorder {
return m.recorder
}
// Rel mocks base method.
func (m *MockWorkspace) Rel(path string) (string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Rel", path)
ret0, _ := ret[0].(string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Rel indicates an expected call of Rel.
func (mr *MockWorkspaceMockRecorder) Rel(path interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Rel", reflect.TypeOf((*MockWorkspace)(nil).Rel), path)
}
// WriteJobManifest mocks base method.
func (m *MockWorkspace) WriteJobManifest(marshaler encoding.BinaryMarshaler, jobName string) (string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "WriteJobManifest", marshaler, jobName)
ret0, _ := ret[0].(string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// WriteJobManifest indicates an expected call of WriteJobManifest.
func (mr *MockWorkspaceMockRecorder) WriteJobManifest(marshaler, jobName interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WriteJobManifest", reflect.TypeOf((*MockWorkspace)(nil).WriteJobManifest), marshaler, jobName)
}
// WriteServiceManifest mocks base method.
func (m *MockWorkspace) WriteServiceManifest(marshaler encoding.BinaryMarshaler, serviceName string) (string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "WriteServiceManifest", marshaler, serviceName)
ret0, _ := ret[0].(string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// WriteServiceManifest indicates an expected call of WriteServiceManifest.
func (mr *MockWorkspaceMockRecorder) WriteServiceManifest(marshaler, serviceName interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WriteServiceManifest", reflect.TypeOf((*MockWorkspace)(nil).WriteServiceManifest), marshaler, serviceName)
}
// MockProg is a mock of Prog interface.
type MockProg struct {
ctrl *gomock.Controller
recorder *MockProgMockRecorder
}
// MockProgMockRecorder is the mock recorder for MockProg.
type MockProgMockRecorder struct {
mock *MockProg
}
// NewMockProg creates a new mock instance.
func NewMockProg(ctrl *gomock.Controller) *MockProg {
mock := &MockProg{ctrl: ctrl}
mock.recorder = &MockProgMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockProg) EXPECT() *MockProgMockRecorder {
return m.recorder
}
// Start mocks base method.
func (m *MockProg) Start(label string) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "Start", label)
}
// Start indicates an expected call of Start.
func (mr *MockProgMockRecorder) Start(label interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Start", reflect.TypeOf((*MockProg)(nil).Start), label)
}
// Stop mocks base method.
func (m *MockProg) Stop(label string) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "Stop", label)
}
// Stop indicates an expected call of Stop.
func (mr *MockProgMockRecorder) Stop(label interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Stop", reflect.TypeOf((*MockProg)(nil).Stop), label)
}
| 287 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package logging contains utility functions for ECS logging.
package logging
import (
"fmt"
"io"
"github.com/aws/copilot-cli/internal/pkg/aws/cloudwatchlogs"
)
// HumanJSONStringer can output in both human-readable and JSON format.
type HumanJSONStringer interface {
HumanString() string
JSONString() (string, error)
}
// WriteJSONLogs outputs CloudWatch logs in JSON format.
func WriteJSONLogs(w io.Writer, logStringers []HumanJSONStringer) error {
for _, logStringer := range logStringers {
data, err := logStringer.JSONString()
if err != nil {
return fmt.Errorf("get log string in JSON: %w", err)
}
fmt.Fprint(w, data)
}
return nil
}
// WriteHumanLogs outputs CloudWatch logs in human-readable format.
func WriteHumanLogs(w io.Writer, logStringers []HumanJSONStringer) error {
for _, logStringer := range logStringers {
fmt.Fprint(w, logStringer.HumanString())
}
return nil
}
func cwEventsToHumanJSONStringers(events []*cloudwatchlogs.Event) []HumanJSONStringer {
// golang limitation: https://golang.org/doc/faq#convert_slice_of_interface
logStringers := make([]HumanJSONStringer, len(events))
for ind, event := range events {
logStringers[ind] = event
}
return logStringers
}
| 48 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package logging contains utility functions for ECS logging.
package logging
import (
"fmt"
"io"
"time"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/copilot-cli/internal/pkg/aws/cloudwatchlogs"
"github.com/aws/copilot-cli/internal/pkg/aws/ecs"
"github.com/aws/copilot-cli/internal/pkg/task"
"github.com/aws/copilot-cli/internal/pkg/term/log"
)
const (
numCWLogsCallsPerRound = 10
fmtTaskLogGroupName = "/copilot/%s"
// e.g., copilot-task/python/4f8243e83f8a4bdaa7587fa1eaff2ea3
fmtTaskLogStreamName = "copilot-task/%s/%s"
)
// TasksDescriber describes ECS tasks.
type TasksDescriber interface {
DescribeTasks(cluster string, taskARNs []string) ([]*ecs.Task, error)
}
// TaskClient retrieves the logs of Amazon ECS tasks.
type TaskClient struct {
// Inputs to the task client.
groupName string
tasks []*task.Task
eventsWriter io.Writer
eventsLogger logGetter
taskDescriber TasksDescriber
// Replaced in tests.
sleep func()
}
// NewTaskClient returns a TaskClient that can retrieve logs from the given tasks under the groupName.
func NewTaskClient(sess *session.Session, groupName string, tasks []*task.Task) *TaskClient {
return &TaskClient{
groupName: groupName,
tasks: tasks,
taskDescriber: ecs.New(sess),
eventsLogger: cloudwatchlogs.New(sess),
eventsWriter: log.OutputWriter,
sleep: func() {
time.Sleep(cloudwatchlogs.SleepDuration)
},
}
}
// WriteEventsUntilStopped writes tasks' events to a writer until all tasks have stopped.
func (t *TaskClient) WriteEventsUntilStopped() error {
in := cloudwatchlogs.LogEventsOpts{
LogGroup: fmt.Sprintf(fmtTaskLogGroupName, t.groupName),
}
for {
logStreams, err := t.logStreamNamesFromTasks(t.tasks)
if err != nil {
return err
}
in.LogStreamPrefixFilters = logStreams
for i := 0; i < numCWLogsCallsPerRound; i++ {
logEventsOutput, err := t.eventsLogger.LogEvents(in)
if err != nil {
return fmt.Errorf("get task log events: %w", err)
}
if err := WriteHumanLogs(t.eventsWriter, cwEventsToHumanJSONStringers(logEventsOutput.Events)); err != nil {
return fmt.Errorf("write log event: %w", err)
}
in.StreamLastEventTime = logEventsOutput.StreamLastEventTime
t.sleep()
}
stopped, err := t.allTasksStopped()
if err != nil {
return err
}
if stopped {
return nil
}
}
}
func (t *TaskClient) allTasksStopped() (bool, error) {
taskARNs := make([]string, len(t.tasks))
for idx, task := range t.tasks {
taskARNs[idx] = task.TaskARN
}
// NOTE: all tasks are deployed to the same cluster and there are at least one tasks being deployed
cluster := t.tasks[0].ClusterARN
tasksResp, err := t.taskDescriber.DescribeTasks(cluster, taskARNs)
if err != nil {
return false, fmt.Errorf("describe tasks: %w", err)
}
stopped := true
var runningTasks []*task.Task
for _, t := range tasksResp {
if *t.LastStatus != ecs.DesiredStatusStopped {
stopped = false
runningTasks = append(runningTasks, &task.Task{
ClusterARN: *t.ClusterArn,
TaskARN: *t.TaskArn,
})
}
}
t.tasks = runningTasks
return stopped, nil
}
func (t *TaskClient) logStreamNamesFromTasks(tasks []*task.Task) ([]string, error) {
var logStreamNames []string
for _, task := range tasks {
id, err := ecs.TaskID(task.TaskARN)
if err != nil {
return nil, fmt.Errorf("parse task ID from ARN %s", task.TaskARN)
}
logStreamNames = append(logStreamNames, fmt.Sprintf(fmtTaskLogStreamName, t.groupName, id))
}
return logStreamNames, nil
}
| 134 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package logging
import (
"errors"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/copilot-cli/internal/pkg/aws/cloudwatchlogs"
"github.com/aws/copilot-cli/internal/pkg/aws/ecs"
"github.com/aws/copilot-cli/internal/pkg/logging/mocks"
"github.com/aws/copilot-cli/internal/pkg/task"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
type writeEventMocks struct {
logGetter *mocks.MocklogGetter
describer *mocks.MockTasksDescriber
}
type mockWriter struct{}
func (mockWriter) Write(p []byte) (int, error) { return 0, nil }
func TestEventsWriter_WriteEventsUntilStopped(t *testing.T) {
const (
groupName = "my-log-group"
taskARN1 = "arn:aws:ecs:us-west-2:123456789:task/cluster/task1"
taskARN2 = "arn:aws:ecs:us-west-2:123456789:task/cluster/task2"
taskARN3 = "arn:aws:ecs:us-west-2:123456789:task/cluster/task3"
taskARN4 = "task4"
)
now := time.Now()
tomorrow := now.AddDate(0, 0, 1)
theDayAfter := now.AddDate(0, 0, 2)
goodTasks := []*task.Task{
{
TaskARN: taskARN1,
ClusterARN: "cluster",
StartedAt: &now,
},
{
TaskARN: taskARN2,
ClusterARN: "cluster",
StartedAt: &tomorrow,
},
{
TaskARN: taskARN3,
ClusterARN: "cluster",
StartedAt: &theDayAfter,
},
}
badTasks := []*task.Task{
{
TaskARN: taskARN4,
ClusterARN: "cluster",
StartedAt: &now,
},
}
testCases := map[string]struct {
tasks []*task.Task
setUpMocks func(m writeEventMocks)
wantedError error
}{
"error parsing task ID": {
tasks: badTasks,
setUpMocks: func(m writeEventMocks) {},
wantedError: errors.New("parse task ID from ARN task4"),
},
"error getting log events": {
tasks: goodTasks,
setUpMocks: func(m writeEventMocks) {
m.logGetter.EXPECT().LogEvents(gomock.Any()).
Return(&cloudwatchlogs.LogEventsOutput{}, errors.New("error getting log events"))
},
wantedError: errors.New("get task log events: error getting log events"),
},
"error describing tasks": {
tasks: goodTasks,
setUpMocks: func(m writeEventMocks) {
m.logGetter.EXPECT().LogEvents(gomock.Any()).
Return(&cloudwatchlogs.LogEventsOutput{
Events: []*cloudwatchlogs.Event{},
}, nil).AnyTimes()
m.describer.EXPECT().DescribeTasks("cluster", []string{taskARN1, taskARN2, taskARN3}).
Return(nil, errors.New("error describing tasks"))
},
wantedError: errors.New("describe tasks: error describing tasks"),
},
"success": {
tasks: goodTasks,
setUpMocks: func(m writeEventMocks) {
m.logGetter.EXPECT().LogEvents(gomock.Any()).Do(func(param cloudwatchlogs.LogEventsOpts) {
require.Equal(t, param.LogGroup, "/copilot/my-log-group")
require.Equal(t, param.LogStreamPrefixFilters, []string{"copilot-task/my-log-group/task1", "copilot-task/my-log-group/task2", "copilot-task/my-log-group/task3"})
}).
Return(&cloudwatchlogs.LogEventsOutput{
Events: []*cloudwatchlogs.Event{},
}, nil).Times(numCWLogsCallsPerRound)
m.describer.EXPECT().DescribeTasks("cluster", []string{taskARN1, taskARN2, taskARN3}).
Return([]*ecs.Task{
{
TaskArn: aws.String(taskARN1),
LastStatus: aws.String(ecs.DesiredStatusStopped),
},
{
TaskArn: aws.String(taskARN2),
LastStatus: aws.String(ecs.DesiredStatusStopped),
},
{
TaskArn: aws.String(taskARN3),
LastStatus: aws.String(ecs.DesiredStatusStopped),
},
}, nil)
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mocks := writeEventMocks{
logGetter: mocks.NewMocklogGetter(ctrl),
describer: mocks.NewMockTasksDescriber(ctrl),
}
tc.setUpMocks(mocks)
ew := &TaskClient{
groupName: groupName,
tasks: tc.tasks,
eventsWriter: mockWriter{},
eventsLogger: mocks.logGetter,
taskDescriber: mocks.describer,
sleep: func() {}, // no-op.
}
err := ew.WriteEventsUntilStopped()
if tc.wantedError != nil {
require.EqualError(t, tc.wantedError, err.Error())
} else {
require.NoError(t, err)
}
})
}
}
| 155 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package logging contains utility functions for ECS logging.
package logging
import (
"fmt"
"io"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/copilot-cli/internal/pkg/aws/apprunner"
"github.com/aws/copilot-cli/internal/pkg/aws/cloudwatchlogs"
"github.com/aws/copilot-cli/internal/pkg/describe"
"github.com/aws/copilot-cli/internal/pkg/term/log"
)
const (
defaultServiceLogsLimit = 10
fmtWkldLogGroupName = "/copilot/%s-%s-%s"
wkldLogStreamPrefix = "copilot"
stateMachineLogStreamPrefix = "states"
)
type logGetter interface {
LogEvents(opts cloudwatchlogs.LogEventsOpts) (*cloudwatchlogs.LogEventsOutput, error)
}
type serviceARNGetter interface {
ServiceARN(env string) (string, error)
}
// NewWorkloadLoggerOpts contains fields that initiate workloadLogger struct.
type NewWorkloadLoggerOpts struct {
App string
Env string
Name string
Sess *session.Session
}
// newWorkloadLogger returns a workloadLogger for the service under env and app.
// The logging client is initialized from the given sess session.
func newWorkloadLogger(opts *NewWorkloadLoggerOpts) *workloadLogger {
return &workloadLogger{
app: opts.App,
env: opts.Env,
name: opts.Name,
eventsGetter: cloudwatchlogs.New(opts.Sess),
w: log.OutputWriter,
now: time.Now,
}
}
type workloadLogger struct {
app string
env string
name string
eventsGetter logGetter
w io.Writer
now func() time.Time
}
// WriteLogEvents writes service logs.
func (s *workloadLogger) writeEventLogs(logEventsOpts cloudwatchlogs.LogEventsOpts, onEvent func(io.Writer, []HumanJSONStringer) error, follow bool) error {
for {
logEventsOutput, err := s.eventsGetter.LogEvents(logEventsOpts)
if err != nil {
return fmt.Errorf("get log events for log group %s: %w", logEventsOpts.LogGroup, err)
}
if err := onEvent(s.w, cwEventsToHumanJSONStringers(logEventsOutput.Events)); err != nil {
return err
}
if !follow {
return nil
}
// For unit test.
if logEventsOutput.StreamLastEventTime == nil {
return nil
}
logEventsOpts.StreamLastEventTime = logEventsOutput.StreamLastEventTime
time.Sleep(cloudwatchlogs.SleepDuration)
}
}
func ecsLogStreamPrefixes(taskIDs []string, service, container string) []string {
// By default, we only want logs from copilot task log streams.
// This filters out log stream not starting with `copilot/`, or `copilot/datadog` if container is set.
if len(taskIDs) == 0 {
return []string{fmt.Sprintf("%s/%s", wkldLogStreamPrefix, container)}
}
var logStreamPrefixes []string
if container == "" {
container = service
}
for _, taskID := range taskIDs {
prefix := fmt.Sprintf("%s/%s/%s", wkldLogStreamPrefix, container, taskID) // Example: copilot/sidecar/1111 or copilot/web/1111
logStreamPrefixes = append(logStreamPrefixes, prefix)
}
return logStreamPrefixes
}
// NewECSServiceClient returns an ECSServiceClient for the service under env and app.
func NewECSServiceClient(opts *NewWorkloadLoggerOpts) *ECSServiceLogger {
return &ECSServiceLogger{
workloadLogger: newWorkloadLogger(opts),
}
}
// ECSServiceLogger retrieves the logs of an Amazon ECS service.
type ECSServiceLogger struct {
*workloadLogger
}
// WriteLogEvents writes service logs.
func (s *ECSServiceLogger) WriteLogEvents(opts WriteLogEventsOpts) error {
logGroup := fmt.Sprintf(fmtWkldLogGroupName, s.app, s.env, s.name)
if opts.LogGroup != "" {
logGroup = opts.LogGroup
}
logEventsOpts := cloudwatchlogs.LogEventsOpts{
LogGroup: logGroup,
Limit: opts.limit(),
StartTime: opts.startTime(s.now),
EndTime: opts.EndTime,
StreamLastEventTime: nil,
LogStreamLimit: opts.LogStreamLimit,
LogStreamPrefixFilters: s.logStreamPrefixes(opts.TaskIDs, opts.ContainerName),
}
return s.workloadLogger.writeEventLogs(logEventsOpts, opts.OnEvents, opts.Follow)
}
func (s *ECSServiceLogger) logStreamPrefixes(taskIDs []string, container string) []string {
return ecsLogStreamPrefixes(taskIDs, s.name, container)
}
// NewAppRunnerServiceLoggerOpts contains fields that initiate AppRunnerServiceLoggerOpts struct.
type NewAppRunnerServiceLoggerOpts struct {
*NewWorkloadLoggerOpts
ConfigStore describe.ConfigStoreSvc
}
// NewAppRunnerServiceLogger returns an AppRunnerServiceLogger for the service under env and app.
func NewAppRunnerServiceLogger(opts *NewAppRunnerServiceLoggerOpts) (*AppRunnerServiceLogger, error) {
serviceDescriber, err := describe.NewRDWebServiceDescriber(describe.NewServiceConfig{
App: opts.App,
Svc: opts.Name,
ConfigStore: opts.ConfigStore,
})
if err != nil {
return nil, err
}
return &AppRunnerServiceLogger{
workloadLogger: newWorkloadLogger(opts.NewWorkloadLoggerOpts),
serviceARNGetter: serviceDescriber,
}, nil
}
// AppRunnerServiceLogger retrieves the logs of an AppRunner service.
type AppRunnerServiceLogger struct {
*workloadLogger
serviceARNGetter serviceARNGetter
}
// WriteLogEvents writes service logs.
func (s *AppRunnerServiceLogger) WriteLogEvents(opts WriteLogEventsOpts) error {
var logGroup string
switch strings.ToLower(opts.LogGroup) {
case "system":
serviceArn, err := s.serviceARNGetter.ServiceARN(s.env)
if err != nil {
return fmt.Errorf("get service ARN for %s: %w", s.name, err)
}
logGroup, err = apprunner.SystemLogGroupName(serviceArn)
if err != nil {
return fmt.Errorf("get system log group name: %w", err)
}
case "":
serviceArn, err := s.serviceARNGetter.ServiceARN(s.env)
if err != nil {
return fmt.Errorf("get service ARN for %s: %w", s.name, err)
}
logGroup, err = apprunner.LogGroupName(serviceArn)
if err != nil {
return fmt.Errorf("get log group name: %w", err)
}
default:
logGroup = opts.LogGroup
}
logEventsOpts := cloudwatchlogs.LogEventsOpts{
LogGroup: logGroup,
Limit: opts.limit(),
StartTime: opts.startTime(s.now),
EndTime: opts.EndTime,
StreamLastEventTime: nil,
LogStreamLimit: opts.LogStreamLimit,
}
return s.workloadLogger.writeEventLogs(logEventsOpts, opts.OnEvents, opts.Follow)
}
// NewJobLogger returns an JobLogger for the job under env and app.
func NewJobLogger(opts *NewWorkloadLoggerOpts) *JobLogger {
return &JobLogger{
workloadLogger: newWorkloadLogger(opts),
}
}
// JobLogger retrieves the logs of a job.
type JobLogger struct {
*workloadLogger
}
// WriteLogEvents writes job logs.
func (s *JobLogger) WriteLogEvents(opts WriteLogEventsOpts) error {
logStreamLimit := opts.LogStreamLimit
if opts.IncludeStateMachineLogs {
logStreamLimit *= 2
}
logGroup := fmt.Sprintf(fmtWkldLogGroupName, s.app, s.env, s.name)
if opts.LogGroup != "" {
logGroup = opts.LogGroup
}
logEventsOpts := cloudwatchlogs.LogEventsOpts{
LogGroup: logGroup,
Limit: opts.limit(),
StartTime: opts.startTime(s.now),
EndTime: opts.EndTime,
StreamLastEventTime: nil,
LogStreamLimit: logStreamLimit,
LogStreamPrefixFilters: s.logStreamPrefixes(opts.TaskIDs, opts.IncludeStateMachineLogs),
}
return s.workloadLogger.writeEventLogs(logEventsOpts, opts.OnEvents, opts.Follow)
}
// The log stream prefixes for a job should be:
// 1. copilot/;
// 2. copilot/, states;
// 3. copilot/query/taskID where query is the job's name, thus the main container's name.
func (s *JobLogger) logStreamPrefixes(taskIDs []string, includeStateMachineLogs bool) []string {
// `includeStateMachineLogs` is mutually exclusive with specific task IDs and only used for jobs. Therefore, we
// need to grab all recent log streams with no prefix filtering.
if includeStateMachineLogs {
return []string{fmt.Sprintf("%s/", wkldLogStreamPrefix), stateMachineLogStreamPrefix}
}
return ecsLogStreamPrefixes(taskIDs, s.name, "")
}
// WriteLogEventsOpts wraps the parameters to call WriteLogEvents.
type WriteLogEventsOpts struct {
Follow bool
Limit *int64
StartTime *int64
EndTime *int64
// OnEvents is a handler that's invoked when logs are retrieved from the service.
OnEvents func(w io.Writer, logs []HumanJSONStringer) error
LogGroup string
// Job specific options.
IncludeStateMachineLogs bool
// LogStreamLimit is an optional parameter for jobs and tasks to speed up CW queries
// involving multiple log streams.
LogStreamLimit int
// ECS specific options.
ContainerName string
TaskIDs []string
}
func (o WriteLogEventsOpts) limit() *int64 {
if o.Limit != nil {
return o.Limit
}
if o.hasTimeFilters() {
// If time filtering is set, then set limit to be maximum number.
// https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_GetLogEvents.html#CWL-GetLogEvents-request-limit
return nil
}
if o.hasLogStreamLimit() {
// If log stream limit is set and no log event limit is set, then set limit to maximum.
return nil
}
return aws.Int64(defaultServiceLogsLimit)
}
func (o WriteLogEventsOpts) hasLogStreamLimit() bool {
return o.LogStreamLimit != 0
}
func (o WriteLogEventsOpts) startTime(now func() time.Time) *int64 {
if o.StartTime != nil {
return o.StartTime
}
if o.Follow {
// Start following log events from current timestamp.
return aws.Int64(now().UnixMilli())
}
return nil
}
func (o WriteLogEventsOpts) hasTimeFilters() bool {
return o.Follow || o.StartTime != nil || o.EndTime != nil
}
| 307 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package logging
import (
"bytes"
"errors"
"fmt"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/copilot-cli/internal/pkg/aws/cloudwatchlogs"
"github.com/aws/copilot-cli/internal/pkg/logging/mocks"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
type workloadLogsMocks struct {
logGetter *mocks.MocklogGetter
serviceARNGetter *mocks.MockserviceARNGetter
}
func TestECSServiceLogger_WriteLogEvents(t *testing.T) {
const (
mockLogGroupName = "mockLogGroup"
logEventsHumanString = `firelens_log_router/fcfe4 10.0.0.00 - - [01/Jan/1970 01:01:01] "GET / HTTP/1.1" 200 -
firelens_log_router/fcfe4 10.0.0.00 - - [01/Jan/1970 01:01:01] "FATA some error" - -
firelens_log_router/fcfe4 10.0.0.00 - - [01/Jan/1970 01:01:01] "WARN some warning" - -
`
logEventsJSONString = "{\"logStreamName\":\"firelens_log_router/fcfe4ab8043841c08162318e5ad805f1\",\"ingestionTime\":0,\"message\":\"10.0.0.00 - - [01/Jan/1970 01:01:01] \\\"GET / HTTP/1.1\\\" 200 -\",\"timestamp\":0}\n{\"logStreamName\":\"firelens_log_router/fcfe4ab8043841c08162318e5ad805f1\",\"ingestionTime\":0,\"message\":\"10.0.0.00 - - [01/Jan/1970 01:01:01] \\\"FATA some error\\\" - -\",\"timestamp\":0}\n{\"logStreamName\":\"firelens_log_router/fcfe4ab8043841c08162318e5ad805f1\",\"ingestionTime\":0,\"message\":\"10.0.0.00 - - [01/Jan/1970 01:01:01] \\\"WARN some warning\\\" - -\",\"timestamp\":0}\n"
)
mockLogEvents := []*cloudwatchlogs.Event{
{
LogStreamName: "firelens_log_router/fcfe4ab8043841c08162318e5ad805f1",
Message: `10.0.0.00 - - [01/Jan/1970 01:01:01] "GET / HTTP/1.1" 200 -`,
},
{
LogStreamName: "firelens_log_router/fcfe4ab8043841c08162318e5ad805f1",
Message: `10.0.0.00 - - [01/Jan/1970 01:01:01] "FATA some error" - -`,
},
{
LogStreamName: "firelens_log_router/fcfe4ab8043841c08162318e5ad805f1",
Message: `10.0.0.00 - - [01/Jan/1970 01:01:01] "WARN some warning" - -`,
},
}
mockMoreLogEvents := []*cloudwatchlogs.Event{
{
LogStreamName: "firelens_log_router/fcfe4ab8043841c08162318e5ad805f1",
Message: `10.0.0.00 - - [01/Jan/1970 01:01:01] "GET / HTTP/1.1" 404 -`,
},
}
mockCurrentTimestamp := time.Date(2020, 11, 23, 0, 0, 0, 0, time.UTC) // Copilot GA date :).
testCases := map[string]struct {
follow bool
limit *int64
startTime *int64
jsonOutput bool
taskIDs []string
containerName string
setupMocks func(mocks workloadLogsMocks)
wantedError error
wantedContent string
}{
"failed to get task log events": {
setupMocks: func(m workloadLogsMocks) {
m.logGetter.EXPECT().LogEvents(gomock.Any()).Return(nil, errors.New("some error"))
},
wantedError: fmt.Errorf("get log events for log group mockLogGroup: some error"),
},
"success with human output": {
limit: aws.Int64(100),
setupMocks: func(m workloadLogsMocks) {
m.logGetter.EXPECT().LogEvents(gomock.Any()).
Do(func(param cloudwatchlogs.LogEventsOpts) {
require.Equal(t, param.Limit, aws.Int64(100))
}).
Return(&cloudwatchlogs.LogEventsOutput{
Events: mockLogEvents,
}, nil)
},
wantedContent: logEventsHumanString,
},
"success with json output": {
jsonOutput: true,
startTime: aws.Int64(123456789),
setupMocks: func(m workloadLogsMocks) {
m.logGetter.EXPECT().LogEvents(gomock.Any()).
Do(func(param cloudwatchlogs.LogEventsOpts) {
require.Equal(t, param.Limit, (*int64)(nil))
}).
Return(&cloudwatchlogs.LogEventsOutput{
Events: mockLogEvents,
}, nil)
},
wantedContent: logEventsJSONString,
},
"success with follow flag": {
follow: true,
setupMocks: func(m workloadLogsMocks) {
gomock.InOrder(
m.logGetter.EXPECT().LogEvents(gomock.Any()).
Do(func(param cloudwatchlogs.LogEventsOpts) {
require.Equal(t, param.Limit, (*int64)(nil))
require.Equal(t, param.StartTime, aws.Int64(mockCurrentTimestamp.UnixMilli()))
}).
Return(&cloudwatchlogs.LogEventsOutput{
Events: mockLogEvents,
StreamLastEventTime: map[string]int64{
"mockLogStreamName": 123456,
},
}, nil),
m.logGetter.EXPECT().LogEvents(gomock.Any()).
Return(&cloudwatchlogs.LogEventsOutput{
Events: mockMoreLogEvents,
StreamLastEventTime: nil,
}, nil),
)
},
wantedContent: `firelens_log_router/fcfe4 10.0.0.00 - - [01/Jan/1970 01:01:01] "GET / HTTP/1.1" 200 -
firelens_log_router/fcfe4 10.0.0.00 - - [01/Jan/1970 01:01:01] "FATA some error" - -
firelens_log_router/fcfe4 10.0.0.00 - - [01/Jan/1970 01:01:01] "WARN some warning" - -
firelens_log_router/fcfe4 10.0.0.00 - - [01/Jan/1970 01:01:01] "GET / HTTP/1.1" 404 -
`,
},
"success with log limit set": {
limit: aws.Int64(50),
setupMocks: func(m workloadLogsMocks) {
gomock.InOrder(
m.logGetter.EXPECT().LogEvents(gomock.Any()).
Do(func(param cloudwatchlogs.LogEventsOpts) {
require.Equal(t, param.LogStreamPrefixFilters, []string{"copilot/"})
require.Equal(t, param.Limit, aws.Int64(50))
}).
Return(&cloudwatchlogs.LogEventsOutput{
Events: mockLogEvents,
}, nil),
)
},
wantedContent: logEventsHumanString,
},
"success when filtered by task IDs": {
taskIDs: []string{"mockTaskID1"},
setupMocks: func(m workloadLogsMocks) {
gomock.InOrder(
m.logGetter.EXPECT().LogEvents(gomock.Any()).
Do(func(param cloudwatchlogs.LogEventsOpts) {
require.Equal(t, param.LogStreamPrefixFilters, []string{"copilot/mockSvc/mockTaskID1"})
require.Equal(t, param.Limit, aws.Int64(10))
}).
Return(&cloudwatchlogs.LogEventsOutput{
Events: mockLogEvents,
}, nil),
)
},
wantedContent: logEventsHumanString,
},
"success when filtered by certain container and certain tasks": {
containerName: "datadog",
taskIDs: []string{"mockTaskID"},
setupMocks: func(m workloadLogsMocks) {
gomock.InOrder(
m.logGetter.EXPECT().LogEvents(gomock.Any()).
Do(func(param cloudwatchlogs.LogEventsOpts) {
require.Equal(t, param.LogStreamPrefixFilters, []string{"copilot/datadog/mockTaskID"})
require.Equal(t, param.Limit, aws.Int64(10))
}).
Return(&cloudwatchlogs.LogEventsOutput{
Events: mockLogEvents,
}, nil),
)
},
wantedContent: logEventsHumanString,
},
"success when filtered by certain container": {
containerName: "datadog",
setupMocks: func(m workloadLogsMocks) {
gomock.InOrder(
m.logGetter.EXPECT().LogEvents(gomock.Any()).
Do(func(param cloudwatchlogs.LogEventsOpts) {
require.Equal(t, param.LogStreamPrefixFilters, []string{"copilot/datadog"})
require.Equal(t, param.Limit, aws.Int64(10))
}).
Return(&cloudwatchlogs.LogEventsOutput{
Events: mockLogEvents,
}, nil),
)
},
wantedContent: logEventsHumanString,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mocklogGetter := mocks.NewMocklogGetter(ctrl)
mocks := workloadLogsMocks{
logGetter: mocklogGetter,
}
tc.setupMocks(mocks)
b := &bytes.Buffer{}
svcLogs := &ECSServiceLogger{
workloadLogger: &workloadLogger{
app: "mockApp",
env: "mockEnv",
name: "mockSvc",
eventsGetter: mocklogGetter,
w: b,
now: func() time.Time {
return mockCurrentTimestamp
},
},
}
// WHEN
logWriter := WriteHumanLogs
if tc.jsonOutput {
logWriter = WriteJSONLogs
}
err := svcLogs.WriteLogEvents(WriteLogEventsOpts{
Follow: tc.follow,
TaskIDs: tc.taskIDs,
Limit: tc.limit,
StartTime: tc.startTime,
OnEvents: logWriter,
ContainerName: tc.containerName,
LogGroup: mockLogGroupName,
})
// THEN
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedContent, b.String(), "expected output content match")
}
})
}
}
func TestAppRunnerServiceLogger_WriteLogEvents(t *testing.T) {
const (
logEventsHumanString = `instance/85372273718e4806 [email protected] start /app
instance/4e66ee07f2034a7c Server is running on port 4055
`
logEventsJSONString = "{\"logStreamName\":\"instance/85372273718e4806b5cd805044755bc8\",\"ingestionTime\":0,\"message\":\"[email protected] start /app\",\"timestamp\":0}\n{\"logStreamName\":\"instance/4e66ee07f2034a7cb287fdb5f2fd04f9\",\"ingestionTime\":0,\"message\":\"Server is running on port 4055\",\"timestamp\":0}\n"
)
logEvents := []*cloudwatchlogs.Event{
{
LogStreamName: "instance/85372273718e4806b5cd805044755bc8",
Message: `[email protected] start /app`,
},
{
LogStreamName: "instance/4e66ee07f2034a7cb287fdb5f2fd04f9",
Message: `Server is running on port 4055`,
},
}
mockLimit := aws.Int64(100)
var mockNilLimit *int64
mockStartTime := aws.Int64(123456789)
testCases := map[string]struct {
follow bool
limit *int64
startTime *int64
jsonOutput bool
logGroupName string
setupMocks func(mocks workloadLogsMocks)
wantedError error
wantedContent string
}{
"failed to get service ARN": {
setupMocks: func(m workloadLogsMocks) {
m.serviceARNGetter.EXPECT().ServiceARN("mockEnv").Return("", errors.New("some error"))
},
wantedError: fmt.Errorf("get service ARN for mockSvc: some error"),
},
"failed to get log events": {
logGroupName: "mockLogGroup",
setupMocks: func(m workloadLogsMocks) {
m.logGetter.EXPECT().LogEvents(gomock.Any()).Return(nil, errors.New("some error"))
},
wantedError: fmt.Errorf("get log events for log group mockLogGroup: some error"),
},
"success with human output": {
limit: mockLimit,
logGroupName: "mockLogGroup",
setupMocks: func(m workloadLogsMocks) {
m.logGetter.EXPECT().LogEvents(gomock.Any()).
Do(func(param cloudwatchlogs.LogEventsOpts) {
require.Equal(t, param.Limit, mockLimit)
}).Return(&cloudwatchlogs.LogEventsOutput{
Events: logEvents,
}, nil)
},
wantedContent: logEventsHumanString,
},
"success with json output": {
jsonOutput: true,
startTime: mockStartTime,
logGroupName: "mockLogGroup",
setupMocks: func(m workloadLogsMocks) {
m.logGetter.EXPECT().LogEvents(gomock.Any()).
Do(func(param cloudwatchlogs.LogEventsOpts) {
require.Equal(t, param.Limit, mockNilLimit)
}).
Return(&cloudwatchlogs.LogEventsOutput{
Events: logEvents,
}, nil)
},
wantedContent: logEventsJSONString,
},
"success with application log": {
setupMocks: func(m workloadLogsMocks) {
gomock.InOrder(
m.serviceARNGetter.EXPECT().ServiceARN("mockEnv").Return("arn:aws:apprunner:us-east-1:11111111111:service/mockSvc/mockSvcID", nil),
m.logGetter.EXPECT().LogEvents(gomock.Any()).
Do(func(param cloudwatchlogs.LogEventsOpts) {
require.Equal(t, param.LogGroup, "/aws/apprunner/mockSvc/mockSvcID/application")
}).Return(&cloudwatchlogs.LogEventsOutput{
Events: logEvents,
}, nil),
)
},
wantedContent: logEventsHumanString,
},
"success with system log": {
logGroupName: "system",
setupMocks: func(m workloadLogsMocks) {
gomock.InOrder(
m.serviceARNGetter.EXPECT().ServiceARN("mockEnv").Return("arn:aws:apprunner:us-east-1:11111111111:service/mockSvc/mockSvcID", nil),
m.logGetter.EXPECT().LogEvents(gomock.Any()).
Do(func(param cloudwatchlogs.LogEventsOpts) {
require.Equal(t, param.LogGroup, "/aws/apprunner/mockSvc/mockSvcID/service")
}).Return(&cloudwatchlogs.LogEventsOutput{
Events: logEvents,
}, nil),
)
},
wantedContent: logEventsHumanString,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := workloadLogsMocks{
logGetter: mocks.NewMocklogGetter(ctrl),
serviceARNGetter: mocks.NewMockserviceARNGetter(ctrl),
}
tc.setupMocks(m)
b := &bytes.Buffer{}
svcLogs := &AppRunnerServiceLogger{
workloadLogger: &workloadLogger{
app: "mockApp",
env: "mockEnv",
name: "mockSvc",
eventsGetter: m.logGetter,
w: b,
},
serviceARNGetter: m.serviceARNGetter,
}
// WHEN
logWriter := WriteHumanLogs
if tc.jsonOutput {
logWriter = WriteJSONLogs
}
err := svcLogs.WriteLogEvents(WriteLogEventsOpts{
Follow: tc.follow,
Limit: tc.limit,
StartTime: tc.startTime,
LogGroup: tc.logGroupName,
OnEvents: logWriter,
})
// THEN
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedContent, b.String(), "expected output content match")
}
})
}
}
func TestJobLogger_WriteLogEvents(t *testing.T) {
const (
mockLogGroupName = "mockLogGroup"
logEventsHumanString = `firelens_log_router/fcfe4 10.0.0.00 - - [01/Jan/1970 01:01:01] "GET / HTTP/1.1" 200 -
firelens_log_router/fcfe4 10.0.0.00 - - [01/Jan/1970 01:01:01] "FATA some error" - -
firelens_log_router/fcfe4 10.0.0.00 - - [01/Jan/1970 01:01:01] "WARN some warning" - -
`
logEventsJSONString = "{\"logStreamName\":\"firelens_log_router/fcfe4ab8043841c08162318e5ad805f1\",\"ingestionTime\":0,\"message\":\"10.0.0.00 - - [01/Jan/1970 01:01:01] \\\"GET / HTTP/1.1\\\" 200 -\",\"timestamp\":0}\n{\"logStreamName\":\"firelens_log_router/fcfe4ab8043841c08162318e5ad805f1\",\"ingestionTime\":0,\"message\":\"10.0.0.00 - - [01/Jan/1970 01:01:01] \\\"FATA some error\\\" - -\",\"timestamp\":0}\n{\"logStreamName\":\"firelens_log_router/fcfe4ab8043841c08162318e5ad805f1\",\"ingestionTime\":0,\"message\":\"10.0.0.00 - - [01/Jan/1970 01:01:01] \\\"WARN some warning\\\" - -\",\"timestamp\":0}\n"
)
mockLogEvents := []*cloudwatchlogs.Event{
{
LogStreamName: "firelens_log_router/fcfe4ab8043841c08162318e5ad805f1",
Message: `10.0.0.00 - - [01/Jan/1970 01:01:01] "GET / HTTP/1.1" 200 -`,
},
{
LogStreamName: "firelens_log_router/fcfe4ab8043841c08162318e5ad805f1",
Message: `10.0.0.00 - - [01/Jan/1970 01:01:01] "FATA some error" - -`,
},
{
LogStreamName: "firelens_log_router/fcfe4ab8043841c08162318e5ad805f1",
Message: `10.0.0.00 - - [01/Jan/1970 01:01:01] "WARN some warning" - -`,
},
}
mockMoreLogEvents := []*cloudwatchlogs.Event{
{
LogStreamName: "firelens_log_router/fcfe4ab8043841c08162318e5ad805f1",
Message: `10.0.0.00 - - [01/Jan/1970 01:01:01] "GET / HTTP/1.1" 404 -`,
},
}
mockCurrentTimestamp := time.Date(2020, 11, 23, 0, 0, 0, 0, time.UTC) // Copilot GA date :).
testCases := map[string]struct {
follow bool
logStreamLimit int
limit *int64
startTime *int64
jsonOutput bool
taskIDs []string
includeStateMachine bool
setupMocks func(mocks workloadLogsMocks)
wantedError error
wantedContent string
}{
"failed to get task log events": {
setupMocks: func(m workloadLogsMocks) {
m.logGetter.EXPECT().LogEvents(gomock.Any()).Return(nil, errors.New("some error"))
},
wantedError: fmt.Errorf("get log events for log group mockLogGroup: some error"),
},
"success with human output": {
limit: aws.Int64(100),
setupMocks: func(m workloadLogsMocks) {
m.logGetter.EXPECT().LogEvents(gomock.Any()).
Do(func(param cloudwatchlogs.LogEventsOpts) {
require.Equal(t, param.Limit, aws.Int64(100))
}).
Return(&cloudwatchlogs.LogEventsOutput{
Events: mockLogEvents,
}, nil)
},
wantedContent: logEventsHumanString,
},
"success with json output": {
jsonOutput: true,
startTime: aws.Int64(123456789),
setupMocks: func(m workloadLogsMocks) {
m.logGetter.EXPECT().LogEvents(gomock.Any()).
Do(func(param cloudwatchlogs.LogEventsOpts) {
require.Equal(t, param.Limit, (*int64)(nil))
}).
Return(&cloudwatchlogs.LogEventsOutput{
Events: mockLogEvents,
}, nil)
},
wantedContent: logEventsJSONString,
},
"success with follow flag": {
follow: true,
setupMocks: func(m workloadLogsMocks) {
gomock.InOrder(
m.logGetter.EXPECT().LogEvents(gomock.Any()).
Do(func(param cloudwatchlogs.LogEventsOpts) {
require.Equal(t, param.Limit, (*int64)(nil))
require.Equal(t, param.StartTime, aws.Int64(mockCurrentTimestamp.UnixMilli()))
}).
Return(&cloudwatchlogs.LogEventsOutput{
Events: mockLogEvents,
StreamLastEventTime: map[string]int64{
"mockLogStreamName": 123456,
},
}, nil),
m.logGetter.EXPECT().LogEvents(gomock.Any()).
Return(&cloudwatchlogs.LogEventsOutput{
Events: mockMoreLogEvents,
StreamLastEventTime: nil,
}, nil),
)
},
wantedContent: `firelens_log_router/fcfe4 10.0.0.00 - - [01/Jan/1970 01:01:01] "GET / HTTP/1.1" 200 -
firelens_log_router/fcfe4 10.0.0.00 - - [01/Jan/1970 01:01:01] "FATA some error" - -
firelens_log_router/fcfe4 10.0.0.00 - - [01/Jan/1970 01:01:01] "WARN some warning" - -
firelens_log_router/fcfe4 10.0.0.00 - - [01/Jan/1970 01:01:01] "GET / HTTP/1.1" 404 -
`,
},
"success with log limit set": {
limit: aws.Int64(50),
setupMocks: func(m workloadLogsMocks) {
m.logGetter.EXPECT().LogEvents(gomock.Any()).
Do(func(param cloudwatchlogs.LogEventsOpts) {
require.Equal(t, param.LogStreamPrefixFilters, []string{"copilot/"})
require.Equal(t, param.Limit, aws.Int64(50))
}).
Return(&cloudwatchlogs.LogEventsOutput{
Events: mockLogEvents,
}, nil)
},
wantedContent: logEventsHumanString,
},
"success with state machine included": {
includeStateMachine: true,
logStreamLimit: 1,
setupMocks: func(m workloadLogsMocks) {
m.logGetter.EXPECT().LogEvents(gomock.Any()).
Do(func(param cloudwatchlogs.LogEventsOpts) {
require.Equal(t, param.LogStreamPrefixFilters, []string{"copilot/", "states"})
require.Equal(t, param.Limit, (*int64)(nil))
require.Equal(t, param.LogStreamLimit, 2)
}).
Return(&cloudwatchlogs.LogEventsOutput{
Events: mockLogEvents,
}, nil)
},
wantedContent: logEventsHumanString,
},
"success with log stream limit set": {
logStreamLimit: 1,
setupMocks: func(m workloadLogsMocks) {
m.logGetter.EXPECT().LogEvents(gomock.Any()).
Do(func(param cloudwatchlogs.LogEventsOpts) {
require.Equal(t, param.LogStreamPrefixFilters, []string{"copilot/"})
require.Equal(t, param.LogStreamLimit, 1)
require.Equal(t, param.Limit, (*int64)(nil))
}).
Return(&cloudwatchlogs.LogEventsOutput{
Events: mockLogEvents,
}, nil)
},
wantedContent: logEventsHumanString,
},
"success with log stream limit and log limit": {
logStreamLimit: 1,
limit: aws.Int64(50),
setupMocks: func(m workloadLogsMocks) {
gomock.InOrder(
m.logGetter.EXPECT().LogEvents(gomock.Any()).
Do(func(param cloudwatchlogs.LogEventsOpts) {
require.Equal(t, param.LogStreamPrefixFilters, []string{"copilot/"})
require.Equal(t, param.LogStreamLimit, 1)
require.Equal(t, param.Limit, aws.Int64(50))
}).
Return(&cloudwatchlogs.LogEventsOutput{
Events: mockLogEvents,
}, nil),
)
},
wantedContent: logEventsHumanString,
},
"success when filtered by task IDs": {
taskIDs: []string{"mockTaskID1"},
setupMocks: func(m workloadLogsMocks) {
gomock.InOrder(
m.logGetter.EXPECT().LogEvents(gomock.Any()).
Do(func(param cloudwatchlogs.LogEventsOpts) {
require.Equal(t, param.LogStreamPrefixFilters, []string{"copilot/mockSvc/mockTaskID1"})
require.Equal(t, param.Limit, aws.Int64(10))
}).
Return(&cloudwatchlogs.LogEventsOutput{
Events: mockLogEvents,
}, nil),
)
},
wantedContent: logEventsHumanString,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mocklogGetter := mocks.NewMocklogGetter(ctrl)
mocks := workloadLogsMocks{
logGetter: mocklogGetter,
}
tc.setupMocks(mocks)
b := &bytes.Buffer{}
svcLogs := &JobLogger{
workloadLogger: &workloadLogger{
app: "mockApp",
env: "mockEnv",
name: "mockSvc",
eventsGetter: mocklogGetter,
w: b,
now: func() time.Time {
return mockCurrentTimestamp
},
},
}
// WHEN
logWriter := WriteHumanLogs
if tc.jsonOutput {
logWriter = WriteJSONLogs
}
err := svcLogs.WriteLogEvents(WriteLogEventsOpts{
Follow: tc.follow,
TaskIDs: tc.taskIDs,
Limit: tc.limit,
StartTime: tc.startTime,
OnEvents: logWriter,
LogStreamLimit: tc.logStreamLimit,
LogGroup: mockLogGroupName,
IncludeStateMachineLogs: tc.includeStateMachine,
})
// THEN
if tc.wantedError != nil {
require.EqualError(t, err, tc.wantedError.Error())
} else {
require.NoError(t, err)
require.Equal(t, tc.wantedContent, b.String(), "expected output content match")
}
})
}
}
| 637 |
copilot-cli | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: ./internal/pkg/logging/task.go
// Package mocks is a generated GoMock package.
package mocks
import (
reflect "reflect"
ecs "github.com/aws/copilot-cli/internal/pkg/aws/ecs"
gomock "github.com/golang/mock/gomock"
)
// MockTasksDescriber is a mock of TasksDescriber interface.
type MockTasksDescriber struct {
ctrl *gomock.Controller
recorder *MockTasksDescriberMockRecorder
}
// MockTasksDescriberMockRecorder is the mock recorder for MockTasksDescriber.
type MockTasksDescriberMockRecorder struct {
mock *MockTasksDescriber
}
// NewMockTasksDescriber creates a new mock instance.
func NewMockTasksDescriber(ctrl *gomock.Controller) *MockTasksDescriber {
mock := &MockTasksDescriber{ctrl: ctrl}
mock.recorder = &MockTasksDescriberMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockTasksDescriber) EXPECT() *MockTasksDescriberMockRecorder {
return m.recorder
}
// DescribeTasks mocks base method.
func (m *MockTasksDescriber) DescribeTasks(cluster string, taskARNs []string) ([]*ecs.Task, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DescribeTasks", cluster, taskARNs)
ret0, _ := ret[0].([]*ecs.Task)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DescribeTasks indicates an expected call of DescribeTasks.
func (mr *MockTasksDescriberMockRecorder) DescribeTasks(cluster, taskARNs interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeTasks", reflect.TypeOf((*MockTasksDescriber)(nil).DescribeTasks), cluster, taskARNs)
}
| 51 |
copilot-cli | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: ./internal/pkg/logging/workload.go
// Package mocks is a generated GoMock package.
package mocks
import (
reflect "reflect"
cloudwatchlogs "github.com/aws/copilot-cli/internal/pkg/aws/cloudwatchlogs"
gomock "github.com/golang/mock/gomock"
)
// MocklogGetter is a mock of logGetter interface.
type MocklogGetter struct {
ctrl *gomock.Controller
recorder *MocklogGetterMockRecorder
}
// MocklogGetterMockRecorder is the mock recorder for MocklogGetter.
type MocklogGetterMockRecorder struct {
mock *MocklogGetter
}
// NewMocklogGetter creates a new mock instance.
func NewMocklogGetter(ctrl *gomock.Controller) *MocklogGetter {
mock := &MocklogGetter{ctrl: ctrl}
mock.recorder = &MocklogGetterMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MocklogGetter) EXPECT() *MocklogGetterMockRecorder {
return m.recorder
}
// LogEvents mocks base method.
func (m *MocklogGetter) LogEvents(opts cloudwatchlogs.LogEventsOpts) (*cloudwatchlogs.LogEventsOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "LogEvents", opts)
ret0, _ := ret[0].(*cloudwatchlogs.LogEventsOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// LogEvents indicates an expected call of LogEvents.
func (mr *MocklogGetterMockRecorder) LogEvents(opts interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LogEvents", reflect.TypeOf((*MocklogGetter)(nil).LogEvents), opts)
}
// MockserviceARNGetter is a mock of serviceARNGetter interface.
type MockserviceARNGetter struct {
ctrl *gomock.Controller
recorder *MockserviceARNGetterMockRecorder
}
// MockserviceARNGetterMockRecorder is the mock recorder for MockserviceARNGetter.
type MockserviceARNGetterMockRecorder struct {
mock *MockserviceARNGetter
}
// NewMockserviceARNGetter creates a new mock instance.
func NewMockserviceARNGetter(ctrl *gomock.Controller) *MockserviceARNGetter {
mock := &MockserviceARNGetter{ctrl: ctrl}
mock.recorder = &MockserviceARNGetterMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockserviceARNGetter) EXPECT() *MockserviceARNGetterMockRecorder {
return m.recorder
}
// ServiceARN mocks base method.
func (m *MockserviceARNGetter) ServiceARN(env string) (string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ServiceARN", env)
ret0, _ := ret[0].(string)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ServiceARN indicates an expected call of ServiceARN.
func (mr *MockserviceARNGetterMockRecorder) ServiceARN(env interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceARN", reflect.TypeOf((*MockserviceARNGetter)(nil).ServiceARN), env)
}
| 89 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package manifest
import (
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/stretchr/testify/require"
)
func TestEnsureTransformersOrder(t *testing.T) {
t.Run("ensure we call basic transformer first", func(t *testing.T) {
_, ok := defaultTransformers[0].(basicTransformer)
require.True(t, ok, "basicTransformer needs to used before the rest of the custom transformers, because the other transformers do not merge anything - they just unset the fields that do not get specified in source manifest.")
})
}
func TestApplyEnv_Bool(t *testing.T) {
testCases := map[string]struct {
inSvc func(svc *LoadBalancedWebService)
wanted func(svc *LoadBalancedWebService)
}{
"bool value overridden": {
inSvc: func(svc *LoadBalancedWebService) {
svc.HTTPOrBool.Main.Stickiness = aws.Bool(false)
svc.Environments["test"].HTTPOrBool.Main.Stickiness = aws.Bool(true)
},
wanted: func(svc *LoadBalancedWebService) {
svc.HTTPOrBool.Main.Stickiness = aws.Bool(true)
},
},
"bool value overridden by zero value": {
inSvc: func(svc *LoadBalancedWebService) {
svc.HTTPOrBool.Main.Stickiness = aws.Bool(true)
svc.Environments["test"].HTTPOrBool.Main.Stickiness = aws.Bool(false)
},
wanted: func(svc *LoadBalancedWebService) {
svc.HTTPOrBool.Main.Stickiness = aws.Bool(false)
},
},
"bool value not overridden": {
inSvc: func(svc *LoadBalancedWebService) {
svc.HTTPOrBool.Main.Stickiness = aws.Bool(true)
},
wanted: func(svc *LoadBalancedWebService) {
svc.HTTPOrBool.Main.Stickiness = aws.Bool(true)
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
var inSvc, wantedSvc LoadBalancedWebService
inSvc.Environments = map[string]*LoadBalancedWebServiceConfig{
"test": {},
}
tc.inSvc(&inSvc)
tc.wanted(&wantedSvc)
got, err := inSvc.applyEnv("test")
require.NoError(t, err)
require.Equal(t, &wantedSvc, got)
})
}
}
func testApplyEnv(t *testing.T, initial, env, expected LoadBalancedWebServiceConfig) {
mft := LoadBalancedWebService{
LoadBalancedWebServiceConfig: initial,
Environments: map[string]*LoadBalancedWebServiceConfig{
"test": &env,
},
}
expectedMft := LoadBalancedWebService{
LoadBalancedWebServiceConfig: expected,
}
got, err := mft.applyEnv("test")
require.NoError(t, err)
require.Equal(t, &expectedMft, got)
}
func TestApplyEnv_Int(t *testing.T) {
tests := map[string]struct {
initial *int
override *int
expected *int
}{
"overridden": {
initial: aws.Int(24),
override: aws.Int(42),
expected: aws.Int(42),
},
"overridden by zero": {
initial: aws.Int(24),
override: aws.Int(0),
expected: aws.Int(0),
},
"not overridden": {
initial: aws.Int(24),
expected: aws.Int(24),
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
initial := LoadBalancedWebServiceConfig{
TaskConfig: TaskConfig{
CPU: tc.initial,
},
}
override := LoadBalancedWebServiceConfig{
TaskConfig: TaskConfig{
CPU: tc.override,
},
}
expected := LoadBalancedWebServiceConfig{
TaskConfig: TaskConfig{
CPU: tc.expected,
},
}
testApplyEnv(t, initial, override, expected)
})
}
}
func TestApplyEnv_Int64(t *testing.T) {
tests := map[string]struct {
initial *int64
override *int64
expected *int64
}{
"overridden": {
initial: aws.Int64(24),
override: aws.Int64(42),
expected: aws.Int64(42),
},
"overridden by zero": {
initial: aws.Int64(24),
override: aws.Int64(0),
expected: aws.Int64(0),
},
"not overridden": {
initial: aws.Int64(24),
expected: aws.Int64(24),
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
initial := LoadBalancedWebServiceConfig{
HTTPOrBool: HTTPOrBool{
HTTP: HTTP{
Main: RoutingRule{
HealthCheck: HealthCheckArgsOrString{
AdvancedToUnion[string](HTTPHealthCheckArgs{
HealthyThreshold: tc.initial,
}),
},
},
},
},
}
override := LoadBalancedWebServiceConfig{
HTTPOrBool: HTTPOrBool{
HTTP: HTTP{
Main: RoutingRule{
HealthCheck: HealthCheckArgsOrString{
AdvancedToUnion[string](HTTPHealthCheckArgs{
HealthyThreshold: tc.override,
}),
},
},
},
},
}
expected := LoadBalancedWebServiceConfig{
HTTPOrBool: HTTPOrBool{
HTTP: HTTP{
Main: RoutingRule{
HealthCheck: HealthCheckArgsOrString{
AdvancedToUnion[string](HTTPHealthCheckArgs{
HealthyThreshold: tc.expected,
}),
},
},
},
},
}
testApplyEnv(t, initial, override, expected)
})
}
}
func TestApplyEnv_Uint16(t *testing.T) {
tests := map[string]struct {
initial *uint16
override *uint16
expected *uint16
}{
"overridden": {
initial: aws.Uint16(24),
override: aws.Uint16(42),
expected: aws.Uint16(42),
},
"overridden by zero": {
initial: aws.Uint16(24),
override: aws.Uint16(0),
expected: aws.Uint16(0),
},
"not overridden": {
initial: aws.Uint16(24),
expected: aws.Uint16(24),
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
initial := LoadBalancedWebServiceConfig{
ImageConfig: ImageWithPortAndHealthcheck{
ImageWithPort: ImageWithPort{
Port: tc.initial,
},
},
}
override := LoadBalancedWebServiceConfig{
ImageConfig: ImageWithPortAndHealthcheck{
ImageWithPort: ImageWithPort{
Port: tc.override,
},
},
}
expected := LoadBalancedWebServiceConfig{
ImageConfig: ImageWithPortAndHealthcheck{
ImageWithPort: ImageWithPort{
Port: tc.expected,
},
},
}
testApplyEnv(t, initial, override, expected)
})
}
}
func TestApplyEnv_Uint32(t *testing.T) {
tests := map[string]struct {
initial *uint32
override *uint32
expected *uint32
}{
"overridden": {
initial: aws.Uint32(24),
override: aws.Uint32(42),
expected: aws.Uint32(42),
},
"overridden by zero": {
initial: aws.Uint32(24),
override: aws.Uint32(0),
expected: aws.Uint32(0),
},
"not overridden": {
initial: aws.Uint32(24),
expected: aws.Uint32(24),
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
initial := LoadBalancedWebServiceConfig{
TaskConfig: TaskConfig{
Storage: Storage{
Volumes: map[string]*Volume{
"volume1": {
EFS: EFSConfigOrBool{
Advanced: EFSVolumeConfiguration{
UID: tc.initial,
},
},
},
},
},
},
}
override := LoadBalancedWebServiceConfig{
TaskConfig: TaskConfig{
Storage: Storage{
Volumes: map[string]*Volume{
"volume1": {
EFS: EFSConfigOrBool{
Advanced: EFSVolumeConfiguration{
UID: tc.override,
},
},
},
},
},
},
}
expected := LoadBalancedWebServiceConfig{
TaskConfig: TaskConfig{
Storage: Storage{
Volumes: map[string]*Volume{
"volume1": {
EFS: EFSConfigOrBool{
Advanced: EFSVolumeConfiguration{
UID: tc.expected,
},
},
},
},
},
},
}
testApplyEnv(t, initial, override, expected)
})
}
}
func TestApplyEnv_Duration(t *testing.T) {
testCases := map[string]struct {
inSvc func(svc *LoadBalancedWebService)
wanted func(svc *LoadBalancedWebService)
}{
"duration overridden": {
inSvc: func(svc *LoadBalancedWebService) {
mockDuration, mockDurationTest := 24*time.Second, 42*time.Second
svc.HTTPOrBool.Main.DeregistrationDelay = &mockDuration
svc.Environments["test"].HTTPOrBool.Main.DeregistrationDelay = &mockDurationTest
},
wanted: func(svc *LoadBalancedWebService) {
mockDurationTest := 42 * time.Second
svc.HTTPOrBool.Main.DeregistrationDelay = &mockDurationTest
},
},
"duration overridden by zero value": {
inSvc: func(svc *LoadBalancedWebService) {
mockDuration, mockDurationTest := 24*time.Second, 0*time.Second
svc.HTTPOrBool.Main.DeregistrationDelay = &mockDuration
svc.Environments["test"].HTTPOrBool.Main.DeregistrationDelay = &mockDurationTest
},
wanted: func(svc *LoadBalancedWebService) {
mockDurationTest := 0 * time.Second
svc.HTTPOrBool.Main.DeregistrationDelay = &mockDurationTest
},
},
"duration not overridden": {
inSvc: func(svc *LoadBalancedWebService) {
mockDuration := 24 * time.Second
svc.HTTPOrBool.Main.DeregistrationDelay = &mockDuration
},
wanted: func(svc *LoadBalancedWebService) {
mockDurationTest := 24 * time.Second
svc.HTTPOrBool.Main.DeregistrationDelay = &mockDurationTest
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
var inSvc, wantedSvc LoadBalancedWebService
inSvc.Environments = map[string]*LoadBalancedWebServiceConfig{
"test": {},
}
tc.inSvc(&inSvc)
tc.wanted(&wantedSvc)
got, err := inSvc.applyEnv("test")
require.NoError(t, err)
require.Equal(t, &wantedSvc, got)
})
}
}
func TestApplyEnv_String(t *testing.T) {
testCases := map[string]struct {
inSvc func(svc *LoadBalancedWebService)
wanted func(svc *LoadBalancedWebService)
}{
"string overridden": {
inSvc: func(svc *LoadBalancedWebService) {
svc.ImageConfig.Image.Location = aws.String("cairo")
svc.Environments["test"].ImageConfig.Image.Location = aws.String("nerac")
},
wanted: func(svc *LoadBalancedWebService) {
svc.ImageConfig.Image.Location = aws.String("nerac")
},
},
"string overridden by zero value": {
inSvc: func(svc *LoadBalancedWebService) {
svc.ImageConfig.Image.Location = aws.String("cairo")
svc.Environments["test"].ImageConfig.Image.Location = aws.String("")
},
wanted: func(svc *LoadBalancedWebService) {
svc.ImageConfig.Image.Location = aws.String("")
},
},
"string not overridden": {
inSvc: func(svc *LoadBalancedWebService) {
svc.ImageConfig.Image.Location = aws.String("cairo")
},
wanted: func(svc *LoadBalancedWebService) {
svc.ImageConfig.Image.Location = aws.String("cairo")
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
var inSvc, wantedSvc LoadBalancedWebService
inSvc.Environments = map[string]*LoadBalancedWebServiceConfig{
"test": {},
}
tc.inSvc(&inSvc)
tc.wanted(&wantedSvc)
got, err := inSvc.applyEnv("test")
require.NoError(t, err)
require.Equal(t, &wantedSvc, got)
})
}
}
func TestApplyEnv_StringSlice(t *testing.T) {
testCases := map[string]struct {
inSvc func(svc *LoadBalancedWebService)
wanted func(svc *LoadBalancedWebService)
}{
"string slice overridden": {
inSvc: func(svc *LoadBalancedWebService) {
svc.ImageConfig.HealthCheck.Command = []string{"walk", "like", "an", "egyptian"}
svc.Environments["test"].ImageConfig.HealthCheck.Command = []string{"walk", "on", "the", "wild", "side"}
},
wanted: func(svc *LoadBalancedWebService) {
svc.ImageConfig.HealthCheck.Command = []string{"walk", "on", "the", "wild", "side"}
},
},
"string slice overridden by zero value": {
inSvc: func(svc *LoadBalancedWebService) {
svc.ImageConfig.HealthCheck.Command = []string{"walk", "like", "an", "egyptian"}
svc.Environments["test"].ImageConfig.HealthCheck.Command = []string{}
},
wanted: func(svc *LoadBalancedWebService) {
svc.ImageConfig.HealthCheck.Command = []string{}
},
},
"string slice not overridden": {
inSvc: func(svc *LoadBalancedWebService) {
svc.ImageConfig.HealthCheck.Command = []string{"walk", "like", "an", "egyptian"}
},
wanted: func(svc *LoadBalancedWebService) {
svc.ImageConfig.HealthCheck.Command = []string{"walk", "like", "an", "egyptian"}
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
var inSvc, wantedSvc LoadBalancedWebService
inSvc.Environments = map[string]*LoadBalancedWebServiceConfig{
"test": {},
}
tc.inSvc(&inSvc)
tc.wanted(&wantedSvc)
got, err := inSvc.applyEnv("test")
require.NoError(t, err)
require.Equal(t, &wantedSvc, got)
})
}
}
func TestApplyEnv_StructSlice(t *testing.T) {
testCases := map[string]struct {
inSvc func(svc *LoadBalancedWebService)
wanted func(svc *LoadBalancedWebService)
}{
"struct slice overridden": {
inSvc: func(svc *LoadBalancedWebService) {
svc.PublishConfig.Topics = []Topic{
{
Name: aws.String("walk like an egyptian"),
},
}
svc.Environments["test"].PublishConfig.Topics = []Topic{
{
Name: aws.String("walk on the wild side"),
},
}
},
wanted: func(svc *LoadBalancedWebService) {
svc.PublishConfig.Topics = []Topic{
{
Name: aws.String("walk on the wild side"),
},
}
},
},
"string slice overridden by zero value": {
inSvc: func(svc *LoadBalancedWebService) {
svc.PublishConfig.Topics = []Topic{
{
Name: aws.String("walk like an egyptian"),
},
}
svc.Environments["test"].PublishConfig.Topics = []Topic{}
},
wanted: func(svc *LoadBalancedWebService) {
svc.PublishConfig.Topics = []Topic{}
},
},
"string slice not overridden": {
inSvc: func(svc *LoadBalancedWebService) {
svc.PublishConfig.Topics = []Topic{
{
Name: aws.String("walk like an egyptian"),
},
}
},
wanted: func(svc *LoadBalancedWebService) {
svc.PublishConfig.Topics = []Topic{
{
Name: aws.String("walk like an egyptian"),
},
}
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
var inSvc, wantedSvc LoadBalancedWebService
inSvc.Environments = map[string]*LoadBalancedWebServiceConfig{
"test": {},
}
tc.inSvc(&inSvc)
tc.wanted(&wantedSvc)
got, err := inSvc.applyEnv("test")
require.NoError(t, err)
require.Equal(t, &wantedSvc, got)
})
}
}
func TestApplyEnv_MapToString(t *testing.T) {
testCases := map[string]struct {
inSvc func(svc *LoadBalancedWebService)
wanted func(svc *LoadBalancedWebService)
}{
"map upserted": {
inSvc: func(svc *LoadBalancedWebService) {
svc.ImageConfig.Image.DockerLabels = map[string]string{
"var1": "the secret sauce is mole",
"var2": "the secret agent is johnny rivers",
}
svc.Environments["test"].ImageConfig.Image.DockerLabels = map[string]string{
"var1": "the secret sauce is blue cheese which has mold in it",
"var3": "the secret route is through egypt",
}
},
wanted: func(svc *LoadBalancedWebService) {
svc.ImageConfig.Image.DockerLabels = map[string]string{
"var1": "the secret sauce is blue cheese which has mold in it", // Overridden.
"var2": "the secret agent is johnny rivers", // Kept.
"var3": "the secret route is through egypt", // Appended
}
},
},
"map not overridden by zero map": {
inSvc: func(svc *LoadBalancedWebService) {
svc.ImageConfig.Image.DockerLabels = map[string]string{
"var1": "the secret sauce is mole",
"var2": "the secret agent man is johnny rivers",
}
svc.Environments["test"].ImageConfig.Image.DockerLabels = map[string]string{}
},
wanted: func(svc *LoadBalancedWebService) {
svc.ImageConfig.Image.DockerLabels = map[string]string{
"var1": "the secret sauce is mole",
"var2": "the secret agent man is johnny rivers",
}
},
},
"map not overridden": {
inSvc: func(svc *LoadBalancedWebService) {
svc.ImageConfig.Image.DockerLabels = map[string]string{
"var1": "the secret sauce is mole",
"var2": "the secret agent man is johnny rivers",
}
},
wanted: func(svc *LoadBalancedWebService) {
svc.ImageConfig.Image.DockerLabels = map[string]string{
"var1": "the secret sauce is mole",
"var2": "the secret agent man is johnny rivers",
}
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
var inSvc, wantedSvc LoadBalancedWebService
inSvc.Environments = map[string]*LoadBalancedWebServiceConfig{
"test": {},
}
tc.inSvc(&inSvc)
tc.wanted(&wantedSvc)
got, err := inSvc.applyEnv("test")
require.NoError(t, err)
require.Equal(t, &wantedSvc, got)
})
}
}
func TestApplyEnv_MapToPStruct(t *testing.T) {
testCases := map[string]struct {
inSvc func(svc *LoadBalancedWebService)
wanted func(svc *LoadBalancedWebService)
}{
"map upserted": {
inSvc: func(svc *LoadBalancedWebService) {
svc.Storage.Volumes = map[string]*Volume{
"volume1": {
MountPointOpts: MountPointOpts{
ContainerPath: aws.String("mockPath"),
},
},
"volume2": {
MountPointOpts: MountPointOpts{
ReadOnly: aws.Bool(true),
},
},
}
svc.Environments["test"].Storage.Volumes = map[string]*Volume{
"volume1": {
EFS: EFSConfigOrBool{
Enabled: aws.Bool(true),
},
MountPointOpts: MountPointOpts{
ContainerPath: aws.String("mockPathTest"),
},
},
"volume3": {
EFS: EFSConfigOrBool{
Enabled: aws.Bool(true),
},
},
}
},
wanted: func(svc *LoadBalancedWebService) {
svc.Storage.Volumes = map[string]*Volume{
"volume1": {
EFS: EFSConfigOrBool{
Enabled: aws.Bool(true),
},
MountPointOpts: MountPointOpts{
ContainerPath: aws.String("mockPathTest"),
},
}, // Overridden.
"volume2": {
MountPointOpts: MountPointOpts{
ReadOnly: aws.Bool(true),
},
}, // Kept.
"volume3": {
EFS: EFSConfigOrBool{
Enabled: aws.Bool(true),
},
}, // Appended.
}
},
},
"map not overridden by zero map": {
inSvc: func(svc *LoadBalancedWebService) {
svc.Storage.Volumes = map[string]*Volume{
"volume1": {
MountPointOpts: MountPointOpts{
ContainerPath: aws.String("mockPath"),
},
},
"volume2": {
MountPointOpts: MountPointOpts{
ReadOnly: aws.Bool(true),
},
},
}
svc.Environments["test"].Storage.Volumes = map[string]*Volume{}
},
wanted: func(svc *LoadBalancedWebService) {
svc.Storage.Volumes = map[string]*Volume{
"volume1": {
MountPointOpts: MountPointOpts{
ContainerPath: aws.String("mockPath"),
},
},
"volume2": {
MountPointOpts: MountPointOpts{
ReadOnly: aws.Bool(true),
},
},
}
},
},
"map not overridden": {
inSvc: func(svc *LoadBalancedWebService) {
svc.Storage.Volumes = map[string]*Volume{
"volume1": {
MountPointOpts: MountPointOpts{
ContainerPath: aws.String("mockPath"),
},
},
"volume2": {
MountPointOpts: MountPointOpts{
ReadOnly: aws.Bool(true),
},
},
}
},
wanted: func(svc *LoadBalancedWebService) {
svc.Storage.Volumes = map[string]*Volume{
"volume1": {
MountPointOpts: MountPointOpts{
ContainerPath: aws.String("mockPath"),
},
},
"volume2": {
MountPointOpts: MountPointOpts{
ReadOnly: aws.Bool(true),
},
},
}
},
},
"override a nil value": {
inSvc: func(svc *LoadBalancedWebService) {
svc.Storage = Storage{
Volumes: map[string]*Volume{
"mockVolume1": nil,
},
}
svc.Environments["test"].Storage = Storage{
Volumes: map[string]*Volume{
"mockVolume1": {
MountPointOpts: MountPointOpts{
ContainerPath: aws.String("mockPath"),
},
EFS: EFSConfigOrBool{
Enabled: aws.Bool(true),
},
},
},
}
},
wanted: func(svc *LoadBalancedWebService) {
svc.Storage = Storage{
Volumes: map[string]*Volume{
"mockVolume1": {
MountPointOpts: MountPointOpts{
ContainerPath: aws.String("mockPath"),
},
EFS: EFSConfigOrBool{
Enabled: aws.Bool(true),
},
},
},
}
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
var inSvc, wantedSvc LoadBalancedWebService
inSvc.Environments = map[string]*LoadBalancedWebServiceConfig{
"test": {},
}
tc.inSvc(&inSvc)
tc.wanted(&wantedSvc)
got, err := inSvc.applyEnv("test")
require.NoError(t, err)
require.Equal(t, &wantedSvc, got)
})
}
}
func TestApplyEnv_MapToStruct(t *testing.T) {
testCases := map[string]struct {
inSvc func(svc *LoadBalancedWebService)
wanted func(svc *LoadBalancedWebService)
}{
"map upserted": {
inSvc: func(svc *LoadBalancedWebService) {
svc.TaskConfig.Variables = map[string]Variable{
"VAR1": {
stringOrFromCFN{
Plain: stringP("var1"),
},
},
"VAR2": {
stringOrFromCFN{
FromCFN: fromCFN{
Name: stringP("import-var2"),
},
},
},
}
svc.Environments["test"].TaskConfig.Variables = map[string]Variable{
"VAR1": {
stringOrFromCFN{
FromCFN: fromCFN{
Name: stringP("import-var1-test"),
},
},
},
"VAR3": {
stringOrFromCFN{
Plain: stringP("var3-test"),
},
},
}
},
wanted: func(svc *LoadBalancedWebService) {
svc.TaskConfig.Variables = map[string]Variable{
"VAR1": {
stringOrFromCFN{
FromCFN: fromCFN{
Name: stringP("import-var1-test"),
},
},
},
"VAR2": {
stringOrFromCFN{
FromCFN: fromCFN{
Name: stringP("import-var2"),
},
},
},
"VAR3": {
stringOrFromCFN{
Plain: stringP("var3-test"),
},
},
}
},
},
"map not overridden by zero map": {
inSvc: func(svc *LoadBalancedWebService) {
svc.TaskConfig.Variables = map[string]Variable{
"VAR1": {
stringOrFromCFN{
Plain: stringP("var1"),
},
},
"VAR2": {
stringOrFromCFN{
FromCFN: fromCFN{
Name: stringP("import-var2"),
},
},
},
}
svc.Environments["test"].TaskConfig.Variables = map[string]Variable{}
},
wanted: func(svc *LoadBalancedWebService) {
svc.TaskConfig.Variables = map[string]Variable{
"VAR1": {
stringOrFromCFN{
Plain: stringP("var1"),
},
},
"VAR2": {
stringOrFromCFN{
FromCFN: fromCFN{
Name: stringP("import-var2"),
},
},
},
}
},
},
"map not overridden": {
inSvc: func(svc *LoadBalancedWebService) {
svc.TaskConfig.Variables = map[string]Variable{
"VAR1": {
stringOrFromCFN{
Plain: stringP("var1"),
},
},
"VAR2": {
stringOrFromCFN{
FromCFN: fromCFN{
Name: stringP("import-var2"),
},
},
},
}
},
wanted: func(svc *LoadBalancedWebService) {
svc.TaskConfig.Variables = map[string]Variable{
"VAR1": {
stringOrFromCFN{
Plain: stringP("var1"),
},
},
"VAR2": {
stringOrFromCFN{
FromCFN: fromCFN{
Name: stringP("import-var2"),
},
},
},
}
},
},
"override a zero value": {
inSvc: func(svc *LoadBalancedWebService) {
svc.TaskConfig.Variables = map[string]Variable{
"VAR1": {},
}
svc.Environments["test"].TaskConfig.Variables = map[string]Variable{
"VAR1": {
stringOrFromCFN{
Plain: stringP("var1-test"),
},
},
}
},
wanted: func(svc *LoadBalancedWebService) {
svc.TaskConfig.Variables = map[string]Variable{
"VAR1": {
stringOrFromCFN{
Plain: stringP("var1-test"),
},
},
}
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
var inSvc, wantedSvc LoadBalancedWebService
inSvc.Environments = map[string]*LoadBalancedWebServiceConfig{
"test": {},
}
tc.inSvc(&inSvc)
tc.wanted(&wantedSvc)
got, err := inSvc.applyEnv("test")
require.NoError(t, err)
require.Equal(t, &wantedSvc, got)
})
}
}
| 971 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package manifest
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/copilot-cli/internal/pkg/manifest/manifestinfo"
"github.com/aws/copilot-cli/internal/pkg/template"
"github.com/imdario/mergo"
)
const (
backendSvcManifestPath = "workloads/services/backend/manifest.yml"
)
// BackendService holds the configuration to create a backend service manifest.
type BackendService struct {
Workload `yaml:",inline"`
BackendServiceConfig `yaml:",inline"`
// Use *BackendServiceConfig because of https://github.com/imdario/mergo/issues/146
Environments map[string]*BackendServiceConfig `yaml:",flow"`
parser template.Parser
}
// BackendServiceConfig holds the configuration that can be overridden per environments.
type BackendServiceConfig struct {
ImageConfig ImageWithHealthcheckAndOptionalPort `yaml:"image,flow"`
ImageOverride `yaml:",inline"`
HTTP HTTP `yaml:"http,flow"`
TaskConfig `yaml:",inline"`
Logging Logging `yaml:"logging,flow"`
Sidecars map[string]*SidecarConfig `yaml:"sidecars"` // NOTE: keep the pointers because `mergo` doesn't automatically deep merge map's value unless it's a pointer type.
Network NetworkConfig `yaml:"network"`
PublishConfig PublishConfig `yaml:"publish"`
TaskDefOverrides []OverrideRule `yaml:"taskdef_overrides"`
DeployConfig DeploymentConfig `yaml:"deployment"`
Observability Observability `yaml:"observability"`
}
// BackendServiceProps represents the configuration needed to create a backend service.
type BackendServiceProps struct {
WorkloadProps
Port uint16
Path string // Optional path if multiple ports are exposed.
HealthCheck ContainerHealthCheck // Optional healthcheck configuration.
Platform PlatformArgsOrString // Optional platform configuration.
}
// NewBackendService applies the props to a default backend service configuration with
// minimal task sizes, single replica, no healthcheck, and then returns it.
func NewBackendService(props BackendServiceProps) *BackendService {
svc := newDefaultBackendService()
// Apply overrides.
svc.Name = stringP(props.Name)
svc.BackendServiceConfig.ImageConfig.Image.Location = stringP(props.Image)
svc.BackendServiceConfig.ImageConfig.Image.Build.BuildArgs.Dockerfile = stringP(props.Dockerfile)
svc.BackendServiceConfig.ImageConfig.Port = uint16P(props.Port)
svc.BackendServiceConfig.ImageConfig.HealthCheck = props.HealthCheck
svc.BackendServiceConfig.Platform = props.Platform
if isWindowsPlatform(props.Platform) {
svc.BackendServiceConfig.TaskConfig.CPU = aws.Int(MinWindowsTaskCPU)
svc.BackendServiceConfig.TaskConfig.Memory = aws.Int(MinWindowsTaskMemory)
}
svc.parser = template.New()
for _, envName := range props.PrivateOnlyEnvironments {
svc.Environments[envName] = &BackendServiceConfig{
Network: NetworkConfig{
VPC: vpcConfig{
Placement: PlacementArgOrString{
PlacementString: placementStringP(PrivateSubnetPlacement),
},
},
},
}
}
return svc
}
// MarshalBinary serializes the manifest object into a binary YAML document.
// Implements the encoding.BinaryMarshaler interface.
func (s *BackendService) MarshalBinary() ([]byte, error) {
content, err := s.parser.Parse(backendSvcManifestPath, *s, template.WithFuncs(map[string]interface{}{
"fmtSlice": template.FmtSliceFunc,
"quoteSlice": template.QuoteSliceFunc,
}))
if err != nil {
return nil, err
}
return content.Bytes(), nil
}
func (s *BackendService) requiredEnvironmentFeatures() []string {
var features []string
if !s.HTTP.IsEmpty() {
features = append(features, template.InternalALBFeatureName)
}
features = append(features, s.Network.requiredEnvFeatures()...)
features = append(features, s.Storage.requiredEnvFeatures()...)
return features
}
// Port returns the exposed port in the manifest.
// If the backend service is not meant to be reachable, then ok is set to false.
func (s *BackendService) Port() (port uint16, ok bool) {
value := s.BackendServiceConfig.ImageConfig.Port
if value == nil {
return 0, false
}
return aws.Uint16Value(value), true
}
// Publish returns the list of topics where notifications can be published.
func (s *BackendService) Publish() []Topic {
return s.BackendServiceConfig.PublishConfig.publishedTopics()
}
// BuildArgs returns a docker.BuildArguments object for the service given a context directory.
func (s *BackendService) BuildArgs(contextDir string) (map[string]*DockerBuildArgs, error) {
required, err := requiresBuild(s.ImageConfig.Image)
if err != nil {
return nil, err
}
// Creating an map to store buildArgs of all sidecar images and main container image.
buildArgsPerContainer := make(map[string]*DockerBuildArgs, len(s.Sidecars)+1)
if required {
buildArgsPerContainer[aws.StringValue(s.Name)] = s.ImageConfig.Image.BuildConfig(contextDir)
}
return buildArgs(contextDir, buildArgsPerContainer, s.Sidecars)
}
// EnvFiles returns the locations of all env files against the ws root directory.
// This method returns a map[string]string where the keys are container names
// and the values are either env file paths or empty strings.
func (s *BackendService) EnvFiles() map[string]string {
return envFiles(s.Name, s.TaskConfig, s.Logging, s.Sidecars)
}
func (s *BackendService) subnets() *SubnetListOrArgs {
return &s.Network.VPC.Placement.Subnets
}
func (s BackendService) applyEnv(envName string) (workloadManifest, error) {
overrideConfig, ok := s.Environments[envName]
if !ok {
return &s, nil
}
if overrideConfig == nil {
return &s, nil
}
// Apply overrides to the original service s.
for _, t := range defaultTransformers {
err := mergo.Merge(&s, BackendService{
BackendServiceConfig: *overrideConfig,
}, mergo.WithOverride, mergo.WithTransformers(t))
if err != nil {
return nil, err
}
}
s.Environments = nil
return &s, nil
}
// newDefaultBackendService returns a backend service with minimal task sizes and a single replica.
func newDefaultBackendService() *BackendService {
return &BackendService{
Workload: Workload{
Type: aws.String(manifestinfo.BackendServiceType),
},
BackendServiceConfig: BackendServiceConfig{
ImageConfig: ImageWithHealthcheckAndOptionalPort{},
TaskConfig: TaskConfig{
CPU: aws.Int(256),
Memory: aws.Int(512),
Count: Count{
Value: aws.Int(1),
AdvancedCount: AdvancedCount{ // Leave advanced count empty while passing down the type of the workload.
workloadType: manifestinfo.BackendServiceType,
},
},
ExecuteCommand: ExecuteCommand{
Enable: aws.Bool(false),
},
},
Network: NetworkConfig{
VPC: vpcConfig{
Placement: PlacementArgOrString{
PlacementString: placementStringP(PublicSubnetPlacement),
},
},
},
},
Environments: map[string]*BackendServiceConfig{},
}
}
// ExposedPorts returns all the ports that are container ports available to receive traffic.
func (b *BackendService) ExposedPorts() (ExposedPortsIndex, error) {
var exposedPorts []ExposedPort
workloadName := aws.StringValue(b.Name)
exposedPorts = append(exposedPorts, b.ImageConfig.exposedPorts(workloadName)...)
for name, sidecar := range b.Sidecars {
out, err := sidecar.exposedPorts(name)
if err != nil {
return ExposedPortsIndex{}, err
}
exposedPorts = append(exposedPorts, out...)
}
for _, rule := range b.HTTP.RoutingRules() {
exposedPorts = append(exposedPorts, rule.exposedPorts(exposedPorts, workloadName)...)
}
portsForContainer, containerForPort := prepareParsedExposedPortsMap(sortExposedPorts(exposedPorts))
return ExposedPortsIndex{
WorkloadName: workloadName,
PortsForContainer: portsForContainer,
ContainerForPort: containerForPort,
}, nil
}
| 223 |
copilot-cli | aws | Go | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package manifest
import (
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/copilot-cli/internal/pkg/manifest/manifestinfo"
"github.com/aws/copilot-cli/internal/pkg/template"
"github.com/stretchr/testify/require"
"gopkg.in/yaml.v3"
)
func TestNewBackendSvc(t *testing.T) {
testCases := map[string]struct {
inProps BackendServiceProps
wantedManifest *BackendService
}{
"without healthcheck and port": {
inProps: BackendServiceProps{
WorkloadProps: WorkloadProps{
Name: "subscribers",
Dockerfile: "./subscribers/Dockerfile",
PrivateOnlyEnvironments: []string{
"metrics",
},
},
},
wantedManifest: &BackendService{
Workload: Workload{
Name: aws.String("subscribers"),
Type: aws.String(manifestinfo.BackendServiceType),
},
BackendServiceConfig: BackendServiceConfig{
ImageConfig: ImageWithHealthcheckAndOptionalPort{
ImageWithOptionalPort: ImageWithOptionalPort{
Image: Image{
ImageLocationOrBuild: ImageLocationOrBuild{
Build: BuildArgsOrString{
BuildArgs: DockerBuildArgs{
Dockerfile: aws.String("./subscribers/Dockerfile"),
},
},
},
},
},
},
TaskConfig: TaskConfig{
CPU: aws.Int(256),
Memory: aws.Int(512),
Count: Count{
Value: aws.Int(1),
},
ExecuteCommand: ExecuteCommand{
Enable: aws.Bool(false),
},
},
Network: NetworkConfig{
VPC: vpcConfig{
Placement: PlacementArgOrString{
PlacementString: placementStringP(PublicSubnetPlacement),
},
},
},
},
Environments: map[string]*BackendServiceConfig{
"metrics": {
Network: NetworkConfig{
VPC: vpcConfig{
Placement: PlacementArgOrString{
PlacementString: placementStringP(PrivateSubnetPlacement),
},
},
},
},
},
},
},
"with custom healthcheck command": {
inProps: BackendServiceProps{
WorkloadProps: WorkloadProps{
Name: "subscribers",
Image: "mockImage",
},
HealthCheck: ContainerHealthCheck{
Command: []string{"CMD", "curl -f http://localhost:8080 || exit 1"},
},
Port: 8080,
},
wantedManifest: &BackendService{
Workload: Workload{
Name: aws.String("subscribers"),
Type: aws.String(manifestinfo.BackendServiceType),
},
BackendServiceConfig: BackendServiceConfig{
ImageConfig: ImageWithHealthcheckAndOptionalPort{
ImageWithOptionalPort: ImageWithOptionalPort{
Image: Image{
ImageLocationOrBuild: ImageLocationOrBuild{
Location: aws.String("mockImage"),
},
},
Port: aws.Uint16(8080),
},
HealthCheck: ContainerHealthCheck{
Command: []string{"CMD", "curl -f http://localhost:8080 || exit 1"},
},
},
TaskConfig: TaskConfig{
CPU: aws.Int(256),
Memory: aws.Int(512),
Count: Count{
Value: aws.Int(1),
},
ExecuteCommand: ExecuteCommand{
Enable: aws.Bool(false),
},
},
Network: NetworkConfig{
VPC: vpcConfig{
Placement: PlacementArgOrString{
PlacementString: placementStringP(PublicSubnetPlacement),
},
},
},
},
},
},
"with windows platform": {
inProps: BackendServiceProps{
WorkloadProps: WorkloadProps{
Name: "subscribers",
Dockerfile: "./subscribers/Dockerfile",
},
Platform: PlatformArgsOrString{PlatformString: (*PlatformString)(aws.String("windows/amd64"))},
},
wantedManifest: &BackendService{
Workload: Workload{
Name: aws.String("subscribers"),
Type: aws.String(manifestinfo.BackendServiceType),
},
BackendServiceConfig: BackendServiceConfig{
ImageConfig: ImageWithHealthcheckAndOptionalPort{
ImageWithOptionalPort: ImageWithOptionalPort{
Image: Image{
ImageLocationOrBuild: ImageLocationOrBuild{
Build: BuildArgsOrString{
BuildArgs: DockerBuildArgs{
Dockerfile: aws.String("./subscribers/Dockerfile"),
},
},
},
},
},
},
TaskConfig: TaskConfig{
CPU: aws.Int(1024),
Memory: aws.Int(2048),
Platform: PlatformArgsOrString{
PlatformString: (*PlatformString)(aws.String("windows/amd64")),
PlatformArgs: PlatformArgs{
OSFamily: nil,
Arch: nil,
},
},
Count: Count{
Value: aws.Int(1),
},
ExecuteCommand: ExecuteCommand{
Enable: aws.Bool(false),
},
},
Network: NetworkConfig{
VPC: vpcConfig{
Placement: PlacementArgOrString{
PlacementString: placementStringP(PublicSubnetPlacement),
},
},
},
},
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// GIVEN
wantedBytes, err := yaml.Marshal(tc.wantedManifest)
require.NoError(t, err)
// WHEN
actualBytes, err := yaml.Marshal(NewBackendService(tc.inProps))
require.NoError(t, err)
require.Equal(t, string(wantedBytes), string(actualBytes))
})
}
}
func TestBackendService_RequiredEnvironmentFeatures(t *testing.T) {
testCases := map[string]struct {
mft func(svc *BackendService)
wanted []string
}{
"no feature required by default": {
mft: func(svc *BackendService) {},
},
"internal alb feature required": {
mft: func(svc *BackendService) {
svc.HTTP = HTTP{
Main: RoutingRule{
Path: aws.String("/mock_path"),
},
}
},
wanted: []string{template.InternalALBFeatureName},
},
"nat feature required": {
mft: func(svc *BackendService) {
svc.Network = NetworkConfig{
VPC: vpcConfig{
Placement: PlacementArgOrString{
PlacementString: placementStringP(PrivateSubnetPlacement),
},
},
}
},
wanted: []string{template.NATFeatureName},
},
"efs feature required by enabling managed volume": {
mft: func(svc *BackendService) {
svc.Storage = Storage{
Volumes: map[string]*Volume{
"mock-managed-volume-1": {
EFS: EFSConfigOrBool{
Enabled: aws.Bool(true),
},
},
"mock-imported-volume": {
EFS: EFSConfigOrBool{
Advanced: EFSVolumeConfiguration{
FileSystemID: aws.String("mock-id"),
},
},
},
},
}
},
wanted: []string{template.EFSFeatureName},
},
"efs feature not required because storage is imported": {
mft: func(svc *BackendService) {
svc.Storage = Storage{
Volumes: map[string]*Volume{
"mock-imported-volume": {
EFS: EFSConfigOrBool{
Advanced: EFSVolumeConfiguration{
FileSystemID: aws.String("mock-id"),
},
},
},
},
}
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
inSvc := BackendService{
Workload: Workload{
Name: aws.String("mock-svc"),
Type: aws.String(manifestinfo.BackendServiceType),
},
}
tc.mft(&inSvc)
got := inSvc.requiredEnvironmentFeatures()
require.Equal(t, tc.wanted, got)
})
}
}
func TestBackendService_Port(t *testing.T) {
testCases := map[string]struct {
mft *BackendService
wantedPort uint16
wantedOK bool
}{
"sets ok to false if no port is exposed": {
mft: &BackendService{},
},
"returns the port value and sets ok to true if a port is exposed": {
mft: &BackendService{
BackendServiceConfig: BackendServiceConfig{
ImageConfig: ImageWithHealthcheckAndOptionalPort{
ImageWithOptionalPort: ImageWithOptionalPort{
Port: uint16P(80),
},
},
},
},
wantedPort: 80,
wantedOK: true,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// WHEN
actual, ok := tc.mft.Port()
// THEN
require.Equal(t, tc.wantedOK, ok)
require.Equal(t, tc.wantedPort, actual)
})
}
}
func TestBackendService_Publish(t *testing.T) {
testCases := map[string]struct {
mft *BackendService
wantedTopics []Topic
}{
"returns nil if there are no topics set": {
mft: &BackendService{},
},
"returns the list of topics if manifest publishes notifications": {
mft: &BackendService{
BackendServiceConfig: BackendServiceConfig{
PublishConfig: PublishConfig{
Topics: []Topic{
{
Name: stringP("hello"),
},
},
},
},
},
wantedTopics: []Topic{
{
Name: stringP("hello"),
},
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// WHEN
actual := tc.mft.Publish()
// THEN
require.Equal(t, tc.wantedTopics, actual)
})
}
}
func TestBackendSvc_ApplyEnv(t *testing.T) {
perc := Percentage(70)
mockConfig := ScalingConfigOrT[Percentage]{
Value: &perc,
}
mockBackendServiceWithNoEnvironments := BackendService{
Workload: Workload{
Name: aws.String("phonetool"),
Type: aws.String(manifestinfo.BackendServiceType),
},
BackendServiceConfig: BackendServiceConfig{
ImageConfig: ImageWithHealthcheckAndOptionalPort{
ImageWithOptionalPort: ImageWithOptionalPort{
Image: Image{
ImageLocationOrBuild: ImageLocationOrBuild{
Build: BuildArgsOrString{
BuildArgs: DockerBuildArgs{
Dockerfile: aws.String("./Dockerfile"),
},
},
},
},
Port: aws.Uint16(8080),
},
HealthCheck: ContainerHealthCheck{
Command: []string{"hello", "world"},
Interval: durationp(1 * time.Second),
Retries: aws.Int(100),
Timeout: durationp(100 * time.Minute),
StartPeriod: durationp(5 * time.Second),
},
},
TaskConfig: TaskConfig{
CPU: aws.Int(256),
Memory: aws.Int(256),
Count: Count{
Value: aws.Int(1),
},
},
},
}
mockBackendServiceWithNilEnvironment := BackendService{
BackendServiceConfig: BackendServiceConfig{
ImageConfig: ImageWithHealthcheckAndOptionalPort{
ImageWithOptionalPort: ImageWithOptionalPort{
Port: aws.Uint16(80),
},
},
},
Environments: map[string]*BackendServiceConfig{
"test": nil,
},
}
mockBackendServiceWithMinimalOverride := BackendService{
BackendServiceConfig: BackendServiceConfig{
ImageConfig: ImageWithHealthcheckAndOptionalPort{
ImageWithOptionalPort: ImageWithOptionalPort{
Port: aws.Uint16(80),
},
},
},
Environments: map[string]*BackendServiceConfig{
"test": {
ImageConfig: ImageWithHealthcheckAndOptionalPort{
ImageWithOptionalPort: ImageWithOptionalPort{
Port: aws.Uint16(5000),
},
},
},
},
}
mockBackendServiceWithAllOverride := BackendService{
BackendServiceConfig: BackendServiceConfig{
ImageConfig: ImageWithHealthcheckAndOptionalPort{
ImageWithOptionalPort: ImageWithOptionalPort{
Port: aws.Uint16(80),
Image: Image{
DockerLabels: map[string]string{
"com.amazonaws.ecs.copilot.description": "Hello world!",
},
},
},
},
TaskConfig: TaskConfig{
CPU: aws.Int(256),
Memory: aws.Int(256),
Count: Count{
Value: aws.Int(1),
},
},
Sidecars: map[string]*SidecarConfig{
"xray": {
Port: aws.String("2000/udp"),
Image: Union[*string, ImageLocationOrBuild]{
Basic: aws.String("123456789012.dkr.ecr.us-east-2.amazonaws.com/xray-daemon"),
},
},
},
Logging: Logging{
Destination: map[string]string{
"Name": "datadog",
"exclude-pattern": "*",
},
},
},
Environments: map[string]*BackendServiceConfig{
"test": {
ImageConfig: ImageWithHealthcheckAndOptionalPort{
ImageWithOptionalPort: ImageWithOptionalPort{
Image: Image{
DockerLabels: map[string]string{
"com.amazonaws.ecs.copilot.description": "Overridden!",
},
},
},
},
TaskConfig: TaskConfig{
Count: Count{
AdvancedCount: AdvancedCount{
CPU: mockConfig,
},
},
CPU: aws.Int(512),
Variables: map[string]Variable{
"LOG_LEVEL": {
stringOrFromCFN{
Plain: stringP(""),
},
},
},
},
Sidecars: map[string]*SidecarConfig{
"xray": {
CredsParam: aws.String("some arn"),
},
},
Logging: Logging{
Destination: map[string]string{
"include-pattern": "*",
"exclude-pattern": "fe/",
},
},
},
},
}
mockBackendServiceWithImageOverrideBuildByLocation := BackendService{
Workload: Workload{
Name: aws.String("phonetool"),
Type: aws.String(manifestinfo.BackendServiceType),
},
BackendServiceConfig: BackendServiceConfig{
ImageConfig: ImageWithHealthcheckAndOptionalPort{
ImageWithOptionalPort: ImageWithOptionalPort{
Image: Image{
ImageLocationOrBuild: ImageLocationOrBuild{
Build: BuildArgsOrString{
BuildArgs: DockerBuildArgs{
Dockerfile: aws.String("./Dockerfile"),
},
},
},
},
},
},
},
Environments: map[string]*BackendServiceConfig{
"prod-iad": {
ImageConfig: ImageWithHealthcheckAndOptionalPort{
ImageWithOptionalPort: ImageWithOptionalPort{
Image: Image{
ImageLocationOrBuild: ImageLocationOrBuild{
Location: aws.String("env-override location"),
},
},
},
},
},
},
}
mockBackendServiceWithImageOverrideLocationByLocation := BackendService{
Workload: Workload{
Name: aws.String("phonetool"),
Type: aws.String(manifestinfo.BackendServiceType),
},
BackendServiceConfig: BackendServiceConfig{
ImageConfig: ImageWithHealthcheckAndOptionalPort{
ImageWithOptionalPort: ImageWithOptionalPort{
Image: Image{
ImageLocationOrBuild: ImageLocationOrBuild{
Location: aws.String("original location"),
},
},
},
},
},
Environments: map[string]*BackendServiceConfig{
"prod-iad": {
ImageConfig: ImageWithHealthcheckAndOptionalPort{
ImageWithOptionalPort: ImageWithOptionalPort{
Image: Image{
ImageLocationOrBuild: ImageLocationOrBuild{
Location: aws.String("env-override location"),
},
},
},
},
},
},
}
mockBackendServiceWithImageOverrideBuildByBuild := BackendService{
Workload: Workload{
Name: aws.String("phonetool"),
Type: aws.String(manifestinfo.BackendServiceType),
},
BackendServiceConfig: BackendServiceConfig{
ImageConfig: ImageWithHealthcheckAndOptionalPort{
ImageWithOptionalPort: ImageWithOptionalPort{
Image: Image{
ImageLocationOrBuild: ImageLocationOrBuild{
Build: BuildArgsOrString{
BuildArgs: DockerBuildArgs{
Dockerfile: aws.String("original dockerfile"),
Context: aws.String("original context"),
},
},
},
},
},
},
},
Environments: map[string]*BackendServiceConfig{
"prod-iad": {
ImageConfig: ImageWithHealthcheckAndOptionalPort{
ImageWithOptionalPort: ImageWithOptionalPort{
Image: Image{
ImageLocationOrBuild: ImageLocationOrBuild{
Build: BuildArgsOrString{
BuildString: aws.String("env overridden dockerfile"),
},
},
},
},
},
},
},
}
mockBackendServiceWithImageOverrideLocationByBuild := BackendService{
Workload: Workload{
Name: aws.String("phonetool"),
Type: aws.String(manifestinfo.BackendServiceType),
},
BackendServiceConfig: BackendServiceConfig{
ImageConfig: ImageWithHealthcheckAndOptionalPort{
ImageWithOptionalPort: ImageWithOptionalPort{
Image: Image{
ImageLocationOrBuild: ImageLocationOrBuild{
Location: aws.String("original location"),
},
},
},
},
},
Environments: map[string]*BackendServiceConfig{
"prod-iad": {
ImageConfig: ImageWithHealthcheckAndOptionalPort{
ImageWithOptionalPort: ImageWithOptionalPort{
Image: Image{
ImageLocationOrBuild: ImageLocationOrBuild{
Build: BuildArgsOrString{
BuildString: aws.String("env overridden dockerfile"),
},
},
},
},
},
},
},
}
testCases := map[string]struct {
svc *BackendService
inEnvName string
wanted *BackendService
original *BackendService
}{
"no env override": {
svc: &mockBackendServiceWithNoEnvironments,
inEnvName: "test",
wanted: &mockBackendServiceWithNoEnvironments,
original: &mockBackendServiceWithNoEnvironments,
},
"with nil env override": {
svc: &mockBackendServiceWithNilEnvironment,
inEnvName: "test",
wanted: &mockBackendServiceWithNilEnvironment,
original: &mockBackendServiceWithNilEnvironment,
},
"uses env minimal overrides": {
svc: &mockBackendServiceWithMinimalOverride,
inEnvName: "test",
wanted: &BackendService{
BackendServiceConfig: BackendServiceConfig{
ImageConfig: ImageWithHealthcheckAndOptionalPort{
ImageWithOptionalPort: ImageWithOptionalPort{
Port: aws.Uint16(5000),
},
},
},
},
original: &mockBackendServiceWithMinimalOverride,
},
"uses env all overrides": {
svc: &mockBackendServiceWithAllOverride,
inEnvName: "test",
wanted: &BackendService{
BackendServiceConfig: BackendServiceConfig{
ImageConfig: ImageWithHealthcheckAndOptionalPort{
ImageWithOptionalPort: ImageWithOptionalPort{
Port: aws.Uint16(80),
Image: Image{
DockerLabels: map[string]string{
"com.amazonaws.ecs.copilot.description": "Overridden!",
},
},
},
},
TaskConfig: TaskConfig{
CPU: aws.Int(512),
Memory: aws.Int(256),
Count: Count{
AdvancedCount: AdvancedCount{
CPU: mockConfig,
},
},
Variables: map[string]Variable{
"LOG_LEVEL": {
stringOrFromCFN{
Plain: stringP(""),
},
},
},
},
Sidecars: map[string]*SidecarConfig{
"xray": {
Port: aws.String("2000/udp"),
Image: Union[*string, ImageLocationOrBuild]{
Basic: aws.String("123456789012.dkr.ecr.us-east-2.amazonaws.com/xray-daemon"),
},
CredsParam: aws.String("some arn"),
},
},
Logging: Logging{
Destination: map[string]string{
"Name": "datadog",
"include-pattern": "*",
"exclude-pattern": "fe/",
},
},
},
},
original: &mockBackendServiceWithAllOverride,
},
"with image build overridden by image location": {
svc: &mockBackendServiceWithImageOverrideBuildByLocation,
inEnvName: "prod-iad",
wanted: &BackendService{
Workload: Workload{
Name: aws.String("phonetool"),
Type: aws.String(manifestinfo.BackendServiceType),
},
BackendServiceConfig: BackendServiceConfig{
ImageConfig: ImageWithHealthcheckAndOptionalPort{
ImageWithOptionalPort: ImageWithOptionalPort{
Image: Image{
ImageLocationOrBuild: ImageLocationOrBuild{
Location: aws.String("env-override location"),
},
},
},
},
},
},
original: &mockBackendServiceWithImageOverrideBuildByLocation,
},
"with image location overridden by image location": {
svc: &mockBackendServiceWithImageOverrideLocationByLocation,
inEnvName: "prod-iad",
wanted: &BackendService{
Workload: Workload{
Name: aws.String("phonetool"),
Type: aws.String(manifestinfo.BackendServiceType),
},
BackendServiceConfig: BackendServiceConfig{
ImageConfig: ImageWithHealthcheckAndOptionalPort{
ImageWithOptionalPort: ImageWithOptionalPort{
Image: Image{
ImageLocationOrBuild: ImageLocationOrBuild{
Location: aws.String("env-override location"),
},
},
},
},
},
},
original: &mockBackendServiceWithImageOverrideLocationByLocation,
},
"with image build overridden by image build": {
svc: &mockBackendServiceWithImageOverrideBuildByBuild,
inEnvName: "prod-iad",
wanted: &BackendService{
Workload: Workload{
Name: aws.String("phonetool"),
Type: aws.String(manifestinfo.BackendServiceType),
},
BackendServiceConfig: BackendServiceConfig{
ImageConfig: ImageWithHealthcheckAndOptionalPort{
ImageWithOptionalPort: ImageWithOptionalPort{
Image: Image{
ImageLocationOrBuild: ImageLocationOrBuild{
Build: BuildArgsOrString{
BuildString: aws.String("env overridden dockerfile"),
},
},
},
},
},
},
},
original: &mockBackendServiceWithImageOverrideBuildByBuild,
},
"with image location overridden by image build": {
svc: &mockBackendServiceWithImageOverrideLocationByBuild,
inEnvName: "prod-iad",
wanted: &BackendService{
Workload: Workload{
Name: aws.String("phonetool"),
Type: aws.String(manifestinfo.BackendServiceType),
},
BackendServiceConfig: BackendServiceConfig{
ImageConfig: ImageWithHealthcheckAndOptionalPort{
ImageWithOptionalPort: ImageWithOptionalPort{
Image: Image{
ImageLocationOrBuild: ImageLocationOrBuild{
Build: BuildArgsOrString{
BuildString: aws.String("env overridden dockerfile"),
},
},
},
},
},
},
},
original: &mockBackendServiceWithImageOverrideLocationByBuild,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
got, _ := tc.svc.applyEnv(tc.inEnvName)
// Should override properly.
require.Equal(t, tc.wanted, got)
// Should not impact the original manifest struct.
require.Equal(t, tc.svc, tc.original)
})
}
}
func TestBackendSvc_ApplyEnv_CountOverrides(t *testing.T) {
mockRange := IntRangeBand("1-10")
perc := Percentage(80)
mockConfig := ScalingConfigOrT[Percentage]{
Value: &perc,
}
testCases := map[string]struct {
svcCount Count
envCount Count
expected *BackendService
}{
"empty env advanced count override": {
svcCount: Count{
AdvancedCount: AdvancedCount{
Range: Range{Value: &mockRange},
CPU: mockConfig,
},
},
envCount: Count{},
expected: &BackendService{
BackendServiceConfig: BackendServiceConfig{
TaskConfig: TaskConfig{
Count: Count{
AdvancedCount: AdvancedCount{
Range: Range{Value: &mockRange},
CPU: mockConfig,
},
},
},
},
},
},
"with count value overriden by count value": {
svcCount: Count{Value: aws.Int(5)},
envCount: Count{Value: aws.Int(8)},
expected: &BackendService{
BackendServiceConfig: BackendServiceConfig{
TaskConfig: TaskConfig{
Count: Count{Value: aws.Int(8)},
},
},
},
},
"with count value overriden by spot count": {
svcCount: Count{Value: aws.Int(4)},
envCount: Count{
AdvancedCount: AdvancedCount{
Spot: aws.Int(6),
},
},
expected: &BackendService{
BackendServiceConfig: BackendServiceConfig{
TaskConfig: TaskConfig{
Count: Count{
AdvancedCount: AdvancedCount{
Spot: aws.Int(6),
},
},
},
},
},
},
"with range overriden by spot count": {
svcCount: Count{
AdvancedCount: AdvancedCount{
Range: Range{Value: &mockRange},
},
},
envCount: Count{
AdvancedCount: AdvancedCount{
Spot: aws.Int(6),
},
},
expected: &BackendService{
BackendServiceConfig: BackendServiceConfig{
TaskConfig: TaskConfig{
Count: Count{
AdvancedCount: AdvancedCount{
Spot: aws.Int(6),
},
},
},
},
},
},
"with range overriden by range config": {
svcCount: Count{
AdvancedCount: AdvancedCount{
Range: Range{Value: &mockRange},
},
},
envCount: Count{
AdvancedCount: AdvancedCount{
Range: Range{
RangeConfig: RangeConfig{
Min: aws.Int(2),
Max: aws.Int(8),
},
},
},
},
expected: &BackendService{
BackendServiceConfig: BackendServiceConfig{
TaskConfig: TaskConfig{
Count: Count{
AdvancedCount: AdvancedCount{
Range: Range{
RangeConfig: RangeConfig{
Min: aws.Int(2),
Max: aws.Int(8),
},
},
},
},
},
},
},
},
"with spot overriden by count value": {
svcCount: Count{
AdvancedCount: AdvancedCount{
Spot: aws.Int(5),
},
},
envCount: Count{Value: aws.Int(12)},
expected: &BackendService{
BackendServiceConfig: BackendServiceConfig{
TaskConfig: TaskConfig{
Count: Count{Value: aws.Int(12)},
},
},
},
},
}
for name, tc := range testCases {
// GIVEN
svc := BackendService{
BackendServiceConfig: BackendServiceConfig{
TaskConfig: TaskConfig{
Count: tc.svcCount,
},
},
Environments: map[string]*BackendServiceConfig{
"test": {
TaskConfig: TaskConfig{
Count: tc.envCount,
},
},
"staging": {
TaskConfig: TaskConfig{},
},
},
}
t.Run(name, func(t *testing.T) {
// WHEN
actual, _ := svc.applyEnv("test")
// THEN
require.Equal(t, tc.expected, actual)
})
}
}
func TestBackendService_ExposedPorts(t *testing.T) {
testCases := map[string]struct {
mft *BackendService
wantedExposedPorts map[string][]ExposedPort
}{
"expose primary container port through target_port": {
mft: &BackendService{
Workload: Workload{
Name: aws.String("frontend"),
},
BackendServiceConfig: BackendServiceConfig{
ImageConfig: ImageWithHealthcheckAndOptionalPort{},
HTTP: HTTP{
Main: RoutingRule{
TargetPort: aws.Uint16(81),
},
},
Sidecars: map[string]*SidecarConfig{
"xray": {
Port: aws.String("2000"),
Image: Union[*string, ImageLocationOrBuild]{
Basic: aws.String("123456789012.dkr.ecr.us-east-2.amazonaws.com/xray-daemon"),
},
CredsParam: aws.String("some arn"),
},
},
},
},
wantedExposedPorts: map[string][]ExposedPort{
"frontend": {
{
Port: 81,
ContainerName: "frontend",
Protocol: "tcp",
},
},
"xray": {
{
Port: 2000,
ContainerName: "xray",
Protocol: "tcp",
isDefinedByContainer: true,
},
},
},
},
"expose two primary container port internally through image.port and target_port": {
mft: &BackendService{
Workload: Workload{
Name: aws.String("frontend"),
},
BackendServiceConfig: BackendServiceConfig{
ImageConfig: ImageWithHealthcheckAndOptionalPort{
ImageWithOptionalPort: ImageWithOptionalPort{
Port: aws.Uint16(80),
},
},
HTTP: HTTP{
Main: RoutingRule{
TargetPort: aws.Uint16(81),
},
},
Sidecars: map[string]*SidecarConfig{
"xray": {
Port: aws.String("2000"),
Image: Union[*string, ImageLocationOrBuild]{
Basic: aws.String("123456789012.dkr.ecr.us-east-2.amazonaws.com/xray-daemon"),
},
CredsParam: aws.String("some arn"),
},
},
},
},
wantedExposedPorts: map[string][]ExposedPort{
"frontend": {
{
Port: 80,
ContainerName: "frontend",
Protocol: "tcp",
isDefinedByContainer: true,
},
{
Port: 81,
ContainerName: "frontend",
Protocol: "tcp",
},
},
"xray": {
{
Port: 2000,
ContainerName: "xray",
Protocol: "tcp",
isDefinedByContainer: true,
},
},
},
},
"expose two primary container port internally through image.port and target_port and target_container": {
mft: &BackendService{
Workload: Workload{
Name: aws.String("frontend"),
},
BackendServiceConfig: BackendServiceConfig{
ImageConfig: ImageWithHealthcheckAndOptionalPort{
ImageWithOptionalPort: ImageWithOptionalPort{
Port: aws.Uint16(80),
},
},
HTTP: HTTP{
Main: RoutingRule{
TargetContainer: aws.String("frontend"),
TargetPort: aws.Uint16(81),
},
},
Sidecars: map[string]*SidecarConfig{
"xray": {
Port: aws.String("2000"),
Image: Union[*string, ImageLocationOrBuild]{
Basic: aws.String("123456789012.dkr.ecr.us-east-2.amazonaws.com/xray-daemon"),
},
CredsParam: aws.String("some arn"),
},
},
},
},
wantedExposedPorts: map[string][]ExposedPort{
"frontend": {
{
Port: 80,
ContainerName: "frontend",
Protocol: "tcp",
isDefinedByContainer: true,
},
{
Port: 81,
ContainerName: "frontend",
Protocol: "tcp",
},
},
"xray": {
{
Port: 2000,
ContainerName: "xray",
Protocol: "tcp",
isDefinedByContainer: true,
},
},
},
},
"expose primary container port through image.port and sidecar container port through target_port and target_container": {
mft: &BackendService{
Workload: Workload{
Name: aws.String("frontend"),
},
BackendServiceConfig: BackendServiceConfig{
ImageConfig: ImageWithHealthcheckAndOptionalPort{
ImageWithOptionalPort: ImageWithOptionalPort{
Port: aws.Uint16(80),
},
},
HTTP: HTTP{
Main: RoutingRule{
TargetContainer: aws.String("xray"),
TargetPort: aws.Uint16(81),
},
},
Sidecars: map[string]*SidecarConfig{
"xray": {
Image: Union[*string, ImageLocationOrBuild]{
Advanced: ImageLocationOrBuild{
Location: aws.String("123456789012.dkr.ecr.us-east-2.amazonaws.com/xray-daemon"),
},
},
CredsParam: aws.String("some arn"),
},
},
},
},
wantedExposedPorts: map[string][]ExposedPort{
"frontend": {
{
Port: 80,
ContainerName: "frontend",
Protocol: "tcp",
isDefinedByContainer: true,
},
},
"xray": {
{
Port: 81,
ContainerName: "xray",
Protocol: "tcp",
},
},
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
// WHEN
actual, err := tc.mft.ExposedPorts()
// THEN
require.NoError(t, err)
require.Equal(t, tc.wantedExposedPorts, actual.PortsForContainer)
})
}
}
| 1,211 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.