コード例 #1
0
ファイル: kkbAgent.py プロジェクト: iTraceur/KKBMonitorAgent
    def run(self):
        while True:
            time.sleep(4)
            try:
                line = sys.stdin.readline()
                if not line:
                    continue

                if line == 'stop\n':
                    try:
                        kkbLib.rmPid('agent')
                        self.agentProcess.stop()
                        self.masterMonitor.stop()
                    finally:
                        os._exit(0)

                if line == 'restart\n':
                    self.agentProcess.restart()

                if line == 'ping\n':
                    self.masterMonitor.heartbeat()
                    continue

            except Exception:
                kkbLib.error(traceback.format_exc())
コード例 #2
0
ファイル: kkbMaster.py プロジェクト: iTraceur/KKBMonitorAgent
    def _run(self):
        try:
            verInfo = kkbLib.getPythonVer()
            if verInfo not in kkbConfig.pythonVer:
                verStr = '/'.join(kkbConfig.pythonVer)
                kkbLib.info('当前pyhon版本还没兼容,程序执行中止,目前支持python版本:' + verStr)
                sys.exit(1)
            print('Starting master process')
            kkbLib.info('Starting master process')
            masterProcess = MasterProcess()
            monitor = AgentProcessMonitor(masterProcess)
            monitor.setName('AgentProcessMonitor')
            monitor.setDaemon(True)
            monitor.start()

            print('Started master process')
            kkbLib.info('Started master process')

            while True:
                try:
                    time.sleep(5)
                    masterProcess.ping()
                except Exception:
                    kkbLib.error(traceback.format_exc())

        except KeyboardInterrupt:
            masterProcess.stop()
        except Exception:
            kkbLib.error(traceback.format_exc())
コード例 #3
0
ファイル: kkbAgent.py プロジェクト: iTraceur/KKBMonitorAgent
 def postlog(self):
     try:
         logStr = kkbLib.readLog()
         parms = {'data': logStr}
         parms = parse.urlencode(parms)
         parms = parms.encode('UTF8')
         urllib2.urlopen(urllib2.Request(kkbConfig.logUrl, parms))
     except Exception:
         kkbLib.error(traceback.format_exc())
コード例 #4
0
ファイル: kkbAgent.py プロジェクト: iTraceur/KKBMonitorAgent
 def getUsrPluginSet(self):
     try:
         url = kkbConfig.configUrl + '&mac=' + str(self.mac) + '&ip=' + str(self.ip) + '&t=' + self.os_type
         res = urllib2.urlopen(url)
         redata = res.read()
         res.close()
         redata = kkbLib.decode(redata, kkbConfig.kkbDataKey)
         return json.loads(redata)
     except Exception:
         kkbLib.error(traceback.format_exc())
コード例 #5
0
ファイル: kkbMaster.py プロジェクト: iTraceur/KKBMonitorAgent
 def run(self):
     while True:
         try:
             time.sleep(8)
             self.masterProcess.lock.acquire()
             try:
                 if self.masterProcess.agent is None or self.masterProcess.agent.poll() is not None:
                     self.masterProcess.agent = self._startAgentProcess()
             except Exception:
                 kkbLib.error(traceback.format_exc())
         finally:
             self.masterProcess.lock.release()
コード例 #6
0
ファイル: kkbAgent.py プロジェクト: iTraceur/KKBMonitorAgent
    def postData(self):
        try:
            reData = {}
            for taskId in self.objList:
                obj = self.objList[taskId + '']
                reData[taskId + ''] = obj.returnData()
                obj.clearData()
            try:
                reData = json.dumps(reData, ensure_ascii=False)
            except Exception:
                try:
                    reData = str(reData)
                    reData = reData.encode('UTF8', errors="ignore")
                    reData = reData.decode('UTF8', errors="ignore")
                    reData = dict(eval(reData))
                    reData = json.dumps(reData, ensure_ascii=False)
                except Exception:
                    kkbLib.error('json.dumps loss!')
                    kkbLib.error(traceback.format_exc())
                    reData = {}
                    reData = json.dumps(reData, ensure_ascii=False)

            if zlib:
                reData = reData.encode('UTF8')
                reData = zlib.compress(reData, 9)
                if base64:
                    reData = base64.encodestring(reData)
                else:
                    reData = reData.encode('base64')

            parms = {'data': reData, 'post_time': self.post_time}
            parms = parse.urlencode(parms)
            parms = parms.encode('UTF8')
            command = ''
            url = kkbConfig.postUrl + '&mac=' + str(self.mac) + '&ip=' + str(self.ip)
            try:
                res = urllib2.urlopen(urllib2.Request(url, parms))
                command = res.read()
                res.close()
            except Exception:
                kkbLib.error(traceback.format_exc())
                res = urllib2.urlopen(urllib2.Request(url, parms))
                command = res.read()
                res.close()
            command = kkbLib.decode(command, kkbConfig.kkbDataKey)
            command = json.loads(command)
            if command == '':
                kkbLib.error('command is none!!')
                return ''
            return command
        except Exception:
            kkbLib.error(traceback.format_exc())
コード例 #7
0
ファイル: kkbAgent.py プロジェクト: iTraceur/KKBMonitorAgent
 def initPlug(self, plug):
     try:
         if os.path.exists('plugin/' + plug['pluginFileName'] + '.py'):
             md = kkbLib.getMD5('plugin/' + plug['pluginFileName'] + '.py')
             if md != plug['md5']:
                 os.remove('plugin/' + plug['pluginFileName'] + '.py')
                 kkbLib.download(kkbConfig.kkbServer + '/agent/plugin/' + plug['pluginFileName'] + '.py',
                                 'plugin/' + plug['pluginFileName'] + '.py')
         else:
             kkbLib.download(kkbConfig.kkbServer + '/agent/plugin/' + plug['pluginFileName'] + '.py',
                             'plugin/' + plug['pluginFileName'] + '.py')
     except Exception:
         kkbLib.error(traceback.format_exc())
コード例 #8
0
ファイル: plugin.py プロジェクト: iTraceur/KKBMonitorAgent
 def postData(self):
     try:
         reData = {}
         reData[self.taskId + ""] = self.returnData()
         self.clearData()
         try:
             reData = json.dumps(reData, ensure_ascii=False, encoding="UTF8")
         except Exception:
             try:
                 reData = json.dumps(reData, ensure_ascii=False, encoding="GBK")
             except Exception:
                 kkbLib.error("json.dumps loss!")
                 kkbLib.error(traceback.format_exc())
         if zlib:
             reData = reData.encode("UTF8")
             reData = zlib.compress(reData, 9)
             if base64:
                 reData = base64.encodestring(reData)
             else:
                 reData = reData.encode("base64")
         parms = {"data": reData, "post_time": "", "plug_post": "true"}
         parms = parse.urlencode(parms)
         parms = parms.encode("UTF8")
         try:
             res = urllib2.urlopen(urllib2.Request(kkbConfig.postUrl, parms))
             command = res.read()
             res.close()
         except Exception:
             kkbLib.error(traceback.format_exc())
             res = urllib2.urlopen(urllib2.Request(kkbConfig.postUrl, parms))
             command = res.read()
             res.close()
     except Exception:
         kkbLib.error(traceback.format_exc())
コード例 #9
0
ファイル: kkbAgent.py プロジェクト: iTraceur/KKBMonitorAgent
    def startOne(self, plug):
        try:
            self.initPlug(plug)
            module_meta = __import__('plugin', globals(), locals(), [str(plug['pluginFileName'])])
            class_meta = getattr(module_meta, plug['pluginFileName'])
            c = getattr(class_meta, plug['pluginClassName'])
            obj = c(plug['taskId'], plug['taskConf'], plug['agentType'], plug['pluginId'])
            self.objList[plug['taskId']] = obj
            obj.setIntervalTime(self.pluginTime)
            obj.setName(plug['pluginClassName'] + plug['taskId'])
            obj.setDaemon(True)
            obj.start()

        except Exception:
            kkbLib.error(traceback.format_exc())
コード例 #10
0
ファイル: kkbAgent.py プロジェクト: iTraceur/KKBMonitorAgent
    def run(self):
        while self.running:
            time.sleep(4)
            try:
                try:
                    self.lock.acquire()

                    if (time.time() - self.lastHeartbeat) > 12:
                        self.agentProcess.stop()
                        kkbLib.rmPid('agent')
                        os._exit(0)

                finally:
                    self.lock.release()

            except Exception:
                kkbLib.error(traceback.format_exc())
                raise
コード例 #11
0
ファイル: plugin.py プロジェクト: iTraceur/KKBMonitorAgent
 def run(self):
     self.taskConf = self.taskConf_tmp
     if "ser_time" in self.taskConf:
         self.ser_time = int(self.taskConf["ser_time"] - time.time())
     time.sleep(random.randint(1, 20))
     while self.running:
         self.taskConf = self.taskConf_tmp
         if "pluginTime" in self.taskConf:
             self.interval = self.taskConf["pluginTime"]
         cur_time = time.time()
         self.getData()
         self.postData()
         cur_time = time.time() - cur_time
         # cur_time = int(cur_time)
         if cur_time < self.interval:
             time.sleep(self.interval - cur_time)
         else:
             kkbLib.error("get data out time!!")
             time.sleep(60)
コード例 #12
0
ファイル: kkbAgent.py プロジェクト: iTraceur/KKBMonitorAgent
    def run(self):
        self.objList = {}
        try:
            if 'agent' in self.plugConf and 'agentTime' in self.plugConf['agent']:
                self.post_interval = self.plugConf['agent']['agentTime']

            if 'agent' in self.plugConf and 'pluginTime' in self.plugConf['agent']:
                self.pluginTime = self.plugConf['agent']['pluginTime']

            if 'agent' in self.plugConf and 'post_time' in self.plugConf['agent']:
                self.post_time = self.plugConf['agent']['post_time']
            else:
                kkbLib.error('none set post time!')

            if 'error' in self.plugConf:
                kkbLib.error(self.plugConf['error'])

            if 'plugin' in self.plugConf:
                for taskId in self.plugConf['plugin']:
                    plug = self.plugConf['plugin'][taskId + '']
                    if plug['status'] == '1':
                        # self.startOne(plug)
                        kkbLib.info(str(plug))
            else:
                kkbLib.info('none plugin info!!')

            cur_time = 0
            while self.running:
                if ((cur_time + 10) < self.post_interval):
                    time.sleep(self.post_interval - cur_time)
                else:
                    kkbLib.error('post data out time!!')
                    time.sleep(180)
                cur_time = time.time()
                # command = self.postData()
                # self.doneCommand(command)
                kkbLib.info('do commands...')
                cur_time = time.time() - cur_time
                #cur_time = int(cur_time)
        except Exception:
            kkbLib.error(traceback.format_exc())
コード例 #13
0
ファイル: kkbAgent.py プロジェクト: iTraceur/KKBMonitorAgent
    def doneCommand(self, command):
        if command == '':
            return False
        try:
            if 'agent' in command and 'post_time' in command['agent']:
                self.post_time = command['agent']['post_time']
            else:
                kkbLib.error('none return post_time!!')

            if 'agent' in command and 'agentTime' in command['agent']:
                self.post_interval = command['agent']['agentTime']

            if 'error' in command:
                kkbLib.error(command['error'])

            if 'agent' in command and 'pluginTime' in command['agent'] and self.pluginTime != command['agent'][
                'pluginTime']:
                self.pluginTime = command['agent']['pluginTime']
                for pid in self.objList:
                    self.objList[pid].setIntervalTime(self.pluginTime)

            if 'sysCommand' in command and 'agent' in command['sysCommand']:
                if command['sysCommand']['agent'] == 'restart':
                    self.restart()
                if command['sysCommand']['agent'] == 'getlog':
                    self.postlog()

            if 'plugin' in command:
                for plugOne in self.objList:
                    if plugOne not in command['plugin']:
                        if len(command['plugin']) == 0:
                            command['plugin'] = {}
                        command['plugin'][plugOne] = {'taskId': plugOne, 'status': '0'}
                    else:
                        self.objList[plugOne].setConf(command['plugin'][plugOne]['taskConf'])

                for taskId in command['plugin']:
                    plug = command['plugin'][taskId + '']
                    if plug['status'] == '1' and plug['taskId'] not in self.objList:
                        self.startOne(plug)

                    if plug['status'] == '0' and plug['taskId'] in self.objList:
                        self.stopOne(plug)
        except Exception:
            kkbLib.error(traceback.format_exc())
コード例 #14
0
ファイル: kkbAgent.py プロジェクト: iTraceur/KKBMonitorAgent
 def stopOne(self, plug):
     try:
         self.objList[plug['taskId']].plugStop()
         del self.objList[plug['taskId']]
     except Exception:
         kkbLib.error(traceback.format_exc())
コード例 #15
0
ファイル: kkbAgent.py プロジェクト: iTraceur/KKBMonitorAgent
    if pid > 0:
        isRun = kkbLib.checkPidLinux(pid)
        if isRun:
            kkbLib.printout('Program has been started, the process PID:' + str(pid))
            sys.exit(1)

    kkbLib.writePid(agentPid, 'agent')

    kkbLib.info('Starting agent process')
    kkbLib.printout('Starting agent process')
    parentPid = None
    try:
        if len(sys.argv) > 1:
            parentPid = sys.argv[1]
    except Exception:
        kkbLib.error(traceback.format_exc())

    try:
        agentProcess = AgentProcess()
        agentProcess.setName('AgentProcess')
        agentProcess.start()

        monitor = MasterProcessMonitor(agentProcess)
        monitor.setName('MasterProcessMonitor')
        monitor.start()

        pingReader = MasterPingReader(agentProcess, monitor)
        pingReader.setName('MasterPingReader')
        pingReader.start()

        kkbLib.info('Started agent process, parent PID:' + str(parentPid) + ' the agent PID:' + str(agentPid))