Пример #1
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_)
Пример #2
0
    def getInstances(self, uid, start=0, params=None, limit=50, sort='name',
                     page=None, dir='ASC'):
        """
        Get a list of instances for a service UID.

        @type  uid: string
        @param uid: Service 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 service instances
             - totalCount: (integer) Total number of instances
        """
        if isinstance(params, basestring):
            params = unjson(params)
        instances = self.api.getInstances(uid, start=start, params=params,
                                          limit=limit, sort=sort, dir=dir)

        keys = ['description', 'device', 'locking', 'monitored', 'name',
                 'pingStatus', 'uid']
        data = Zuul.marshal(instances, keys)
        return DirectResponse.succeed(data=data, totalCount=instances.total)
Пример #3
0
 def stream(self):
     data = unjson(self.request.get('data'))
     command = self.context.getUserCommands(asDict=True).get(data['command'], None)
     if command:
         for uid in data['uids']:
             target = self.context.unrestrictedTraverse(uid)
             self.execute(command, target)
Пример #4
0
    def addClass(self, contextUid, id, posQuery=None):
        """
        Add a new service class.

        @type  contextUid: string
        @param contextUid: Unique ID of the service ogranizer to add new class to
        @type  id: string
        @param id: ID of the new service
        @type  posQuery: dictionary
        @param posQuery: Object defining a query where the returned position will lie
        @rtype:   DirectResponse
        @return:  B{Properties}:
             - newIndex: (integer) Index of the newly added class in the query
             defined by posQuery
        """
        newUid = self.api.addClass(contextUid, id)
        if isinstance(posQuery.get('params'), basestring):
            posQuery['params'] = unjson(posQuery['params'])
        result = self.api.getList(**posQuery)
        for count, serviceInfo in enumerate(result['serviceInfos']):
            if serviceInfo.uid == newUid:
                newIndex = count
                break
        else:
            raise Exception('The new service was added, but the system was '
                            'unable to add it to the list.')
        audit('UI.Service.Add', contextUid + '/' + id)
        return DirectResponse(newIndex=newIndex)
Пример #5
0
 def stream(self):
     data = unjson(self.request.get('data'))
     uids = data['uids']
     facade = getFacade('device', self.context)
     for deviceOrganizer in imap(facade._getObject, uids):
         deviceOrganizer.runDeviceMonitor(REQUEST=self.request,
                                          write=self.write)
Пример #6
0
    def getInstances(self, uid, start=0, params=None, limit=50, sort='name',
                     page=None, dir='ASC'):
        """
        Get a list of instances for a service UID.

        @type  uid: string
        @param uid: Service 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 service instances
             - totalCount: (integer) Total number of instances
        """
        if isinstance(params, basestring):
            params = unjson(params)
        instances = self.api.getInstances(uid, start=start, params=params,
                                          limit=limit, sort=sort, dir=dir)

        keys = ['description', 'device', 'locking', 'monitored', 'name',
                 'pingStatus', 'uid']
        data = Zuul.marshal(instances, keys)
        return DirectResponse.succeed(data=data, totalCount=instances.total)
Пример #7
0
    def addClass(self, contextUid, id, posQuery=None):
        """
        Add a new service class.

        @type  contextUid: string
        @param contextUid: Unique ID of the service ogranizer to add new class to
        @type  id: string
        @param id: ID of the new service
        @type  posQuery: dictionary
        @param posQuery: Object defining a query where the returned position will lie
        @rtype:   DirectResponse
        @return:  B{Properties}:
             - newIndex: (integer) Index of the newly added class in the query
             defined by posQuery
        """
        newUid = self.api.addClass(contextUid, id)
        if isinstance(posQuery.get('params'), basestring):
            posQuery['params'] = unjson(posQuery['params'])
        result = self.api.getList(**posQuery)
        for count, serviceInfo in enumerate(result['serviceInfos']):
            if serviceInfo.uid == newUid:
                newIndex = count
                break
        else:
            raise Exception('The new service was added, but the system was '
                            'unable to add it to the list.')
        audit('UI.Service.Add', contextUid + '/' + id)
        return DirectResponse(newIndex=newIndex)
Пример #8
0
 def stream(self):
     data = unjson(self.request.get('data'))
     command = self.context.getUserCommands(asDict=True).get(data['command'], None)
     if command:
         for uid in data['uids']:
             target = self.context.unrestrictedTraverse(uid)
             self.execute(command, target)
Пример #9
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']
        data = Zuul.marshal(instances.results, keys)
        return DirectResponse.succeed(data=data, totalCount=instances.total,
                                      hash=instances.hash_)
 def stream(self):
     daemons = [
         d["name"]
         for d in self.context.dmd.About.getZenossDaemonStates()
         if d["msg"] == "Up" and d["name"] not in DEFAULT_MASTER_DAEMONS
     ]
     if "zeneventserver" in daemons:
         daemons.remove("zeneventserver")
         if "zenrrdcached" not in daemons:
             daemons.append("zenrrdcached")
     if os.path.exists(MASTER_DAEMON_LIST_FILE):
         for line in fileinput.input(MASTER_DAEMON_LIST_FILE):
             line = line.strip()
             if line in daemons:
                 daemons.remove(line)
     df = open("%s/daemons.txt" % zpDir, "w")
     df.write("%s\n" % "\n".join(daemons))
     df.close()
     data = unjson(self.request.get("data"))
     ids = data["uids"]
     if not ids:
         self.write("No Remote Collectors were selected")
     command = data["command"]
     if command == "add":
         new_id = ids[0]
         self.context.manage_addMonitor(new_id, submon="Performance")
         #            self.context.Performance[new_id].renderurl = 'http://%s:8090/%s'%(
         #                                                    socket.getfqdn(), new_id)
         self.context.Performance[new_id].renderurl = "http://%s:8091" % new_id
         transaction.commit()
     for id in ids:
         self.write("%s Remote Collector %s" % (command.capitalize(), id))
         self.write("Stopping zenoss daemons")
         executeStreamCommand('ssh %s "zenoss stop"' % id, self.write, timeout=COMMAND_TIMEOUT)
         if command in ("update", "remove"):
             self.write("Revert Remote Collector configuration")
             executeStreamCommand(
                 "ssh %s %s localhost localhost" % (id, updConfZenBin), self.write, timeout=COMMAND_TIMEOUT
             )
         self.write("Remove ZenPacks files from Remote Collector")
         executeStreamCommand("ssh %s rm -fr %s" % (id, zpDir), self.write, timeout=COMMAND_TIMEOUT)
         if command in ("add", "update"):
             self.write("Copy ZenPacks files to Remote Collector")
             executeStreamCommand(
                 'find %s -print | cpio -oc | ssh -C %s "cd / && cpio -ic 2>/dev/null"' % (zpDir, id),
                 self.write,
                 timeout=COMMAND_TIMEOUT,
             )
             self.write("Update Remote Collector configuration")
             executeStreamCommand(
                 "ssh %s %s %s %s" % (id, updConfBin, socket.getfqdn(), id), self.write, timeout=COMMAND_TIMEOUT
             )
         self.write("Starting zenoss daemons")
         executeStreamCommand('ssh %s "zenoss start"' % id, self.write, timeout=COMMAND_TIMEOUT)
     if command == "remove":
         self.context.manage_removeMonitor(ids=ids, submon="Performance")
         transaction.commit()
     self.write("All Tasks Finished")
     os.unlink("%s/daemons.txt" % zpDir)
Пример #11
0
 def stream(self):
     data = unjson(self.request.get('data'))
     uids = data['uids']
     facade = getFacade('device', self.context)
     for device in imap(facade._getObject, uids):
         device.collectDevice(REQUEST=self.request,
                              write=self.write,
                              debug=True)
Пример #12
0
    def query(self,
              limit=None,
              start=None,
              sort=None,
              dir=None,
              params=None,
              page=None,
              history=False,
              uid=None,
              criteria=()):
        """
        Retrieve a list of services based on a set of parameters.

        @type  limit: integer
        @param limit: (optional) Number of items to return; used in pagination
                      (default: None)
        @type  start: integer
        @param start: (optional) Offset to return the results from; used in
                      pagination (default: None)
        @type  sort: string
        @param sort: (optional) Key on which to sort the return results (default:
                     None)
        @type  dir: string
        @param dir: (optional) Sort order; can be either 'ASC' or 'DESC'
                    (default: None)
        @type  params: dictionary
        @param params: (optional) Key-value pair of filters for this search.
        @type  history: boolean
        @param history: not used
        @type  uid: string
        @param uid: Service class UID to query
        @type  criteria: list
        @param criteria: not used
        @rtype:   DirectResponse
        @return:  B{Properties}:
             - services: ([dictionary]) List of objects representing services
             - totalCount: (integer) Total number of services
             - hash: (string) Hashcheck of the current services state
             - disabled: (boolean) True if current user cannot manage services
        """
        if uid is None:
            uid = "/".join(self.context.getPhysicalPath())

        if isinstance(params, basestring):
            params = unjson(params)
        services = self.api.getList(limit, start, sort, dir, params, uid,
                                    criteria)

        disabled = not Zuul.checkPermission('Manage DMD')

        data = Zuul.marshal(services['serviceInfos'],
                            keys=('name', 'description', 'count', 'uid',
                                  'port'))
        return DirectResponse(services=data,
                              totalCount=services['total'],
                              hash=services['hash'],
                              disabled=disabled)
Пример #13
0
    def query(self,
              limit=None,
              start=None,
              sort=None,
              dir=None,
              params=None,
              page=None,
              history=False,
              uid=None,
              criteria=()):
        """
        Retrieve a list of processes based on a set of parameters.

        @type  limit: integer
        @param limit: (optional) Number of items to return; used in pagination
                      (default: None)
        @type  start: integer
        @param start: (optional) Offset to return the results from; used in
                      pagination (default: None)
        @type  sort: string
        @param sort: (optional) Key on which to sort the return results (default:
                     None)
        @type  dir: string
        @param dir: (optional) Sort order; can be either 'ASC' or 'DESC'
                    (default: None)
        @type  params: dictionary
        @param params: (optional) Key-value pair of filters for this search.
        @type  history: boolean
        @param history: not used
        @type  uid: string
        @param uid: Service class UID to query
        @type  criteria: list
        @param criteria: not used
        @rtype:   DirectResponse
        @return:  B{Properties}:
             - processes: ([dictionary]) List of objects representing processes
             - totalCount: (integer) Total number of processes
             - hash: (string) Hashcheck of the current processes state
             - disabled: (boolean) True if current user cannot manage processes
        """
        facade = self._getFacade()
        if uid is None:
            uid = self.context

        if isinstance(params, basestring):
            params = unjson(params)

        processes = facade.getList(limit, start, sort, dir, params, uid,
                                   criteria)
        disabled = not Zuul.checkPermission('Manage DMD')

        data = Zuul.marshal(processes)
        return DirectResponse(processes=data,
                              totalCount=processes.total,
                              hash=processes.hash_,
                              disabled=disabled)
    def stream(self):
        daemons=[d['name'] for d in self.context.dmd.About.getZenossDaemonStates() \
                if d['msg'] == 'Up' and d['name'] not in DEFAULT_MASTER_DAEMONS]
        if 'zeneventserver' in daemons:
            daemons.remove('zeneventserver') 
        if 'zenrrdcached' not in daemons:
            daemons.append('zenrrdcached')
        if 'zenrender' not in daemons:
            daemons.append('zenrender')
        if os.path.exists(MASTER_DAEMON_LIST_FILE):
            for line in fileinput.input(MASTER_DAEMON_LIST_FILE):
                line = line.strip()
                if line in daemons:
                    daemons.remove(line)
        df = open('%s/daemons.txt'%zpDir, 'w')
        df.write('%s\n'%'\n'.join(daemons))
        df.close()
        data = unjson(self.request.get('data'))
        ids = data['uids']
        if not ids:
            self.write('No Remote Collectors were selected')
        command = data['command']
        if command == 'add':
            new_id = ids[0]
            self.context.manage_addMonitor(new_id, submon='Performance')
#            self.context.Performance[new_id].renderurl = 'http://%s:8090/%s'%(
#                                                    socket.getfqdn(), new_id)
            self.context.Performance[new_id].renderurl='http://%s:8091' % new_id
            transaction.commit()
        for id in ids:
            self.write('%s Remote Collector %s'%(command.capitalize(), id))
            self.write('Stopping zenoss daemons')
            executeStreamCommand('ssh %s "zenoss stop"'%id,
                                        self.write, timeout=COMMAND_TIMEOUT)
            if command in ('update', 'remove'):
                self.write('Revert Remote Collector configuration')
                executeStreamCommand('ssh %s %s localhost localhost'%(id,
                            updConfZenBin), self.write, timeout=COMMAND_TIMEOUT)
            self.write('Remove ZenPacks files from Remote Collector')
            executeStreamCommand('ssh %s rm -fr %s'%(id, zpDir),
                                            self.write, timeout=COMMAND_TIMEOUT)
            if command in ('add', 'update'):
                self.write('Copy ZenPacks files to Remote Collector')
                executeStreamCommand('find %s -print | cpio -oc | ssh -C %s "cd / && cpio -ic 2>/dev/null"'%(
                                zpDir, id), self.write, timeout=COMMAND_TIMEOUT)
                self.write('Update Remote Collector configuration')
                executeStreamCommand('ssh %s %s %s %s'%(id, updConfBin,
                    socket.getfqdn(), id), self.write, timeout=COMMAND_TIMEOUT)
            self.write('Starting zenoss daemons')
            executeStreamCommand('ssh %s "zenoss start"'%id,
                    self.write, timeout=COMMAND_TIMEOUT)
        if command == 'remove':
            self.context.manage_removeMonitor(ids=ids, submon='Performance')
            transaction.commit()
        self.write('All Tasks Finished')
        os.unlink('%s/daemons.txt'%zpDir)
 def stream(self):
     self.write('Starting to retrieve logs...\n')
     facade = getFacade('auditlogs', self.context)
     data = unjson(self.request.get('data'))
     deviceUids = data['uids']
     for deviceUid in deviceUids:
         output = facade.getLogs(deviceUid)
         for line in output:
             self.write(str(line))
     self.write('\nFinished.')
Пример #16
0
 def stream(self):
     data = unjson(self.request.get('data'))
     args = data['args']
     includeEvents = args[0]
     includeMysqlLogin = args[1]
     timeoutString = args[2]
     try:
         timeout = int(timeoutString)
     except ValueError:
         timeout = 120
     self.context.zport.dmd.manage_createBackup(includeEvents,
             includeMysqlLogin, timeout, self.request, self.write)
Пример #17
0
 def stream(self):
     data = unjson(self.request.get('data'))
     args = data['args']
     includeEvents = args[0]
     includeMysqlLogin = args[1]
     timeoutString = args[2]
     try:
         timeout = int(timeoutString)
     except ValueError:
         timeout = 120
     self.context.zport.dmd.manage_createBackup(includeEvents,
             includeMysqlLogin, timeout, self.request, self.write)
Пример #18
0
 def stream(self):
     data = unjson(self.request.get('data'))
     command = self.context.getUserCommands(asDict=True).get(
         data['command'], None)
     if command:
         for uid in data['uids']:
             target = self.context.unrestrictedTraverse(uid)
             if permissionsForContext(target)[ZEN_RUN_COMMANDS.lower()]:
                 self.execute(command, target)
             else:
                 self.write(
                     '==== No permissions to run command %s for %s, skipping ===='
                     .format(command, target))
Пример #19
0
    def stream(self):
        # Setup a logging file
        logfile = open('/opt/zenoss/log/rancid_example_logging.log', 'a')
        logfile.write('Start logging')
        # data is a list that will contain 2 elemets:
        #   the url argument and the uid

        #self.write('TEST parameter = %s\n' % (self.request.arguments()))

        data = unjson(self.request.get('data'))
        self.write('data stream = %s\n' % (data))

        #data = ""

        logfile.write(' data is %s \n' % (data))
        try:
            args = data['args']
            logfile.write('Argument is %s \n' % (args))
            arg3 = args
        except:
            logfile.write(' No args \n')
            arg3 = ''
        try:
            uids = data['uids']
            logfile.write('uids is %s \n' % (uids))
            arg4 = uids
        except:
            logfile.write('No uids \n')
            arg4 = ''

        libexec = os.path.join(os.path.dirname(__file__), 'libexec')

        arg1 = "Hello"
        arg2 = "World"

        # Put the  script in the libexec directory of the ZenPack
        myPredefinedCmd1 = [
            #libexec + '/mywrapper_script1',
            #"ls -a"
            #arg1, arg2, arg3, arg4
            "find",
            "/tmp"
        ]
        logfile.write(' myPredefinedCmd1 is %s ' % (myPredefinedCmd1))
        self.write('Preparing my command...')
        result = executeCommand(myPredefinedCmd1, None, write=self.write)
        #logfile.write(result)
        #self.write(result)
        self.write('End of command...')
        logfile.close()
        return result
Пример #20
0
 def stream(self):
     try:
         request = self.request
         data = unjson(request.form['data'])
         for key in data:
             request[key] = data[key]
         self.write("Preparing Command...")
         request['renderTemplate'] = False
         results = self.context.testDataSourceAgainstDevice(
             data.get('testDevice'), request, self.write, self.reportError)
         return results
     except Exception:
         self.write('Exception while performing command: <br />')
         self.write('<pre>%s</pre>' % (traceback.format_exc()))
Пример #21
0
    def __call__(self):
        body = self.request.form['body']
        state = unjson(body)
        params = state['params']
        type = state['type']
        archive = state.get('isHistory', False)

        # Send the events to the appropriate formatting method
        filter_params = state['params']['params']
        del state['params']['params']
        params.update(filter_params)
        getattr(self, type)(self.request.response, archive, **params)
        # aborting the long running export transaction so it is not retried
        import transaction
        transaction.abort()
Пример #22
0
    def __call__(self):
        body = self.request.form['body']
        state = unjson(body)
        params = state['params']
        type = state['type']
        archive = state.get('isHistory', False)

        # Send the events to the appropriate formatting method
        filter_params = state['params']['params']
        del state['params']['params']
        params.update(filter_params)
        getattr(self, type)(self.request.response, archive, **params)
        # aborting the long running export transaction so it is not retried
        import transaction
        transaction.abort()
Пример #23
0
    def query(self, limit=None, start=None, sort=None, dir=None, params=None,
              page=None, history=False, uid=None, criteria=()):
        """
        Retrieve a list of processes based on a set of parameters.

        @type  limit: integer
        @param limit: (optional) Number of items to return; used in pagination
                      (default: None)
        @type  start: integer
        @param start: (optional) Offset to return the results from; used in
                      pagination (default: None)
        @type  sort: string
        @param sort: (optional) Key on which to sort the return results (default:
                     None)
        @type  dir: string
        @param dir: (optional) Sort order; can be either 'ASC' or 'DESC'
                    (default: None)
        @type  params: dictionary
        @param params: (optional) Key-value pair of filters for this search.
        @type  history: boolean
        @param history: not used
        @type  uid: string
        @param uid: Service class UID to query
        @type  criteria: list
        @param criteria: not used
        @rtype:   DirectResponse
        @return:  B{Properties}:
             - processes: ([dictionary]) List of objects representing processes
             - totalCount: (integer) Total number of processes
             - hash: (string) Hashcheck of the current processes state
             - disabled: (boolean) True if current user cannot manage processes
        """
        facade = self._getFacade()
        if uid is None:
            uid = self.context

        if isinstance(params, basestring):
            params = unjson(params)

        processes = facade.getList(limit, start, sort, dir, params, uid,
                                  criteria)
        disabled = not Zuul.checkPermission('Manage DMD')

        data = Zuul.marshal(processes)
        return DirectResponse(processes=data, totalCount=processes.total,
                              hash=processes.hash_, disabled=disabled)
Пример #24
0
    def query(self, limit=None, start=None, sort=None, dir=None, params=None,
              page=None, history=False, uid=None, criteria=()):
        """
        Retrieve a list of services based on a set of parameters.

        @type  limit: integer
        @param limit: (optional) Number of items to return; used in pagination
                      (default: None)
        @type  start: integer
        @param start: (optional) Offset to return the results from; used in
                      pagination (default: None)
        @type  sort: string
        @param sort: (optional) Key on which to sort the return results (default:
                     None)
        @type  dir: string
        @param dir: (optional) Sort order; can be either 'ASC' or 'DESC'
                    (default: None)
        @type  params: dictionary
        @param params: (optional) Key-value pair of filters for this search.
        @type  history: boolean
        @param history: not used
        @type  uid: string
        @param uid: Service class UID to query
        @type  criteria: list
        @param criteria: not used
        @rtype:   DirectResponse
        @return:  B{Properties}:
             - services: ([dictionary]) List of objects representing services
             - totalCount: (integer) Total number of services
             - hash: (string) Hashcheck of the current services state
             - disabled: (boolean) True if current user cannot manage services
        """
        if uid is None:
            uid = "/".join(self.context.getPhysicalPath())

        if isinstance(params, basestring):
            params = unjson(params)
        services = self.api.getList(limit, start, sort, dir, params, uid,
                                  criteria)

        disabled = not Zuul.checkPermission('Manage DMD')

        data = Zuul.marshal(services['serviceInfos'], keys=('name','description', 'count', 'uid','port'))
        return DirectResponse(services=data, totalCount=services['total'],
                              hash=services['hash'], disabled=disabled)
Пример #25
0
    def _filterData(self, params, data):
        """
        @param params: params passed to the caller and used here for filtering
        @param data: data to be filtered and returned
        """
        # filter
        if params:
            if isinstance(params, basestring):
                filters = unjson(params)
            else:
                filters = params
            def hasFilter(row, key, value):
                if row.get(key) is not None:
                    return value.lower() in str(row.get(key)).lower()

            for key, value in filters.iteritems():
                # assume AND for sorting
                data = [row for row in data if hasFilter(row, key, value)]
               
        return data   
Пример #26
0
    def _filterData(self, params, data):
        """
        @param params: params passed to the caller and used here for filtering
        @param data: data to be filtered and returned
        """
        # filter
        if params:
            if isinstance(params, basestring):
                filters = unjson(params)
            else:
                filters = params
            def hasFilter(row, key, value):
                if row.get(key) is not None:
                    return value.lower() in str(row.get(key)).lower()

            for key, value in filters.iteritems():
                # assume AND for sorting
                data = [row for row in data if hasFilter(row, key, value)]
               
        return data   
    def stream(self):
    # Setup a logging file
        lf = os.path.join(os.environ['ZENHOME'], 'log/example_logging.log')
        logfile = open(lf, 'a')

        logfile.write('Start logging')
        # data is a list that will contain 2 elements:
        #   the url argument and the uid
        data = unjson(self.request.get('data'))
        logfile.write(' data is \n' % (data))
        try:
            args = data['args']
            logfile.write('Argument is %s \n' % (args))
            arg3 = args
        except:
            logfile.write(' No args \n')
            arg3 = ''
        try:
            uids = data['uids']
            logfile.write('uids is %s \n' % (uids))
            arg4 = uids
        except:
            logfile.write('No uids \n')
            arg4 = ''

        libexec = os.path.join(os.path.dirname(__file__), 'libexec')

        arg1 = "Hello"
        arg2 = "World"

        # Find the  script in the libexec directory of the ZenPack
        myPredefinedCmd1 = [
             libexec + '/mywrapper_script1',
            arg1, arg2, arg3, arg4
        ]
        logfile.write(' myPredefinedCmd1 is %s ' % (myPredefinedCmd1))
        self.write('Preparing my command...')
        result = executeCommand(myPredefinedCmd1, None, write=self.write)
        self.write('End of command...')
        logfile.close()
        return result
Пример #28
0
    def stream(self):
        """
        Called by the parent class, this method asks the datasource
        to test itself.
        """
        try:
            request = self.request
            data = unjson(request.form['data'])
            # datasource expect the request object, so set the attributes
            # from the request (so the user can test without saving the datasource)
            for key in data:
                request[key] = data[key]

            self.write("Preparing Command...")
            request['renderTemplate'] = False
            results = self.context.testDataSourceAgainstDevice(
                data.get('testDevice'), request, self.write, self.reportError)
            return results
        except Exception:
            self.write('Exception while performing command: <br />')
            self.write('<pre>%s</pre>' % (traceback.format_exc()))
    def stream(self):
# Setup a logging file
        logfile = open('/usr/local/zenoss/zenoss/log/example_logging.log', 'a')
        logfile.write('Start logging')
        data = unjson(self.request.get('data'))
        logfile.write(' data is \n' % (data))
        try:
            args = data['args']
            logfile.write('Argument is %s \n' % (args))
            arg3 = args
        except:
            logfile.write(' No args \n')
            arg3 = ''
        try:
            uids = data['uids']
            logfile.write('uids is %s \n' % (uids))
            arg4 = uids
        except:
            logfile.write('No uids \n')
            arg4 = ''
#        facade = getFacade('device', self.context)
#        organizer = facade._getObject(uids[0])
#        logfile.write(' organizer is %s ' % (organizer))

        libexec = os.path.join(os.path.dirname(__file__), 'libexec')

        arg1 = "Hello"
        arg2 = "World"

# Put the  script in the libexec directory of the ZenPack
        myPredefinedCmd1 = [
             libexec + '/mywrapper_script1',
            arg1, arg2, arg3, arg4
        ]
        logfile.write(' myPredefinedCmd1 is %s ' % (myPredefinedCmd1))
        self.write('Preparing my command...')
        result = executeCommand(myPredefinedCmd1, None, write=self.write)
        self.write('End of command...')
        logfile.close()
        return result
Пример #30
0
    def __call__(self, body):
        # Decode the request data
        try:
            body = unjson(body)
        except Exception:
            raise DirectException("Request body is not unjson()-able: %s" % body)
        self._body = body

        if isinstance(body, list):
            directRequests = body
        elif isinstance(body, dict):
            directRequests = [body]
        else:
            raise DirectException("Body is not a supported type: %s" % body)

        directResponses = []
        for directRequest in directRequests:
            directResponses.append(self._processDirectRequest(directRequest))

        if len(directResponses) == 1:
            directResponses = directResponses[0]

        return directResponses
Пример #31
0
    def __call__(self, body):
        # Decode the request data
        try:
            body = unjson(body)
        except Exception:
            raise DirectException("Request body is not unjson()-able: %s" % body)
        self._body = body

        if isinstance(body, list):
            directRequests = body
        elif isinstance(body, dict):
            directRequests = [body]
        else:
            raise DirectException("Body is not a supported type: %s" % body)

        directResponses = []
        for directRequest in directRequests:
            directResponses.append(self._processDirectRequest(directRequest))

        if len(directResponses) == 1:
            directResponses = directResponses[0]

        return directResponses
Пример #32
0
    def inner(self, *args, **kwargs):
        """
        Inner portion of the decorator

        @param *args: arguments
        @type *args: possible list
        @param **kwargs: keyword arguments
        @type **kwargs: possible list
        @return: decorator function return
        @rtype: function
        """
        if self.request.REQUEST_METHOD=='POST':
            content = extractPostContent(self.request)
            try:
                args += (unjson(content),)
            except ValueError:
                kwargs.update(self.request.form)
        else:
            kwargs.update(self.request.form)
        # Get rid of useless Zope thing that appears when no querystring
        if kwargs.has_key('-C'): del kwargs['-C']
        # Get rid of kw used to prevent browser caching
        if kwargs.has_key('_dc'): del kwargs['_dc']
        return f(self, *args, **kwargs)
Пример #33
0
    def stream(self):
        """
        Called by the parent class, this method asks the datasource
        to test itself.
        """
        try:
            request = self.request
            data = unjson(request.form['data'])
            # datasource expect the request object, so set the attributes
            # from the request (so the user can test without saving the datasource)
            for key in data:
                request[key] = data[key]

            self.write("Preparing Command...")
            request['renderTemplate'] = False
            results = self.context.testDataSourceAgainstDevice(
                data.get('testDevice'),
                request,
                self.write,
                self.reportError)
            return results
        except Exception:
            self.write('Exception while performing command: <br />')
            self.write('<pre>%s</pre>' % (traceback.format_exc()))
Пример #34
0
 def __call__(self):
     body = unjson(self.request.form['body'])
     type = body.get('type')
     getattr(self, type)(self.request.response, self._query(body), body['fields'])
 def stream(self):
     daemons=[d['name'] for d in self.context.dmd.About.getZenossDaemonStates() \
             if d['msg'] == 'Up' and d['name'] not in DEFAULT_MASTER_DAEMONS]
     if 'zenrrdcached' not in daemons:
         daemons.append('zenrrdcached')
     if 'zenrender' not in daemons:
         daemons.append('zenrender')
     if os.path.exists(MASTER_DAEMON_LIST_FILE):
         for line in fileinput.input(MASTER_DAEMON_LIST_FILE):
             line = line.strip()
             if line in daemons:
                 daemons.remove(line)
     df = open('%s/daemons.txt'%zpDir, 'w')
     df.write('%s\n'%'\n'.join(daemons))
     df.close()
     data = unjson(self.request.get('data'))
     ids = data['uids']
     if not ids:
         self.write('No Remote Collectors were selected')
     command = data['command']
     if command == 'add':
         new_id = ids[0]
         self.context.manage_addMonitor(new_id, submon='Performance')
         self.context.Performance[new_id].renderurl='http://%s:8091' % new_id
         transaction.commit()
     for id in ids:
         self.write('%s Remote Collector %s' % (command.capitalize(), id))
         if command in ('update', 'remove'):
             self.write('Stopping zenoss daemons')
             executeStreamCommand('ssh root@%s "/sbin/service zenoss stop"' % id,
                                         self.write, timeout=COMMAND_TIMEOUT)
         if command in ('add'):
             self.write('Copy Zenoss files to Remote Collector')
             self.write('....zenoss user')
             executeStreamCommand('rsync --rsh=ssh --recursive --times --owner --group --perms --links /home/zenoss/.bash* root@%s:%s' % (
                             id, '/home/zenoss'), self.write, timeout=COMMAND_TIMEOUT)
             self.write('....zenoss directory')
             executeStreamCommand('rsync --rsh=ssh --recursive --times --owner --group --perms --links --exclude=perf --exclude=backups --exclude=log --exclude=deps --exclude=lost+found --exclude=var %s root@%s:%s' % (
                             zenDir, id, '/opt'), self.write, timeout=COMMAND_TIMEOUT)
             executeStreamCommand('ssh -C root@%s "mkdir /opt/zenoss/var; mkdir /opt/zenoss/perf; mkdir /opt/zenoss/log;"' % (
                             id), self.write, timeout=COMMAND_TIMEOUT)
             self.write('....init script')
             executeStreamCommand('find %s -print | cpio -oc | ssh -C root@%s "cd / && cpio -ic 2>/dev/null"' % (
                             zenScript, id), self.write, timeout=COMMAND_TIMEOUT)
             executeStreamCommand('ssh -C root@%s "/sbin/chkconfig --add zenoss --level 345"' % (
                             id), self.write, timeout=COMMAND_TIMEOUT)
             self.write('....zenoss sockets')
             executeStreamCommand('ssh -C root@%s "chmod +s /opt/zenoss/bin/zensocket /opt/zenoss/bin/pyraw /opt/zenoss/bin/nmap; chown zenoss:zenoss /opt/zenoss/var /opt/zenoss/perf /opt/zenoss/log -Rf"' % (
                             id), self.write, timeout=COMMAND_TIMEOUT)
             self.write('Update Remote Collector configuration')
             executeStreamCommand('ssh %s %s %s %s' % (id, updConfBin,
                 socket.getfqdn(), id), self.write, timeout=COMMAND_TIMEOUT)
             self.write('Starting zenoss daemons')
             executeStreamCommand('ssh root@%s "/sbin/service zenoss start"' % id,
                     self.write, timeout=COMMAND_TIMEOUT)
         if command in ('update'):
             self.write('Revert Remote Collector configuration')
             executeStreamCommand('ssh %s %s localhost localhost' % (id,
                         updConfZenBin), self.write, timeout=COMMAND_TIMEOUT)
             self.write('Remove ZenPacks files from Remote Collector')
             executeStreamCommand('ssh %s rm -fr %s' % (id, zpDir),
                                         self.write, timeout=COMMAND_TIMEOUT)
             ##TODO: Don't assume the stuff is already there
             self.write('Copy Zenoss files to Remote Collector')
             self.write('....just zenpacks')
             executeStreamCommand('find %s -print | cpio -oc | ssh -C %s "cd / && cpio -ic 2>/dev/null"' % (
                             zpDir, id), self.write, timeout=COMMAND_TIMEOUT)
             self.write('Update Remote Collector configuration')
             executeStreamCommand('ssh %s %s %s %s'%(id, updConfBin,
                 socket.getfqdn(), id), self.write, timeout=COMMAND_TIMEOUT)
             self.write('Starting zenoss daemons')
             executeStreamCommand('ssh root@%s "/sbin/service zenoss start"' % id,
                     self.write, timeout=COMMAND_TIMEOUT)
     if command == 'remove':
         self.write('Notice: This does not delete Zenoss from the remote machine!')
         self.write('Disable Zenoss startup')
         executeStreamCommand('ssh -C root@%s "/sbin/chkconfig zenoss off"' % (
                         id), self.write, timeout=COMMAND_TIMEOUT)
         self.context.manage_removeMonitor(ids=ids, submon='Performance')
         transaction.commit()
     self.write('All Tasks Finished')
     os.unlink('%s/daemons.txt' % zpDir)
 def stream(self):
     daemons=[d['name'] for d in self.context.dmd.About.getZenossDaemonStates() \
             if d['msg'] == 'Up' and d['name'] not in DEFAULT_MASTER_DAEMONS]
     if 'zenrrdcached' not in daemons:
         daemons.append('zenrrdcached')
     if 'zenrender' not in daemons:
         daemons.append('zenrender')
     if os.path.exists(MASTER_DAEMON_LIST_FILE):
         for line in fileinput.input(MASTER_DAEMON_LIST_FILE):
             line = line.strip()
             if line in daemons:
                 daemons.remove(line)
     df = open('%s/daemons.txt' % zpDir, 'w')
     df.write('%s\n' % '\n'.join(daemons))
     df.close()
     data = unjson(self.request.get('data'))
     ids = data['uids']
     if not ids:
         self.write('No Remote Collectors were selected')
     command = data['command']
     if command == 'add':
         new_id = ids[0]
         self.context.manage_addMonitor(new_id, submon='Performance')
         self.context.Performance[
             new_id].renderurl = 'http://%s:8091' % new_id
         transaction.commit()
     for id in ids:
         self.write('%s Remote Collector %s' % (command.capitalize(), id))
         if command in ('update', 'remove'):
             self.write('Stopping zenoss daemons')
             executeStreamCommand(
                 'ssh root@%s "/sbin/service zenoss stop"' % id,
                 self.write,
                 timeout=COMMAND_TIMEOUT)
         if command in ('add'):
             self.write('Copy Zenoss files to Remote Collector')
             self.write('....zenoss user')
             executeStreamCommand(
                 'rsync --rsh=ssh --recursive --times --owner --group --perms --links /home/zenoss/.bash* root@%s:%s'
                 % (id, '/home/zenoss'),
                 self.write,
                 timeout=COMMAND_TIMEOUT)
             self.write('....zenoss directory')
             executeStreamCommand(
                 'rsync --rsh=ssh --recursive --times --owner --group --perms --links --exclude=perf --exclude=backups --exclude=log --exclude=deps --exclude=lost+found --exclude=var %s root@%s:%s'
                 % (zenDir, id, '/opt'),
                 self.write,
                 timeout=COMMAND_TIMEOUT)
             executeStreamCommand(
                 'ssh -C root@%s "mkdir /opt/zenoss/var; mkdir /opt/zenoss/perf; mkdir /opt/zenoss/log;"'
                 % (id),
                 self.write,
                 timeout=COMMAND_TIMEOUT)
             self.write('....init script')
             executeStreamCommand(
                 'find %s -print | cpio -oc | ssh -C root@%s "cd / && cpio -ic 2>/dev/null"'
                 % (zenScript, id),
                 self.write,
                 timeout=COMMAND_TIMEOUT)
             executeStreamCommand(
                 'ssh -C root@%s "/sbin/chkconfig --add zenoss --level 345"'
                 % (id),
                 self.write,
                 timeout=COMMAND_TIMEOUT)
             self.write('....zenoss sockets')
             executeStreamCommand(
                 'ssh -C root@%s "chmod +s /opt/zenoss/bin/zensocket /opt/zenoss/bin/pyraw /opt/zenoss/bin/nmap; chown zenoss:zenoss /opt/zenoss/var /opt/zenoss/perf /opt/zenoss/log -Rf"'
                 % (id),
                 self.write,
                 timeout=COMMAND_TIMEOUT)
             self.write('Update Remote Collector configuration')
             executeStreamCommand('ssh %s %s %s %s' %
                                  (id, updConfBin, socket.getfqdn(), id),
                                  self.write,
                                  timeout=COMMAND_TIMEOUT)
             self.write('Starting zenoss daemons')
             executeStreamCommand(
                 'ssh root@%s "/sbin/service zenoss start"' % id,
                 self.write,
                 timeout=COMMAND_TIMEOUT)
         if command in ('update'):
             self.write('Revert Remote Collector configuration')
             executeStreamCommand('ssh %s %s localhost localhost' %
                                  (id, updConfZenBin),
                                  self.write,
                                  timeout=COMMAND_TIMEOUT)
             self.write('Remove ZenPacks files from Remote Collector')
             executeStreamCommand('ssh %s rm -fr %s' % (id, zpDir),
                                  self.write,
                                  timeout=COMMAND_TIMEOUT)
             ##TODO: Don't assume the stuff is already there
             self.write('Copy Zenoss files to Remote Collector')
             self.write('....just zenpacks')
             executeStreamCommand(
                 'find %s -print | cpio -oc | ssh -C %s "cd / && cpio -ic 2>/dev/null"'
                 % (zpDir, id),
                 self.write,
                 timeout=COMMAND_TIMEOUT)
             self.write('Update Remote Collector configuration')
             executeStreamCommand('ssh %s %s %s %s' %
                                  (id, updConfBin, socket.getfqdn(), id),
                                  self.write,
                                  timeout=COMMAND_TIMEOUT)
             self.write('Starting zenoss daemons')
             executeStreamCommand(
                 'ssh root@%s "/sbin/service zenoss start"' % id,
                 self.write,
                 timeout=COMMAND_TIMEOUT)
     if command == 'remove':
         self.write(
             'Notice: This does not delete Zenoss from the remote machine!')
         self.write('Disable Zenoss startup')
         executeStreamCommand(
             'ssh -C root@%s "/sbin/chkconfig zenoss off"' % (id),
             self.write,
             timeout=COMMAND_TIMEOUT)
         self.context.manage_removeMonitor(ids=ids, submon='Performance')
         transaction.commit()
     self.write('All Tasks Finished')
     os.unlink('%s/daemons.txt' % zpDir)
Пример #37
0
 def __call__(self):
     body = unjson(self.request.form['body'])
     type = body.get('type')
     getattr(self, type)(self.request.response, self._query(body),
                         body['fields'])
Пример #38
0
 def stream(self):
     data = unjson(self.request.get('data'))
     uids = data['uids']
     facade = getFacade('device', self.context)
     for device in imap(facade._getObject, uids):
         device.runDeviceMonitor(REQUEST=self.request, write=self.write, debug=True)
Пример #39
0
 def stream(self):
     data = unjson(self.request.get('data'))
     uids = data['uids']
     facade = getFacade('device', self.context)
     for device in imap(facade._getObject, uids):
         device.collectDevice(REQUEST=self.request, write=self.write)