Ejemplo n.º 1
0
def createSoftwareDict(prodKey, vendor, description, installDate):
    """
    Create a software dictionary that can be passed as the data parameter when
    constructing an ObjectMap that represents a Software entity.
    """
    return {"id": Utils.prepId(prodKey),
            "setProductKey": MultiArgs(prodKey, Utils.prepId(vendor)),
            "setDescription": description,
            "setInstallDate": formatDate(installDate)}
Ejemplo n.º 2
0
def createSoftwareDict(prodKey, vendor, description, installDate):
    """
    Create a software dictionary that can be passed as the data parameter when
    constructing an ObjectMap that represents a Software entity.
    """
    return {
        "id": Utils.prepId(prodKey),
        "setProductKey": MultiArgs(prodKey, Utils.prepId(vendor)),
        "setDescription": description,
        "setInstallDate": formatDate(installDate),
    }
Ejemplo n.º 3
0
    def executeOnTarget(self, notification, signal, target):
        """
        @TODO: handle the deferred parameter on the sendPage call.
        """
        log.debug('Executing action: Page')

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

        success, errorMsg = Utils.sendPage(
            target,
            subject,
            self.page_command,
            #deferred=self.options.cycle)
            deferred=False)

        if success:
            log.debug("Notification '%s' sent page to %s." %
                      (notification, target))
        else:
            raise ActionExecutionException(
                "Notification '%s' failed to send page to %s. (%s)" %
                (notification, target, errorMsg))
Ejemplo n.º 4
0
 def manage_pagerTest(self, REQUEST=None):
     ''' Send a test page
     '''
     destSettings = self.getUserSettings(self.getId())
     destPagers = [ x.strip() for x in
         (destSettings.getPagerAddresses() or []) ]
     msg = None
     fqdn = socket.getfqdn()
     srcId = self.getUser().getId()
     testMsg = ('Test sent by %s' % srcId +
             ' from the Zenoss installation on %s.' % fqdn)
     for destPager in destPagers:
         result, errorMsg = Utils.sendPage(destPager, testMsg,
                                 self.dmd.pageCommand)
         if result:
             msg = 'Test page sent to %s' % ', '.join(destPagers)
         else:
             msg = 'Test failed: %s' % errorMsg
             break
     if not destPagers:
         msg = 'Test page not sent, user has no pager number.'
     if REQUEST:
         messaging.IMessageSender(self).sendToBrowser(
             'Pager Test', msg)
         return self.callZenScreen(REQUEST)
     else:
         return msg
Ejemplo n.º 5
0
    def executeOnTarget(self, notification, signal, target):
        """
        @TODO: handle the deferred parameter on the sendPage call.
        """
        log.debug("Executing action: Page")

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

        success, errorMsg = Utils.sendPage(
            target,
            subject,
            self.page_command,
            # deferred=self.options.cycle)
            deferred=False,
        )

        if success:
            log.debug("Notification '%s' sent page to %s." % (notification, target))
        else:
            raise ActionExecutionException(
                "Notification '%s' failed to send page to %s. (%s)" % (notification, target, errorMsg)
            )
Ejemplo n.º 6
0
    def updateTrigger(self, **data):
        user = getSecurityManager().getUser()

        triggerObj = self._guidManager.getObject(data['uuid'])

        log.debug('Trying to update trigger: %s' % triggerObj.id)

        if self.triggerPermissions.userCanManageTrigger(user, triggerObj):
            if 'globalRead' in data:
                triggerObj.globalRead = data.get('globalRead', False)
                log.debug('setting globalRead %s' % triggerObj.globalRead)

            if 'globalWrite' in data:
                triggerObj.globalWrite = data.get('globalWrite', False)
                log.debug('setting globalWrite %s' % triggerObj.globalWrite)

            if 'globalManage' in data:
                triggerObj.globalManage = data.get('globalManage', False)
                log.debug('setting globalManage %s' % triggerObj.globalManage)

            triggerObj.users = data.get('users', [])
            self.triggerPermissions.clearPermissions(triggerObj)
            self.triggerPermissions.updatePermissions(
                self._guidManager, triggerObj
            )

        if self.triggerPermissions.userCanUpdateTrigger(user, triggerObj):
            if "name" in data:
                triggerObj.setTitle(cgi.escape(data["name"]))
                parent = triggerObj.getPrimaryParent()
                path = triggerObj.absolute_url_path()
                oldId = triggerObj.getId()
                newId = triggerObj.title
                if not isinstance(newId, unicode):
                    newId = Utils.prepId(newId)
                newId = newId.strip()
                if not newId:
                    raise Exception("New trigger id cannot be empty.")
                if newId != oldId:
                    # rename the trigger id since its title changed
                    try:
                        if triggerObj.getDmd().Triggers.findObject(newId):
                            message = 'Trigger %s already exists' % newId
                            # Duplicate trigger found
                            raise Exception(message)
                    except AttributeError as ex:
                        # the newId is not a duplicate
                        pass

                    try:
                        parent.manage_renameObject(oldId, newId)
                        triggerObj.id = newId
                    except CopyError:
                        raise Exception("Trigger rename failed.")

            trigger = from_dict(zep.EventTrigger, data)
            response, content = self.triggers_service.updateTrigger(trigger)
            return content
Ejemplo n.º 7
0
    def run(self):
        'Fetch a report by URL and post as a mime encoded email'
        self.connect()
        o = self.options
        if not o.passwd and not o.url:
            sys.stderr.write("No zenoss password or url provided\n")
            sys.exit(1)
        try:
            user = self.dmd.ZenUsers._getOb(o.user)
        except AttributeError:
            sys.stderr.write("Unknown user %s\n" % o.user)
            sys.exit(1)

        if not o.addresses and user.email:
            o.addresses = [user.email]
        if not o.addresses:
            sys.stderr.write("No address for user %s\n" % o.user)
            sys.exit(1)
        page = Page(o.user, o.passwd)
        url = self.mangleUrl(o.url)

        reportFileType = self.determineFileFormat(o.reportFileType)
        reportFileName = "report_screenshot." + reportFileType
        page.generateScreenShot(url, reportFileName)
        msg = page.mail(reportFileName)

        # we aren't actually parsing any HTML so rely on the last "segment"
        # of the URL for the subject if one is not provided
        title = urllib2.unquote(url.split("/")[-1].split("?")[0])
        if o.subject:
            msg['Subject'] = o.subject
        elif title:
            msg['Subject'] = title
        else:
            msg['Subject'] = 'Zenoss Report'
        msg['From'] = o.fromAddress
        msg['To'] = ', '.join(o.addresses)

        result, errorMsg = Utils.sendEmail(msg, self.dmd.smtpHost,
                                           self.dmd.smtpPort,
                                           self.dmd.smtpUseTLS,
                                           self.dmd.smtpUser,
                                           self.dmd.smtpPass)

        # delete the file so we don't resend it with the next failing request
        if os.path.isfile(reportFileName):
            os.remove(reportFileName)

        if result:
            print "sent email: %s to:%s" % (msg.as_string(), o.addresses)
        else:
            sys.stderr.write("failed to send email to %s: %s %s\n" %
                             (o.addresses, msg.as_string(), errorMsg))
            sys.exit(1)

        sys.exit(0)
Ejemplo n.º 8
0
    def run(self):
        'Fetch a report by URL and post as a mime encoded email'
        self.connect()
        o = self.options
        if not o.passwd and not o.url:
            sys.stderr.write("No zenoss password or url provided\n")
            sys.exit(1)
        try:
            user = self.dmd.ZenUsers._getOb(o.user)
        except AttributeError:
            sys.stderr.write("Unknown user %s\n" % o.user)
            sys.exit(1)

        if not o.addresses and user.email:
            o.addresses = [user.email]
        if not o.addresses:
            sys.stderr.write("No address for user %s\n" % o.user)
            sys.exit(1)
        page = Page(o.user, o.passwd)
        url = self.mangleUrl(o.url)

        reportFileType = self.determineFileFormat(o.reportFileType)
        reportFileName = "report_screenshot." + reportFileType
        page.generateScreenShot(url, reportFileName)
        msg = page.mail(reportFileName)

        # we aren't actually parsing any HTML so rely on the last "segment"
        # of the URL for the subject if one is not provided
        title = urllib2.unquote(url.split("/")[-1].split("?")[0])
        if o.subject:
            msg['Subject'] = o.subject
        elif title:
            msg['Subject'] = title
        else:
            msg['Subject'] = 'Zenoss Report'
        msg['From'] = o.fromAddress
        msg['To'] = ', '.join(o.addresses)

        result, errorMsg = Utils.sendEmail(msg,
                                           self.dmd.smtpHost,
                                           self.dmd.smtpPort,
                                           self.dmd.smtpUseTLS,
                                           self.dmd.smtpUser,
                                           self.dmd.smtpPass)

        # delete the file so we don't resend it with the next failing request
        if os.path.isfile(reportFileName):
            os.remove(reportFileName)

        if result:
            print "sent email: %s to:%s" % ( msg.as_string(), o.addresses)
        else:
            sys.stderr.write("failed to send email to %s: %s %s\n" %(o.addresses, msg.as_string(), errorMsg))
            sys.exit(1)

        sys.exit(0)
Ejemplo n.º 9
0
    def sendEmail( self ):
        """
        Sends an email using the email account configured in Zenoss Settings
        One email is sent to each --toaddress. The subject line is a number
        that is saved until the email has been received.
        """
        
        sentMail = False
        subject = str( self.emailNumber )
        
        # loop thru each "to" address
        for address in self.toAddresses:
            
            # Check to see if this "to" address queue is full. If so,
            # delete the oldest from the queue
            if len( self.toAddresses[address].subjects ) == \
                    self.options.emailqueuelength:
                self.log.warning( 'Email queue %s full.' % address )
                del self.toAddresses[address].subjects[0]
            
            # set up new mail message
            emsg = MIMEText('')
            emsg['From'] = self.dmd.getEmailFrom()
            emsg['Subject'] = subject
            emsg['To'] = address

            # send it
            result, errorMsg = Utils.sendEmail( emsg, 
                                                self.dmd.smtpHost,
                                                self.dmd.smtpPort, 
                                                self.dmd.smtpUseTLS, 
                                                self.dmd.smtpUser,
                                                self.dmd.smtpPass )
            # if successful send
            if result:
                msg = "Sent email \'%s\' to %s" % ( subject, address )
                self.log.info( msg )
                self.toAddresses[address].subjects.append( subject )
                sentMail = True
                # If this address was previously flagged with a failure, but
                # now succeeded, send event
                if self.toAddresses[address].sendFailure:
                    msg = 'Sent email to %s' % address
                    self.sendEmailPingEvent( 'epSendClear', address, msg )
                    self.toAddresses[address].sendFailure = False
            
            # if not successful send
            else:
                msg = "Failed to send email \'%s\' to %s" % ( subject, address )
                self.log.warning( msg )
                msg = 'Failed to send email to %s' % address
                self.sendEmailPingEvent( 'epSendFailure', address, msg )
                self.toAddresses[address].sendFailure = True
       
        if sentMail:
            self.incrementEmailNumber()
Ejemplo n.º 10
0
    def _signalToContextDict(self, signal, notification=None):
        """
        Parse the event data out from the signal
        """
        # use zopeurl in the zenactiond.conf file if it is defined else use the value from DMD
        zopeurl = self.options.get('zopeurl')
        if zopeurl == Utils.getDefaultZopeUrl() and hasattr(self, "zenossHostname"):
            zopeurl = self.zenossHostname

        data = _signalToContextDict(signal, zopeurl, notification, self.guidManager)
        return data
Ejemplo n.º 11
0
    def manage_resetPassword(self):
        """
        Reset a password.
        """
        email = self.email.strip()
        if not email:
            messaging.IMessageSender(self).sendToBrowser(
                'Password Reset Failed',
                'Cannot send password reset email; user has no'+
                ' email address.',
                priority=messaging.WARNING
            )
            return self.callZenScreen(self.REQUEST)

        newpw = self.generatePassword()
        body = """
        Your Zenoss password has been reset at %s's request.

        Your new password is: %s
        """ % (self.getUser().getId(), newpw)
        msg = MIMEText(body)
        msg['Subject'] = 'Zenoss Password Reset Request'
        msg['From'] = self.dmd.getEmailFrom()
        msg['To'] = email
        msg['Date'] = DateTime().rfc822()
        result, errorMsg = Utils.sendEmail(msg, self.dmd.smtpHost,
                            self.dmd.smtpPort,
                            self.dmd.smtpUseTLS, self.dmd.smtpUser,
                            self.dmd.smtpPass)
        if result:
            userManager = self.acl_users.userManager
            try:
                userManager.updateUserPassword(self.id, newpw)
            except KeyError:
                self.getPhysicalRoot().acl_users.userManager.updateUserPassword(
                                self.id, newpw)
            messaging.IMessageSender(self).sendToBrowser(
                'Password reset',
                'An email with a new password has been sent.'
            )
            audit('UI.User.ResetPassword', username=self.id)
            loggedInUser = self.REQUEST['AUTHENTICATED_USER']
            # we only want to log out the user if it's *their* password
            # they've changed, not, for example, if the admin user is
            # changing another user's password
            if loggedInUser.getUserName() == self.id:
                self.acl_users.logout(self.REQUEST)
        else:
            messaging.IMessageSender(self).sendToBrowser(
                'Password reset failed',
                'Unable to send password reset email: %s' % errorMsg,
                priority=messaging.WARNING
            )
        return self.callZenScreen(self.REQUEST)
Ejemplo n.º 12
0
 def setDashboardState(self, userid=None, REQUEST=None):
     """ Store a user's portlets and layout. If userid is not passed
         set the state for the current user.
     """
     user = self.getUserSettings(userid)
     posted = Utils.extractPostContent(REQUEST)
     if posted:
         user.dashboardState = posted
         if REQUEST:
             audit('UI.Dashboard.Edit', username=userid)
     return True
Ejemplo n.º 13
0
    def run(self):
        'Fetch a report by URL and post as a mime encoded email'
        self.connect()
        o = self.options
        if not o.passwd and not o.url:
            self.log.error("No zenoss password or url provided")
            sys.exit(1)
        try:
            user = self.dmd.ZenUsers._getOb(o.user)
        except AttributeError:
            self.log.error("Unknown user %s" % o.user)
            sys.exit(1)

        if not o.addresses and user.email:
            o.addresses = [user.email]
        if not o.addresses:
            self.log.error("No address for user %s" % o.user)
            sys.exit(1)
        page = Page(o.user, o.passwd, o.div, o.comment)
        url = self.mangleUrl(o.url)
        # ZEN-2414: POST "doReport" so it will export as CSV rather than HTML.
        page.fetch(url,
                   dataMap={'doExport':''},
                   errorHTML='Could not retrieve the report.')
        msg = page.mail()
        if o.subject:
            msg['Subject'] = o.subject
        elif page.title:
            msg['Subject'] = page.title
        else:
            msg['Subject'] = 'Zenoss Report'
        msg['From'] = o.fromAddress
        msg['To'] = ', '.join(o.addresses)
        result, errorMsg = Utils.sendEmail(msg,
                                           self.dmd.smtpHost,
                                           self.dmd.smtpPort,
                                           self.dmd.smtpUseTLS,
                                           self.dmd.smtpUser, 
                                           self.dmd.smtpPass)
        if result:
            self.log.debug("sent email: %s to:%s", msg.as_string(), o.addresses)
        else:
            self.log.info("failed to send email to %s: %s %s",
                          o.addresses, msg.as_string(), errorMsg)
            sys.exit(1)
        sys.exit(0)
Ejemplo n.º 14
0
 def manage_emailTest(self, REQUEST=None):
     ''' Send a test email to the given userid.
     '''
     destSettings = self.getUserSettings(self.getId())
     destAddresses = destSettings.getEmailAddresses()
     msg = None
     if destAddresses:
         fqdn = socket.getfqdn()
         thisUser = self.getUser()
         srcId = thisUser.getId()
         self.getUserSettings(srcId)
         srcAddress = self.dmd.getEmailFrom()
         # Read body from file probably
         body = ('This is a test message sent by %s' % srcId +
                 ' from the Zenoss installation on %s.' % fqdn)
         emsg = MIMEText(body)
         emsg['Subject'] = 'Zenoss Email Test'
         emsg['From'] = srcAddress
         emsg['To'] = ', '.join(destAddresses)
         emsg['Date'] = DateTime().rfc822()
         result, errorMsg = Utils.sendEmail(emsg, self.dmd.smtpHost,
                             self.dmd.smtpPort,
                             self.dmd.smtpUseTLS, self.dmd.smtpUser,
                             self.dmd.smtpPass)
         if result:
             msg = 'Test email sent to %s' % ', '.join(destAddresses)
         else:
             msg = 'Test failed: %s' % errorMsg
     else:
         msg = 'Test email not sent, user has no email address.'
     if REQUEST:
         messaging.IMessageSender(self).sendToBrowser(
             'Email Test',
             msg.replace("'", "\\'")
         )
         return self.callZenScreen(REQUEST)
     else:
         return msg
Ejemplo n.º 15
0
def _getBaseUrl(zopeurl):
    if not zopeurl:
        zopeurl = Utils.getDefaultZopeUrl()
    return '%s/zport/dmd' % zopeurl
Ejemplo n.º 16
0
def _getBaseUrl(zopeurl):
    if not zopeurl:
        zopeurl = Utils.getDefaultZopeUrl()
    return zopeurl + getUtility(IVirtualRoot).ensure_virtual_root('/zport/dmd')