in setup/lambda-custom-resource/prepare_dev_package_cr.py [0:0]
def prepare_device_package(event, context):
"""Prepares the edge device package in a lambda function and uploads it to the S3 bucket"""
# create a new thing group
thing_group_arn = None
agent_pkg_bucket = 'sagemaker-edge-release-store-us-west-2-linux-x64'
agent_config_package_prefix = 'edge-device-configuration/agent/config.tgz'
# check if edge agent package has already been built
try:
s3_client.download_file(Bucket=BUCKET_NAME, Key=agent_config_package_prefix, Filename='/tmp/dump')
LOGGER.info('The agent configuration package was already built! Skipping...')
quit()
except ClientError as e:
pass
# Create a new thing group if not found yet
try:
thing_group_arn = iot_client.describe_thing_group(thingGroupName=iot_thing_group_name)['thingGroupArn']
LOGGER.info("Thing group found")
except iot_client.exceptions.ResourceNotFoundException as e:
LOGGER.info("Creating a new thing group")
thing_group_arn = iot_client.create_thing_group(thingGroupName=iot_thing_group_name)['thingGroupArn']
LOGGER.info("Creating the directory structure for the agent")
# create a structure for the agent files
os.makedirs(LOCAL_DIR_PREFIX + 'agent/certificates/root', exist_ok=True)
os.makedirs(LOCAL_DIR_PREFIX + 'agent/certificates/iot', exist_ok=True)
os.makedirs(LOCAL_DIR_PREFIX + 'agent/logs', exist_ok=True)
os.makedirs(LOCAL_DIR_PREFIX + 'agent/model', exist_ok=True)
os.makedirs(LOCAL_DIR_PREFIX + 'agent/conf', exist_ok=True)
LOGGER.info("Downloading root certificate and agent binary")
# then get some root certificates
resp = http.request('GET', 'https://www.amazontrust.com/repository/AmazonRootCA1.pem')
with open(LOCAL_DIR_PREFIX + 'agent/certificates/iot/AmazonRootCA1.pem', 'w') as c:
c.write(resp.data.decode('utf-8'))
# this certificate validates the edge manage package
s3_client.download_file(
Bucket=agent_pkg_bucket,
Key='Certificates/%s/%s.pem' % (AWS_REGION, AWS_REGION),
Filename=LOCAL_DIR_PREFIX + 'agent/certificates/root/%s.pem' % AWS_REGION
)
LOGGER.info("Adjusting file permissions of pem files")
# adjust the permissions of the files
os.chmod(LOCAL_DIR_PREFIX + 'agent/certificates/iot/AmazonRootCA1.pem', stat.S_IRUSR|stat.S_IRGRP)
os.chmod(LOCAL_DIR_PREFIX + 'agent/certificates/root/%s.pem' % AWS_REGION, stat.S_IRUSR|stat.S_IRGRP)
LOGGER.info("Processing the agent...")
setup_agent(iot_thing_group_name, thing_group_arn )
LOGGER.info("Creating the final package...")
with io.BytesIO() as f:
with tarfile.open(fileobj=f, mode='w:gz') as tar:
tar.add(LOCAL_DIR_PREFIX + 'agent', 'agent', recursive=True)
f.seek(0)
LOGGER.info("Uploading to S3")
s3_client.upload_fileobj(f, Bucket=BUCKET_NAME, Key=agent_config_package_prefix)
LOGGER.info("Done!")