예제 #1
0
    def remove(self, uid, id=None, properties=None):
        """Removes the local instance of the each property in properties.
        Note that the property will only be deleted if a hasProperty is true

        @param uid {str} Path to the object owning the properties.
        @param id {str} The ID of the property to delete.
        @param properties {list[str]} List of property IDs to delete.

        Note that specifying both 'id' and 'properties' is valid.
        Duplicate property IDs skipped.
        """
        facade = self._getFacade()
        names = set()
        if id is not None:
            names.add(id)
        if properties is not None:
            if not isinstance(properties, (list, tuple)):
                properties = [properties]
            names.update(properties)
        for name in names:
            facade.deleteZenProperty(uid, name)
            obj = facade._getObject(uid)
            audit('UI.zProperty.Delete', name, data_={obj.meta_type: uid})
        if len(names) == 1:
            return DirectResponse.succeed(
                msg="Property %s successfully deleted." % names.pop()
            )
        return DirectResponse.succeed(
            msg="Successfully deleted %s properties." % len(names)
        )
예제 #2
0
    def pingDevices(self, evids):
        """Ping devices associated with evids."""
        if not evids:
            return DirectResponse.succeed(msg="No events selected.")

        # Gather unique devices.
        devices = {}

        zep = getFacade('zep')
        evt_filter = zep.createEventFilter(uuid=evids)
        evt_summaries = zep.getEventSummaries(offset=0, filter=evt_filter)
        for evt_summary in evt_summaries.get('events', []):
            device_id = evt_summary['occurrence'][0]['actor'][
                'element_identifier']
            if device_id in devices:
                continue

            device = self.context.dmd.Devices.findDeviceByIdExact(device_id)
            if not device or not device.getManageIp():
                continue

            devices[device_id] = device

        # Run ping for each unique device.
        ping_output = {}

        for device_id, device in devices.iteritems():
            ping_output[device_id] = subprocess.check_output(
                "ping -c3 {} ; exit 0".format(device.getManageIp()),
                stderr=subprocess.STDOUT,
                shell=True)

        return DirectResponse.succeed(data=ping_output)
예제 #3
0
    def pingDevices(self, evids):
        """Ping devices associated with evids."""
        if not evids:
            return DirectResponse.succeed(msg="No events selected.")

        # Gather unique devices.
        devices = {}

        zep = getFacade('zep')
        evt_filter = zep.createEventFilter(uuid=evids)
        evt_summaries = zep.getEventSummaries(offset=0, filter=evt_filter)
        for evt_summary in evt_summaries.get('events', []):
            device_id = evt_summary['occurrence'][0]['actor']['element_identifier']
            if device_id in devices:
                continue

            device = self.context.dmd.Devices.findDeviceByIdExact(device_id)
            if not device or not device.getManageIp():
                continue

            devices[device_id] = device

        # Run ping for each unique device.
        ping_output = {}

        for device_id, device in devices.iteritems():
            ping_output[device_id] = subprocess.check_output(
                "ping -c3 {} ; exit 0".format(device.getManageIp()),
                stderr=subprocess.STDOUT,
                shell=True)

        return DirectResponse.succeed(data=ping_output)
예제 #4
0
    def removeSavedSearch(self, searchName):
        """
        Removes the search specified by searchName
        @param string searchName
        """
        facade = self._getFacade()
        if facade.noSaveSearchProvidersPresent():
            return DirectResponse.succeed()

        # save the search
        facade.removeSavedSearch(searchName)
        return DirectResponse.succeed()
예제 #5
0
    def removeSavedSearch(self, searchName):
        """
        Removes the search specified by searchName
        @param string searchName
        """
        facade = self._getFacade()
        if facade.noSaveSearchProvidersPresent():
            return DirectResponse.succeed()

        # save the search
        facade.removeSavedSearch(searchName)
        return DirectResponse.succeed()
예제 #6
0
    def updateSavedSearch(self, searchName, queryString):
        """
        Updates the specified search with the new query
        @param string searchName: name of the search we want to update
        @param string query: value of the new query we are searching on
        """
        facade = self._getFacade()
        if facade.noSaveSearchProvidersPresent():
            return DirectResponse.succeed()

        # save the search
        facade.updateSavedSearch(searchName, queryString)
        return DirectResponse.succeed()
예제 #7
0
    def updateSavedSearch(self, searchName, queryString):
        """
        Updates the specified search with the new query
        @param string searchName: name of the search we want to update
        @param string query: value of the new query we are searching on
        """
        facade = self._getFacade()
        if facade.noSaveSearchProvidersPresent():
            return DirectResponse.succeed()

        # save the search
        facade.updateSavedSearch(searchName, queryString)
        return DirectResponse.succeed()
예제 #8
0
    def getAllSavedSearches(self, query=None, addManageSavedSearch=False):
        """
        @returns [ISavedSearchInfo] All the searches the logged in
        user can access
        """
        facade = self._getFacade()
        if facade.noSaveSearchProvidersPresent():
            return DirectResponse.succeed()

        data = Zuul.marshal(facade.getSavedSearchesByUser())
        if addManageSavedSearch:
            manageName = '<span id="manage-search-link">%s</span>' % (_t('Manage Saved Searches...'))
            data.append(dict(id='manage_saved_search', name=manageName))
        return DirectResponse.succeed(data=data)
예제 #9
0
파일: routers.py 프로젝트: c0ns0le/zenoss-4
    def getAllSavedSearches(self, query=None, addManageSavedSearch=False):
        """
        @returns [ISavedSearchInfo] All the searches the logged in
        user can access
        """
        facade = self._getFacade()
        if facade.noSaveSearchProvidersPresent():
            return DirectResponse.succeed()

        data = Zuul.marshal(facade.getSavedSearchesByUser())
        if addManageSavedSearch:
            manageName = '<span id="manage-search-link">%s</span>' % (_t('Manage Saved Searches...'))
            data.append(dict(id='manage_saved_search', name=manageName))
        return DirectResponse.succeed(data=data)
예제 #10
0
    def saveSearch(self, queryString, searchName):
        """
        Adds this search to our collection of saved searches
        @param string queryString: term we are searching for
        @param string searchName: our query string's identifier
        """
        facade = self._getFacade()
        if facade.noSaveSearchProvidersPresent():
            return DirectResponse.succeed()

        creator = self._getLoggedinUserId()

        # save the search
        facade.saveSearch(queryString, searchName, creator)
        return DirectResponse.succeed()
예제 #11
0
    def saveSearch(self, queryString, searchName):
        """
        Adds this search to our collection of saved searches
        @param string queryString: term we are searching for
        @param string searchName: our query string's identifier
        """
        facade = self._getFacade()
        if facade.noSaveSearchProvidersPresent():
            return DirectResponse.succeed()

        creator = self._getLoggedinUserId()

        # save the search
        facade.saveSearch(queryString, searchName, creator)
        return DirectResponse.succeed()
예제 #12
0
 def editProduct(self, params=None):
     """
     Edit a product
     """
     facade = self._getFacade()
     oldData = facade.getProductData(params['uid'], params['oldname'])[0]
     scheduled = facade.editProduct(params)
     audit('UI.Manufacturers.editProduct',
           params['uid'],
           data_=params,
           oldData_=oldData)
     if scheduled:
         return DirectResponse.succeed(
             "Scheduled job to update product %s." % params['oldname'])
     return DirectResponse.succeed()
예제 #13
0
 def stop(self, uids):
     """
     Will issue the command to stop the selected ids
     @type uids: Array[Strings]
     @param uids: List of valid daemon ids that will need to stopped
     @rtype: DirectResposne
     @return: DirectReponse of success if no errors are encountered
     """
     facade = self._getFacade()
     for uid in uids:
         facade.stop(uid)
         audit('UI.Applications.Stop', id)
     if len(uids) > 1:
         return DirectResponse.succeed("Stopped %s daemons" % len(uids))
     return DirectResponse.succeed()
예제 #14
0
 def stop(self, uids):
     """
     Will issue the command to stop the selected ids
     @type uids: Array[Strings]
     @param uids: List of valid daemon ids that will need to stopped
     @rtype: DirectResposne
     @return: DirectReponse of success if no errors are encountered
     """
     facade = self._getFacade()
     for uid in uids:
         facade.stop(uid)
         audit('UI.Applications.Stop', id)
     if len(uids) > 1:
         return DirectResponse.succeed("Stopped %s daemons" % len(uids))
     return DirectResponse.succeed()
예제 #15
0
 def testRule(self, rule):
     """
     Test our rule by compiling it.
     """
     facade = self._getFacade()
     facade.testRule(rule)
     return DirectResponse.succeed()
예제 #16
0
    def getIpAddresses(self, uid, start=0, params=None, limit=50, sort='ipAddressAsInt',
                       page=None, dir='ASC'):
        """
        Given a subnet, get a list of IP addresses and their relations.

        @type  uid: string
        @param uid: Unique identifier of a subnet
        @type  start: integer
        @param start: Offset to return the results from; used in pagination
        @type  params: string
        @param params: Not used
        @type  limit: integer
        @param limit: Number of items to return; used in pagination
        @type  sort: string
        @param sort: (optional) Key on which to sort the return results;
                     defaults to 'name'
        @type  order: string
        @param order: Sort order; can be either 'ASC' or 'DESC'
        @rtype: DirectResponse
        """
        if isinstance(params, basestring):
            params = unjson(params)
        instances = self.api.getIpAddresses(uid=uid, start=start, params=params,
                                          limit=limit, sort=sort, dir=dir)

        keys = ['name', 'netmask', 'pingstatus', 'snmpstatus', 'uid',
                'device', 'interface', 'macAddress',
                'interfaceDescription', 'manageDevice']
        data = Zuul.marshal(instances.results, keys)
        return DirectResponse.succeed(data=data, totalCount=instances.total,
                                      hash=instances.hash_)
예제 #17
0
 def removeAdmin(self, uid, id):
     """
     removes admin and role on a existing device
     """
     facade = self._getFacade()
     facade.removeAdmin(uid, id)
     return DirectResponse.succeed()
예제 #18
0
    def getInstances(self, uid, start=0, params=None, limit=50, sort='name',
                     page=None, dir='ASC'):
        """
        Get a list of instances for a process UID.

        @type  uid: string
        @param uid: Process UID to get instances of
        @type  start: integer
        @param start: (optional) Offset to return the results from; used in
                      pagination (default: 0)
        @type  params: dictionary
        @param params: (optional) Key-value pair of filters for this search.
        @type  limit: integer
        @param limit: (optional) Number of items to return; used in pagination
                      (default: 50)
        @type  sort: string
        @param sort: (optional) Key on which to sort the return results (default:
                     'name')
        @type  dir: string
        @param dir: (optional) Sort order; can be either 'ASC' or 'DESC'
                    (default: 'ASC')
        @rtype:   DirectResponse
        @return:  B{Properties}:
             - data: ([dictionary]) List of objects representing process instances
             - total: (integer) Total number of instances
        """
        facade = self._getFacade()
        instances = facade.getInstances(uid, start, limit, sort, dir, params)
        keys = ['device', 'monitored', 'pingStatus', 'processName', 'name', 
                'uid', 'minProcessCount', 'maxProcessCount']
        data = Zuul.marshal(instances, keys)
        return DirectResponse.succeed(data=data, totalCount=instances.total)
예제 #19
0
    def addThreshold(self, **data):
        """
        Add a threshold.

        @type    uid: string
        @keyword uid: Unique identifier of template to add threshold to
        @type    thresholdType: string
        @keyword thresholdType: Type of the new threshold. From getThresholdTypes()
        @type    thresholdId: string
        @keyword thresholdId: ID of the new threshold
        @type    dataPoints: [string]
        @keyword dataPoints: List of data points to select for this threshold
        @rtype:  DirectResponse
        @return: Success message
        """
        uid = data['uid']
        thresholdType = data['thresholdType']
        thresholdId = data['thresholdId']
        dataPoints = data.get('dataPoints', None)
        facade = self._getFacade()
        facade.addThreshold(uid, thresholdType, thresholdId, dataPoints)
        thresholdUid = uid + '/thresholds/' + thresholdId
        audit('UI.Threshold.Add', thresholdUid, thresholdtype=thresholdType,
              datapoints=dataPoints)
        return DirectResponse.succeed()
예제 #20
0
 def addMaintWindow(self, params):
     """
     adds a new Maintenance Window
     """    
     facade = self._getFacade()
     facade.addMaintWindow(params)
     return DirectResponse.succeed(msg="Maintenance Window %s added successfully." % (params['name']))    
예제 #21
0
 def deleteUserCommand(self, uid, id):
     """
     delete a user command
     """
     facade = self._getFacade()
     data = facade.deleteUserCommand(uid, id)
     return DirectResponse.succeed(data=Zuul.marshal(data))         
예제 #22
0
 def getAccountSettings(self):
     """
     Retrieves the account object from /zport/dmd/pagerduty_account.
     """
     dmdRoot = _dmdRoot(self.context)
     account = getattr(dmdRoot, ACCOUNT_ATTR, models.account.Account(None, None))
     return DirectResponse.succeed(msg=None, data=account.getDict())
예제 #23
0
 def getUsers(self, keys=None, start=0, limit=50, page=0,
                 sort='name', dir='ASC', name=None):
     """
     Retrieves a list of users. This method supports pagination.
     @type  start: integer
     @param start: (optional) Offset to return the results from; used in
                   pagination (default: 0)
     @type  name: string
     @param name: (optional) filter to be applied to users returned (default: None)
     @type  limit: integer
     @param limit: (optional) Number of items to return; used in pagination
                   (default: 50)
     @type  sort: string
     @param sort: (optional) Key on which to sort the return results (default:
                  'name')
     @type  dir: string
     @param dir: (optional) Sort order; can be either 'ASC' or 'DESC'
                 (default: 'ASC')
     @rtype:   DirectResponse
     @return:  B{Properties}:
          - data: (list) Dictionaries of user properties
          - totalCount: (integer) Number of devices returned
     """
     facade = self._getFacade()
     users = facade.getUsers(start=start, limit=limit, sort=sort,
                             dir=dir, name=name)
     total = users.total
     data = Zuul.marshal(users, keys)
     return DirectResponse.succeed(data=data, totalCount=total)
예제 #24
0
 def addCustomProperty(self, id, value, label, uid, type):
     """
     adds a new property to the / of the tree
     """    
     facade = self._getFacade()
     facade.addCustomProperty(id, value, label, uid, type)
     return DirectResponse.succeed(msg="Property %s added successfully." % (id))
예제 #25
0
    def deleteNode(self, uid):
        """
        Deletes a node from the tree.

        B{NOTE}: You can not delete a root node of a tree

        @type  uid: string
        @param uid: Unique identifier of the node we wish to delete
        @rtype:   DirectResponse
        @return:  B{Properties}:
             - msg: (string) Status message
        """
        # make sure we are not deleting a root node
        if not self._canDeleteUid(uid):
            raise Exception('You cannot delete the root node')
        facade = self._getFacade()
        node = facade._getObject(uid)

        # Audit first so it can display details like "name" while they exist.
        # Trac #29148: When we delete a DeviceClass we also delete its devices
        #     and child device classes and their devices, so audit them all.
        if isinstance(node, DeviceClass):
            childBrains = ICatalogTool(node).search((
                'Products.ZenModel.DeviceClass.DeviceClass',
                'Products.ZenModel.Device.Device',
            ))
            for child in childBrains:
                audit(['UI', getDisplayType(child), 'Delete'], child.getPath())
        else:
            audit(['UI', getDisplayType(node), 'Delete'], node)

        facade.deleteNode(uid)
        msg = "Deleted node '%s'" % uid
        return DirectResponse.succeed(msg=msg)
예제 #26
0
 def deleteMaintWindow(self, uid, id):
     """
     delete a maintenance window
     """
     facade = self._getFacade()
     data = facade.deleteMaintWindow(uid, id)
     return DirectResponse.succeed(data=Zuul.marshal(data))
예제 #27
0
    def update_zovp_account(self, zovPushKey=None , triggers=None):

        if zovPushKey == None:
            return DirectResponse.fail("Missing zovPushKey")

        dmdRoot = _dmdRoot(self.context)
        accounts = getattr(dmdRoot, 'zovp_accounts', [])

        this_account_details = models.zovpaccount.ZOVPAccount(zovPushKey, triggers)

        index = 0
        newaccount = True

        for accountDetails in accounts:
            if accountDetails.zovPushKey == zovPushKey:
                newaccount = False
                break
            else:
                index += 1


        if newaccount == True:
            accounts.append(this_account_details)
        else:
            accounts[index] = this_account_details

        setattr(dmdRoot, 'zovp_accounts', accounts)
        return DirectResponse.succeed("Account updated")
예제 #28
0
 def _treeMoveUpdates(self, uid, target):
     oldPathTokens = uid.split('/')
     oldPath = '/'.join(oldPathTokens[:-1])
     oldBranch = self._marshalPath(oldPath,
                                   localKeys=self.keys + ('id', 'children'))
     newId = oldPathTokens[-1]
     newBranch = self._marshalPath(target,
                                   newId,
                                   localKeys=self.keys + ('id', 'children'))
     for newParent, newChild, oldParent, oldChild in izip_longest(
             newBranch[:-1],
             newBranch[1:],
             oldBranch[:-1],
             oldBranch[1:],
             fillvalue=None):
         if newParent and oldParent and newParent['id'] != oldParent['id']:
             newParent['children'] = [newChild]
             oldParent['children'] = [oldChild]
         else:
             parent = newParent if newParent else oldParent
             if newChild and oldChild and newChild['id'] != oldChild['id']:
                 parent['children'] = [oldChild, newChild]
             else:
                 child = newChild if newChild else oldChild
                 parent['children'] = [child]
     tree = [newBranch[0]]
     if oldBranch[0]['id'] != newBranch[0]['id']:
         tree.append(oldBranch[0])
     #newNode = newBranch[-1]
     return DirectResponse.succeed()
예제 #29
0
 def deleteUserCommand(self, uid, id):
     """
     delete a user command
     """
     facade = self._getFacade()
     data = facade.deleteUserCommand(uid, id)
     return DirectResponse.succeed(data=Zuul.marshal(data))
예제 #30
0
 def addTrap(self, uid, id, oid, nodetype='notification'):
     if not self._validateOid(oid):
         msg = "Invalid OID value %s" % oid
         return DirectResponse.fail(msg)
     self.api.addTrap(uid, id, oid, nodetype)
     audit('UI.Mib.AddTrap', uid, id=id, oid=oid, nodetype=nodetype)
     return DirectResponse.succeed()
예제 #31
0
 def updateAdminRole(self, params):
     """
     adds or updates a role on a existing device administrator
     """
     facade = self._getFacade()
     facade.updateAdminRole(params)
     return DirectResponse.succeed()   
예제 #32
0
 def getTraps(
         self, uid, dir='ASC', sort='name', start=0, page=None, limit=256):
     count, nodes = self.api.getMibNodes(
         uid=uid, dir=dir, sort=sort, start=start,
         limit=limit, relation='notifications'
     )
     return DirectResponse.succeed(count=count, data=Zuul.marshal(nodes))
    def manage_addHttpSLAs(self,
                           newId,
                           rttIndex,
                           deviceIp,
                           community,
                           rttMonEchoAdminURL,
                           rttMonScheduleAdminRttStartTime=1,
                           rttMonCtrlAdminFrequency=60,
                           rttMonCtrlAdminOwner="zenoss",
                           rttMonCtrlAdminThreshold=5000,
                           rttMonCtrlAdminTimeout=5):
        facade = self._getFacade()
        success, message = facade.manage_addHttpSLAs(
            newId,
            rttIndex,
            deviceIp,
            community,
            rttMonEchoAdminURL,
            rttMonScheduleAdminRttStartTime=1,
            rttMonCtrlAdminFrequency=60,
            rttMonCtrlAdminOwner="zenoss",
            rttMonCtrlAdminThreshold=5000,
            rttMonCtrlAdminTimeout=5)

        if success:
            return DirectResponse.succeed(jobId=message)
        else:
            return DirectResponse.fail(message)
예제 #34
0
    def getInstances(self, uid, start=0, params=None, limit=50, sort='name',
                     page=None, dir='ASC'):
        """
        Get a list of instances for a process UID.

        @type  uid: string
        @param uid: Process UID to get instances of
        @type  start: integer
        @param start: (optional) Offset to return the results from; used in
                      pagination (default: 0)
        @type  params: dictionary
        @param params: (optional) Key-value pair of filters for this search.
        @type  limit: integer
        @param limit: (optional) Number of items to return; used in pagination
                      (default: 50)
        @type  sort: string
        @param sort: (optional) Key on which to sort the return results (default:
                     'name')
        @type  dir: string
        @param dir: (optional) Sort order; can be either 'ASC' or 'DESC'
                    (default: 'ASC')
        @rtype:   DirectResponse
        @return:  B{Properties}:
             - data: ([dictionary]) List of objects representing process instances
             - total: (integer) Total number of instances
        """
        facade = self._getFacade()
        instances = facade.getInstances(uid, start, limit, sort, dir, params)
        keys = ['device', 'monitored', 'pingStatus', 'processName', 'name', 'uid']
        data = Zuul.marshal(instances, keys)
        return DirectResponse.succeed(data=data, totalCount=instances.total)
예제 #35
0
    def setGraphDefinition(self, **data):
        """
        Set attributes on an graph definition.
        This method accepts any keyword argument for the property that you wish
        to set. Properties are enumerated via getGraphDefinition(). The only
        required property is "uid".

        @type    uid: string
        @keyword uid: Unique identifier of an object
        @rtype:  DirectResponse
        @return: B{Properties}:
            - data: (dictionary) The modified object
        """
        uid = data['uid']
        del data['uid']
        for axis_vals in ('miny', 'maxy'):
            try:
                x = float(data[axis_vals])
            except (ValueError, KeyError):
                x = -1
            data[axis_vals] = x
        obj = self._getFacade()._getObject(uid)
        oldData = self._getInfoData(obj, data)
        self._getFacade().setInfo(uid, data)
        newData = self._getInfoData(obj, data)
        audit(['UI', getDisplayType(obj), 'Edit'], data_=newData, oldData_=oldData,
              skipFields_=('newId',))  # special case in TemplateFacade.setInfo()
        return DirectResponse.succeed()
예제 #36
0
 def testRule(self, rule):
     """
     Test our rule by compiling it.
     """
     facade = self._getFacade()
     facade.testRule(rule)
     return DirectResponse.succeed()
예제 #37
0
 def addCustomProperty(self, id, value, label, uid, type):
     """
     adds a new property to the / of the tree
     """    
     facade = self._getFacade()
     facade.addCustomProperty(id, value, label, uid, type)
     return DirectResponse.succeed(msg="Property %s added successfully." % (id))
예제 #38
0
 def updateAdminRole(self, params):
     """
     adds or updates a role on a existing device administrator
     """
     facade = self._getFacade()
     facade.updateAdminRole(params)
     return DirectResponse.succeed()
예제 #39
0
 def testCompileTransform(self, transform):
     """
     Test our transform by compiling it.
     """
     facade = self._getFacade()
     facade.testCompileTransform(transform)
     return DirectResponse.succeed()
예제 #40
0
 def startModelingJob(self,id):
   _dmd = self.context.dmd
   _zpName='ZenPacks.ssv.OrgModeler'
   _orgModeler = _dmd.getObjByPath('/zport/dmd/ZenPackManager/packs/' + _zpName ).eggPath() + '/' + _zpName.replace('.','/') + '/lib/orgModeler.py'
   _cmd = ['python' , _orgModeler, id ]
   jobStatus=_dmd.JobManager.addJob(SubprocessJob, description="Model organizer job for %s" % id,args=(_cmd,) )
   return DirectResponse.succeed(jobId=jobStatus.id)
예제 #41
0
파일: network.py 프로젝트: c0ns0le/zenoss-4
    def getIpAddresses(self, uid, start=0, params=None, limit=50, sort='ipAddressAsInt',
                       page=None, dir='ASC'):
        """
        Given a subnet, get a list of IP addresses and their relations.

        @type  uid: string
        @param uid: Unique identifier of a subnet
        @type  start: integer
        @param start: Offset to return the results from; used in pagination
        @type  params: string
        @param params: Not used
        @type  limit: integer
        @param limit: Number of items to return; used in pagination
        @type  sort: string
        @param sort: (optional) Key on which to sort the return results;
                     defaults to 'name'
        @type  order: string
        @param order: Sort order; can be either 'ASC' or 'DESC'
        @rtype: DirectResponse
        """
        if isinstance(params, basestring):
            params = unjson(params)
        instances = self.api.getIpAddresses(uid=uid, start=start, params=params,
                                          limit=limit, sort=sort, dir=dir)

        keys = ['name', 'netmask', 'pingstatus', 'snmpstatus', 'uid',
                'device', 'interface', 'macAddress',
                'interfaceDescription']
        data = Zuul.marshal(instances.results, keys)
        return DirectResponse.succeed(data=data, totalCount=instances.total,
                                      hash=instances.hash_)
    def addnrpeComponent(self, title, nrpe_cmd, nrpe_args, nrpe_timeout, nrpe_min, nrpe_max, nrpe_type, userCreated=None, REQUEST=None):
        """ Adds NRPE Check/Component monitor """

        title = prepId(title)
        nrpecomponent = nrpeComponent(title)
        nrpecomponent.nrpe_cmd = nrpe_cmd
        nrpecomponent.nrpe_args = nrpe_args
        nrpecomponent.nrpe_timeout = int(nrpe_timeout)
        nrpecomponent.nrpe_min = nrpe_min
        nrpecomponent.nrpe_max = nrpe_max
        nrpecomponent.nrpe_type = nrpe_type
        nrpecomponent.lockFromDeletion()

        for nrpeCheck in d.os.nrpeComponent():
            if nrpeCheck.title == nrpecomponent.title:
                return DirectResponse.fail(_t("A NRPE Check %s already exists." % nrpecomponent.title))
        self.context.os._setObject(nrpecomponent.id, nrpecomponent)

        _zNRPEChecks = self.context.zNRPEChecks

        nrpe_dict = "{ 'title': '%s', 'cmd': '%s', 'args': %s , 'timeout': %d, 'min': %d, 'max': %d, 'type': '%s' }" \
            % (prepId(title), nrpe_cmd, nrpe_args, int(nrpe_timeout), nrpe_min, nrpe_max, nrpe_type)

        _zNRPEChecks.append(nrpe_dict)        

        eventDict = {
            'eventClass': Change_Add,
            'device': self.device().id,
            'component': nrpecomponent or '',
            'summary': 'Added by user: %s' % 'user',
            'severity': Event.Info,
            }
        self.dmd.ZenEventManager.sendEvent(eventDict)

        return DirectResponse.succeed(_t("NRPE Check %s added." % nrpecomponent.title))
예제 #43
0
 def testCompileTransform(self, transform):
     """
     Test our transform by compiling it.
     """
     facade = self._getFacade()
     facade.testCompileTransform(transform)
     return DirectResponse.succeed()
예제 #44
0
    def setInfo(self, **data):
        """
        Set attributes on an object.
        This method accepts any keyword argument for the property that you wish
        to set. The only required property is "uid".

        @type    uid: string
        @keyword uid: Unique identifier of an object
        @rtype:  DirectResponse
        @return: B{Properties}:
            - data: (dictionary) The modified object
        """
        uid = data['uid']
        del data['uid']
        obj = self._getFacade()._getObject(uid)
        oldData = self._getInfoData(obj, data)
        info = self._getFacade().setInfo(uid, data)
        newData = self._getInfoData(obj, data)
        # Trac #29376: Consistently show thresholdType with threshold operations.
        thresholdType = obj.getTypeName() if isinstance(
            obj, ThresholdClass) else None
        audit(['UI', getDisplayType(obj), 'Edit'],
              obj,
              thresholdType=thresholdType,
              data_=newData,
              oldData_=oldData,
              skipFields_=(
                  'newId', ))  # special case in TemplateFacade.setInfo()
        return DirectResponse.succeed(data=Zuul.marshal(info))
예제 #45
0
파일: users.py 프로젝트: bbc/zenoss-prodbin
 def getUsers(self, keys=None, start=0, limit=50, page=0,
                 sort='name', dir='ASC', name=None):
     """
     Retrieves a list of users. This method supports pagination.
     @type  start: integer
     @param start: (optional) Offset to return the results from; used in
                   pagination (default: 0)
     @type  name: string
     @param name: (optional) filter to be applied to users returned (default: None)
     @type  limit: integer
     @param limit: (optional) Number of items to return; used in pagination
                   (default: 50)
     @type  sort: string
     @param sort: (optional) Key on which to sort the return results (default:
                  'name')
     @type  dir: string
     @param dir: (optional) Sort order; can be either 'ASC' or 'DESC'
                 (default: 'ASC')
     @rtype:   DirectResponse
     @return:  B{Properties}:
          - data: (list) Dictionaries of user properties
          - totalCount: (integer) Number of devices returned
     """
     facade = self._getFacade()
     users = facade.getUsers(start=start, limit=limit, sort=sort,
                             dir=dir, name=name)
     total = users.total
     data = Zuul.marshal(users, keys)
     return DirectResponse.succeed(data=data, totalCount=total)
예제 #46
0
    def setGraphDefinition(self, **data):
        """
        Set attributes on an graph definition.
        This method accepts any keyword argument for the property that you wish
        to set. Properties are enumerated via getGraphDefinition(). The only
        required property is "uid".

        @type    uid: string
        @keyword uid: Unique identifier of an object
        @rtype:  DirectResponse
        @return: B{Properties}:
            - data: (dictionary) The modified object
        """
        uid = data['uid']
        del data['uid']
        for int_attr in ('miny', 'maxy'):
            try:
                x = int(data[int_attr])
            except (ValueError, KeyError):
                x = -1
            data[int_attr] = x
        obj = self._getFacade()._getObject(uid)
        oldData = self._getInfoData(obj, data)
        self._getFacade().setInfo(uid, data)
        newData = self._getInfoData(obj, data)
        audit(['UI', getDisplayType(obj), 'Edit'],
              data_=newData,
              oldData_=oldData,
              skipFields_=(
                  'newId', ))  # special case in TemplateFacade.setInfo()
        return DirectResponse.succeed()
예제 #47
0
    def remove_zovp_account(self, zovPushKey=None):


        if zovPushKey == None:
            return DirectResponse.fail("Missing zovPushKey")

        dmdRoot = _dmdRoot(self.context)
        accounts = getattr(dmdRoot, 'zovp_accounts', [])

        foundaccount = False

        this_account_details = models.zovpaccount.ZOVPAccount("None", "None")

        for accountDetails in accounts:
            if accountDetails.zovPushKey == zovPushKey:
                foundaccount = True
                this_account_details = accountDetails
                break

        if foundaccount == True:
            accounts.remove(this_account_details)
            setattr(dmdRoot, 'zovp_accounts', accounts)
            return DirectResponse.succeed()
        else:
            return DirectResponse.fail("Account not found")
    def manage_addJitterSLAs(self,
                             newId,
                             rttIndex,
                             deviceIp,
                             community,
                             rttMonEchoAdminTargetAddress,
                             rttMonEchoAdminTargetPort,
                             rttMonEchoAdminInterval=60,
                             rttMonEchoAdminNumPackets=100,
                             rttMonScheduleAdminRttStartTime=1,
                             rttMonCtrlAdminOwner="zenoss"):
        facade = self._getFacade()
        success, message = facade.manage_addJitterSLAs(
            newId,
            rttIndex,
            deviceIp,
            community,
            rttMonEchoAdminTargetAddress,
            rttMonEchoAdminTargetPort,
            rttMonEchoAdminInterval=60,
            rttMonEchoAdminNumPackets=100,
            rttMonScheduleAdminRttStartTime=1,
            rttMonCtrlAdminOwner="zenoss")

        if success:
            return DirectResponse.succeed(jobId=message)
        else:
            return DirectResponse.fail(message)
예제 #49
0
    def addThreshold(self, **data):
        """
        Add a threshold.

        @type    uid: string
        @keyword uid: Unique identifier of template to add threshold to
        @type    thresholdType: string
        @keyword thresholdType: Type of the new threshold. From getThresholdTypes()
        @type    thresholdId: string
        @keyword thresholdId: ID of the new threshold
        @type    dataPoints: [string]
        @keyword dataPoints: List of data points to select for this threshold
        @rtype:  DirectResponse
        @return: Success message
        """
        uid = data['uid']
        thresholdType = data['thresholdType']
        thresholdId = data['thresholdId']
        dataPoints = data.get('dataPoints', None)
        facade = self._getFacade()
        facade.addThreshold(uid, thresholdType, thresholdId, dataPoints)
        thresholdUid = uid + '/thresholds/' + thresholdId
        audit('UI.Threshold.Add',
              thresholdUid,
              thresholdtype=thresholdType,
              datapoints=dataPoints)
        return DirectResponse.succeed()
예제 #50
0
    def updateConfigFiles(self, id, configFiles):
        """
        Updates the configuration files for an application specified by id.
        The configFiles parameters is an array of dictionaries of the form:
        {
            filename: "blah",
            content: "line 1\nline 2\n..."
        }
        The filename parameter serves as the "id" of each configFile
        passed in.
        """

        if not Zuul.checkPermission('Manage DMD'):
            return DirectResponse.fail("You don't have permission to set update config files", sticky=False)

        facade = self._getFacade()
        deployedApp = facade.get(id)
        newConfigs = []
        for deployedAppConfig in deployedApp.configurations:
            if deployedAppConfig.filename in [ cf['filename'] for cf in configFiles ]:
                audit('UI.Applications.UpdateConfigFiles',
                      service=id,
                      servicename=deployedApp.name,
                      filename=deployedAppConfig.filename)
                deployedAppConfig.content = next((cf['content'] for cf in configFiles if cf['filename'] == deployedAppConfig.filename))
            newConfigs.append(deployedAppConfig)
        deployedApp.configurations = newConfigs
        return DirectResponse.succeed()
예제 #51
0
    def add_ovirt(self,
                  url,
                  username,
                  domain,
                  password,
                  collector='localhost'):
        # Check the permissions on the context
        context = self.context.dmd.Devices.oVirt
        if not Zuul.checkPermission(ZEN_MANAGE_DMD, context):
            message = "Insufficient privileges to add an oVirt infrastructure"
            audit('UI.oVirt.Login', url=url)
            return DirectResponse.fail(message)

        facade = self._getFacade()
        success, message = facade.add_ovirt(url, username, domain, password,
                                            collector)

        if success:
            audit('UI.oVirt.Add',
                  url=url,
                  username=username,
                  domain=domain,
                  password=password,
                  collector=collector,
                  jobId=message)
            return DirectResponse.succeed(jobId=message)
        else:
            return DirectResponse.fail(message)
예제 #52
0
    def addNode(self, contextUid='', id='', type=''):
        """
        Add an organizer or new blank MIB.

        @type  contextUid: string
        @param contextUid: Context to attach new node
        @type  id: string
        @param id: Id of the new orgainzer or blank MIB
        @type  type: string
        @param type: Type of new node. Can be 'organizer' or 'MIB'
        @rtype:   DirectResponse
        @return:  B{Properties}:
           - tree: ([dictionary]) Object representing the new tree
        """
        # GAH!  JS passes back a keyword of 'type'
        nodeType = type
        try:
            if nodeType == 'organizer':
                uid = contextUid + '/' + id
                maoUid = uid.replace('/zport/dmd', '')
                self.context.dmd.Mibs.manage_addOrganizer(maoUid)
                self.context.dmd.restrictedTraverse(uid)
                audit('UI.Organizer.Add', uid)
            elif nodeType == 'MIB':
                container = self.context.dmd.restrictedTraverse(contextUid)
                container.manage_addMibModule(id)
                audit('UI.Mib.Add', contextUid + '/' + id)
            else:
                return DirectResponse.fail('Invalid node type "%s"' % nodeType)
            return DirectResponse.succeed(tree=self.getTree())
        except Exception as ex:
            log.exception(ex)
            return DirectResponse.exception(
                ex, message="Failed to create '{}'".format(id))
예제 #53
0
 def addAdminRole(self, params):
     """
     add an admin with a role to a device
     """
     facade = self._getFacade()
     facade.addAdminRole(params)
     return DirectResponse.succeed(msg="New Administrator added successfully.")
예제 #54
0
    def deleteNode(self, uid):
        """
        Deletes a node from the tree.

        B{NOTE}: You can not delete a root node of a tree

        @type  uid: string
        @param uid: Unique identifier of the node we wish to delete
        @rtype:   DirectResponse
        @return:  B{Properties}:
             - msg: (string) Status message
        """
        # make sure we are not deleting a root node
        if not self._canDeleteUid(uid):
            raise Exception('You cannot delete the root node')
        facade = self._getFacade()
        node = facade._getObject(uid)

        # Audit first so it can display details like "name" while they exist.
        # Trac #29148: When we delete a DeviceClass we also delete its devices
        #     and child device classes and their devices, so audit them all.
        if isinstance(node, DeviceClass):
            childBrains = ICatalogTool(node).search((
                'Products.ZenModel.DeviceClass.DeviceClass',
                'Products.ZenModel.Device.Device',
            ))
            for child in childBrains:
                audit(['UI', getDisplayType(child), 'Delete'], child.getPath())
        else:
            audit(['UI', getDisplayType(node), 'Delete'], node)

        facade.deleteNode(uid)
        msg = "Deleted node '%s'" % uid
        return DirectResponse.succeed(msg=msg)
예제 #55
0
 def removeAdmin(self, uid, id):
     """
     removes admin and role on a existing device
     """
     facade = self._getFacade()
     facade.removeAdmin(uid, id)
     return DirectResponse.succeed()         
예제 #56
0
    def setInfo(self, **data):
        """
        Set attributes on an object.
        This method accepts any keyword argument for the property that you wish
        to set. The only required property is "uid".

        @type    uid: string
        @keyword uid: Unique identifier of an object
        @rtype:  DirectResponse
        @return: B{Properties}:
            - data: (dictionary) The modified object
        """
        uid = data['uid']
        del data['uid']
        obj = self._getFacade()._getObject(uid)
        passwordFields = self._getPasswordFields(obj)
        oldData = self._getInfoData(obj, data)
        info = self._getFacade().setInfo(uid, data)
        newData = self._getInfoData(obj, data)
        # Trac #29376: Consistently show thresholdType with threshold operations.
        thresholdType = obj.getTypeName() if isinstance(obj, ThresholdClass) else None
        audit(['UI', getDisplayType(obj), 'Edit'], obj, thresholdType=thresholdType,
              data_=newData, oldData_=oldData,
              skipFields_=('newId',), # special case in TemplateFacade.setInfo()
              maskFields_=passwordFields)  
        return DirectResponse.succeed(data=Zuul.marshal(info))
예제 #57
0
 def deleteMaintWindow(self, uid, id):
     """
     delete a maintenance window
     """
     facade = self._getFacade()
     data = facade.deleteMaintWindow(uid, id)
     return DirectResponse.succeed(data=Zuul.marshal(data))           
예제 #58
0
    def getServices(self, wantsMessages=False):
        dmdRoot = _dmdRoot(self.context)
        noAccountMsg = 'PagerDuty account info not set.'
        setUpApiKeyInlineMsg = 'Set up your account info in "Advanced... PagerDuty Settings"'
        msg = noAccountMsg if wantsMessages else None
        if not hasattr(dmdRoot, ACCOUNT_ATTR):
            return DirectResponse.fail(msg=msg, inlineMessage=setUpApiKeyInlineMsg)

        account = getattr(dmdRoot, ACCOUNT_ATTR)
        if not account.apiAccessKey or not account.subdomain:
            return DirectResponse.fail(msg=msg, inline_message=setUpApiKeyInlineMsg)

        try:
            apiServices = _retrieveServices(account)
        except requests.InvalidTokenException:
            msg = 'Your API Access Key was denied.' if wantsMessages else None
            return DirectResponse.fail(msg=msg, inline_message='Access key denied: Go to "Advanced... PagerDuty Settings"')
        except requests.PagerDutyUnreachableException as pdue:
            msg = pdue.message if wantsMessages else None
            return DirectResponse.fail(msg=msg, inline_message=pdue.message)

        if not apiServices:
            msg = ("No services with events integration v2 were found for %s.pagerduty.com." % account.subdomain) if wantsMessages else None
            return DirectResponse.fail(msg=msg)

        data = [service.getDict() for service in apiServices]
        return DirectResponse.succeed(msg=None, data=data)