Lambda_dequeue

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.4 kB
6
Indexable
from datetime import datetime
import concurrent.futures 
import threading
import socket
import boto3
import ssl

def ssl_expiry_date(domainname):
    ssl_date_fmt = r'%b %d %H:%M:%S %Y %Z'
    context = ssl.create_default_context()
    conn = context.wrap_socket(
        socket.socket(socket.AF_INET),
        server_hostname = domainname,
    )
    
    conn.settimeout(2.0)
    try : 
        conn.connect((domainname, 443))
        ssl_info = conn.getpeercert()
        registration_date   = (datetime.strptime(ssl_info['notBefore'], ssl_date_fmt).date())
        expiry_date         = (datetime.strptime(ssl_info['notAfter'], ssl_date_fmt).date())

        return (registration_date, expiry_date)
    
    except Exception as e : 
        print(e)
        return -1
    
def ssl_valid_time_remaining(record, dynamodb_table) :
    message = eval(record['body'])
    domain_name = message['domainName']
    
    old_expiry_date = datetime.strptime(message['expiryDate'], "%Y-%m-%d").date()
    new_registration_date, new_expiry_date = ssl_expiry_date(domain_name)
    
    print(threading.current_thread().name, domain_name)
                
    if (old_expiry_date != new_expiry_date) : 
        print("Update domain", domain_name, old_expiry_date, new_expiry_date)
        
        message['registrationDate'] = new_registration_date.strftime("%Y-%m-%d")
        message['expiryDate'] = new_expiry_date.strftime("%Y-%m-%d")
        dynamodb_table.put_item(Item = message)

    else : print("Nothing to update on domain ", domain_name)
    print()
    
def lambda_handler(event, context) :
    dynamodb_table = boto3.resource("dynamodb").Table("test-table")
    
    my_event = event['Records']
    batch_failure_response = {}
    failed_messages = []
    
    print(len(my_event))
    print(event)
    
    with concurrent.futures.ThreadPoolExecutor() as executor : 
        for record in my_event :
            try : 
                # ssl_valid_time_remaining(record, dynamodb_table)
                executor.submit(ssl_valid_time_remaining, record, dynamodb_table)
            except :
                failed_messages.append({"itemIdentifier", record['messageId']})
                
    print("Number of fail processed messages : ", len(failed_messages))
    batch_failure_response["batchItemFailures"] = failed_messages
    return batch_failure_response