def CheckCloudEndureReplication()

in AWSConfig/CloudEndureCheckReplication/lambda_function/CloudEndureReplicationCheck.py [0:0]


def CheckCloudEndureReplication(api_token, projectname, ciData):
    import requests
    import json
    import sys
    import time
    import random
    
    HOST = 'https://console.cloudendure.com'
    headers = {'Content-Type': 'application/json'}
    endpoint = '/api/latest/{}'
    session = {}
    
    should_retry = True 
    retries = 0

    while should_retry:
        if retries > 10:
            return ["FAILED", "Exceeded max retries on login"]
        retry_sleep = random.randint(1,15)
        time.sleep (retry_sleep)
        r = requests.post(HOST + endpoint.format('login'), data = json.dumps({'userApiToken': api_token}), headers = headers)
    
        if r.status_code != 200 and r.status_code != 307:
            print ("Bad API Token or loging issue")
            retries = retries + 1
        else:
            should_retry = False

        

    # check if need to use a different API entry point
    if r.history:
        endpoint = '/' + '/'.join(r.url.split('/')[3:-1]) + '/{}'
        r = requests.post(HOST + endpoint.format('login'), data = json.dumps(login_data), headers = headers)

    session = {'session': r.cookies['session']}
    headers['X-XSRF-TOKEN'] = r.cookies['XSRF-TOKEN']

    should_retry = True 
    retries = 0

    while should_retry:
        if retries > 10:
            return ["FAILED", "Exceeded max retries on getting project list"]
        retry_sleep = random.randint(1,5)
        time.sleep (retry_sleep)
        r = requests.get(HOST + endpoint.format('projects'), headers = headers, cookies = session)
        if r.status_code != 200:
            print ("Failed to fetch the project")
            retries = retries + 1
        else:
            should_retry = False
        

    try:
        projects = json.loads(r.content)['items']
        for project in projects:
            if project['name'] == projectname:
                machines = False
                project_id = project['id']
                should_retry = True 
                retries = 0
            
                while should_retry:
                    if retries > 10:
                        return ["FAILED", "Exceeded max retries on login"]
                    retry_sleep = random.randint(1,5)
                    time.sleep (retry_sleep)
                    r = requests.get(HOST + endpoint.format('projects/{}/machines').format(project_id), headers = headers, cookies = session)
                    if r.status_code != 200:
                        print ("Failed to fetch the machines")
                        retries = retries + 1
                    else:
                        should_retry = False
                        
                for machine in json.loads(r.content)['items']:
                    if ciData['resourceId'].startswith('mi-'):
                        if machine['sourceProperties']['name'] == ciData['configuration']['AWS:InstanceInformation']['Content'][ciData['resourceId']]['ComputerName']:
                            backlog = 0

                            if 'backloggedStorageBytes' in machine['replicationInfo']:		
                                if machine['replicationInfo']['backloggedStorageBytes'] > 0:
                                    return ['FAILED', 'Backlogged bytes is higher than 0']
                
                            now = datetime.datetime.now()
                            now_minus_10 = now - datetime.timedelta(minutes = 10)
                            current = now_minus_10.strftime("%Y-%m-%dT%H:%M:%S")
                            if 'lastConsistencyDateTime' in machine['replicationInfo']:
                                if machine['replicationInfo']['lastConsistencyDateTime'] < current:
                                    return ['FAILED', 'Communication with Source machine lost']
                            

                            if 'lastConsistencyDateTime' not in machine['replicationInfo']:
                                return ['FAILED', 'Last consistency date does not exist or system still replicating']
                            if 'lastTestLaunchDateTime' not in machine['lifeCycle']:
                                return ['FAILED', 'Machine has not been tested']
                            return ['PASSED', 'Replication enabled and consistent ']
                        machines = True
                    elif ciData['resourceId'].startswith('i-'):
                        
                        if machine['sourceProperties']['machineCloudId'] == ciData['resourceId']: 
                            backlog = 0

                            if 'backloggedStorageBytes' in machine['replicationInfo']:		
                                if machine['replicationInfo']['backloggedStorageBytes'] > 0:
                                    return ['FAILED', 'Backlogged bytes is higher than 0']
                    
                            now = datetime.datetime.now()
                            now_minus_10 = now - datetime.timedelta(minutes = 10)
                            current = now_minus_10.strftime("%Y-%m-%dT%H:%M:%S")
                            if 'lastConsistencyDateTime' in machine['replicationInfo']:
                                if machine['replicationInfo']['lastConsistencyDateTime'] < current:
                                    return ['FAILED', 'Communication with Source machine lost']
            
                
                            if 'lastConsistencyDateTime' not in machine['replicationInfo']:
                                return ['FAILED', 'Last consistency date does not exist or system still replicating']
                            if 'lastTestLaunchDateTime' not in machine['lifeCycle']:
                                return ['FAILED', 'Machine has not been tested']
                            return ['PASSED', 'Replication enabled and consistent ']
                        machines = True
                    
    
                print (ciData['resourceId'])
                return ["NOT_APPLICABLE", "Machine not in CloudEndure"]
    except Exception as e:
        return ['FAILED', e]