Skip to content

Commit 8cd7e87

Browse files
committed
Add function to wait for the OpenSearch index to exist and remove delay using custom resource from cdk stack
1 parent 40b69e3 commit 8cd7e87

File tree

2 files changed

+31
-33
lines changed

2 files changed

+31
-33
lines changed

packages/cdk/stacks/EpsAssistMeStack.ts

Lines changed: 2 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -346,34 +346,8 @@ export class EpsAssistMeStack extends Stack {
346346
}
347347
}
348348
})
349-
350-
// Add a delay using a custom resource that doesn't do anything but wait
351-
const delay = new cr.AwsCustomResource(this, "IndexReadyDelay", {
352-
installLatestAwsSdk: true,
353-
onCreate: {
354-
service: "CloudFormation",
355-
action: "describeStacks",
356-
parameters: {
357-
StackName: this.stackName
358-
},
359-
physicalResourceId: cr.PhysicalResourceId.of(`Delay-${Date.now()}`)
360-
},
361-
onUpdate: {
362-
service: "CloudFormation",
363-
action: "describeStacks",
364-
parameters: {
365-
StackName: this.stackName
366-
},
367-
physicalResourceId: cr.PhysicalResourceId.of(`Delay-${Date.now()}`)
368-
},
369-
policy: cr.AwsCustomResourcePolicy.fromSdkCalls({
370-
resources: cr.AwsCustomResourcePolicy.ANY_RESOURCE
371-
})
372-
})
373-
374-
// Create dependency chain: vectorIndex -> delay -> kb
375-
delay.node.addDependency(vectorIndex)
376-
kb.node.addDependency(delay)
349+
// Ensure the Knowledge Base is created after the vector index
350+
kb.node.addDependency(vectorIndex)
377351

378352
// Attach S3 data source to Knowledge Base
379353
new CfnDataSource(this, "EpsKbDataSource", {

packages/createIndexFunction/app.py

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import json
22
import logging
33
import os
4+
import time
45

56
import boto3
67
from botocore.exceptions import NoCredentialsError
@@ -32,6 +33,29 @@ def get_opensearch_client(endpoint):
3233
)
3334

3435

36+
def wait_for_index(opensearch_client, index_name, timeout=120, poll_interval=4):
37+
"""
38+
Waits for the OpenSearch index to exist and be at least 'yellow' health.
39+
"""
40+
logger.info(f"Polling for index '{index_name}' to exist and be ready...")
41+
start = time.time()
42+
while True:
43+
try:
44+
if opensearch_client.indices.exists(index=index_name):
45+
health = opensearch_client.cluster.health(index=index_name, wait_for_status="yellow", timeout="5s")
46+
status = health.get("status")
47+
logger.info(f"Index '{index_name}' exists, health: {status}")
48+
if status in ("yellow", "green"):
49+
return
50+
else:
51+
logger.info(f"Index '{index_name}' does not exist yet...")
52+
except Exception as exc:
53+
logger.info(f"Error checking index status: {exc}")
54+
if time.time() - start > timeout:
55+
raise TimeoutError(f"Timed out waiting for index '{index_name}' to become ready.")
56+
time.sleep(poll_interval)
57+
58+
3559
def handler(event, context):
3660
logger.info("Received event: %s", json.dumps(event, indent=2))
3761
print(event)
@@ -86,14 +110,14 @@ def handler(event, context):
86110
opensearch_client.indices.create(
87111
index=params["index"], body=params["body"]
88112
)
89-
# Wait for the index to be available
90-
logger.info(f"Waiting for index {params['index']} to be ready")
91-
opensearch_client.cluster.health(index=params["index"], wait_for_status="yellow")
92-
logger.info(f"Index {params['index']} is ready")
113+
logger.info(f"Index {params['index']} creation initiated.")
93114
else:
94115
logger.info(f"Index {params['index']} already exists")
116+
# Wait for the index to be available and ready
117+
wait_for_index(opensearch_client, params["index"])
118+
logger.info(f"Index {params['index']} is ready.")
95119
except Exception as e:
96-
logger.error(f"Error creating index: {e}")
120+
logger.error(f"Error creating or waiting for index: {e}")
97121
raise e # Re-raise to fail the custom resource
98122

99123
elif event["RequestType"] == "Delete":

0 commit comments

Comments
 (0)