def upcall(self, kind, upcallInfo): if kind == pyndn.UPCALL_FINAL: return pyndn.RESULT_OK if kind == pyndn.UPCALL_INTEREST_TIMED_OUT: return self.retry(upcallInfo.Interest.name) # make sure we're getting sane responses if not kind in [pyndn.UPCALL_CONTENT, pyndn.UPCALL_CONTENT_UNVERIFIED, pyndn.UPCALL_CONTENT_BAD]: log.error("Received invalid kind type: %d" % kind) return pyndn.RESULT_OK response_name = upcallInfo.ContentObject.name s = QueueItem.STATUS_OK if kind == pyndn.UPCALL_CONTENT_UNVERIFIED: s = QueueItem.STATUS_UNVERIFIED if kind == pyndn.UPCALL_CONTENT_BAD: s = QueueItem.STATUS_BAD self.recv_queue.put_nowait(QueueItem(response_name, s, upcallInfo.ContentObject.content)) return pyndn.RESULT_OK
def getHostStatus(self, h): s = None try: self.mutex.acquire() s = copy(self.host_status[h]) except Exception, e: log.error(e)
def new_uploading(self, name, remotename, key): self.mark_uploading(name, True) try: self.uploading_queue.put_nowait((name, remotename, key)) except Exception, e: log.error("failed to put into queue: %s" % e) self.mark_uploading(name, False)
def handleRequest(self, interest): length = len(self.service_prefix) iname = str(interest.name) assert(iname.startswith(self.service_prefix)) args = iname[length:].split('/') if args[0] == 'handshake': return self.doHandshake(args, interest) elif args[0] == 'auth': log.debug("'auth' interest received {}".format(args)) return self.doAuth(args, interest) elif len(args) == 3: log.debug("interest received {}".format(args)) (sid, seq, data) = tuple(args) seq = int(seq) s = self.getSessionItem(sid) if not s: log.warn("session not found") return self.buildResponse(interest, seq, statuscode.STATUS_AUTH_ERROR, '') if s.seq+1 != seq: log.error("sequence number error, {} expected, but {} received".format(s.seq+1, seq)) return None else: s.seq += 1 try: result, status = self.OnDataRecv(s.session_decrypt_data(data)) return self.buildResponse(interest, seq, status, s.session_encrypt_data(result)) except Exception, e: log.error(e) return self.buildResponse(interest, seq, statuscode.STATUS_INTERNAL_ERROR, '')
def Connect(self, timeout): """Shake hand and authorize with server (may block)""" self.connect_timeout = timeout auth = security.Auth() if self.state != STATE_NOT_AUTH: raise ValueError log.debug('Connecting to %s' % self.name_prefix) self.auth_cond.acquire() self._auth_result = None self.ndn_interface.send(self.name_prefix + '/auth/{}'.format(hex(auth.getDHKey())), timeout, 0) self.auth_cond.wait(timeout) self.auth_cond.release() if not self._auth_result: raise RMSAuthException('Authorization timed out') try: data = json.loads(self._auth_result) auth.setOtherDHKey(long(data['randS'], 0)) auth.decryptPreMasterKey(unhexlify(data['preMaster']), self.pemFile) self.cipher = security.AESCipher(auth.genMasterKey()) self.session_id = data['session'] self.state = STATE_IDLE log.debug('Connected') except Exception, e: log.error(e) raise RMSAuthException('Illegal authorization response received')
def run(self): while True: time.sleep(5.0) for x in self.clients: try: if not x.IsConnected(): x.ReConnect(webconfig.NDN_CONNECT_TIMEOUT) except Exception, e: log.error(e)
def api_execute(host, cmd): try: cmd = unhexlify(cmd) ret = backend_cmd.ExecuteOneCmd(host, cmd) if ret == None: raise ValueError return json.dumps(dict(text=ret)) except Exception, e: log.error(e) abort(500)
def mark_uploading(self, name, b): self.uploading_mutex.acquire() try: if b: log.debug('set uploading mark %s' % name) self.uploading_set.add(name) else: log.debug('remove uploading mark %s' % name) self.uploading_set.remove(name) except Exception, e: log.error(e)
def api_sys_all_status(): try: with closing(connect_db()) as db: cur = db.execute('select name from hosts order by id') result = dict() for row in cur.fetchall(): result[row[0]] = backend_sys.GetHostStatus(row[0]) return json.dumps(result) except Exception, e: log.error(e) raise e
def api_sys_reboot(hosts): try: hosts = hosts.split(',') for x in hosts: backend_sys.RebootHost(x) return '{"error": 0}' except Exception, e: log.error(e) raise e
def run(self): while True: for i in range(len(self.clients)): try: x = self.clients[i] if not x.IsConnected(): x.ReConnect(webconfig.NDN_CONNECT_TIMEOUT) except Exception, e: log.error(e) time.sleep(30.0)
def run(self): while True: try: (name, remotename, key) = self.uploading_queue.get() except: continue try: with open(name, 'wb') as f: consumer = ndn_flow.FlowConsumer(999, str(remotename), fout=f) consumer.start() except Exception, e: log.error("failed to fetch file: %s" % e) # import traceback # traceback.print_exc() try: os.unlink(name) except Exception, e: log.error("cannot delete %s %s" % (name,e))
def _recv_thread(self): while True: try: item = self.recv_queue.get() except Exception, e: log.error(e) continue if self.state == STATE_NOT_AUTH: #handle auth response if item.status == QueueItem.STATUS_TIME_OUT: self._auth_timed_out() else: self._auth_response(item.content) continue if item.status == QueueItem.STATUS_TIME_OUT: log.info("send timed out %s" % item.name) self.state = STATE_IDLE continue if self.state != STATE_WAIT_RECV: log.warn('content received in a wrong state %d'%self.state) continue if item.status in [QueueItem.STATUS_BAD, QueueItem.STATUS_UNVERIFIED]: log.warn('got bad content') self.state = STATE_IDLE elif item.status == QueueItem.STATUS_OK: log.debug('got content') try: (seq, status, content) = self._decode_response(item.content) if int(status) == common.statuscode.STATUS_AUTH_ERROR: log.warn("session expired") self.ReConnect(self.connect_timeout or 10.0) raise RMSAuthException #quit normal receiving procedure seq = int(seq) content = self._decrypt(content) log.debug("content: %s" %(content)) except RMSAuthException: pass except Exception, e: log.error("unable to decode content, %s" % e) except:
def run(self): for x in self.clients: self.doConnect(x) while True: for i in range(len(self.clients)): info = dict(alive = False, delay = None, updated = time.time()) try: x = self.clients[i] if not x.IsConnected(): x.ReConnect(webconfig.NDN_CONNECT_TIMEOUT) info['alive'], info['delay'] = x.Ping() except Exception, e: log.error(e) try: self.mutex.acquire() self.host_status[self.hosts[i]] = info except Exception, e: log.error(e) finally:
def connect_hosts(self): for x in self.clients: try: x.Connect(webconfig.NDN_CONNECT_TIMEOUT) except Exception, e: log.error(e)
def _auth_timed_out(self): log.error('Authorization timed out') self.auth_cond.acquire() self._auth_result = None self.auth_cond.notify_all() self.auth_cond.release()
def DeleteFiles(self, host, name): try: return self.thread.remove(host, name) except Exception,e: log.error(e) return False
content = self._decrypt(content) log.debug("content: %s" %(content)) except RMSAuthException: pass except Exception, e: log.error("unable to decode content, %s" % e) except: pass else: if seq != self.seq: log.warn("sequence number error, {} expected, but {} received".format(self.seq, seq)) else: self.result_queue.put_nowait((status, content)) self.state = STATE_IDLE else: log.error('got unknown QueueItem') def Recv(self, timeout = None): """Receive data from server (may block)""" try: item = self.result_queue.get(True, timeout) return item except: return (None, None) def DiscardCurrentResult(self): if self.state != STATE_WAIT_RECV: log.warn('not waiting for result') else: self.state = STATE_IDLE
def doConnect(self, client): try: client.Connect(webconfig.NDN_CONNECT_TIMEOUT) except Exception, e: log.error(e)
def reboot(self, h): try: i = self.hosts.index(h) self.clients[i].Reboot() except Exception, e: log.error(e)