def publish_event_grid_event(data, topic_hostname, topic_key):
    """Sends a message to the provided Event Grid topic with the provided data payload.
    :param dict data: content of the message to be sent.
    :param string topic_hostname: The host name of the topic, e.g. 'topic1.westus2-1.eventgrid.azure.net'
    :param string topic_key: A 44 character access key for the topic.
    """
    credentials = TopicCredentials(topic_key)

    event_grid_client = EventGridClient(credentials)

    event_id = str(uuid.uuid4())

    event_grid_client.publish_events(topic_hostname,
                                     events=[{
                                         'id':
                                         event_id,
                                         'subject':
                                         "Houston Stage Trigger",
                                         'data':
                                         data,
                                         'event_type':
                                         'HoustonStageTrigger',
                                         'event_time':
                                         datetime.now(timezone.utc),
                                         'data_version':
                                         1
                                     }])
Ejemplo n.º 2
0
def publish_eventgrid(EVENT_GRID_ENDPOINT, EVENT_GRID_KEY, vm_uuid,
                      config_uuid, deploy_uuid, file_path, min_unixtime,
                      max_unixtime, total_records, storage_account,
                      container_name):

    credentials = TopicCredentials(EVENT_GRID_KEY)
    event_grid_client = EventGridClient(credentials)
    event_time = datetime.datetime.fromtimestamp(time.time())
    events_content = [{
        'id': str(uuid.uuid1()),
        'subject': "FINISH INGEST TO ADX",
        'data': {
            'vm_uuid': vm_uuid,
            'config_uuid': config_uuid,
            'deploy_uuid': deploy_uuid,
            'file_path': file_path,
            'min_unixtime': min_unixtime,
            'max_unixtime': max_unixtime,
            'total_records': total_records,
            'storage_account': storage_account,
            'container_name': container_name
        },
        'event_type': 'INGEST_ADX_FINSIHED',
        'event_time': event_time,
        'data_version': 1
    }]

    print("{} Send to EventGrid with Content: {}".format(
        LOG_MESSAGE_HEADER, events_content))

    event_grid_client.publish_events(EVENT_GRID_ENDPOINT,
                                     events=events_content)
def run_example():

    credentials = TopicCredentials(EVENT_GRID_KEY)
    event_grid_client = EventGridClient(credentials)
    event_grid_client.publish_events(TOPIC_ENDPOINT,
                                     events=build_events_list())
    print("Published events to Event Grid.")
Ejemplo n.º 4
0
    def __init__(self, hass, host, name, key):
        from azure.eventgrid import EventGridClient
        from msrest.authentication import TopicCredentials

        self.host = host
        self.name = name
        self.hass = hass
        self.client = EventGridClient(TopicCredentials(key))
Ejemplo n.º 5
0
class EventGridMsgSender:

    def __init__(self, connectionString=None):
        if connectionString == None:
            config = configparser.ConfigParser()
            config.read('/srv/scheduledEvents/scheduledEvents.config')
            self.topicKey = config.get(eventGridSection,'event_topic_key')
            if self.topicKey is None:
                logger.error ("Failed to load Event Grid key. Make sure config file contains 'event_topic_key' entry")
            self.topicEndpoint = config.get(eventGridSection,'event_topic_endpoint')
            if self.topicEndpoint is None:
                logger.error ("Failed to load Event Grid Topic Name. Make sure config file contains 'event_topic_name' entry")
            self.credentials = TopicCredentials(self.topicKey)
            self.egClient = EventGridClient(self.credentials)
            self.handleLocalEventsOnly = config.getboolean(agentSection,'scheduledEvents_handleLocalOnly')
            if self.handleLocalEventsOnly is None:
                logger.debug ("Failed to load Event Grid Topic Name. Make sure config file contains correct 'event_topic_name' entry")
                self.handleLocalEventsOnly = False

    def send_to_evnt_grid (self, msg, localHostName):
        if len(msg['Events']) == 0:
            logger.debug ("send_to_evnt_grid: No Scheduled Events")
            return
        try:
            logger.debug ("send_to_evnt_grid was called")
            credentials = TopicCredentials(self.topicKey)
            egClient = EventGridClient(credentials)

            for event in msg['Events']:
                eventid=event['EventId']
                status=event['EventStatus']
                eventype=event['EventType']
                restype=event['ResourceType']
                notbefore=event['NotBefore'].replace(" ","_")
                isLocal = False
                for resourceId in event['Resources']:
                    if localHostName in resourceId or self.handleLocalEventsOnly == False:
                        logger.debug ("before sending to event grid "+ str(datetime.now()))
                        self.egClient.publish_events(
                            self.topicEndpoint,
                            events=[{
                                'id' : eventid,
                                'subject' : "ScheduledEvent:"+eventype+", Host:"+resourceId+", Not Before:"+notbefore,
                                'data': event,
                                'event_type': "ScheduledEvent",
                                'event_time': datetime.now(),
                                'data_version': "1.0"
                                }] )
                        logger.debug ("send_to_evnt_grid: message "+eventid+" was send to EventGrid")

        except:
            logger.error ("send_to_evnt_grid: failed to send ")
Ejemplo n.º 6
0
def publish_event(data):
    credentials = TopicCredentials(
        "Nb3K+Pif1hNKWzk4j7dp6bzbgQywjEiMWGKUs+k8qZk=")
    event_grid_client = EventGridClient(credentials)
    event_grid_client.publish_events(
        "nancyeventgrid.eastus-1.eventgrid.azure.net",
        events=[{
            'id': uuid.uuid4(),
            'subject': "FaceData",
            'data': data,
            'event_type': 'NancyEventGrid',
            'event_time': datetime.now(pytz.timezone('US/Central')),
            'data_version': 2
        }])
Ejemplo n.º 7
0
    def send_to_evnt_grid (self, msg, localHostName):
        if len(msg['Events']) == 0:
            logger.debug ("send_to_evnt_grid: No Scheduled Events")
            return
        try:
            logger.debug ("send_to_evnt_grid was called")
            credentials = TopicCredentials(self.topicKey)
            egClient = EventGridClient(credentials)

            for event in msg['Events']:
                eventid=event['EventId']
                status=event['EventStatus']
                eventype=event['EventType']
                restype=event['ResourceType']
                notbefore=event['NotBefore'].replace(" ","_")
                isLocal = False
                for resourceId in event['Resources']:
                    if localHostName in resourceId or self.handleLocalEventsOnly == False:
                        logger.debug ("before sending to event grid "+ str(datetime.now()))
                        self.egClient.publish_events(
                            self.topicEndpoint,
                            events=[{
                                'id' : eventid,
                                'subject' : "ScheduledEvent:"+eventype+", Host:"+resourceId+", Not Before:"+notbefore,
                                'data': event,
                                'event_type': "ScheduledEvent",
                                'event_time': datetime.now(),
                                'data_version': "1.0"
                                }] )
                        logger.debug ("send_to_evnt_grid: message "+eventid+" was send to EventGrid")

        except:
            logger.error ("send_to_evnt_grid: failed to send ")
Ejemplo n.º 8
0
 def __init__(self, connectionString=None):
     if connectionString == None:
         config = configparser.ConfigParser()
         config.read('/srv/scheduledEvents/scheduledEvents.config')
         self.topicKey = config.get(eventGridSection,'event_topic_key')
         if self.topicKey is None:
             logger.error ("Failed to load Event Grid key. Make sure config file contains 'event_topic_key' entry")
         self.topicEndpoint = config.get(eventGridSection,'event_topic_endpoint')
         if self.topicEndpoint is None:
             logger.error ("Failed to load Event Grid Topic Name. Make sure config file contains 'event_topic_name' entry")
         self.credentials = TopicCredentials(self.topicKey)
         self.egClient = EventGridClient(self.credentials)
         self.handleLocalEventsOnly = config.getboolean(agentSection,'scheduledEvents_handleLocalOnly')
         if self.handleLocalEventsOnly is None:
             logger.debug ("Failed to load Event Grid Topic Name. Make sure config file contains correct 'event_topic_name' entry")
             self.handleLocalEventsOnly = False
Ejemplo n.º 9
0
    def test_event_grid_basic(self):

        credentials = TopicCredentials(self.settings.EVENT_GRID_KEY)
        event_grid_client = EventGridClient(credentials)
        event_grid_client.publish_events(
            "lmazuel-eventgrid-test.westus2-1.eventgrid.azure.net",
            events=[{
                'id': "dbf93d79-3859-4cac-8055-51e3b6b54bea",
                'subject': "My subject",
                'data': {
                    'key': 'I accept any kind of data here'
                },
                'event_type': 'PersonalEventType',
                'event_time': datetime(2018, 1, 30),
                'data_version': 1
            }])
Ejemplo n.º 10
0
def get_service(hass, config, discovery_info=None):
    from azure.eventgrid import EventGridClient
    from msrest.authentication import TopicCredentials

    credentials = TopicCredentials(config[CONF_TOPIC_KEY])
    event_grid_client = EventGridClient(credentials)

    return AzureEventGrid(config[CONF_HOST], event_grid_client)
    def test_event_grid_basic(self):

        credentials = TopicCredentials(
            self.settings.EVENT_GRID_KEY
        )
        event_grid_client = EventGridClient(credentials)
        event_grid_client.publish_events(
            "lmazuel-eventgrid-test.westus2-1.eventgrid.azure.net",
            events=[{
                'id' : "dbf93d79-3859-4cac-8055-51e3b6b54bea",
                'subject' : "My subject",
                'data': {
                    'key': 'I accept any kind of data here'
                },
                'event_type': 'PersonalEventType',
                'event_time': datetime(2018, 1, 30),
                'data_version': 1
            }]
        )
Ejemplo n.º 12
0
    def PublishEvent(endpoint, key, subject, eventType, dataJson):
        try:
            events = []
            for i in range(1):
                events.append(
                    EventGridEvent(id=uuid.uuid4(),
                                   subject=subject,
                                   data=dataJson,
                                   event_type=eventType,
                                   event_time=datetime.utcnow(),
                                   data_version=1.0))

            credentials = TopicCredentials(key)
            event_grid_client = EventGridClient(credentials)
            event_grid_client.publish_events(endpoint, events=events)
            print("Published event")
        except Exception as ex:
            print(ex)
            #TODO/ deal with this....
            pass
Ejemplo n.º 13
0
class AzureEventGrid(object):
    """Implement the notification service for the azure event grid."""
    def __init__(self, hass, host, name, key):
        from azure.eventgrid import EventGridClient
        from msrest.authentication import TopicCredentials

        self.host = host
        self.name = name
        self.hass = hass
        self.client = EventGridClient(TopicCredentials(key))

    def event_grid_publish_message(self, call):
        try:
            data = call.data[ATTR_PAYLOAD]
            subject = call.data[ATTR_SUBJECT]

            eventType = call.data[ATTR_EVENT_TYPE]
            if eventType is None:
                eventType = DEFAULT_EVENT_TYPE

            dataVersion = call.data[ATTR_DATA_VERSION]
            if dataVersion is None:
                dataVersion = DEFAULT_DATA_VERSION

            payload = {
                'id': str(uuid.uuid4()),
                'subject': subject,
                'data': data,
                'event_type': eventType,
                'event_time': datetime.utcnow().replace(tzinfo=pytz.UTC),
                'data_version': dataVersion
            }

            self.client.publish_events(self.host, events=[payload])
            LOGGER.debug("message published for topic %s", self.name)

        except HomeAssistantError as err:
            LOGGER.error("Unable to send event to Event Grid: %s", err)
Ejemplo n.º 14
0
 def __get_connection(self):
     if not self.client:
         credentials = TopicCredentials(self.topic_key)
         self.client = EventGridClient(credentials)
     return self.client
Ejemplo n.º 15
0
class AzureEventGrid(object):
    """Implement the notification service for the azure event grid."""
    def __init__(self, hass, host, name, key):
        from azure.eventgrid import EventGridClient
        from msrest.authentication import TopicCredentials

        self.host = host
        self.name = name
        self.hass = hass
        self.client = EventGridClient(TopicCredentials(key))

    def event_grid_publish_message(self, call):
        try:
            data = call.data[ATTR_PAYLOAD]
            subject = call.data[ATTR_SUBJECT]

            eventType = call.data[ATTR_EVENT_TYPE]
            if eventType is None:
                eventType = DEFAULT_EVENT_TYPE

            dataVersion = call.data[ATTR_DATA_VERSION]
            if dataVersion is None:
                dataVersion = DEFAULT_DATA_VERSION

            payload = {
                'id': str(uuid.uuid4()),
                'subject': subject,
                'data': data,
                'event_type': eventType,
                'event_time': datetime.utcnow().replace(tzinfo=pytz.UTC),
                'data_version': dataVersion
            }

            self.client.publish_events(self.host, events=[payload])
            LOGGER.debug("message published for topic %s", self.name)

        except HomeAssistantError as err:
            LOGGER.error("Unable to send event to Event Grid: %s", err)


# class EventGridView(HomeAssistantView):

#     # requires_auth = False
#     url = EVENT_GRID_HTTP_ENDPOINT
#     name = EVENT_GRID_HTTP_NAME
#     LOGGER.debug(f"Create event grid viewer")

#     def __init__(self, hass, name, mon_var):
#         self.hass = hass
#         self._name = name
#         self._mon_var = mon_var
#         self._state = None
#         self._state_attr = None

#     @asyncio.coroutine
#     def post(self, request):
#         from azure.eventgrid.models import SubscriptionValidationResponse
#         SubscriptionValidationEvent = "Microsoft.EventGrid.SubscriptionValidationEvent"
#         LOGGER.debug(f"Start event grid viewer call {request}")
#         try:
#             data = yield from request.json()
#             LOGGER.debug(f"Processing EventGrid data {data}")
#         except ValueError:
#             LOGGER.error("Received event grid data: %s", request)
#             return self.json_message('Invalid JSON', HTTP_BAD_REQUEST)

#         for event in data:
#             LOGGER.debug(f"Processing EventGrid message {event}")
#             if "eventType" in event:
#                 if event['eventType'] == SubscriptionValidationEvent:
#                     #[{'id': '58f9787a-xxxx-xxxx-xxxx-4fbb31c69398', 'topic': '/subscriptions/f2da982c-fc6f-xxxx-ad1e-46a186f9fa84/resourceGroups/eventgridtest/providers/Microsoft.EventGrid/topics/keestesttopic', 'subject': '', 'data': {'validationCode': '09E2E428-xxxx-xxxx-xxxx-BCD800D109A3', 'validationUrl': 'https://rp-westeurope.eventgrid.azure.net/eventsubscriptions/test/validate?id=09E2E428-xxxx-xxxx-xxxx-BCD800D109A3&t=2018-06-10T12:23:49.7126308Z&apiVersion=2018-05-01-preview&token=xxxx%2fXT1Uy8ndIfaro1mo%3d'}, 'eventType': 'Microsoft.EventGrid.SubscriptionValidationEvent', 'eventTime': '2018-06-10T12:23:49.7126308Z', 'metadataVersion': '1', 'dataVersion': '2'}]
#                     return self.json({
#                         'ValidationResponse': event['data']['validationCode']
#                     })
#                 else:
#                     # {'data': "{ 'message': 'test' }",
#                     # 'eventTime': '2018-07-01T15:24:10.6291209999999999Z',
#                     # 'eventType': 'doUpdate',
#                     # 'id': '5e0e8f49-c958-4bb9-9746-f56f8ce3c7f5',
#                     # 'subject': 'homeassistant.update',
#                     # 'dataVersion': '',
#                     # 'metadataVersion': '1',
#                     # 'topic': '/subscriptions/8f962503-0c00-4280-a157-8c20b3a9d990/resourceGroups/edvanhome/providers/Microsoft.EventGrid/topics/hass'}
#                     LOGGER.debug("else statement")
#                     self.hass.bus.fire(EVENT_STATE_CHANGED, event_data=event['eventType'])
#                     # Todo do simething with this message
#                     # hass.

# raise LOGGER.error('Unknown request on EventGrid api')

# http://eavv.nl:8123/api/azure_event_grid?api_password=eduardvv1
# https://edvanfunction.azurewebsites.net/api/TestHASSWebhook?code=bqpUXVoA/La1pu89d7mN8DKZpcOMzRSRx7c43EDlAD0TmP1f2/tuKg==&clientId=_master
Ejemplo n.º 16
0
from azure.eventgrid import EventGridClient
from msrest.authentication import TopicCredentials
import uuid
from datetime import datetime
import json

eventgrid_accesskey = input('Please enter your access key:')

credentials = TopicCredentials(eventgrid_accesskey)
event_grid_client = EventGridClient(credentials)
subject = 'traffic/01/1-bmz-406'
event_grid_client.publish_events(
    'savanh-real-time-iot.westeurope-1.eventgrid.azure.net',
    events=[{
        'id': str(uuid.uuid4()),
        'subject': subject,
        'data': "{'test':'test'}",
        'event_type': 'SuspectedCarDetected',
        'event_time': datetime.utcnow(),
        'data_version': 1
    }])
print('done')