示例#1
0
    def executeBatch(self, notification, signal, targets):
        log.debug("Executing %s action for targets: %s", self.name, targets)
        self.setupAction(notification.dmd)

        data = _signalToContextDict(signal, self.options.get('zopeurl'), notification, self.guidManager)
        if signal.clear:
            log.debug('This is a clearing signal.')
            subject = processTalSource(notification.content['clear_subject_format'], **data)
            body = processTalSource(notification.content['clear_body_format'], **data)
        else:
            subject = processTalSource(notification.content['subject_format'], **data)
            body = processTalSource(notification.content['body_format'], **data)

        log.debug('Sending this subject: %s' % subject)
        log.debug('Sending this body: %s' % body)

        plain_body = MIMEText(self._stripTags(body))
        email_message = plain_body

        if notification.content['body_content_type'] == 'html':
            email_message = MIMEMultipart('related')
            email_message_alternative = MIMEMultipart('alternative')
            email_message_alternative.attach(plain_body)

            html_body = MIMEText(body.replace('\n', '<br />\n'))
            html_body.set_type('text/html')
            email_message_alternative.attach(html_body)

            email_message.attach(email_message_alternative)

        host = notification.content['host']
        port = notification.content['port']
        user = notification.content['user']
        password = notification.content['password']
        useTls = notification.content['useTls']
        email_from = notification.content['email_from']

        email_message['Subject'] = subject
        email_message['From'] = email_from
        email_message['To'] = ','.join(targets)
        email_message['Date'] = formatdate(None, True)

        result, errorMsg = sendEmail(
            email_message,
            host, port,
            useTls,
            user, password
        )

        if result:
            log.debug("Notification '%s' sent emails to: %s",
                     notification.id, targets)
        else:
            raise ActionExecutionException(
                "Notification '%s' FAILED to send emails to %s: %s" %
                (notification.id, targets, errorMsg)
            )
    def execute(self, notification, signal):
        """
        Sets up the execution environment and POSTs to PagerDuty's Event API.
        """
        log.debug('Executing Pagerduty Events API action: %s', self.name)
        self.setupAction(notification.dmd)

        if signal.clear:
            eventType = EventType.RESOLVE
        elif signal.event.status == STATUS_ACKNOWLEDGED:
            eventType = EventType.ACKNOWLEDGE
        else:
            eventType = EventType.TRIGGER

        # Set up the TALES environment
        environ = {'dmd': notification.dmd, 'env':None}

        actor = signal.event.occurrence[0].actor

        device = None
        if actor.element_uuid:
            device = self.guidManager.getObject(actor.element_uuid)
        environ.update({'dev': device})

        component = None
        if actor.element_sub_uuid:
            component = self.guidManager.getObject(actor.element_sub_uuid)
        environ.update({'component': component})

        data = _signalToContextDict(signal, self.options.get('zopeurl'), notification, self.guidManager)
        environ.update(data)

        try:
            details_list = json.loads(notification.content['details'])
        except ValueError:
            raise ActionExecutionException('Invalid JSON string in details')

        details = dict()
        for kv in details_list:
            details[kv['key']] = kv['value']

        details['zenoss'] = {
            'version'        : ZENOSS_VERSION,
            'zenpack_version': zenpack_version()
        }
        body = {'event_type': eventType,
                'client'    : 'Zenoss',
                'client_url': '${urls/eventUrl}',
                'details'   : details}

        for prop in REQUIRED_PROPERTIES:
            if prop in notification.content:
                body[prop] = notification.content[prop]
            else:
                raise ActionExecutionException("Required property '%s' not found" % (prop))

        self._performRequest(body, environ)
示例#3
0
    def execute(self, notification, signal):
        log.debug("Executing %s action", self.name)
        self.setupAction(notification.dmd)

        data = _signalToContextDict(signal, self.options.get('zopeurl'),
                                    notification, self.guidManager)
        sendSlack(notification.content['slackUrl'],
                  notification.content['proxyUrl'],
                  notification.content['proxyUsername'],
                  notification.content['proxyPassword'], **data)
示例#4
0
    def executeOnTarget(self, notification, signal, target):
        self.setupAction(notification.dmd)

        log.debug('Executing action: %s on %s', self.name, target)

        if signal.clear:
            command = notification.content['clear_body_format']
        else:
            command = notification.content['body_format']

        log.debug('Executing this command: %s', command)

        actor = signal.event.occurrence[0].actor
        device = None
        if actor.element_uuid:
            device = self.guidManager.getObject(actor.element_uuid)

        component = None
        if actor.element_sub_uuid:
            component = self.guidManager.getObject(actor.element_sub_uuid)

        user_env_format = notification.content['user_env_format']
        env = dict( envvar.split('=') for envvar in user_env_format.split(';') if '=' in envvar)

        environ = {'dev': device, 'component': component, 'dmd': notification.dmd,
                   'env': env}
        data = _signalToContextDict(signal, self.options.get('zopeurl'), notification, self.guidManager)
        environ.update(data)

        if environ.get('evt', None):
            environ['evt'] = self._escapeEvent(environ['evt'])

        if environ.get('clearEvt', None):
            environ['clearEvt'] = self._escapeEvent(environ['clearEvt'])

        environ['user'] = getattr(self.dmd.ZenUsers, target, None)

        try:
            command = processTalSource(command, **environ)
        except Exception:
            raise ActionExecutionException('Unable to perform TALES evaluation on "%s" -- is there an unescaped $?' % command)

        log.debug('Executing this compiled command: "%s"' % command)
        _protocol = EventCommandProtocol(command)

        log.debug('Queueing up command action process.')
        self.processQueue.queueProcess(
            '/bin/sh',
                ('/bin/sh', '-c', command),
            env=environ['env'],
            processProtocol=_protocol,
            timeout=int(notification.content['action_timeout']),
            timeout_callback=_protocol.timedOut
        )
示例#5
0
    def execute(self, notification, signal):
        """
        Send out an SNMP trap according to the definition in ZENOSS-MIB.
        """
        log.debug('Processing %s Trap action.', self.name)
        self.setupAction(notification.dmd)

        data = _signalToContextDict(signal, self.options.get('zopeurl'),
                                    notification, self.guidManager)
        event = data['eventSummary']
        actor = event.actor
        details = event.details

        baseOID = '1.3.6.1.4.1.14296.1.100'

        fields = {
            'uuid': (1, event),
            'fingerprint': (2, event),
            'element_identifier': (3, actor),
            'element_sub_identifier': (4, actor),
            'event_class': (5, event),
            'event_key': (6, event),
            'summary': (7, event),
            'message': (8, event),
            'severity': (9, event),
            'status': (10, event),
            'event_class_key': (11, event),
            'event_group': (12, event),
            'state_change_time': (13, event),
            'first_seen_time': (14, event),
            'last_seen_time': (15, event),
            'count': (16, event),
            'zenoss.device.production_state': (17, details),
            'agent': (20, event),
            'zenoss.device.device_class': (21, details),
            'zenoss.device.location': (22, details),
            'zenoss.device.systems': (23, details),
            'zenoss.device.groups': (24, details),
            'zenoss.device.ip_address': (25, details),
            'syslog_facility': (26, event),
            'syslog_priority': (27, event),
            'nt_event_code': (28, event),
            'current_user_name': (29, event),
            'cleared_by_event_uuid': (31, event),
            'zenoss.device.priority': (32, details),
            'event_class_mapping_uuid': (33, event)
        }

        eventDict = self.creatEventDict(fields, event)
        self.processEventDict(eventDict, data, notification.dmd)
        varbinds = self.makeVarBinds(baseOID, fields, eventDict)

        session = self._getSession(notification.content)
        session.sendTrap(baseOID + '.0.0.1', varbinds=varbinds)
示例#6
0
    def execute(self, notification, signal):
        log.debug("Executing %s action", self.name)
        self.setupAction(notification.dmd)
	
        data = _signalToContextDict(
            signal,
            self.options.get('zopeurl'),
            notification,
            self.guidManager
        )
	sendSlack(notification.content['slackUrl'],notification.content['proxyUrl'],notification.content['proxyUsername'],notification.content['proxyPassword'],**data)
    def execute(self, notification, signal):
        """
        Send out an SNMP trap according to the definition in ZENOSS-MIB.
        """
        log.debug("Processing %s Trap action.", self.name)
        self.setupAction(notification.dmd)

        data = _signalToContextDict(signal, self.options.get("zopeurl"), notification, self.guidManager)
        event = data["eventSummary"]
        actor = event.actor
        details = event.details

        baseOID = "1.3.6.1.4.1.14296.1.100"

        fields = {
            "uuid": (1, event),
            "fingerprint": (2, event),
            "element_identifier": (3, actor),
            "element_sub_identifier": (4, actor),
            "event_class": (5, event),
            "event_key": (6, event),
            "summary": (7, event),
            "message": (8, event),
            "severity": (9, event),
            "status": (10, event),
            "event_class_key": (11, event),
            "event_group": (12, event),
            "state_change_time": (13, event),
            "first_seen_time": (14, event),
            "last_seen_time": (15, event),
            "count": (16, event),
            "zenoss.device.production_state": (17, details),
            "agent": (20, event),
            "zenoss.device.device_class": (21, details),
            "zenoss.device.location": (22, details),
            "zenoss.device.systems": (23, details),
            "zenoss.device.groups": (24, details),
            "zenoss.device.ip_address": (25, details),
            "syslog_facility": (26, event),
            "syslog_priority": (27, event),
            "nt_event_code": (28, event),
            "current_user_name": (29, event),
            "cleared_by_event_uuid": (31, event),
            "zenoss.device.priority": (32, details),
            "event_class_mapping_uuid": (33, event),
        }

        eventDict = self.creatEventDict(fields, event)
        self.processEventDict(eventDict, data, notification.dmd)
        varbinds = self.makeVarBinds(baseOID, fields, eventDict)

        session = self._getSession(notification.content)
        session.sendTrap(baseOID + ".0.0.1", varbinds=varbinds)
    def execute(self, notification, signal):
        data = _signalToContextDict(signal, self.options.get('zopeurl'), notification, self.guidManager)
        if signal.clear and data['clearEventSummary'].uuid:
            event = data['clearEventSummary']
        else:
            event = data['eventSummary']

        actor = getattr(event, "actor", None)
        details = event.details
        fields = {
           'created_time' :                 ( 0, event),
           'uuid' :                         ( 1, event),
           'fingerprint' :                  ( 2, event),
           'element_identifier' :           ( 3, actor),
           'element_sub_identifier' :       ( 4, actor),
           'event_class' :                  ( 5, event),
           'event_key' :                    ( 6, event),
           'summary' :                      ( 7, event),
           'message' :                      ( 8, event),
           'severity' :                     ( 9, event),
           'status' :                       (10, event),
           'event_class_key' :              (11, event),
           'event_group' :                  (12, event),
           'status_change_time' :           (13, event),
           'first_seen_time' :              (14, event),
           'last_seen_time' :               (15, event),
           'count' :                        (16, event),
           'zenoss.device.production_state':(17, details),
           'monitor':                       (18, event),
           'manager':                       (19, details),
           'agent':                         (20, event),
           'zenoss.device.device_class':    (21, details),
           'zenoss.device.location' :       (22, details),
           'zenoss.device.systems' :        (23, details),
           'zenoss.device.groups' :         (24, details),
           'zenoss.device.ip_address':      (25, details),
           'syslog_facility' :              (26, event),
           'syslog_priority' :              (27, event),
           'nt_event_code' :                (28, event),
           'current_user_name' :            (29, event),
           'cleared_by_event_uuid' :        (31, event),
           'zenoss.device.priority' :       (32, details),
           'event_class_mapping_uuid':      (33, event),
           'element_title':                 (34, actor),
           'element_sub_title':             (35, actor),
           'originalTime':                  (36, details)
        }

        eventDict = self.createEventDict(fields, event)

        self.eventForwarderToKafkaAction(notification, data, eventDict)
    def execute(self, notification, signal):
        log.debug("Executing %s action", self.name)
        self.setupAction(notification.dmd)

        data = _signalToContextDict(signal, self.options.get('zopeurl'),
                                    notification, self.guidManager)

        message_body = processTalSource(notification.content['message_body'],
                                        **data)
        sendHipChat(message_body, data['evt'].severity,
                    notification.content['hipChatUrl'],
                    notification.content['proxyUrl'],
                    notification.content['proxyUsername'],
                    notification.content['proxyPassword'])
示例#10
0
    def executeOnTarget(self, notification, signal, targets):
        log.debug("Executing %s action for targets: %s", self.name, targets)
        self.setupAction(notification.dmd)

        data = _signalToContextDict(signal, self.options.get('zopeurl'), notification, self.guidManager)
        if signal.clear:
            log.debug('This is a clearing signal.')
            subject = processTalSource(notification.content['clear_subject_format'], **data)
            body = processTalSource(notification.content['clear_body_format'], **data)
        else:
            subject = processTalSource(notification.content['subject_format'], **data)
            body = processTalSource(notification.content['body_format'], **data)

        log.debug('Sending this subject: %s' % subject)
        log.debug('Sending this body: %s' % body)

        email_message = body

        if notification.content['body_content_type'] == 'html':
            email_message = body.replace('\n', '<br />\n')

        aws_access_key = notification.content['aws_access_key']
        aws_secret_key = notification.content['aws_secret_key']
        aws_region = notification.content['aws_region']
        email_from = notification.content['email_from']
        email_format = notification.content['body_content_type']

        email_subject = subject
        email_to = targets

        conn = boto.ses.connect_to_region(
            aws_region,
            aws_access_key_id=aws_access_key,
            aws_secret_access_key=aws_secret_key
        )

        conn.send_email(
            email_from,
            email_subject,
            email_message,
            email_to,
            format=email_format
        )

        log.debug("Notification '%s' sent emails to: %s",
                  notification.id, targets)
示例#11
0
    def _get_environ(self, notification, signal):
        """
        Set up TALES environment for the action.
        """
        actor = signal.event.occurrence[0].actor
        device = None
        if actor.element_uuid:
            device = self.guidManager.getObject(actor.element_uuid)

        component = None
        if actor.element_sub_uuid:
            component = self.guidManager.getObject(actor.element_sub_uuid)

        environ = dict(dev=device, component=component, dmd=notification.dmd)
        data = _signalToContextDict(signal, self.options.get('zopeurl'),
                                    notification, self.guidManager)
        environ.update(data)
        return environ
    def _get_environ(self, notification, signal):
        """
        Set up TALES environment for the action.
        """
        actor = signal.event.occurrence[0].actor
        device = None
        if actor.element_uuid:
            device = self.guidManager.getObject(actor.element_uuid)

        component = None
        if actor.element_sub_uuid:
            component = self.guidManager.getObject(actor.element_sub_uuid)

        environ = dict(dev=device, component=component, dmd=notification.dmd)
        data = _signalToContextDict(signal, self.options.get('zopeurl'),
                                    notification, self.guidManager)
        environ.update(data)
        return environ
示例#13
0
    def execute(self, notification, signal):
        log.debug("Executing %s action", self.name)
        self.setupAction(notification.dmd)

        data = _signalToContextDict(signal, self.options.get('zopeurl'),
                                    notification, self.guidManager)

        bot = TelegramBot(notification.content['token'])
        bot.update_bot_info().wait()

        if signal.clear:
            text = processTalSource(notification.content['message_clear'],
                                    **data)

        else:
            text = processTalSource(notification.content['message_body'],
                                    **data)

        bot.send_message(notification.content['chat_id'],
                         text,
                         parse_mode="Markdown").wait()
        print
    def execute(self, notification, signal):
        evt = _signalToContextDict(signal, "").get("evt")
        if not evt:
            return

        LOG.debug("DEBUG: %r", evt.__dict__)
示例#15
0
    def executeOnTarget(self, notification, signal, target):
        self.setupAction(notification.dmd)

        log.debug('[research] execute : %s on %s' % (self.name, target))

        jiraURL = notification.content['jira_instance']
        jiraUser = notification.content['jira_user']
        jiraPass = notification.content['jira_password']

        issueProject = notification.content['issue_project']
        issueType = notification.content['issue_type']
        issuePriority = notification.content['issue_priority_key']
        customfields = notification.content['customfield_keypairs']
        eventRawData = notification.content['event_rawdata']
        serviceRoot = notification.content['service_group_root']

        summary = ''
        description = ''

        if (signal.clear):
            log.info('[research] event cleared : %s' % (target))
            description = notification.content['clear_issue_description']
        else:
            log.warn('[research] event detected : %s' % (target))
            summary = notification.content['issue_summary']
            description = notification.content['issue_description']

        actor = signal.event.occurrence[0].actor
        device = None
        if (actor.element_uuid):
            device = self.guidManager.getObject(actor.element_uuid)

        component = None
        if (actor.element_sub_uuid):
            component = self.guidManager.getObject(actor.element_sub_uuid)

        environ = {
            'dev': device, 'component': component, 'dmd': notification.dmd
        }

        data = _signalToContextDict(
            signal, self.options.get('zopeurl'),
            notification, self.guidManager
        )

        environ.update(data)

        if (environ.get('evt', None)):
            environ['evt'] = self._escapeEvent(environ['evt'])

        if (environ.get('clearEvt', None)):
            environ['clearEvt'] = self._escapeEvent(environ['clearEvt'])

        environ['user'] = getattr(self.dmd.ZenUsers, target, None)

        issueValues = {
            'summary' : summary,
            'description' : description,
            'eventraw' : eventRawData,
            'customfields' : customfields
        }

        log.debug('[research] base issue values : %s' % (issueValues))

        targetValues = {
            'project' : issueProject,
            'issuetype' : issueType,
            'priority' : issuePriority,
            'serviceroot' : serviceRoot 
        }

        log.debug('[research] base target values : %s' % (targetValues))

        self.connectJIRA(jiraURL, jiraUser, jiraPass)

        if (signal.clear):
            self.clearEventIssue(environ, targetValues, issueValues)
        else:
            self.createEventIssue(environ, targetValues, issueValues)

        log.debug("[research] event update reported : %s" % (jiraURL));
示例#16
0
    def execute(self, notification, signal):
        self.setupAction(notification.dmd)
        
        data = _signalToContextDict(signal, self.options.get('zopeurl'), notification, self.guidManager)

        #if notification.content['gcmdeviceid'] == "AABBCCDDEEFF00112233":
        #    raise ActionExecutionException("Cannot send a Rhybudd GCM message with the default GCM Key")
        
	#if signal.clear and data['clearEventSummary'].uuid:
	#    log.info('------------------------------------ This is a clear message')
        #else:
        #    log.info('------------------------------------ This is an alert')

        #log.info(data['eventSummary'].summary)
        #log.info(data['eventSummary'].status)
        #log.info(data['eventSummary'].count)
        #log.info(data['eventSummary'].severity)
        #log.info(data['eventSummary'].event_class)
        #log.info(data['eventSummary'].event_class_key) 

        actor = signal.event.occurrence[0].actor
        device = None
        if actor.element_uuid:
            device = self.guidManager.getObject(actor.element_uuid)

	#------------------------------------
	#The CURL Way of doing things
        #curlCall = "curl -H \"Content-Type: application/json\" -X POST -d '{\"gcm_id\": \"%s\",\"evid\": \"%s\",\"device\": \"%s\",\"summary\": \"%s\",\"status\": \"%s\",\"count\": \"%s\",\"severity\": \"%s\",\"event_class\": \"%s\",\"event_class_key\": \"%s\"}' http://api.coldstart.io/1/zenoss.php" % (notification.content['gcmdeviceid'], signal.event.uuid,device,data['eventSummary'].summary,data['eventSummary'].status,data['eventSummary'].count,data['eventSummary'].severity,data['eventSummary'].event_class,data['eventSummary'].event_class_key)
        #call(curlCall, shell=True)

	#------------------------------------
	#The URL Lib way of doing things

	prodstate = ""
	try:
		prodstate = "%s" % data.prodstate  		
	except Exception:
		prodstate = "" 
  		pass

        payload = {
        'filter_key': notification.content['gcmdeviceid'],
"evid": "%s" % signal.event.uuid,
"device": "%s" % device,
"summary": "%s" % data['eventSummary'].summary,
"status": data['eventSummary'].status,
"count": data['eventSummary'].count,
"severity": data['eventSummary'].severity,
"event_class": "%s" % data['eventSummary'].event_class,
"event_class_key": "%s" % data['eventSummary'].event_class_key,

"prodstate": "%s" % prodstate,
"firsttime": "%s" % data['eventSummary'].first_seen_time,
#"componenttext": "%s" % data['eventSummary'].component.text,
"ownerid": "%s" % data['eventSummary'].current_user_name
}

	gcm_details = getattr(self.dmd, 'rhybudd_gcm', Gcm("", ""))
	log.info("%s",gcm_details.gcm_api_key)
	stored_regids = getattr(self.dmd, 'rhybudd_regids', [])
	reg_ids = []

	for regDetails in stored_regids:
          #log.info('Found a GCM ID: %s',regDetails.gcm_reg_id)
	  reg_ids.append(regDetails.gcm_reg_id)

	if gcm_details.gcm_api_key == "":
		#------------------------------------
		#No GCM Key specified so we'll proxy through ColdStart.io so as to not expose our GCM API Key
		log.info('------------------------------------ Sending a coldstart GCM Request')
        	
		coldstart_payload = {'payload': payload, 'regids': reg_ids} 
		data = "json=%s" % json.dumps(coldstart_payload)
		
        	h = httplib.HTTPSConnection('api.coldstart.io')
        	headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
        	h.request('POST', '/1/zenoss', data, headers)
    
	else:
		#------------------------------------
		# Direct to GCM
		log.info('------------------------------------ Sending a direct GCM Request')
		gcm = GCMSERVER(gcm_details.gcm_api_key)
		#reg_ids = ['APA91bEPJ_Pf7k5KgpZxbNBpq9snGjYyQn6Q21w_JYl-_4FADgNH54kzcQxGb6Wjb1PkWGiEaVQE0MXhMw7q-jTOvDN_smiaSa96F9sEOLd1xYt4yd7PiYVCYsVULiFoN_isvz1AcN-HXjZVfipBLBIzN5ohqN_MM2tpmBj9JFpdwjFgM6ZNhPU']
		response = gcm.json_request(registration_ids=reg_ids, data=payload, collapse_key=signal.event.uuid, time_to_live=0)
		log.info("%s",json.dumps(response))
		log.info('------------------------------------ Sent a direct GCM Request')	
示例#17
0
    def executeOnTarget(self, notification, signal, target):
        self.setupAction(notification.dmd)

        log.debug('[research] execute : %s on %s' % (self.name, target))

        jiraURL = notification.content['jira_instance']
        jiraUser = notification.content['jira_user']
        jiraPass = notification.content['jira_password']

        issueProject = notification.content['issue_project']
        issueType = notification.content['issue_type']
        issuePriority = notification.content['issue_priority_key']
        customfields = notification.content['customfield_keypairs']
        eventRawData = notification.content['event_rawdata']
        serviceRoot = notification.content['service_group_root']

        summary = ''
        description = ''

        if (signal.clear):
            log.info('[research] event cleared : %s' % (target))
            description = notification.content['clear_issue_description']
        else:
            log.warn('[research] event detected : %s' % (target))
            summary = notification.content['issue_summary']
            description = notification.content['issue_description']

        actor = signal.event.occurrence[0].actor
        device = None
        if (actor.element_uuid):
            device = self.guidManager.getObject(actor.element_uuid)

        component = None
        if (actor.element_sub_uuid):
            component = self.guidManager.getObject(actor.element_sub_uuid)

        environ = {
            'dev': device,
            'component': component,
            'dmd': notification.dmd
        }

        data = _signalToContextDict(signal, self.options.get('zopeurl'),
                                    notification, self.guidManager)

        environ.update(data)

        if (environ.get('evt', None)):
            environ['evt'] = self._escapeEvent(environ['evt'])

        if (environ.get('clearEvt', None)):
            environ['clearEvt'] = self._escapeEvent(environ['clearEvt'])

        environ['user'] = getattr(self.dmd.ZenUsers, target, None)

        issueValues = {
            'summary': summary,
            'description': description,
            'eventraw': eventRawData,
            'customfields': customfields
        }

        log.debug('[research] base issue values : %s' % (issueValues))

        targetValues = {
            'project': issueProject,
            'issuetype': issueType,
            'priority': issuePriority,
            'serviceroot': serviceRoot
        }

        log.debug('[research] base target values : %s' % (targetValues))

        self.connectJIRA(jiraURL, jiraUser, jiraPass)

        if (signal.clear):
            self.clearEventIssue(environ, targetValues, issueValues)
        else:
            self.createEventIssue(environ, targetValues, issueValues)

        log.debug("[research] event update reported : %s" % (jiraURL))
示例#18
0
    def executeBatch(self, notification, signal, targets):
        log.debug("Executing %s action for targets: %s", self.name, targets)
        self.setupAction(notification.dmd)

        data = _signalToContextDict(signal, self.options.get('zopeurl'),
                                    notification, self.guidManager)
        if signal.clear:
            log.debug('This is a clearing signal.')
            subject = processTalSource(
                notification.content['clear_subject_format'], **data)
            body = processTalSource(notification.content['clear_body_format'],
                                    **data)
        else:
            subject = processTalSource(notification.content['subject_format'],
                                       **data)
            body = processTalSource(notification.content['body_format'],
                                    **data)

        log.debug('Sending this subject: %s' % subject)
        log.debug('Sending this body: %s' % body)

        #plain_body = MIMEText(self._stripTags(body))
        plain_body = MIMEText(self._stripTags(body),
                              _subtype='plain',
                              _charset='utf-8')
        email_message = plain_body

        if notification.content['body_content_type'] == 'html':
            email_message = MIMEMultipart('related')
            email_message_alternative = MIMEMultipart('alternative')
            email_message_alternative.attach(plain_body)

            html_body = MIMEText(body.replace('\n', '<br />\n'),
                                 _subtype='html',
                                 _charset='utf-8')
            #html_body = MIMEText(body.replace('\n', '<br />\n'))
            html_body.set_type('text/html')
            email_message_alternative.attach(html_body)

            email_message.attach(email_message_alternative)

            # Attach image

            (zpdir,
             tail) = os.path.split(__file__)  # Get path to this directory
            imFile = zpdir + '/imageFile0.jpg'
            imageFile = open(imFile, 'rb')
            msgImage = MIMEImage(imageFile.read())
            imageFile.close()
            msgImage.add_header('Content-ID', '<image0>')
            email_message.attach(msgImage)

            # Add the trailer images - see and of body_format and clear_body_format
            if signal.clear:
                imFile = zpdir + '/imageFile2.jpg'
                imageFile = open(imFile, 'rb')
                msgImage = MIMEImage(imageFile.read())
                imageFile.close()
                msgImage.add_header('Content-ID', '<image2>')
                email_message.attach(msgImage)
            else:
                imFile = zpdir + '/imageFile1.jpg'
                imageFile = open(imFile, 'rb')
                msgImage = MIMEImage(imageFile.read())
                imageFile.close()
                msgImage.add_header('Content-ID', '<image1>')
                email_message.attach(msgImage)

        host = notification.content['host']
        port = notification.content['port']
        user = notification.content['user']
        password = notification.content['password']
        useTls = notification.content['useTls']
        email_from = notification.content['email_from']

        email_message['Subject'] = subject
        email_message['From'] = email_from
        email_message['To'] = ','.join(targets)
        email_message['Date'] = formatdate(None, True)

        result, errorMsg = sendEmail(email_message, host, port, useTls, user,
                                     password)

        if result:
            log.debug("Notification '%s' sent emails to: %s", notification.id,
                      targets)
        else:
            raise ActionExecutionException(
                "Notification '%s' FAILED to send emails to %s: %s" %
                (notification.id, targets, errorMsg))
    def execute(self, notification, signal):
        evt = _signalToContextDict(signal, '').get('evt')
        if not evt:
            return

        LOG.debug("DEBUG: %r", evt.__dict__)
    def executeBatch(self, notification, signal, targets):
        log.debug("Executing %s action for targets: %s", self.name, targets)
        self.setupAction(notification.dmd)

        data = _signalToContextDict(signal, self.options.get('zopeurl'), notification, self.guidManager)
        if signal.clear:
            log.debug('This is a clearing signal.')
            subject = processTalSource(notification.content['clear_subject_format'], **data)
            body = processTalSource(notification.content['clear_body_format'], **data)
        else:
            subject = processTalSource(notification.content['subject_format'], **data)
            body = processTalSource(notification.content['body_format'], **data)

        log.debug('Sending this subject: %s' % subject)
        log.debug('Sending this body: %s' % body)

        #plain_body = MIMEText(self._stripTags(body))
        plain_body = MIMEText(self._stripTags(body), _subtype='plain', _charset='utf-8')
        email_message = plain_body

        if notification.content['body_content_type'] == 'html':
            email_message = MIMEMultipart('related')
            email_message_alternative = MIMEMultipart('alternative')
            email_message_alternative.attach(plain_body)

            html_body = MIMEText(body.replace('\n', '<br />\n'), _subtype='html', _charset='utf-8')
            #html_body = MIMEText(body.replace('\n', '<br />\n'))
            html_body.set_type('text/html')
            email_message_alternative.attach(html_body)

            email_message.attach(email_message_alternative)

            # Attach image

            (zpdir, tail) = os.path.split(__file__)   # Get path to this directory
            imFile = zpdir + '/imageFile0.jpg'
            imageFile = open(imFile, 'rb')
            msgImage = MIMEImage(imageFile.read())
            imageFile.close()
            msgImage.add_header('Content-ID', '<image0>')
            email_message.attach(msgImage)

            # Add the trailer images - see and of body_format and clear_body_format
            if signal.clear:
                imFile = zpdir + '/imageFile2.jpg'
                imageFile = open(imFile, 'rb')
                msgImage = MIMEImage(imageFile.read())
                imageFile.close()
                msgImage.add_header('Content-ID', '<image2>')
                email_message.attach(msgImage)
            else:
                imFile = zpdir + '/imageFile1.jpg'
                imageFile = open(imFile, 'rb')
                msgImage = MIMEImage(imageFile.read())
                imageFile.close()
                msgImage.add_header('Content-ID', '<image1>')
                email_message.attach(msgImage)



        host = notification.content['host']
        port = notification.content['port']
        user = notification.content['user']
        password = notification.content['password']
        useTls = notification.content['useTls']
        email_from = notification.content['email_from']

        email_message['Subject'] = subject
        email_message['From'] = email_from
        email_message['To'] = ','.join(targets)
        email_message['Date'] = formatdate(None, True)

        result, errorMsg = sendEmail(
            email_message,
            host, port,
            useTls,
            user, password
        )

        if result:
            log.debug("Notification '%s' sent emails to: %s",
                     notification.id, targets)
        else:
            raise ActionExecutionException(
                "Notification '%s' FAILED to send emails to %s: %s" %
                (notification.id, targets, errorMsg)
            )
示例#21
0
    def execute(self, notification, signal):
        """
        Sets up the execution environment and POSTs to PagerDuty's Event API.
        """
        log.debug('Executing Pagerduty Events API action: %s', self.name)

        self.setupAction(notification.dmd)

        if signal.clear:
            eventType = EventType.RESOLVE
        elif signal.event.status == STATUS_ACKNOWLEDGED:
            eventType = EventType.ACKNOWLEDGE
        else:
            eventType = EventType.TRIGGER

        # Set up the TALES environment
        environ = {'dmd': notification.dmd, 'env': None}

        actor = signal.event.occurrence[0].actor

        device = None
        if actor.element_uuid:
            device = self.guidManager.getObject(actor.element_uuid)
        environ.update({'dev': device})

        component = None
        if actor.element_sub_uuid:
            component = self.guidManager.getObject(actor.element_sub_uuid)
        environ.update({'component': component})

        data = _signalToContextDict(signal, self.options.get('zopeurl'),
                                    notification, self.guidManager)
        environ.update(data)

        try:
            detailsList = json.loads(notification.content['details'])
        except ValueError:
            raise ActionExecutionException('Invalid JSON string in details')

        details = dict()
        for kv in detailsList:
            details[kv['key']] = kv['value']

        details['zenoss'] = {
            'version': ZENOSS_VERSION,
            'zenpack_version': zenpack_version(),
        }

        payload = {
            'severity': '${evt/severity}',
            'class': '${evt/eventClass}',
            'custom_details': details,
        }
        body = {
            'event_action': eventType,
            'dedup_key': data['evt'].evid,
            'payload': payload
        }

        for prop in REQUIRED_PROPERTIES:
            if prop in notification.content:
                payload.update({prop: notification.content[prop]})
            else:
                raise ActionExecutionException(
                    "Required property '%s' not found" % prop)

        if NotificationProperties.SERVICE_KEY in notification.content:
            body.update({'routing_key': notification.content['serviceKey']})
        else:
            raise ActionExecutionException(
                "API Key for PagerDuty service was not found. "
                "Did you configure a notification correctly?")

        self._performRequest(body, environ)