Esempio n. 1
0
def main(msg: func.ServiceBusMessage):
    message = msg.get_body().decode('utf-8')
    body = json.loads(message)
    action = body['Message']
    params = body['MessageAttributes']
    worker = WORKER_NAME_MAP[action]
    worker_type = worker['type']
    worker_name = worker['name']
    input = {k: params[k]['Value'] for k in params.keys()}
    job_id = input['job_id']
    tenant_id = input['tenant_id']

    result = json.dumps({
        'message_id': msg.message_id,
        'body': msg.get_body().decode('utf-8'),
        'worker_type': worker_type,
        'worker_name': worker_name,
        'job_id': job_id,
        'tenant_id': tenant_id,
        'content_type': msg.content_type,
        'expiration_time': msg.expiration_time,
        'label': msg.label,
        'partition_key': msg.partition_key,
        'reply_to': msg.reply_to,
        'reply_to_session_id': msg.reply_to_session_id,
        'scheduled_enqueue_time': msg.scheduled_enqueue_time,
        'session_id': msg.session_id,
        'time_to_live': msg.time_to_live,
        'to': msg.to,
        'user_properties': msg.user_properties,
    })

    logging.info(result)
Esempio n. 2
0
def main(message: func.ServiceBusMessage):
    notification_id = None
    try:
        notification_id = int(message.get_body().decode('utf-8'))
        logging.info(
            'Python ServiceBus queue trigger processed message: %s', notification_id)
    except Exception as e:
        logging.error('Invalid entry, skipping message {}'.format(message.get_body().decode('utf-8')))
        return

    conn = None
    cur = None
    nRepo = NoticationRepo()

    try:
        conn = get_conn(SSL_PATH)
        logging.info("Connection successful")

        cur = conn.cursor()
        n = nRepo.getById(notification_id, cur)
        if n != None:
            ats = AttendeeRepo().getAttendees(cur)
            for at in ats:
                subject = '{}: {}'.format(at.firstName, n.subject)
                send_email(at.email, n.subject, n.message)

            n.setNotificationCompleted(len(ats))
            nRepo.setCompleted(n, cur, conn)

    except Exception as e:
        logging.error('General Exception: ' + str(e))
    finally:
        closeDb(cur, conn)
Esempio n. 3
0
async def main(msg: func.ServiceBusMessage):
    try:
        logging.info('Python ServiceBus queue trigger processed message: %s',
                     msg.get_body().decode('utf-8'))

        raise Exception('something went wrong')
    except Exception:
        retry_count = int(msg.user_properties['retry-count']
                          ) if 'retry-count' in msg.user_properties else 0

        # If there are retries remaining
        if retry_count < RETRY_LIMIT:
            # Calculate a delay of seconds for next message
            retry_count += 1
            delay_seconds = retry_count * RETRY_MULTIPLIER_SECONDS
            logging.info('Scheduling message for the %i retry in %i seconds',
                         retry_count, delay_seconds)

            # Schedule and resend message onto queue
            async with queue_client.get_sender() as sender:
                message = Message(msg.get_body())
                message.message_id = msg.message_id
                message.user_properties = {
                    'original-message-id': msg.message_id,
                    'retry-count': retry_count
                }
                enqueue_time = datetime.now() + timedelta(
                    seconds=delay_seconds)
                await sender.schedule(enqueue_time, message)
        else:
            logging.error('Exhausted all retries')
def main(msg: func.ServiceBusMessage):
    logging.info('Python ServiceBus queue trigger processed message: %s')
    logging.info(msg.get_body().decode('utf-8'))
    logging.info('sleeping....')
    time.sleep(900)
    logging.info('completing')
    logging.info(msg.get_body().decode('utf-8'))
Esempio n. 5
0
async def main(msg: func.ServiceBusMessage, starter: str):
    logging.info("starting analyze_text_handler")
    
    message_body = msg.get_body().decode('utf-8')
    logging.info(f"message body: {message_body}")

    message_details = json.dumps({
        'message_id': msg.message_id,   
        'body': msg.get_body().decode('utf-8'),
        'content_type': msg.content_type,
        # 'expiration_time': msg.expiration_time,
        'label': msg.label,
        'partition_key': msg.partition_key,
        'reply_to': msg.reply_to,
        'reply_to_session_id': msg.reply_to_session_id,
        # 'scheduled_enqueue_time': msg.scheduled_enqueue_time,
        'session_id': msg.session_id,
        'time_to_live': msg.time_to_live,
        'to': msg.to,
        'user_properties': msg.user_properties,
        'metadata' : msg.metadata
    })
    logging.info(message_details)

    # State the orchestration function
    logging.info("starting analyze_text_orchestration")
    client = df.DurableOrchestrationClient(starter)
    instance_id = await client.start_new("analyze_text_orchestration", client_input=message_body)
    logging.info(f"started orchestration with instance id: {instance_id}")

    # How to manage an orchestration instance
    # https://docs.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-instance-management?tabs=python
Esempio n. 6
0
def main(msg: func.ServiceBusMessage):
    logging.info('Python ServiceBus queue trigger processed message: %s',
                 msg.get_body().decode('utf-8'))
    message = msg.get_body().decode('utf-8')
    print("message = {}".format(message))

    message_json = json.loads(message)
    first_name = message_json.get('firstName')

    print("firstName = {}".format(first_name))
Esempio n. 7
0
def main(message: func.ServiceBusMessage) -> func.InputStream:  #pylint: disable=E1136
    # Log the Service Bus Message as plaintext

    #message_content_type = message.content_type
    message_body = message.get_body().decode("utf-8")

    logging.info("Python ServiceBus topic trigger processed message.")
    #logging.info("Message Content Type: " + message_content_type)
    logging.info("Message Body: " + message_body)

    messagePayload = json.loads(message_body)

    receiptUrl = messagePayload["receiptUrl"]

    r = requests.get(receiptUrl)
    pdfEncoded = b64encode(r.content)

    outPayload = {
        "Store": messagePayload["storeLocation"],
        "SalesNumber": messagePayload["salesNumber"],
        "TotalCost": messagePayload["totalCost"],
        "Items": messagePayload["totalItems"],
        "SalesDate": messagePayload["salesDate"],
        "ReceiptImage": pdfEncoded.decode('utf-8')
    }

    return json.dumps(outPayload)
Esempio n. 8
0
def main(msg: func.ServiceBusMessage):
    result = msg.get_body().decode('utf-8')
    results = json.loads(result)
    item_payload = {
        'id': str(uuid.uuid1()),
        'timestamp': results['created'],
        'prediction': results['predictions']['tagName'],
        'probability': results['predictions']['probability'],
        'resolved': False
    }
    # {
    #     "id": "",
    #     "predictions": {
    #         "probability": 0.2551375,
    #         "boundingBox": {
    #             "left": 0.00870211,
    #             "height": 0.82958604,
    #             "top": 0.01420201,
    #             "width": 0.53497158
    #         },
    #         "tagId": 5,
    #         "tagName": "glass container"
    #     },
    #     "created": "2019-08-31T12:25:58.163379",
    #     "project": "",
    #     "iteration": ""
    # }

    # Only post if higher then 50%
    if results['predictions']['probability'] > 0.5:
        # Create and add some items to the container
        item = client.CreateItem(container['_self'], item_payload)
Esempio n. 9
0
def main(message: func.ServiceBusMessage):

    message_content_type = message.content_type
    message_body = message.get_body().decode("utf-8")

    logging_info = {
        "Message Content Type": message_content_type,
        "Message Body": message_body
    }

    logging.info(json.dumps(logging_info))

    storage_receipt_conn_str = os.environ.get('storage_receipt_conn_str')
    storage_receipt_lt100_container = os.environ.get(
        'storage_receipt_lt100_container')

    receipt_json = json.loads(message_body)

    receipt_lt100_json = {
        "Store": receipt_json["storeLocation"],
        "SalesNumber": receipt_json["salesNumber"],
        "TotalCost": receipt_json["totalCost"],
        "Items": receipt_json["totalItems"],
        "SalesDate": receipt_json["salesDate"]
    }

    blob_name = receipt_json["salesNumber"] + '.json'

    blob_service = blob.BlobClient.from_connection_string(
        storage_receipt_conn_str, storage_receipt_lt100_container, blob_name)
    blob_service.upload_blob(json.dumps(receipt_lt100_json), overwrite=True)
Esempio n. 10
0
async def run(msg: func.ServiceBusMessage):
    try:
        global nlp
        if nlp is None:
            nlp = get_model()
        if msg.message_id == "warmup-message":
            return

        paragraph_text = msg.get_body().decode('utf-8')
        topics_connection_string = os.environ["WordTopicsConnection"]
        q_connection_string = os.environ["TextQueuesConnection"]

        if nlp is None:
            nlp = get_model()

        doc = nlp(paragraph_text)

        paragraphs_task = asyncio.create_task(
            send_paragraph(q_connection_string, doc, msg.correlation_id,
                           msg.user_properties))

        lemmas = get_lemmas(doc)
        create_rule_for_dictionary_articles(
            topics_connection_string, msg.correlation_id,
            msg.user_properties["ParagraphNumber"], lemmas)
        lemmas_task = asyncio.create_task(
            send_lemmas(topics_connection_string, lemmas, msg.correlation_id,
                        msg.user_properties))

        await paragraphs_task
        await lemmas_task
    except Exception as ex:
        message = str.format("Error: {}", ex)
        logging.error(message)
def main(msg: azf.ServiceBusMessage) -> str:
    result = json.dumps({
        'message_id':
        msg.message_id,
        'body':
        msg.get_body().decode('utf-8'),
        'content_type':
        msg.content_type,
        'delivery_count':
        msg.delivery_count,
        'expiration_time':
        (msg.expiration_time.isoformat() if msg.expiration_time else None),
        'label':
        msg.label,
        'partition_key':
        msg.partition_key,
        'reply_to':
        msg.reply_to,
        'reply_to_session_id':
        msg.reply_to_session_id,
        'scheduled_enqueue_time': (msg.scheduled_enqueue_time.isoformat()
                                   if msg.scheduled_enqueue_time else None),
        'session_id':
        msg.session_id,
        'time_to_live':
        msg.time_to_live,
        'to':
        msg.to,
        'user_properties':
        msg.user_properties,
    })

    return result
Esempio n. 12
0
def main(msg: func.ServiceBusMessage):
    """When a message arrives on the servicebus, send a trigger to IoT Hub to start the fan for that device.

    Args:
        msg (func.ServiceBusMessage): Message from the connected Queue in a Azure ServiceBus
    """

    # Extract the method into a dictionary
    msg_dict = json.loads(msg.get_body().decode("utf-8"))

    logging.info(
        f"Python ServiceBus queue trigger processed message: {msg_dict}")

    # Enable a connection with the IoT Hub. The connectionstring for the IoT Hub
    # is preloaded in the Azure Functions configurations.
    connectino_string_iothub = os.getenv("connectionStringIotHub")
    registry_manager = IoTHubRegistryManager(connectino_string_iothub)

    # Settings for the method that the IoT Device should run upon receiving the message.
    callback_method = "start_fan"
    callback_payload = {}
    device_method = CloudToDeviceMethod(method_name=callback_method,
                                        payload=callback_payload)

    # Sending the actual cloud-to-device message and invoke a function on the IoT device.
    device_id = msg_dict["IoTHub"]["ConnectionDeviceId"]
    response = registry_manager.invoke_device_method(device_id, device_method)

    print("")
    print("Device Method called")
    print("Device Method name       : {0}".format(callback_method))
    print("Device Method payload    : {0}".format(callback_payload))
    print("")
    print("Response status          : {0}".format(response.status))
    print("Response payload         : {0}".format(response.payload))
Esempio n. 13
0
def main(msg: func.ServiceBusMessage):
    notification_id = None
    try:
        notification_id = int(msg.get_body().decode('utf-8'))
        logging.info('Python ServiceBus queue trigger processed message: %s',
                     notification_id)
    except Exception as e:
        logging.error('Message is not valid {}'.format(
            message.get_body().decode('utf-8')))
        return

    try:
        con = get_connection()

        cur = con.cursor()

        notification = get_notication(cur, notification_id)

        if notification != None:
            attendees = get_attendees(cur)
            for attendee in attendees:
                subject = '{}: {}'.format(attendee['firstName'],
                                          notification['subject'])
                send_email(attendee['email'], notification['subject'],
                           notification['message'])

            set_notif_complete(cur, con, notification, len(attendees))

    except Exception as e:
        logging.error('Exception: ' + str(e))
    finally:
        close_connection(cur, con)
Esempio n. 14
0
def main(msg: func.ServiceBusMessage):
    sms_event_data = SmsRecieved(loads(msg.get_body().decode('utf-8')))
    sms = SimpleMessagingService(
        leased_phone_number=environ['LEASED_PHONE_NUMBER'],
        target_phone_numbers=environ['TARGET_PHONE_NUMBERS'],
        comm_service_connection_string=environ['COMM_SERVICE_CONNECTION_STRING']
    )
    sms.send_sms(message_to_send=f'Sent from {sms_event_data.data.message_from}: {sms_event_data.data.message}')
Esempio n. 15
0
def main(msg: func.ServiceBusMessage):
    logging.info('function Invoked')
    notification_id = int(msg.get_body().decode('utf-8'))
    logging.info('Python ServiceBus queue trigger processed message: %s',
                 notification_id)

    # TODO: Get connection to database

    dbname = "techconfdb"
    user = "******"
    password = "******"
    host = "techconfdb.postgres.database.azure.com"
    sslmode = "require"

    conn_string = "host={0} user={1} dbname={2} password={3} sslmode={4}".format(
        host, user, dbname, password, sslmode)
    conn = psycopg2.connect(conn_string)
    logging.info('after connetion:')
    cursor = conn.cursor()

    try:
        # TODO: Get notification message and subject from database using the notification_id
        cursor.execute("SELECT * FROM notification WHERE id = %s;",
                       (notification_id, ))
        notification = cursor.fetchone()

        # TODO: Get attendees email and name
        cursor.execute("SELECT * FROM attendee;")
        attendees = cursor.fetchall()
        attendees_count = str(cursor.rowcount)
        cursor.execute(
            "UPDATE notification SET status = %s, completed_date = %s WHERE id = %s;",
            ("Notified {} attendees".format(attendees_count),
             datetime.utcnow(), notification_id))

        # TODO: Loop through each attendee and send an email with a personalized subject
        for attendee in attendees:
            send_email(
                str(attendee[5]), "{} {} {}".format(str(notification[5]),
                                                    str(attendee[1]),
                                                    str(attendee[2])),
                str(notification[2]))

        # TODO: Update the notification table by setting the completed date and updating the status with the total number of attendees notified
        cursor.execute(
            "UPDATE notification SET status = %s, completed_date = %s WHERE id = %s;",
            ("Notified {} attendees".format(attendees_count),
             datetime.utcnow(), notification_id))

    except (Exception, psycopg2.DatabaseError) as error:
        logging.error(error)
    finally:
        # TODO: Close connection
        conn.commit()
        cursor.close()
        conn.close()
        logging.info("Connection Closed")
Esempio n. 16
0
def main(message: func.ServiceBusMessage):
    # Log the Service Bus Message as plaintext

    #message_content_type = message.content_type
    message_body = message.get_body().decode("utf-8")

    logging.info("Python ServiceBus topic trigger processed message.")
    #logging.info("Message Content Type: " + message_content_type)
    logging.info("Message Body: " + message_body)
def main(msg: func.ServiceBusMessage):
    twitter_key = os.environ['TwitterAPIKey']
    twitter_secret = os.environ['TwitterAPISecret']
    twitter_access_token = os.environ['TwitterAccessToken']
    twitter_access_token_secret = os.environ['TwitterAccessTokenSecret']

    # Setup auth
    twitter_auth = tweepy.OAuthHandler(twitter_key, twitter_secret)
    twitter_auth.set_access_token(twitter_access_token,
                                  twitter_access_token_secret)

    # Create twitter API object
    tweeter = tweepy.API(twitter_auth)

    # Tweet message
    body_content = msg.get_body().decode('utf-8')
    tweeter.update_status(body_content)
    logging.info('Python ServiceBus queue trigger processed message: %s',
                 msg.get_body().decode('utf-8'))
Esempio n. 18
0
def main(msg: func.ServiceBusMessage):
    notification_id = int(msg.get_body().decode('utf-8'))
    logging.info('Python ServiceBus queue trigger processed message: %s',
                 notification_id)

    connection = psycopg2.connect(
        user="******",
        password="******",
        host="uda-postgresql.postgres.database.azure.com",
        port="5432",
        database="techconfdb")
    cursor = connection.cursor()

    try:
        notification_query = '''SELECT subject, message 
                                FROM Notification
                                WHERE id = %s;'''

        cursor.execute(notification_query, (notification_id, ))
        notification = cursor.fetchone()

        subject = notification[0]
        message = notification[1]

        attendees_query = 'SELECT first_name, email FROM Attendee;'
        cursor.execute(attendees_query)
        attendees = cursor.fetchall()

        for attendee in attendees:
            first_name = attendee[0]
            email = attendee[1]
            custom_subject = '{}: {}'.format(first_name, subject)
            # send_email(email, custom_subject, message)

        completed_date = datetime.utcnow()
        status = 'Notified {} attendees'.format(len(attendees))

        notification_update_query = '''UPDATE Notification 
                                SET completed_date = %s, status = %s 
                                WHERE id = %s;'''
        cursor.execute(notification_update_query,
                       (completed_date, status, notification_id))
        connection.commit()
        count = cursor.rowcount
        print(count, "Record Updated successfully ")

    except (Exception, psycopg2.DatabaseError) as error:
        logging.error(error)
    finally:
        #closing database connection.
        if (connection):
            cursor.close()
            connection.close()
            print("PostgreSQL connection is closed")
Esempio n. 19
0
def main(msg: func.ServiceBusMessage):
    scrape_json = msg.get_body().decode('utf-8')
    scrape_obj = scrape.Scrape(**json.loads(scrape_json))

    proc = best_buy_processor.BestBuyProcessor()
    scrpr = scraper.Scraper()

    status = scrpr.scrape(scrape_obj, proc)

    # Clear out any possible null values
    return json.dumps({k: v for k, v in status._asdict().items() if v})
def main(message: ServiceBusMessage) -> NoReturn:
    logging.info(
        f"--- ServiceBus event has triggered the function. Starting the process"
    )

    message = loads(message.get_body().decode())
    logging.info(f"Message: {message}")

    repopulate(message)

    return None
Esempio n. 21
0
async def main(message: ServiceBusMessage, starter: str) -> NoReturn:
    logging.info(
        f"--- ServiceBus event has triggered the function. Starting the process"
    )

    client = DurableOrchestrationClient(starter)
    raw_message = message.get_body().decode()
    message = loads(raw_message)
    logging.info(f"Message: {raw_message}")

    instance_id = await client.start_new("despatch_ops_orchestrator",
                                         instance_id=message.get(
                                             "instance_id", None),
                                         client_input=raw_message)

    logging.info(
        f"Started orchestration for 'despatch_ops_orchestrator' with ID = '{instance_id}'."
    )

    return None
Esempio n. 22
0
def main(msg: func.ServiceBusMessage):
    notification_id = int(msg.get_body().decode('utf-8'))
    logging.info('Python ServiceBus queue trigger processed message: %s',
                 notification_id)

    # TODO: Get connection to database
    dbname = "techconfdb"
    user = "******"
    host = "techcondb.postgres.database.azure.com"
    password = "******"

    conn = psycopg2.connect(host=host,
                            dbname=dbname,
                            user=user,
                            password=password)
    try:
        # TODO: Get notification message and subject fron database using the notification_id
        cur = conn.cursor()
        notf_query = f"select message, subject form notifications where id = {notification_id}"
        cur.execute(notf_query)
        notification_message, subject = cur.fetchall()
        # TODO: Get attendees email and name
        attendees_query = "select email, name from attendee"
        cur.execute(attendees_query)
        # TODO: Loop thru each attendee and send an email with a personalized subject
        attendees = cur.fetchall()

        if not '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"':
            for attendee in attendees:
                message = Mail(from_email="*****@*****.**",
                               to_emails=attendee[0],
                               subject=subject,
                               plain_text_content=notification_message)

            sg = SendGridAPIClient(
                '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"'
            )
            sg.send(message)

        # TODO: Update the notification table by setting the completed date and updating the status with the total number of attendees notified
        status = f'Notified {msg.delivery_count} attendees'
        query = f'update notification set status = {status}, completed_date = {datetime.utcnow()} where id = {notification_id}'
        cur.execute(query)
    except (Exception, psycopg2.DatabaseError) as error:
        logging.error(error)
    finally:
        # TODO: Close connection
        if (conn):
            conn.commit()
            cur.close()
            conn.close()
            print("PostgresSQL connection closed \n")
Esempio n. 23
0
def main(msg: func.ServiceBusMessage):

    # logging.info('Python ServiceBus queue trigger processed message: %s',
    #              msg.get_body().decode('utf-8'))
    notification_id = int(msg.get_body().decode('utf-8'))
    logging.info('Python ServiceBus queue trigger processed message: %s',notification_id)

    # TODO: Get connection to database
    conn = psycopg2.connect(
        host=',
        dbname='techconfdb', 
        user='',
        password=''
    )

    cursor = conn.cursor()
    try:
        # TODO: Get notification message and subject from database using the notification_id
        query = "SELECT message, subject FROM notification WHERE id = {0}".format(notification_id)
        cursor.execute(query)
        notification = cursor.fetchone()

        # TODO: Get attendees email and name
        query = "SELECT email, CONCAT(first_name, ' ', last_name) FROM attendee"
        cursor.execute(query)
        attendees = cursor.fetchall()

        # TODO: Loop through each attendee and send an email with a personalized subject
        for attendee in attendees:
            # logging.info('attendee[0]: %s',attendee[0])
            # logging.info('notification[0]: %s',notification[0])
            # logging.info('notification[1]: %s',notification[1])
            Mail(
                "*****@*****.**",
                attendee[0],
                notification[1],
                notification[0]
            )

        # TODO: Update the notification table by setting the completed date and updating the status with the total number of attendees notified
        status = "Notified {0} attendees".format(len(attendees))
        query = "UPDATE notification SET status = '{0}', completed_date='{1}' WHERE id = {2}".format(status, datetime.utcnow(), notification_id)
        cursor.execute(query)

        conn.commit()


    except (Exception, psycopg2.DatabaseError) as error:
        logging.error(error)
    finally:
        # TODO: Close connection
        conn.close()
Esempio n. 24
0
def main(msg: func.ServiceBusMessage):

    notification_id = int(float(msg.get_body().decode('utf-8')))
    logging.info('Python ServiceBus queue trigger processed message: %s',
                 notification_id)

    # Get connection to database
    conn = psycopg2.connect(
        dbname="techconfdb",
        user="******",
        password="******",
        host="sqlserver20210405.postgres.database.azure.com")
    cur = conn.cursor()
    try:
        # Get notification message and subject from database using the notification_id
        cur.execute(
            "SELECT subject, message FROM notification WHERE id={};".format(
                notification_id))
        result = cur.fetchall()
        subject, body = result[0][0], result[0][1]

        # Get attendees email and name
        cur.execute("SELECT email, first_name FROM attendee;")
        attendees = cur.fetchall()

        # Loop through each attendee and send an email with a personalized subject
        for (email, first_name) in attendees:
            mail = Mail(from_email='*****@*****.**',
                        to_emails=email,
                        subject=subject,
                        plain_text_content="Hi {}, \n {}".format(
                            first_name, body))
            try:
                SENDGRID_API_KEY = os.environ['SENDGRID_API_KEY']
                sg = SendGridAPIClient(SENDGRID_API_KEY)
                response = sg.send(mail)
            except Exception as e:
                logging.error(e)
        status = "Notified {} attendees".format(len(attendees))
        # Update the notification table by setting the completed date and updating the status with the total number of attendees notified
        cur.execute(
            "UPDATE notification SET status = '{}', completed_date = '{}' WHERE id = {};"
            .format(status, datetime.utcnow(), notification_id))
        # cur.execute("INSERT INTO notification(status, message, completed_date, subject) VALUES ('{}', '{}', '{}','{}');".format(status, body, datetime.utcnow(), subject))
        conn.commit()
    except (Exception, psycopg2.DatabaseError) as error:
        logging.error(error)
        conn.rollback()
    finally:
        # Close connection
        cur.close()
        conn.close()
Esempio n. 25
0
def main(message: func.ServiceBusMessage):
    # set teams variables
    url = os.environ['TEAMS_URL_WEBHOOK']
    account = os.environ["TENANT_NAME"]

    # Log the Service Bus Message as plaintext
    message_body = message.get_body().decode("utf-8")
    logging.info('Python ServiceBus topic trigger processed message.')
    logging.info(f'Message Body: {message_body}')

    message = json.loads(message_body)
    findings = message['scanning_result'].get('Findings')

    if findings:
        malwares = []
        types = []
        for finding in findings:
            malwares.append(finding.get('malware'))
            types.append(finding.get('type'))

        malwares = ', '.join(malwares)
        types = ', '.join(types)
        file_url = str(message['file_url'])

        payload = {
            "summary":
            "Malicious Object Detected",
            "sections": [{
                "activityTitle":
                "A <b>Malicious object</b> has been detected!"
            }, {
                "markdown":
                False,
                "facts": [{
                    "name": "Azure Tenant:",
                    "value": account
                }, {
                    "name": "Malware Name(s):",
                    "value": malwares
                }, {
                    "name": "Malware Type(s):",
                    "value": types
                }, {
                    "name": "File URL:",
                    "value": file_url
                }]
            }]
        }

        encoded_msg = json.dumps(payload).encode('utf-8')
        resp = http.request('POST', url, body=encoded_msg)
        logging.info(f'sending ms teams response: {resp}')
def sd_xmltojson_function(msgIn: func.ServiceBusMessage,
                          msgOut: func.Out[str]):
    try:
        strxml = msgIn.get_body().decode('utf-8')
        logging.info('Received xml from sdxmlqueue: %s', strxml)
        outMsgDict = xmltodict.parse(strxml,
                                     namespaces=namespaces,
                                     cdata_key='_value')
        logging.debug('Converted xml to json message: %s', outMsgDict)
        msgOut.set(json.dumps(outMsgDict))
    except Exception as e:
        logging.error('Failed to parse xml: {}'.format(str(e)))
        raise e
Esempio n. 27
0
def main(msg: func.ServiceBusMessage):

    logging.info(
        "Python Cosmos DB messaging automation function receiving message {0}".
        format(msg.message_id))

    try:
        msg_body = msg.get_body().decode('utf-8')
        msg_json = json.loads(msg_body)

        resource_group_name_res_id = msg_json['resource_group_name']
        account_name_res_id = msg_json['account_name']

        if resource_group_name != resource_group_name_res_id:
            raise ValueError(
                'Invalid Alert Resource Group. Expected alert for resource group {0} and received {1}. Review the Azure Metric Alert and action group configuration.'
                .format(resource_group_name, resource_group_name_res_id))
        if account_name != account_name_res_id:
            raise ValueError(
                'Invalid Alert Cosmos Db Account. Expected alert for cosmos db account {0} and received {1}. Review the Azure Metric Alert and action group configuration.'
                .format(account_name, account_name_res_id))
    except ValueError as err:
        logging.error(err.args)
        raise
    else:
        alert_rule_name = msg_json['alert_rule_name']
        severity = msg_json['severity']

    logging.info(
        'Python Cosmos DB messaging automation function processing alert {0} with severity {1}'
        .format(alert_rule_name, severity))

    try:
        client.database_accounts.update_sql_container_throughput(
            resource_group_name,
            account_name,
            database_name,
            container_name,
            resource=container_rus)

        logging.info(
            'Successfully provisioned {0} resources units for {1}/sql/{2}/{3}'.
            format(container_rus["throughput"], account_name, database_name,
                   container_name))
    except Exception as e:
        logging.error(
            '\ncosmosdb-provision-rus has caught an error. {0}'.format(e))
        # since Azure Functions Service trigger are using PeekLock connection mode we expect this raise to send this message to the DLQ
        raise
    finally:
        logging.info("\ncosmosdb-provision-rus done")
Esempio n. 28
0
def main(msg: func.ServiceBusMessage):

    notification_id = int(msg.get_body().decode('utf-8'))
    logging.info('Python ServiceBus queue trigger processed message: %s',
                 notification_id)

    # TODO: Get connection to database
    # Update connection string information
    host = "techconfdbudacity.postgres.database.azure.com"
    dbname = "techconfdb"
    user = "******"
    password = "******"
    sslmode = "require"

    # Construct connection string
    conn_string = "host={0} user={1} dbname={2} password={3} sslmode={4}".format(
        host, user, dbname, password, sslmode)
    conn = psycopg2.connect(conn_string)
    print("Connection established")

    try:
        # TODO: Get notification message and subject fron database using the notification_id
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM Notification WHERE id = %s;",
                       (notification_id, ))
        notification = cursor.fetchall()
        print(notification[0][0])
        # TODO: Get attendees email and name
        cursor.execute("SELECT * FROM Attendee;")
        rows = cursor.fetchall()

        # TODO: Loop thru each attendee and send an email with a personalized subject
        for row in rows:
            print("Data row = (%s, %s, %s)" %
                  (str(row[0]), str(row[1]), str(row[2])))
            subject = '{}: {}'.format(str(row[0]), str(notification[0][3]))

    # TODO: Update the notification table by setting the completed date and updating the status with the total number of attendees notified
        cursor.execute(
            "UPDATE Notification SET completed_date = %s WHERE id = %s;",
            (datetime.utcnow(), notification_id))
        cursor.execute(
            "UPDATE Notification SET status = %s WHERE id = %s;",
            ('Notified {} attendees'.format(len(rows)), notification_id))
    except (Exception, psycopg2.DatabaseError) as error:
        logging.error(error)
    finally:
        # TODO: Close connection
        conn.commit()
        cursor.close()
        conn.close()
def main(msg: func.ServiceBusMessage):

    notification_id = int(msg.get_body().decode('utf-8'))
    logging.info('Python ServiceBus queue trigger processed message: %s',
                 notification_id)

    # Get connection to database
    connection = psycopg2.connect(
        host="migratedbproject.postgres.database.azure.com",
        dbname="techconfdb",
        user="******",
        password="******")
    cursor = connection.cursor()

    try:
        # Get notification message and subject from database using the notification_id
        logging.info('Fetching notification message and subject...')
        notification_query = cursor.execute(
            "SELECT message, subject FROM notification WHERE id = {};".format(
                notification_id))

        # Get attendees email and name
        logging.info('Fetching attendees email and name...')
        cursor.execute("SELECT first_name, last_name, email FROM attendee;")
        attendees = cursor.fetchall()

        # Loop through each attendee and send an email with a personalized subject
        logging.info('Sending emails...')
        for attendee in attendees:
            Mail('{}, {}, {}'.format({'*****@*****.**'},
                                     {attendee[2]}, {notification_query}))

        # Update the notification table by setting the completed date and updating the status with the total number of attendees notified
        logging.info('Updating notifications...')
        notification_completed_date = datetime.utcnow()
        notification_status = 'Notified {} attendees'.format(len(attendees))
        update_query = cursor.execute(
            "UPDATE notification SET status = '{}', completed_date = '{}' WHERE id = {};"
            .format(notification_status, notification_completed_date,
                    notification_id))
        connection.commit()

    except (Exception, psycopg2.DatabaseError) as error:
        logging.error(error)
        connection.rollback()
    finally:
        # Close connection
        cursor.close()
        connection.close()
Esempio n. 30
0
def main(msg: func.ServiceBusMessage):    

    notification_id = int(msg.get_body().decode('utf-8'))
    logging.info('Python ServiceBus queue trigger processed message: %s',notification_id)

    # TODO: Get connection to database
    

    conn = psycopg2.connect(dbname="", user="", password="", host="")                                                                                 
    print("Connection established")
    cursor = conn.cursor()
    try:
        # TODO: Get notification message and subject from database using the notification_id
        cursor.execute("select status, message from public.notification where id = "+str(notification_id))
        notification = cursor.fetchall()

        # TODO: Get attendees email and name
        cursor.execute("select last_name,email from public.attendee")
        mail = cursor.fetchall()

        # https://docs.microsoft.com/de-de/azure/postgresql/flexible-server/connect-python
        # https://sendgrid.com/docs/for-developers/sending-email/v3-python-code-example/

        # TODO: Loop through each attendee and send an email with a personalized subject        
        for m in mail: 
            #print(m[1])           
            message = Mail(
                from_email='*****@*****.**',
                to_emails=m[1],
                subject='Updated',
                html_content='Message')            
            
        completed_date = datetime.utcnow()
        #print(completed_date)
        notification_status = 'Notified {} people'.format(len(mail))         
        logging.info('Python ServiceBus queue trigger processed message: %s',len(mail))

        # TODO: Update the notification table by setting the completed date and updating the status with the total number of attendees notified
        cursor.execute("UPDATE public.notification SET status = '{}', completed_date = '{}' WHERE id = {};".format(notification_status, completed_date, notification_id))        
        #print(completed_date)
        conn.commit()

    except (Exception, psycopg2.DatabaseError) as error:
        logging.error(error)
        conn.rollback()
    finally:
        # TODO: Close connection        
        cursor.close()
        conn.close()
def main(msg: func.ServiceBusMessage):
    logging.info('Python ServiceBus topic trigger processed message: %s',
                 msg.get_body().decode('utf-8'))