SAT9/.resources/adac1dcf931d343c8081e27fbb61e6094391f68c4d42f9a0f7cb4a82cc32fc36

77 lines
2.3 KiB
Plaintext

def DynamoWriter(site,latency):
import json
from pprint import pformat
import boto3
from datetime import datetime
from decimal import Decimal
import time
LOGGER = system.util.getLogger('latency_to_dynamodb_log')
# Get STAGE variable
API_ID, STAGE, ACC_ID, FUNC_URL = AWS.secrets_manager.get_secret(str(site), 'scada/api/endpoint')
API_ID,ACC_ID,FUNC_URL = None, None, None # set these to None becuase they are not used in here but must be returned during the call.
# Make sure STAGE is valid. no gamma stage configured
if STAGE not in ['alpha', 'beta', 'gamma', 'prod']:
STAGE = 'beta'
if STAGE == 'gamma':
STAGE = 'beta'
STAGE_CONFIG = {
'alpha':{
'region' : 'us-east-1',
'roleArn' : 'arn:aws:iam::905418469996:role/ignition_to_aws_latency_alpha',
'tableName' : 'SCADA_Latency_alpha'
},
'beta': {
'region':'us-east-1',
'roleArn': 'arn:aws:iam::381492071451:role/ignition_to_aws_latency_beta',
'tableName' : 'SCADA_Latency_beta'
},
'prod': {
'region':'us-east-1',
'roleArn': 'arn:aws:iam::891377003949:role/ignition_to_aws_latency_prod',
'tableName' : 'SCADA_Latency_prod'
}
}
# create sts session to get credentials from EC2
sts_client = boto3.client('sts')
region_name = STAGE_CONFIG.get(STAGE, 'alpha').get('region', 'us-east-1')
assume_role_response = sts_client.assume_role(
RoleArn = STAGE_CONFIG.get(STAGE, 'alpha').get('roleArn', 'arn:aws:iam::905418469996:role/ignition_to_aws_latency_alpha_test'),
RoleSessionName = 'AssumeRole'
)
temp_credentials = assume_role_response['Credentials']
# create session using the temp creds
b3_session = boto3.Session(
aws_access_key_id = temp_credentials['AccessKeyId'],
aws_secret_access_key = temp_credentials['SecretAccessKey'],
aws_session_token = temp_credentials['SessionToken'],
region_name = 'us-east-1',
)
# create a dynamodb session
dynamodb = b3_session.resource('dynamodb')
table = dynamodb.Table(STAGE_CONFIG.get(STAGE, 'alpha').get('tableName', 'SCADA_Latency_alpha'))
# write data directly to dynamodb table
try:
response = table.put_item(Item={
'site':site,
'timestamp':int(time.time()*1000),
'latency':str(round( int(Decimal(latency)) / 1000.0 , 3 ) ),
'source':3,
'TTL':int(time.time()+ (30*60) )
}
)
except Exception as e:
LOGGER.error(str(e))