-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathsubmit-job.ts
327 lines (291 loc) · 9.77 KB
/
submit-job.ts
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
import * as ec2 from '@aws-cdk/aws-ec2';
import * as iam from '@aws-cdk/aws-iam';
import * as sfn from '@aws-cdk/aws-stepfunctions';
import { Size, Stack, withResolved } from '@aws-cdk/core';
import { Construct } from 'constructs';
import { integrationResourceArn, validatePatternSupported } from '../private/task-utils';
/**
* The overrides that should be sent to a container.
*/
export interface BatchContainerOverrides {
/**
* The command to send to the container that overrides
* the default command from the Docker image or the job definition.
*
* @default - No command overrides
*/
readonly command?: string[];
/**
* The environment variables to send to the container.
* You can add new environment variables, which are added to the container
* at launch, or you can override the existing environment variables from
* the Docker image or the job definition.
*
* @default - No environment overrides
*/
readonly environment?: { [key: string]: string };
/**
* The instance type to use for a multi-node parallel job.
* This parameter is not valid for single-node container jobs.
*
* @default - No instance type overrides
*/
readonly instanceType?: ec2.InstanceType;
/**
* Memory reserved for the job.
*
* @default - No memory overrides. The memory supplied in the job definition will be used.
*/
readonly memory?: Size;
/**
* The number of physical GPUs to reserve for the container.
* The number of GPUs reserved for all containers in a job
* should not exceed the number of available GPUs on the compute
* resource that the job is launched on.
*
* @default - No GPU reservation
*/
readonly gpuCount?: number;
/**
* The number of vCPUs to reserve for the container.
* This value overrides the value set in the job definition.
*
* @default - No vCPUs overrides
*/
readonly vcpus?: number;
}
/**
* An object representing an AWS Batch job dependency.
*/
export interface BatchJobDependency {
/**
* The job ID of the AWS Batch job associated with this dependency.
*
* @default - No jobId
*/
readonly jobId?: string;
/**
* The type of the job dependency.
*
* @default - No type
*/
readonly type?: string;
}
/**
* Properties for RunBatchJob
*
*/
export interface BatchSubmitJobProps extends sfn.TaskStateBaseProps {
/**
* The arn of the job definition used by this job.
*/
readonly jobDefinitionArn: string;
/**
* The name of the job.
* The first character must be alphanumeric, and up to 128 letters (uppercase and lowercase),
* numbers, hyphens, and underscores are allowed.
*/
readonly jobName: string;
/**
* The arn of the job queue into which the job is submitted.
*/
readonly jobQueueArn: string;
/**
* The array size can be between 2 and 10,000.
* If you specify array properties for a job, it becomes an array job.
* For more information, see Array Jobs in the AWS Batch User Guide.
*
* @default - No array size
*/
readonly arraySize?: number;
/**
* A list of container overrides in JSON format that specify the name of a container
* in the specified job definition and the overrides it should receive.
*
* @see https://docs.aws.amazon.com/batch/latest/APIReference/API_SubmitJob.html#Batch-SubmitJob-request-containerOverrides
*
* @default - No container overrides
*/
readonly containerOverrides?: BatchContainerOverrides;
/**
* A list of dependencies for the job.
* A job can depend upon a maximum of 20 jobs.
*
* @see https://docs.aws.amazon.com/batch/latest/APIReference/API_SubmitJob.html#Batch-SubmitJob-request-dependsOn
*
* @default - No dependencies
*/
readonly dependsOn?: BatchJobDependency[];
/**
* The payload to be passed as parameters to the batch job
*
* @default - No parameters are passed
*/
readonly payload?: sfn.TaskInput;
/**
* The number of times to move a job to the RUNNABLE status.
* You may specify between 1 and 10 attempts.
* If the value of attempts is greater than one,
* the job is retried on failure the same number of attempts as the value.
*
* @default 1
*/
readonly attempts?: number;
}
/**
* Task to submits an AWS Batch job from a job definition.
*
* @see https://docs.aws.amazon.com/step-functions/latest/dg/connect-batch.html
*/
export class BatchSubmitJob extends sfn.TaskStateBase {
private static readonly SUPPORTED_INTEGRATION_PATTERNS: sfn.IntegrationPattern[] = [
sfn.IntegrationPattern.REQUEST_RESPONSE,
sfn.IntegrationPattern.RUN_JOB,
];
protected readonly taskMetrics?: sfn.TaskMetricsConfig;
protected readonly taskPolicies?: iam.PolicyStatement[];
private readonly integrationPattern: sfn.IntegrationPattern;
constructor(scope: Construct, id: string, private readonly props: BatchSubmitJobProps) {
super(scope, id, props);
this.integrationPattern = props.integrationPattern ?? sfn.IntegrationPattern.RUN_JOB;
validatePatternSupported(this.integrationPattern, BatchSubmitJob.SUPPORTED_INTEGRATION_PATTERNS);
// validate arraySize limits
withResolved(props.arraySize, (arraySize) => {
if (arraySize !== undefined && (arraySize < 2 || arraySize > 10_000)) {
throw new Error(`arraySize must be between 2 and 10,000. Received ${arraySize}.`);
}
});
// validate dependency size
if (props.dependsOn && props.dependsOn.length > 20) {
throw new Error(`dependencies must be 20 or less. Received ${props.dependsOn.length}.`);
}
// validate attempts
withResolved(props.attempts, (attempts) => {
if (attempts !== undefined && (attempts < 1 || attempts > 10)) {
throw new Error(`attempts must be between 1 and 10. Received ${attempts}.`);
}
});
// validate timeout
props.timeout !== undefined && withResolved(props.timeout.toSeconds(), (timeout) => {
if (timeout < 60) {
throw new Error(`attempt duration must be greater than 60 seconds. Received ${timeout} seconds.`);
}
});
// This is required since environment variables must not start with AWS_BATCH;
// this naming convention is reserved for variables that are set by the AWS Batch service.
if (props.containerOverrides?.environment) {
Object.keys(props.containerOverrides.environment).forEach(key => {
if (key.match(/^AWS_BATCH/)) {
throw new Error(
`Invalid environment variable name: ${key}. Environment variable names starting with 'AWS_BATCH' are reserved.`,
);
}
});
}
this.taskPolicies = this.configurePolicyStatements();
}
/**
* @internal
*/
protected _renderTask(): any {
return {
Resource: integrationResourceArn('batch', 'submitJob', this.integrationPattern),
Parameters: sfn.FieldUtils.renderObject({
JobDefinition: this.props.jobDefinitionArn,
JobName: this.props.jobName,
JobQueue: this.props.jobQueueArn,
Parameters: this.props.payload?.value,
ArrayProperties:
this.props.arraySize !== undefined
? { Size: this.props.arraySize }
: undefined,
ContainerOverrides: this.props.containerOverrides
? this.configureContainerOverrides(this.props.containerOverrides)
: undefined,
DependsOn: this.props.dependsOn
? this.props.dependsOn.map(jobDependency => ({
JobId: jobDependency.jobId,
Type: jobDependency.type,
}))
: undefined,
RetryStrategy:
this.props.attempts !== undefined
? { Attempts: this.props.attempts }
: undefined,
Timeout: this.props.timeout
? { AttemptDurationSeconds: this.props.timeout.toSeconds() }
: undefined,
}),
TimeoutSeconds: undefined,
};
}
private configurePolicyStatements(): iam.PolicyStatement[] {
return [
// Resource level access control for job-definition requires revision which batch does not support yet
// Using the alternative permissions as mentioned here:
// https://docs.aws.amazon.com/batch/latest/userguide/batch-supported-iam-actions-resources.html
new iam.PolicyStatement({
resources: [
Stack.of(this).formatArn({
service: 'batch',
resource: 'job-definition',
resourceName: '*',
}),
this.props.jobQueueArn,
],
actions: ['batch:SubmitJob'],
}),
new iam.PolicyStatement({
resources: [
Stack.of(this).formatArn({
service: 'events',
resource: 'rule/StepFunctionsGetEventsForBatchJobsRule',
}),
],
actions: ['events:PutTargets', 'events:PutRule', 'events:DescribeRule'],
}),
];
}
private configureContainerOverrides(containerOverrides: BatchContainerOverrides) {
let environment;
if (containerOverrides.environment) {
environment = Object.entries(containerOverrides.environment).map(
([key, value]) => ({
Name: key,
Value: value,
}),
);
}
let resources: Array<any> = [];
if (containerOverrides.gpuCount) {
resources.push(
{
Type: 'GPU',
Value: `${containerOverrides.gpuCount}`,
},
);
}
if (containerOverrides.memory) {
resources.push(
{
Type: 'MEMORY',
Value: `${containerOverrides.memory.toMebibytes()}`,
},
);
}
if (containerOverrides.vcpus) {
resources.push(
{
Type: 'VCPU',
Value: `${containerOverrides.vcpus}`,
},
);
}
return {
Command: containerOverrides.command,
Environment: environment,
InstanceType: containerOverrides.instanceType?.toString(),
ResourceRequirements: resources.length ? resources : undefined,
};
}
}