Ejemplo n.º 1
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
        if nodeType not in ['organizer', 'MIB']:
            return DirectResponse.fail('Not creating "%s"' % nodeType)

        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)
            else:
                container = self.context.dmd.restrictedTraverse(contextUid)
                container.manage_addMibModule(id)
                audit('UI.Mib.Add', contextUid + '/' + id)

            return DirectResponse.succeed(tree=self.getTree())
        except Exception, e:
            return DirectResponse.exception(e)
Ejemplo n.º 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)
Ejemplo n.º 3
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")
    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))
Ejemplo n.º 5
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")
Ejemplo n.º 6
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)
        )
    def get_services(self, wants_messages=False):
        dmdRoot = _dmdRoot(self.context)
        no_account_msg = 'PagerDuty account info not set.'
        set_up_api_key_inline_msg = 'Set up your account info in "Advanced... PagerDuty Settings"'
        msg = no_account_msg if wants_messages else None
        if not hasattr(dmdRoot, ACCOUNT_ATTR):
            return DirectResponse.fail(msg=msg, inline_message=set_up_api_key_inline_msg)

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

        try:
            api_services = _retrieve_services(account)
        except requests.InvalidTokenException:
            msg = 'Your api_access_key was denied.' if wants_messages 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 wants_messages else None
            return DirectResponse.fail(msg=msg, inline_message=pdue.message)

        if not api_services:
            msg = ("No generic event services were found for %s.pagerduty.com." % account.subdomain) if wants_messages else None
            return DirectResponse.fail(msg=msg)
        
        return _success(api_services)
Ejemplo n.º 8
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()
Ejemplo n.º 9
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()
Ejemplo n.º 10
0
 def deleteTrap(self, uid):
     if uid.find('/notifications/') == -1:
         return DirectResponse.fail('"%s" does not appear to refer to a trap' % uid)
     mibUid, trapId = uid.split('/notifications/')
     self.api.deleteTrap(mibUid, trapId)
     audit('UI.Mib.DeleteTrap', mibUid, trap=trapId)
     return DirectResponse.succeed()
Ejemplo n.º 11
0
 def deleteOidMapping(self, uid):
     if uid.find('/nodes/') == -1:
         return DirectResponse.fail('"%s" does not appear to refer to an OID Mapping' % uid)
     mibUid, mappingId = uid.split('/nodes/')
     self.api.deleteOidMapping(mibUid, mappingId)
     audit('UI.Mib.DeleteOidMapping', mibUid, mapping=mappingId)
     return DirectResponse.succeed()
Ejemplo n.º 12
0
    def add_ec2account(self, accountname, accesskey, secretkey, collector):
        success = self._getFacade().add_ec2account(
            accountname, accesskey, secretkey, collector)

        if success:
            return DirectResponse.succeed()
        else:
            return DirectResponse.fail("Failed to add EC2 account")
Ejemplo n.º 13
0
    def add_xenserver(self, name, address, username, password, collector='localhost'):
        success = self._getFacade().add_xenserver(
            name, address, username, password, collector=collector)

        if success:
            return DirectResponse.succeed()
        else:
            return DirectResponse.fail("Failed to add XenServer")
Ejemplo n.º 14
0
    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)
Ejemplo n.º 15
0
    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)
Ejemplo n.º 16
0
    def manage_delSLAs(self, rttIndex, deviceIp, community):
        facade = self._getFacade()
        success, message = facade.manage_delSLAs(rttIndex, deviceIp, community)

        if success:
            return DirectResponse.succeed(jobId=message)
        else:
            return DirectResponse.fail(message)
Ejemplo n.º 17
0
    def manage_addDhcpSLAs(self, newId, rttIndex, deviceIp, community, rttMonScheduleAdminRttStartTime=1, rttMonCtrlAdminOwner="zenoss"):
        facade = self._getFacade()
        success, message = facade.manage_addDhcpSLAs(newId, rttIndex, deviceIp, community, rttMonScheduleAdminRttStartTime=1, rttMonCtrlAdminOwner="zenoss")

        if success:
            return DirectResponse.succeed(jobId=message)
        else:
            return DirectResponse.fail(message)
Ejemplo n.º 18
0
 def getOid(self, oid):
     try:
         node = next(iter(self.api.getOidList(oid)), None)
     except Exception as ex:
         log.warn("Error while looking up OID '%s': %s", oid, ex)
         node = None
     if node is None:
         return DirectResponse.fail()
     return DirectResponse.succeed(info=Zuul.marshal(IInfo(node)))
    def add_cloudstack(self, url, api_key, secret_key):
        facade = self._getFacade()
        success, message = facade.add_cloudstack(
            url, api_key, secret_key)

        if success:
            return DirectResponse.succeed(jobId=message)
        else:
            return DirectResponse.fail(message)
Ejemplo n.º 20
0
 def testRegex(self, regex, example):
     """
     Test our regex using the example event string.
     """
     facade = self._getFacade()
     reg = facade.testRegex(regex, example)
     if reg is True:
         return DirectResponse.succeed()
     return DirectResponse.fail(reg)
Ejemplo n.º 21
0
 def addOpenStack(self, hostname, authUrl, username, apiKey):
     facade = self._getFacade()
     success, message = facade.addOpenStack(
         hostname, authUrl, username, apiKey)
     
     if success:
         return DirectResponse.succeed(jobId=message)
     else:
         return DirectResponse.fail(message)
    def addHttpComponentRouter(self, httpPort, httpUseSSL, httpUrl, httpAuthUser, httpAuthPassword, httpJsonPost, httpFindString):
        
        facade = self._getFacade()

        ob = self.context
        success, message = facade.addHttpComponent(ob, httpPort, httpUseSSL, httpUrl, httpAuthUser, httpAuthPassword, httpJsonPost, httpFindString)
        if success:
            return DirectResponse.succeed(message)
        else:
            return DirectResponse.fail(message) 
    def add_cloudstack(self, url, api_key, secret_key,collector='localhost'):
        facade = self._getFacade()
        success, message = facade.add_cloudstack(
            url, api_key, secret_key,collector)

        audit('UI.Cloudstack.Add', url=url, collector=collector)
        if success:
            return DirectResponse.succeed(jobId=message)
        else:
            return DirectResponse.fail(message)
Ejemplo n.º 24
0
    def add_cloudstack(self, device_name, url, api_key, secret_key,collector='localhost'):

        facade = self._getFacade()
        success = facade.add_cloudstack(
            device_name, url, api_key, secret_key,collector)

        audit('UI.Cloudstack.Add', url=url, collector=collector)
        if success:
            return DirectResponse.succeed()
        else:
            return DirectResponse.fail("Failed to add CloudStack device: %s" % device_name)
    def addOpenStack(self, username, api_key, project_id, auth_url,
                     region_name=None):

        facade = self._getFacade()
        success, message = facade.addOpenStack(
            username, api_key, project_id, auth_url, region_name=region_name)

        if success:
            return DirectResponse.succeed(jobId=message)
        else:
            return DirectResponse.fail(message)
Ejemplo n.º 26
0
 def deleteDevices(self, devices=()):
     """
     Delete the list of specified device names
     """
     facade = self._getFacade()
     try:
         facade.deleteDevices(devices)
     except Exception:
         msg = "Unable to delete devices: %s" % devices
         log.exception(msg)
         return DirectResponse.fail(msg=msg)
     return DirectResponse.succeed(msg="Deleted devices", success=True)
    def add_ExampleDevice(self, deviceIp, community, comment):
        facade = self._getFacade()

        # The facade name in the next line & its parameters must match with a method defined
        #   in facades.py (ie. add_ExampleDevice(deviceIp, community, comment) )

        success, message = facade.add_ExampleDevice(deviceIp, community, comment)

        if success:
            return DirectResponse.succeed(jobId=message)
        else:
            return DirectResponse.fail(message)
    def addEndpoint(self, target, email, password, collector=None):
        if not collector:
            collector = 'localhost'

        facade = self._getFacade()
        success, message = facade.addEndpoint(
            target, email, password, collector)
        
        if success:
            return DirectResponse.succeed(jobId=message)
        else:
            return DirectResponse.fail(message)
Ejemplo n.º 29
0
    def update_zovp_server(self, zovpServerKey=None, zovpServerEndPointURL=None):

        if zovpServerKey == None or zovpServerEndPointURL == None:
            return DirectResponse.fail("Missing zovpServerKey or zovpServerEndPointURL")


        zovp_server_details = models.zovpserver.ZOVPServer(zovpServerKey, zovpServerEndPointURL)
        dmdRoot = _dmdRoot(self.context)

        setattr(dmdRoot, 'zovp_server', zovp_server_details)

        return DirectResponse.succeed("Server set or updated")
Ejemplo n.º 30
0
 def importDevices(self, data, options={}):
     """
     Create zenbatchload format file starting from the device class.
     """
     facade = self._getFacade()
     try:
         stats = facade.importDevices(data=data, options=options)
     except Exception:
         log.exception("Unable to import devices: %s", data)
         msg = "Failed -- see $ZENHOME/logs/event.log for details."
         return DirectResponse.fail(msg=msg)
     return DirectResponse.succeed(data=data, stats=stats)
Ejemplo n.º 31
0
    def getGraphInstructionTypes(self, query=''):
        """
        Get a list of available instruction types for graph points.

        @type  query: string
        @param query: not used
        @rtype:   DirectResponse
        @return: B{Properties}:
            - data: ([dictionary]) List of objects representing instruction types
        """
        facade = self._getFacade()
        types = facade.getGraphInstructionTypes()
        return DirectResponse.succeed(data=Zuul.marshal(types))
Ejemplo n.º 32
0
    def getGraphPoints(self, uid):
        """
        Get a list of graph points for a graph definition.

        @type  uid: string
        @param uid: Unique ID of a graph definition
        @rtype:  DirectResponse
        @return: B{Properties}:
            - data: ([dictionary]) List of objects representing graph points
        """
        facade = self._getFacade()
        graphPoints = facade.getGraphPoints(uid)
        return DirectResponse.succeed(data=Zuul.marshal(graphPoints))
Ejemplo n.º 33
0
    def deleteGraphPoint(self, uid):
        """
        Delete a graph point.

        @type  uid: string
        @param uid: Unique ID of the graph point to delete
        @rtype:  DirectResponse
        @return: Success message
        """
        facade = self._getFacade()
        facade.deleteGraphPoint(uid)
        audit('UI.GraphPoint.Remove', uid)
        return DirectResponse.succeed()
Ejemplo n.º 34
0
    def deleteGraphDefinition(self, uid):
        """
        Delete a graph definition.

        @type  uid: string
        @param uid: Unique ID of the graph definition to delete
        @rtype:  DirectResponse
        @return: Success message
        """
        facade = self._getFacade()
        facade.deleteGraphDefinition(uid)
        audit('UI.GraphDefinition.Delete', uid)
        return DirectResponse.succeed()
Ejemplo n.º 35
0
    def deleteNode(self, uid):
        """
        Delete a subnet.

        @type  uid: string
        @param uid: Unique identifier of the subnet to delete
        @rtype:   DirectResponse
        @return:  B{Properties}:
           - tree: (dictionary) An object representing the new network tree
        """
        self.api.deleteSubnet(uid)
        audit('UI.Network.DeleteSubnet', subnet=uid)
        return DirectResponse.succeed(tree=self.getTree())
Ejemplo n.º 36
0
    def getDataSourceTypes(self, query):
        """
        Get a list of available data source types.

        @type  query: string
        @param query: not used
        @rtype:   [dictionary]
        @return:  List of objects representing data source types
        """
        facade = self._getFacade()
        data = facade.getDataSourceTypes()
        data = sorted(data, key=lambda row: row['type'].lower())
        return DirectResponse.succeed(data=data)
Ejemplo n.º 37
0
    def getSequence2(self, *args, **kwargs):
        """
        Get the current processes sequence.

        @rtype:   DirectResponse
        @return:  B{Properties}:
             - data: ([dictionary]) List of objects representing processes in
             sequence order
        """
        facade = self._getFacade()
        sequence = facade.getSequence2()
        data = Zuul.marshal(sequence)
        return DirectResponse.succeed(data=data)
Ejemplo n.º 38
0
    def setSequence(self, uids):
        """
        Set the current processes sequence.

        @type  uids: [string]
        @param uids: The set of process uid's in the desired sequence
        @rtype:   DirectResponse
        @return:  Success message
        """
        facade = self._getFacade()
        facade.setSequence(uids)
        audit('UI.Process.SetSequence', sequence=uids)
        return DirectResponse.succeed()
Ejemplo n.º 39
0
 def removeIpAddresses(self, uids=None):
     """
     Removes every ip address specified by uids that are
     not attached to any device
     @type  uids: Array of Strings
     @param uids: unique identfiers of the ip addresses to delete
     """
     if uids:
         removedCount, errorCount = self.api.removeIpAddresses(uids)
         audit('UI.IPAddress.Remove', ips=uids, numremoved=removedCount,
               numerrors=errorCount)
         return DirectResponse.succeed(removedCount=removedCount,
                                       errorCount=errorCount)
Ejemplo n.º 40
0
    def getGraphDefinition(self, uid):
        """
        Get a graph definition.

        @type  uid: string
        @param uid: Unique ID of the graph definition to retrieve
        @rtype:   DirectResponse
        @return: B{Properties}:
            - data: (dictionary) Object representing a graph definition
        """
        facade = self._getFacade()
        graphDef = facade.getGraphDefinition(uid)
        return DirectResponse.succeed(data=Zuul.marshal(graphDef))
Ejemplo n.º 41
0
 def deleteDashboard(self, uid):
     user = getSecurityManager().getUser()
     facade = self._getFacade()
     obj = facade._getObject(uid)
     # can't delete the default dashboard
     if obj.getPrimaryId() == "/zport/dmd/ZenUsers/dashboards/default":
         return
     if obj.owner != user.getId() and not Zuul.checkPermission(
             ZEN_DELETE, facade.context):
         raise Exception("You have no permission to delete this dashboard")
     result = facade.deleteObject(uid)
     audit('UI.Dashboard.Remove', uid)
     return DirectResponse.succeed(data=Zuul.marshal(result))
Ejemplo n.º 42
0
 def createGroups(self, groups):
     """
     Adds a new group to the system.
     @type  groups: list of string
     @param groups: The unique names of each group
     @rtype:   DirectResponse
     @return:  B{Properties}:
          - data: properties of the new users
     """
     facade = self._getFacade()
     newGroups = facade.createGroups(groups)
     audit('UI.Users.CreateGroups', groups)
     return DirectResponse.succeed(data=Zuul.marshal(newGroups))
Ejemplo n.º 43
0
    def getEligiblePacks(self, **data):
        """
        Get a list of eligible ZenPacks to add to.

        @rtype:   DirectResponse
        @return:  B{Properties}:
             - packs: ([dictionary]) List of objects representing ZenPacks
             - totalCount: (integer) Total number of eligible ZenPacks
        """
        devZenPacks = self._getFacade().getDevelopmentZenPacks()
        packs = [{'name': zp.getId()} for zp in devZenPacks]
        packs = sorted(packs, key=lambda pack: pack['name'])
        return DirectResponse(packs=packs, totalCount=len(packs))
Ejemplo n.º 44
0
    def deleteDataSource(self, uid):
        """
        Delete a data source.

        @type  uid: string
        @param uid: Unique ID of the data source to delete
        @rtype:  DirectResponse
        @return: Success message
        """
        facade = self._getFacade()
        facade.deleteDataSource(uid)
        audit('UI.DataSource.Delete', uid)
        return DirectResponse.succeed()
Ejemplo n.º 45
0
 def setTransform(self, uid, transform):
     """
     sets the transform for the context
     """
     self.testCompileTransform(transform)
     facade = self._getFacade()
     facade.setTransform(uid, transform)
     if isinstance(transform, Mapping):
         auditTransform = transform
     else:
         auditTransform = {'transform': transform}
     audit('UI.EventClasses.SetTransform', uid, data_=auditTransform)
     return DirectResponse.succeed()
Ejemplo n.º 46
0
    def applyOSProcessClassMatchers(self, *args, **kwargs):
        """
        Get the current processes sequence.

        @rtype:   DirectResponse
        @return:  B{Properties}:
             - data: ([dictionary]) List of objects representing processes in
             sequence order
        """
        facade = self._getFacade()
        sequence = facade.applyOSProcessClassMatchers(kwargs['uids'], kwargs['lines'])
        data = Zuul.marshal(sequence)
        return DirectResponse.succeed(data=data, total=len(data))
Ejemplo n.º 47
0
 def moveInstance(self, params):
     """
     move a mapped instance to a different organizer
     @params['targetUid']
     @params['UidsToMove']
     """
     facade = self._getFacade()
     for uid in params['UidsToMove']:
         facade.moveInstance(params['targetUid'], uid)
     audit('UI.EventClasses.MoveInstance',
           movedInstances=params['UidsToMove'],
           target=params['targetUid'])
     return DirectResponse.succeed()
Ejemplo n.º 48
0
 def moveProduct(self, moveFrom, moveTarget, ids):
     """
     move products to a different organizer
     """
     facade = self._getFacade()
     if isinstance(ids, basestring):
         ids = (ids, )
     facade.moveProduct(moveFrom, moveTarget, ids)
     audit('UI.Manufacturers.MoveProduct',
           movedProducts=ids,
           target=moveTarget)
     return DirectResponse.succeed("Scheduled job to move %d product(s)." %
                                   len(ids))
Ejemplo n.º 49
0
    def addNode(self, newSubnet, contextUid):
        """Add a new subnet.

        @type  newSubnet: string
        @param newSubnet: New subnet to add
        @type  contextUid: string
        @param contextUid: Unique identifier of the network parent
            of the new subnet.
        @rtype:   DirectResponse
        @return:  B{Properties}:
           - newNode: (dictionary) An object representing the new subnet node
        """
        # If the user doesn't include a mask, reject the request.
        if "/" not in newSubnet:
            return DirectResponse.fail("You must include a subnet mask.")

        try:
            contextUid = getUtility(IVirtualRoot).strip_virtual_root(
                contextUid)
            netip, netmask = newSubnet.split("/")
            netmask = int(netmask)
            foundSubnet = self.api.findSubnet(netip, netmask, contextUid)

            if foundSubnet is not None:
                response = DirectResponse.fail(
                    "Did not add duplicate subnet: %s (%s/%s)" %
                    (newSubnet, foundSubnet.id, foundSubnet.netmask))
            else:
                newNet = self.api.addSubnet(newSubnet, contextUid)
                node = ITreeNode(newNet)
                audit("UI.Network.AddSubnet", contextUid, subnet=newSubnet)
                response = DirectResponse.succeed(newNode=Zuul.marshal(node))
        except IpAddressError as error:
            response = DirectResponse.exception(error, "Error adding subnet.")
        except Exception as error:
            log.exception("Error adding subnet.")
            response = DirectResponse.exception(error, "Error adding subnet.")
        return response
Ejemplo n.º 50
0
    def addToZenPack(self, topack, zenpack):
        """
        Add an object to a ZenPack.

        @type  topack: string
        @param topack: Unique ID of the object to add to ZenPack
        @type  zenpack: string
        @param zenpack: Unique ID of the ZenPack to add object to
        @rtype:   DirectResponse
        @return:  Success message
        """
        self._getFacade().addToZenPack(topack, zenpack)
        audit('UI.ZenPack.AddObject', zenpack, object=topack)
        return DirectResponse.succeed()
Ejemplo n.º 51
0
    def setInfo(self, **data):
        """
        Main method for setting attributes on a network or network organizer.
        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
        """
        network = self.api.getInfo(data['uid'])
        Zuul.unmarshal(data, network)
        audit(['UI', getDisplayType(network), 'Edit'], network, data_=data)
        return DirectResponse.succeed()
Ejemplo n.º 52
0
    def deleteTemplate(self, uid):
        """
        Delete a template.

        @type  uid: string
        @param uid: Unique ID of the template to delete
        @rtype:   DirectResponse
        @return:  Success message
        """
        facade = self._getFacade()
        facade.deleteTemplate(uid)
        msg = "Deleted node '%s'" % uid
        audit('UI.Template.Delete', uid)
        return DirectResponse.succeed(msg=msg)
Ejemplo n.º 53
0
    def removeThreshold(self, uid):
        """
        Remove a threshold.

        @type  uid: string
        @param uid: Unique identifier of threshold to remove
        @rtype:  DirectResponse
        @return: Success message
        """
        facade = self._getFacade()
        thresholdType = facade._getThresholdClass(uid).getTypeName()
        facade.removeThreshold(uid)
        audit('UI.Threshold.Delete', uid, thresholdType=thresholdType)
        return DirectResponse.succeed()
Ejemplo n.º 54
0
    def getThresholds(self, uid, query=''):
        """
        Get the thresholds for a template.

        @type  uid: string
        @param uid: Unique ID of a template
        @type  query: string
        @param query: not used
        @rtype:   [dictionary]
        @return:  List of objects representing representing thresholds
        """
        facade = self._getFacade()
        thresholds = facade.getThresholds(uid)
        return DirectResponse.succeed(data=Zuul.marshal(thresholds))
Ejemplo n.º 55
0
    def addMIB(self, package, organizer='/'):
        """
        Add a new MIB by URL or local file.

        @type  package: string
        @param package: URL or local file path to MIB file
        @type  organizer: string
        @param organizer: ID of the organizer to add MIB to
        @rtype:   DirectResponse
        @return:  B{Properties}:
           - jobId: (string) ID of the add MIB job
        """
        facade = self._getFacade()
        jobrecord = facade.addMibPackage(package, organizer)
        if jobrecord:
            audit('UI.Mib.AddFromPackage',
                  mibpackage=package,
                  organizer=organizer)
            return DirectResponse.succeed(new_jobs=Zuul.marshal(
                [jobrecord], keys=('uuid', 'description', 'started')))
        else:
            return DirectResponse.fail("Failed to add MIB package %s" %
                                       package)
Ejemplo n.º 56
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))
Ejemplo n.º 57
0
    def editProduct(self, params=None):
        """
        Edit a product
        """
        oldData = self.getProductData(params['uid'], params['oldname'])
        facade = self._getFacade()
        facade.editProduct(params)

        audit('UI.Manufacturers.editProduct',
              params['uid'],
              data_=params,
              oldData_=oldData)

        return DirectResponse.succeed()
Ejemplo n.º 58
0
    def getJobs(self, start, limit, page, sort, dir, uid=None):
        # if user isn't global only show them the jobs they created
        user = self.context.dmd.ZenUsers.getUserSettings()
        createdBy = user.id if user.hasNoGlobalRoles() else None

        results, total = self.api.getJobs(start=start,
                                          limit=limit,
                                          sort=sort,
                                          dir=dir,
                                          createdBy=createdBy)
        jobs = Zuul.marshal(results, keys=JOBKEYS)
        for job in jobs:
            job['description'] = cgi.escape(job.get('description') or '')
        return DirectResponse(jobs=jobs, totalCount=total)
Ejemplo n.º 59
0
    def setGraphDefinitionSequence(self, uids):
        """
        Sets the sequence of graph definitions.

        @type  uids: [string]
        @param uids: List of graph definition UID's in desired order
        @rtype:  DirectResponse
        @return: Success message
        """
        facade = self._getFacade()
        facade._setGraphDefinitionSequence(uids)
        # TODO: Is it enforced that they're all in the same template?
        #       If so:  template=/blah/uid sequence=[one,two,three]
        audit('UI.Template.SetGraphDefinitionSequence', sequence=uids)
        return DirectResponse.succeed()
Ejemplo n.º 60
0
    def addThresholdToGraph(self, graphUid, thresholdUid):
        """
        Add a threshold to a graph definition.

        @type  graphUid: string
        @param graphUid: Unique ID of the graph definition to add threshold to
        @type  thresholdUid: string
        @param thresholdUid: Unique ID of the threshold to add
        @rtype:   DirectResponse
        @return:  Success message
        """
        facade = self._getFacade()
        facade.addThresholdToGraph(graphUid, thresholdUid)
        audit('UI.Graph.AddThreshold', graphUid, thresholdclass=thresholdUid)
        return DirectResponse.succeed()