Beispiel #1
0
class PageAction(IActionBase, TargetableAction):
    implements(IAction)

    id = 'page'
    name = 'Page'
    actionContentInfo = IPageActionContentInfo
    shouldExecuteInBatch = False

    def configure(self, options):
        super(PageAction, self).configure(options)
        self.pagingWorkersTimeout = options.get('pagingWorkersTimeout', 30)
        self.processQueue = ProcessQueue(options.get('maxPagingWorkers', 1))
        self.processQueue.start()

    def setupAction(self, dmd):
        self.guidManager = GUIDManager(dmd)
        self.dmd = dmd
        self.page_command = dmd.pageCommand
        self.zenossHostname = dmd.zenossHostname

    def executeOnTarget(self, notification, signal, target):
        log.debug('Executing Page %s action on %s', self.name, target)
        environ = dict(os.environ)
        environ["RECIPIENT"] = target
        self._execute(notification, signal, environ)

    def _execute(self, notification, signal, env={}):
        self.setupAction(notification.dmd)
        log.debug('Executing page action: %s', self.name)
        data = self._signalToContextDict(signal, notification)

        skipfails = notification.content.get('skipfails', False)

        if signal.clear:
            log.debug('This is a clearing signal.')
            subject = processTalSource(notification.content['clear_subject_format'], skipfails, **data)
        else:
            subject = processTalSource(notification.content['subject_format'], skipfails, **data)

        msg = str(subject)

        log.debug('Sending page message: "%s"', msg)
        _protocol = SendPageProtocol(msg, notification)
        log.debug('Queueing up page action process. Page command is %s', self.page_command)
        self.processQueue.queueProcess(
            '/bin/sh', ('/bin/sh', '-c', self.page_command),
            env=env,
            processProtocol=_protocol,
            timeout=self.pagingWorkersTimeout,
            timeout_callback=_protocol.timedOut
        )

    def getActionableTargets(self, target):
        """
        @param target: This is an object that implements the IProvidesPagerAddresses
            interface.
        @type target: UserSettings or GroupSettings.
        """
        if IProvidesPagerAddresses.providedBy(target):
            return target.getPagerAddresses()
Beispiel #2
0
class PageAction(IActionBase, TargetableAction):
    implements(IAction)

    id = 'page'
    name = 'Page'
    actionContentInfo = IPageActionContentInfo
    shouldExecuteInBatch = False

    def configure(self, options):
        super(PageAction, self).configure(options)
        self.pagingWorkersTimeout = options.get('pagingWorkersTimeout', 30)
        self.processQueue = ProcessQueue(options.get('maxPagingWorkers', 1))
        self.processQueue.start()

    def setupAction(self, dmd):
        self.guidManager = GUIDManager(dmd)
        self.dmd = dmd
        self.page_command = dmd.pageCommand
        self.zenossHostname = dmd.zenossHostname

    def executeOnTarget(self, notification, signal, target):
        log.debug('Executing Page %s action on %s', self.name, target)
        environ = dict(os.environ)
        environ["RECIPIENT"] = target
        self._execute(notification, signal, environ)

    def _execute(self, notification, signal, env={}):
        self.setupAction(notification.dmd)
        log.debug('Executing page action: %s', self.name)
        data = self._signalToContextDict(signal, notification)

        skipfails = notification.content.get('skipfails', False)

        if signal.clear:
            log.debug('This is a clearing signal.')
            subject = processTalSource(notification.content['clear_subject_format'], skipfails, **data)
        else:
            subject = processTalSource(notification.content['subject_format'], skipfails, **data)

        msg = str(subject)

        log.debug('Sending page message: "%s"', msg)
        _protocol = SendPageProtocol(msg, notification)
        log.debug('Queueing up page action process. Page command is %s', self.page_command)
        self.processQueue.queueProcess(
            '/bin/sh', ('/bin/sh', '-c', self.page_command),
            env=env,
            processProtocol=_protocol,
            timeout=self.pagingWorkersTimeout,
            timeout_callback=_protocol.timedOut
        )

    def getActionableTargets(self, target):
        """
        @param target: This is an object that implements the IProvidesPagerAddresses
            interface.
        @type target: UserSettings or GroupSettings.
        """
        if IProvidesPagerAddresses.providedBy(target):
            return target.getPagerAddresses()
Beispiel #3
0
class CommandAction(IActionBase, TargetableAction):
    implements(IAction)

    id = 'command'
    name = 'Command'
    actionContentInfo = ICommandActionContentInfo

    shouldExecuteInBatch = False

    def configure(self, options):
        super(CommandAction, self).configure(options)
        self.processQueue = ProcessQueue(options.get('maxCommands', 10))
        self.processQueue.start()

    def setupAction(self, dmd):
        self.guidManager = GUIDManager(dmd)
        self.dmd = dmd
        self.zenossHostname = dmd.zenossHostname

    def execute(self, notification, signal):
        # check to see if we have any targets
        if notification.recipients:
            return super(CommandAction, self).execute(notification, signal)
        else:
            self._execute(notification, signal)

    def executeOnTarget(self, notification, signal, target):
        log.debug('Executing command action: %s on %s', self.name, target)
        environ = {}
        environ['user'] = getattr(self.dmd.ZenUsers, target, None)
        self._execute(notification, signal, environ)

    def _execute(self, notification, signal, extra_env= {}):
        self.setupAction(notification.dmd)
        log.debug('Executing command action: %s', self.name)

        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.get('user_env_format', '') or ''
        env = os.environ.copy()
        user_env = dict( envvar.split('=', 1) for envvar in user_env_format.split(';') if '=' in envvar)
        env.update(user_env)
        environ = {'dev': device, 'component': component, 'dmd': notification.dmd, 'env': env}
        data = self._signalToContextDict(signal, notification)
        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.update(extra_env)

        # Get the proper command
        command = processTalSource(command, **environ)

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

        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
        )

    def getActionableTargets(self, target):
        ids = [target.id]
        if isinstance(target, GroupSettings):
            ids = [x.id for x in target.getMemberUserSettings()]
        return ids

    def _escapeEvent(self, evt):
        """
        Escapes the relavent fields of an event context for event commands.
        """
        if evt.message:
            evt.message = self._wrapInQuotes(evt.message)
        if evt.summary:
            evt.summary = self._wrapInQuotes(evt.summary)
        return evt

    def _wrapInQuotes(self, msg):
        """
        Wraps the message in quotes, escaping any existing quote.

        Before:  How do you pronounce "Zenoss"?
        After:  "How do you pronounce \"Zenoss\"?"
        """
        QUOTE = '"'
        BACKSLASH = '\\'
        return ''.join((QUOTE, msg.replace(QUOTE, BACKSLASH + QUOTE), QUOTE))
Beispiel #4
0
class UserCommandAction(IActionBase, TargetableAction):
    implements(IAction)

    id = 'user_command'
    name = 'User Command'
    actionContentInfo = IUserCommandActionContentInfo

    shouldExecuteInBatch = False

    def configure(self, options):
        super(UserCommandAction, self).configure(options)
        self.processQueue = ProcessQueue(options.get('maxCommands', 10))
        self.processQueue.start()

    def setupAction(self, dmd):
        self.guidManager = GUIDManager(dmd)
        self.dmd = dmd

    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
        )

    def getActionableTargets(self, target):
        ids = [target.id]
        if isinstance(target, GroupSettings):
            ids = [x.id for x in target.getMemberUserSettings()]
        return ids

    def updateContent(self, content=None, data=None):
        updates = dict()

        properties = ['body_format', 'clear_body_format', 'action_timeout', 
                      'user_env_format']
        for k in properties:
            updates[k] = data.get(k)

        content.update(updates)

    def _escapeEvent(self, evt):
        """
        Escapes the relavent fields of an event context for event commands.
        """
        if evt.message:
            evt.message = self._wrapInQuotes(evt.message)
        if evt.summary:
            evt.summary = self._wrapInQuotes(evt.summary)
        return evt

    def _wrapInQuotes(self, msg):
        """
        Wraps the message in quotes, escaping any existing quote.

        Before:  How do you pronounce "Zenoss"?
        After:  "How do you pronounce \"Zenoss\"?"
        """
        QUOTE = '"'
        BACKSLASH = '\\'
        return ''.join((QUOTE, msg.replace(QUOTE, BACKSLASH + QUOTE), QUOTE))
class CommandAction(IActionBase, TargetableAction):
    implements(IAction)

    id = "command"
    name = "Command"
    actionContentInfo = ICommandActionContentInfo

    shouldExecuteInBatch = False

    def configure(self, options):
        super(CommandAction, self).configure(options)
        self.processQueue = ProcessQueue(options.get("maxCommands", 10))
        self.processQueue.start()

    def setupAction(self, dmd):
        self.guidManager = GUIDManager(dmd)
        self.dmd = dmd

    def execute(self, notification, signal):
        # check to see if we have any targets
        if notification.recipients:
            return super(CommandAction, self).execute(notification, signal)
        else:
            self._execute(notification, signal)

    def executeOnTarget(self, notification, signal, target):
        log.debug("Executing command action: %s on %s", self.name, target)
        environ = {}
        environ["user"] = getattr(self.dmd.ZenUsers, target, None)
        self._execute(notification, signal, environ)

    def _execute(self, notification, signal, extra_env={}):
        self.setupAction(notification.dmd)
        log.debug("Executing command action: %s", self.name)

        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.get("user_env_format", "") or ""
        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 = self._signalToContextDict(signal, notification)
        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.update(extra_env)

        # Get the proper command
        command = processTalSource(command, **environ)

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

        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,
        )

    def getActionableTargets(self, target):
        ids = [target.id]
        if isinstance(target, GroupSettings):
            ids = [x.id for x in target.getMemberUserSettings()]
        return ids

    def _escapeEvent(self, evt):
        """
        Escapes the relavent fields of an event context for event commands.
        """
        if evt.message:
            evt.message = self._wrapInQuotes(evt.message)
        if evt.summary:
            evt.summary = self._wrapInQuotes(evt.summary)
        return evt

    def _wrapInQuotes(self, msg):
        """
        Wraps the message in quotes, escaping any existing quote.

        Before:  How do you pronounce "Zenoss"?
        After:  "How do you pronounce \"Zenoss\"?"
        """
        QUOTE = '"'
        BACKSLASH = "\\"
        return "".join((QUOTE, msg.replace(QUOTE, BACKSLASH + QUOTE), QUOTE))