Jenkinsfile
13.4 KB
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
pipeline {
agent {
label 'jenkins-agent'
}
environment {
// AWS Configuration
AWS_ACCOUNT_ID = '319998871902'
AWS_REGION = 'us-east-1'
EKS_CLUSTER_NAME = 'comic-website-prod'
DOCKER_REGISTRY = "${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com"
// Project Configuration
PROJECT_NAME = 'ecommerce'
NAMESPACE = 'ecommerce'
// Docker Images
FRONTEND_IMAGE = "${DOCKER_REGISTRY}/${PROJECT_NAME}-frontend"
USER_SERVICE_IMAGE = "${DOCKER_REGISTRY}/${PROJECT_NAME}-user-service"
PRODUCT_SERVICE_IMAGE = "${DOCKER_REGISTRY}/${PROJECT_NAME}-product-service"
ORDER_SERVICE_IMAGE = "${DOCKER_REGISTRY}/${PROJECT_NAME}-order-service"
PAYMENT_SERVICE_IMAGE = "${DOCKER_REGISTRY}/${PROJECT_NAME}-payment-service"
INVENTORY_SERVICE_IMAGE = "${DOCKER_REGISTRY}/${PROJECT_NAME}-inventory-service"
NOTIFICATION_SERVICE_IMAGE = "${DOCKER_REGISTRY}/${PROJECT_NAME}-notification-service"
// Versioning
BUILD_VERSION = "${env.BUILD_NUMBER}"
DOCKER_TAG = "${BUILD_VERSION}-${env.GIT_COMMIT.substring(0, 7)}"
// Java Configuration
JAVA_HOME = "/opt/java/openjdk"
}
options {
buildDiscarder(logRotator(numToKeepStr: '10'))
timeout(time: 60, unit: 'MINUTES')
disableConcurrentBuilds()
}
stages {
stage('Checkout') {
steps {
checkout scm
script {
currentBuild.displayName = "#${BUILD_VERSION}"
currentBuild.description = "Commit: ${env.GIT_COMMIT}"
}
}
}
stage('Setup Environment') {
steps {
withCredentials([[
$class: 'AmazonWebServicesCredentialsBinding',
credentialsId: 'dev-user-aws-credentials',
accessKeyVariable: 'AWS_ACCESS_KEY_ID',
secretKeyVariable: 'AWS_SECRET_ACCESS_KEY'
]]) {
script {
sh '''
echo "=== Environment Setup ==="
echo "Java Home: $JAVA_HOME"
echo "Java Version:"
java -version
echo "Gradle Version:"
gradle --version
echo "Node Version:"
node --version || echo "Node.js not installed"
# Configure AWS and EKS
aws configure set region ${AWS_REGION}
aws configure set output json
aws eks update-kubeconfig --region ${AWS_REGION} --name ${EKS_CLUSTER_NAME}
echo "Kubernetes cluster info:"
kubectl cluster-info
echo "Available disk space:"
df -h
echo "=== Environment setup completed ==="
'''
}
}
}
}
stage('Build User Service') {
steps {
script {
buildServiceSequential('user-service')
}
}
}
stage('Build Product Service') {
steps {
script {
buildServiceSequential('product-service')
}
}
}
stage('Build Order Service') {
steps {
script {
buildServiceSequential('order-service')
}
}
}
stage('Build Payment Service') {
steps {
script {
buildServiceSequential('payment-service')
}
}
}
stage('Build Inventory Service') {
steps {
script {
buildServiceSequential('inventory-service')
}
}
}
stage('Build Notification Service') {
steps {
script {
buildServiceSequential('notification-service')
}
}
}
stage('Build Frontend') {
steps {
dir('frontend') {
sh '''
echo "Building Frontend..."
npm ci
npm run build
echo "Frontend build completed"
'''
}
}
}
stage('ECR Login') {
steps {
withCredentials([[
$class: 'AmazonWebServicesCredentialsBinding',
credentialsId: 'dev-user-aws-credentials',
accessKeyVariable: 'AWS_ACCESS_KEY_ID',
secretKeyVariable: 'AWS_SECRET_ACCESS_KEY'
]]) {
script {
sh """
echo "Logging into ECR..."
aws ecr get-login-password --region ${AWS_REGION} | docker login --username AWS --password-stdin ${DOCKER_REGISTRY}
echo "✅ ECR login successful"
"""
}
}
}
}
stage('Docker Build Frontend') {
steps {
script {
dockerBuildPushSequential('frontend', "${FRONTEND_IMAGE}")
}
}
}
stage('Docker Build User Service') {
steps {
script {
dockerBuildPushSequential('user-service', "${USER_SERVICE_IMAGE}")
}
}
}
stage('Docker Build Product Service') {
steps {
script {
dockerBuildPushSequential('product-service', "${PRODUCT_SERVICE_IMAGE}")
}
}
}
stage('Docker Build Order Service') {
steps {
script {
dockerBuildPushSequential('order-service', "${ORDER_SERVICE_IMAGE}")
}
}
}
stage('Docker Build Payment Service') {
steps {
script {
dockerBuildPushSequential('payment-service', "${PAYMENT_SERVICE_IMAGE}")
}
}
}
stage('Docker Build Inventory Service') {
steps {
script {
dockerBuildPushSequential('inventory-service', "${INVENTORY_SERVICE_IMAGE}")
}
}
}
stage('Docker Build Notification Service') {
steps {
script {
dockerBuildPushSequential('notification-service', "${NOTIFICATION_SERVICE_IMAGE}")
}
}
}
stage('Deploy to EKS') {
steps {
withCredentials([[
$class: 'AmazonWebServicesCredentialsBinding',
credentialsId: 'dev-user-aws-credentials',
accessKeyVariable: 'AWS_ACCESS_KEY_ID',
secretKeyVariable: 'AWS_SECRET_ACCESS_KEY'
]]) {
script {
sh """
echo "🚀 Starting deployment to EKS..."
# Update kubeconfig
aws eks update-kubeconfig --region ${AWS_REGION} --name ${EKS_CLUSTER_NAME}
# Create namespace if not exists
kubectl create namespace ${NAMESPACE} --dry-run=client -o yaml | kubectl apply -f -
echo "Deploying databases..."
kubectl apply -f kubernetes/databases/ -n ${NAMESPACE} || echo "No databases configuration found"
echo "Deploying message queue..."
kubectl apply -f kubernetes/message-queue/ -n ${NAMESPACE} || echo "No message queue configuration found"
echo "Deploying microservices..."
kubectl apply -f kubernetes/microservices/ -n ${NAMESPACE}
echo "Deploying frontend..."
kubectl apply -f kubernetes/frontend/ -n ${NAMESPACE}
echo "Deploying networking..."
kubectl apply -f kubernetes/networking/ -n ${NAMESPACE} || echo "No networking configuration found"
echo "✅ Deployment completed!"
# Wait for deployments to be ready
echo "Waiting for deployments to be ready..."
sleep 30
# Check deployment status
echo "Current pod status:"
kubectl get pods -n ${NAMESPACE} --sort-by='.metadata.creationTimestamp'
# Show services
echo "Services:"
kubectl get services -n ${NAMESPACE}
"""
}
}
}
}
}
post {
always {
// Archive build artifacts
archiveArtifacts artifacts: '**/build/libs/*.jar', fingerprint: true
// Clean up Docker to free space
sh '''
echo "Cleaning up Docker resources..."
docker system prune -f || true
echo "Cleanup completed"
'''
// Log disk space after build
sh '''
echo "Disk space after build:"
df -h
'''
}
success {
echo "🎉 Build and deployment successful!"
sh '''
echo "✅ All tasks completed successfully"
echo "📊 Final resource usage:"
df -h
echo "🚀 Application deployed successfully!"
'''
}
failure {
echo "❌ Build failed! Check the logs for details."
sh '''
echo "💡 Troubleshooting tips:"
echo "1. Check disk space: df -h"
echo "2. Check Docker: docker system df"
echo "3. Check Gradle cache: du -sh ~/.gradle/"
echo "4. Check Kubernetes resources: kubectl get pods -n ecommerce"
'''
}
}
}
// 串行构建微服务的函数
def buildServiceSequential(serviceName) {
echo "🔨 Building ${serviceName}..."
dir("microservices/${serviceName}") {
// 添加重试机制和资源监控
retry(2) {
sh """
echo "=== Starting Gradle build for ${serviceName} ==="
echo "Current directory: \$(pwd)"
echo "Java version:"
java -version
echo "Gradle version:"
gradle --version
# 清理 Gradle 缓存以防万一
echo "Cleaning project..."
gradle clean --no-daemon
# 构建项目(跳过测试以减少资源使用)
echo "Building project..."
gradle build -x test --no-daemon --stacktrace
echo "✅ ${serviceName} build completed"
echo "Build artifacts:"
ls -la build/libs/
"""
}
}
echo "✅ ${serviceName} build completed successfully"
}
// 串行构建和推送 Docker 镜像的函数
def dockerBuildPushSequential(serviceDir, imageName) {
echo "🐳 Building and pushing Docker image for ${serviceDir}..."
def contextDir = serviceDir == 'frontend' ? 'frontend' : "microservices/${serviceDir}"
dir(contextDir) {
retry(2) {
sh """
echo "=== Building Docker image: ${imageName}:${DOCKER_TAG} ==="
echo "Build context: \$(pwd)"
# 检查 Dockerfile 是否存在
echo "Checking for Dockerfile..."
ls -la Dockerfile || echo "Dockerfile not found, listing all files:"
ls -la
# 构建 Docker 镜像
echo "Building Docker image..."
docker build -t ${imageName}:${DOCKER_TAG} .
# 推送 Docker 镜像
echo "Pushing Docker image to ECR..."
docker push ${imageName}:${DOCKER_TAG}
echo "✅ ${serviceDir} Docker image pushed successfully"
# 清理本地镜像以节省空间
echo "Cleaning up local Docker image..."
docker rmi ${imageName}:${DOCKER_TAG} || true
echo "=== ${serviceDir} Docker build completed ==="
"""
}
}
}