-
Notifications
You must be signed in to change notification settings - Fork 392
/
job_logs.go
286 lines (255 loc) · 8.63 KB
/
job_logs.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package cli
import (
"errors"
"fmt"
"github.com/aws/aws-sdk-go/service/ssm"
"github.com/aws/copilot-cli/internal/pkg/aws/identity"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/copilot-cli/internal/pkg/aws/sessions"
"github.com/aws/copilot-cli/internal/pkg/config"
"github.com/aws/copilot-cli/internal/pkg/deploy"
"github.com/aws/copilot-cli/internal/pkg/logging"
"github.com/aws/copilot-cli/internal/pkg/term/log"
"github.com/aws/copilot-cli/internal/pkg/term/prompt"
"github.com/aws/copilot-cli/internal/pkg/term/selector"
"github.com/spf13/cobra"
)
const (
jobAppNamePrompt = "Which application does your job belong to?"
jobLogNamePrompt = "Which job's logs would you like to show?"
jobLogNameHelpPrompt = "The logs of the indicated deployed job will be shown."
defaultJobLogExecutionLimit = 1
)
type jobLogsVars struct {
wkldLogsVars
includeStateMachineLogs bool // Whether to include the logs from the state machine log streams
last int // The number of previous executions of the state machine to show.
}
type jobLogsOpts struct {
jobLogsVars
wkldLogOpts
// Cached variables.
targetEnv *config.Environment
}
func newJobLogOpts(vars jobLogsVars) (*jobLogsOpts, error) {
sessProvider := sessions.ImmutableProvider(sessions.UserAgentExtras("job logs"))
defaultSess, err := sessProvider.Default()
if err != nil {
return nil, err
}
configStore := config.NewSSMStore(identity.New(defaultSess), ssm.New(defaultSess), aws.StringValue(defaultSess.Config.Region))
deployStore, err := deploy.NewStore(sessProvider, configStore)
if err != nil {
return nil, fmt.Errorf("connect to deploy store: %w", err)
}
opts := &jobLogsOpts{
jobLogsVars: vars,
wkldLogOpts: wkldLogOpts{
w: log.OutputWriter,
configStore: configStore,
deployStore: deployStore,
sel: selector.NewDeploySelect(prompt.New(), configStore, deployStore),
},
}
opts.initLogsSvc = func() error {
env, err := opts.getTargetEnv()
if err != nil {
return fmt.Errorf("get environment: %w", err)
}
sess, err := sessProvider.FromRole(env.ManagerRoleARN, env.Region)
if err != nil {
return err
}
opts.logsSvc, err = logging.NewWorkloadClient(&logging.NewWorkloadLogsConfig{
Sess: sess,
App: opts.appName,
Env: opts.envName,
Name: opts.name,
LogGroup: opts.logGroup,
TaskIDs: opts.taskIDs,
ConfigStore: configStore,
})
if err != nil {
return err
}
return nil
}
return opts, nil
}
// Validate returns an error if the values provided by flags are invalid.
func (o *jobLogsOpts) Validate() error {
if o.appName != "" {
if _, err := o.configStore.GetApplication(o.appName); err != nil {
return err
}
if o.envName != "" {
if _, err := o.configStore.GetEnvironment(o.appName, o.envName); err != nil {
return err
}
}
if o.name != "" {
if _, err := o.configStore.GetJob(o.appName, o.name); err != nil {
return err
}
}
}
if o.since != 0 && o.humanStartTime != "" {
return errors.New("only one of --since or --start-time may be used")
}
if o.humanEndTime != "" && o.follow {
return errors.New("only one of --follow or --end-time may be used")
}
if o.since != 0 {
if o.since < 0 {
return fmt.Errorf("--since must be greater than 0")
}
// round up to the nearest second
o.startTime = parseSince(o.since)
}
if o.humanStartTime != "" {
startTime, err := parseRFC3339(o.humanStartTime)
if err != nil {
return fmt.Errorf(`invalid argument %s for "--start-time" flag: %w`, o.humanStartTime, err)
}
o.startTime = aws.Int64(startTime)
}
if o.humanEndTime != "" {
endTime, err := parseRFC3339(o.humanEndTime)
if err != nil {
return fmt.Errorf(`invalid argument %s for "--end-time" flag: %w`, o.humanEndTime, err)
}
o.endTime = aws.Int64(endTime)
}
if o.limit != 0 && (o.limit < cwGetLogEventsLimitMin || o.limit > cwGetLogEventsLimitMax) {
return fmt.Errorf("--limit %d is out-of-bounds, value must be between %d and %d", o.limit, cwGetLogEventsLimitMin, cwGetLogEventsLimitMax)
}
return nil
}
// Ask asks for fields that are required but not passed in.
func (o *jobLogsOpts) Ask() error {
if err := o.validateOrAskApp(); err != nil {
return err
}
return o.validateAndAskJobEnvName()
}
// Execute outputs logs of the job.
func (o *jobLogsOpts) Execute() error {
if err := o.initLogsSvc(); err != nil {
return err
}
eventsWriter := logging.WriteHumanLogs
if o.shouldOutputJSON {
eventsWriter = logging.WriteJSONLogs
}
var limit *int64
if o.limit != 0 {
limit = aws.Int64(int64(o.limit))
}
// By default, only display the logs of the last execution of the job.
logStreamLimit := defaultJobLogExecutionLimit
if o.last != 0 {
logStreamLimit = o.last
}
err := o.logsSvc.WriteLogEvents(logging.WriteLogEventsOpts{
Follow: o.follow,
Limit: limit,
EndTime: o.endTime,
StartTime: o.startTime,
TaskIDs: o.taskIDs,
OnEvents: eventsWriter,
LogStreamLimit: logStreamLimit,
IncludeStateMachineLogs: o.includeStateMachineLogs,
})
if err != nil {
return fmt.Errorf("write log events for job %s: %w", o.name, err)
}
return nil
}
func (o *jobLogsOpts) getTargetEnv() (*config.Environment, error) {
if o.targetEnv != nil {
return o.targetEnv, nil
}
env, err := o.configStore.GetEnvironment(o.appName, o.envName)
if err != nil {
return nil, err
}
o.targetEnv = env
return o.targetEnv, nil
}
func (o *jobLogsOpts) validateOrAskApp() error {
if o.appName != "" {
_, err := o.configStore.GetApplication(o.appName)
return err
}
app, err := o.sel.Application(jobAppNamePrompt, wkldAppNameHelpPrompt)
if err != nil {
return fmt.Errorf("select application: %w", err)
}
o.appName = app
return nil
}
func (o *jobLogsOpts) validateAndAskJobEnvName() error {
if o.envName != "" {
if _, err := o.getTargetEnv(); err != nil {
return err
}
}
if o.name != "" {
if _, err := o.configStore.GetJob(o.appName, o.name); err != nil {
return err
}
}
deployedJob, err := o.sel.DeployedJob(jobLogNamePrompt, jobLogNameHelpPrompt, o.appName, selector.WithEnv(o.envName), selector.WithName(o.name))
if err != nil {
return fmt.Errorf("select deployed jobs for application %s: %w", o.appName, err)
}
o.name = deployedJob.Name
o.envName = deployedJob.Env
return nil
}
// buildJobLogsCmd builds the command for displaying job logs in an application.
func buildJobLogsCmd() *cobra.Command {
vars := jobLogsVars{}
cmd := &cobra.Command{
Use: "logs",
Short: "Displays logs of a deployed job.",
Example: `
Displays logs of the job "my-job" in environment "test".
/code $ copilot job logs -n my-job -e test
Displays logs in the last hour.
/code $ copilot job logs --since 1h
Displays logs from the last execution of the job.
/code $ copilot job logs --last 1
Displays logs from specific task IDs.
/code $ copilot job logs --tasks 709c7ea,1de57fd
Displays logs in real time.
/code $ copilot job logs --follow
Displays container logs and state machine execution logs from the last execution.
/code $ copilot job logs --include-state-machine --last 1`,
RunE: runCmdE(func(cmd *cobra.Command, args []string) error {
opts, err := newJobLogOpts(vars)
if err != nil {
return err
}
return run(opts)
}),
}
cmd.Flags().StringVarP(&vars.name, nameFlag, nameFlagShort, "", svcFlagDescription)
cmd.Flags().StringVarP(&vars.envName, envFlag, envFlagShort, "", envFlagDescription)
cmd.Flags().StringVarP(&vars.appName, appFlag, appFlagShort, tryReadingAppName(), appFlagDescription)
cmd.Flags().StringVar(&vars.humanStartTime, startTimeFlag, "", startTimeFlagDescription)
cmd.Flags().StringVar(&vars.humanEndTime, endTimeFlag, "", endTimeFlagDescription)
cmd.Flags().BoolVar(&vars.shouldOutputJSON, jsonFlag, false, jsonFlagDescription)
cmd.Flags().BoolVar(&vars.follow, followFlag, false, followFlagDescription)
cmd.Flags().DurationVar(&vars.since, sinceFlag, 0, sinceFlagDescription)
cmd.Flags().IntVar(&vars.limit, limitFlag, 0, limitFlagDescription)
cmd.Flags().IntVar(&vars.last, lastFlag, 1, lastFlagDescription)
cmd.Flags().StringSliceVar(&vars.taskIDs, tasksFlag, nil, tasksLogsFlagDescription)
cmd.Flags().BoolVar(&vars.includeStateMachineLogs, includeStateMachineLogsFlag, false, includeStateMachineLogsFlagDescription)
// There's no way to associate a specific execution with a task without parsing the logs of every state machine invocation.
cmd.MarkFlagsMutuallyExclusive(includeStateMachineLogsFlag, tasksFlag)
cmd.MarkFlagsMutuallyExclusive(followFlag, lastFlag)
return cmd
}