Monday, May 16, 2016

Lambda interacting with Redshift #AWS #LAMBDA #REDSHIFT #SNS #Python

'''
Here I am sharing methods to interact with Redshift or Arora DB in AWS, posting message to a given topic in SNS
'''

import json
import urllib2

import hmac
import hashlib
import base64
import string
import psycopg2
from time import strftime,gmtime,time

ACCESS  = 'XXXXXXXXXXXXXXXXXXX'
SECRET  = 'uxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
                     

REGION  = 'xxxx'
TOPIC   =  'xxxx'
MSG    = 'This is test message xxxxx'
SUBJECT = 'demo2'

'''
Here, the function fetchData will establish a connection with Redshift, execute a query and fetch the data.
'''

def fetchData():
       
    conn = psycopg2.connect(
        host="host_name_apearing_at_aws_console_excluding_port",
        user='myuser',
        port=5439,
        password='password',
        dbname='rdb')

    cur = conn.cursor()
   
    column_names = [];
    cur.execute("select * from dummy limit 10;");
    tmp=cur.fetchall();
   
   #conn.commit()
    conn.close()

'''
Below function will post to SNS
'''
def publishAmazonSnsMsg(Subject,TopicArn,Message,AWSAccessKeyId,privatekey):
  #http://docs.amazonwebservices.com/AWSSimpleQueueService/2008-01-01/SQSDeveloperGuide/
  amzsnshost = REGION
  params = {'Subject' : Subject,
            'TopicArn' : TopicArn,
            'Message' :Message,
            'Timestamp' : strftime("%Y-%m-%dT%H:%M:%S.000Z", gmtime(time())),
            'AWSAccessKeyId' : AWSAccessKeyId,
            'Action' : 'Publish',
            'SignatureVersion' : '2',
            'SignatureMethod' : 'HmacSHA256',
            }
 
  cannqs=string.join(["%s=%s"%(urllib2.quote(key),urllib2.quote(params[key], safe='-_~')) \
                                for key in sorted(params.keys())],'&')
  string_to_sign=string.join(["GET",amzsnshost,"/",cannqs],'\n')
  sig=base64.b64encode(hmac.new(privatekey,string_to_sign,digestmod=hashlib.sha256).digest())
  url="http://%s/?%s&Signature=%s"%(amzsnshost,cannqs,urllib2.quote(sig))
  print url
 
  try:
    return urllib2.urlopen(url).read()
  except urllib2.HTTPError, exception:
    return "Error %s (%s):\n%s"%(exception.code,exception.msg,exception.read())

def lambda_handler(event, context):
    fetchData()
    try:
        ret = publishAmazonSnsMsg(SUBJECT, TOPIC ,MSG , ACCESS, SECRET)
    except:
        pass

'''
# To test the function from cli
if __name__ == '__main__':
lambda_handler(None, None)
'''
'''

The above method running inside a lamba fuction will connect with the db and post to the SNS. There are some modules which are not available in AWS enviornment. We need to attach the the module folder in the root directory while zipping the module. As example for the above code psycopg2 was not available. So I have attached the module while zipping the source code.

Ex: ++lambda_function.py
       ++ psycopg2
               ++
               ++
In the same way we can attach the custom module too. For the psycopg2, it requires to be statically compiled. I am sharing a git link having the compiled module as well as listing method to compile the same. https://github.com/prrs/awslambda-psycopg2. courtsey: https://github.com/jkehler/awslambda-psycopg2
'''

No comments:

Post a Comment