This repository has been archived by the owner on Oct 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 63
/
cloud_watch_scheduler.go
297 lines (271 loc) · 11.8 KB
/
cloud_watch_scheduler.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
287
288
289
290
291
292
293
294
295
296
297
package aws
import (
"context"
"fmt"
"strings"
"github.com/flyteorg/flyteadmin/pkg/async/schedule/aws/interfaces"
scheduleInterfaces "github.com/flyteorg/flyteadmin/pkg/async/schedule/interfaces"
"github.com/flyteorg/flyteadmin/pkg/errors"
appInterfaces "github.com/flyteorg/flyteadmin/pkg/runtime/interfaces"
"github.com/flyteorg/flyteidl/gen/pb-go/flyteidl/admin"
"github.com/flyteorg/flyteidl/gen/pb-go/flyteidl/core"
"github.com/flyteorg/flytestdlib/logger"
"github.com/flyteorg/flytestdlib/promutils"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatchevents"
"github.com/prometheus/client_golang/prometheus"
"google.golang.org/grpc/codes"
)
// To indicate that a schedule rule is enabled.
var enableState = "ENABLED"
// CloudWatch schedule expressions.
const (
cronExpression = "cron(%s)"
rateExpression = "rate(%v %s)"
)
const timePlaceholder = "time"
var timeValue = "$.time"
const scheduleNameInputsFormat = "%s:%s:%s"
const scheduleDescriptionFormat = "Schedule for Project:%s Domain:%s Name:%s launch plan"
const scheduleNameFormat = "%s_%d"
// Container for initialized metrics objects
type cloudWatchSchedulerMetrics struct {
Scope promutils.Scope
InvalidSchedules prometheus.Counter
AddRuleFailures prometheus.Counter
AddTargetFailures prometheus.Counter
SchedulesAdded prometheus.Counter
RemoveRuleFailures prometheus.Counter
RemoveRuleDoesntExist prometheus.Counter
RemoveTargetFailures prometheus.Counter
RemoveTargetDoesntExist prometheus.Counter
RemovedSchedules prometheus.Counter
ActiveSchedules prometheus.Gauge
}
// An AWS CloudWatch implementation of the EventScheduler.
type cloudWatchScheduler struct {
// The ARN of the IAM role associated with the scheduler.
scheduleRoleArn string
// The ARN of the SQS target used for registering schedule events.
targetSqsArn string
// AWS CloudWatchEvents service client.
cloudWatchEventClient interfaces.CloudWatchEventClient
// For emitting scheduler-related metrics
metrics cloudWatchSchedulerMetrics
}
func getScheduleName(scheduleNamePrefix string, identifier core.Identifier) string {
hashedIdentifier := hashIdentifier(identifier)
if len(scheduleNamePrefix) > 0 {
return fmt.Sprintf(scheduleNameFormat, scheduleNamePrefix, hashedIdentifier)
}
return fmt.Sprintf("%d", hashedIdentifier)
}
func getScheduleDescription(identifier core.Identifier) string {
return fmt.Sprintf(scheduleDescriptionFormat,
identifier.Project, identifier.Domain, identifier.Name)
}
func getScheduleExpression(schedule admin.Schedule) (string, error) {
if schedule.GetCronExpression() != "" {
return fmt.Sprintf(cronExpression, schedule.GetCronExpression()), nil
}
if schedule.GetRate() != nil {
// AWS uses pluralization for units of values not equal to 1.
// See https://docs.aws.amazon.com/lambda/latest/dg/tutorial-scheduled-events-schedule-expressions.html
unit := strings.ToLower(schedule.GetRate().Unit.String())
if schedule.GetRate().Value != 1 {
unit = fmt.Sprintf("%ss", unit)
}
return fmt.Sprintf(rateExpression, schedule.GetRate().Value, unit), nil
}
logger.Debugf(context.Background(), "scheduler encountered invalid schedule expression: %s", schedule.String())
return "", errors.NewFlyteAdminErrorf(codes.InvalidArgument, "unrecognized schedule expression")
}
func formatEventScheduleInputs(inputTemplate *string) cloudwatchevents.InputTransformer {
inputsPathMap := map[string]*string{
timePlaceholder: &timeValue,
}
return cloudwatchevents.InputTransformer{
InputPathsMap: inputsPathMap,
InputTemplate: inputTemplate,
}
}
func (s *cloudWatchScheduler) AddSchedule(ctx context.Context, input scheduleInterfaces.AddScheduleInput) error {
if input.Payload == nil {
logger.Debugf(ctx, "AddSchedule called with empty input payload: %+v", input)
return errors.NewFlyteAdminError(codes.InvalidArgument, "payload serialization function cannot be nil")
}
scheduleExpression, err := getScheduleExpression(input.ScheduleExpression)
if err != nil {
s.metrics.InvalidSchedules.Inc()
return err
}
scheduleName := getScheduleName(input.ScheduleNamePrefix, input.Identifier)
scheduleDescription := getScheduleDescription(input.Identifier)
// First define a rule which gets triggered on a schedule.
requestInput := cloudwatchevents.PutRuleInput{
ScheduleExpression: &scheduleExpression,
Name: &scheduleName,
Description: &scheduleDescription,
RoleArn: &s.scheduleRoleArn,
State: &enableState,
}
putRuleOutput, err := s.cloudWatchEventClient.PutRule(&requestInput)
if err != nil {
logger.Infof(ctx, "Failed to add rule to cloudwatch for schedule [%+v] with name %s and expression %s with err: %v",
input.Identifier, scheduleName, scheduleExpression, err)
s.metrics.AddRuleFailures.Inc()
return errors.NewFlyteAdminErrorf(codes.Internal, "failed to add rule to cloudwatch with err: %v", err)
}
eventInputTransformer := formatEventScheduleInputs(input.Payload)
// Next, add a target which gets invoked when the above rule is triggered.
putTargetOutput, err := s.cloudWatchEventClient.PutTargets(&cloudwatchevents.PutTargetsInput{
Rule: &scheduleName,
Targets: []*cloudwatchevents.Target{
{
Arn: &s.targetSqsArn,
Id: &scheduleName,
InputTransformer: &eventInputTransformer,
},
},
})
if err != nil {
logger.Infof(ctx, "Failed to add target for event schedule [%+v] with name %s with err: %v",
input.Identifier, scheduleName, err)
s.metrics.AddTargetFailures.Inc()
return errors.NewFlyteAdminErrorf(codes.Internal, "failed to add target for event schedule with err: %v", err)
} else if putTargetOutput.FailedEntryCount != nil && *putTargetOutput.FailedEntryCount > 0 {
logger.Infof(ctx, "Failed to add target for event schedule [%+v] with name %s with failed entries: %d",
input.Identifier, scheduleName, *putTargetOutput.FailedEntryCount)
s.metrics.AddTargetFailures.Inc()
return errors.NewFlyteAdminErrorf(codes.Internal,
"failed to add target for event schedule with %v errs", *putTargetOutput.FailedEntryCount)
}
var putRuleOutputName string
if putRuleOutput != nil && putRuleOutput.RuleArn != nil {
putRuleOutputName = *putRuleOutput.RuleArn
}
logger.Debugf(ctx, "Added schedule %s [%s] with arn: %s (%s)",
scheduleName, scheduleExpression, putRuleOutputName, scheduleDescription)
s.metrics.SchedulesAdded.Inc()
s.metrics.ActiveSchedules.Inc()
return nil
}
func (s *cloudWatchScheduler) CreateScheduleInput(ctx context.Context, appConfig *appInterfaces.SchedulerConfig,
identifier core.Identifier, schedule *admin.Schedule) (scheduleInterfaces.AddScheduleInput, error) {
payload, err := SerializeScheduleWorkflowPayload(
schedule.GetKickoffTimeInputArg(),
admin.NamedEntityIdentifier{
Project: identifier.Project,
Domain: identifier.Domain,
Name: identifier.Name,
})
if err != nil {
logger.Errorf(ctx, "failed to serialize schedule workflow payload for launch plan: %v with err: %v",
identifier, err)
return scheduleInterfaces.AddScheduleInput{}, err
}
// Backward compatible with old EvenSchedulerConfig structure
scheduleNamePrefix := appConfig.EventSchedulerConfig.GetScheduleNamePrefix()
if appConfig.EventSchedulerConfig.GetAWSSchedulerConfig() != nil {
scheduleNamePrefix = appConfig.EventSchedulerConfig.GetAWSSchedulerConfig().GetScheduleNamePrefix()
}
addScheduleInput := scheduleInterfaces.AddScheduleInput{
Identifier: identifier,
ScheduleExpression: *schedule,
Payload: payload,
ScheduleNamePrefix: scheduleNamePrefix,
}
return addScheduleInput, nil
}
func isResourceNotFoundException(err error) bool {
switch err := err.(type) {
case awserr.Error:
return err.Code() == cloudwatchevents.ErrCodeResourceNotFoundException
}
return false
}
func (s *cloudWatchScheduler) RemoveSchedule(ctx context.Context, input scheduleInterfaces.RemoveScheduleInput) error {
name := getScheduleName(input.ScheduleNamePrefix, input.Identifier)
// All outbound targets for a rule must be deleted before the rule itself can be deleted.
output, err := s.cloudWatchEventClient.RemoveTargets(&cloudwatchevents.RemoveTargetsInput{
Ids: []*string{
&name,
},
Rule: &name,
})
if err != nil {
if isResourceNotFoundException(err) {
s.metrics.RemoveTargetDoesntExist.Inc()
logger.Debugf(ctx, "Tried to remove cloudwatch target %s but it was not found", name)
} else {
s.metrics.RemoveTargetFailures.Inc()
logger.Errorf(ctx, "failed to remove cloudwatch target %s with err: %v", name, err)
return errors.NewFlyteAdminErrorf(codes.Internal, "failed to remove cloudwatch target %s with err: %v", name, err)
}
}
if output != nil && output.FailedEntryCount != nil && *output.FailedEntryCount > 0 {
s.metrics.RemoveTargetFailures.Inc()
logger.Errorf(ctx, "failed to remove cloudwatch target %s with %v errs",
name, *output.FailedEntryCount)
return errors.NewFlyteAdminErrorf(codes.Internal, "failed to remove cloudwatch target %s with %v errs",
name, *output.FailedEntryCount)
}
// Output from the call to DeleteRule is an empty struct.
_, err = s.cloudWatchEventClient.DeleteRule(&cloudwatchevents.DeleteRuleInput{
Name: &name,
})
if err != nil {
if isResourceNotFoundException(err) {
s.metrics.RemoveRuleDoesntExist.Inc()
logger.Debugf(ctx, "Tried to remove cloudwatch rule %s but it was not found", name)
} else {
s.metrics.RemoveRuleFailures.Inc()
logger.Errorf(ctx, "failed to remove cloudwatch rule %s with err: %v", name, err)
return errors.NewFlyteAdminErrorf(codes.Internal,
"failed to remove cloudwatch rule %s with err: %v", name, err)
}
}
s.metrics.RemovedSchedules.Inc()
s.metrics.ActiveSchedules.Dec()
logger.Debugf(ctx, "Removed schedule %s for identifier [%+v]", name, input.Identifier)
return nil
}
// Initializes a new set of metrics specific to the cloudwatch scheduler implementation.
func newCloudWatchSchedulerMetrics(scope promutils.Scope) cloudWatchSchedulerMetrics {
return cloudWatchSchedulerMetrics{
Scope: scope,
InvalidSchedules: scope.MustNewCounter("schedules_invalid", "count of invalid schedule expressions submitted"),
AddRuleFailures: scope.MustNewCounter("add_rule_failures",
"count of attempts to add a cloudwatch rule that have failed"),
AddTargetFailures: scope.MustNewCounter("add_target_failures",
"count of attempts to add a cloudwatch target that have failed"),
SchedulesAdded: scope.MustNewCounter("schedules_added",
"count of all schedules successfully added to cloudwatch"),
RemoveRuleFailures: scope.MustNewCounter("delete_rule_failures",
"count of attempts to remove a cloudwatch rule that have failed"),
RemoveRuleDoesntExist: scope.MustNewCounter("delete_rule_no_rule",
"count of attempts to remove a cloudwatch rule that doesn't exist"),
RemoveTargetFailures: scope.MustNewCounter("delete_target_failures",
"count of attempts to remove a cloudwatch target that have failed"),
RemoveTargetDoesntExist: scope.MustNewCounter("delete_target_no_target",
"count of attempts to remove a cloudwatch target that doesn't exist"),
RemovedSchedules: scope.MustNewCounter("schedules_removed",
"count of all schedules successfully removed from cloudwatch"),
ActiveSchedules: scope.MustNewGauge("active_schedules",
"count of all active schedules currently in cloudwatch"),
}
}
func NewCloudWatchScheduler(
scheduleRoleArn, targetSqsArn string, session *session.Session, config *aws.Config,
scope promutils.Scope) scheduleInterfaces.EventScheduler {
cloudwatchEventClient := cloudwatchevents.New(session, config)
metrics := newCloudWatchSchedulerMetrics(scope)
return &cloudWatchScheduler{
scheduleRoleArn: scheduleRoleArn,
targetSqsArn: targetSqsArn,
cloudWatchEventClient: cloudwatchEventClient,
metrics: metrics,
}
}