-
Notifications
You must be signed in to change notification settings - Fork 0
/
qdrant-ecr-image-ecs-deployment-cdk-stack.ts
227 lines (202 loc) · 11.8 KB
/
qdrant-ecr-image-ecs-deployment-cdk-stack.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
import * as cdk from 'aws-cdk-lib';
import * as ecs from 'aws-cdk-lib/aws-ecs';
import { Construct } from 'constructs';
import * as efs from 'aws-cdk-lib/aws-efs';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as iam from 'aws-cdk-lib/aws-iam';
import * as ecr from 'aws-cdk-lib/aws-ecr';
import { ApplicationLoadBalancedCodeDeployedFargateService } from '@cdklabs/cdk-ecs-codedeploy';
import { QdrantDockerImageEcsDeploymentCdkStackProps } from './QdrantDockerImageEcsDeploymentCdkStackProps';
import { createVPC } from './qdrant-vpc-deployment';
/**
* The `QdrantEcrImageEcsDeploymentCdkStack` class defines the infrastructure stack
* for deploying the Qdrant Docker image to an Amazon ECS cluster.
* It sets up the necessary resources such as the ECS cluster, task definitions,
* and load balancer to run the Qdrant service in a scalable and secure manner.
*/
export class QdrantEcrImageEcsDeploymentCdkStack extends cdk.Stack {
constructor(scope: Construct, id: string, props: QdrantDockerImageEcsDeploymentCdkStackProps) {
super(scope, id, props);
const qdrantVpc = createVPC(this, props);
const ecrRepositoryName = props.repositoryName;
console.log(`ecrRepositoryName: ${ecrRepositoryName}`);
const imageVersion = props.imageVersion;
console.log(`imageVersion: ${imageVersion}`);
const ecrRepository = ecr.Repository.fromRepositoryName(this, `${props.environment}-${props.platformString}-${props.deployRegion}-ERCRepository`, ecrRepositoryName);
const ecsContainerImage = ecs.ContainerImage.fromEcrRepository(ecrRepository, imageVersion);
// define a cluster with spot instances, linux type
const ecsCluster = new ecs.Cluster(this, `${props.environment}-${props.platformString}-${props.deployRegion}-Cluster`, {
clusterName: `${props.environment}-${props.platformString}-${props.deployRegion}-Cluster`,
vpc: qdrantVpc,
containerInsights: true,
});
// define a security group for EFS
const qdrantEfsSG = new ec2.SecurityGroup(this, `${props.environment}-${props.platformString}-${props.deployRegion}-qdrantEfsSG`, {
securityGroupName: `${props.environment}-${props.platformString}-${props.deployRegion}-qdrantEfsSG`,
vpc: qdrantVpc,
allowAllOutbound: true,
allowAllIpv6Outbound: true,
});
qdrantEfsSG.addIngressRule(
// ec2.Peer.ipv4(qdrantVpc.vpcCidrBlock)
qdrantEfsSG,
ec2.Port.tcp(2049),
'Allow NFS traffic from the ECS tasks.'
);
const qdrantDbSG = new ec2.SecurityGroup(this, `${props.environment}-${props.platformString}-${props.deployRegion}-qdrantDbSG`, {
securityGroupName: `${props.environment}-${props.platformString}-${props.deployRegion}-qdrantDbSG`,
vpc: qdrantVpc,
allowAllOutbound: true,
allowAllIpv6Outbound: true,
});
const vectorDatabasePort = props.vectorDatabasePort;
console.log(`vectorDatabasePort: ${vectorDatabasePort}`);
qdrantDbSG.addIngressRule(
// ec2.Peer.ipv4(qdrantVpc.vpcCidrBlock),
qdrantEfsSG,
ec2.Port.tcp(vectorDatabasePort),
'Allow Qdrant traffic from the VPC.'
);
// create an EFS File System
const efsFileSystem = new efs.FileSystem(this, `${props.environment}-${props.platformString}-${props.deployRegion}-QdrantServiceEfsFileSystem`, {
fileSystemName: `${props.environment}-${props.platformString}-${props.deployRegion}-QdrantServiceEfsFileSystem`,
vpc: qdrantVpc,
removalPolicy: cdk.RemovalPolicy.DESTROY,
securityGroup: qdrantEfsSG, // Ensure this security group allows NFS traffic from the ECS tasks
encrypted: true, // Enable encryption at rest
performanceMode: efs.PerformanceMode.MAX_IO, // For AI application, HCP application, Analytics application, and media processing workflows
allowAnonymousAccess: false, // Disable anonymous access
throughputMode: efs.ThroughputMode.BURSTING,
lifecyclePolicy: efs.LifecyclePolicy.AFTER_30_DAYS, // After 2 weeks, if a file is not accessed for given days, it will move to EFS Infrequent Access.
});
// add EFS access policy
efsFileSystem.addToResourcePolicy(
new iam.PolicyStatement({
actions: ['elasticfilesystem:ClientMount'],
principals: [new iam.AnyPrincipal()],
conditions: {
Bool: {
'elasticfilesystem:AccessedViaMountTarget': 'true'
}
},
}),
);
// create Fargate Task Definition with EFS volume
const fargateTaskDefinition = new ecs.FargateTaskDefinition(this, `${props.environment}-${props.platformString}-${props.deployRegion}-TaskDef`, {
memoryLimitMiB: 2048,
cpu: 1024,
ephemeralStorageGiB: 40,
runtimePlatform: {
cpuArchitecture: props.platformString === `arm` ? ecs.CpuArchitecture.ARM64 : ecs.CpuArchitecture.X86_64,
operatingSystemFamily: ecs.OperatingSystemFamily.LINUX,
},
executionRole: new iam.Role(this, `${props.environment}-${props.platformString}-${props.deployRegion}-TaskExecutionRole`, {
assumedBy: new iam.ServicePrincipal('ecs-tasks.amazonaws.com'),
managedPolicies: [
iam.ManagedPolicy.fromAwsManagedPolicyName('service-role/AmazonECSTaskExecutionRolePolicy'),
],
roleName: `${props.environment}-${props.platformString}-${props.deployRegion}-TaskExecutionRole`,
inlinePolicies: {
efsAccess: new cdk.aws_iam.PolicyDocument({
statements: [
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: [
'elasticfilesystem:ClientMount',
'elasticfilesystem:ClientWrite',
'elasticfilesystem:DescribeMountTargets',
'elasticfilesystem:ClientRootAccess',
'elasterfilesystem:ClientRead',
'elasticfilesystem:DescribeFileSystems',
],
resources: [efsFileSystem.fileSystemArn],
})
],
}),
}
}),
taskRole: new iam.Role(this, `${props.environment}-${props.platformString}-${props.deployRegion}-TaskRole`, {
// define a role for the task to access EFS with mount, read, write permissions
assumedBy: new iam.ServicePrincipal('ecs-tasks.amazonaws.com'),
managedPolicies: [
iam.ManagedPolicy.fromAwsManagedPolicyName('service-role/AmazonECSTaskExecutionRolePolicy'),
],
roleName: `${props.environment}-${props.platformString}-${props.deployRegion}-TaskRole`,
inlinePolicies: {
efsAccess: new iam.PolicyDocument({
statements: [
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: [
'elasticfilesystem:ClientMount',
'elasticfilesystem:ClientWrite',
'elasticfilesystem:DescribeMountTargets',
'elasticfilesystem:ClientRootAccess',
'elasticfilesystem:ClientRead',
'elasticfilesystem:DescribeFileSystems',
],
resources: [efsFileSystem.fileSystemArn],
}),
],
}),
},
}),
});
// define a container with the image
const qdrantContainer = fargateTaskDefinition.addContainer(`${props.environment}-${props.platformString}-${props.deployRegion}-QdrantContainer`, {
image: ecsContainerImage,
logging: ecs.LogDrivers.awsLogs({ streamPrefix: `${props.environment}-${props.platformString}-${props.deployRegion}-QdrantService` }),
containerName: `${props.environment}-${props.platformString}-${props.deployRegion}-QdrantContainer`,
});
// add port mapping
qdrantContainer.addPortMappings({
containerPort: vectorDatabasePort, // The port on the container to which the listener forwards traffic
protocol: ecs.Protocol.TCP
});
const efsVolumeName = props.appRootFilePath;
// add EFS volume to the task definition
fargateTaskDefinition.addVolume({
name: efsVolumeName, // This name is referenced in the sourceVolume parameter of container definition mountPoints.
efsVolumeConfiguration: {
fileSystemId: efsFileSystem.fileSystemId,
},
});
// mount EFS to the container
qdrantContainer.addMountPoints({
sourceVolume: efsVolumeName, // The name of the volume to mount. Must be a volume name referenced in the name parameter of task definition volume.
containerPath: `/${efsVolumeName}`, // The path on the container to mount the host volume at.
readOnly: false, // Allow the container to write to the EFS volume.
});
const albFargateService = new ApplicationLoadBalancedCodeDeployedFargateService(this, `${props.environment}-${props.platformString}-${props.deployRegion}-FargateService`, {
cluster: ecsCluster,
taskDefinition: fargateTaskDefinition,
desiredCount: 1,
publicLoadBalancer: true,
platformVersion: ecs.FargatePlatformVersion.VERSION1_4,
securityGroups: [qdrantEfsSG, qdrantDbSG], // might be needed to define port for qdrant vector sg
listenerPort: 80, // The port on which the listener listens for incoming traffic
});
// set deregistration delay to 30 seconds
albFargateService.targetGroup.setAttribute('deregistration_delay.timeout_seconds', '30');
// allow access to EFS from Fargate ECS
efsFileSystem.grantRootAccess(albFargateService.taskDefinition.taskRole.grantPrincipal);
efsFileSystem.connections.allowDefaultPortFrom(albFargateService.service.connections);
// setup AutoScaling policy
const scaling = albFargateService.service.autoScaleTaskCount({ maxCapacity: 2, minCapacity: 1 });
scaling.scaleOnCpuUtilization(`${props.appName}-${props.environment}-${props.platformString}-CpuScaling`, {
targetUtilizationPercent: 70,
scaleInCooldown: cdk.Duration.seconds(60),
scaleOutCooldown: cdk.Duration.seconds(60)
});
// print out fargateService dns name
new cdk.CfnOutput(this, `${props.environment}-${props.platformString}-${props.deployRegion}-FargateServiceDns`, {
value: albFargateService.loadBalancer.loadBalancerDnsName,
exportName: `${props.environment}-${props.platformString}-${props.deployRegion}-FargateServiceDns`,
});
// print out fargateService service url
new cdk.CfnOutput(this, `${props.environment}-${props.platformString}-${props.deployRegion}-FargateServiceUrl`, {
value: `http://${albFargateService.loadBalancer.loadBalancerDnsName}`,
exportName: `${props.environment}-${props.platformString}-${props.deployRegion}-FargateServiceUrl`,
});
}
}